@jskit-ai/auth-provider-local-core 0.2.13 → 0.2.15

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,7 +2,12 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
- - `AUTH_LOCAL_SELF_REGISTRATION=false` closes self-registration: an account registers only by an invitation a feature's invitation context resolver resolves for its email, or as the first account (admitted by its setup code in production); anyone else is refused with 403 `auth.local.register.closed` (new message key `jskit.auth.local.register.closed`). Confirmation guards self-registration, so with it off a production server starts without an `auth.local.confirmation-sender`, and those registrations sign in at once. Upgrading: an invitation-only or admin-created-accounts app that refused to start in production for want of a confirmation sender sets `AUTH_LOCAL_SELF_REGISTRATION=false` (and can drop its own 404 hook on the register routes); the startup refusal now names this way out too. `resolveLocalAuthConfig()` returns `selfRegistration`.
5
+ - The local file backend takes over a store lock left by a crashed process (older than 30 s, its process gone) at its first attempt, instead of after waiting out the 2 s lock timeout. A lock whose process is alive is still never removed, however old.
6
+ - A request authenticates once. The route's auth policy and the handlers it runs (`getSecurityStatus`, `updateDisplayName`, `changePassword`, `signOutOtherSessions`, `startProviderLink`, `unlinkProvider`, an OAuth link) share the first `authenticateRequest()` answer for the same request object, instead of reading the session, the user and the app profile again each time. A display name change updates that answer's actor. `logout`, `signOutOtherSessions` and `resetPassword` forget it, so a later check in the same request reads the sessions again. Every new request still reads its session and user, so sign-out, revocation and disabling take effect from the next request. A failed authentication is not remembered, and a `syncProfile: false` check is never shared.
7
+ - An ordinary request synchronizes the app profile only when it is missing or its email or display name no longer matches the user (`onlyWhenChanged`); its session and user are still read on every request, so sign-out, revocation and disabling take effect at once. Sign-in, registration and a session refresh (every 15 minutes, when the access token has expired) synchronize in full, which also re-runs workspace provisioning. Measured in apps, every signed-in request ran a second transaction for the sync: GET /api/session 8 statements, GET /api/settings 21 (two authentications), PATCH /api/settings/profile 52. Visible difference: a personal workspace, owner membership or settings row deleted while someone is signed in comes back at their next refresh or sign-in instead of their next request.
8
+ - `updateDisplayName` answers the synchronized app profile as `profile`, so users-core no longer writes the users row a second time after a display name change.
9
+ - Local auth reports `features.password.selfRegister: false` with `AUTH_LOCAL_SELF_REGISTRATION=false`, so the sign-in page hides its Register tab, except while the app has no account: its first account may register (with the setup code in production), in development too, where the server now checks once at startup whether there is an account.
10
+ - `AUTH_LOCAL_SELF_REGISTRATION=false` closes self-registration: an account registers only by an invitation a feature's invitation context resolver resolves for its email, or as the first account (admitted by its setup code in production); anyone else is refused with 403 `auth.local.register.closed` (new message key `jskit.auth.local.register.closed`; an app with other locales adds it with `npx jskit i18n export <locale>`). Confirmation guards self-registration, so with it off a production server starts without an `auth.local.confirmation-sender`, and those registrations sign in at once. Upgrading: an invitation-only or admin-created-accounts app that refused to start in production for want of a confirmation sender sets `AUTH_LOCAL_SELF_REGISTRATION=false` (and can drop its own 404 hook on the register routes); the startup refusal now names this way out too. `resolveLocalAuthConfig()` returns `selfRegistration`.
6
11
  - The first account of a production server needs a one-time setup code. While local auth has no account, each start of a production server makes a new code, writes it in the log (a warning with `firstAccountSetupCode` and `firstAccountSetupCodeFile`) and in `first-account-setup-code` in `AUTH_LOCAL_STORE_DIR` (mode 600), and keeps only its hash; registering without it is refused with 403 `auth.local.setup.codeRequired`, with a wrong one with 403 `auth.local.setup.codeInvalid`, and an OAuth sign-in cannot create that account. Once an account exists the code stops working and its file is deleted. Development needs no code, and servers that already have accounts are unchanged. `getCapabilities()` says `features.firstAccountSetupCode` while it waits. `AuthLocalProvider` checks for an account as it starts, and `createLocalAuthService()` takes the started `firstAccountSetup` (by default it checks on first use). New exports `createFirstAccountSetup` and `SETUP_CODE_FILE`; new message keys `jskit.auth.local.setup.codeRequired` and `jskit.auth.local.setup.codeInvalid`.
7
12
  - Upgrading: a custom `auth.local.backend` implements `users.hasAny()`.
