@jskit-ai/auth-web 0.2.32 → 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,134 @@
1
+ import {
2
+ ACTION_CONFIRM_SECOND_FACTOR_SETUP,
3
+ ACTION_READ_SECOND_FACTOR,
4
+ ACTION_REMOVE_SECOND_FACTOR,
5
+ ACTION_REPLACE_SECOND_FACTOR_RECOVERY_CODES,
6
+ ACTION_START_SECOND_FACTOR_SETUP,
7
+ ACTION_VERIFY_SECOND_FACTOR
8
+ } from "@jskit-ai/auth-core/server/actions/secondFactorActions";
9
+ import { AUTH_PATHS } from "@jskit-ai/auth-core/shared/authPaths";
10
+ import {
11
+ authSecondFactorReadCommand,
12
+ authSecondFactorRecoveryCodesReplaceCommand,
13
+ authSecondFactorRemoveCommand,
14
+ authSecondFactorSetupConfirmCommand,
15
+ authSecondFactorSetupStartCommand,
16
+ authSecondFactorVerifyCommand
17
+ } from "@jskit-ai/auth-core/shared/commands";
18
+ import { withStandardErrorResponses } from "@jskit-ai/http-runtime/shared/validators/errorResponses";
19
+
20
+ /**
21
+ * The signed-in person's second factor: reading it, setting up an
22
+ * authenticator, proving a code for this session, and replacing the recovery
23
+ * codes or removing the authenticator with a proof. Each route runs its
24
+ * auth.secondFactor action, limited per client address by its entry in
25
+ * `rateLimits` (none when that entry is null); the provider also makes an
26
+ * account wait after wrong codes.
27
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
28
+ * @param {{ rateLimits: import("../types.js").AuthRateLimits }} dependencies
29
+ */
30
+ function registerSecondFactorRoutes(router, { rateLimits }) {
31
+ router.register(
32
+ "GET",
33
+ AUTH_PATHS.SECOND_FACTOR,
34
+ {
35
+ auth: "required",
36
+ meta: { tags: ["auth"], summary: "Read the account's second factor and when this session proved it" },
37
+ responses: withStandardErrorResponses({ 200: authSecondFactorReadCommand.operation.response })
38
+ },
39
+ async function (request, reply) {
40
+ reply.code(200).send(await request.executeAction({ actionId: ACTION_READ_SECOND_FACTOR }));
41
+ }
42
+ );
43
+
44
+ router.register(
45
+ "POST",
46
+ AUTH_PATHS.SECOND_FACTOR_SETUP,
47
+ {
48
+ auth: "required",
49
+ meta: { tags: ["auth"], summary: "Start setting up an authenticator app: its secret, shown once" },
50
+ responses: withStandardErrorResponses({ 200: authSecondFactorSetupStartCommand.operation.response }),
51
+ rateLimit: rateLimits.secondFactorSetup
52
+ },
53
+ async function (request, reply) {
54
+ reply.code(200).send(await request.executeAction({ actionId: ACTION_START_SECOND_FACTOR_SETUP }));
55
+ }
56
+ );
57
+
58
+ router.register(
59
+ "POST",
60
+ AUTH_PATHS.SECOND_FACTOR_SETUP_CONFIRM,
61
+ {
62
+ auth: "required",
63
+ meta: { tags: ["auth"], summary: "Confirm the authenticator with its first code: the recovery codes, shown once" },
64
+ body: authSecondFactorSetupConfirmCommand.operation.body,
65
+ responses: withStandardErrorResponses(
66
+ { 200: authSecondFactorSetupConfirmCommand.operation.response },
67
+ { includeValidation400: true }
68
+ ),
69
+ rateLimit: rateLimits.secondFactorSetupConfirm
70
+ },
71
+ async function (request, reply) {
72
+ reply.code(200).send(await request.executeAction({ actionId: ACTION_CONFIRM_SECOND_FACTOR_SETUP, input: request.input.body }));
73
+ }
74
+ );
75
+
76
+ router.register(
77
+ "POST",
78
+ AUTH_PATHS.SECOND_FACTOR_VERIFY,
79
+ {
80
+ auth: "required",
81
+ meta: { tags: ["auth"], summary: "Prove the second factor for this session with a code or a recovery code" },
82
+ body: authSecondFactorVerifyCommand.operation.body,
83
+ responses: withStandardErrorResponses(
84
+ { 200: authSecondFactorVerifyCommand.operation.response },
85
+ { includeValidation400: true }
86
+ ),
87
+ rateLimit: rateLimits.secondFactorVerify
88
+ },
89
+ async function (request, reply) {
90
+ reply.code(200).send(await request.executeAction({ actionId: ACTION_VERIFY_SECOND_FACTOR, input: request.input.body }));
91
+ }
92
+ );
93
+
94
+ router.register(
95
+ "POST",
96
+ AUTH_PATHS.SECOND_FACTOR_RECOVERY_CODES,
97
+ {
98
+ auth: "required",
99
+ meta: { tags: ["auth"], summary: "Replace the recovery codes, with a proof: the new codes, shown once" },
100
+ body: authSecondFactorRecoveryCodesReplaceCommand.operation.body,
101
+ responses: withStandardErrorResponses(
102
+ { 200: authSecondFactorRecoveryCodesReplaceCommand.operation.response },
103
+ { includeValidation400: true }
104
+ ),
105
+ rateLimit: rateLimits.secondFactorRecoveryCodes
106
+ },
107
+ async function (request, reply) {
108
+ reply.code(200).send(await request.executeAction({
109
+ actionId: ACTION_REPLACE_SECOND_FACTOR_RECOVERY_CODES,
110
+ input: request.input.body
111
+ }));
112
+ }
113
+ );
114
+
115
+ router.register(
116
+ "DELETE",
117
+ AUTH_PATHS.SECOND_FACTOR,
118
+ {
119
+ auth: "required",
120
+ meta: { tags: ["auth"], summary: "Remove the authenticator, with a proof" },
121
+ body: authSecondFactorRemoveCommand.operation.body,
122
+ responses: withStandardErrorResponses(
123
+ { 200: authSecondFactorRemoveCommand.operation.response },
124
+ { includeValidation400: true }
125
+ ),
126
+ rateLimit: rateLimits.secondFactorRemove
127
+ },
128
+ async function (request, reply) {
129
+ reply.code(200).send(await request.executeAction({ actionId: ACTION_REMOVE_SECOND_FACTOR, input: request.input.body }));
130
+ }
131
+ );
132
+ }
133
+
134
+ export { registerSecondFactorRoutes };
@@ -1,5 +1,10 @@
1
- // The type of the `auth.web` capability, for features that require it.
1
+ // The type of the `auth.web` capability, for features that require it, and of the auth routes' rate limits.
2
2
 
