@jskit-ai/auth-provider-local-core 0.2.26 → 0.2.27

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,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `AUTH_COOKIE_SAME_SITE=strict` makes every local auth cookie SameSite=Strict, and its clearing: the access, refresh, recovery and OAuth attempt cookies. Unset, blank or `lax` keeps them Lax, as before; any other value stops startup, naming the setting. OAuth sign-in works under `strict`: the provider's cross-site return only loads the login page, and the attempt cookie is read by that page's same-origin `POST /api/oauth/complete`. `resolveLocalAuthConfig()` returns `cookieSameSite`.
6
+
5
7
  - **Second factor: authenticator-app codes (TOTP, RFC 6238) with recovery codes**, one per account, in the file backend and through the backend contract. Setting up shows the secret once (as text and in an `otpauth://` address for a QR code, whose issuer is `APP_PUBLIC_URL`'s host) and a first code confirms it, answering ten single-use recovery codes once. A code is six digits of a 30-second step, accepted within one step either side of the server's clock and only once: no code of an accepted step or an earlier one passes again. The secret is sealed with AES-256-GCM, bound to its account, under a key derived from `AUTH_LOCAL_SECOND_FACTOR_KEY`; recovery codes are kept as keyed hashes. An accepted code or recovery code marks the request's session with the time (`secondFactorAt`, which `authenticate` returns for the auth policy); removing the authenticator clears it from every session of the account. Wrong codes make the account wait as wrong passwords do (five, then 30 seconds doubling to an hour), refused with 429 `auth.local.secondFactor.locked`. New refusals, each with its message key under `jskit.auth.local.secondFactor`: `notSetUp`, `alreadySetUp`, `setupNotStarted`, `proofRequired`, `codeInvalid`, `codeUsed`, `recoveryCodeInvalid` and `locked`.
6
8
  - Every second-factor change and failed attempt (setup started or confirmed, verified, failed with its reason, recovery codes replaced, removed, reset) is an event, with the account id, the request's address and the time and never a secret or a code, for the optional `auth.local.second-factor-events` capability (`AuthLocalSecondFactorEvent`), an application's audit log; without one, local auth logs each event. `listSecondFactors({ userIds })` and `resetSecondFactor({ userId, byUserId })` serve an application's own owner screens.
7
9
  - Upgrading: a production server has a second factor only with `AUTH_LOCAL_SECOND_FACTOR_KEY` set (at least 32 characters, which then also requires `APP_PUBLIC_URL`); outside production the session secret stands in for it. Keep the key: a factor sealed under one key does not open under another, and verifying one then fails as a server error. A custom `auth.local.backend` implements the `secondFactors` collection (`find`, `findMany`, `save`, `delete`) and `sessions.markSecondFactorProved` / `sessions.clearSecondFactorForUser`, and keeps a session's `secondFactorAt`; the file backend keeps the factors in `second-factors.passwd`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.26",
3
+ "version": "0.2.27",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -69,7 +69,7 @@
69
69
  }
70
70
  },
71
71
  "peerDependencies": {
72
- "@jskit-ai/auth-core": "0.2.22",
72
+ "@jskit-ai/auth-core": "0.2.23",
73
73
  "@jskit-ai/kernel": "0.2.22"
74
74
  }
75
75
  }
@@ -4,6 +4,7 @@ import { randomBytes } from "node:crypto";
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
6
  import { AUTH_PASSWORD_MIN_LENGTH } from "@jskit-ai/auth-core/shared/authConstraints";
7
+ import { resolveAuthCookieSameSite } from "@jskit-ai/auth-core/server/utils";
7
8
  import { parsePositiveInteger } from "@jskit-ai/kernel/server/runtime";
8
9
  import { assertDevelopmentOnlySettings } from "@jskit-ai/kernel/server/runtime/runtimeMode";
9
10
  import { SETUP_CODE_ENV, SETUP_CODE_MIN_CHARACTERS, normalizedSetupCode } from "./firstAccountSetup.js";