8
13
  - A hosting tool may supply the first account's setup code in `AUTH_LOCAL_SETUP_CODE` (production only; at least 20 letters and digits, or startup stops naming the variable) and show it to the operator itself. The server then asks for that code at every start and on every server, writes no `first-account-setup-code` file (it deletes one left behind), and logs only that the code is in `AUTH_LOCAL_SETUP_CODE` (`firstAccountSetupCodeEnv`), never the code. New export `SETUP_CODE_ENV`. The refusal and sign-in texts name the server's log or its hosting service.
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
4
4
  "type": "module",
5
5
  "scripts": {
6
- "test": "node --test --test-concurrency=1"
6
+ "test": "jskit test"
7
7
  },
8
8
  "exports": {
9
9
  "./server/providers/AuthLocalProvider": "./src/server/providers/AuthLocalProvider.js",
@@ -67,7 +67,7 @@
67
67
  }
68
68
  },
69
69
  "peerDependencies": {
70
- "@jskit-ai/auth-core": "0.2.10",
71
- "@jskit-ai/kernel": "0.2.10"
70
+ "@jskit-ai/auth-core": "0.2.12",
71
+ "@jskit-ai/kernel": "0.2.12"
72
72
  }
73
73
  }
@@ -4,7 +4,7 @@ import { ensureDevAuthExchangeAvailable, isDevAuthBootstrapEnabled } from "@jski
4
4
  import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
