@jskit-ai/auth-provider-local-core 0.2.14 → 0.2.16
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 +4 -0
- package/package.json +3 -3
- package/src/server/lib/accounts.js +5 -3
- package/src/server/lib/authPayloads.js +21 -3
- package/src/server/lib/fileBackend.js +5 -3
- package/src/server/lib/passwordFlows.js +1 -0
- package/src/server/lib/sessions.js +46 -1
- package/test/profileSync.test.js +143 -0
- package/test/providerRuntime.test.js +33 -1
- package/test/requestAuthentication.test.js +95 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
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.
|
|
5
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.
|
|
6
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`.
|
|
7
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`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-provider-local-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.16",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
}
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
|
-
"@jskit-ai/auth-core": "0.2.
|
|
71
|
-
"@jskit-ai/kernel": "0.2.
|
|
70
|
+
"@jskit-ai/auth-core": "0.2.13",
|
|
71
|
+
"@jskit-ai/kernel": "0.2.13"
|
|
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
|
-
|
|
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
|
|
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));
|
|
@@ -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)
|
|
@@ -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
|
+
});
|
|
@@ -1177,7 +1177,14 @@ test("local auth provider requires an explicit public URL for email recovery", a
|
|
|
1177
1177
|
);
|
|
1178
1178
|
});
|
|
1179
1179
|
|
|
1180
|
-
|
|
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);
|
|
1181
1188
|
const storeDir = await temporaryStoreDir("jskit-auth-local-");
|
|
1182
1189
|
await fs.mkdir(storeDir, { recursive: true });
|
|
1183
1190
|
const lockPath = path.join(storeDir, "store.lock");
|
|
@@ -1202,6 +1209,31 @@ test("local file backend recovers stale transaction locks", async () => {
|
|
|
1202
1209
|
|
|
1203
1210
|
const user = await backend.withTransaction((tx) => tx.users.findByEmail("stale-lock@example.com"));
|
|
1204
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"]);
|
|
1205
1237
|
});
|
|
1206
1238
|
|
|
1207
1239
|
test("local file backend replays a pending multi-file transaction journal before reads", async () => {
|
|
@@ -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
|
+
});
|