3
3
  /** @typedef {ReturnType<typeof import("./authWeb.js").createAuthWeb>} AuthWeb */
4
4
 
5
+ /**
6
+ * The per-address limit of each auth route; null for a route without one.
7
+ * @typedef {ReturnType<typeof import("./authRateLimits.js").resolveAuthRateLimits>} AuthRateLimits
8
+ */
9
+
5
10
  export {};
@@ -4,7 +4,8 @@ import test from "node:test";
4
4
 
5
5
  import {
6
6
  DEFAULT_PREVIEW_IDENTITY_PROTOCOL,
7
- executeManagedPreviewIdentityRequest
7
+ executeManagedPreviewIdentityRequest,
8
+ runManagedPreviewIdentityCommand
8
9
  } from "../src/server/managedPreviewIdentity.js";
9
10
 
10
11
  const SECRET = "a".repeat(64);
@@ -196,3 +197,99 @@ test("the auth surface pattern ships the managed-preview login as standard", ()
196
197
  "- Runtimes: `nodejs`"
197
198
  ].join("\n")));
198
199
  });
200
+
201
+ test("an application's own exchange signs the preview in instead of the development exchange", async () => {
202
+ const exchanged = [];
203
+ const request = {
204
+ operation: "login-as",
205
+ protocol: HOST_PROTOCOL,
206
+ requestId: "request-own",
207
+ subject: { kind: "selector", selector: { type: "email", value: "you@example.com" } },
208
+ target: { origin: "http://127.0.0.1:3000" }
209
+ };
210
+ const fetchImpl = async () => assert.fail("JSKIT's development exchange must not run");
211
+ const exchange = async (call) => {
212
+ exchanged.push(call);
213
+ return call.operation === "logout"
214
+ ? { setCookie: ["key=; Max-Age=0; Path=/"] }
215
+ : { identity: { displayName: "You", email: "You@Example.com" }, setCookie: ["key=k; Path=/; HttpOnly", "session=s; Path=/"] };
216
+ };
217
+
218
+ // No development exchange is enabled, and none is needed.
219
+ const signedIn = await executeManagedPreviewIdentityRequest(request, { ...HOST_OPTIONS, fetchImpl, exchange });
220
+ assert.equal(signedIn.ok, true);
221
+ assert.equal(signedIn.protocol, HOST_PROTOCOL);
222
+ assert.equal(signedIn.requestId, "request-own");
223
+ assert.equal(signedIn.signedOut, false);
224
+ assert.deepEqual(signedIn.identity, { displayName: "You", email: "you@example.com", userId: "", username: "" });
225
+ assert.deepEqual(signedIn.setCookie, ["key=k; Path=/; HttpOnly", "session=s; Path=/"]);
226
+ assert.deepEqual(exchanged[0], {
227
+ operation: "login-as",
228
+ identity: { email: "you@example.com" },
229
+ targetOrigin: "http://127.0.0.1:3000",
230
+ fetchImpl
231
+ });
232
+
233
+ const signedOut = await executeManagedPreviewIdentityRequest({ ...request, operation: "logout", subject: undefined }, {
234
+ ...HOST_OPTIONS,
235
+ fetchImpl,
236
+ exchange
237
+ });
238
+ assert.equal(signedOut.ok, true);
239
+ assert.equal(signedOut.signedOut, true);
240
+ assert.equal(signedOut.identity, null);
241
+ assert.deepEqual(signedOut.setCookie, ["key=; Max-Age=0; Path=/"]);
242
+ assert.equal(exchanged[1].identity, null);
243
+
244
+ // The request is checked before the exchange runs.
245
+ const remote = await executeManagedPreviewIdentityRequest({ ...request, target: { origin: "https://example.com" } }, {
246
+ ...HOST_OPTIONS,
247
+ exchange: async () => assert.fail("the exchange must not run")
248
+ });
249
+ assert.equal(remote.code, "jskit_managed_preview_identity_target_invalid");
250
+ });
251
+
252
+ test("an application's own exchange refuses with its own error, and must return its cookies", async () => {
253
+ const request = {
254
+ operation: "login-as",
255
+ protocol: HOST_PROTOCOL,
256
+ requestId: "request-refused",
257
+ subject: { kind: "selector", selector: { type: "email", value: "someone@example.com" } },
258
+ target: { origin: "http://localhost:3000" }
259
+ };
260
+ const refused = await executeManagedPreviewIdentityRequest(request, {
261
+ ...HOST_OPTIONS,
262
+ exchange: async () => {
263
+ throw Object.assign(new Error("This application has one person."), { code: "one_person", statusCode: 404 });
264
+ }
265
+ });
266
+ assert.deepEqual(
267
+ [refused.ok, refused.code, refused.error, refused.statusCode, refused.setCookie],
268
+ [false, "one_person", "This application has one person.", 404, []]
269
+ );
270
+
271
+ const cookieless = await executeManagedPreviewIdentityRequest(request, {
272
+ ...HOST_OPTIONS,
273
+ exchange: async () => ({ identity: { email: "someone@example.com" } })
274
+ });
275
+ assert.equal(cookieless.ok, false);
276
+ assert.equal(cookieless.code, "jskit_managed_preview_identity_exchange_invalid");
277
+ });
278
+
279
+ test("the preview identity command hands an application's exchange the request it reads", async () => {
280
+ const written = [];
281
+ const exitCode = await runManagedPreviewIdentityCommand({
282
+ protocol: HOST_PROTOCOL,
283
+ stdin: [Buffer.from(JSON.stringify({
284
+ operation: "logout",
285
+ protocol: HOST_PROTOCOL,
286
+ requestId: "request-command",
287
+ target: { origin: "http://localhost:3000" }
288
+ }))],
289
+ stdout: { write: (text) => written.push(text) },
290
+ exchange: async ({ operation }) => ({ setCookie: [`${operation}=done; Path=/`] })
291
+ });
292
+ assert.equal(exitCode, 0);
293
+ const answer = JSON.parse(written.join(""));
294
+ assert.deepEqual([answer.ok, answer.signedOut, answer.setCookie], [true, true, ["logout=done; Path=/"]]);
295
+ });
@@ -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
+ });