5
5
  import { AUTH_TEXTS, authFieldErrorDetails, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
6
6
  import { invitationAsGiven } from "@jskit-ai/auth-core/server/authExtensions";
7
- import { DEV_AUTH_SESSION_PURPOSE, buildAuthPayload, buildAuthResult, findExistingAppProfile } from "./authPayloads.js";
7
+ import { DEV_AUTH_SESSION_PURPOSE, buildAuthPayload, buildAuthResult, buildProfileChangePayload, findExistingAppProfile } from "./authPayloads.js";
8
8
  import { forgottenFailuresBefore, recordSignInFailure, signInLockedError, signInWaitMs } from "./signInThrottle.js";
9
9
  import { createId } from "./tokens.js";
10
10
 
@@ -285,13 +285,15 @@ function createLocalAccounts({
285
285
  if (!displayName) {
286
286
  throw createAuthError(AUTH_TEXTS.displayNameRequired);
287
287
  }
288
- return backend.withTransaction(async (tx) => {
288
+ const changed = await backend.withTransaction(async (tx) => {
289
289
  const user = await tx.users.updateProfile(authResult.actor.providerUserId, { displayName });
290
290
  if (!user) {
291
291
  throw createAuthError(AUTH_TEXTS.sessionRequired);
292
292
  }
293
- return buildAuthPayload({ user, session: null, profileProjector });
293
+ return buildProfileChangePayload({ user, profileProjector });
294
294
  });
295
+ sessions.updateRequestActor(request, changed.actor);
296
+ return changed;
295
297
  }
296
298
 
297
299
  return Object.freeze({
@@ -59,6 +59,18 @@ async function buildAuthPayload({ user, session, profileProjector, profileOption
59
59
  return buildAuthResult({ user, session, appProfile });
60
60
  }
61
61
 
62
+ /**
63
+ * The result of a change to the user's own profile: the auth result and the synchronized app profile
64
+ * (`profile`, null when the application keeps none), so the caller does not write the profile again.
65
+ * @param {object} input
66
+ * @param {object} input.user
67
+ * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} input.profileProjector
68
+ */
69
+ async function buildProfileChangePayload({ user, profileProjector }) {
70
+ const appProfile = await profileProjector.syncIdentityProfile(buildProfile(user));
71
+ return { ...buildAuthResult({ user, session: null, appProfile }), profile: appProfile };
72
+ }
73
+
62
74
  /**
63
75
  * @param {object} user
64
76
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} profileProjector
@@ -70,7 +82,10 @@ function findExistingAppProfile(user, profileProjector) {
70
82
  /**
71
83
  * A dev session, or a caller that asks only who is signed in (syncProfile:
72
84
  * false), reads the existing app profile instead of synchronizing it. When the
73
- * application keeps profiles, a user without one is not signed in.
85
+ * application keeps profiles, a user without one is not signed in. An ordinary
86
+ * request (`onlyWhenChanged`) synchronizes only a missing profile or one whose
87
+ * email or display name no longer matches the user; a sign-in or a session
88
+ * refresh synchronizes in full.
74
89
  * @param {object} input
75
90
  * @param {boolean} input.appProfileProjection True when the application keeps profiles.
76
91
  * @param {object} input.devAuth
@@ -79,11 +94,13 @@ function findExistingAppProfile(user, profileProjector) {
79
94
  * @param {object} input.session
80
95
  * @param {object} input.user
81
96
  * @param {boolean} [input.syncProfile]
97
+ * @param {boolean} [input.onlyWhenChanged]
82
98
  */
83
- async function buildSessionAuthPayload({ appProfileProjection, devAuth, profileProjector, request, session, user, syncProfile = true }) {
99
+ async function buildSessionAuthPayload({ appProfileProjection, devAuth, profileProjector, request, session, user, syncProfile = true,
100
+ onlyWhenChanged = false }) {
84
101
  const devSession = isDevAuthSession(session);
85
102
  if (!devSession && syncProfile) {
86
- return buildAuthPayload({ user, session: null, profileProjector });
103
+ return buildAuthPayload({ user, session: null, profileProjector, profileOptions: onlyWhenChanged ? { onlyWhenChanged } : {} });
87
104
  }
88
105
  if (devSession) {
89
106
  try {
@@ -103,6 +120,7 @@ export {
103
120
  PROVIDER_ID,
104
121
  buildAuthPayload,
105
122
  buildAuthResult,
123
+ buildProfileChangePayload,
106
124
  buildSessionAuthPayload,
107
125
  findExistingAppProfile,
108
126
  isAuthenticatingSession
@@ -175,10 +175,12 @@ async function acquireLock(storeDir, timeoutMs = 2000) {
175
175
  if (!error || error.code !== "EEXIST") {
176
176
  throw new Error(`Could not acquire local auth store lock at ${lockPath}.`);
177
177
  }
178
+ // A lock older than LOCK_STALE_MS whose process has ended was left by a crash: take it over at once instead of
179
+ // after waiting out the timeout. A lock whose process is alive, or a recent one, is never removed.
180
+ if (await removeStaleLock(lockPath)) {
181
+ continue;
182
+ }
178
183
  if (Date.now() - startedAt > timeoutMs) {
179
- if (await removeStaleLock(lockPath)) {
180
- continue;
181
- }
182
184
  throw new Error(`Could not acquire local auth store lock at ${lockPath}.`);
183
185
  }
184
186
  await new Promise((resolve) => setTimeout(resolve, 25));
@@ -49,7 +49,9 @@ function setupCodeInvalid() {
49
49
  * AUTH_LOCAL_SETUP_CODE shows it to the operator itself: the server then uses
50
50
  * that code at every start, and neither logs nor writes it. The code admits
51
51
  * registrations until an account exists, then stops working and its file is
52
- * deleted. Development needs no code.
52
+ * deleted. Development needs no code. In every mode it knows whether the app
53
+ * still has no account, so an invitation-only app can let its first account
54
+ * register.
53
55
  * @param {object} dependencies
54
56
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
55
57
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
@@ -58,6 +60,7 @@ function setupCodeInvalid() {
58
60
  function createFirstAccountSetup({ backend, config, logger }) {
59
61
  const codeFile = path.join(config.storeDir, SETUP_CODE_FILE);
60
62
  let codeHash = null;
63
+ let ownerless = false;
61
64
  let started = null;
62
65
 
63
66
  // The file only hands the code to the operator, and the log has it too, so
@@ -84,6 +87,7 @@ function createFirstAccountSetup({ backend, config, logger }) {
84
87
 
85
88
  function finish() {
86
89
  codeHash = null;
90
+ ownerless = false;
87
91
  removeCodeFile();
88
92
  }
89
93
 
@@ -92,6 +96,10 @@ function createFirstAccountSetup({ backend, config, logger }) {
92
96
  finish();
93
97
  return;
94
98
  }
99
+ ownerless = true;
100
+ if (!config.isProduction) {
101
+ return;
102
+ }
95
103
  if (config.setupCode) {
96
104
  // The hosting tool shows its code, so a file left by an earlier start would only mislead.
97
105
  codeHash = setupCodeHash(config.setupCode);
@@ -112,12 +120,9 @@ function createFirstAccountSetup({ backend, config, logger }) {
112
120
 
113
121
  /**
114
122
  * Checks for an account once, when the server starts; outside production,
115
- * there is nothing to check. Later calls answer the same check.
123
+ * only whether there is one. Later calls answer the same check.
116
124
  */
117
125
  function start() {
118
- if (!config.isProduction) {
119
- return Promise.resolve();
120
- }
121
126
  started ??= prepare().catch((error) => {
122
127
  started = null;
123
128
  throw error;
@@ -167,6 +172,12 @@ function createFirstAccountSetup({ backend, config, logger }) {
167
172
  if (codeHash !== null) {
168
173
  finish();
169
174
  }
175
+ ownerless = false;
176
+ }
177
+
178
+ /** True while the app has no account, as far as this server knows. */
179
+ function isOwnerless() {
180
+ return ownerless;
170
181
  }
171
182
 
172
183
  /** True while the first account needs the setup code, as far as this server knows. */
@@ -179,6 +190,7 @@ function createFirstAccountSetup({ backend, config, logger }) {
179
190
  admitRegistration,
180
191
  admitOAuthAccount,
181
192
  accountCreated,
193
+ isOwnerless,
182
194
  isWaiting
183
195
  });
184
196
  }
@@ -117,6 +117,7 @@ function createLocalPasswordFlows({ backend, config, passwords, profileProjector
117
117
  await tx.signInFailures.clear(user.email);
118
118
  }
119
119
  });
120
+ sessions.forgetRequestAuthentication(request);
120
121
  return {
121
122
  ok: true,
122
123
  ...authMessageFields(AUTH_TEXTS.passwordUpdatedSignIn)
@@ -56,6 +56,8 @@ function createLocalAuthService({
56
56
  password: {
57
57
  login: true,
58
58
  register: true,
59
+ // Off with AUTH_LOCAL_SELF_REGISTRATION=false: an account registers by invitation, or as the first one.
60
+ selfRegister: config.selfRegistration,
59
61
  change: true,
60
62
  methodToggle: false
61
63
  },
@@ -84,10 +86,14 @@ function createLocalAuthService({
84
86
  devLoginAs: isDevAuthBootstrapEnabled(config.devAuth)
85
87
  }
86
88
  });
87
- // While a production server has no account, registering asks for the setup code.
88
- const capabilitiesWaitingForFirstAccount = normalizeAuthCapabilities({
89
+ // While the app has no account, its first one may register, and on a production server that asks for the setup code.
90
+ const capabilitiesForFirstAccount = normalizeAuthCapabilities({
89
91
  ...capabilities,
90
- features: { ...capabilities.features, firstAccountSetupCode: true }
92
+ features: { ...capabilities.features, password: { ...capabilities.features.password, selfRegister: true } }
93
+ });
94
+ const capabilitiesWaitingForFirstAccount = normalizeAuthCapabilities({
95
+ ...capabilitiesForFirstAccount,
96
+ features: { ...capabilitiesForFirstAccount.features, firstAccountSetupCode: true }
91
97
  });
92
98
 
93
99
  const sessions = createLocalSessions({ appProfileProjection, backend, config, profileProjector });
@@ -132,7 +138,10 @@ function createLocalAuthService({
132
138
  });
133
139
 
134
140
  function getCapabilities() {
135
- return firstAccountSetup.isWaiting() ? capabilitiesWaitingForFirstAccount : capabilities;
141
+ if (firstAccountSetup.isWaiting()) {
142
+ return capabilitiesWaitingForFirstAccount;
143
+ }
144
+ return firstAccountSetup.isOwnerless() ? capabilitiesForFirstAccount : capabilities;
136
145
  }
137
146
 
138
147
  function resendRegisterConfirmation(input) {
@@ -124,7 +124,46 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
124
124
  });
125
125
  }
126
126
 
127
+ // One authentication per request: the route's auth policy and the handlers it runs (security status, a display
128
+ // name change, a password change, ...) share the first answer for the same request object instead of reading the
129
+ // session, the user and the profile again. A request that revokes sessions forgets its answer, so a later check in
130
+ // it reads them again, and every new request reads them afresh, so sign-out, revocation and disabling still apply
131
+ // from the next request on.
132
+ const requestAuthentications = new WeakMap();
133
+
127
134
  async function authenticateRequest(request, { syncProfile = true } = {}) {
135
+ // A check without profile synchronization does not answer for a synchronizing one, and only an object can be
136
+ // remembered.
137
+ if (!syncProfile || !request || typeof request !== "object") {
138
+ return authenticateFromCookies(request, { syncProfile });
139
+ }
140
+ if (!requestAuthentications.has(request)) {
141
+ const answer = authenticateFromCookies(request, { syncProfile });
142
+ requestAuthentications.set(request, answer);
143
+ // A failure is not remembered: a later check in the request tries again.
144
+ answer.catch(() => {
145
+ if (requestAuthentications.get(request) === answer) {
146
+ requestAuthentications.delete(request);
147
+ }
148
+ });
149
+ }
150
+ return requestAuthentications.get(request);
151
+ }
152
+
153
+ /** The request revoked sessions: a later authentication in it reads its session again. */
154
+ function forgetRequestAuthentication(request) {
155
+ requestAuthentications.delete(request);
156
+ }
157
+
158
+ /** The request changed its own user's profile: a later authentication in it answers the new `actor`. */
159
+ function updateRequestActor(request, actor) {
160
+ const answer = requestAuthentications.get(request);
161
+ if (answer) {
162
+ requestAuthentications.set(request, answer.then((result) => (result.authenticated ? { ...result, actor } : result)));
163
+ }
164
+ }
165
+
166
+ async function authenticateFromCookies(request, { syncProfile }) {
128
167
  const cookies = safeRequestCookies(request);
129
168
  const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
130
169
  const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
@@ -144,6 +183,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
144
183
  return { user, session };
145
184
  });
146
185
  if (resolved && isAuthenticatingSession(resolved.session)) {
186
+ // An ordinary request: its session and user are read above; the profile is synchronized only when it changed.
147
187
  const authPayload = await buildSessionAuthPayload({
148
188
  appProfileProjection,
149
189
  devAuth,
@@ -151,7 +191,8 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
151
191
  request,
152
192
  session: resolved.session,
153
193
  user: resolved.user,
154
- syncProfile
194
+ syncProfile,
195
+ onlyWhenChanged: true
155
196
  });
156
197
  if (!authPayload) {
157
198
  return unauthenticatedAuthResult(true);
@@ -282,6 +323,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
282
323
  await tx.sessions.revoke(session.id);
283
324
  }
284
325
  });
326
+ forgetRequestAuthentication(request);
285
327
  return {
286
328
  ok: true,
287
329
  clearSession: true
@@ -301,6 +343,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
301
343
  exceptSessionId: currentSession?.session?.id
302
344
  })
303
345
  );
346
+ forgetRequestAuthentication(request);
304
347
  return {
305
348
  ok: true,
306
349
  revokedSessions: count
@@ -310,6 +353,8 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
310
353
  return Object.freeze({
311
354
  createSessionForUser,
312
355
  authenticateRequest,
356
+ forgetRequestAuthentication,
357
+ updateRequestActor,
313
358
  requireNormalSessionUserId,
314
359
  readRecoveryAccessToken,
315
360
  hasAccessTokenCookie,
@@ -0,0 +1,143 @@
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 { createService as createProfileSyncService } from "../../users-core/src/server/common/services/authProfileSyncService.js";
7
+ import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
8
+ import { localServiceOptions } from "../test-support/localService.js";
9
+ import { sessionCookies } from "../test-support/oauthHarness.js";
10
+
11
+ // Records how each synchronization was asked for: in full, or only when the profile changed.
12
+ function recordingProjector() {
13
+ const syncs = [];
14
+ let profile = null;
15
+ return {
16
+ syncs,
17
+ async syncIdentityProfile(identity, options = {}) {
18
+ syncs.push(options.onlyWhenChanged ? "when changed" : "full");
19
+ profile = { ...identity, id: "1" };
20
+ return profile;
21
+ },
22
+ async findByIdentity() {
23
+ return profile;
24
+ }
25
+ };
26
+ }
27
+
28
+ async function startService(t, profileProjector) {
29
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-profile-sync-"));
30
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
31
+ return createLocalAuthService({ ...localServiceOptions(), backend: createLocalFileBackend({ storeDir }), profileProjector });
32
+ }
33
+
34
+ async function signedInCookies(service) {
35
+ await service.register({ email: "ada@example.com", password: "correct horse" });
36
+ return sessionCookies((await service.login({ email: "ada@example.com", password: "correct horse" })).session);
37
+ }
38
+
39
+ test("a display name change answers the synchronized app profile, so users-core does not write it again", async (t) => {
40
+ const projector = recordingProjector();
41
+ const service = await startService(t, projector);
42
+ const cookies = await signedInCookies(service);
43
+ const changed = await service.updateDisplayName({ cookies }, { displayName: "Ada Lovelace" });
44
+ assert.equal(changed.profile.id, "1");
45
+ assert.equal(changed.profile.displayName, "Ada Lovelace");
46
+ assert.equal(changed.actor.appUserId, "1");
47
+ });
48
+
49
+ test("an ordinary request synchronizes its profile only when it changed; sign-in, a session refresh and a name change synchronize in full", async (t) => {
50
+ const projector = recordingProjector();
51
+ const service = await startService(t, projector);
52
+ await service.register({ email: "ada@example.com", password: "correct horse" });
53
+ projector.syncs.length = 0;
54
+ const signedIn = await service.login({ email: "ada@example.com", password: "correct horse" });
55
+ assert.deepEqual(projector.syncs.splice(0), ["full"]);
56
+ const cookies = sessionCookies(signedIn.session);
57
+
58
+ // Each ordinary request still reads its session and user; its profile is synchronized only when it changed.
59
+ for (let index = 0; index < 3; index += 1) {
60
+ assert.equal((await service.authenticateRequest({ cookies })).authenticated, true);
61
+ }
62
+ await service.getSecurityStatus({ cookies });
63
+ assert.deepEqual(projector.syncs.splice(0), ["when changed", "when changed", "when changed", "when changed"]);
64
+
65
+ // A session refresh (the access token has expired) issues new tokens and synchronizes in full.
66
+ const refreshed = await service.authenticateRequest({ cookies: { jskit_local_refresh_token: cookies.jskit_local_refresh_token } });
67
+ assert.equal(refreshed.authenticated, true);
68
+ assert.ok(refreshed.session?.access_token);
69
+ assert.deepEqual(projector.syncs.splice(0), ["full"]);
70
+
71
+ // A display name change authenticates like a request, then synchronizes the new name in full.
72
+ await service.updateDisplayName({ cookies }, { displayName: "Ada Lovelace" });
73
+ assert.deepEqual(projector.syncs.splice(0), ["when changed", "full"]);
74
+
75
+ // Authorization rests on the session read, not on the profile: signing out ends the next ordinary request.
76
+ await service.logout({ cookies });
77
+ assert.equal((await service.authenticateRequest({ cookies })).authenticated, false);
78
+ });
79
+
80
+ // users-core's profile projector over in-memory repositories; its lifecycle contributor stands where workspaces-core
81
+ // provisions the personal workspace (re-creating one that was deleted).
82
+ function usersProfileSync() {
83
+ const profiles = [];
84
+ const provisioned = [];
85
+ const profileProjector = createProfileSyncService({
86
+ userProfilesRepository: {
87
+ async findByIdentity(identity) {
88
+ return profiles.find((profile) => profile.authProviderUserSid === identity.providerUserId) || null;
89
+ },
90
+ async upsert(payload) {
91
+ const existing = profiles.find((profile) => profile.authProviderUserSid === payload.authProviderUserSid);
92
+ if (existing) return Object.assign(existing, payload);
93
+ const profile = { id: String(profiles.length + 1), ...payload };
94
+ profiles.push(profile);
95
+ return profile;
96
+ },
97
+ async withTransaction(work) {
98
+ return work({});
99
+ }
100
+ },
101
+ userSettingsRepository: {
102
+ async ensureForUserId(userId) {
103
+ return { userId };
104
+ }
105
+ },
106
+ resolveLifecycleContributors: () => [{
107
+ contributorId: "workspaces.provisioning",
108
+ async afterIdentityProfileSynced({ profile }) {
109
+ provisioned.push(profile.displayName);
110
+ }
111
+ }]
112
+ });
113
+ return { profileProjector, profiles, provisioned };
114
+ }
115
+
116
+ test("with users-core, a name changed at the provider shows at the next request, and provisioning runs again at the next refresh", async (t) => {
117
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-profile-sync-"));
118
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
119
+ const backend = createLocalFileBackend({ storeDir });
120
+ const users = usersProfileSync();
121
+ const service = createLocalAuthService({ ...localServiceOptions(), backend, profileProjector: users.profileProjector });
122
+ await service.register({ email: "ada@example.com", password: "correct horse" });
123
+ const signedIn = await service.login({ email: "ada@example.com", password: "correct horse" });
124
+ const cookies = sessionCookies(signedIn.session);
125
+ users.provisioned.length = 0;
126
+
127
+ // An ordinary request with a matching profile only reads it: no provisioning.
128
+ assert.equal((await service.authenticateRequest({ cookies })).actor.appUserId, "1");
129
+ assert.deepEqual(users.provisioned, []);
130
+
131
+ // A name changed at the provider (the local user store, outside the app) is synchronized by the next request.
132
+ await backend.withTransaction((tx) => tx.users.updateProfile(signedIn.actor.providerUserId, { displayName: "Ada Lovelace" }));
133
+ assert.equal((await service.authenticateRequest({ cookies })).actor.displayName, "Ada Lovelace");
134
+ assert.equal(users.profiles[0].displayName, "Ada Lovelace");
135
+ assert.deepEqual(users.provisioned.splice(0), ["Ada Lovelace"]);
136
+
137
+ // A deleted personal workspace is provisioned again at the next session refresh, not at the next request.
138
+ await service.authenticateRequest({ cookies });
139
+ assert.deepEqual(users.provisioned, []);
140
+ const refreshed = await service.authenticateRequest({ cookies: { jskit_local_refresh_token: cookies.jskit_local_refresh_token } });
141
+ assert.ok(refreshed.session?.access_token);
142
+ assert.deepEqual(users.provisioned, ["Ada Lovelace"]);
143
+ });
@@ -696,6 +696,10 @@ test("local auth service accepts a custom stored-password format", async () => {
696
696
  async withTransaction(callback) {
697
697
  return callback({
698
698
  users: {
699
+ // The first-account check reads this at the first registration, in development too.
700
+ async hasAny() {
701
+ return true;
702
+ },
699
703
  async findByEmail(email) {
700
704
  if (email !== "existing@example.com") {
701
705
  return null;
@@ -1173,7 +1177,14 @@ test("local auth provider requires an explicit public URL for email recovery", a
1173
1177
  );
1174
1178
  });
1175
1179
 
1176
- test("local file backend recovers stale transaction locks", async () => {
1180
+ // The file backend waits 25 ms between attempts at a held lock.
1181
+ function lockWaits(t) {
1182
+ const setTimeoutSpy = t.mock.method(globalThis, "setTimeout");
1183
+ return () => setTimeoutSpy.mock.calls.filter((call) => call.arguments[1] === 25).length;
1184
+ }
1185
+
1186
+ test("local file backend recovers stale transaction locks", async (t) => {
1187
+ const waits = lockWaits(t);
1177
1188
  const storeDir = await temporaryStoreDir("jskit-auth-local-");
1178
1189
  await fs.mkdir(storeDir, { recursive: true });
1179
1190
  const lockPath = path.join(storeDir, "store.lock");
@@ -1198,6 +1209,31 @@ test("local file backend recovers stale transaction locks", async () => {
1198
1209
 
1199
1210
  const user = await backend.withTransaction((tx) => tx.users.findByEmail("stale-lock@example.com"));
1200
1211
  assert.equal(user.id, "usr_stale_lock");
1212
+ assert.equal(waits(), 0, "A crashed holder's lock is taken over without waiting");
1213
+ });
1214
+
1215
+ // The bound only turns a regression (the second transaction neither waiting nor running) into a failure, not a hang.
1216
+ test("local file backend never takes over a lock whose process is alive, however old", { timeout: 10_000 }, async (t) => {
1217
+ const waits = lockWaits(t);
1218
+ const storeDir = await temporaryStoreDir("jskit-auth-local-live-");
1219
+ const lockPath = path.join(storeDir, "store.lock");
1220
+ const backend = createLocalFileBackend({ storeDir });
1221
+ const order = [];
1222
+ let second;
1223
+ await backend.withTransaction(async () => {
1224
+ // This process holds the lock; make it look as old as a crashed one.
1225
+ const old = new Date(Date.now() - 60_000);
1226
+ await fs.utimes(lockPath, old, old);
1227
+ second = backend.withTransaction(async () => {
1228
+ order.push("second");
1229
+ });
1230
+ while (waits() === 0 && order.length === 0) {
1231
+ await new Promise((resolve) => setImmediate(resolve));
1232
+ }
1233
+ order.push("first");
1234
+ });
1235
+ await second;
1236
+ assert.deepEqual(order, ["first", "second"]);
1201
1237
  });
1202
1238
 
1203
1239
  test("local file backend replays a pending multi-file transaction journal before reads", async () => {
@@ -1385,6 +1421,9 @@ test("with AUTH_LOCAL_SELF_REGISTRATION=false, production starts without a confi
1385
1421
  });
1386
1422
  t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1387
1423
  assert.equal(app.authService.getCapabilities().features.emailConfirmation, false);
1424
+ // Until the first account exists, its registration is offered; then only an invited person's.
1425
+ const password = () => app.authService.getCapabilities().features.password;
1426
+ assert.deepEqual([password().register, password().selfRegister], [true, true]);
1388
1427
  // The first account registers with its setup code.
1389
1428
  const owner = await app.authService.register({
1390
1429
  email: "owner@example.com",
@@ -1392,6 +1431,7 @@ test("with AUTH_LOCAL_SELF_REGISTRATION=false, production starts without a confi
1392
1431
  setupCode: await firstAccountSetupCode(app.storeDir)
1393
1432
  });
1394
1433
  assert.equal(owner.actor.email, "owner@example.com");
1434
+ assert.deepEqual([password().register, password().selfRegister], [true, false]);
1395
1435
  const closed = { status: 403, code: "auth.local.register.closed" };
1396
1436
  await assert.rejects(() => app.authService.register({ email: "eve@example.com", password: "correct horse battery staple" }), closed);
1397
1437
  await assert.rejects(() => app.authService.register({
@@ -1408,6 +1448,24 @@ test("with AUTH_LOCAL_SELF_REGISTRATION=false, production starts without a confi
1408
1448
  assert.equal(invited.requiresEmailConfirmation, false);
1409
1449
  });
1410
1450
 
1451
+ test("in development with AUTH_LOCAL_SELF_REGISTRATION=false, the first account's registration is offered until it exists", async (t) => {
1452
+ const app = await createStartedApp({ env: { AUTH_LOCAL_SELF_REGISTRATION: "false", AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
1453
+ t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1454
+ const password = () => app.authService.getCapabilities().features.password;
1455
+ assert.equal(password().selfRegister, true);
1456
+ assert.equal(app.authService.getCapabilities().features.firstAccountSetupCode, false, "development needs no setup code");
1457
+ await app.authService.register({ email: "owner@example.com", password: "correct horse battery staple" });
1458
+ assert.equal(password().selfRegister, false);
1459
+ await assert.rejects(
1460
+ () => app.authService.register({ email: "eve@example.com", password: "correct horse battery staple" }),
1461
+ { status: 403, code: "auth.local.register.closed" }
1462
+ );
1463
+ // With self-registration on (the default), anyone may register.
1464
+ const open = await createStartedApp({ env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "false" } });
1465
+ t.after(() => fs.rm(open.storeDir, { recursive: true, force: true }));
1466
+ assert.equal(open.authService.getCapabilities().features.password.selfRegister, true);
1467
+ });
1468
+
1411
1469
  test("the confirmation sender emails the link, which is never returned or logged, and the register hook runs on confirming", async (t) => {
1412
1470
  const messages = [];
1413
1471
  const logs = [];
@@ -0,0 +1,95 @@
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 { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
7
+ import { localServiceOptions } from "../test-support/localService.js";
8
+ import { sessionCookies } from "../test-support/oauthHarness.js";
9
+
10
+ // A file backend that counts session reads (each authentication reads its session once) and can fail the next one.
11
+ async function startService(t) {
12
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-request-auth-"));
13
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
14
+ const files = createLocalFileBackend({ storeDir });
15
+ const reads = { sessions: 0, failNext: false };
16
+ function readSession(tx, method, args) {
17
+ reads.sessions += 1;
18
+ if (reads.failNext) {
19
+ reads.failNext = false;
20
+ throw new Error("The session store is unavailable.");
21
+ }
22
+ return tx.sessions[method](...args);
23
+ }
24
+ const backend = {
25
+ ...files,
26
+ withTransaction: (work) => files.withTransaction((tx) => work({
27
+ ...tx,
28
+ sessions: Object.create(tx.sessions, {
29
+ findById: { value: (...args) => readSession(tx, "findById", args) },
30
+ findByTokenHash: { value: (...args) => readSession(tx, "findByTokenHash", args) }
31
+ })
32
+ }))
33
+ };
34
+ const service = createLocalAuthService({ ...localServiceOptions(), backend });
35
+ await service.register({ email: "ada@example.com", password: "correct horse" });
36
+ return { service, reads };
37
+ }
38
+
39
+ async function signIn(service) {
40
+ return sessionCookies((await service.login({ email: "ada@example.com", password: "correct horse" })).session);
41
+ }
42
+
43
+ test("a request authenticates once however many of its handlers ask, and answers its own display name change", async (t) => {
44
+ const { service, reads } = await startService(t);
45
+ const cookies = await signIn(service);
46
+
47
+ // GET /api/settings: the route's auth policy, then the security status.
48
+ const settings = { cookies };
49
+ reads.sessions = 0;
50
+ assert.equal((await service.authenticateRequest(settings)).authenticated, true);
51
+ assert.equal((await service.getSecurityStatus(settings)).actions.signOutOtherSessions, true);
52
+ assert.equal(reads.sessions, 1);
53
+
54
+ // PATCH /api/settings/profile: the route's auth policy, the display name change, then the security status.
55
+ const patch = { cookies };
56
+ reads.sessions = 0;
57
+ assert.equal((await service.authenticateRequest(patch)).actor.displayName, "ada");
58
+ await service.updateDisplayName(patch, { displayName: "Ada Lovelace" });
59
+ await service.getSecurityStatus(patch);
60
+ assert.equal((await service.authenticateRequest(patch)).actor.displayName, "Ada Lovelace");
61
+ assert.equal(reads.sessions, 1);
62
+
63
+ // Each new request reads its session again.
64
+ assert.equal((await service.authenticateRequest({ cookies })).actor.displayName, "Ada Lovelace");
65
+ assert.equal(reads.sessions, 2);
66
+ });
67
+
68
+ test("revocation applies from the next request, and within the request that signs itself out", async (t) => {
69
+ const { service } = await startService(t);
70
+ const laptop = await signIn(service);
71
+ const phone = await signIn(service);
72
+
73
+ // The phone signs out the laptop (and the session registering opened): the laptop's next request is signed out,
74
+ // the phone's are not.
75
+ const phoneRequest = { cookies: phone };
76
+ assert.equal((await service.authenticateRequest(phoneRequest)).authenticated, true);
77
+ assert.equal((await service.signOutOtherSessions(phoneRequest)).revokedSessions, 2);
78
+ assert.equal((await service.authenticateRequest(phoneRequest)).authenticated, true);
79
+ assert.equal((await service.authenticateRequest({ cookies: laptop })).authenticated, false);
80
+
81
+ // A request that signs out answers signed out from then on.
82
+ const signOut = { cookies: phone };
83
+ assert.equal((await service.authenticateRequest(signOut)).authenticated, true);
84
+ await service.logout(signOut);
85
+ assert.equal((await service.authenticateRequest(signOut)).authenticated, false);
86
+ assert.equal((await service.authenticateRequest({ cookies: phone })).authenticated, false);
87
+ });
88
+
89
+ test("a failed authentication is not remembered for the rest of its request", async (t) => {
90
+ const { service, reads } = await startService(t);
91
+ const request = { cookies: await signIn(service) };
92
+ reads.failNext = true;
93
+ await assert.rejects(service.authenticateRequest(request), /session store is unavailable/u);
94
+ assert.equal((await service.authenticateRequest(request)).authenticated, true);
95
+ });