@jskit-ai/auth-provider-local-core 0.2.44 → 0.2.45
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 +2 -0
- package/locales/en.json +2 -0
- package/package.json +4 -4
- package/src/server/lib/fileBackend.js +3 -0
- package/src/server/lib/index.js +1 -0
- package/src/server/lib/secondFactor.js +75 -14
- package/src/server/lib/service.js +2 -0
- package/src/server/lib/serviceKeys.js +123 -0
- package/src/server/lib/sessions.js +46 -2
- package/src/server/types.js +9 -2
- package/test/codedTexts.test.js +4 -0
- package/test/secondFactor.test.js +186 -0
- package/test/serviceKeys.test.js +186 -0
- package/test-support/secondFactorScenario.js +13 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- `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
|
+
- 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.
|
|
5
7
|
- 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.
|
|
6
8
|
- A provider sign-in started from an invitation (`oauthStart({ provider, returnTo, invitationToken })`) keeps the token with its attempt (a thirteenth field of `oauth-attempts.passwd`; twelve-field records still read) and, at the end, resolves it through the invitation context resolver for the signed-in account and hands the result to profile synchronization (`source` and `invitation`), as a registration's invitation is handed on. An invitation the resolver refuses never fails the sign-in, which continues as one without; a failure that is not a refusal is logged.
|
|
7
9
|
- The password lockout names the email address, never an account: 429 `auth.local.login.locked` says "Password sign-in for this email address is paused for N minute(s) after too many failed attempts. Try again after that." (it said "Too many failed sign-ins for this account."). An address without an account waits the same way. Code, params (`count`, `retryAfterSeconds`) and `Retry-After` are unchanged.
|
package/locales/en.json
CHANGED
|
@@ -58,6 +58,8 @@
|
|
|
58
58
|
},
|
|
59
59
|
"secondFactor": {
|
|
60
60
|
"notSetUp": "No authenticator is set up for this account.",
|
|
61
|
+
"accountNotFound": "There is no such account.",
|
|
62
|
+
"accountDisabled": "This account is disabled.",
|
|
61
63
|
"alreadySetUp": "An authenticator is already set up for this account. Remove it before setting up another.",
|
|
62
64
|
"setupNotStarted": "Start setting up the authenticator again.",
|
|
63
65
|
"proofRequired": "Enter a code from your authenticator app or one of your recovery codes.",
|
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.45",
|
|
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.8",
|
|
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.39",
|
|
77
|
+
"@jskit-ai/kernel": "0.2.34"
|
|
78
78
|
}
|
|
79
79
|
}
|
|
@@ -239,6 +239,9 @@ function createTx(state, touched) {
|
|
|
239
239
|
async findByEmail(email) {
|
|
240
240
|
return clone(state.users.find((user) => user.email === email) || null);
|
|
241
241
|
},
|
|
242
|
+
async findAllByEmail(email) {
|
|
243
|
+
return state.users.filter((user) => user.email === email).map(clone);
|
|
244
|
+
},
|
|
242
245
|
async hasAny() {
|
|
243
246
|
return state.users.length > 0;
|
|
244
247
|
},
|
package/src/server/lib/index.js
CHANGED
|
@@ -7,6 +7,7 @@ export { createLoggedRecoverySender } from "./passwordFlows.js";
|
|
|
7
7
|
export { createLocalFileBackend } from "./fileBackend.js";
|
|
8
8
|
export { createLoggedSecondFactorEvents } from "./secondFactor.js";
|
|
9
9
|
export { createLoggedSignInEvents } from "./sessions.js";
|
|
10
|
+
export { ACT_AS_USER_HEADER, SERVICE_KEY_PURPOSE, createServiceKeyRecord } from "./serviceKeys.js";
|
|
10
11
|
export { SETUP_CODE_ENV, SETUP_CODE_FILE, createFirstAccountSetup } from "./firstAccountSetup.js";
|
|
11
12
|
export {
|
|
12
13
|
LOCAL_AUTH_USER_REGISTERED_EVENT,
|
|
@@ -21,6 +21,8 @@ const RECOVERY_CODE_COUNT = 10;
|
|
|
21
21
|
// attempts, which make the account wait as failed sign-ins do.
|
|
22
22
|
const REFUSALS = Object.freeze({
|
|
23
23
|
notSetUp: Object.freeze({ status: 409, code: "auth.local.secondFactor.notSetUp", message: "No authenticator is set up for this account." }),
|
|
24
|
+
accountNotFound: Object.freeze({ status: 404, code: "auth.local.secondFactor.accountNotFound", message: "There is no such account." }),
|
|
25
|
+
accountDisabled: Object.freeze({ status: 403, code: "auth.local.secondFactor.accountDisabled", message: "This account is disabled." }),
|
|
24
26
|
alreadySetUp: Object.freeze({
|
|
25
27
|
status: 409,
|
|
26
28
|
code: "auth.local.secondFactor.alreadySetUp",
|
|
@@ -109,8 +111,9 @@ function createLoggedSecondFactorEvents(logger) {
|
|
|
109
111
|
* recovery codes, one factor per account. Its secret is kept sealed with the
|
|
110
112
|
* application's AUTH_LOCAL_SECOND_FACTOR_KEY and its recovery codes as keyed
|
|
111
113
|
* hashes. An accepted code marks the request's session with the time, which
|
|
112
|
-
* routes and actions that ask for a second factor compare
|
|
113
|
-
*
|
|
114
|
+
* routes and actions that ask for a second factor compare, except one the
|
|
115
|
+
* application checks for an account it names (verifySecondFactorOf); a code is
|
|
116
|
+
* accepted once. Every change and every failed attempt is an event for the
|
|
114
117
|
* application's `auth.local.second-factor-events`.
|
|
115
118
|
* @param {object} dependencies
|
|
116
119
|
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
@@ -188,26 +191,26 @@ function createLocalSecondFactor({ backend, config, logger, secondFactorEvents,
|
|
|
188
191
|
}
|
|
189
192
|
|
|
190
193
|
/**
|
|
191
|
-
* Proves
|
|
194
|
+
* Proves an account's second factor in the caller's transaction. While the
|
|
192
195
|
* account waits after wrong codes, nothing is checked. A refused proof counts
|
|
193
196
|
* one more failure; an accepted one forgets them, uses up its code, confirms
|
|
194
|
-
* a factor still being set up
|
|
195
|
-
*
|
|
197
|
+
* a factor still being set up and applies the caller's changes. The failures
|
|
198
|
+
* are the factor's own, so every way of proving it counts the same attempts.
|
|
196
199
|
* @param {import("../types.js").AuthLocalBackendTransaction} tx
|
|
197
|
-
* @param {
|
|
200
|
+
* @param {string} userId
|
|
198
201
|
* @param {object} factor The account's factor, as `secondFactors.find` held it.
|
|
199
202
|
* @param {{ code: string } | { recoveryCode: string }} proof
|
|
200
203
|
* @param {object} [changes]
|
|
201
204
|
*/
|
|
202
|
-
async function
|
|
205
|
+
async function proveFactor(tx, userId, factor, proof, changes = {}) {
|
|
203
206
|
const now = Date.now();
|
|
204
207
|
const waitMs = signInWaitMs(factor, now);
|
|
205
208
|
if (waitMs > 0) {
|
|
206
209
|
return { waitMs };
|
|
207
210
|
}
|
|
208
211
|
const checked = Object.hasOwn(proof, "recoveryCode")
|
|
209
|
-
? checkRecoveryCode(
|
|
210
|
-
: checkCode(
|
|
212
|
+
? checkRecoveryCode(userId, factor, proof.recoveryCode)
|
|
213
|
+
: checkCode(userId, factor, proof.code, now);
|
|
211
214
|
const at = new Date(now).toISOString();
|
|
212
215
|
if (checked.refusal) {
|
|
213
216
|
await tx.secondFactors.save({ ...factor, ...nextFailures(config.signInThrottle, factor, now), updatedAt: at });
|
|
@@ -215,10 +218,26 @@ function createLocalSecondFactor({ backend, config, logger, secondFactorEvents,
|
|
|
215
218
|
}
|
|
216
219
|
const proved = { ...factor, ...checked.changes, ...changes, ...NO_FAILURES, confirmedAt: factor.confirmedAt || at, updatedAt: at };
|
|
217
220
|
await tx.secondFactors.save(proved);
|
|
218
|
-
await tx.sessions.markSecondFactorProved(session.sessionId, at);
|
|
219
221
|
return { factor: proved, method: checked.method, verifiedAt: at };
|
|
220
222
|
}
|
|
221
223
|
|
|
224
|
+
/**
|
|
225
|
+
* Proves the session's second factor (proveFactor) and, when accepted, marks
|
|
226
|
+
* the session with the time.
|
|
227
|
+
* @param {import("../types.js").AuthLocalBackendTransaction} tx
|
|
228
|
+
* @param {{ userId: string, sessionId: string }} session
|
|
229
|
+
* @param {object} factor
|
|
230
|
+
* @param {{ code: string } | { recoveryCode: string }} proof
|
|
231
|
+
* @param {object} [changes]
|
|
232
|
+
*/
|
|
233
|
+
async function prove(tx, session, factor, proof, changes = {}) {
|
|
234
|
+
const outcome = await proveFactor(tx, session.userId, factor, proof, changes);
|
|
235
|
+
if (outcome.factor) {
|
|
236
|
+
await tx.sessions.markSecondFactorProved(session.sessionId, outcome.verifiedAt);
|
|
237
|
+
}
|
|
238
|
+
return outcome;
|
|
239
|
+
}
|
|
240
|
+
|
|
222
241
|
/**
|
|
223
242
|
* Proves the session's second factor with the account's confirmed factor.
|
|
224
243
|
* @param {import("../types.js").AuthLocalBackendTransaction} tx
|
|
@@ -231,15 +250,20 @@ function createLocalSecondFactor({ backend, config, logger, secondFactorEvents,
|
|
|
231
250
|
return factor?.confirmedAt ? prove(tx, session, factor, proof, changes) : { refusal: REFUSALS.notSetUp };
|
|
232
251
|
}
|
|
233
252
|
|
|
234
|
-
/**
|
|
235
|
-
|
|
253
|
+
/**
|
|
254
|
+
* Throws a refused outcome's error after its transaction, so the failure it counted is kept, and records it.
|
|
255
|
+
* @param {object} outcome
|
|
256
|
+
* @param {{ userId: string, ip: string }} session
|
|
257
|
+
* @param {object} [details] More of the event, as its `via`.
|
|
258
|
+
*/
|
|
259
|
+
async function refuseFailed(outcome, session, details = {}) {
|
|
236
260
|
if (outcome.waitMs) {
|
|
237
|
-
await recordEvent("failed", session, { reason: "locked" });
|
|
261
|
+
await recordEvent("failed", session, { ...details, reason: "locked" });
|
|
238
262
|
throw secondFactorLockedError(outcome.waitMs);
|
|
239
263
|
}
|
|
240
264
|
if (outcome.refusal) {
|
|
241
265
|
if (outcome.refusal.reason) {
|
|
242
|
-
await recordEvent("failed", session, { reason: outcome.refusal.reason });
|
|
266
|
+
await recordEvent("failed", session, { ...details, reason: outcome.refusal.reason });
|
|
243
267
|
}
|
|
244
268
|
throw secondFactorError(outcome.refusal);
|
|
245
269
|
}
|
|
@@ -330,6 +354,42 @@ function createLocalSecondFactor({ backend, config, logger, secondFactorEvents,
|
|
|
330
354
|
return { verifiedAt: outcome.verifiedAt, method: outcome.method, recoveryCodesLeft };
|
|
331
355
|
}
|
|
332
356
|
|
|
357
|
+
/**
|
|
358
|
+
* Checks a proof of the second factor of an account the application names
|
|
359
|
+
* (a local account id), which decides whose and when: for a caller with no
|
|
360
|
+
* session of that account, such as a command signed in with an API key that
|
|
361
|
+
* asks for its creator's code. It proves what verifySecondFactor proves, with
|
|
362
|
+
* the same attempts, waits and once-only codes, but marks no session. An
|
|
363
|
+
* unknown or disabled account is refused before anything is checked, and a
|
|
364
|
+
* refusal throws, as verifySecondFactor's do. Its events say `via`
|
|
365
|
+
* "application", with no request's address.
|
|
366
|
+
* @param {{ userId: string, proof: import("@jskit-ai/auth-core/server/types").AuthSecondFactorProof }} input
|
|
367
|
+
*/
|
|
368
|
+
async function verifySecondFactorOf({ userId, proof } = {}) {
|
|
369
|
+
const id = String(userId ?? "").trim();
|
|
370
|
+
if (!id) {
|
|
371
|
+
throw new TypeError("verifySecondFactorOf() takes the userId whose second factor it checks and its proof.");
|
|
372
|
+
}
|
|
373
|
+
const checked = readProof(proof ?? {});
|
|
374
|
+
const subject = { userId: id, ip: "" };
|
|
375
|
+
const via = { via: "application" };
|
|
376
|
+
const outcome = await backend.withTransaction(async (tx) => {
|
|
377
|
+
const user = await tx.users.findById(id);
|
|
378
|
+
if (!user) {
|
|
379
|
+
return { refusal: REFUSALS.accountNotFound };
|
|
380
|
+
}
|
|
381
|
+
if (user.disabled) {
|
|
382
|
+
return { refusal: REFUSALS.accountDisabled };
|
|
383
|
+
}
|
|
384
|
+
const factor = await tx.secondFactors.find(id);
|
|
385
|
+
return factor?.confirmedAt ? proveFactor(tx, id, factor, checked) : { refusal: REFUSALS.notSetUp };
|
|
386
|
+
});
|
|
387
|
+
await refuseFailed(outcome, subject, via);
|
|
388
|
+
const recoveryCodesLeft = outcome.factor.recoveryCodes.length;
|
|
389
|
+
await recordEvent("verified", subject, { ...via, method: outcome.method, recoveryCodesLeft });
|
|
390
|
+
return { verifiedAt: outcome.verifiedAt, method: outcome.method, recoveryCodesLeft };
|
|
391
|
+
}
|
|
392
|
+
|
|
333
393
|
async function replaceSecondFactorRecoveryCodes(request, input) {
|
|
334
394
|
const session = await signedInSession(request);
|
|
335
395
|
const proof = readProof(input);
|
|
@@ -398,6 +458,7 @@ function createLocalSecondFactor({ backend, config, logger, secondFactorEvents,
|
|
|
398
458
|
startSecondFactorSetup,
|
|
399
459
|
confirmSecondFactorSetup,
|
|
400
460
|
verifySecondFactor,
|
|
461
|
+
verifySecondFactorOf,
|
|
401
462
|
replaceSecondFactorRecoveryCodes,
|
|
402
463
|
removeSecondFactor,
|
|
403
464
|
listSecondFactors,
|
|
@@ -22,6 +22,7 @@ const NO_SECOND_FACTOR = Object.freeze({
|
|
|
22
22
|
startSecondFactorSetup: () => throwUnsupportedAuthOperation("startSecondFactorSetup"),
|
|
23
23
|
confirmSecondFactorSetup: () => throwUnsupportedAuthOperation("confirmSecondFactorSetup"),
|
|
24
24
|
verifySecondFactor: () => throwUnsupportedAuthOperation("verifySecondFactor"),
|
|
25
|
+
verifySecondFactorOf: () => throwUnsupportedAuthOperation("verifySecondFactorOf"),
|
|
25
26
|
replaceSecondFactorRecoveryCodes: () => throwUnsupportedAuthOperation("replaceSecondFactorRecoveryCodes"),
|
|
26
27
|
removeSecondFactor: () => throwUnsupportedAuthOperation("removeSecondFactor"),
|
|
27
28
|
listSecondFactors: () => throwUnsupportedAuthOperation("listSecondFactors"),
|
|
@@ -276,6 +277,7 @@ function createLocalAuthService({
|
|
|
276
277
|
startSecondFactorSetup: secondFactor.startSecondFactorSetup,
|
|
277
278
|
confirmSecondFactorSetup: secondFactor.confirmSecondFactorSetup,
|
|
278
279
|
verifySecondFactor: secondFactor.verifySecondFactor,
|
|
280
|
+
verifySecondFactorOf: secondFactor.verifySecondFactorOf,
|
|
279
281
|
replaceSecondFactorRecoveryCodes: secondFactor.replaceSecondFactorRecoveryCodes,
|
|
280
282
|
removeSecondFactor: secondFactor.removeSecondFactor,
|
|
281
283
|
listSecondFactors: secondFactor.listSecondFactors,
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { createId, isExpiredIso, randomToken, sha256Base64url, verifySignedToken } from "./tokens.js";
|
|
2
|
+
|
|
3
|
+
// A service key lets another application's server (an assistant such as Mercbot) call this app's bearer routes
|
|
4
|
+
// (credentials: "bearer") as the users it names: each call names exactly one (Act-As-User: a user id, or an email that
|
|
5
|
+
// exactly one enabled account has) and runs with that user's own rights, never with the key's. A key is one row of the
|
|
6
|
+
// sessions store, purpose "service-key", of a dedicated service user whose display name names it; an administrator
|
|
7
|
+
// makes it (createServiceKeyRecord, written with the backend's sessions.create) and ends it by revoking that row or
|
|
8
|
+
// disabling the service user. It never signs in a browser: cookie authentication takes only normal and development
|
|
9
|
+
// sessions.
|
|
10
|
+
|
|
11
|
+
const SERVICE_KEY_PURPOSE = "service-key";
|
|
12
|
+
const ACT_AS_USER_HEADER = "act-as-user";
|
|
13
|
+
const DEFAULT_LIFETIME_DAYS = 365;
|
|
14
|
+
const MAX_LIFETIME_DAYS = 3650;
|
|
15
|
+
const DAY_MS = 86_400_000;
|
|
16
|
+
const BEARER_PATTERN = /^Bearer ([A-Za-z0-9._~+/-]+=*)$/u;
|
|
17
|
+
// The most of a caller's Act-As-User a refusal repeats back.
|
|
18
|
+
const ECHO_MAX_LENGTH = 320;
|
|
19
|
+
|
|
20
|
+
const REFUSALS = Object.freeze({
|
|
21
|
+
required: [401, "auth.serviceKey.required",
|
|
22
|
+
() => "This route takes a service key: send Authorization: Bearer <key> and Act-As-User: <user id or email>."],
|
|
23
|
+
invalid: [401, "auth.serviceKey.invalid",
|
|
24
|
+
() => "The service key is unknown, revoked or expired, or its service user is disabled."],
|
|
25
|
+
notServiceKey: [403, "auth.serviceKey.notServiceKey",
|
|
26
|
+
() => "Only a service key may act as other users; a person's own sign-in may not."],
|
|
27
|
+
actAsRequired: [400, "auth.serviceKey.actAsRequired",
|
|
28
|
+
() => "Name the user this call acts as in Act-As-User (a user id or email): a service key never acts as itself."],
|
|
29
|
+
actAsUnknown: [403, "auth.serviceKey.actAsUnknown", (who) => `There is no user ${who} to act as.`],
|
|
30
|
+
actAsInactive: [403, "auth.serviceKey.actAsInactive", (who) => `User ${who} is disabled, so nothing may act as them.`],
|
|
31
|
+
actAsAmbiguous: [403, "auth.serviceKey.actAsAmbiguous",
|
|
32
|
+
(who) => `More than one user has the email ${who}, so it names no one: pick yours and act as it by its id.`],
|
|
33
|
+
actAsSelf: [403, "auth.serviceKey.actAsSelf", () => "A service key acts as other users, never as its own service user."]
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A new service key for a service user, and the sessions-store row that holds its hash: the caller writes the row in
|
|
38
|
+
* its backend's transaction (`tx.sessions.create(record)`) and shows the key once; it cannot be read back.
|
|
39
|
+
* @param {{ userId: string, now?: number, days?: number }} options `days` is the key's lifetime, 1 to 3650 (365).
|
|
40
|
+
*/
|
|
41
|
+
function createServiceKeyRecord({ userId, now = Date.now(), days = DEFAULT_LIFETIME_DAYS } = /** @type {any} */ ({})) {
|
|
42
|
+
if (!String(userId ?? "").trim()) throw new TypeError("createServiceKeyRecord needs the userId of the key's service user.");
|
|
43
|
+
if (!Number.isInteger(days) || days < 1 || days > MAX_LIFETIME_DAYS) {
|
|
44
|
+
throw new TypeError(`createServiceKeyRecord days is a key's lifetime in whole days, 1 to ${MAX_LIFETIME_DAYS}.`);
|
|
45
|
+
}
|
|
46
|
+
const key = `svk_${randomToken(32)}`;
|
|
47
|
+
return Object.freeze({
|
|
48
|
+
key,
|
|
49
|
+
record: Object.freeze({
|
|
50
|
+
id: createId("svk"),
|
|
51
|
+
userId: String(userId).trim(),
|
|
52
|
+
tokenHash: sha256Base64url(key),
|
|
53
|
+
purpose: SERVICE_KEY_PURPOSE,
|
|
54
|
+
createdAt: new Date(now).toISOString(),
|
|
55
|
+
expiresAt: new Date(now + days * DAY_MS).toISOString()
|
|
56
|
+
})
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A bearer route's refusal in words, which auth-core answers with its status and code. */
|
|
61
|
+
function serviceKeyRefusal(reason, actAs = "") {
|
|
62
|
+
const [status, code, message] = REFUSALS[reason];
|
|
63
|
+
return Object.freeze({
|
|
64
|
+
authenticated: false,
|
|
65
|
+
session: null,
|
|
66
|
+
clearSession: false,
|
|
67
|
+
transientFailure: false,
|
|
68
|
+
refusal: Object.freeze({ status, code, message: message(JSON.stringify(actAs.slice(0, ECHO_MAX_LENGTH))) })
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The user an email names: the one enabled account with it, else a disabled one (which is refused as disabled), else
|
|
74
|
+
* none; more than one enabled account with it names no one.
|
|
75
|
+
* @param {import("../types.js").AuthLocalBackendTransaction["users"]} users
|
|
76
|
+
* @param {string} email
|
|
77
|
+
*/
|
|
78
|
+
async function userByEmail(users, email) {
|
|
79
|
+
// readable-check: allow method-probe - input validation: a backend from before findAllByEmail fails naming its fix
|
|
80
|
+
if (typeof users.findAllByEmail !== "function") {
|
|
81
|
+
throw new TypeError("A service key acts as a user by email through the backend's users.findAllByEmail(email), every account with that email: add it to the local auth backend.");
|
|
82
|
+
}
|
|
83
|
+
const matches = await users.findAllByEmail(email);
|
|
84
|
+
const enabled = matches.filter((match) => !match.disabled);
|
|
85
|
+
if (enabled.length > 1) return { ambiguous: true, user: null };
|
|
86
|
+
return { ambiguous: false, user: enabled[0] || matches[0] || null };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Who a bearer request acts as: its service key, checked, and the active user its Act-As-User names; or the reason it
|
|
91
|
+
* is refused. One read of the key and two of users, in one transaction.
|
|
92
|
+
* @param {object} dependencies
|
|
93
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
94
|
+
* @param {string} dependencies.sessionSecret What a person's own access tokens are signed with.
|
|
95
|
+
* @param {{ headers?: Record<string, unknown> }} request
|
|
96
|
+
* @returns {Promise<{ refusal: string, actAs?: string } | { key: object, keyUser: object, user: object }>}
|
|
97
|
+
*/
|
|
98
|
+
async function resolveServiceKeyCall({ backend, sessionSecret }, request) {
|
|
99
|
+
const authorization = String(request?.headers?.authorization || "").trim();
|
|
100
|
+
if (!authorization) return { refusal: "required" };
|
|
101
|
+
const token = BEARER_PATTERN.exec(authorization)?.[1] || "";
|
|
102
|
+
if (!token) return { refusal: "invalid" };
|
|
103
|
+
// A person's own access token is signed: it is theirs alone, never a key.
|
|
104
|
+
if (verifySignedToken(token, sessionSecret)) return { refusal: "notServiceKey" };
|
|
105
|
+
const actAs = String(request.headers[ACT_AS_USER_HEADER] || "").trim();
|
|
106
|
+
return backend.withTransaction(async (tx) => {
|
|
107
|
+
const key = await tx.sessions.findByTokenHash(sha256Base64url(token));
|
|
108
|
+
if (!key || key.revokedAt || isExpiredIso(key.expiresAt)) return { refusal: "invalid" };
|
|
109
|
+
if (key.purpose !== SERVICE_KEY_PURPOSE) return { refusal: "notServiceKey" };
|
|
110
|
+
const keyUser = await tx.users.findById(String(key.userId));
|
|
111
|
+
if (!keyUser || keyUser.disabled) return { refusal: "invalid" };
|
|
112
|
+
if (!actAs) return { refusal: "actAsRequired" };
|
|
113
|
+
const found = actAs.includes("@") ? await userByEmail(tx.users, actAs.toLowerCase()) : { user: await tx.users.findById(actAs) };
|
|
114
|
+
if (found.ambiguous) return { refusal: "actAsAmbiguous", actAs };
|
|
115
|
+
const { user } = found;
|
|
116
|
+
if (!user) return { refusal: "actAsUnknown", actAs };
|
|
117
|
+
if (String(user.id) === String(keyUser.id)) return { refusal: "actAsSelf", actAs };
|
|
118
|
+
if (user.disabled) return { refusal: "actAsInactive", actAs };
|
|
119
|
+
return { key, keyUser, user };
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export { ACT_AS_USER_HEADER, SERVICE_KEY_PURPOSE, createServiceKeyRecord, resolveServiceKeyCall, serviceKeyRefusal };
|
|
@@ -2,6 +2,7 @@ import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authText
|
|
|
2
2
|
import { hostOnlyCookieName } from "@jskit-ai/auth-core/server/utils";
|
|
3
3
|
import { buildSessionAuthPayload, isAuthenticatingSession } from "./authPayloads.js";
|
|
4
4
|
import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url, signToken, verifySignedToken } from "./tokens.js";
|
|
5
|
+
import { SERVICE_KEY_PURPOSE, resolveServiceKeyCall, serviceKeyRefusal } from "./serviceKeys.js";
|
|
5
6
|
|
|
6
7
|
const ACCESS_TOKEN_COOKIE_NAME = "jskit_local_access_token";
|
|
7
8
|
const REFRESH_TOKEN_COOKIE_NAME = "jskit_local_refresh_token";
|
|
@@ -238,10 +239,10 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
|
|
|
238
239
|
// A check without profile synchronization does not answer for a synchronizing one, and only an object can be
|
|
239
240
|
// remembered.
|
|
240
241
|
if (!syncProfile || !request || typeof request !== "object") {
|
|
241
|
-
return
|
|
242
|
+
return authenticateFromCredentials(request, { syncProfile });
|
|
242
243
|
}
|
|
243
244
|
if (!requestAuthentications.has(request)) {
|
|
244
|
-
const answer =
|
|
245
|
+
const answer = authenticateFromCredentials(request, { syncProfile });
|
|
245
246
|
requestAuthentications.set(request, answer);
|
|
246
247
|
// A failure is not remembered: a later check in the request tries again.
|
|
247
248
|
answer.catch(() => {
|
|
@@ -266,6 +267,49 @@ function createLocalSessions({ appProfileProjection, backend, config, deliveries
|
|
|
266
267
|
}
|
|
267
268
|
}
|
|
268
269
|
|
|
270
|
+
/**
|
|
271
|
+
* A request is authenticated by the credentials its route takes (auth-core sets `request.authCredentials`): a bearer
|
|
272
|
+
* route by its service key and the user it acts as alone, every other route by its cookies alone.
|
|
273
|
+
*/
|
|
274
|
+
function authenticateFromCredentials(request, options) {
|
|
275
|
+
return request?.authCredentials === "bearer" ? authenticateFromServiceKey(request, options) : authenticateFromCookies(request, options);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* A service key's call (serviceKeys.js): signed in as the active user its Act-As-User names, never as the key's own
|
|
280
|
+
* service user, which it carries as `via`. It refreshes nothing and writes no cookie; its sign-in has no address and
|
|
281
|
+
* no second factor, so a route that asks for either refuses it.
|
|
282
|
+
*/
|
|
283
|
+
async function authenticateFromServiceKey(request, { syncProfile }) {
|
|
284
|
+
const resolved = await resolveServiceKeyCall({ backend, sessionSecret: config.sessionSecret }, request);
|
|
285
|
+
if ("refusal" in resolved) return serviceKeyRefusal(resolved.refusal, resolved.actAs);
|
|
286
|
+
const authPayload = await buildSessionAuthPayload({
|
|
287
|
+
appProfileProjection,
|
|
288
|
+
devAuth,
|
|
289
|
+
profileProjector,
|
|
290
|
+
request,
|
|
291
|
+
session: resolved.key,
|
|
292
|
+
user: resolved.user,
|
|
293
|
+
syncProfile,
|
|
294
|
+
onlyWhenChanged: true
|
|
295
|
+
});
|
|
296
|
+
if (!authPayload) return serviceKeyRefusal("actAsUnknown", String(resolved.user.id));
|
|
297
|
+
return {
|
|
298
|
+
authenticated: true,
|
|
299
|
+
...authPayload,
|
|
300
|
+
credentials: "bearer",
|
|
301
|
+
via: Object.freeze({ userId: String(resolved.keyUser.id), name: resolved.keyUser.displayName }),
|
|
302
|
+
session: null,
|
|
303
|
+
sessionId: resolved.key.id,
|
|
304
|
+
secondFactorAt: "",
|
|
305
|
+
sessionPurpose: SERVICE_KEY_PURPOSE,
|
|
306
|
+
signIn: sessionSignIn(resolved.key),
|
|
307
|
+
credentialsChangedAt: credentialsChangedAt(resolved.user),
|
|
308
|
+
clearSession: false,
|
|
309
|
+
transientFailure: false
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
269
313
|
async function authenticateFromCookies(request, { syncProfile }) {
|
|
270
314
|
const cookies = safeRequestCookies(request);
|
|
271
315
|
const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
|
package/src/server/types.js
CHANGED
|
@@ -12,12 +12,15 @@
|
|
|
12
12
|
* create(input: object): Promise<object>,
|
|
13
13
|
* findById(userId: string): Promise<object | null>,
|
|
14
14
|
* findByEmail(email: string): Promise<object | null>,
|
|
15
|
+
* findAllByEmail(email: string): Promise<object[]>,
|
|
15
16
|
* hasAny(): Promise<boolean>,
|
|
16
17
|
* updatePassword(userId: string, passwordRecord: object): Promise<object | null>,
|
|
17
18
|
* updateProfile(userId: string, updates: object): Promise<object | null>,
|
|
18
19
|
* updatePendingEmail(userId: string, pendingEmail: string): Promise<object | null>,
|
|
19
20
|
* updateEmail(userId: string, email: string): Promise<object | null>
|
|
20
|
-
* }} users `
|
|
21
|
+
* }} users `findAllByEmail` answers every account with the email, enabled or not, which a store whose emails are
|
|
22
|
+
* unique answers as one or none: a service key acts as a user by email only when exactly one enabled account has it.
|
|
23
|
+
* `hasAny` answers whether any account exists. A user whose `disabled` is true has every sign-in and session
|
|
21
24
|
* refused, and a sign-in that proves who it is (the right password, a provider or a pass) is told its
|
|
22
25
|
* `disabledMessage`, or that the account is disabled when it has none; the file backend keeps no message. A user's
|
|
23
26
|
* `pendingEmail` is the address its email change waits to confirm ("" when none): `updatePendingEmail` sets it, and
|
|
@@ -138,7 +141,10 @@
|
|
|
138
141
|
* recoveryCodeInvalid or locked), the recovery codes replaced, the
|
|
139
142
|
* authenticator removed by its person, or reset by the application for the
|
|
140
143
|
* account `byUserId` names. `userId` is the local account's id, `ip` the
|
|
141
|
-
* request's address ("" for a reset
|
|
144
|
+
* request's address ("" for a reset, and for a proof the application checked
|
|
145
|
+
* with verifySecondFactorOf, which has no request), `at` an ISO time. `via` is
|
|
146
|
+
* "application" on the events of verifySecondFactorOf, and absent on a
|
|
147
|
+
* session's own.
|
|
142
148
|
* @typedef {object} AuthLocalSecondFactorEvent
|
|
143
149
|
* @property {"setupStarted" | "setupConfirmed" | "verified" | "failed" | "recoveryCodesReplaced" | "removed" | "reset"} type
|
|
144
150
|
* @property {string} userId
|
|
@@ -148,6 +154,7 @@
|
|
|
148
154
|
* @property {number} [recoveryCodesLeft]
|
|
149
155
|
* @property {"codeInvalid" | "codeUsed" | "recoveryCodeInvalid" | "locked"} [reason]
|
|
150
156
|
* @property {string} [byUserId]
|
|
157
|
+
* @property {"application"} [via]
|
|
151
158
|
*/
|
|
152
159
|
|
|
153
160
|
/**
|
package/test/codedTexts.test.js
CHANGED
|
@@ -89,6 +89,10 @@ test("second factor refusals carry codes whose English is the thrown message", a
|
|
|
89
89
|
const coded = (code) => (error) => assertCoded(error, code);
|
|
90
90
|
|
|
91
91
|
await assert.rejects(service.verifySecondFactor(request(), { code: "123456" }), coded("auth.local.secondFactor.notSetUp"));
|
|
92
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: "usr_missing", proof: { code: "123456" } }),
|
|
93
|
+
coded("auth.local.secondFactor.accountNotFound"));
|
|
94
|
+
const user = (await service.authenticateRequest(request())).actor.providerUserId;
|
|
95
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: user, proof: { code: "123456" } }), coded("auth.local.secondFactor.notSetUp"));
|
|
92
96
|
await assert.rejects(service.confirmSecondFactorSetup(request(), { code: "123456" }), coded("auth.local.secondFactor.setupNotStarted"));
|
|
93
97
|
const { secret } = await service.startSecondFactorSetup(request());
|
|
94
98
|
await service.confirmSecondFactorSetup(request(), { code: codeAt(secret) });
|
|
@@ -6,6 +6,7 @@ import test from "node:test";
|
|
|
6
6
|
import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
|
|
7
7
|
import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
8
8
|
import { __testables, deriveSecondFactorKeys, openSecret, sealSecret } from "../src/server/lib/secondFactorCrypto.js";
|
|
9
|
+
import { NO_PASSWORD } from "../src/server/lib/accounts.js";
|
|
9
10
|
import { localServiceOptions } from "../test-support/localService.js";
|
|
10
11
|
import { sessionCookies } from "../test-support/oauthHarness.js";
|
|
11
12
|
import {
|
|
@@ -67,6 +68,189 @@ test("an authenticator sets up, proves sessions, refuses wrong, used and expired
|
|
|
67
68
|
});
|
|
68
69
|
});
|
|
69
70
|
|
|
71
|
+
const PASSWORD = "correct horse battery staple";
|
|
72
|
+
const CODE_INVALID = Object.freeze({ status: 400, code: "auth.local.secondFactor.codeInvalid" });
|
|
73
|
+
const CODE_USED = Object.freeze({ status: 400, code: "auth.local.secondFactor.codeUsed" });
|
|
74
|
+
const RECOVERY_CODE_INVALID = Object.freeze({ status: 400, code: "auth.local.secondFactor.recoveryCodeInvalid" });
|
|
75
|
+
const PROOF_REQUIRED = Object.freeze({ status: 400, code: "auth.local.secondFactor.proofRequired" });
|
|
76
|
+
const NOT_SET_UP = Object.freeze({ status: 409, code: "auth.local.secondFactor.notSetUp" });
|
|
77
|
+
const ACCOUNT_NOT_FOUND = Object.freeze({ status: 404, code: "auth.local.secondFactor.accountNotFound" });
|
|
78
|
+
const ACCOUNT_DISABLED = Object.freeze({ status: 403, code: "auth.local.secondFactor.accountDisabled" });
|
|
79
|
+
|
|
80
|
+
/** A refusal while the account waits after wrong codes, for `seconds`. */
|
|
81
|
+
function lockedFor(seconds) {
|
|
82
|
+
return (error) => {
|
|
83
|
+
assert.equal(error.status, 429);
|
|
84
|
+
assert.equal(error.code, "auth.local.secondFactor.locked");
|
|
85
|
+
assert.equal(error.headers["retry-after"], String(seconds));
|
|
86
|
+
return true;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Six digits that are none of the codes accepted now. */
|
|
91
|
+
function wrongCode(secret) {
|
|
92
|
+
const accepted = new Set([-1, 0, 1].map((offset) => codeAt(secret, offset)));
|
|
93
|
+
let guess = 0;
|
|
94
|
+
while (accepted.has(String(guess).padStart(6, "0"))) {
|
|
95
|
+
guess += 1;
|
|
96
|
+
}
|
|
97
|
+
return String(guess).padStart(6, "0");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* A file-backed service where Ada has an authenticator, confirmed one step ago, and two sessions (the second never
|
|
102
|
+
* proved its second factor), and Bob has none.
|
|
103
|
+
*/
|
|
104
|
+
async function enrolledAda(t) {
|
|
105
|
+
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
106
|
+
const { events, options } = secondFactorServiceOptions();
|
|
107
|
+
const backend = createLocalFileBackend({ storeDir: await storeDirFor(t) });
|
|
108
|
+
const service = createLocalAuthService({ ...options, backend });
|
|
109
|
+
await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
110
|
+
await service.register({ email: "bob@example.com", password: PASSWORD });
|
|
111
|
+
const signIn = async (email) => {
|
|
112
|
+
const cookies = sessionCookies((await service.login({ email, password: PASSWORD })).session);
|
|
113
|
+
return () => ({ cookies, ip: "203.0.113.7" });
|
|
114
|
+
};
|
|
115
|
+
const ada = await signIn("ada@example.com");
|
|
116
|
+
const adaPhone = await signIn("ada@example.com");
|
|
117
|
+
const bob = await signIn("bob@example.com");
|
|
118
|
+
const adaId = (await service.authenticateRequest(ada())).actor.providerUserId;
|
|
119
|
+
const bobId = (await service.authenticateRequest(bob())).actor.providerUserId;
|
|
120
|
+
const { secret } = await service.startSecondFactorSetup(ada());
|
|
121
|
+
const { recoveryCodes } = await service.confirmSecondFactorSetup(ada(), { code: codeAt(secret) });
|
|
122
|
+
t.mock.timers.tick(30_000);
|
|
123
|
+
return { service, backend, events, ada, adaPhone, bob, adaId, bobId, secret, recoveryCodes };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
test("verifySecondFactorOf accepts the named account's current code once, answers the verification and marks no session", async (t) => {
|
|
127
|
+
const { service, events, adaPhone, adaId, secret } = await enrolledAda(t);
|
|
128
|
+
const typed = codeAt(secret);
|
|
129
|
+
const at = new Date().toISOString();
|
|
130
|
+
assert.deepEqual(await service.verifySecondFactorOf({ userId: adaId, proof: { code: ` ${typed.slice(0, 3)} ${typed.slice(3)} ` } }), {
|
|
131
|
+
verifiedAt: at,
|
|
132
|
+
method: "code",
|
|
133
|
+
recoveryCodesLeft: 10
|
|
134
|
+
});
|
|
135
|
+
assert.equal((await service.getSecondFactorStatus(adaPhone())).verifiedAt, null, "no session proved anything");
|
|
136
|
+
// The code is used up for every path: the same one again, here or by a session, is refused.
|
|
137
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: typed } }), CODE_USED);
|
|
138
|
+
await assert.rejects(service.verifySecondFactor(adaPhone(), { code: typed }), CODE_USED);
|
|
139
|
+
assert.deepEqual(events.at(-3), { type: "verified", userId: adaId, ip: "", via: "application", at, method: "code", recoveryCodesLeft: 10 });
|
|
140
|
+
assert.equal(events.at(-2).via, "application");
|
|
141
|
+
assert.equal(Object.hasOwn(events.at(-1), "via"), false, "a session's own event has no via");
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test("verifySecondFactorOf refuses a wrong code or recovery code, and a proof that is not exactly one of them", async (t) => {
|
|
145
|
+
const { service, events, adaId, secret, recoveryCodes } = await enrolledAda(t);
|
|
146
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: wrongCode(secret) } }), CODE_INVALID);
|
|
147
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: "12345" } }), CODE_INVALID);
|
|
148
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { recoveryCode: "abcde-fghjk" } }), RECOVERY_CODE_INVALID);
|
|
149
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: {} }), PROOF_REQUIRED);
|
|
150
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId }), PROOF_REQUIRED);
|
|
151
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret), recoveryCode: recoveryCodes[0] } }),
|
|
152
|
+
PROOF_REQUIRED);
|
|
153
|
+
await assert.rejects(service.verifySecondFactorOf({ proof: { code: codeAt(secret) } }), TypeError);
|
|
154
|
+
const failures = events.filter((event) => event.type === "failed");
|
|
155
|
+
assert.deepEqual(failures.map((event) => [event.userId, event.ip, event.via, event.reason]), [
|
|
156
|
+
[adaId, "", "application", "codeInvalid"],
|
|
157
|
+
[adaId, "", "application", "codeInvalid"],
|
|
158
|
+
[adaId, "", "application", "recoveryCodeInvalid"]
|
|
159
|
+
]);
|
|
160
|
+
const everyEvent = JSON.stringify(events);
|
|
161
|
+
for (const shown of [secret, ...recoveryCodes]) {
|
|
162
|
+
assert.equal(everyEvent.includes(shown), false, "no event carries a secret or a code");
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test("verifySecondFactorOf and a session's verification count the same wrong codes: failing through one locks the other", async (t) => {
|
|
167
|
+
const { service, ada, adaPhone, adaId, bob, bobId, secret, recoveryCodes } = await enrolledAda(t);
|
|
168
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
169
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: wrongCode(secret) } }), CODE_INVALID);
|
|
170
|
+
}
|
|
171
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: codeAt(secret) }), lockedFor(30));
|
|
172
|
+
await assert.rejects(service.verifySecondFactor(adaPhone(), { recoveryCode: recoveryCodes[0] }), lockedFor(30));
|
|
173
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret) } }), lockedFor(30));
|
|
174
|
+
|
|
175
|
+
// After the wait a right code here forgets the failures; then wrong codes in a session lock this call.
|
|
176
|
+
t.mock.timers.tick(30_000);
|
|
177
|
+
assert.equal((await service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret) } })).method, "code");
|
|
178
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
179
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: wrongCode(secret) }), CODE_INVALID);
|
|
180
|
+
}
|
|
181
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret) } }), lockedFor(30));
|
|
182
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { recoveryCode: recoveryCodes[0] } }), lockedFor(30));
|
|
183
|
+
|
|
184
|
+
// Failures through both add up to one count.
|
|
185
|
+
t.mock.timers.tick(30_000);
|
|
186
|
+
assert.equal((await service.verifySecondFactor(ada(), { code: codeAt(secret) })).method, "code");
|
|
187
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
188
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: wrongCode(secret) }), CODE_INVALID);
|
|
189
|
+
}
|
|
190
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
191
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { recoveryCode: "abcde-fghjk" } }), RECOVERY_CODE_INVALID);
|
|
192
|
+
}
|
|
193
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: codeAt(secret) }), lockedFor(30));
|
|
194
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret) } }), lockedFor(30));
|
|
195
|
+
|
|
196
|
+
// Another account's attempts count apart.
|
|
197
|
+
const { secret: bobSecret } = await service.startSecondFactorSetup(bob());
|
|
198
|
+
await service.confirmSecondFactorSetup(bob(), { code: codeAt(bobSecret) });
|
|
199
|
+
t.mock.timers.tick(30_000);
|
|
200
|
+
assert.equal((await service.verifySecondFactorOf({ userId: bobId, proof: { code: codeAt(bobSecret) } })).method, "code");
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
test("verifySecondFactorOf uses a recovery code up once, shared with the session's recovery codes", async (t) => {
|
|
204
|
+
const { service, ada, adaId, recoveryCodes } = await enrolledAda(t);
|
|
205
|
+
const [first, second] = recoveryCodes;
|
|
206
|
+
const at = new Date().toISOString();
|
|
207
|
+
assert.deepEqual(await service.verifySecondFactorOf({ userId: adaId, proof: { recoveryCode: ` ${first.toUpperCase()} ` } }), {
|
|
208
|
+
verifiedAt: at,
|
|
209
|
+
method: "recoveryCode",
|
|
210
|
+
recoveryCodesLeft: 9
|
|
211
|
+
});
|
|
212
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { recoveryCode: first } }), RECOVERY_CODE_INVALID);
|
|
213
|
+
await assert.rejects(service.verifySecondFactor(ada(), { recoveryCode: first }), RECOVERY_CODE_INVALID);
|
|
214
|
+
assert.equal((await service.verifySecondFactor(ada(), { recoveryCode: second })).recoveryCodesLeft, 8);
|
|
215
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { recoveryCode: second } }), RECOVERY_CODE_INVALID);
|
|
216
|
+
assert.equal((await service.getSecondFactorStatus(ada())).recoveryCodesLeft, 8);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("verifySecondFactorOf refuses an unknown account, a disabled one, one without an authenticator and a waiting one, each with its own code", async (t) => {
|
|
220
|
+
const { service, backend, bob, adaId, bobId, secret } = await enrolledAda(t);
|
|
221
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: "usr_missing", proof: { code: "123456" } }), ACCOUNT_NOT_FOUND);
|
|
222
|
+
// A disabled account is refused even with its authenticator's right code.
|
|
223
|
+
const offSecret = toBase32(Buffer.from("12345678901234567890"));
|
|
224
|
+
const at = new Date().toISOString();
|
|
225
|
+
await backend.withTransaction(async (tx) => {
|
|
226
|
+
await tx.users.create({ id: "usr_off", email: "off@example.com", displayName: "Off", password: NO_PASSWORD, disabled: true });
|
|
227
|
+
await tx.secondFactors.save({
|
|
228
|
+
userId: "usr_off",
|
|
229
|
+
secretSealed: sealSecret(deriveSecondFactorKeys(SECOND_FACTOR_KEY), "usr_off", offSecret),
|
|
230
|
+
confirmedAt: at,
|
|
231
|
+
lastUsedStep: 0,
|
|
232
|
+
recoveryCodes: [],
|
|
233
|
+
failures: 0,
|
|
234
|
+
lastFailedAt: "",
|
|
235
|
+
lockedUntil: "",
|
|
236
|
+
createdAt: at,
|
|
237
|
+
updatedAt: at
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: "usr_off", proof: { code: codeAt(offSecret) } }), ACCOUNT_DISABLED);
|
|
241
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: bobId, proof: { code: "123456" } }), NOT_SET_UP);
|
|
242
|
+
const { secret: started } = await service.startSecondFactorSetup(bob());
|
|
243
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: bobId, proof: { code: codeAt(started) } }), NOT_SET_UP,
|
|
244
|
+
"a setup nobody confirmed is no authenticator");
|
|
245
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
246
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: wrongCode(secret) } }), CODE_INVALID);
|
|
247
|
+
}
|
|
248
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret) } }), lockedFor(30));
|
|
249
|
+
// After the wait the account's code is accepted again.
|
|
250
|
+
t.mock.timers.tick(30_000);
|
|
251
|
+
assert.equal((await service.verifySecondFactorOf({ userId: adaId, proof: { code: codeAt(secret) } })).method, "code");
|
|
252
|
+
});
|
|
253
|
+
|
|
70
254
|
test("the file store keeps a factor and its session's proof across restarts, and another key cannot open it", async (t) => {
|
|
71
255
|
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
72
256
|
const storeDir = await storeDirFor(t);
|
|
@@ -104,6 +288,8 @@ test("a production server has a second factor only with its key, at least 32 cha
|
|
|
104
288
|
assert.equal(service.getCapabilities().features.secondFactor, false);
|
|
105
289
|
assert.throws(() => service.getSecondFactorStatus({ cookies: {} }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
106
290
|
assert.throws(() => service.listSecondFactors({ userIds: [] }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
291
|
+
assert.throws(() => service.verifySecondFactorOf({ userId: "usr_1", proof: { code: "123456" } }),
|
|
292
|
+
{ status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
107
293
|
|
|
108
294
|
const resolve = (env) => resolveLocalAuthConfig({
|
|
109
295
|
appRoot: os.tmpdir(),
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { SERVICE_KEY_PURPOSE, createLocalAuthService, createLocalFileBackend, createServiceKeyRecord } from "../src/server/lib/index.js";
|
|
7
|
+
import { NO_PASSWORD } from "../src/server/lib/accounts.js";
|
|
8
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
9
|
+
import { sessionCookies } from "../test-support/oauthHarness.js";
|
|
10
|
+
|
|
11
|
+
// A service key lets another application's server call this app's bearer routes as the users it names, one per call
|
|
12
|
+
// (Act-As-User), with exactly that user's rights. Every way a call can go wrong is refused in words, and none falls back
|
|
13
|
+
// to the key's own service user.
|
|
14
|
+
|
|
15
|
+
async function startService(t) {
|
|
16
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-service-keys-"));
|
|
17
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
18
|
+
const backend = createLocalFileBackend({ storeDir });
|
|
19
|
+
const service = createLocalAuthService({ ...localServiceOptions(), backend });
|
|
20
|
+
const account = async (email) => (await service.register({ email, password: "correct horse" })).actor;
|
|
21
|
+
const robot = await account("mercbot@example.com");
|
|
22
|
+
const anna = await account("anna@example.com");
|
|
23
|
+
await backend.withTransaction((tx) => tx.users.create({
|
|
24
|
+
id: "usr_gone", email: "gone@example.com", displayName: "Gone", password: NO_PASSWORD, disabled: true
|
|
25
|
+
}));
|
|
26
|
+
async function issue(userId, options = {}) {
|
|
27
|
+
const { key, record } = createServiceKeyRecord({ userId, ...options });
|
|
28
|
+
await backend.withTransaction((tx) => tx.sessions.create(record));
|
|
29
|
+
return { key, record };
|
|
30
|
+
}
|
|
31
|
+
return { backend, service, robot, anna, issue };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// What a bearer route (credentials: "bearer") hands the auth service: auth-core sets authCredentials.
|
|
35
|
+
function call(key, actAs, extra = {}) {
|
|
36
|
+
return {
|
|
37
|
+
authCredentials: "bearer",
|
|
38
|
+
headers: { ...(key ? { authorization: `Bearer ${key}` } : {}), ...(actAs ? { "act-as-user": actAs } : {}) },
|
|
39
|
+
cookies: {},
|
|
40
|
+
...extra
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function assertRefused(result, status, code, words) {
|
|
45
|
+
assert.equal(result.authenticated, false);
|
|
46
|
+
assert.equal(result.actor ?? null, null);
|
|
47
|
+
assert.equal(result.refusal?.status, status, JSON.stringify(result.refusal));
|
|
48
|
+
assert.equal(result.refusal.code, code);
|
|
49
|
+
assert.match(result.refusal.message, words);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
test("a service key acts as the user it names, by id or by email, with that user's identity and the key's name", async (t) => {
|
|
53
|
+
const { service, robot, anna, issue } = await startService(t);
|
|
54
|
+
const { key, record } = await issue(robot.providerUserId);
|
|
55
|
+
assert.equal(record.purpose, SERVICE_KEY_PURPOSE);
|
|
56
|
+
assert.equal(record.userId, robot.providerUserId);
|
|
57
|
+
assert.notEqual(record.tokenHash, key, "the store keeps only the key's hash");
|
|
58
|
+
assert.equal(record.id.length <= 64 && record.tokenHash.length <= 64, true, "it fits a sessions table's 64-character columns");
|
|
59
|
+
|
|
60
|
+
const byId = await service.authenticateRequest(call(key, anna.providerUserId));
|
|
61
|
+
assert.equal(byId.authenticated, true);
|
|
62
|
+
assert.equal(byId.credentials, "bearer");
|
|
63
|
+
assert.equal(byId.actor.providerUserId, anna.providerUserId);
|
|
64
|
+
assert.equal(byId.actor.email, "anna@example.com");
|
|
65
|
+
assert.deepEqual(byId.via, { userId: robot.providerUserId, name: robot.displayName });
|
|
66
|
+
assert.equal(byId.session, null, "it writes no cookie");
|
|
67
|
+
assert.equal(byId.secondFactorAt, "", "a route that asks for a second factor refuses it");
|
|
68
|
+
|
|
69
|
+
const byEmail = await service.authenticateRequest(call(key, "Anna@Example.com"));
|
|
70
|
+
assert.equal(byEmail.actor.providerUserId, anna.providerUserId);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("a call without a key, with a wrong, revoked or expired key, or with a disabled key user is refused", async (t) => {
|
|
74
|
+
const { backend, service, robot, anna, issue } = await startService(t);
|
|
75
|
+
assertRefused(await service.authenticateRequest(call("", anna.providerUserId)), 401, "auth.serviceKey.required", /service key/u);
|
|
76
|
+
assertRefused(await service.authenticateRequest(call("svk_not-a-key", anna.providerUserId)), 401, "auth.serviceKey.invalid",
|
|
77
|
+
/unknown, revoked or expired/u);
|
|
78
|
+
assertRefused(await service.authenticateRequest({ ...call("", anna.providerUserId), headers: { authorization: "Basic abc", "act-as-user": anna.providerUserId } }),
|
|
79
|
+
401, "auth.serviceKey.invalid", /unknown, revoked or expired/u);
|
|
80
|
+
|
|
81
|
+
const revoked = await issue(robot.providerUserId);
|
|
82
|
+
await backend.withTransaction((tx) => tx.sessions.revoke(revoked.record.id));
|
|
83
|
+
assertRefused(await service.authenticateRequest(call(revoked.key, anna.providerUserId)), 401, "auth.serviceKey.invalid", /revoked/u);
|
|
84
|
+
|
|
85
|
+
const expired = await issue(robot.providerUserId, { now: Date.now() - 3 * 86_400_000, days: 1 });
|
|
86
|
+
assertRefused(await service.authenticateRequest(call(expired.key, anna.providerUserId)), 401, "auth.serviceKey.invalid", /expired/u);
|
|
87
|
+
|
|
88
|
+
const ofGone = await issue("usr_gone");
|
|
89
|
+
assertRefused(await service.authenticateRequest(call(ofGone.key, anna.providerUserId)), 401, "auth.serviceKey.invalid", /disabled/u);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("a person's own sign-in may not act as anyone, on a bearer route or by sending the key as a cookie", async (t) => {
|
|
93
|
+
const { service, robot, anna, issue } = await startService(t);
|
|
94
|
+
const signedIn = (await service.login({ email: "anna@example.com", password: "correct horse" })).session;
|
|
95
|
+
assertRefused(await service.authenticateRequest(call(signedIn.access_token, robot.providerUserId)), 403,
|
|
96
|
+
"auth.serviceKey.notServiceKey", /Only a service key may act as other users/u);
|
|
97
|
+
assertRefused(await service.authenticateRequest(call(signedIn.refresh_token, robot.providerUserId)), 403,
|
|
98
|
+
"auth.serviceKey.notServiceKey", /Only a service key/u);
|
|
99
|
+
|
|
100
|
+
const { key } = await issue(robot.providerUserId);
|
|
101
|
+
const asCookie = await service.authenticateRequest({ cookies: sessionCookies({ access_token: "", refresh_token: key }), headers: {} });
|
|
102
|
+
assert.equal(asCookie.authenticated, false, "a service key never signs in a browser");
|
|
103
|
+
const onCookieRoute = await service.authenticateRequest({ cookies: {}, headers: { authorization: `Bearer ${key}`, "act-as-user": anna.providerUserId } });
|
|
104
|
+
assert.equal(onCookieRoute.authenticated, false, "a route that takes cookies ignores the Authorization header");
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("a call that names nobody, an unknown user, a disabled user or the key's own user is refused, never run as the key's user", async (t) => {
|
|
108
|
+
const { service, robot, issue } = await startService(t);
|
|
109
|
+
const { key } = await issue(robot.providerUserId);
|
|
110
|
+
assertRefused(await service.authenticateRequest(call(key, "")), 400, "auth.serviceKey.actAsRequired", /Act-As-User/u);
|
|
111
|
+
assertRefused(await service.authenticateRequest(call(key, " ")), 400, "auth.serviceKey.actAsRequired", /never acts as itself/u);
|
|
112
|
+
assertRefused(await service.authenticateRequest(call(key, "usr_nobody")), 403, "auth.serviceKey.actAsUnknown", /no user "usr_nobody"/u);
|
|
113
|
+
assertRefused(await service.authenticateRequest(call(key, "nobody@example.com")), 403, "auth.serviceKey.actAsUnknown",
|
|
114
|
+
/no user "nobody@example.com"/u);
|
|
115
|
+
assertRefused(await service.authenticateRequest(call(key, "usr_gone")), 403, "auth.serviceKey.actAsInactive", /disabled/u);
|
|
116
|
+
assertRefused(await service.authenticateRequest(call(key, "gone@example.com")), 403, "auth.serviceKey.actAsInactive", /disabled/u);
|
|
117
|
+
assertRefused(await service.authenticateRequest(call(key, robot.providerUserId)), 403, "auth.serviceKey.actAsSelf", /its own service user/u);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// A store whose accounts may share an email, as an app whose accounts are its contacts: it answers every match.
|
|
121
|
+
function withSharedEmails(backend, accounts) {
|
|
122
|
+
return {
|
|
123
|
+
...backend,
|
|
124
|
+
withTransaction: (work) => backend.withTransaction((tx) => work({
|
|
125
|
+
...tx,
|
|
126
|
+
users: {
|
|
127
|
+
...tx.users,
|
|
128
|
+
async findById(id) {
|
|
129
|
+
return accounts.find((account) => account.id === id) || tx.users.findById(id);
|
|
130
|
+
},
|
|
131
|
+
async findAllByEmail(email) {
|
|
132
|
+
return [...await tx.users.findAllByEmail(email), ...accounts.filter((account) => account.email === email)];
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}))
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
test("an email names a user only when exactly one enabled account has it; two enabled accounts with it name no one", async (t) => {
|
|
140
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-service-keys-shared-"));
|
|
141
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
142
|
+
const fileBackend = createLocalFileBackend({ storeDir });
|
|
143
|
+
const plain = createLocalAuthService({ ...localServiceOptions(), backend: fileBackend });
|
|
144
|
+
const robot = (await plain.register({ email: "mercbot@example.com", password: "correct horse" })).actor;
|
|
145
|
+
const anna = (await plain.register({ email: "anna@example.com", password: "correct horse" })).actor;
|
|
146
|
+
const contact = (id, email, disabled) => ({ id, email, displayName: id, password: NO_PASSWORD, disabled });
|
|
147
|
+
const backend = withSharedEmails(fileBackend, [
|
|
148
|
+
contact("usr_twin_1", "twin@example.com", false), contact("usr_twin_2", "twin@example.com", false),
|
|
149
|
+
contact("usr_anna_old", "anna@example.com", true),
|
|
150
|
+
contact("usr_gone_1", "gone@example.com", true), contact("usr_gone_2", "gone@example.com", true)
|
|
151
|
+
]);
|
|
152
|
+
const service = createLocalAuthService({ ...localServiceOptions(), backend });
|
|
153
|
+
const { key, record } = createServiceKeyRecord({ userId: robot.providerUserId });
|
|
154
|
+
await fileBackend.withTransaction((tx) => tx.sessions.create(record));
|
|
155
|
+
|
|
156
|
+
assertRefused(await service.authenticateRequest(call(key, "Twin@Example.com")), 403, "auth.serviceKey.actAsAmbiguous",
|
|
157
|
+
/More than one user has the email "Twin@Example.com".*by its id/u);
|
|
158
|
+
const byId = await service.authenticateRequest(call(key, "usr_twin_2"));
|
|
159
|
+
assert.equal(byId.refusal?.code, undefined, "each twin may still be acted as by id");
|
|
160
|
+
const one = await service.authenticateRequest(call(key, "anna@example.com"));
|
|
161
|
+
assert.equal(one.actor.providerUserId, anna.providerUserId, "a disabled account with the same email does not count");
|
|
162
|
+
assertRefused(await service.authenticateRequest(call(key, "gone@example.com")), 403, "auth.serviceKey.actAsInactive", /disabled/u);
|
|
163
|
+
|
|
164
|
+
const before = createLocalAuthService({ ...localServiceOptions(), backend: { ...fileBackend,
|
|
165
|
+
withTransaction: (work) => fileBackend.withTransaction((tx) => work({ ...tx, users: { ...tx.users, findAllByEmail: undefined } })) } });
|
|
166
|
+
await assert.rejects(before.authenticateRequest(call(key, "anna@example.com")), /users\.findAllByEmail\(email\).*add it to the local auth backend/u,
|
|
167
|
+
"a backend without the lookup fails naming its fix");
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test("the file backend answers every account with an email, and none for an email no one has", async (t) => {
|
|
171
|
+
const { backend, anna } = await startService(t);
|
|
172
|
+
const found = await backend.withTransaction((tx) => tx.users.findAllByEmail("anna@example.com"));
|
|
173
|
+
assert.deepEqual(found.map((user) => user.id), [anna.providerUserId]);
|
|
174
|
+
assert.deepEqual(await backend.withTransaction((tx) => tx.users.findAllByEmail("nobody@example.com")), []);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
test("a key's lifetime is whole days, at most ten years, and it names its user", () => {
|
|
178
|
+
for (const options of [{ userId: "" }, { userId: "usr_a", days: 0 }, { userId: "usr_a", days: 3651 }, { userId: "usr_a", days: 1.5 }]) {
|
|
179
|
+
assert.throws(() => createServiceKeyRecord(options), /createServiceKeyRecord/u, JSON.stringify(options));
|
|
180
|
+
}
|
|
181
|
+
const now = Date.UTC(2026, 10, 24);
|
|
182
|
+
const { key, record } = createServiceKeyRecord({ userId: "usr_a", now });
|
|
183
|
+
assert.match(key, /^svk_[A-Za-z0-9_-]{43}$/u);
|
|
184
|
+
assert.equal(record.createdAt, new Date(now).toISOString());
|
|
185
|
+
assert.equal(record.expiresAt, new Date(now + 365 * 86_400_000).toISOString(), "a year unless it says");
|
|
186
|
+
});
|
|
@@ -21,6 +21,7 @@ const PROOF_REQUIRED = Object.freeze({ status: 400, code: "auth.local.secondFact
|
|
|
21
21
|
const CODE_INVALID = Object.freeze({ status: 400, code: "auth.local.secondFactor.codeInvalid" });
|
|
22
22
|
const CODE_USED = Object.freeze({ status: 400, code: "auth.local.secondFactor.codeUsed" });
|
|
23
23
|
const RECOVERY_CODE_INVALID = Object.freeze({ status: 400, code: "auth.local.secondFactor.recoveryCodeInvalid" });
|
|
24
|
+
const ACCOUNT_NOT_FOUND = Object.freeze({ status: 404, code: "auth.local.secondFactor.accountNotFound" });
|
|
24
25
|
const NOTHING_PROVED = Object.freeze({ enrolled: false, enrolledAt: null, recoveryCodesLeft: 0, verifiedAt: null });
|
|
25
26
|
|
|
26
27
|
/** Checks a refusal while the account waits after wrong codes: the minutes, the seconds and Retry-After. */
|
|
@@ -178,6 +179,12 @@ async function exerciseSecondFactor(t, { service, events, storedText }) {
|
|
|
178
179
|
await assert.rejects(service.removeSecondFactor(ada(), { recoveryCode: bobConfirmed.recoveryCodes[0], userId: bobId }),
|
|
179
180
|
RECOVERY_CODE_INVALID);
|
|
180
181
|
assert.equal((await service.verifySecondFactor(bob(), { recoveryCode: bobConfirmed.recoveryCodes[0] })).recoveryCodesLeft, 9);
|
|
182
|
+
// The application checks Bob's recovery code for him, with no session of his: it is used up for his sessions too.
|
|
183
|
+
const checkedAt = now();
|
|
184
|
+
assert.equal((await service.verifySecondFactorOf({ userId: bobId, proof: { recoveryCode: bobConfirmed.recoveryCodes[1] } }))
|
|
185
|
+
.recoveryCodesLeft, 8);
|
|
186
|
+
await assert.rejects(service.verifySecondFactor(bob(), { recoveryCode: bobConfirmed.recoveryCodes[1] }), RECOVERY_CODE_INVALID);
|
|
187
|
+
await assert.rejects(service.verifySecondFactorOf({ userId: "usr_missing", proof: { code: "123456" } }), ACCOUNT_NOT_FOUND);
|
|
181
188
|
assert.equal((await service.getSecondFactorStatus(ada())).recoveryCodesLeft, 8);
|
|
182
189
|
|
|
183
190
|
// Ada's next proof forgets that failure. Then five wrong codes make the account wait, even for a right code or a
|
|
@@ -243,15 +250,20 @@ async function exerciseSecondFactor(t, { service, events, storedText }) {
|
|
|
243
250
|
"setupConfirmed",
|
|
244
251
|
"failed:recoveryCodeInvalid",
|
|
245
252
|
"verified:recoveryCode",
|
|
253
|
+
"verified:recoveryCode",
|
|
254
|
+
"failed:recoveryCodeInvalid",
|
|
246
255
|
"verified:code",
|
|
247
256
|
"reset"
|
|
248
257
|
]);
|
|
258
|
+
assert.deepEqual(events.filter((event) => event.via), [
|
|
259
|
+
{ type: "verified", userId: bobId, ip: "", via: "application", at: checkedAt, method: "recoveryCode", recoveryCodesLeft: 8 }
|
|
260
|
+
]);
|
|
249
261
|
assert.deepEqual(events.find((event) => event.type === "reset"), { type: "reset", userId: bobId, ip: "", at: now(), byUserId: adaId });
|
|
250
262
|
assert.deepEqual(events.find((event) => event.type === "removed"), { type: "removed", userId: adaId, ip: IP, at: now(), method: "code" });
|
|
251
263
|
const adaFailures = events.filter((event) => event.userId === adaId && event.type === "failed").map((event) => event.reason);
|
|
252
264
|
assert.equal(adaFailures.filter((reason) => reason === "locked").length, 4);
|
|
253
265
|
for (const event of events) {
|
|
254
|
-
assert.equal(event.ip === IP || event.type === "reset", true, `${event.type} names where it came from`);
|
|
266
|
+
assert.equal(event.ip === IP || event.type === "reset" || event.via === "application", true, `${event.type} names where it came from`);
|
|
255
267
|
}
|
|
256
268
|
const everyEvent = JSON.stringify(events);
|
|
257
269
|
for (const shown of [setup.secret, secret, bobSetup.secret, ...confirmed.recoveryCodes, ...replaced.recoveryCodes]) {
|