@jskit-ai/auth-web 0.2.40 → 0.2.42

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 CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `POST /api/login/pass` reads its settings with `resolvePassSignInFromEnv` from `@jskit-ai/auth-pass/server`, a new dependency, instead of auth-core's removed `./server/passSignIn`. The route behaves as before.
6
+
7
+ - `POST /api/login/pass`, registered only while `AUTH_PASS_PUBLIC_KEY` is set: an issuer's page posts a one-time pass as the form field `pass`, and a pass that signs in sets the session cookies and answers 303 to `/`; a refused one answers 303 to `/auth/login` with `error=sign_in_unavailable`, `error_description` and `error_code`, which the sign-in page shows. It takes form bodies in a Fastify scope of its own, registered at boot, so the feature now requires `runtime.fastify`; it is public, takes no CSRF token (the pass authenticates it) and answers `Cache-Control: no-store`. Its rate limit is `config.auth.rateLimits.passSignIn` (20 a minute per address); one that no route limiter would enforce stops startup.
5
8
  - The package manifest no longer requires `runtime.actions`: its feature declares no actions, so since the kernel's 9646ecf21 it does not require the action catalogue, and the catalog's manifest check reported the requirement as one no server provider has.
6
9
  - `SecondFactorSettings` emits `codes-saved` when the person says they saved a new set of recovery codes (after setting an authenticator up, or replacing its codes), so a page that needs an authenticator before it goes on, such as a console's way in, goes on then; and its recovery codes step has **Download codes** beside **Copy codes**, which saves them as `recovery-codes.txt`, one a line (new message key `jskit.auth.secondFactor.codes.download`). `SecondFactorDialog` gives focus back to the element that had it when it opened, the control that sent the refused request, after the code as after a cancel: the dialog opens for a request and has no activator, so focus used to fall to the page's body.
7
10
  - **Second factor.** The routes `GET /api/second-factor`, `POST /api/second-factor/setup`, `/setup/confirm`, `/verify` and `/recovery-codes`, and `DELETE /api/second-factor` run the `auth.secondFactor.*` actions for the signed-in session, each with its own per-address limit in `AUTH_RATE_LIMITS` (`secondFactorSetup`, `secondFactorSetupConfirm` and `secondFactorVerify` 10 a minute, `secondFactorRecoveryCodes` and `secondFactorRemove` 5 a minute).
