@jskit-ai/auth-web 0.2.33 → 0.2.35

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,220 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs/promises";
3
+ import http from "node:http";
4
+ import { once } from "node:events";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import process from "node:process";
8
+ import { after, before, test } from "node:test";
9
+ import { fileURLToPath } from "node:url";
10
+ import { chromium, expect } from "@playwright/test";
11
+ import Fastify from "fastify";
12
+ import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
13
+ import { AuthExtensionsProvider } from "@jskit-ai/auth-core/server/providers/AuthExtensionsProvider";
14
+ import { AuthFeature } from "@jskit-ai/auth-core/server/providers/AuthFeature";
15
+ import { AuthPolicyProvider } from "@jskit-ai/auth-core/server/providers/AuthPolicyProvider";
16
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
17
+ import { HttpProvider } from "@jskit-ai/kernel/server/http";
18
+ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
19
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
20
+ import { createCapabilityRuntime } from "@jskit-ai/kernel/shared/capabilities";
21
+ import { createLocalFileBackend } from "../../auth-provider-local-core/src/server/lib/index.js";
22
+ import { createService, oidcProviderEntry, startOidcProvider } from "../../auth-provider-local-core/test-support/oauthHarness.js";
23
+ import {
24
+ createChromiumLaunchOptions,
25
+ reservePort,
26
+ startViteFixture,
27
+ stopProcess
28
+ } from "../../../tooling/testUtils/browserFixture.mjs";
29
+ import { AuthWebFeature } from "../src/server/AuthWebFeature.js";
30
+
31
+ // The real sign-in page, served on http://localhost:PORT, with the real auth routes, auth policy and local auth behind
32
+ // its /api, all with AUTH_COOKIE_SAME_SITE=strict. The Google stand-in and the webmail page are on 127.0.0.1, another
33
+ // site, and the way back from either starts on its own page (the stand-in's Continue button, the webmail's link), so
34
+ // it is a cross-site navigation, on which a browser sends no SameSite=Strict cookie. (Chromium still sends them when
35
+ // the provider only redirects the app's own navigation back, without a page of its own.)
36
+ const RUN = process.env.JSKIT_AUTH_WEB_BROWSER_INTEGRATION === "1";
37
+ const options = { skip: !RUN, timeout: 120_000 };
38
+ const STRICT = Object.freeze({ AUTH_COOKIE_SAME_SITE: "strict" });
39
+ const PASSWORD = "correct horse battery staple";
40
+ const SESSION_COOKIES = ["_csrf", "jskit_local_access_token", "jskit_local_refresh_token"];
41
+
42
+ let stack = null;
43
+ const cleanups = [];
44
+
45
+ before(async () => {
46
+ if (!RUN) return;
47
+ const vitePort = await reservePort();
48
+ const appUrl = `http://localhost:${vitePort}`;
49
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-web-same-site-"));
50
+ cleanups.push(() => fs.rm(storeDir, { recursive: true, force: true }));
51
+ const issuer = await startOidcProvider({ appUrl, consentPage: true });
52
+ cleanups.push(() => issuer.close());
53
+ const authService = createService({
54
+ backend: createLocalFileBackend({ storeDir }),
55
+ oauthProviders: [oidcProviderEntry(issuer)],
56
+ profileProjector: noAppProfiles,
57
+ env: { APP_PUBLIC_URL: appUrl, ...STRICT }
58
+ });
59
+
60
+ const api = Fastify();
61
+ cleanups.push(() => api.close());
62
+ // What reaches the server: each request with the names of the cookies it carried.
63
+ const apiRequests = [];
64
+ api.addHook("onRequest", async (request) => {
65
+ apiRequests.push({ key: `${request.method} ${request.url.split("?")[0]}`, cookies: cookieNames(request.headers.cookie) });
66
+ });
67
+ const runtime = createCapabilityRuntime({
68
+ inputs: {
69
+ "auth.service": authService,
70
+ "runtime.config": {},
71
+ "runtime.env": { NODE_ENV: "test", ...STRICT },
72
+ "runtime.fastify": api,
73
+ "runtime.logger": silentLogger
74
+ },
75
+ providers: [EventProvider, ActionProvider, HttpProvider, AuthExtensionsProvider, AuthFeature, AuthPolicyProvider,
76
+ AuthWebFeature]
77
+ });
78
+ await runtime.start();
79
+ cleanups.push(() => runtime.shutdown());
80
+ await api.listen({ host: "127.0.0.1", port: 0 });
81
+
82
+ const vite = await startViteFixture({
83
+ fixtureRoot: fileURLToPath(new URL("../fixtures/sign-in/", import.meta.url)),
84
+ port: vitePort,
85
+ env: { JSKIT_AUTH_WEB_FIXTURE_API_SERVER: `http://127.0.0.1:${api.server.address().port}` }
86
+ });
87
+ cleanups.push(() => stopProcess(vite));
88
+ const browser = await chromium.launch(createChromiumLaunchOptions());
89
+ cleanups.push(() => browser.close());
90
+ stack = { appUrl, issuerUrl: issuer.issuer, authService, apiRequests, browser };
91
+ });
92
+
93
+ after(async () => {
94
+ for (const cleanup of cleanups.reverse()) {
95
+ await cleanup();
96
+ }
97
+ });
98
+
99
+ function cookieNames(header) {
100
+ return String(header || "").split(";").map((pair) => pair.split("=")[0].trim()).filter(Boolean).sort();
101
+ }
102
+
103
+ /** A browser of its own, which records every page it loads with the headers it sent. */
104
+ async function openBrowser(t) {
105
+ const context = await stack.browser.newContext();
106
+ t.after(() => context.close());
107
+ const page = await context.newPage();
108
+ page.setDefaultTimeout(15_000);
109
+ page.setDefaultNavigationTimeout(60_000);
110
+ const documents = [];
111
+ const errors = [];
112
+ page.on("pageerror", (error) => errors.push(error.message));
113
+ page.on("request", (request) => {
114
+ if (request.resourceType() === "document") {
115
+ documents.push({ url: new URL(request.url()), headers: request.allHeaders() });
116
+ }
117
+ });
118
+ return { context, page, documents, errors };
119
+ }
120
+
121
+ /** The headers of the one page load of the app that `matches` its address. */
122
+ async function appDocument(documents, matches) {
123
+ const loads = documents.filter(({ url }) => url.origin === new URL(stack.appUrl).origin && matches(url));
124
+ assert.equal(loads.length, 1, `page loads: ${documents.map(({ url }) => url.href).join(", ")}`);
125
+ return loads[0].headers;
126
+ }
127
+
128
+ function apiRequest(key) {
129
+ const requests = stack.apiRequests.filter((request) => request.key === key);
130
+ assert.equal(requests.length > 0, true, `no ${key} among ${stack.apiRequests.map((request) => request.key).join(", ")}`);
131
+ return requests;
132
+ }
133
+
134
+ test("with strict cookies, Google sign-in comes back from the provider's site and completes on the login page", options, async (t) => {
135
+ const { context, page, documents, errors } = await openBrowser(t);
136
+ const attemptSetCookies = [];
137
+ page.on("response", (response) => {
138
+ if (new URL(response.url()).pathname === "/api/oauth/google/start") {
139
+ attemptSetCookies.push(response.headersArray());
140
+ }
141
+ });
142
+ stack.apiRequests.length = 0;
143
+ await page.goto(`${stack.appUrl}/auth/login?returnTo=/home`);
144
+ await page.getByRole("button", { name: "Continue with Google" }).click();
145
+ await page.waitForURL((url) => url.href.startsWith(stack.issuerUrl));
146
+ await page.getByRole("button", { name: "Continue", exact: true }).click();
147
+ await expect(page.getByTestId("home")).toHaveText("Signed in: true");
148
+ assert.equal(new URL(page.url()).pathname, "/home");
149
+
150
+ // The start set the attempt cookie Strict, before the browser left for the provider.
151
+ const [startHeaders] = await Promise.all(attemptSetCookies);
152
+ const attemptCookie = startHeaders.find(({ name, value }) => name.toLowerCase() === "set-cookie" &&
153
+ value.startsWith("jskit_local_oauth_attempt="));
154
+ assert.match(attemptCookie.value, /; SameSite=Strict(;|$)/u);
155
+
156
+ // The way back to the login page started on the provider's page, a cross-site navigation, so it carried none of the
157
+ // app's cookies: neither the attempt nor the CSRF secret the login page had been given.
158
+ const back = await appDocument(documents, (url) => url.pathname === "/auth/login" && url.searchParams.has("code"));
159
+ assert.equal(back["sec-fetch-site"], "cross-site");
160
+ assert.deepEqual(cookieNames(back.cookie), []);
161
+ // The page's own same-origin POST carried the attempt, which completed the sign-in.
162
+ assert.deepEqual(apiRequest("POST /api/oauth/complete").map(({ cookies }) => cookies), [
163
+ ["_csrf", "jskit_local_oauth_attempt"]
164
+ ]);
165
+ assert.deepEqual(apiRequest("GET /api/session").at(-1).cookies, SESSION_COOKIES);
166
+
167
+ const kept = (await context.cookies(stack.appUrl)).map(({ name, sameSite }) => [name, sameSite]);
168
+ assert.deepEqual(kept.sort(), SESSION_COOKIES.map((name) => [name, "Strict"]));
169
+ assert.deepEqual(errors, []);
170
+ });
171
+
172
+ /** A webmail page on 127.0.0.1, another site than the app's, with one link into the app. */
173
+ async function startWebmail(t, link) {
174
+ const server = http.createServer((_request, response) => {
175
+ response.setHeader("content-type", "text/html; charset=utf-8");
176
+ response.end(`<!doctype html><title>Inbox</title><a href="${link}">Open your account</a>`);
177
+ });
178
+ server.listen(0, "127.0.0.1");
179
+ await once(server, "listening");
180
+ t.after(async () => {
181
+ server.closeAllConnections();
182
+ server.close();
183
+ await once(server, "close");
184
+ });
185
+ return `http://127.0.0.1:${server.address().port}/`;
186
+ }
187
+
188
+ test("with strict cookies, a link from another site opens the app signed in by the page's own requests", options, async (t) => {
189
+ await stack.authService.register({ email: "grace@example.com", password: PASSWORD });
190
+ const webmail = await startWebmail(t, `${stack.appUrl}/home`);
191
+ const { page, documents, errors } = await openBrowser(t);
192
+ await page.goto(`${stack.appUrl}/auth/login?returnTo=/home`);
193
+ await page.getByLabel("Email").fill("grace@example.com");
194
+ await page.getByLabel("Password", { exact: true }).fill(PASSWORD);
195
+ await page.getByTestId("auth-submit").click();
196
+ await expect(page.getByTestId("home")).toHaveText("Signed in: true");
197
+
198
+ stack.apiRequests.length = 0;
199
+ documents.length = 0;
200
+ await page.goto(webmail);
201
+ await page.getByRole("link", { name: "Open your account" }).click();
202
+ await expect(page.getByTestId("home")).toHaveText("Signed in: true");
203
+ // The link's page load came from another site and carried no Strict cookie ...
204
+ const landing = await appDocument(documents, (url) => url.pathname === "/home");
205
+ assert.equal(landing["sec-fetch-site"], "cross-site");
206
+ assert.deepEqual(cookieNames(landing.cookie), []);
207
+ // ... and the page's own requests carried them all, so the person is signed in.
208
+ for (const { cookies } of apiRequest("GET /api/session")) {
209
+ assert.deepEqual(cookies, SESSION_COOKIES);
210
+ }
211
+
212
+ // A page load the person starts in the app carries them, so the empty Cookie header above is SameSite at work.
213
+ documents.length = 0;
214
+ await page.goto(`${stack.appUrl}/home`);
215
+ await expect(page.getByTestId("home")).toHaveText("Signed in: true");
216
+ const typed = await appDocument(documents, (url) => url.pathname === "/home");
217
+ assert.equal(typed["sec-fetch-site"], "none");
218
+ assert.deepEqual(cookieNames(typed.cookie), SESSION_COOKIES);
219
+ assert.deepEqual(errors, []);
220
+ });
@@ -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
+ });