@jskit-ai/auth-provider-local-core 0.2.45 → 0.2.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -0
- package/package.json +4 -4
- package/src/server/lib/fileBackend.js +3 -1
- package/src/server/lib/secondFactor.js +20 -0
- package/src/server/lib/service.js +2 -0
- package/src/server/lib/sessions.js +4 -2
- package/src/server/types.js +3 -0
- package/test/requestAuthentication.test.js +9 -7
- package/test/secondFactor.test.js +31 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- `accountStateOf({ userId })` answers whether the local account `userId` names is `"active"` (with or without an authenticator), `"disabled"` or `"missing"`: one read of the account, beside `verifySecondFactorOf`, which refuses those accounts only when it checks a code. It checks no code, leaves the account's attempts and wait as they were, records no event and writes nothing; a missing `userId` is a `TypeError`. Unsupported, as every second-factor operation, on a production server without `AUTH_LOCAL_SECOND_FACTOR_KEY`.
|
|
5
6
|
- `verifySecondFactorOf({ userId, proof })` checks an authenticator code or recovery code of the local account `userId` names, for the application, which decides whose and when (an API key's command asking for its creator's code, say). It is verifySecondFactor's own check: the same attempts, counted on the account's factor, so wrong codes through either make the account wait for both (five, then 30 seconds doubling to an hour, `AUTH_LOCAL_SIGN_IN_*`); the same once-only codes, so a code or recovery code accepted by one is refused by the other. It answers `{ verifiedAt, method, recoveryCodesLeft }` and marks no session. Refusals throw as verifySecondFactor's do: 404 `auth.local.secondFactor.accountNotFound` (new, message key `jskit.auth.local.secondFactor.accountNotFound`, "There is no such account.") for an id with no account, 403 `auth.local.secondFactor.accountDisabled` (new, message key `jskit.auth.local.secondFactor.accountDisabled`, "This account is disabled.") for a disabled account, even with its right code, 409 `notSetUp` for an account without a confirmed authenticator, 429 `locked` (with `Retry-After`) while it waits, 400 `codeInvalid`, `codeUsed`, `recoveryCodeInvalid` or `proofRequired`; a missing `userId` is a `TypeError`. Its outcome is a second-factor event as a session's is (`verified` with `method` and `recoveryCodesLeft`, or `failed` with its `reason`), marked `via: "application"` (new on `AuthLocalSecondFactorEvent`; a session's own events have none) with `ip` "", never a code; an unknown or disabled account and a missing factor record no event. The shared second-factor scenario runs it on the file backend and on `@jskit-ai/auth-provider-local-db-core`'s SQLite, MySQL and PostgreSQL.
|
|
6
7
|
- Service keys: another application's server calls the app's bearer routes (`credentials: "bearer"`) with `Authorization: Bearer <key>` and `Act-As-User: <user id or email>` (an email only when exactly one enabled account has it, through the backend's new `users.findAllByEmail(email)`, which the file backend answers; more than one is refused as `auth.serviceKey.actAsAmbiguous`), and each call runs as exactly that user, with their rights, carrying the key's service user as `via`. A key is a sessions-store row of a dedicated service user with purpose `service-key` (`SERVICE_KEY_PURPOSE`), made by `createServiceKeyRecord({ userId, days? })` (365 days unless given, at most 3650) and written with the backend's `sessions.create`; no table or column changes. Revoking the row or disabling the service user ends it. A call without a key, with an unknown, revoked or expired key or a disabled key user, with a person's own sign-in token, without `Act-As-User`, naming an unknown or disabled user, or naming the key's own user is refused in words with its code (`auth.serviceKey.*`); none falls back to the key's user. A key never signs in a browser, and a cookie route ignores `Authorization`. `test/serviceKeys.test.js` proves each.
|
|
7
8
|
- A session keeps where it was signed in from, the sign-in request's address and browser, written once at its creation: the backend contract's sessions take `signInIp` and `signInUserAgent`, and `touch` never changes them (the file store keeps them in a fourteenth and fifteenth field of each session line; older lines read ""). An account keeps when its password and email last changed: `users.updatePassword` (a reset and a change alike) sets `passwordChangedAt` and `users.updateEmail` (a used email-change link) `emailChangedAt`, in the same write; registering and confirming a new account's email set neither (the file store keeps them in a fourteenth and fifteenth field of each account line; older lines read ""). An authenticated request's answer gives them as `signIn` (`{ at, ip, userAgent, purpose }`, `at` the session's creation) and `credentialsChangedAt` (`{ password, email }`), which auth-core's policy sets as `request.sessionSignIn` and `request.credentialsChangedAt`. A session signed in before this release has `ip` and `userAgent` "": an action that asks for them makes its person sign in again.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-provider-local-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.47",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"./locales/en.json": "./locales/en.json"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@jskit-ai/auth-pass": "0.1.
|
|
15
|
+
"@jskit-ai/auth-pass": "0.1.9",
|
|
16
16
|
"openid-client": "6.8.8"
|
|
17
17
|
},
|
|
18
18
|
"description": "Local auth provider with a file backend default, no database requirement, and optional Google, Microsoft and GitHub sign-in.",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
}
|
|
74
74
|
},
|
|
75
75
|
"peerDependencies": {
|
|
76
|
-
"@jskit-ai/auth-core": "0.2.
|
|
77
|
-
"@jskit-ai/kernel": "0.2.
|
|
76
|
+
"@jskit-ai/auth-core": "0.2.40",
|
|
77
|
+
"@jskit-ai/kernel": "0.2.35"
|
|
78
78
|
}
|
|
79
79
|
}
|
|
@@ -684,7 +684,9 @@ function createLocalFileBackend({ storeDir }) {
|
|
|
684
684
|
|
|
685
685
|
return Object.freeze({
|
|
686
686
|
storeDir: resolvedStoreDir,
|
|
687
|
-
withTransaction
|
|
687
|
+
withTransaction,
|
|
688
|
+
// The files are read and written under the store's lock either way.
|
|
689
|
+
withRecords: withTransaction
|
|
688
690
|
});
|
|
689
691
|
}
|
|
690
692
|
|
|
@@ -390,6 +390,25 @@ function createLocalSecondFactor({ backend, config, logger, secondFactorEvents,
|
|
|
390
390
|
return { verifiedAt: outcome.verifiedAt, method: outcome.method, recoveryCodesLeft };
|
|
391
391
|
}
|
|
392
392
|
|
|
393
|
+
/**
|
|
394
|
+
* Whether an account the application names (a provider user id) is "active", "disabled" or "missing", as
|
|
395
|
+
* verifySecondFactorOf would find it, so an application can refuse before it asks for a code. One read of the
|
|
396
|
+
* account: it checks nothing, spends no attempt, records no event and writes nothing.
|
|
397
|
+
* @param {{ userId: string }} input
|
|
398
|
+
* @returns {Promise<"active" | "disabled" | "missing">}
|
|
399
|
+
*/
|
|
400
|
+
async function accountStateOf({ userId } = {}) {
|
|
401
|
+
const id = String(userId ?? "").trim();
|
|
402
|
+
if (!id) {
|
|
403
|
+
throw new TypeError("accountStateOf() takes the userId whose account it reads.");
|
|
404
|
+
}
|
|
405
|
+
const user = await backend.withTransaction((tx) => tx.users.findById(id));
|
|
406
|
+
if (!user) {
|
|
407
|
+
return "missing";
|
|
408
|
+
}
|
|
409
|
+
return user.disabled ? "disabled" : "active";
|
|
410
|
+
}
|
|
411
|
+
|
|
393
412
|
async function replaceSecondFactorRecoveryCodes(request, input) {
|
|
394
413
|
const session = await signedInSession(request);
|
|
395
414
|
const proof = readProof(input);
|
|
@@ -459,6 +478,7 @@ function createLocalSecondFactor({ backend, config, logger, secondFactorEvents,
|
|
|
459
478
|
confirmSecondFactorSetup,
|
|
460
479
|
verifySecondFactor,
|
|
461
480
|
verifySecondFactorOf,
|
|
481
|
+
accountStateOf,
|
|
462
482
|
replaceSecondFactorRecoveryCodes,
|
|
463
483
|
removeSecondFactor,
|
|
464
484
|
listSecondFactors,
|
|
@@ -23,6 +23,7 @@ const NO_SECOND_FACTOR = Object.freeze({
|
|
|
23
23
|
confirmSecondFactorSetup: () => throwUnsupportedAuthOperation("confirmSecondFactorSetup"),
|
|
24
24
|
verifySecondFactor: () => throwUnsupportedAuthOperation("verifySecondFactor"),
|
|
25
25
|
verifySecondFactorOf: () => throwUnsupportedAuthOperation("verifySecondFactorOf"),
|
|
26
|
+
accountStateOf: () => throwUnsupportedAuthOperation("accountStateOf"),
|
|
26
27
|
replaceSecondFactorRecoveryCodes: () => throwUnsupportedAuthOperation("replaceSecondFactorRecoveryCodes"),
|
|
27
28
|
removeSecondFactor: () => throwUnsupportedAuthOperation("removeSecondFactor"),
|
|
28
29
|
listSecondFactors: () => throwUnsupportedAuthOperation("listSecondFactors"),
|
|
@@ -278,6 +279,7 @@ function createLocalAuthService({
|
|
|
278
279
|
confirmSecondFactorSetup: secondFactor.confirmSecondFactorSetup,
|
|
279
280
|
verifySecondFactor: secondFactor.verifySecondFactor,
|
|
280
281
|
verifySecondFactorOf: secondFactor.verifySecondFactorOf,
|
|
282
|
+
accountStateOf: secondFactor.accountStateOf,
|
|
281
283
|
replaceSecondFactorRecoveryCodes: secondFactor.replaceSecondFactorRecoveryCodes,
|
|
282
284
|
removeSecondFactor: secondFactor.removeSecondFactor,
|
|
283
285
|
listSecondFactors: secondFactor.listSecondFactors,
|
|
@@ -209,9 +209,11 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
|
|
|
209
209
|
await tx.sessions.touch(session.id, { lastSeenAt: new Date(now).toISOString(), ...requestClient(request) });
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
+
// A request's session and user are read with no transaction around them: each read sees the latest rows, so a
|
|
213
|
+
// session revoked or an account disabled is refused from the next request on.
|
|
212
214
|
async function resolveValidSessionByRefreshToken(refreshToken, request) {
|
|
213
215
|
const tokenHash = sha256Base64url(refreshToken);
|
|
214
|
-
return backend.
|
|
216
|
+
return backend.withRecords(async (tx) => {
|
|
215
217
|
const session = await tx.sessions.findByTokenHash(tokenHash);
|
|
216
218
|
if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
|
|
217
219
|
return null;
|
|
@@ -318,7 +320,7 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
|
|
|
318
320
|
if (accessToken) {
|
|
319
321
|
const payload = verifySignedToken(accessToken, config.sessionSecret);
|
|
320
322
|
if (payload?.sid && payload?.sub) {
|
|
321
|
-
const resolved = await backend.
|
|
323
|
+
const resolved = await backend.withRecords(async (tx) => {
|
|
322
324
|
const session = await tx.sessions.findById(String(payload.sid));
|
|
323
325
|
if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
|
|
324
326
|
return null;
|
package/src/server/types.js
CHANGED
|
@@ -216,6 +216,9 @@
|
|
|
216
216
|
* @typedef {object} AuthLocalBackend
|
|
217
217
|
* @property {<T>(callback: (tx: AuthLocalBackendTransaction) => Promise<T>) => Promise<T>} withTransaction
|
|
218
218
|
* Runs the callback in one transaction and answers what it answered.
|
|
219
|
+
* @property {<T>(callback: (records: AuthLocalBackendTransaction) => Promise<T>) => Promise<T>} withRecords
|
|
220
|
+
* Runs the callback on the same records outside a transaction, each call on its own, and answers what it answered:
|
|
221
|
+
* a request's authentication reads its session and its user this way, without a transaction's BEGIN and COMMIT.
|
|
219
222
|
*/
|
|
220
223
|
|
|
221
224
|
/**
|
|
@@ -21,15 +21,17 @@ async function startService(t) {
|
|
|
21
21
|
}
|
|
22
22
|
return tx.sessions[method](...args);
|
|
23
23
|
}
|
|
24
|
+
const counted = (tx) => ({
|
|
25
|
+
...tx,
|
|
26
|
+
sessions: Object.create(tx.sessions, {
|
|
27
|
+
findById: { value: (...args) => readSession(tx, "findById", args) },
|
|
28
|
+
findByTokenHash: { value: (...args) => readSession(tx, "findByTokenHash", args) }
|
|
29
|
+
})
|
|
30
|
+
});
|
|
24
31
|
const backend = {
|
|
25
32
|
...files,
|
|
26
|
-
withTransaction: (work) => files.withTransaction((tx) => work(
|
|
27
|
-
|
|
28
|
-
sessions: Object.create(tx.sessions, {
|
|
29
|
-
findById: { value: (...args) => readSession(tx, "findById", args) },
|
|
30
|
-
findByTokenHash: { value: (...args) => readSession(tx, "findByTokenHash", args) }
|
|
31
|
-
})
|
|
32
|
-
}))
|
|
33
|
+
withTransaction: (work) => files.withTransaction((tx) => work(counted(tx))),
|
|
34
|
+
withRecords: (work) => files.withRecords((tx) => work(counted(tx)))
|
|
33
35
|
};
|
|
34
36
|
const service = createLocalAuthService({ ...localServiceOptions(), backend });
|
|
35
37
|
await service.register({ email: "ada@example.com", password: "correct horse" });
|
|
@@ -251,6 +251,36 @@ test("verifySecondFactorOf refuses an unknown account, a disabled one, one witho
|
|
|
251
251
|
assert.equal((await service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret) } })).method, "code");
|
|
252
252
|
});
|
|
253
253
|
|
|
254
|
+
// An application that asks for an account's code first checks the account is still there and enabled (mobilynet
|
|
255
|
+
// refuses a release-key change whose key maker's account is gone or disabled before asking for a code). The read
|
|
256
|
+
// spends nothing: no attempt on the account's factor, no event, no write.
|
|
257
|
+
test("accountStateOf answers whether the named account is active, disabled or missing, and spends no attempt", async (t) => {
|
|
258
|
+
const { service, backend, events, adaId, bobId, secret } = await enrolledAda(t);
|
|
259
|
+
await backend.withTransaction((tx) => tx.users.create({
|
|
260
|
+
id: "usr_off", email: "off@example.com", displayName: "Off", password: NO_PASSWORD, disabled: true
|
|
261
|
+
}));
|
|
262
|
+
// One wrong code already counted on Ada's factor.
|
|
263
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: wrongCode(secret) } }), CODE_INVALID);
|
|
264
|
+
const factorBefore = await backend.withTransaction((tx) => tx.secondFactors.find(adaId));
|
|
265
|
+
const eventsBefore = events.length;
|
|
266
|
+
|
|
267
|
+
assert.equal(await service.accountStateOf({ userId: adaId }), "active");
|
|
268
|
+
assert.equal(await service.accountStateOf({ userId: ` ${bobId} ` }), "active", "an account without an authenticator is active");
|
|
269
|
+
assert.equal(await service.accountStateOf({ userId: "usr_off" }), "disabled");
|
|
270
|
+
assert.equal(await service.accountStateOf({ userId: "usr_missing" }), "missing");
|
|
271
|
+
await assert.rejects(service.accountStateOf({}), TypeError);
|
|
272
|
+
|
|
273
|
+
assert.deepEqual(await backend.withTransaction((tx) => tx.secondFactors.find(adaId)), factorBefore,
|
|
274
|
+
"the factor's attempts, wait and codes are untouched");
|
|
275
|
+
assert.equal(factorBefore.failures, 1);
|
|
276
|
+
assert.equal(events.length, eventsBefore, "no event is recorded");
|
|
277
|
+
// Four more wrong codes still make the account wait: accountStateOf forgot nothing.
|
|
278
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
279
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: wrongCode(secret) } }), CODE_INVALID);
|
|
280
|
+
}
|
|
281
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret) } }), lockedFor(30));
|
|
282
|
+
});
|
|
283
|
+
|
|
254
284
|
test("the file store keeps a factor and its session's proof across restarts, and another key cannot open it", async (t) => {
|
|
255
285
|
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
256
286
|
const storeDir = await storeDirFor(t);
|
|
@@ -290,6 +320,7 @@ test("a production server has a second factor only with its key, at least 32 cha
|
|
|
290
320
|
assert.throws(() => service.listSecondFactors({ userIds: [] }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
291
321
|
assert.throws(() => service.verifySecondFactorOf({ userId: "usr_1", proof: { code: "123456" } }),
|
|
292
322
|
{ status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
323
|
+
assert.throws(() => service.accountStateOf({ userId: "usr_1" }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
293
324
|
|
|
294
325
|
const resolve = (env) => resolveLocalAuthConfig({
|
|
295
326
|
appRoot: os.tmpdir(),
|