@@ -120,6 +120,8 @@ function branded(View) {
120
120
  const router = createRouter({
121
121
  history: createWebHistory(),
122
122
  routes: [
123
+ // The app's home, where a pass sign-in goes.
124
+ { path: "/", redirect: "/home" },
123
125
  { path: "/home", component: HomePage },
124
126
  { path: "/account/second-factor", component: SecondFactorPage },
125
127
  { path: "/console", component: ConsolePage },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-web",
3
- "version": "0.2.40",
3
+ "version": "0.2.42",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -28,10 +28,11 @@
28
28
  "./locales/en.json": "./locales/en.json"
29
29
  },
30
30
  "dependencies": {
31
+ "@jskit-ai/auth-pass": "0.1.0",
31
32
  "uqr": "0.1.3"
32
33
  },
33
34
  "peerDependencies": {
34
- "@jskit-ai/auth-core": "0.2.27",
35
+ "@jskit-ai/auth-core": "0.2.29",
35
36
  "@jskit-ai/http-runtime": "0.2.26",
36
37
  "@jskit-ai/kernel": "0.2.26",
37
38
  "@jskit-ai/shell-web": "0.2.36",
@@ -52,6 +53,7 @@
52
53
  "auth.service",
53
54
  "runtime.config",
54
55
  "runtime.env",
56
+ "runtime.fastify",
55
57
  "runtime.http"
56
58
  ]
57
59
  },
@@ -127,6 +129,11 @@
127
129
  "path": "/api/login/otp/verify",
128
130
  "summary": "Verify one-time email login code and create session"
129
131
  },
132
+ {
133
+ "method": "POST",
134
+ "path": "/api/login/pass",
135
+ "summary": "Sign in with a one-time signed pass posted as a form, when AUTH_PASS_PUBLIC_KEY is set"
136
+ },
130
137
  {
131
138
  "method": "POST",
132
139
  "path": "/api/logout",
@@ -1,5 +1,6 @@
1
1
  import { defineFeature } from "@jskit-ai/kernel/server/features";
2
2
  import { createAuthWeb } from "./authWeb.js";
3
+ import { registerPassSignInRoutes } from "./routes/passSignInRoutes.js";
3
4
  import { registerSecondFactorRoutes } from "./routes/secondFactorRoutes.js";
4
5
 
5
6
  const AuthWebFeature = defineFeature({
@@ -9,6 +10,7 @@ const AuthWebFeature = defineFeature({
9
10
  authService: "auth.service",
10
11
  config: "runtime.config",
11
12
  env: "runtime.env",
13
+ fastify: "runtime.fastify",
12
14
  http: "runtime.http"
13
15
  },
14
16
  provides: {
@@ -28,6 +30,19 @@ const AuthWebFeature = defineFeature({
28
30
  }
29
31
  registerSecondFactorRoutes(http.router, { rateLimits: authWeb.rateLimits });
30
32
  return { authWeb };
33
+ },
34
+ /**
35
+ * The pass sign-in route takes a form body, so it has a Fastify scope of its own, registered once runtime.http has
36
+ * started: the routes' rate limiter is registered by then, and limits it too.
37
+ * @param {object} capabilities
38
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeFastify} capabilities.fastify
39
+ * @param {{ outputs: { authWeb: import("./types.js").AuthWeb } }} lifecycle
40
+ */
41
+ async boot({ fastify }, { outputs }) {
42
+ const { authWeb } = outputs;
43
+ if (authWeb.passSignIn) {
44
+ await registerPassSignInRoutes(fastify, { service: authWeb.service, rateLimit: authWeb.rateLimits.passSignIn });
45
+ }
31
46
  }
32
47
  });
33
48
 
@@ -12,6 +12,7 @@ const DEFAULT_AUTH_RATE_LIMITS = Object.freeze({
12
12
  login: Object.freeze({ max: 10, timeWindow: "1 minute" }),
13
13
  loginOtpRequest: Object.freeze({ max: 10, timeWindow: "1 minute" }),
14
14
  loginOtpVerify: Object.freeze({ max: 10, timeWindow: "1 minute" }),
15
+ passSignIn: Object.freeze({ max: 20, timeWindow: "1 minute" }),
15
16
  oauthStart: Object.freeze({ max: 20, timeWindow: "1 minute" }),
16
17
  oauthComplete: Object.freeze({ max: 20, timeWindow: "1 minute" }),
17
18
  devLoginAs: Object.freeze({ max: 30, timeWindow: "1 minute" }),
@@ -1,4 +1,5 @@
1
1
  import { isDevAuthBootstrapEnabled, resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth-core/server/devAuth";
2
+ import { resolvePassSignInFromEnv } from "@jskit-ai/auth-pass/server";
2
3
  import { resolveAuthRateLimits } from "./authRateLimits.js";
3
4
  import { AuthController } from "./controllers/AuthController.js";
4
5
  import { buildRoutes } from "./routes/authRoutes.js";
@@ -6,9 +7,10 @@ import { AuthWebService } from "./services/AuthWebService.js";
6
7
 
7
8
  /**
8
9
  * The auth web routes over the installed auth service: their service,
9
- * controller and route table, and every auth route's rate limit. Routes are
10
- * registered at setup, before the deferred auth service exists, so dev
11
- * login-as is read from the env with the predicate the auth providers use.
10
+ * controller and route table, every auth route's rate limit, and whether
11
+ * one-time pass sign-in is on. Routes are registered at setup, before the
12
+ * deferred auth service exists, so dev login-as and pass sign-in are read from
13
+ * the env with the predicates the auth providers use.
12
14
  * @param {object} dependencies
13
15
  * @param {import("@jskit-ai/auth-core/server/types").AuthService} dependencies.authService
14
16
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
@@ -29,7 +31,9 @@ function createAuthWeb({ authService, env, config }) {
29
31
  controller,
30
32
  routes: Object.freeze(routes),
31
33
  service,
32
- rateLimits
34
+ rateLimits,
35
+ // AUTH_PASS_PUBLIC_KEY is set: POST /api/login/pass takes one-time signed passes.
36
+ passSignIn: resolvePassSignInFromEnv(env) !== null
33
37
  });
34
38
  }
35
39
 
@@ -0,0 +1,56 @@
1
+ import { AUTH_PATHS } from "@jskit-ai/auth-core/shared/authPaths";
2
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
3
+
4
+ const FORM_CONTENT_TYPE = "application/x-www-form-urlencoded";
5
+ const MAX_FORM_BYTES = 8 * 1024;
6
+
7
+ function parseForm(_request, body, done) {
8
+ done(null, Object.fromEntries(new URLSearchParams(String(body || ""))));
9
+ }
10
+
11
+ /**
12
+ * Registers `POST /api/login/pass`, where the issuer's page makes the browser POST a one-time signed pass as the form
13
+ * field `pass` (a POST, so the pass never sits in an address, a history or a log). The pass authenticates the request,
14
+ * so the route is public and takes no CSRF token: the page that posts it is on the issuer's site. A pass that signs
15
+ * someone in sets the session cookies and goes to the app's home; a refused one goes to the sign-in page, which shows
16
+ * the reason. It bypasses actions, as a provider's callback does, and has its own Fastify scope, so the form parser it
17
+ * needs applies to it alone.
18
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeFastify} fastify
19
+ * @param {object} dependencies
20
+ * @param {import("../services/AuthWebService.js").AuthWebService} dependencies.service
21
+ * @param {{ max: number, timeWindow: string | number } | null} dependencies.rateLimit The `passSignIn` auth rate limit.
22
+ */
23
+ async function registerPassSignInRoutes(fastify, { service, rateLimit }) {
24
+ // runtime.http registers the limiter only while some route of its own has a limit; without it this one would be
25
+ // silently unlimited.
26
+ if (rateLimit && !fastify.hasDecorator("rateLimit")) {
27
+ throw new Error("config.auth.rateLimits.passSignIn limits one-time pass sign-in, and no route rate limiter is registered because no other route has a limit. Give another auth route a limit, or set passSignIn to false.");
28
+ }
29
+ await fastify.register(async (scope) => {
30
+ scope.addContentTypeParser(FORM_CONTENT_TYPE, { parseAs: "string", bodyLimit: MAX_FORM_BYTES }, parseForm);
31
+ const config = { authPolicy: "public", csrfProtection: false, ...(rateLimit ? { rateLimit } : {}) };
32
+ scope.post(AUTH_PATHS.LOGIN_PASS, { config }, async function signInWithPass(request, reply) {
33
+ reply.header("Cache-Control", "no-store");
34
+ const form = /** @type {{ pass?: unknown } | undefined} */ (request.body);
35
+ let result;
36
+ try {
37
+ result = await service.signInWithPass({ pass: String(form?.pass ?? "") });
38
+ } catch (error) {
39
+ if (!(error instanceof AppError) || error.statusCode >= 500) {
40
+ throw error;
41
+ }
42
+ request.log.warn({ code: error.code }, "A one-time sign-in pass was refused.");
43
+ const explained = new URLSearchParams({
44
+ error: "sign_in_unavailable",
45
+ error_description: error.message,
46
+ error_code: String(error.code)
47
+ });
48
+ return reply.redirect(`/auth/login?${explained}`, 303);
49
+ }
50
+ service.writeSessionCookies(reply, result.session);
51
+ return reply.redirect("/", 303);
52
+ });
53
+ });
54
+ }
55
+
56
+ export { registerPassSignInRoutes };
@@ -1,3 +1,4 @@
1
+ import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
1
2
  import { normalizeAuthCapabilities } from "@jskit-ai/auth-core/shared/authCapabilities";
2
3
  import { AUTH_ACTION_IDS } from "../constants/authActionIds.js";
3
4
 
@@ -120,6 +121,19 @@ class AuthWebService {
120
121
  });
121
122
  }
122
123
 
124
+ /**
125
+ * Signs in the account a one-time signed pass names; a provider without pass sign-in refuses it as unsupported.
126
+ * @param {{ pass: string }} input
127
+ */
128
+ async signInWithPass(input) {
129
+ const { authService } = this;
130
+ // readable-check: allow method-probe - optional operation: signInWithPass is an optional auth.service operation
131
+ if (typeof authService.signInWithPass !== "function") {
132
+ return throwUnsupportedAuthOperation("signInWithPass");
133
+ }
134
+ return authService.signInWithPass(input);
135
+ }
136
+
123
137
  writeSessionCookies(reply, session) {
124
138
  if (session && reply) {
125
139
  this.authService.writeSessionCookies(reply, session);
@@ -0,0 +1,174 @@
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 { AuthExtensionsProvider } from "@jskit-ai/auth-core/server/providers/AuthExtensionsProvider";
13
+ import { AuthFeature } from "@jskit-ai/auth-core/server/providers/AuthFeature";
14
+ import { AuthPolicyProvider } from "@jskit-ai/auth-core/server/providers/AuthPolicyProvider";
15
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
16
+ import { HttpProvider } from "@jskit-ai/kernel/server/http";
17
+ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
18
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
19
+ import { createCapabilityRuntime } from "@jskit-ai/kernel/shared/capabilities";
20
+ import { createLocalAuthService, createLocalFileBackend } from "../../auth-provider-local-core/src/server/lib/index.js";
21
+ import { localServiceOptions } from "../../auth-provider-local-core/test-support/localService.js";
22
+ import { createPassIssuer, passIdentityByEmail, passwordlessAccount } from "../../auth-provider-local-core/test-support/passSignInScenario.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 and app, served on http://localhost:PORT, with the real auth routes, auth policy and local
32
+ // auth behind its /api, trusting a pass issuer whose page is on 127.0.0.1, another site. The issuer's page posts a
33
+ // pass to the app's pass sign-in route as a form, as an issuer opening the app for its person does. Cookies are
34
+ // SameSite=Strict, the setting under which a cross-site arrival carries the fewest.
35
+ const RUN = process.env.JSKIT_AUTH_WEB_BROWSER_INTEGRATION === "1";
36
+ const options = { skip: !RUN, timeout: 120_000 };
37
+ const STRICT = Object.freeze({ AUTH_COOKIE_SAME_SITE: "strict" });
38
+ const SESSION_COOKIES = ["jskit_local_access_token", "jskit_local_refresh_token"];
39
+
40
+ let stack = null;
41
+ const cleanups = [];
42
+
43
+ before(async () => {
44
+ if (!RUN) return;
45
+ const vitePort = await reservePort();
46
+ const appUrl = `http://localhost:${vitePort}`;
47
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-web-pass-"));
48
+ cleanups.push(() => fs.rm(storeDir, { recursive: true, force: true }));
49
+ const issuer = createPassIssuer();
50
+ const env = { ...issuer.env, ...STRICT };
51
+ const backend = createLocalFileBackend({ storeDir });
52
+ await backend.withTransaction((tx) => tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" })));
53
+ const authService = createLocalAuthService({
54
+ ...localServiceOptions({ env: { APP_PUBLIC_URL: appUrl, ...env } }),
55
+ backend,
56
+ passIdentity: passIdentityByEmail(backend)
57
+ });
58
+
59
+ const api = Fastify();
60
+ cleanups.push(() => api.close());
61
+ const runtime = createCapabilityRuntime({
62
+ inputs: {
63
+ "auth.service": authService,
64
+ "runtime.config": {},
65
+ "runtime.env": { NODE_ENV: "test", ...env },
66
+ "runtime.fastify": api,
67
+ "runtime.logger": silentLogger
68
+ },
69
+ providers: [EventProvider, ActionProvider, HttpProvider, AuthExtensionsProvider, AuthFeature, AuthPolicyProvider,
70
+ AuthWebFeature]
71
+ });
72
+ await runtime.start();
73
+ cleanups.push(() => runtime.shutdown());
74
+ await api.listen({ host: "127.0.0.1", port: 0 });
75
+
76
+ const vite = await startViteFixture({
77
+ fixtureRoot: fileURLToPath(new URL("../fixtures/sign-in/", import.meta.url)),
78
+ port: vitePort,
79
+ env: { JSKIT_AUTH_WEB_FIXTURE_API_SERVER: `http://127.0.0.1:${api.server.address().port}` }
80
+ });
81
+ cleanups.push(() => stopProcess(vite));
82
+ const browser = await chromium.launch(createChromiumLaunchOptions());
83
+ cleanups.push(() => browser.close());
84
+ stack = { appUrl, issuer, browser };
85
+ });
86
+
87
+ after(async () => {
88
+ for (const cleanup of cleanups.reverse()) {
89
+ await cleanup();
90
+ }
91
+ });
92
+
93
+ function cookieNames(header) {
94
+ return String(header || "").split(";").map((pair) => pair.split("=")[0].trim()).filter(Boolean).sort();
95
+ }
96
+
97
+ /** The issuer's page on 127.0.0.1, which posts the pass to the app as soon as it loads. */
98
+ async function startIssuerPage(t, pass) {
99
+ const server = http.createServer((_request, response) => {
100
+ response.setHeader("content-type", "text/html; charset=utf-8");
101
+ response.end(`<!doctype html><title>Opening the app</title>
102
+ <form method="post" action="${stack.appUrl}/api/login/pass"><input type="hidden" name="pass" value="${pass}"></form>
103
+ <script>document.forms[0].submit();</script>`);
104
+ });
105
+ server.listen(0, "127.0.0.1");
106
+ await once(server, "listening");
107
+ t.after(async () => {
108
+ server.closeAllConnections();
109
+ server.close();
110
+ await once(server, "close");
111
+ });
112
+ return `http://127.0.0.1:${server.address().port}/`;
113
+ }
114
+
115
+ /** A browser of its own, which records every page it loads with the method and headers it sent. */
116
+ async function openBrowser(t) {
117
+ const context = await stack.browser.newContext();
118
+ t.after(() => context.close());
119
+ const page = await context.newPage();
120
+ page.setDefaultTimeout(15_000);
121
+ page.setDefaultNavigationTimeout(60_000);
122
+ const documents = [];
123
+ const errors = [];
124
+ page.on("pageerror", (error) => errors.push(error.message));
125
+ page.on("request", (request) => {
126
+ if (request.resourceType() === "document") {
127
+ documents.push({ url: new URL(request.url()), method: request.method(), headers: request.allHeaders() });
128
+ }
129
+ });
130
+ return { context, page, documents, errors };
131
+ }
132
+
133
+ test("a pass the issuer's page posts from another site signs its person in on the app, with no password", options, async (t) => {
134
+ const pass = stack.issuer.pass("ada@example.com");
135
+ const issuerPage = await startIssuerPage(t, pass);
136
+ const { context, page, documents, errors } = await openBrowser(t);
137
+
138
+ await page.goto(issuerPage);
139
+ await expect(page.getByTestId("home")).toHaveText("Signed in: true");
140
+ assert.equal(new URL(page.url()).pathname, "/home");
141
+
142
+ // The pass arrived as a cross-site form post, carrying none of the app's cookies, and set the session's.
143
+ const posts = documents.filter(({ url, method }) => method === "POST" && url.pathname === "/api/login/pass");
144
+ assert.equal(posts.length, 1);
145
+ const postHeaders = await posts[0].headers;
146
+ assert.equal(postHeaders["sec-fetch-site"], "cross-site");
147
+ assert.deepEqual(cookieNames(postHeaders.cookie), []);
148
+ const kept = (await context.cookies(stack.appUrl)).filter(({ name }) => SESSION_COOKIES.includes(name));
149
+ assert.deepEqual(kept.map(({ name, sameSite, httpOnly }) => [name, sameSite, httpOnly]).sort(),
150
+ SESSION_COOKIES.map((name) => [name, "Strict", true]));
151
+ assert.deepEqual(errors, []);
152
+ });
153
+
154
+ test("the same pass posted again, from another browser, and an expired pass land on the sign-in page saying why", options, async (t) => {
155
+ const pass = stack.issuer.pass("ada@example.com");
156
+ const first = await openBrowser(t);
157
+ await first.page.goto(await startIssuerPage(t, pass));
158
+ await expect(first.page.getByTestId("home")).toHaveText("Signed in: true");
159
+
160
+ // The sign-in page reports why to the shell, whose banner shows it (the fixture's shell keeps the reports).
161
+ const { context, page, errors } = await openBrowser(t);
162
+ const lastReport = () => page.evaluate(() => window.authFixture.reports.at(-1)?.message);
163
+ await page.goto(await startIssuerPage(t, pass));
164
+ await page.waitForURL((url) => url.pathname === "/auth/login");
165
+ await expect.poll(lastReport).toBe("This sign-in pass was already used. Open the app again from where you came.");
166
+
167
+ await page.goto(await startIssuerPage(t, stack.issuer.pass("ada@example.com", { now: Date.now() - 91_000 })));
168
+ await page.waitForURL((url) => url.pathname === "/auth/login");
169
+ await expect.poll(lastReport).toBe("This sign-in pass has expired. Open the app again from where you came.");
170
+
171
+ const signedIn = (await context.cookies(stack.appUrl)).filter(({ name }) => SESSION_COOKIES.includes(name));
172
+ assert.deepEqual(signedIn, []);
173
+ assert.deepEqual(errors, []);
174
+ });
@@ -0,0 +1,132 @@
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 } from "@jskit-ai/kernel/shared/capabilities";
15
+ import { createLocalAuthService, createLocalFileBackend } from "../../auth-provider-local-core/src/server/lib/index.js";
16
+ import { localServiceOptions } from "../../auth-provider-local-core/test-support/localService.js";
17
+ import { createPassIssuer, passIdentityByEmail, passwordlessAccount } from "../../auth-provider-local-core/test-support/passSignInScenario.js";
18
+ import { AuthWebFeature } from "../src/server/AuthWebFeature.js";
19
+ import { DEFAULT_AUTH_RATE_LIMITS } from "../src/server/authRateLimits.js";
20
+
21
+ /**
22
+ * The auth routes and policy over local auth in a store of the test's own, trusting the issuer's passes when `env`
23
+ * carries its key.
24
+ * @param {import("node:test").TestContext} t
25
+ * @param {{ env?: Record<string, string>, config?: object }} [options]
26
+ */
27
+ async function startApp(t, { env = {}, config = {} } = {}) {
28
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-web-pass-"));
29
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
30
+ const backend = createLocalFileBackend({ storeDir });
31
+ await backend.withTransaction((tx) => tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" })));
32
+ const authService = createLocalAuthService({ ...localServiceOptions({ env }), backend, passIdentity: passIdentityByEmail(backend) });
33
+ const app = Fastify();
34
+ const runtime = createCapabilityRuntime({
35
+ inputs: {
36
+ "auth.service": authService,
37
+ "runtime.config": config,
38
+ "runtime.env": { NODE_ENV: "test", ...env },
39
+ "runtime.fastify": app,
40
+ "runtime.logger": silentLogger
41
+ },
42
+ providers: [EventProvider, ActionProvider, HttpProvider, AuthExtensionsProvider, AuthFeature, AuthPolicyProvider, AuthWebFeature]
43
+ });
44
+ t.after(() => app.close());
45
+ await runtime.start();
46
+ t.after(() => runtime.shutdown());
47
+ return app;
48
+ }
49
+
50
+ /** The browser's form post of a pass, from the issuer's page, with no CSRF token and no cookies. */
51
+ function postPass(app, pass, remoteAddress = "203.0.113.7") {
52
+ return app.inject({
53
+ method: "POST",
54
+ url: "/api/login/pass",
55
+ remoteAddress,
56
+ headers: { "content-type": "application/x-www-form-urlencoded" },
57
+ payload: new URLSearchParams({ pass }).toString()
58
+ });
59
+ }
60
+
61
+ /** Checks a refused pass went to the sign-in page with its reason, and signed nobody in. */
62
+ function sentToSignIn(response, code) {
63
+ assert.equal(response.statusCode, 303, response.body);
64
+ const location = new URL(response.headers.location, "http://app.test");
65
+ assert.equal(location.pathname, "/auth/login");
66
+ assert.equal(location.searchParams.get("error"), "sign_in_unavailable");
67
+ assert.equal(location.searchParams.get("error_code"), code);
68
+ assert.ok(location.searchParams.get("error_description").length > 0);
69
+ assert.deepEqual(response.cookies, []);
70
+ }
71
+
72
+ test("a pass posted as a form signs its person in and goes home; posted again, it goes to the sign-in page as replayed", async (t) => {
73
+ const issuer = createPassIssuer();
74
+ const app = await startApp(t, { env: issuer.env });
75
+ const pass = issuer.pass("ada@example.com");
76
+
77
+ const signedIn = await postPass(app, pass);
78
+ assert.equal(signedIn.statusCode, 303, signedIn.body);
79
+ assert.equal(signedIn.headers.location, "/");
80
+ assert.equal(signedIn.headers["cache-control"], "no-store");
81
+ const cookies = Object.fromEntries(signedIn.cookies.map((cookie) => [cookie.name, cookie.value]));
82
+ assert.deepEqual(Object.keys(cookies).sort(), ["jskit_local_access_token", "jskit_local_refresh_token"]);
83
+ const session = await app.inject({ method: "GET", url: "/api/session", cookies });
84
+ assert.equal(session.json().authenticated, true);
85
+ assert.equal(session.json().email, "ada@example.com");
86
+
87
+ sentToSignIn(await postPass(app, pass), "auth.pass.replayed");
88
+ sentToSignIn(await postPass(app, issuer.pass("nobody@example.com")), "auth.pass.unmapped");
89
+ sentToSignIn(await postPass(app, issuer.pass("ada@example.com", { resource: "machine-8" })), "auth.pass.wrongResource");
90
+ sentToSignIn(await postPass(app, issuer.pass("ada@example.com", { now: Date.now() - 91_000 })), "auth.pass.expired");
91
+ sentToSignIn(await app.inject({ method: "POST", url: "/api/login/pass", remoteAddress: "203.0.113.8" }), "auth.pass.malformed");
92
+ });
93
+
94
+ test("one address may post 20 passes a minute; the next is refused with 429 and Retry-After", async (t) => {
95
+ const issuer = createPassIssuer();
96
+ const app = await startApp(t, { env: issuer.env });
97
+ assert.deepEqual(DEFAULT_AUTH_RATE_LIMITS.passSignIn, { max: 20, timeWindow: "1 minute" });
98
+ for (let attempt = 0; attempt < 20; attempt += 1) {
99
+ sentToSignIn(await postPass(app, "not a pass"), "auth.pass.malformed");
100
+ }
101
+ const limited = await postPass(app, issuer.pass("ada@example.com"));
102
+ assert.equal(limited.statusCode, 429, limited.body);
103
+ assert.equal(limited.json().code, "kernel.http.rateLimited");
104
+ assert.ok(Number(limited.headers["retry-after"]) > 0);
105
+ // Another address is counted on its own.
106
+ assert.equal((await postPass(app, issuer.pass("ada@example.com"), "203.0.113.9")).headers.location, "/");
107
+ });
108
+
109
+ test("without AUTH_PASS_PUBLIC_KEY the app has no pass sign-in route", async (t) => {
110
+ const issuer = createPassIssuer();
111
+ const app = await startApp(t);
112
+ assert.equal(app.hasRoute({ method: "POST", url: "/api/login/pass" }), false);
113
+ // The post meets the policy every unknown API post meets, and signs nobody in.
114
+ const posted = await postPass(app, issuer.pass("ada@example.com"));
115
+ assert.equal(posted.statusCode, 403, posted.body);
116
+ assert.deepEqual(posted.cookies, []);
117
+
118
+ const withPasses = await startApp(t, { env: issuer.env });
119
+ assert.equal(withPasses.hasRoute({ method: "POST", url: "/api/login/pass" }), true);
120
+ });
121
+
122
+ test("a pass sign-in limit with no limiter to enforce it stops startup", async (t) => {
123
+ const issuer = createPassIssuer();
124
+ const everyOtherLimitOff = Object.fromEntries(Object.keys(DEFAULT_AUTH_RATE_LIMITS)
125
+ .filter((name) => name !== "passSignIn")
126
+ .map((name) => [name, false]));
127
+ await assert.rejects(startApp(t, { env: issuer.env, config: { auth: { rateLimits: everyOtherLimitOff } } }),
128
+ (error) => /config\.auth\.rateLimits\.passSignIn limits one-time pass sign-in, and no route rate limiter is registered/u
129
+ .test(String(error.details?.cause?.message || error.message)));
130
+ const unlimited = await startApp(t, { env: issuer.env, config: { auth: { rateLimits: { ...everyOtherLimitOff, passSignIn: false } } } });
131
+ assert.equal((await postPass(unlimited, issuer.pass("ada@example.com"))).headers.location, "/");
132
+ });