@jskit-ai/auth-provider-local-core 0.2.24 → 0.2.26
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 +4 -0
- package/locales/en.json +10 -0
- package/package.json +8 -6
- package/src/server/lib/accounts.js +5 -3
- package/src/server/lib/config.js +43 -9
- package/src/server/lib/emailConfirmation.js +37 -1
- package/src/server/lib/fileBackend.js +72 -3
- package/src/server/lib/fileRecords.js +56 -3
- package/src/server/lib/index.js +1 -0
- package/src/server/lib/secondFactor.js +408 -0
- package/src/server/lib/secondFactorCrypto.js +239 -0
- package/src/server/lib/securityStatus.js +11 -3
- package/src/server/lib/service.js +38 -4
- package/src/server/lib/sessions.js +7 -1
- package/src/server/lib/signInThrottle.js +34 -11
- package/src/server/providers/AuthLocalProvider.js +31 -5
- package/src/server/types.js +72 -3
- package/test/codedTexts.test.js +28 -0
- package/test/providerRuntime.test.js +151 -0
- package/test/secondFactor.test.js +128 -0
- package/test-support/localService.js +3 -1
- package/test-support/secondFactorScenario.js +262 -0
|
@@ -0,0 +1,128 @@
|
|
|
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 { resolveLocalAuthConfig } from "../src/server/lib/config.js";
|
|
7
|
+
import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
8
|
+
import { __testables, deriveSecondFactorKeys, openSecret, sealSecret } from "../src/server/lib/secondFactorCrypto.js";
|
|
9
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
10
|
+
import { sessionCookies } from "../test-support/oauthHarness.js";
|
|
11
|
+
import {
|
|
12
|
+
SCENARIO_START,
|
|
13
|
+
SECOND_FACTOR_KEY,
|
|
14
|
+
codeAt,
|
|
15
|
+
exerciseSecondFactor,
|
|
16
|
+
secondFactorServiceOptions
|
|
17
|
+
} from "../test-support/secondFactorScenario.js";
|
|
18
|
+
|
|
19
|
+
const { fromBase32, stepAt, toBase32, totpCodeAt } = __testables;
|
|
20
|
+
|
|
21
|
+
async function storeDirFor(t) {
|
|
22
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-second-factor-"));
|
|
23
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
24
|
+
return storeDir;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
test("authenticator codes are RFC 6238's: its test vectors, as six-digit codes", () => {
|
|
28
|
+
const secret = toBase32(Buffer.from("12345678901234567890"));
|
|
29
|
+
assert.equal(secret, "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
|
|
30
|
+
assert.deepEqual(fromBase32(secret), Buffer.from("12345678901234567890"));
|
|
31
|
+
for (const [seconds, code] of [
|
|
32
|
+
[59, "287082"],
|
|
33
|
+
[1111111109, "081804"],
|
|
34
|
+
[1111111111, "050471"],
|
|
35
|
+
[1234567890, "005924"],
|
|
36
|
+
[2000000000, "279037"],
|
|
37
|
+
[20000000000, "353130"]
|
|
38
|
+
]) {
|
|
39
|
+
assert.equal(totpCodeAt(secret, stepAt(seconds * 1000)), code, `T = ${seconds}`);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("a sealed secret opens only for its own account and with the key that sealed it", () => {
|
|
44
|
+
const keys = deriveSecondFactorKeys(SECOND_FACTOR_KEY);
|
|
45
|
+
const sealed = sealSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
|
|
46
|
+
assert.match(sealed, /^v1\.[\w-]+\.[\w-]+\.[\w-]+$/u);
|
|
47
|
+
assert.equal(sealed.includes("GEZDGNBV"), false);
|
|
48
|
+
assert.notEqual(sealSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"), sealed, "each seal has its own nonce");
|
|
49
|
+
assert.equal(openSecret(keys, "usr_ada", sealed), "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
|
|
50
|
+
assert.throws(() => openSecret(keys, "usr_bob", sealed), /does not open with AUTH_LOCAL_SECOND_FACTOR_KEY/u);
|
|
51
|
+
assert.throws(() => openSecret(deriveSecondFactorKeys(`${SECOND_FACTOR_KEY}!`), "usr_ada", sealed), /does not open/u);
|
|
52
|
+
assert.throws(() => openSecret(keys, "usr_ada", "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"), /is not a sealed secret/u);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("an authenticator sets up, proves sessions, refuses wrong, used and expired codes, waits, and resets (file backend)", async (t) => {
|
|
56
|
+
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
57
|
+
const storeDir = await storeDirFor(t);
|
|
58
|
+
const { events, options } = secondFactorServiceOptions();
|
|
59
|
+
const service = createLocalAuthService({ ...options, backend: createLocalFileBackend({ storeDir }) });
|
|
60
|
+
await exerciseSecondFactor(t, {
|
|
61
|
+
service,
|
|
62
|
+
events,
|
|
63
|
+
async storedText() {
|
|
64
|
+
const files = await fs.readdir(storeDir);
|
|
65
|
+
return (await Promise.all(files.map((file) => fs.readFile(path.join(storeDir, file), "utf8")))).join("\n");
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("the file store keeps a factor and its session's proof across restarts, and another key cannot open it", async (t) => {
|
|
71
|
+
t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
|
|
72
|
+
const storeDir = await storeDirFor(t);
|
|
73
|
+
const start = (env = {}) => createLocalAuthService({ ...secondFactorServiceOptions({ env }).options, backend: createLocalFileBackend({ storeDir }) });
|
|
74
|
+
const first = start();
|
|
75
|
+
await first.register({ email: "ada@example.com", password: "correct horse battery staple" });
|
|
76
|
+
const cookies = sessionCookies((await first.login({ email: "ada@example.com", password: "correct horse battery staple" })).session);
|
|
77
|
+
const { secret } = await first.startSecondFactorSetup({ cookies });
|
|
78
|
+
const { recoveryCodes } = await first.confirmSecondFactorSetup({ cookies }, { code: codeAt(secret) });
|
|
79
|
+
|
|
80
|
+
const restarted = start();
|
|
81
|
+
assert.deepEqual(await restarted.getSecondFactorStatus({ cookies }), {
|
|
82
|
+
enrolled: true,
|
|
83
|
+
enrolledAt: new Date(SCENARIO_START).toISOString(),
|
|
84
|
+
recoveryCodesLeft: 10,
|
|
85
|
+
verifiedAt: new Date(SCENARIO_START).toISOString()
|
|
86
|
+
});
|
|
87
|
+
assert.equal((await restarted.verifySecondFactor({ cookies }, { recoveryCode: recoveryCodes[0] })).recoveryCodesLeft, 9);
|
|
88
|
+
|
|
89
|
+
t.mock.timers.tick(30_000);
|
|
90
|
+
const rekeyed = start({ AUTH_LOCAL_SECOND_FACTOR_KEY: `another key, also 32 characters or more` });
|
|
91
|
+
await assert.rejects(rekeyed.verifySecondFactor({ cookies }, { code: codeAt(secret) }), (error) => {
|
|
92
|
+
assert.equal(error.status, undefined, "a key that cannot open the secret is a server failure, not a refusal");
|
|
93
|
+
assert.match(error.message, /does not open with AUTH_LOCAL_SECOND_FACTOR_KEY/u);
|
|
94
|
+
return true;
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("a production server has a second factor only with its key, at least 32 characters, and APP_PUBLIC_URL", async (t) => {
|
|
99
|
+
const production = { NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "", AUTH_LOCAL_SECOND_FACTOR_KEY: "" };
|
|
100
|
+
const service = createLocalAuthService({
|
|
101
|
+
...localServiceOptions({ env: production }),
|
|
102
|
+
backend: createLocalFileBackend({ storeDir: await storeDirFor(t) })
|
|
103
|
+
});
|
|
104
|
+
assert.equal(service.getCapabilities().features.secondFactor, false);
|
|
105
|
+
assert.throws(() => service.getSecondFactorStatus({ cookies: {} }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
106
|
+
assert.throws(() => service.listSecondFactors({ userIds: [] }), { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
|
|
107
|
+
|
|
108
|
+
const resolve = (env) => resolveLocalAuthConfig({
|
|
109
|
+
appRoot: os.tmpdir(),
|
|
110
|
+
env: {
|
|
111
|
+
AUTH_LOCAL_SESSION_SECRET: "test-session-secret",
|
|
112
|
+
AUTH_LOCAL_EMAIL_CONFIRMATION: "false",
|
|
113
|
+
APP_PUBLIC_URL: "https://console.example.com",
|
|
114
|
+
...env
|
|
115
|
+
},
|
|
116
|
+
fileBackend: false,
|
|
117
|
+
emailRecovery: false
|
|
118
|
+
});
|
|
119
|
+
assert.equal(resolve({ NODE_ENV: "production" }).secondFactorKey, "");
|
|
120
|
+
assert.equal(resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY }).secondFactorKey, SECOND_FACTOR_KEY);
|
|
121
|
+
assert.throws(() => resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: "too short" }), /at least 32 characters/u);
|
|
122
|
+
assert.throws(() => resolve({ NODE_ENV: "production", AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY, APP_PUBLIC_URL: "" }),
|
|
123
|
+
/APP_PUBLIC_URL is required when AUTH_LOCAL_SECOND_FACTOR_KEY is set/u);
|
|
124
|
+
// Outside production the session secret stands in for the key.
|
|
125
|
+
assert.equal(resolve({ NODE_ENV: "development" }).secondFactorKey, "test-session-secret");
|
|
126
|
+
assert.equal(createLocalAuthService({ ...localServiceOptions(), backend: createLocalFileBackend({ storeDir: await storeDirFor(t) }) })
|
|
127
|
+
.getCapabilities().features.secondFactor, true);
|
|
128
|
+
});
|
|
@@ -6,6 +6,7 @@ import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
|
|
|
6
6
|
import { createLoggedConfirmationSender } from "../src/server/lib/emailConfirmation.js";
|
|
7
7
|
import { createLoggedRecoverySender } from "../src/server/lib/passwordFlows.js";
|
|
8
8
|
import { scryptPasswordStrategy } from "../src/server/lib/passwords.js";
|
|
9
|
+
import { createLoggedSecondFactorEvents } from "../src/server/lib/secondFactor.js";
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* What a test passes to createLocalAuthService besides its backend: a complete
|
|
@@ -39,7 +40,8 @@ function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmatio
|
|
|
39
40
|
passwordStrategy: scryptPasswordStrategy,
|
|
40
41
|
profileProjector: noAppProfiles,
|
|
41
42
|
recoverySender: createLoggedRecoverySender(silentLogger),
|
|
42
|
-
confirmationSender: createLoggedConfirmationSender(silentLogger)
|
|
43
|
+
confirmationSender: createLoggedConfirmationSender(silentLogger),
|
|
44
|
+
secondFactorEvents: createLoggedSecondFactorEvents(silentLogger)
|
|
43
45
|
};
|
|
44
46
|
}
|
|
45
47
|
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { AUTH_TEXTS } from "@jskit-ai/auth-core/server/authTexts";
|
|
3
|
+
import { __testables } from "../src/server/lib/secondFactorCrypto.js";
|
|
4
|
+
import { localServiceOptions } from "./localService.js";
|
|
5
|
+
import { sessionCookies } from "./oauthHarness.js";
|
|
6
|
+
|
|
7
|
+
const { stepAt, totpCodeAt } = __testables;
|
|
8
|
+
const PASSWORD = "correct horse battery staple";
|
|
9
|
+
const IP = "203.0.113.7";
|
|
10
|
+
// A key as an application supplies it in AUTH_LOCAL_SECOND_FACTOR_KEY.
|
|
11
|
+
const SECOND_FACTOR_KEY = "test second factor key, 32 characters or more";
|
|
12
|
+
// The start of a 30-second step, so the scenario's whole-second ticks land where it expects.
|
|
13
|
+
const SCENARIO_START = Date.parse("2026-11-13T10:00:00.000Z");
|
|
14
|
+
const RECOVERY_CODE = /^[0-9a-hjkmnp-tv-z]{5}-[0-9a-hjkmnp-tv-z]{5}$/u;
|
|
15
|
+
|
|
16
|
+
const SESSION_REQUIRED = AUTH_TEXTS.sessionRequired;
|
|
17
|
+
const NOT_SET_UP = Object.freeze({ status: 409, code: "auth.local.secondFactor.notSetUp" });
|
|
18
|
+
const ALREADY_SET_UP = Object.freeze({ status: 409, code: "auth.local.secondFactor.alreadySetUp" });
|
|
19
|
+
const SETUP_NOT_STARTED = Object.freeze({ status: 409, code: "auth.local.secondFactor.setupNotStarted" });
|
|
20
|
+
const PROOF_REQUIRED = Object.freeze({ status: 400, code: "auth.local.secondFactor.proofRequired" });
|
|
21
|
+
const CODE_INVALID = Object.freeze({ status: 400, code: "auth.local.secondFactor.codeInvalid" });
|
|
22
|
+
const CODE_USED = Object.freeze({ status: 400, code: "auth.local.secondFactor.codeUsed" });
|
|
23
|
+
const RECOVERY_CODE_INVALID = Object.freeze({ status: 400, code: "auth.local.secondFactor.recoveryCodeInvalid" });
|
|
24
|
+
const NOTHING_PROVED = Object.freeze({ enrolled: false, enrolledAt: null, recoveryCodesLeft: 0, verifiedAt: null });
|
|
25
|
+
|
|
26
|
+
/** Checks a refusal while the account waits after wrong codes: the minutes, the seconds and Retry-After. */
|
|
27
|
+
function lockedFor(seconds) {
|
|
28
|
+
return (error) => {
|
|
29
|
+
assert.equal(error.status, 429);
|
|
30
|
+
assert.equal(error.code, "auth.local.secondFactor.locked");
|
|
31
|
+
assert.deepEqual(error.params, { count: Math.ceil(seconds / 60), retryAfterSeconds: seconds });
|
|
32
|
+
assert.equal(error.headers["retry-after"], String(seconds));
|
|
33
|
+
return true;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const now = () => new Date().toISOString();
|
|
38
|
+
|
|
39
|
+
/** The code the authenticator shows now, or `offset` steps from now. */
|
|
40
|
+
function codeAt(secret, offset = 0) {
|
|
41
|
+
return totpCodeAt(secret, stepAt(Date.now()) + offset);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Six digits that are none of the codes accepted now. */
|
|
45
|
+
function wrongCode(secret) {
|
|
46
|
+
const accepted = new Set([-1, 0, 1].map((offset) => codeAt(secret, offset)));
|
|
47
|
+
let guess = 0;
|
|
48
|
+
while (accepted.has(String(guess).padStart(6, "0"))) {
|
|
49
|
+
guess += 1;
|
|
50
|
+
}
|
|
51
|
+
return String(guess).padStart(6, "0");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Local auth's options for a second factor scenario: the test settings with an
|
|
56
|
+
* application's key, and a recorder of the events.
|
|
57
|
+
*/
|
|
58
|
+
function secondFactorServiceOptions({ env = {} } = {}) {
|
|
59
|
+
const events = [];
|
|
60
|
+
const options = localServiceOptions({ env: { AUTH_LOCAL_SECOND_FACTOR_KEY: SECOND_FACTOR_KEY, ...env } });
|
|
61
|
+
return {
|
|
62
|
+
events,
|
|
63
|
+
options: {
|
|
64
|
+
...options,
|
|
65
|
+
async secondFactorEvents(event) {
|
|
66
|
+
events.push(event);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Signs the account in; each call of the answer is a new request from that browser. */
|
|
73
|
+
async function signIn(service, email) {
|
|
74
|
+
const cookies = sessionCookies((await service.login({ email, password: PASSWORD })).session);
|
|
75
|
+
return () => ({ cookies, ip: IP });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Local auth's second factor against any backend, from setup to removal and
|
|
80
|
+
* the application's reset: run with Date mocked through `t.mock.timers`, from
|
|
81
|
+
* the start of a 30-second step (SCENARIO_START).
|
|
82
|
+
* @param {import("node:test").TestContext} t
|
|
83
|
+
* @param {object} input
|
|
84
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthService} input.service
|
|
85
|
+
* @param {object[]} input.events The events the service's secondFactorEvents recorded.
|
|
86
|
+
* @param {() => Promise<string>} input.storedText Everything the backend keeps of the second factors, as text.
|
|
87
|
+
*/
|
|
88
|
+
async function exerciseSecondFactor(t, { service, events, storedText }) {
|
|
89
|
+
await service.register({ email: "ada@example.com", password: PASSWORD, displayName: "Ada" });
|
|
90
|
+
await service.register({ email: "bob@example.com", password: PASSWORD, displayName: "Bob" });
|
|
91
|
+
const ada = await signIn(service, "ada@example.com");
|
|
92
|
+
const adaPhone = await signIn(service, "ada@example.com");
|
|
93
|
+
const bob = await signIn(service, "bob@example.com");
|
|
94
|
+
const adaId = (await service.authenticateRequest(ada())).actor.providerUserId;
|
|
95
|
+
const bobId = (await service.authenticateRequest(bob())).actor.providerUserId;
|
|
96
|
+
|
|
97
|
+
// Nothing is set up yet, and a signed-out request works with no one's factor.
|
|
98
|
+
assert.deepEqual(await service.getSecondFactorStatus(ada()), NOTHING_PROVED);
|
|
99
|
+
await assert.rejects(service.getSecondFactorStatus({ cookies: {}, ip: IP }), SESSION_REQUIRED);
|
|
100
|
+
await assert.rejects(service.startSecondFactorSetup({ cookies: {}, ip: IP }), SESSION_REQUIRED);
|
|
101
|
+
await assert.rejects(service.verifySecondFactor({ cookies: {}, ip: IP }, { code: "123456" }), SESSION_REQUIRED);
|
|
102
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: "123456" }), NOT_SET_UP);
|
|
103
|
+
await assert.rejects(service.confirmSecondFactorSetup(ada(), { code: "123456" }), SETUP_NOT_STARTED);
|
|
104
|
+
|
|
105
|
+
// The secret is shown once, as text and in the address an authenticator app reads from a QR code.
|
|
106
|
+
const setup = await service.startSecondFactorSetup(ada());
|
|
107
|
+
assert.match(setup.secret, /^[A-Z2-7]{32}$/u);
|
|
108
|
+
assert.deepEqual(setup, {
|
|
109
|
+
secret: setup.secret,
|
|
110
|
+
otpauthUrl: `otpauth://totp/localhost%3A5173:ada%40example.com?secret=${setup.secret}` +
|
|
111
|
+
"&issuer=localhost%3A5173&algorithm=SHA1&digits=6&period=30",
|
|
112
|
+
issuer: "localhost:5173",
|
|
113
|
+
accountName: "ada@example.com"
|
|
114
|
+
});
|
|
115
|
+
assert.equal((await service.getSecondFactorStatus(ada())).enrolled, false, "a started setup is no factor yet");
|
|
116
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: codeAt(setup.secret) }), NOT_SET_UP);
|
|
117
|
+
const restarted = await service.startSecondFactorSetup(ada());
|
|
118
|
+
assert.notEqual(restarted.secret, setup.secret, "starting again replaces the setup nobody confirmed");
|
|
119
|
+
await assert.rejects(service.confirmSecondFactorSetup(ada(), { code: wrongCode(restarted.secret) }), CODE_INVALID);
|
|
120
|
+
|
|
121
|
+
// The first code confirms it and answers the recovery codes, once; it proves the second factor of that session only.
|
|
122
|
+
const secret = restarted.secret;
|
|
123
|
+
const confirmed = await service.confirmSecondFactorSetup(ada(), { code: codeAt(secret) });
|
|
124
|
+
assert.equal(confirmed.verifiedAt, now());
|
|
125
|
+
assert.equal(confirmed.recoveryCodes.length, 10);
|
|
126
|
+
assert.equal(new Set(confirmed.recoveryCodes).size, 10);
|
|
127
|
+
for (const code of confirmed.recoveryCodes) {
|
|
128
|
+
assert.match(code, RECOVERY_CODE);
|
|
129
|
+
}
|
|
130
|
+
const enrolledAt = now();
|
|
131
|
+
assert.deepEqual(await service.getSecondFactorStatus(ada()), { enrolled: true, enrolledAt, recoveryCodesLeft: 10, verifiedAt: enrolledAt });
|
|
132
|
+
assert.equal((await service.getSecondFactorStatus(adaPhone())).verifiedAt, null, "the person's other session has not proved it");
|
|
133
|
+
await assert.rejects(service.startSecondFactorSetup(ada()), ALREADY_SET_UP);
|
|
134
|
+
await assert.rejects(service.confirmSecondFactorSetup(ada(), { code: codeAt(secret) }), ALREADY_SET_UP);
|
|
135
|
+
|
|
136
|
+
// A code is accepted once: the first code again, or the one before it, is refused.
|
|
137
|
+
await assert.rejects(service.verifySecondFactor(adaPhone(), { code: codeAt(secret) }), CODE_USED);
|
|
138
|
+
await assert.rejects(service.verifySecondFactor(adaPhone(), { code: codeAt(secret, -1) }), CODE_USED);
|
|
139
|
+
|
|
140
|
+
// The next step's code is accepted, typed as people type it.
|
|
141
|
+
t.mock.timers.tick(30_000);
|
|
142
|
+
const typed = codeAt(secret);
|
|
143
|
+
assert.deepEqual(await service.verifySecondFactor(adaPhone(), { code: ` ${typed.slice(0, 3)} ${typed.slice(3)} ` }), {
|
|
144
|
+
verifiedAt: now(),
|
|
145
|
+
method: "code",
|
|
146
|
+
recoveryCodesLeft: 10
|
|
147
|
+
});
|
|
148
|
+
assert.equal((await service.getSecondFactorStatus(adaPhone())).verifiedAt, now());
|
|
149
|
+
assert.equal((await service.getSecondFactorStatus(ada())).verifiedAt, enrolledAt, "each session keeps its own proof");
|
|
150
|
+
|
|
151
|
+
// A code two steps old has expired, one two steps ahead is not shown yet, and neither is right.
|
|
152
|
+
t.mock.timers.tick(30_000);
|
|
153
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: codeAt(secret, -2) }), CODE_INVALID);
|
|
154
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: codeAt(secret, 2) }), CODE_INVALID);
|
|
155
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: "12345" }), CODE_INVALID);
|
|
156
|
+
// A proof is a code or a recovery code, never both or neither, and a missing one counts no attempt.
|
|
157
|
+
await assert.rejects(service.verifySecondFactor(ada(), {}), PROOF_REQUIRED);
|
|
158
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: codeAt(secret), recoveryCode: confirmed.recoveryCodes[0] }), PROOF_REQUIRED);
|
|
159
|
+
assert.equal((await service.verifySecondFactor(ada(), { code: codeAt(secret) })).method, "code");
|
|
160
|
+
|
|
161
|
+
// A recovery code proves it once, however it is typed.
|
|
162
|
+
const [firstRecovery, secondRecovery] = confirmed.recoveryCodes;
|
|
163
|
+
assert.deepEqual(await service.verifySecondFactor(adaPhone(), { recoveryCode: ` ${firstRecovery.toUpperCase()} ` }), {
|
|
164
|
+
verifiedAt: now(),
|
|
165
|
+
method: "recoveryCode",
|
|
166
|
+
recoveryCodesLeft: 9
|
|
167
|
+
});
|
|
168
|
+
await assert.rejects(service.verifySecondFactor(adaPhone(), { recoveryCode: firstRecovery }), RECOVERY_CODE_INVALID);
|
|
169
|
+
await assert.rejects(service.verifySecondFactor(adaPhone(), { recoveryCode: "not a code" }), RECOVERY_CODE_INVALID);
|
|
170
|
+
assert.equal((await service.verifySecondFactor(adaPhone(), { recoveryCode: secondRecovery })).recoveryCodesLeft, 8);
|
|
171
|
+
|
|
172
|
+
// Bob proves nothing with Ada's factor: with none of his own, then with his own, and naming hers changes nothing.
|
|
173
|
+
await assert.rejects(service.verifySecondFactor(bob(), { recoveryCode: confirmed.recoveryCodes[2] }), NOT_SET_UP);
|
|
174
|
+
const bobSetup = await service.startSecondFactorSetup(bob());
|
|
175
|
+
const bobConfirmed = await service.confirmSecondFactorSetup(bob(), { code: codeAt(bobSetup.secret) });
|
|
176
|
+
const bobEnrolledAt = now();
|
|
177
|
+
await assert.rejects(service.verifySecondFactor(bob(), { recoveryCode: confirmed.recoveryCodes[2] }), RECOVERY_CODE_INVALID);
|
|
178
|
+
await assert.rejects(service.removeSecondFactor(ada(), { recoveryCode: bobConfirmed.recoveryCodes[0], userId: bobId }),
|
|
179
|
+
RECOVERY_CODE_INVALID);
|
|
180
|
+
assert.equal((await service.verifySecondFactor(bob(), { recoveryCode: bobConfirmed.recoveryCodes[0] })).recoveryCodesLeft, 9);
|
|
181
|
+
assert.equal((await service.getSecondFactorStatus(ada())).recoveryCodesLeft, 8);
|
|
182
|
+
|
|
183
|
+
// Ada's next proof forgets that failure. Then five wrong codes make the account wait, even for a right code or a
|
|
184
|
+
// recovery code, and the next wrong one doubles the wait.
|
|
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 < 5; attempt += 1) {
|
|
188
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: wrongCode(secret) }), CODE_INVALID);
|
|
189
|
+
}
|
|
190
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: codeAt(secret) }), lockedFor(30));
|
|
191
|
+
await assert.rejects(service.verifySecondFactor(adaPhone(), { recoveryCode: confirmed.recoveryCodes[3] }), lockedFor(30));
|
|
192
|
+
await assert.rejects(service.removeSecondFactor(ada(), { code: codeAt(secret) }), lockedFor(30));
|
|
193
|
+
assert.equal((await service.verifySecondFactor(bob(), { code: codeAt(bobSetup.secret) })).method, "code", "Bob's attempts count apart");
|
|
194
|
+
t.mock.timers.tick(30_000);
|
|
195
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: wrongCode(secret) }), CODE_INVALID);
|
|
196
|
+
await assert.rejects(service.verifySecondFactor(ada(), { code: codeAt(secret) }), lockedFor(60));
|
|
197
|
+
// A code after the wait is accepted and forgets the failures.
|
|
198
|
+
t.mock.timers.tick(60_000);
|
|
199
|
+
assert.equal((await service.verifySecondFactor(ada(), { code: codeAt(secret) })).method, "code");
|
|
200
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
201
|
+
await assert.rejects(service.verifySecondFactor(ada(), { recoveryCode: "abcde-fghjk" }), RECOVERY_CODE_INVALID);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// New recovery codes replace every unused one.
|
|
205
|
+
t.mock.timers.tick(30_000);
|
|
206
|
+
const replaced = await service.replaceSecondFactorRecoveryCodes(ada(), { code: codeAt(secret) });
|
|
207
|
+
assert.equal(replaced.verifiedAt, now());
|
|
208
|
+
assert.equal(replaced.recoveryCodes.length, 10);
|
|
209
|
+
await assert.rejects(service.verifySecondFactor(ada(), { recoveryCode: confirmed.recoveryCodes[4] }), RECOVERY_CODE_INVALID);
|
|
210
|
+
assert.equal((await service.verifySecondFactor(ada(), { recoveryCode: replaced.recoveryCodes[0] })).recoveryCodesLeft, 9);
|
|
211
|
+
|
|
212
|
+
// The store keeps the secret sealed and the recovery codes as keyed hashes.
|
|
213
|
+
const stored = await storedText();
|
|
214
|
+
assert.equal(stored.includes(secret), false, "the authenticator secret is not stored as it was shown");
|
|
215
|
+
for (const code of [...replaced.recoveryCodes, ...bobConfirmed.recoveryCodes]) {
|
|
216
|
+
assert.equal(stored.includes(code) || stored.includes(code.replace("-", "")), false, `recovery code ${code} is not stored`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Removing takes a proof; afterwards every session of the person must prove a second factor again, and cannot.
|
|
220
|
+
await assert.rejects(service.removeSecondFactor(adaPhone(), { code: wrongCode(secret) }), CODE_INVALID);
|
|
221
|
+
t.mock.timers.tick(30_000);
|
|
222
|
+
assert.deepEqual(await service.removeSecondFactor(adaPhone(), { code: codeAt(secret) }), { ok: true });
|
|
223
|
+
assert.deepEqual(await service.getSecondFactorStatus(ada()), NOTHING_PROVED);
|
|
224
|
+
assert.deepEqual(await service.getSecondFactorStatus(adaPhone()), NOTHING_PROVED);
|
|
225
|
+
await assert.rejects(service.verifySecondFactor(ada(), { recoveryCode: replaced.recoveryCodes[1] }), NOT_SET_UP);
|
|
226
|
+
|
|
227
|
+
// The application lists the accounts with an authenticator (a started setup is none) and resets Bob's.
|
|
228
|
+
await service.startSecondFactorSetup(ada());
|
|
229
|
+
assert.deepEqual(await service.listSecondFactors({ userIds: [adaId, bobId, "usr_missing"] }), [{ userId: bobId, enrolledAt: bobEnrolledAt }]);
|
|
230
|
+
assert.deepEqual(await service.listSecondFactors({ userIds: [] }), []);
|
|
231
|
+
await assert.rejects(service.listSecondFactors({ userIds: bobId }), TypeError);
|
|
232
|
+
await assert.rejects(service.resetSecondFactor({ userId: bobId }), TypeError);
|
|
233
|
+
assert.notEqual((await service.getSecondFactorStatus(bob())).verifiedAt, null);
|
|
234
|
+
assert.deepEqual(await service.resetSecondFactor({ userId: bobId, byUserId: adaId }), { reset: true });
|
|
235
|
+
assert.deepEqual(await service.resetSecondFactor({ userId: bobId, byUserId: adaId }), { reset: false });
|
|
236
|
+
assert.deepEqual(await service.getSecondFactorStatus(bob()), NOTHING_PROVED);
|
|
237
|
+
assert.deepEqual(await service.listSecondFactors({ userIds: [adaId, bobId] }), []);
|
|
238
|
+
|
|
239
|
+
// Each change and failed attempt is an event naming the account and where it came from, never a secret or a code.
|
|
240
|
+
const label = (event) => [event.type, event.reason || event.method].filter(Boolean).join(":");
|
|
241
|
+
assert.deepEqual(events.filter((event) => event.userId === bobId).map(label), [
|
|
242
|
+
"setupStarted",
|
|
243
|
+
"setupConfirmed",
|
|
244
|
+
"failed:recoveryCodeInvalid",
|
|
245
|
+
"verified:recoveryCode",
|
|
246
|
+
"verified:code",
|
|
247
|
+
"reset"
|
|
248
|
+
]);
|
|
249
|
+
assert.deepEqual(events.find((event) => event.type === "reset"), { type: "reset", userId: bobId, ip: "", at: now(), byUserId: adaId });
|
|
250
|
+
assert.deepEqual(events.find((event) => event.type === "removed"), { type: "removed", userId: adaId, ip: IP, at: now(), method: "code" });
|
|
251
|
+
const adaFailures = events.filter((event) => event.userId === adaId && event.type === "failed").map((event) => event.reason);
|
|
252
|
+
assert.equal(adaFailures.filter((reason) => reason === "locked").length, 4);
|
|
253
|
+
for (const event of events) {
|
|
254
|
+
assert.equal(event.ip === IP || event.type === "reset", true, `${event.type} names where it came from`);
|
|
255
|
+
}
|
|
256
|
+
const everyEvent = JSON.stringify(events);
|
|
257
|
+
for (const shown of [setup.secret, secret, bobSetup.secret, ...confirmed.recoveryCodes, ...replaced.recoveryCodes]) {
|
|
258
|
+
assert.equal(everyEvent.includes(shown), false);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export { SCENARIO_START, SECOND_FACTOR_KEY, codeAt, exerciseSecondFactor, secondFactorServiceOptions };
|