@jskit-ai/auth-web 0.2.33 → 0.2.34

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.
@@ -0,0 +1,219 @@
1
+ import assert from "node:assert/strict";
2
+ import process from "node:process";
3
+ import { after, before, test } from "node:test";
4
+ import { fileURLToPath } from "node:url";
5
+ import { chromium, expect } from "@playwright/test";
6
+ import { createChromiumLaunchOptions, startViteFixture, stopProcess } from "../../../tooling/testUtils/browserFixture.mjs";
7
+
8
+ const RUN = process.env.JSKIT_AUTH_WEB_BROWSER_INTEGRATION === "1";
9
+ const options = { skip: !RUN, timeout: 120_000 };
10
+ const PHONE = { width: 390, height: 844 };
11
+ const SESSION = {
12
+ authenticated: true,
13
+ csrfToken: "fixture-csrf",
14
+ username: "Ada Lovelace",
15
+ email: "ada@example.com",
16
+ permissions: [],
17
+ authCapabilities: { provider: { id: "local", label: "Local" }, features: { secondFactor: true } }
18
+ };
19
+ const NOT_ENROLLED = { enrolled: false, enrolledAt: null, recoveryCodesLeft: 0, verifiedAt: null };
20
+ const ENROLLED = {
21
+ enrolled: true,
22
+ enrolledAt: "2026-11-13T10:00:00.000Z",
23
+ recoveryCodesLeft: 10,
24
+ verifiedAt: "2026-11-13T10:00:00.000Z"
25
+ };
26
+ const SECRET = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
27
+ const RECOVERY_CODES = Array.from({ length: 10 }, (_, index) => `abcd${index}-efgh${index}`);
28
+ const REQUIRED = {
29
+ status: 403,
30
+ json: { error: "Confirm it's you with a code from your authenticator app.", code: "auth.secondFactor.required", params: { maxAgeSeconds: 300 } }
31
+ };
32
+
33
+ let runtime = null;
34
+ let browser = null;
35
+
36
+ before(async () => {
37
+ if (!RUN) return;
38
+ runtime = await startViteFixture({ fixtureRoot: fileURLToPath(new URL("../fixtures/sign-in/", import.meta.url)) });
39
+ browser = await chromium.launch(createChromiumLaunchOptions());
40
+ });
41
+
42
+ after(async () => {
43
+ await browser?.close();
44
+ await stopProcess(runtime);
45
+ });
46
+
47
+ function refused(status, code, message) {
48
+ return { status, json: { error: message, code, params: {} } };
49
+ }
50
+
51
+ /**
52
+ * A signed-in phone with the second-factor API behind it. `routes` answers "METHOD /path" with a list of answers, one
53
+ * per request, the last repeated; anything else under /api is a test failure.
54
+ */
55
+ async function openApp(routes) {
56
+ const page = await browser.newPage({ baseURL: runtime.baseURL, viewport: PHONE });
57
+ page.setDefaultTimeout(15_000);
58
+ page.setDefaultNavigationTimeout(60_000);
59
+ const api = { requests: [], unexpected: [], errors: [], page };
60
+ page.on("pageerror", (error) => api.errors.push(error.message));
61
+ await page.route("**/api/**", async (route) => {
62
+ const request = route.request();
63
+ const key = `${request.method()} ${new URL(request.url()).pathname}`;
64
+ if (key === "GET /api/session") {
65
+ await route.fulfill({ json: SESSION });
66
+ return;
67
+ }
68
+ api.requests.push({ key, body: request.postDataJSON() });
69
+ const answers = routes[key];
70
+ if (!answers) {
71
+ api.unexpected.push(key);
72
+ await route.fulfill({ status: 500, json: { error: `unexpected ${key}` } });
73
+ return;
74
+ }
75
+ await route.fulfill(answers.length > 1 ? answers.shift() : answers[0]);
76
+ });
77
+ return api;
78
+ }
79
+
80
+ function bodiesOf(api, key) {
81
+ return api.requests.filter((request) => request.key === key).map((request) => request.body);
82
+ }
83
+
84
+ function reports(page) {
85
+ return page.evaluate(() => window.authFixture.reports.map(({ message, severity, channel }) => ({ message, severity, channel })));
86
+ }
87
+
88
+ async function fitsTheScreen(page) {
89
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "nothing scrolls sideways");
90
+ }
91
+
92
+ async function finish(api) {
93
+ assert.deepEqual(api.unexpected, []);
94
+ assert.deepEqual(api.errors, []);
95
+ await api.page.close();
96
+ }
97
+
98
+ test("on a phone, setting up an authenticator shows its QR code and key, a wrong code beside the field, and the recovery codes once", options, async () => {
99
+ const api = await openApp({
100
+ "GET /api/second-factor": [refused(503, "", "Service unavailable."), { json: NOT_ENROLLED }, { json: ENROLLED }],
101
+ "POST /api/second-factor/setup": [{
102
+ json: { secret: SECRET, otpauthUrl: `otpauth://totp/Console:ada%40example.com?secret=${SECRET}&issuer=Console`, issuer: "Console", accountName: "ada@example.com" }
103
+ }],
104
+ "POST /api/second-factor/setup/confirm": [
105
+ refused(400, "auth.local.secondFactor.codeInvalid", "That code is not right. Enter the code your authenticator app shows now."),
106
+ { json: { recoveryCodes: RECOVERY_CODES, verifiedAt: "2026-11-13T10:00:00.000Z" } }
107
+ ]
108
+ });
109
+ const { page } = api;
110
+ await page.goto("/account/second-factor");
111
+
112
+ // A state that cannot load says so in the page, with a way to try again.
113
+ await expect(page.getByText("Could not load your authenticator settings.")).toBeVisible();
114
+ await page.getByRole("button", { name: "Retry" }).click();
115
+ await expect(page.getByText("No authenticator app is set up.", { exact: false })).toBeVisible();
116
+
117
+ await page.getByRole("button", { name: "Set up authenticator" }).click();
118
+ await expect(page.getByRole("img", { name: "QR code to add ada@example.com to an authenticator app" })).toBeVisible();
119
+ await expect(page.getByText("GEZD GNBV GY3T QOJQ GEZD GNBV GY3T QOJQ")).toBeVisible();
120
+ await expect(page.getByLabel("6-digit code")).toBeFocused();
121
+ await expect(page.getByRole("button", { name: "Use a recovery code" })).toHaveCount(0);
122
+ await fitsTheScreen(page);
123
+
124
+ // The keyboard alone confirms: a wrong code is refused beside the field and stays there to be corrected.
125
+ await page.keyboard.type("000000");
126
+ await page.keyboard.press("Enter");
127
+ await expect(page.getByText("That code is not right. Enter the code your authenticator app shows now.")).toBeVisible();
128
+ await expect(page.getByLabel("6-digit code")).toHaveValue("000000");
129
+ await page.getByLabel("6-digit code").fill("123456");
130
+ await page.keyboard.press("Enter");
131
+
132
+ const codesTitle = page.getByRole("heading", { name: "Save your recovery codes" });
133
+ await expect(codesTitle).toBeFocused();
134
+ await expect(page.getByRole("list", { name: "Recovery codes" }).getByRole("listitem")).toHaveText(RECOVERY_CODES);
135
+ await fitsTheScreen(page);
136
+ await page.getByRole("button", { name: "I've saved them" }).click();
137
+ await expect(page.getByText(/^Authenticator app set up on /u)).toBeFocused();
138
+ await expect(page.getByText("10 recovery codes left.")).toBeVisible();
139
+ await expect(page.getByText(RECOVERY_CODES[0])).toHaveCount(0);
140
+
141
+ assert.deepEqual(bodiesOf(api, "POST /api/second-factor/setup/confirm"), [{ code: "000000" }, { code: "123456" }]);
142
+ assert.deepEqual(await reports(page), []);
143
+ await finish(api);
144
+ });
145
+
146
+ test("removing the authenticator takes a code or a recovery code, shows a wait beside the field and reports a failed request", options, async () => {
147
+ const api = await openApp({
148
+ "GET /api/second-factor": [{ json: { ...ENROLLED, recoveryCodesLeft: 0 } }, { json: NOT_ENROLLED }],
149
+ "DELETE /api/second-factor": [
150
+ refused(429, "auth.local.secondFactor.locked", "Too many wrong codes. Try again in 1 minute."),
151
+ { status: 500, json: { error: "Internal server error." } },
152
+ { json: { ok: true } }
153
+ ]
154
+ });
155
+ const { page } = api;
156
+ await page.goto("/account/second-factor");
157
+ await expect(page.getByText("No recovery codes left: create new ones.")).toBeVisible();
158
+
159
+ // Cancel goes back to the state, where the keyboard carries on.
160
+ await page.getByRole("button", { name: "Remove authenticator" }).click();
161
+ await expect(page.getByLabel("6-digit code")).toBeFocused();
162
+ await page.getByRole("button", { name: "Cancel" }).click();
163
+ await expect(page.getByText(/^Authenticator app set up on /u)).toBeFocused();
164
+
165
+ await page.getByRole("button", { name: "Remove authenticator" }).click();
166
+ await page.getByRole("button", { name: "Use a recovery code" }).click();
167
+ await expect(page.getByLabel("Recovery code")).toBeFocused();
168
+ await page.keyboard.type("abcd0-efgh0");
169
+ await page.keyboard.press("Enter");
170
+ await expect(page.getByText("Too many wrong codes. Try again in 1 minute.")).toBeVisible();
171
+ assert.deepEqual(await reports(page), []);
172
+
173
+ await page.getByRole("button", { name: "Remove authenticator" }).click();
174
+ await expect.poll(() => reports(page)).toEqual([{ message: "Internal server error.", severity: "error", channel: "snackbar" }]);
175
+ await expect(page.getByLabel("Recovery code")).toHaveValue("abcd0-efgh0");
176
+
177
+ await page.getByRole("button", { name: "Remove authenticator" }).click();
178
+ await expect(page.getByRole("button", { name: "Set up authenticator" })).toBeVisible();
179
+ assert.deepEqual((await reports(page)).at(-1), { message: "Authenticator removed.", severity: "success", channel: "snackbar" });
180
+ assert.deepEqual(bodiesOf(api, "DELETE /api/second-factor"), Array(3).fill({ recoveryCode: "abcd0-efgh0" }));
181
+ await fitsTheScreen(page);
182
+ await finish(api);
183
+ });
184
+
185
+ test("a route that asks for a fresh code opens the step-up dialog, runs again after the code, and Escape cancels it", options, async () => {
186
+ const api = await openApp({
187
+ "POST /api/console/refund": [REQUIRED, { json: { refunded: true } }, REQUIRED],
188
+ "POST /api/second-factor/verify": [
189
+ refused(400, "auth.local.secondFactor.codeInvalid", "That code is not right. Enter the code your authenticator app shows now."),
190
+ { json: { verifiedAt: "2026-11-13T10:00:00.000Z", method: "code", recoveryCodesLeft: 10 } }
191
+ ]
192
+ });
193
+ const { page } = api;
194
+ await page.goto("/console");
195
+ await page.getByRole("button", { name: "Refund" }).click();
196
+
197
+ const dialog = page.getByRole("dialog", { name: "Confirm it's you" });
198
+ await expect(dialog.getByRole("heading", { name: "Confirm it's you" })).toBeVisible();
199
+ await expect(dialog.getByLabel("6-digit code")).toBeFocused();
200
+ await fitsTheScreen(page);
201
+ await page.keyboard.type("000000");
202
+ await page.keyboard.press("Enter");
203
+ await expect(dialog.getByText("That code is not right. Enter the code your authenticator app shows now.")).toBeVisible();
204
+ await dialog.getByLabel("6-digit code").fill("123456");
205
+ await page.keyboard.press("Enter");
206
+ await expect(page.getByTestId("console-outcome")).toHaveText("Refunded");
207
+ await expect(dialog).toBeHidden();
208
+
209
+ await page.getByRole("button", { name: "Refund" }).click();
210
+ await expect(dialog.getByLabel("6-digit code")).toBeFocused();
211
+ await page.keyboard.press("Escape");
212
+ await expect(dialog).toBeHidden();
213
+ await expect(page.getByTestId("console-outcome")).toHaveText("Refund failed: Confirm it's you with a code from your authenticator app.");
214
+
215
+ assert.equal(bodiesOf(api, "POST /api/console/refund").length, 3);
216
+ assert.deepEqual(bodiesOf(api, "POST /api/second-factor/verify"), [{ code: "000000" }, { code: "123456" }]);
217
+ assert.deepEqual(await reports(page), []);
218
+ await finish(api);
219
+ });
@@ -0,0 +1,140 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createApp } from "vue";
4
+ import { encode } from "uqr";
5
+ import { SECOND_FACTOR_REQUIRED } from "@jskit-ai/auth-core/shared/authSecondFactor";
6
+ import { SHELL_WEB_ERROR_RUNTIME_KEY } from "@jskit-ai/shell-web/client/error";
7
+ import { useSecondFactorProof } from "../src/client/composables/secondFactor/useSecondFactorProof.js";
8
+ import { useSecondFactorStepUp } from "../src/client/composables/secondFactor/useSecondFactorStepUp.js";
9
+ import { qrCodePath } from "../src/client/lib/qrCode.js";
10
+
11
+ const QUIET_ZONE = 4;
12
+
13
+ /** An error as auth-web's HTTP client throws it for a refused request. */
14
+ function httpError(status, code, message) {
15
+ return Object.assign(new Error(message), { status, code, params: {}, fieldErrors: null });
16
+ }
17
+
18
+ function settled() {
19
+ return new Promise((resolve) => setImmediate(resolve));
20
+ }
21
+
22
+ test("a QR code's path draws exactly its code's dark modules, inside a quiet zone of four modules", () => {
23
+ const text = "otpauth://totp/Console:ada%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Console";
24
+ const { size, path } = qrCodePath(text);
25
+ const runs = [...path.matchAll(/M(\d+) (\d+)h(\d+)v1h-\3z/gu)];
26
+ assert.equal(runs.map(([run]) => run).join(""), path, "the path is rectangles one module tall");
27
+ const drawn = Array.from({ length: size }, () => Array(size).fill(false));
28
+ for (const [, x, y, length] of runs) {
29
+ for (let column = Number(x); column < Number(x) + Number(length); column += 1) {
30
+ assert.equal(drawn[Number(y)][column], false, "no module is drawn twice");
31
+ drawn[Number(y)][column] = true;
32
+ }
33
+ }
34
+ assert.deepEqual(drawn, encode(text, { border: QUIET_ZONE }).data);
35
+ const edges = [...drawn.slice(0, QUIET_ZONE), ...drawn.slice(-QUIET_ZONE)].flat()
36
+ .concat(drawn.flatMap((row) => [...row.slice(0, QUIET_ZONE), ...row.slice(-QUIET_ZONE)]));
37
+ assert.equal(edges.some(Boolean), false);
38
+ });
39
+
40
+ test("a request refused for the second factor waits for the proof, then runs once more; cancelling throws the refusal", async () => {
41
+ const stepUp = useSecondFactorStepUp();
42
+ const refused = httpError(403, SECOND_FACTOR_REQUIRED.code, SECOND_FACTOR_REQUIRED.message);
43
+ const calls = { refund: 0, export: 0 };
44
+ const refund = stepUp.run(async () => {
45
+ calls.refund += 1;
46
+ if (calls.refund === 1) throw refused;
47
+ return { refunded: true };
48
+ });
49
+ const exported = stepUp.run(async () => {
50
+ calls.export += 1;
51
+ if (calls.export === 1) throw refused;
52
+ return { exported: true };
53
+ });
54
+ await settled();
55
+ assert.equal(stepUp.open.value, true);
56
+ assert.deepEqual(calls, { refund: 1, export: 1 }, "nothing runs again before the proof");
57
+ stepUp.verified();
58
+ assert.equal(stepUp.open.value, false);
59
+ assert.deepEqual(await refund, { refunded: true });
60
+ assert.deepEqual(await exported, { exported: true });
61
+ assert.deepEqual(calls, { refund: 2, export: 2 });
62
+
63
+ let cancelledCalls = 0;
64
+ const cancelled = stepUp.run(async () => {
65
+ cancelledCalls += 1;
66
+ throw refused;
67
+ });
68
+ await settled();
69
+ assert.equal(stepUp.open.value, true);
70
+ stepUp.cancel();
71
+ assert.equal(stepUp.open.value, false);
72
+ await assert.rejects(cancelled, (error) => error === refused);
73
+ assert.equal(cancelledCalls, 1, "a cancelled request does not run again");
74
+
75
+ // A refusal for anything else is the caller's, and asks for no code.
76
+ const forbidden = httpError(403, "auth.forbidden", "You can't do that.");
77
+ await assert.rejects(stepUp.run(async () => {
78
+ throw forbidden;
79
+ }), (error) => error === forbidden);
80
+ assert.equal(stepUp.open.value, false);
81
+ });
82
+
83
+ test("a refused code shows beside its field, any other failure is reported, and a proof that passes is handed on", async () => {
84
+ const reports = [];
85
+ const answers = [
86
+ httpError(400, "auth.local.secondFactor.codeInvalid", "That code is not right. Enter the code your authenticator app shows now."),
87
+ httpError(429, "auth.local.secondFactor.locked", "Too many wrong codes. Try again in 1 minute."),
88
+ httpError(0, null, "Network request failed."),
89
+ httpError(409, "auth.local.secondFactor.notSetUp", "No authenticator is set up for this account."),
90
+ { verifiedAt: "2026-11-13T10:00:00.000Z", method: "recoveryCode", recoveryCodesLeft: 9 }
91
+ ];
92
+ const submitted = [];
93
+ const done = [];
94
+ const app = createApp({});
95
+ app.provide(SHELL_WEB_ERROR_RUNTIME_KEY, { report: (event) => reports.push(event), dismiss: () => 0 });
96
+ const proof = app.runWithContext(() => useSecondFactorProof({
97
+ async submit(typed) {
98
+ submitted.push(typed);
99
+ const answer = answers.shift();
100
+ if (answer instanceof Error) throw answer;
101
+ return answer;
102
+ },
103
+ onDone: (result) => done.push(result)
104
+ }));
105
+
106
+ assert.equal(proof.canSubmit.value, false, "nothing typed, nothing to send");
107
+ proof.code.value = " 123 456 ";
108
+ await proof.submitProof();
109
+ assert.equal(proof.fieldError.value, "That code is not right. Enter the code your authenticator app shows now.");
110
+ assert.equal(proof.code.value, " 123 456 ", "the code stays to be corrected");
111
+
112
+ await proof.submitProof();
113
+ assert.equal(proof.fieldError.value, "Too many wrong codes. Try again in 1 minute.");
114
+
115
+ await proof.submitProof();
116
+ assert.equal(proof.fieldError.value, "");
117
+ assert.deepEqual(reports.map(({ message, severity, channel }) => ({ message, severity, channel })), [
118
+ { message: "Network request failed.", severity: "error", channel: "snackbar" }
119
+ ]);
120
+
121
+ await proof.submitProof();
122
+ assert.equal(proof.fieldError.value, "No authenticator is set up for this account.");
123
+ proof.toggleRecoveryCode();
124
+ assert.equal(proof.fieldError.value, "", "the other field starts clean");
125
+ assert.equal(proof.canSubmit.value, false);
126
+ proof.recoveryCode.value = "abcde-fghjk";
127
+ await proof.submitProof();
128
+
129
+ assert.deepEqual(submitted, [
130
+ { code: "123 456" },
131
+ { code: "123 456" },
132
+ { code: "123 456" },
133
+ { code: "123 456" },
134
+ { recoveryCode: "abcde-fghjk" }
135
+ ]);
136
+ assert.deepEqual(done, [{ verifiedAt: "2026-11-13T10:00:00.000Z", method: "recoveryCode", recoveryCodesLeft: 9 }]);
137
+ assert.equal(proof.recoveryCode.value, "");
138
+ assert.equal(proof.pending.value, false);
139
+ assert.equal(reports.length, 1);
140
+ });
@@ -0,0 +1,152 @@
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 Fastify from "fastify";
7
+ import { AuthExtensionsProvider } from "@jskit-ai/auth-core/server/providers/AuthExtensionsProvider";
8
+ import { AuthFeature } from "@jskit-ai/auth-core/server/providers/AuthFeature";
9
+ import { AuthPolicyProvider } from "@jskit-ai/auth-core/server/providers/AuthPolicyProvider";
10
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
11
+ import { HttpProvider } from "@jskit-ai/kernel/server/http";
12
+ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
13
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
14
+ import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
15
+ import { createLocalAuthService, createLocalFileBackend } from "../../auth-provider-local-core/src/server/lib/index.js";
16
+ import { sessionCookies } from "../../auth-provider-local-core/test-support/oauthHarness.js";
17
+ import {
18
+ SCENARIO_START,
19
+ codeAt,
20
+ secondFactorServiceOptions
21
+ } from "../../auth-provider-local-core/test-support/secondFactorScenario.js";
22
+ import { AuthWebFeature } from "../src/server/AuthWebFeature.js";
23
+ import { DEFAULT_AUTH_RATE_LIMITS } from "../src/server/authRateLimits.js";
24
+
25
+ const PASSWORD = "correct horse battery staple";
26
+
27
+ // An application's console: a page that asks for the session's second factor, and a dangerous action that asks for a
28
+ // code proved within five minutes.
29
+ const ConsoleRoutes = defineProvider({
30
+ id: "test.console.routes",
31
+ requires: { http: "runtime.http" },
32
+ setup({ http }) {
33
+ http.router.register("GET", "/api/console", { auth: "required", secondFactor: true }, async (request, reply) => {
34
+ reply.send({ page: "console" });
35
+ });
36
+ http.router.register("POST", "/api/console/refund", { auth: "required", secondFactor: { maxAgeSeconds: 300 } },
37
+ async (request, reply) => {
38
+ reply.send({ refunded: true });
39
+ });
40
+ return {};
41
+ }
42
+ });
43
+
44
+ /** The auth routes, the auth policy and the console over local auth in a store of the test's own. */
45
+ async function startConsole(t) {
46
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-web-second-factor-"));
47
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
48
+ const authService = createLocalAuthService({
49
+ ...secondFactorServiceOptions().options,
50
+ backend: createLocalFileBackend({ storeDir })
51
+ });
52
+ const app = Fastify();
53
+ const runtime = createCapabilityRuntime({
54
+ inputs: {
55
+ "auth.service": authService,
56
+ "runtime.config": {},
57
+ "runtime.env": { NODE_ENV: "test" },
58
+ "runtime.fastify": app,
59
+ "runtime.logger": silentLogger
60
+ },
61
+ providers: [EventProvider, ActionProvider, HttpProvider, AuthExtensionsProvider, AuthFeature, AuthPolicyProvider, AuthWebFeature,
62
+ ConsoleRoutes]
63
+ });
64
+ await runtime.start();
65
+ t.after(async () => {
66
+ await runtime.shutdown();
67
+ await app.close();
68
+ });
69
+ return { app, authService };
70
+ }
71
+
72
+ /** A signed-in browser: its cookies and CSRF token, sending each request from one address. */
73
+ async function signedInBrowser(app, authService, email) {
74
+ await authService.register({ email, password: PASSWORD });
75
+ const cookies = sessionCookies((await authService.login({ email, password: PASSWORD })).session);
76
+ const session = await app.inject({ method: "GET", url: "/api/session", cookies });
77
+ for (const cookie of session.cookies) {
78
+ cookies[cookie.name] = cookie.value;
79
+ }
80
+ const csrfToken = session.json().csrfToken;
81
+ return (method, url, payload) => app.inject({
82
+ method,
83
+ url,
84
+ cookies,
85
+ remoteAddress: "203.0.113.7",
86
+ headers: { "csrf-token": csrfToken },
87
+ ...(payload === undefined ? {} : { payload })
88
+ });
89
+ }
90
+
91
+ function refusedFor(response, status, code) {
92
+ assert.equal(response.statusCode, status, response.body);
93
+ assert.equal(response.json().code, code);
94
+ return response.json();
95
+ }
96
+
97
+ test("a console asks for the session's second factor, and its dangerous action for one proved within five minutes", async (t) => {
98
+ t.mock.timers.enable({ apis: ["Date"], now: SCENARIO_START });
99
+ const { app, authService } = await startConsole(t);
100
+ const ada = await signedInBrowser(app, authService, "ada@example.com");
101
+
102
+ // A signed-in session without a second factor is refused, saying what the route asks for.
103
+ assert.deepEqual(refusedFor(await ada("GET", "/api/console"), 403, "auth.secondFactor.required").params, {});
104
+ assert.deepEqual(refusedFor(await ada("POST", "/api/console/refund"), 403, "auth.secondFactor.required").params, {
105
+ maxAgeSeconds: 300
106
+ });
107
+ refusedFor(await app.inject({ method: "GET", url: "/api/console" }), 401, "auth.session.required");
108
+
109
+ // Setting up the authenticator proves this session's second factor.
110
+ assert.deepEqual((await ada("GET", "/api/second-factor")).json(), { enrolled: false, enrolledAt: null, recoveryCodesLeft: 0, verifiedAt: null });
111
+ const setup = await ada("POST", "/api/second-factor/setup");
112
+ assert.equal(setup.statusCode, 200, setup.body);
113
+ const { secret } = setup.json();
114
+ refusedFor(await ada("POST", "/api/second-factor/setup/confirm", {}), 400, "validation_failed");
115
+ const confirmed = await ada("POST", "/api/second-factor/setup/confirm", { code: codeAt(secret) });
116
+ assert.equal(confirmed.statusCode, 200, confirmed.body);
117
+ assert.equal(confirmed.json().recoveryCodes.length, 10);
118
+ assert.deepEqual((await ada("GET", "/api/console")).json(), { page: "console" });
119
+ assert.deepEqual((await ada("POST", "/api/console/refund")).json(), { refunded: true });
120
+
121
+ // Six minutes on, the console still opens but the refund asks for a fresh code.
122
+ t.mock.timers.tick(6 * 60_000);
123
+ assert.equal((await ada("GET", "/api/console")).statusCode, 200);
124
+ refusedFor(await ada("POST", "/api/console/refund"), 403, "auth.secondFactor.required");
125
+ refusedFor(await ada("POST", "/api/second-factor/verify", { code: codeAt(secret, -2) }), 400, "auth.local.secondFactor.codeInvalid");
126
+ const verified = await ada("POST", "/api/second-factor/verify", { code: codeAt(secret) });
127
+ assert.deepEqual(verified.json(), { verifiedAt: new Date().toISOString(), method: "code", recoveryCodesLeft: 10 });
128
+ assert.deepEqual((await ada("POST", "/api/console/refund")).json(), { refunded: true });
129
+
130
+ // Another signed-in person proves nothing for Ada's session, and Ada's proof opens nothing for them.
131
+ const bob = await signedInBrowser(app, authService, "bob@example.com");
132
+ refusedFor(await bob("GET", "/api/console"), 403, "auth.secondFactor.required");
133
+ refusedFor(await bob("POST", "/api/second-factor/verify", { code: codeAt(secret) }), 409, "auth.local.secondFactor.notSetUp");
134
+
135
+ // Removing it takes a proof, and afterwards the console asks again.
136
+ t.mock.timers.tick(30_000);
137
+ refusedFor(await ada("DELETE", "/api/second-factor", {}), 400, "auth.local.secondFactor.proofRequired");
138
+ assert.deepEqual((await ada("DELETE", "/api/second-factor", { code: codeAt(secret) })).json(), { ok: true });
139
+ refusedFor(await ada("GET", "/api/console"), 403, "auth.secondFactor.required");
140
+ });
141
+
142
+ test("one address may try codes only as fast as the verify route's limit", async (t) => {
143
+ const { app, authService } = await startConsole(t);
144
+ const ada = await signedInBrowser(app, authService, "ada@example.com");
145
+ const statuses = [];
146
+ for (let attempt = 0; attempt < 15; attempt += 1) {
147
+ statuses.push((await ada("POST", "/api/second-factor/verify", { code: "123456" })).statusCode);
148
+ }
149
+ const allowed = DEFAULT_AUTH_RATE_LIMITS.secondFactorVerify.max;
150
+ assert.deepEqual(statuses.slice(0, allowed), Array(allowed).fill(409), "Ada has no authenticator to check");
151
+ assert.deepEqual(statuses.slice(allowed), Array(15 - allowed).fill(429));
152
+ });