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

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
+ - A dev sign-in (`devLoginAs`), a password sign-in, a recovery link's sign-in and a display-name change hold one database connection at a time. Each read or synchronized the application's profile inside local auth's transaction, and the profile projector (users-core's) reads and writes on a connection of its own, so one request held two pool connections, and as many such requests at once as the pool has connections each held one and waited for ever for another. The profile is now read or synchronized after local auth's transaction, as registration, OAuth sign-in and email confirmation already did; a dev sign-in finds its user in one transaction, reads the profile, and only then creates its session in another, so a user without a profile still gets none. Should synchronizing the profile fail after a sign-in's transaction committed, the sign-in still fails and its session is never handed out (it expires), as for a registration; a recovery link is then used up, and a changed display name stays changed until the next request's profile check synchronizes it.
6
+ - `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`.
7
+
5
8
  - **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
9
  - 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
10
  - 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.28",
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
  }
@@ -240,8 +240,7 @@ function createLocalAccounts({
240
240
  if (failures) {
241
241
  await tx.signInFailures.clear(email);
242
242
  }
243
- const session = await sessions.createSessionForUser(tx, user);
244
- return { payload: await buildAuthPayload({ user, session, profileProjector }) };
243
+ return { user, session: await sessions.createSessionForUser(tx, user) };
245
244
  });
246
245
  // Refused after the transaction, so the failure it records is kept.
247
246
  if (outcome.waitMs) {
@@ -253,7 +252,9 @@ function createLocalAccounts({
253
252
  if (outcome.unconfirmed) {
254
253
  throw createAuthError(AUTH_TEXTS.emailUnconfirmed);
255
254
  }
256
- return outcome.payload;
255
+ // After the transaction, as register does: the profile projector works in transactions of its own, so a sign-in
256
+ // that synchronized the profile inside this one held two database connections at once.
257
+ return buildAuthPayload({ user: outcome.user, session: outcome.session, profileProjector });
257
258
  }
258
259
 
259
260
  function devAuthBootstrapEnabled() {
@@ -271,23 +272,24 @@ function createLocalAccounts({
271
272
  });
272
273
  }
273
274
 
274
- return backend.withTransaction(async (tx) => {
275
- let user = userId ? await tx.users.findById(userId) : null;
276
- if (!user && email) {
277
- user = await tx.users.findByEmail(email);
278
- }
279
- if (!user || user.disabled) {
280
- throw devLoginAsUserNotFound({ email, userId });
281
- }
282
- const appProfile = await findExistingAppProfile(user, profileProjector);
283
- if (appProfileProjection && !appProfile) {
284
- throw devLoginAsUserNotFound({ email, userId });
285
- }
286
- const session = await sessions.createSessionForUser(tx, user, {
287
- purpose: DEV_AUTH_SESSION_PURPOSE
288
- });
289
- return buildAuthResult({ user, session, appProfile });
275
+ // The user is found, its app profile read and its session created one after the other, never the profile inside a
276
+ // transaction: the profile projector reads on a connection of its own, so a sign-in that read it inside one held
277
+ // two database connections at once, and as many sign-ins at once as the pool has connections waited for ever.
278
+ const user = await backend.withTransaction(async (tx) => {
279
+ const userById = userId ? await tx.users.findById(userId) : null;
280
+ return userById || (email ? tx.users.findByEmail(email) : null);
290
281
  });
282
+ if (!user || user.disabled) {
283
+ throw devLoginAsUserNotFound({ email, userId });
284
+ }
285
+ const appProfile = await findExistingAppProfile(user, profileProjector);
286
+ if (appProfileProjection && !appProfile) {
287
+ throw devLoginAsUserNotFound({ email, userId });
288
+ }
289
+ const session = await backend.withTransaction((tx) => sessions.createSessionForUser(tx, user, {
290
+ purpose: DEV_AUTH_SESSION_PURPOSE
291
+ }));
292
+ return buildAuthResult({ user, session, appProfile });
291
293
  }
292
294
 
293
295
  async function updateDisplayName(request, input) {
@@ -299,13 +301,12 @@ function createLocalAccounts({
299
301
  if (!displayName) {
300
302
  throw createAuthError(AUTH_TEXTS.displayNameRequired);
301
303
  }
302
- const changed = await backend.withTransaction(async (tx) => {
303
- const user = await tx.users.updateProfile(authResult.actor.providerUserId, { displayName });
304
- if (!user) {
305
- throw createAuthError(AUTH_TEXTS.sessionRequired);
306
- }
307
- return buildProfileChangePayload({ user, profileProjector });
308
- });
304
+ const user = await backend.withTransaction((tx) => tx.users.updateProfile(authResult.actor.providerUserId, { displayName }));
305
+ if (!user) {
306
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
307
+ }
308
+ // After the transaction, so the request holds one database connection at a time (see login).
309
+ const changed = await buildProfileChangePayload({ user, profileProjector });
309
310
  sessions.updateRequestActor(request, changed.actor);
310
311
  return changed;
311
312
  }
@@ -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
 
@@ -98,7 +98,7 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
98
98
  throw createAuthError(AUTH_TEXTS.recoveryTokenRequired);
99
99
  }
100
100
  const tokenInvalid = () => new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
101
- return backend.withTransaction(async (tx) => {
101
+ const { user, session } = await backend.withTransaction(async (tx) => {
102
102
  const recovery = await tx.recovery.findByTokenHash(sha256Base64url(token));
103
103
  if (!recovery || recovery.usedAt || isExpiredIso(recovery.expiresAt)) {
104
104
  throw tokenInvalid();
@@ -111,12 +111,17 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
111
111
  if (!user || user.disabled) {
112
112
  throw tokenInvalid();
113
113
  }
114
- const session = await sessions.createSessionForUser(tx, user, {
115
- purpose: "recovery",
116
- ttlSeconds: RECOVERY_SESSION_TTL_SECONDS
117
- });
118
- return buildAuthPayload({ user, session, profileProjector });
114
+ return {
115
+ user,
116
+ session: await sessions.createSessionForUser(tx, user, {
117
+ purpose: "recovery",
118
+ ttlSeconds: RECOVERY_SESSION_TTL_SECONDS
119
+ })
120
+ };
119
121
  });
122
+ // After the transaction, so the request holds one database connection at a time: the profile projector works in
123
+ // transactions of its own.
124
+ return buildAuthPayload({ user, session, profileProjector });
120
125
  }
121
126
 
122
127
  async function resetPassword(input, request) {
@@ -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,