@@ -216,6 +217,8 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
216
217
  return Object.freeze({
217
218
  storeDir,
218
219
  isProduction,
220
+ // The SameSite of every local auth cookie: AUTH_COOKIE_SAME_SITE, "lax" unless set to "strict".
221
+ cookieSameSite: resolveAuthCookieSameSite(env),
219
222
  appPublicUrl,
220
223
  oauthProviders,
221
224
  oauthEnabled,
@@ -82,15 +82,18 @@ function createLocalOAuthFlows({
82
82
  return beginOAuthAttempt(requireOAuthProvider(input.provider), { intent: "link", userId, returnTo: input.returnTo });
83
83
  }
84
84
 
85
+ // The attempt cookie takes AUTH_COOKIE_SAME_SITE as the session cookies do, strict too: the provider's cross-site
86
+ // return only loads the login page, and the cookie is read by that page's same-origin POST /api/oauth/complete,
87
+ // which carries Strict cookies.
85
88
  function writeOAuthStartCookies(reply, result) {
86
89
  if (reply && result?.attempt) {
87
- reply.setCookie(OAUTH_ATTEMPT_COOKIE, result.attempt, cookieOptions(isProduction, OAUTH_ATTEMPT_TTL_SECONDS));
90
+ reply.setCookie(OAUTH_ATTEMPT_COOKIE, result.attempt, cookieOptions(config, OAUTH_ATTEMPT_TTL_SECONDS));
88
91
  }
89
92
  }
90
93
 
91
94
  function clearOAuthStartCookies(reply) {
92
95
  if (reply) {
93
- reply.clearCookie(OAUTH_ATTEMPT_COOKIE, cookieOptions(isProduction, 0));
96
+ reply.clearCookie(OAUTH_ATTEMPT_COOKIE, cookieOptions(config, 0));
94
97
  }
95
98
  }
96
99
 
@@ -26,21 +26,25 @@ function unauthenticatedAuthResult(clearSession = false) {
26
26
  };
27
27
  }
28
28
 
29
- function cookieOptions(isProduction, maxAge) {
29
+ /**
30
+ * A local auth cookie: httpOnly at Path=/, Secure in production, with the application's SameSite
31
+ * (AUTH_COOKIE_SAME_SITE).
32
+ * @param {Pick<import("../types.js").AuthLocalConfig, "isProduction" | "cookieSameSite">} config
33
+ * @param {number} maxAge
34
+ */
35
+ function cookieOptions({ isProduction, cookieSameSite }, maxAge) {
30
36
  return {
31
37
  path: "/",
32
38
  httpOnly: true,
33
- sameSite: "lax",
39
+ sameSite: cookieSameSite,
34
40
  secure: isProduction,
35
41
  maxAge
36
42
  };
37
43
  }
38
44
 
39
- function clearCookieOptions(isProduction) {
40
- return [
41
- { path: "/", httpOnly: true, sameSite: "lax", secure: isProduction, maxAge: 0 },
42
- { path: "/api", httpOnly: true, sameSite: "lax", secure: isProduction, maxAge: 0 }
43
- ];
45
+ /** @param {Pick<import("../types.js").AuthLocalConfig, "isProduction" | "cookieSameSite">} config */
46
+ function clearCookieOptions(config) {
47
+ return [cookieOptions(config, 0), { ...cookieOptions(config, 0), path: "/api" }];
44
48
  }
45
49
 
46
50
  function buildAccessToken({ user, session, secret, ttlSeconds = ACCESS_TTL_SECONDS }) {
@@ -292,11 +296,11 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
292
296
  reply.setCookie(
293
297
  isRecoverySession ? RECOVERY_TOKEN_COOKIE : ACCESS_TOKEN_COOKIE,
294
298
  accessToken,
295
- cookieOptions(isProduction, accessMaxAge)
299
+ cookieOptions(config, accessMaxAge)
296
300
  );
297
301
  }
298
302
  if (refreshToken) {
299
- reply.setCookie(REFRESH_TOKEN_COOKIE, refreshToken, cookieOptions(isProduction, refreshMaxAge));
303
+ reply.setCookie(REFRESH_TOKEN_COOKIE, refreshToken, cookieOptions(config, refreshMaxAge));
300
304
  }
301
305
  }
302
306
 
@@ -304,7 +308,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
304
308
  if (!reply) {
305
309
  return;
306
310
  }
307
- for (const options of clearCookieOptions(isProduction)) {
311
+ for (const options of clearCookieOptions(config)) {
308
312
  // A __Host- cookie only exists at Path=/.
309
313
  if (options.path === "/" || !isProduction) {
310
314
  reply.clearCookie(ACCESS_TOKEN_COOKIE, options);
@@ -0,0 +1,94 @@
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 { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
7
+ import { createLocalFileBackend } from "../src/server/lib/index.js";
8
+ import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
9
+ import { approveAtProvider, createService, oidcProviderEntry, startOidcProvider } from "../test-support/oauthHarness.js";
10
+
11
+ const PASSWORD = "correct horse battery staple";
12
+
13
+ /**
14
+ * Every cookie local auth sets and clears in one person's sign-in, password recovery, sign-out and Google sign-in,
15
+ * as [name, "set" or "cleared", path, sameSite].
16
+ * @param {import("node:test").TestContext} t
17
+ * @param {Record<string, string>} env
18
+ */
19
+ async function cookiesOfEveryFlow(t, env) {
20
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-same-site-"));
21
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
22
+ const issuer = await startOidcProvider();
23
+ t.after(() => issuer.close());
24
+ const service = createService({
25
+ backend: createLocalFileBackend({ storeDir }),
26
+ oauthProviders: [oidcProviderEntry(issuer)],
27
+ profileProjector: noAppProfiles,
28
+ env
29
+ });
30
+ const written = [];
31
+ const reply = {
32
+ setCookie: (name, _value, options) => written.push([name, "set", options.path, options.sameSite]),
33
+ clearCookie: (name, options) => written.push([name, "cleared", options.path, options.sameSite])
34
+ };
35
+
36
+ service.writeSessionCookies(reply, (await service.register({ email: "ada@example.com", password: PASSWORD })).session);
37
+ const { recoveryUrl } = await service.requestPasswordReset({ email: "ada@example.com" });
38
+ const recovery = await service.completePasswordRecovery({
39
+ code: new URL(recoveryUrl).searchParams.get("token"),
40
+ type: "recovery"
41
+ });
42
+ service.writeSessionCookies(reply, recovery.session);
43
+ service.clearSessionCookies(reply);
44
+
45
+ const { started, input, request } = await approveAtProvider(service);
46
+ service.writeOAuthStartCookies(reply, started);
47
+ const signedIn = await service.oauthComplete(input, request);
48
+ service.clearOAuthStartCookies(reply);
49
+ service.writeSessionCookies(reply, signedIn.session);
50
+ return written;
51
+ }
52
+
53
+ /** What cookiesOfEveryFlow answers when every cookie has the SameSite given. */
54
+ function everyCookie(sameSite) {
55
+ const cleared = (pathName) => ["access", "refresh", "recovery"]
56
+ .map((kind) => [`jskit_local_${kind}_token`, "cleared", pathName, sameSite]);
57
+ return [
58
+ ["jskit_local_access_token", "set", "/", sameSite],
59
+ ["jskit_local_refresh_token", "set", "/", sameSite],
60
+ ["jskit_local_recovery_token", "set", "/", sameSite],
61
+ ["jskit_local_refresh_token", "set", "/", sameSite],
62
+ ...cleared("/"),
63
+ ...cleared("/api"),
64
+ ["jskit_local_oauth_attempt", "set", "/", sameSite],
65
+ ["jskit_local_oauth_attempt", "cleared", "/", sameSite],
66
+ ["jskit_local_access_token", "set", "/", sameSite],
67
+ ["jskit_local_refresh_token", "set", "/", sameSite]
68
+ ];
69
+ }
70
+
71
+ test("without AUTH_COOKIE_SAME_SITE every local auth cookie, the OAuth attempt's included, is SameSite=Lax", async (t) => {
72
+ assert.deepEqual(await cookiesOfEveryFlow(t, {}), everyCookie("lax"));
73
+ assert.deepEqual(await cookiesOfEveryFlow(t, { AUTH_COOKIE_SAME_SITE: " " }), everyCookie("lax"));
74
+ });
75
+
76
+ test("AUTH_COOKIE_SAME_SITE=strict makes every local auth cookie and its clearing SameSite=Strict", async (t) => {
77
+ assert.deepEqual(await cookiesOfEveryFlow(t, { AUTH_COOKIE_SAME_SITE: "strict" }), everyCookie("strict"));
78
+ });
79
+
80
+ test("an AUTH_COOKIE_SAME_SITE other than lax or strict stops local auth's startup", () => {
81
+ const resolve = (value) => resolveLocalAuthConfig({
82
+ appRoot: os.tmpdir(),
83
+ env: { NODE_ENV: "test", AUTH_LOCAL_SESSION_SECRET: "test-session-secret", AUTH_COOKIE_SAME_SITE: value },
84
+ fileBackend: false,
85
+ emailRecovery: false
86
+ });
87
+ assert.equal(resolve("Lax").cookieSameSite, "lax");
88
+ assert.equal(resolve(" Strict ").cookieSameSite, "strict");
89
+ for (const value of ["none", "None", "secure", "strict;", "lax strict"]) {
90
+ assert.throws(() => resolve(value), {
91
+ message: `AUTH_COOKIE_SAME_SITE must be lax or strict, not "${value}".`
92
+ });
93
+ }
94
+ });
@@ -10,14 +10,19 @@ const REDIRECT_URI = `${APP_URL}/auth/login`;
10
10
  const ATTEMPT_COOKIE = "jskit_local_oauth_attempt";
11
11
  const CLIENT = Object.freeze({ clientId: "local-app", clientSecret: "local-app-secret-0123456789abcdef" });
12
12
 
13
- /** A local OpenID Connect provider (Google or Microsoft stand-in) with this app as its static client. */
14
- async function startOidcProvider({ account } = {}) {
13
+ /**
14
+ * A local OpenID Connect provider (Google or Microsoft stand-in) with this app as its static client.
15
+ * @param {{ account?: object, appUrl?: string, consentPage?: boolean }} [options] `appUrl` is the APP_PUBLIC_URL of an
16
+ * app served elsewhere; `consentPage` is the mock issuer's.
17
+ */
18
+ async function startOidcProvider({ account, appUrl = APP_URL, consentPage = false } = {}) {
15
19
  return startMockIssuer({
16
20
  account,
21
+ consentPage,
17
22
  staticClients: [{
18
23
  client_id: CLIENT.clientId,
19
24
  client_secret: CLIENT.clientSecret,
20
- redirect_uris: [REDIRECT_URI],
25
+ redirect_uris: [`${appUrl}/auth/login`],
21
26
  grant_types: ["authorization_code"],
22
27
  response_types: ["code"],
23
28
  token_endpoint_auth_method: "client_secret_post"
@@ -125,9 +130,11 @@ function oidcProviderEntry(issuer, { id = "google", label = "Google" } = {}) {
125
130
  * @param {import("../src/server/types.js").AuthLocalOAuthProvider[]} dependencies.oauthProviders
126
131
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
127
132
  * @param {import("../src/server/types.js").AuthLocalFirstAccountSetup} [dependencies.firstAccountSetup]
133
+ * @param {Record<string, string>} [dependencies.env] Environment values over the test ones, such as another
134
+ * APP_PUBLIC_URL.
128
135
  */
129
- function createService({ backend, oauthProviders, profileProjector, firstAccountSetup }) {
130
- const options = localServiceOptions({ env: { APP_PUBLIC_URL: APP_URL } });
136
+ function createService({ backend, oauthProviders, profileProjector, firstAccountSetup, env = {} }) {
137
+ const options = localServiceOptions({ env: { APP_PUBLIC_URL: APP_URL, ...env } });
131
138
  return createLocalAuthService({
132
139
  ...options,
133
140
  backend,