@jskit-ai/auth-provider-oidc-core 0.2.6 → 0.2.7

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.
@@ -15,7 +15,7 @@ counts unless --apply is given.`;
15
15
 
16
16
  async function appKnex() {
17
17
  try {
18
- process.loadEnvFile?.(".env");
18
+ process.loadEnvFile(".env");
19
19
  } catch (error) {
20
20
  if (error?.code !== "ENOENT") throw error;
21
21
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-oidc-core",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -20,8 +20,8 @@
20
20
  "openid-client": "6.8.8"
21
21
  },
22
22
  "devDependencies": {
23
- "@jskit-ai/auth-provider-local-core": "0.2.5",
24
- "@jskit-ai/auth-web": "0.2.4",
23
+ "@jskit-ai/auth-provider-local-core": "0.2.6",
24
+ "@jskit-ai/auth-web": "0.2.5",
25
25
  "oidc-provider": "9.12.2"
26
26
  },
27
27
  "description": "Sign in through any OpenID Connect issuer: self-registration or a static client, app-owned sessions, and back-channel logout.",
@@ -91,7 +91,7 @@
91
91
  }
92
92
  },
93
93
  "peerDependencies": {
94
- "@jskit-ai/auth-core": "0.2.3",
95
- "@jskit-ai/kernel": "0.2.3"
94
+ "@jskit-ai/auth-core": "0.2.4",
95
+ "@jskit-ai/kernel": "0.2.4"
96
96
  }
97
97
  }
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@jskit-ai/auth-provider-oidc-core": "0.2.6",
6
- "@jskit-ai/auth-web": "0.2.4"
5
+ "@jskit-ai/auth-provider-oidc-core": "0.2.7",
6
+ "@jskit-ai/auth-web": "0.2.5"
7
7
  }
8
8
  }
@@ -13,15 +13,21 @@ class BackchannelLogoutError extends Error {
13
13
  /**
14
14
  * OpenID Connect Back-Channel Logout 1.0 for this app: the issuer posts a
15
15
  * signed logout_token and the matching app sessions end.
16
+ * @param {object} dependencies
17
+ * @param {import("../types.js").OidcConfig} dependencies.config
18
+ * @param {import("../types.js").OidcStore} dependencies.store
19
+ * @param {import("../types.js").OidcIssuerClient} dependencies.issuer
20
+ * @param {typeof fetch} [dependencies.fetchImpl] The fetch that reads the issuer's signing keys.
21
+ * @param {() => number} [dependencies.now]
16
22
  */
17
- function createBackchannelLogout({ config, store, issuer, fetchImpl = null, now = Date.now }) {
23
+ function createBackchannelLogout({ config, store, issuer, fetchImpl = globalThis.fetch, now = Date.now }) {
18
24
  let keySet = null;
19
25
 
20
26
  async function keys() {
21
27
  if (keySet) return keySet;
22
28
  const metadata = await issuer.serverMetadata();
23
29
  if (!metadata.jwks_uri) throw new BackchannelLogoutError("The issuer publishes no signing keys.");
24
- keySet = createRemoteJWKSet(new URL(metadata.jwks_uri), fetchImpl ? { [customFetch]: fetchImpl } : {});
30
+ keySet = createRemoteJWKSet(new URL(metadata.jwks_uri), { [customFetch]: fetchImpl });
25
31
  return keySet;
26
32
  }
27
33
 
@@ -69,10 +69,12 @@ function resolveSessionSecret(env, { appRoot, isProduction }) {
69
69
  * Reads the OIDC sign-in Env. Malformed values stop the app with one sentence.
70
70
  * A missing issuer or client is not fatal: the app runs and sign-in explains
71
71
  * what to set (`setupProblem`), so a project can be prepared before its
72
- * accounts hub exists.
72
+ * accounts hub exists. Production is worked out once, by auth-core's dev auth
73
+ * policy, so sign-in and dev sign-in agree on it.
73
74
  */
74
75
  function resolveOidcConfig({ env = {}, appRoot = process.cwd() } = {}) {
75
- const isProduction = text(env.NODE_ENV) === "production";
76
+ const devAuth = resolveDevAuthPolicyFromEnv(env);
77
+ const { isProduction } = devAuth;
76
78
  const issuerValue = text(env.AUTH_OIDC_ISSUER);
77
79
  const registrationToken = text(env.AUTH_OIDC_REGISTRATION_TOKEN);
78
80
  const clientId = text(env.AUTH_OIDC_CLIENT_ID);
@@ -90,7 +92,6 @@ function resolveOidcConfig({ env = {}, appRoot = process.cwd() } = {}) {
90
92
  }
91
93
  const issuer = issuerValue ? parseAddress(issuerValue, "AUTH_OIDC_ISSUER").href.replace(/\/$/u, "") : "";
92
94
  const appPublicOrigin = publicUrlValue ? parseAddress(publicUrlValue, "APP_PUBLIC_URL").origin : "";
93
- const devAuth = resolveDevAuthPolicyFromEnv(env);
94
95
  assertDevAuthPolicy(devAuth);
95
96
 
96
97
  let setupProblem = null;
@@ -20,9 +20,13 @@ function registrationMetadata(origin, appName) {
20
20
  };
21
21
  }
22
22
 
23
+ /**
24
+ * @param {unknown} error
25
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
26
+ */
23
27
  function unreachable(error, logger) {
24
28
  if (error instanceof AppError) return error;
25
- logger?.warn?.({ err: error }, "OIDC issuer request failed.");
29
+ logger.warn({ err: error }, "OIDC issuer request failed.");
26
30
  return new AppError(503, "Your accounts hub can't be reached right now. Try again in a moment.", {
27
31
  code: "auth.oidc.issuer.unreachable"
28
32
  });
@@ -32,18 +36,24 @@ function unreachable(error, logger) {
32
36
  * The relying party's view of one issuer: discovery, per-origin clients
33
37
  * (self-registered with the registration token, or the static client), and
34
38
  * the openid-client configuration each sign-in uses.
39
+ * @param {object} dependencies
40
+ * @param {import("../types.js").OidcConfig} dependencies.config
41
+ * @param {import("../types.js").OidcStore} dependencies.store
42
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
43
+ * @param {import("openid-client").CustomFetch} [dependencies.fetchImpl] The fetch every issuer request uses.
44
+ * @param {() => number} [dependencies.now]
35
45
  */
36
- function createIssuerClient({ config, store, logger = null, fetchImpl = null, now = Date.now }) {
46
+ function createIssuerClient({ config, store, logger, fetchImpl = globalThis.fetch, now = Date.now }) {
37
47
  const issuerUrl = config.issuer ? new URL(config.issuer) : null;
38
48
  const insecure = Boolean(issuerUrl && issuerUrl.protocol === "http:" && isLoopbackHostname(issuerUrl.hostname));
39
49
  const requestOptions = {
40
- ...(fetchImpl ? { [client.customFetch]: fetchImpl } : {}),
50
+ [client.customFetch]: fetchImpl,
41
51
  ...(insecure ? { execute: [client.allowInsecureRequests] } : {})
42
52
  };
43
53
  let discovered = null;
44
54
 
45
55
  function configure(configuration) {
46
- if (fetchImpl) configuration[client.customFetch] = fetchImpl;
56
+ configuration[client.customFetch] = fetchImpl;
47
57
  if (insecure) client.allowInsecureRequests(configuration);
48
58
  return configuration;
49
59
  }
@@ -12,6 +12,9 @@ function isTruthy(value) {
12
12
  * import: ids, emails, names and the scrypt password fields, unchanged. The
13
13
  * file holds password hashes, so it is created owner-only and never replaces
14
14
  * an existing file.
15
+ * @param {object} input
16
+ * @param {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} input.knex The app's database.
17
+ * @param {string} input.out The file to create.
15
18
  */
16
19
  async function exportLocalAccounts({ knex, out }) {
17
20
  const rows = await knex("auth_local_users as local")
@@ -71,6 +74,10 @@ async function readExportedIds(file) {
71
74
  * accounts listed in the export the hub imported. The hub keeps each local id
72
75
  * as its subject, so `auth_provider_user_sid` stays as it is. Dry-run unless
73
76
  * `apply` is set.
77
+ * @param {object} input
78
+ * @param {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} input.knex The app's database.
79
+ * @param {string} input.file The export the hub imported.
80
+ * @param {boolean} [input.apply] True to move the rows; otherwise only counts them.
74
81
  */
75
82
  async function adoptOidcAccounts({ knex, file, apply = false }) {
76
83
  const ids = await readExportedIds(file);
@@ -28,6 +28,12 @@ function isCrossSiteNavigation(request) {
28
28
  /**
29
29
  * Registers the two OIDC routes in their own Fastify scope, so the form-body
30
30
  * parser the back-channel route needs applies to it alone.
31
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeFastify} fastify
32
+ * @param {object} dependencies
33
+ * @param {ReturnType<typeof import("./service.js").createOidcAuthService>} dependencies.authService The installed
34
+ * `auth.service`: this provider's service with the application's auth.extensions decorators, so a
35
+ * decorator of logoutEverywhere or clearSessionCookies applies to these routes too.
36
+ * @param {ReturnType<typeof import("./backchannelLogout.js").createBackchannelLogout>} dependencies.backchannelLogout
31
37
  */
32
38
  async function registerOidcRoutes(fastify, { authService, backchannelLogout }) {
33
39
  await fastify.register(async (scope) => {
@@ -36,10 +42,11 @@ async function registerOidcRoutes(fastify, { authService, backchannelLogout }) {
36
42
  scope.post(AUTH_OIDC_BACKCHANNEL_LOGOUT_PATH, { config: SELF_AUTHENTICATED_ROUTE }, async (request, reply) => {
37
43
  reply.header("Cache-Control", "no-store");
38
44
  try {
39
- await backchannelLogout.handle(request.body?.logout_token);
45
+ const form = /** @type {{ logout_token?: string } | undefined} */ (request.body);
46
+ await backchannelLogout.handle(form?.logout_token);
40
47
  } catch (error) {
41
48
  if (!(error instanceof BackchannelLogoutError)) throw error;
42
- request.log?.warn?.({ reason: error.message }, "OIDC back-channel logout was refused.");
49
+ request.log.warn({ reason: error.message }, "OIDC back-channel logout was refused.");
43
50
  return reply.code(400).send({ error: "invalid_request", error_description: error.message });
44
51
  }
45
52
  return reply.code(200).send();
@@ -49,7 +56,7 @@ async function registerOidcRoutes(fastify, { authService, backchannelLogout }) {
49
56
  reply.header("Cache-Control", "no-store");
50
57
  if (isCrossSiteNavigation(request)) return reply.redirect("/");
51
58
  const destination = await authService.logoutEverywhere(request, {
52
- everywhere: String(request.query?.everywhere || "") === "1"
59
+ everywhere: String(/** @type {{ everywhere?: string } | undefined} */ (request.query)?.everywhere || "") === "1"
53
60
  });
54
61
  authService.clearSessionCookies(reply);
55
62
  return reply.redirect(destination);
@@ -7,6 +7,7 @@ import {
7
7
  ensureDevAuthExchangeAvailable,
8
8
  ensureDevAuthRuntimeAvailable
9
9
  } from "@jskit-ai/auth-core/server/devAuth";
10
+ import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
10
11
  import { hostOnlyCookieName, normalizeEmail, normalizeReturnToPath } from "@jskit-ai/auth-core/server/utils";
11
12
  import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
12
13
  import { AUTH_TEXTS, authFieldErrorDetails, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
@@ -78,13 +79,20 @@ function buildResult(identity, { session = null, appProfile = null } = {}) {
78
79
  * The auth.service for an OpenID Connect issuer. The issuer verifies who the
79
80
  * person is; this app keeps its own session cookie and its own users row,
80
81
  * keyed (oidc, sub).
82
+ * @param {object} dependencies
83
+ * @param {import("../types.js").OidcConfig} dependencies.config
84
+ * @param {import("../types.js").OidcStore} dependencies.store
85
+ * @param {import("../types.js").OidcIssuerClient} dependencies.issuer
86
+ * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector The `auth.profile.projector`, or noAppProfiles.
87
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
88
+ * @param {() => number} [dependencies.now]
81
89
  */
82
- function createOidcAuthService({ config, store, issuer, profileProjector = null, logger = null, now = Date.now }) {
90
+ function createOidcAuthService({ config, store, issuer, profileProjector, logger, now = Date.now }) {
83
91
  const sealer = createTransactionSealer({ secret: config.sessionSecret, now });
84
92
  const secureCookies = config.isProduction;
85
93
  // Production sessions use a host-only __Host- cookie, like the other providers.
86
94
  const sessionCookie = hostOnlyCookieName(SESSION_COOKIE, secureCookies);
87
- const projectorSyncs = typeof profileProjector?.syncIdentityProfile === "function";
95
+ const appProfileProjection = profileProjector !== noAppProfiles;
88
96
  const devLoginEnabled = config.devAuth.enabled === true && config.devAuth.isProduction !== true;
89
97
  const capabilities = normalizeAuthCapabilities({
90
98
  provider: { id: AUTH_OIDC_PROVIDER_ID, label: config.label },
@@ -102,25 +110,18 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
102
110
  providerLinking: { start: false, unlink: false },
103
111
  securityStatus: false,
104
112
  signOutOtherSessions: false,
105
- appProfileProjection: projectorSyncs,
113
+ appProfileProjection,
106
114
  devLoginAs: devLoginEnabled
107
115
  }
108
116
  });
109
117
 
110
118
  async function syncedResult(identity, { session = null } = {}) {
111
- if (!projectorSyncs) return buildResult(identity, { session });
119
+ if (!appProfileProjection) return buildResult(identity, { session });
112
120
  const appProfile = await profileProjector.syncIdentityProfile(buildProfile(identity));
113
- if (!appProfile || typeof appProfile !== "object") {
114
- throw new Error("auth.profile.projector.syncIdentityProfile() must return a profile object.");
115
- }
116
121
  return buildResult(identity, { session, appProfile });
117
122
  }
118
123
 
119
124
  async function existingProfile(identity) {
120
- if (!profileProjector) return null;
121
- if (typeof profileProjector.findByIdentity !== "function") {
122
- throw new Error("auth.profile.projector.findByIdentity() is required for preview identity and profile lookups without sync.");
123
- }
124
125
  return profileProjector.findByIdentity(buildProfile(identity));
125
126
  }
126
127
 
@@ -166,7 +167,7 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
166
167
  return origin.origin;
167
168
  }
168
169
 
169
- async function oauthStart(input = {}, request = null) {
170
+ async function oauthStart(input, request) {
170
171
  const provider = String(input.provider || AUTH_OIDC_PROVIDER_ID).trim().toLowerCase();
171
172
  if (provider !== AUTH_OIDC_PROVIDER_ID) {
172
173
  throw new AppError(400, `OAuth provider must be ${AUTH_OIDC_PROVIDER_ID}.`, {
@@ -225,7 +226,7 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
225
226
  return { sub: String(claims.sub), email, displayName: displayNameFrom(source, email), sid: String(claims.sid || "") };
226
227
  }
227
228
 
228
- async function oauthComplete(input = {}, request = null) {
229
+ async function oauthComplete(input, request) {
229
230
  const errorCode = String(input.error || input.error_code || "").trim();
230
231
  if (errorCode) {
231
232
  throw errorCode === "access_denied"
@@ -256,7 +257,7 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
256
257
  idTokenExpected: true
257
258
  });
258
259
  } catch (error) {
259
- logger?.warn?.({ err: { name: error?.name, code: error?.code, message: error?.message } }, "OIDC sign-in was rejected.");
260
+ logger.warn({ err: { name: error?.name, code: error?.code, message: error?.message } }, "OIDC sign-in was rejected.");
260
261
  throw new AppError(401, "Your sign-in could not be verified. Start again.", { code: "auth.oidc.signIn.unverified" });
261
262
  }
262
263
  const identity = await identityFromTokens(configuration, tokens);
@@ -273,8 +274,10 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
273
274
  return token ? store.findActiveSessionByTokenHash(sha256(token)) : null;
274
275
  }
275
276
 
276
- // A dev session, or a caller that asks only who is signed in (syncProfile:
277
- // false), reads the existing app profile instead of synchronizing it.
277
+ /**
278
+ * A dev session, or a caller that asks only who is signed in (syncProfile:
279
+ * false), reads the existing app profile instead of synchronizing it.
280
+ */
278
281
  async function authenticateRequest(request, { syncProfile = true } = {}) {
279
282
  const session = await sessionFromRequest(request);
280
283
  if (!session) return unauthenticated(hasSessionCookie(request));
@@ -290,7 +293,7 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
290
293
  let result;
291
294
  if (devSession || !syncProfile) {
292
295
  const appProfile = await existingProfile(identity);
293
- if (profileProjector && !appProfile) return unauthenticated(true);
296
+ if (appProfileProjection && !appProfile) return unauthenticated(true);
294
297
  result = buildResult(identity, { appProfile });
295
298
  } else {
296
299
  result = await syncedResult(identity);
@@ -305,10 +308,10 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
305
308
  };
306
309
  }
307
310
 
308
- async function devLoginAs(request, input = {}) {
311
+ async function devLoginAs(input, request) {
309
312
  ensureDevAuthExchangeAvailable(config.devAuth, request);
310
- const userId = String(input?.userId || "").trim();
311
- const email = normalizeEmail(input?.email);
313
+ const userId = String(input.userId || "").trim();
314
+ const email = normalizeEmail(input.email);
312
315
  if (!userId && !email) {
313
316
  throw createAuthError(AUTH_TEXTS.devUserRequired, {
314
317
  details: authFieldErrorDetails({ userId: AUTH_TEXTS.devUserRequired, email: AUTH_TEXTS.devUserRequired })
@@ -317,7 +320,7 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
317
320
  const known = await store.findKnownUser(AUTH_OIDC_PROVIDER_ID, { userId, email });
318
321
  const identity = known ? { sub: known.sub, email: known.email, displayName: known.displayName } : null;
319
322
  const appProfile = identity ? await existingProfile(identity) : null;
320
- if (!identity || (profileProjector && !appProfile)) {
323
+ if (!identity || (appProfileProjection && !appProfile)) {
321
324
  throw createAuthError(AUTH_TEXTS.devUserNotFound, {
322
325
  details: authFieldErrorDetails({
323
326
  ...(userId ? { userId: AUTH_TEXTS.devUserNotFound } : {}),
@@ -347,10 +350,16 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
347
350
  return Boolean(cookiesOf(request)[sessionCookie]);
348
351
  }
349
352
 
350
- async function logout(request) {
353
+ /** Revokes the request's app session and answers it, or null when it has none. */
354
+ async function endSession(request) {
351
355
  const session = await sessionFromRequest(request);
352
356
  if (session) await store.revokeSession(session.id);
353
- return { ok: true, clearSession: true, session };
357
+ return session;
358
+ }
359
+
360
+ async function logout(request) {
361
+ await endSession(request);
362
+ return { ok: true, clearSession: true };
354
363
  }
355
364
 
356
365
  /**
@@ -358,7 +367,7 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
358
367
  * end-session address so the person also signs out at the hub.
359
368
  */
360
369
  async function logoutEverywhere(request, { everywhere = false } = {}) {
361
- const { session } = await logout(request);
370
+ const session = await endSession(request);
362
371
  if (!everywhere || !session?.idToken || !session.clientId) return "/";
363
372
  try {
364
373
  const configuration = await issuer.configurationForClientId(session.clientId);
@@ -368,16 +377,24 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
368
377
  post_logout_redirect_uri: `${requestOrigin(request)}/`
369
378
  }).href;
370
379
  } catch (error) {
371
- logger?.warn?.({ err: error }, "OIDC end-session address is unavailable.");
380
+ logger.warn({ err: error }, "OIDC end-session address is unavailable.");
372
381
  return "/";
373
382
  }
374
383
  }
375
384
 
376
385
  const unsupported = (operation) => () => throwUnsupportedAuthOperation(operation);
377
386
 
387
+ function getCapabilities() {
388
+ return capabilities;
389
+ }
390
+
391
+ function isDevAuthBootstrapEnabled() {
392
+ return devLoginEnabled;
393
+ }
394
+
378
395
  return Object.freeze({
379
- getCapabilities: () => capabilities,
380
- isDevAuthBootstrapEnabled: () => devLoginEnabled,
396
+ getCapabilities,
397
+ isDevAuthBootstrapEnabled,
381
398
  devLoginAs,
382
399
  authenticateRequest,
383
400
  // One cookie carries the session, so both questions read it.
@@ -389,10 +406,7 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
389
406
  clearOAuthStartCookies,
390
407
  oauthStart,
391
408
  oauthComplete,
392
- logout: async (request) => {
393
- await logout(request);
394
- return { ok: true, clearSession: true };
395
- },
409
+ logout,
396
410
  logoutEverywhere,
397
411
  register: unsupported("register"),
398
412
  resendRegisterConfirmation: unsupported("resendRegisterConfirmation"),
@@ -405,6 +419,7 @@ function createOidcAuthService({ config, store, issuer, profileProjector = null,
405
419
  changePassword: unsupported("changePassword"),
406
420
  updateDisplayName: unsupported("updateDisplayName"),
407
421
  getSecurityStatus: unsupported("getSecurityStatus"),
422
+ // readable-check: allow setter-seam - not a slot: setPasswordSignInEnabled is an auth.service operation
408
423
  setPasswordSignInEnabled: unsupported("setPasswordSignInEnabled"),
409
424
  startProviderLink: unsupported("startProviderLink"),
410
425
  unlinkProvider: unsupported("unlinkProvider"),
@@ -51,96 +51,113 @@ function isDuplicateError(error) {
51
51
  /**
52
52
  * Knex storage for registered clients (one per issuer and app origin), app
53
53
  * sessions, and seen back-channel logout token ids.
54
+ * @param {object} dependencies
55
+ * @param {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} dependencies.knex
56
+ * @param {() => number} [dependencies.now]
54
57
  */
55
58
  function createOidcStore({ knex, now = Date.now }) {
56
- if (typeof knex !== "function") throw new TypeError("OIDC sign-in requires runtime.database knex.");
57
59
  const stamp = () => new Date(now());
58
60
 
59
- return Object.freeze({
60
- async findClient(issuer, origin) {
61
- return mapClient(await knex(TABLES.clients).where({ issuer, origin }).first());
62
- },
63
- async listClientIds(issuer) {
64
- const rows = await knex(TABLES.clients).where({ issuer }).select("client_id");
65
- return rows.map((row) => row.client_id);
66
- },
67
- // Two first sign-ins may register at once; the first stored client wins.
68
- async insertClient(client) {
69
- try {
70
- await knex(TABLES.clients).insert({
71
- issuer: client.issuer,
72
- origin: client.origin,
73
- client_id: client.clientId,
74
- client_secret: client.clientSecret || null,
75
- registration_access_token: client.registrationAccessToken || null,
76
- registration_client_uri: client.registrationClientUri || null,
77
- created_at: stamp(),
78
- updated_at: stamp()
79
- });
80
- } catch (error) {
81
- if (!isDuplicateError(error)) throw error;
82
- }
83
- return mapClient(await knex(TABLES.clients).where({ issuer: client.issuer, origin: client.origin }).first());
84
- },
85
-
86
- async createSession(session) {
87
- const createdAt = stamp();
88
- await knex(TABLES.sessions).insert({
89
- id: session.id,
90
- token_hash: session.tokenHash,
91
- issuer: session.issuer,
92
- client_id: session.clientId || null,
93
- sub: session.sub,
94
- sid: session.sid || null,
95
- email: session.email,
96
- display_name: session.displayName,
97
- id_token: session.idToken || null,
98
- purpose: session.purpose,
99
- expires_at: toDate(session.expiresAt),
100
- created_at: createdAt,
101
- updated_at: createdAt
61
+ async function findClient(issuer, origin) {
62
+ return mapClient(await knex(TABLES.clients).where({ issuer, origin }).first());
63
+ }
64
+
65
+ async function listClientIds(issuer) {
66
+ const rows = await knex(TABLES.clients).where({ issuer }).select("client_id");
67
+ return rows.map((row) => row.client_id);
68
+ }
69
+
70
+ /** Two first sign-ins may register at once; the first stored client wins. */
71
+ async function insertClient(client) {
72
+ try {
73
+ await knex(TABLES.clients).insert({
74
+ issuer: client.issuer,
75
+ origin: client.origin,
76
+ client_id: client.clientId,
77
+ client_secret: client.clientSecret || null,
78
+ registration_access_token: client.registrationAccessToken || null,
79
+ registration_client_uri: client.registrationClientUri || null,
80
+ created_at: stamp(),
81
+ updated_at: stamp()
102
82
  });
103
- },
104
- async findActiveSessionByTokenHash(tokenHash) {
105
- const session = mapSession(await knex(TABLES.sessions).where({ token_hash: tokenHash }).first());
106
- return session && !session.revokedAt && !isExpired(session.expiresAt, now()) ? session : null;
107
- },
108
- async revokeSession(id) {
109
- await knex(TABLES.sessions).where({ id }).whereNull("revoked_at").update({ revoked_at: stamp(), updated_at: stamp() });
110
- },
111
- // A subject ends all of that person's sessions; an issuer session id alone ends its own.
112
- async revokeIssuerSessions(issuer, { sub = "", sid = "" } = {}) {
113
- if (!sub && !sid) return 0;
114
- return knex(TABLES.sessions).where({ issuer }).whereNull("revoked_at")
115
- .andWhere(sub ? { sub } : { sid })
116
- .update({ revoked_at: stamp(), updated_at: stamp() });
117
- },
118
-
119
- // Returns false when this token id was already used.
120
- async rememberLogoutToken(issuer, jti, expiresAt) {
121
- await knex(TABLES.logoutTokens).where("expires_at", "<=", stamp()).del();
122
- try {
123
- await knex(TABLES.logoutTokens).insert({ issuer, jti, expires_at: toDate(expiresAt) });
124
- return true;
125
- } catch (error) {
126
- if (isDuplicateError(error)) return false;
127
- throw error;
128
- }
129
- },
130
-
131
- // Preview identity signs in as an account the app already knows.
132
- async findKnownUser(provider, { userId = "", email = "" } = {}) {
133
- const query = knex("users").where({ auth_provider: provider });
134
- if (userId) query.andWhere({ auth_provider_user_sid: userId });
135
- else query.andWhere({ email });
136
- let row;
137
- try {
138
- row = await query.first("auth_provider_user_sid", "email", "display_name");
139
- } catch {
140
- return null;
141
- }
142
- return row ? { sub: row.auth_provider_user_sid, email: row.email, displayName: row.display_name } : null;
83
+ } catch (error) {
84
+ if (!isDuplicateError(error)) throw error;
143
85
  }
86
+ return mapClient(await knex(TABLES.clients).where({ issuer: client.issuer, origin: client.origin }).first());
87
+ }
88
+
89
+ async function createSession(session) {
90
+ const createdAt = stamp();
91
+ await knex(TABLES.sessions).insert({
92
+ id: session.id,
93
+ token_hash: session.tokenHash,
94
+ issuer: session.issuer,
95
+ client_id: session.clientId || null,
96
+ sub: session.sub,
97
+ sid: session.sid || null,
98
+ email: session.email,
99
+ display_name: session.displayName,
100
+ id_token: session.idToken || null,
101
+ purpose: session.purpose,
102
+ expires_at: toDate(session.expiresAt),
103
+ created_at: createdAt,
104
+ updated_at: createdAt
105
+ });
106
+ }
107
+
108
+ async function findActiveSessionByTokenHash(tokenHash) {
109
+ const session = mapSession(await knex(TABLES.sessions).where({ token_hash: tokenHash }).first());
110
+ return session && !session.revokedAt && !isExpired(session.expiresAt, now()) ? session : null;
111
+ }
112
+
113
+ async function revokeSession(id) {
114
+ await knex(TABLES.sessions).where({ id }).whereNull("revoked_at").update({ revoked_at: stamp(), updated_at: stamp() });
115
+ }
116
+
117
+ /** A subject ends all of that person's sessions; an issuer session id alone ends its own. */
118
+ async function revokeIssuerSessions(issuer, { sub = "", sid = "" } = {}) {
119
+ if (!sub && !sid) return 0;
120
+ return knex(TABLES.sessions).where({ issuer }).whereNull("revoked_at")
121
+ .andWhere(sub ? { sub } : { sid })
122
+ .update({ revoked_at: stamp(), updated_at: stamp() });
123
+ }
124
+
125
+ /** Returns false when this token id was already used. */
126
+ async function rememberLogoutToken(issuer, jti, expiresAt) {
127
+ await knex(TABLES.logoutTokens).where("expires_at", "<=", stamp()).del();
128
+ try {
129
+ await knex(TABLES.logoutTokens).insert({ issuer, jti, expires_at: toDate(expiresAt) });
130
+ return true;
131
+ } catch (error) {
132
+ if (isDuplicateError(error)) return false;
133
+ throw error;
134
+ }
135
+ }
136
+
137
+ /** Preview identity signs in as an account the app already knows. */
138
+ async function findKnownUser(provider, { userId = "", email = "" } = {}) {
139
+ const query = knex("users").where({ auth_provider: provider });
140
+ if (userId) query.andWhere({ auth_provider_user_sid: userId });
141
+ else query.andWhere({ email });
142
+ let row;
143
+ try {
144
+ row = await query.first("auth_provider_user_sid", "email", "display_name");
145
+ } catch {
146
+ return null;
147
+ }
148
+ return row ? { sub: row.auth_provider_user_sid, email: row.email, displayName: row.display_name } : null;
149
+ }
150
+
151
+ return Object.freeze({
152
+ findClient,
153
+ listClientIds,
154
+ insertClient,
155
+ createSession,
156
+ findActiveSessionByTokenHash,
157
+ revokeSession,
158
+ revokeIssuerSessions,
159
+ rememberLogoutToken,
160
+ findKnownUser
144
161
  });
145
162
  }
146
163
 
@@ -11,6 +11,7 @@ function transactionKey(secret) {
11
11
  return Buffer.from(hkdfSync("sha256", Buffer.from(secret, "utf8"), Buffer.alloc(0), "jskit-oidc-attempt-v1", 32));
12
12
  }
13
13
 
14
+ /** @param {{ secret: string, now?: () => number }} options */
14
15
  function createTransactionSealer({ secret, now = Date.now }) {
15
16
  const key = transactionKey(secret);
16
17
 
@@ -36,7 +37,10 @@ function createTransactionSealer({ secret, now = Date.now }) {
36
37
  }
37
38
  }
38
39
 
39
- return Object.freeze({ open, seal });
40
+ return Object.freeze({
41
+ open,
42
+ seal
43
+ });
40
44
  }
41
45
 
42
46
  function transactionCookieOptions(secure, maxAge = TRANSACTION_TTL_SECONDS) {
@@ -2,6 +2,7 @@ import {
2
2
  attachDeferredAuthService,
3
3
  createDeferredAuthService
4
4
  } from "@jskit-ai/auth-core/server/deferredAuthService";
5
+ import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
5
6
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
6
7
  import { createBackchannelLogout } from "../lib/backchannelLogout.js";
7
8
  import { resolveOidcConfig } from "../lib/config.js";
@@ -20,13 +21,26 @@ const AuthOidcProvider = defineProvider({
20
21
  fastify: "runtime.fastify",
21
22
  logger: "runtime.logger"
22
23
  },
24
+ optional: {
25
+ profileProjector: "auth.profile.projector"
26
+ },
23
27
  provides: {
24
28
  authService: "auth.service"
25
29
  },
26
30
  setup() {
27
31
  return { authService: createDeferredAuthService() };
28
32
  },
29
- async boot({ appRoot, database, env, extensions, fastify, logger }, { outputs }) {
33
+ /**
34
+ * @param {object} dependencies
35
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} dependencies.appRoot
36
+ * @param {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase} dependencies.database
37
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
38
+ * @param {import("@jskit-ai/auth-core/server/types").AuthExtensions} dependencies.extensions
39
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeFastify} dependencies.fastify
40
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
41
+ * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector | null} dependencies.profileProjector The `auth.profile.projector`, when one is installed.
42
+ */
43
+ async boot({ appRoot, database, env, extensions, fastify, logger, profileProjector }, { outputs }) {
30
44
  const config = resolveOidcConfig({ env, appRoot });
31
45
  const store = createOidcStore({ knex: database.knex });
32
46
  const issuer = createIssuerClient({ config, store, logger });
@@ -34,18 +48,20 @@ const AuthOidcProvider = defineProvider({
34
48
  config,
35
49
  store,
36
50
  issuer,
37
- profileProjector: extensions.resolveProfileProjector(),
51
+ profileProjector: profileProjector ?? noAppProfiles,
38
52
  logger
39
53
  });
40
- attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
54
+ const authService = extensions.decorateService(baseService);
55
+ // readable-check: allow setter-seam - deferred until boot: auth.service is built after every setup has registered its auth extensions, and those setups already receive it
56
+ attachDeferredAuthService(outputs.authService, authService);
41
57
  await registerOidcRoutes(fastify, {
42
- authService: baseService,
58
+ authService,
43
59
  backchannelLogout: createBackchannelLogout({ config, store, issuer })
44
60
  });
45
61
  if (config.appPublicOrigin && !config.setupProblem) {
46
62
  // Registering early lets the hub's owner approve this address before anyone signs in.
47
63
  issuer.clientFor(config.appPublicOrigin, { appName: config.appName }).catch((error) => {
48
- logger?.info?.({ reason: error?.message }, "OIDC client is not ready yet; sign-in will retry.");
64
+ logger.info({ reason: error?.message }, "OIDC client is not ready yet; sign-in will retry.");
49
65
  });
50
66
  }
51
67
  }
@@ -0,0 +1,7 @@
1
+ // The relying party's own types, named once for the modules that share them.
2
+
3
+ /** @typedef {ReturnType<typeof import("./lib/config.js").resolveOidcConfig>} OidcConfig The relying party's settings, read once from its Env. */
4
+ /** @typedef {ReturnType<typeof import("./lib/store.js").createOidcStore>} OidcStore Where the relying party keeps its issuer clients, app sessions and seen logout tokens. */
5
+ /** @typedef {ReturnType<typeof import("./lib/issuer.js").createIssuerClient>} OidcIssuerClient The relying party's view of its issuer. */
6
+
7
+ export {};
@@ -9,7 +9,7 @@ import fastifyCookie from "@fastify/cookie";
9
9
  import createKnex from "knex";
10
10
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
11
11
  import { createAuthExtensions } from "@jskit-ai/auth-core/server/authExtensions";
12
- import { buildAuthActions } from "@jskit-ai/auth-core/server/actions/auth.contributor";
12
+ import { createAuthActions } from "@jskit-ai/auth-core/server/actions/authActions";
13
13
  import { AuthController } from "@jskit-ai/auth-web/server/controllers/AuthController";
14
14
  import { AuthWebService } from "@jskit-ai/auth-web/server/services/AuthWebService";
15
15
  import packageJson from "../package.json" with { type: "json" };
@@ -21,13 +21,15 @@ import { followAuthorization, startMockIssuer } from "../test-support/mockIssuer
21
21
 
22
22
  const quietLogger = { info() {}, warn() {}, error() {}, debug() {} };
23
23
 
24
- async function startApp(t, { env = {} } = {}) {
24
+ async function startApp(t, { env = {}, configureExtensions = () => {} } = {}) {
25
25
  const issuer = await startMockIssuer();
26
26
  const appRoot = await mkdtemp(path.join(tmpdir(), "jskit-oidc-app-"));
27
27
  const knex = createKnex({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
28
28
  await migration.up(knex);
29
29
  const fastify = Fastify();
30
30
  await fastify.register(fastifyCookie);
31
+ const extensions = createAuthExtensions();
32
+ configureExtensions(extensions);
31
33
  let authService = null;
32
34
  const probe = defineProvider({
33
35
  id: "test.oidc.probe",
@@ -49,7 +51,7 @@ async function startApp(t, { env = {} } = {}) {
49
51
  },
50
52
  "runtime.fastify": fastify,
51
53
  "runtime.logger": quietLogger,
52
- "auth.extensions": createAuthExtensions()
54
+ "auth.extensions": extensions
53
55
  },
54
56
  providers: [AuthOidcProvider, probe]
55
57
  });
@@ -89,7 +91,7 @@ function replyFixture() {
89
91
 
90
92
  // The auth-web controller, its actions and this provider, without the HTTP runtime.
91
93
  function authWeb(authService) {
92
- const actions = new Map(buildAuthActions({ authService }).map((action) => [action.id, action]));
94
+ const actions = new Map(createAuthActions({ authService }).map((action) => [action.id, action]));
93
95
  const request = (extra = {}) => ({
94
96
  headers: { host: "localhost:5173" },
95
97
  protocol: "http",
@@ -100,7 +102,7 @@ function authWeb(authService) {
100
102
  },
101
103
  ...extra
102
104
  });
103
- return { controller: new AuthController({ service: new AuthWebService({ authService }) }), request };
105
+ return { controller: new AuthController({ service: new AuthWebService({ authService, devAuthBootstrapEnabled: false }) }), request };
104
106
  }
105
107
 
106
108
  test("the package provides auth.service with the documented descriptor", () => {
@@ -111,11 +113,11 @@ test("the package provides auth.service with the documented descriptor", () => {
111
113
 
112
114
  test("capabilities: one OIDC button, no password features, preview identity unchanged", async (t) => {
113
115
  const { authService } = await startApp(t, {
114
- env: { AUTH_OIDC_LABEL: "Sign in with Mobily", AUTH_DEV_BYPASS_ENABLED: "true", AUTH_DEV_BYPASS_SECRET: "preview-secret-0123456789abcdef" }
116
+ env: { AUTH_OIDC_LABEL: "Sign in with Example", AUTH_DEV_BYPASS_ENABLED: "true", AUTH_DEV_BYPASS_SECRET: "preview-secret-0123456789abcdef" }
115
117
  });
116
118
  const { provider, features } = authService.getCapabilities();
117
- assert.deepEqual(provider, { id: "oidc", label: "Sign in with Mobily" });
118
- assert.deepEqual(features.oauthLogin, { enabled: true, providers: [{ id: "oidc", label: "Sign in with Mobily" }], defaultProvider: "oidc" });
119
+ assert.deepEqual(provider, { id: "oidc", label: "Sign in with Example" });
120
+ assert.deepEqual(features.oauthLogin, { enabled: true, providers: [{ id: "oidc", label: "Sign in with Example" }], defaultProvider: "oidc" });
119
121
  assert.deepEqual(features.password, { login: false, register: false, change: false, methodToggle: false });
120
122
  assert.equal(features.passwordRecovery.request, false);
121
123
  assert.equal(features.otp.login, false);
@@ -213,3 +215,28 @@ test("the logout route ignores cross-site links and clears the session", async (
213
215
  assert.equal(sameOrigin.headers.location, "/");
214
216
  assert.match(String(sameOrigin.headers["set-cookie"]), /jskit_oidc_session=;/u);
215
217
  });
218
+
219
+ test("the logout route signs out through auth.service with the application's decorators", async (t) => {
220
+ const cleared = [];
221
+ const { fastify } = await startApp(t, {
222
+ configureExtensions(extensions) {
223
+ extensions.registerServiceDecorator({
224
+ decoratorId: "test.oidc.clearAppCookie",
225
+ decorateAuthService(authService) {
226
+ return Object.freeze(Object.defineProperties(Object.create(authService), {
227
+ clearSessionCookies: {
228
+ enumerable: true,
229
+ value(reply) {
230
+ cleared.push("app cookie");
231
+ return authService.clearSessionCookies(reply);
232
+ }
233
+ }
234
+ }));
235
+ }
236
+ });
237
+ }
238
+ });
239
+ const response = await fastify.inject({ method: "GET", url: AUTH_OIDC_LOGOUT_PATH, headers: { "sec-fetch-site": "same-origin" } });
240
+ assert.equal(response.statusCode, 302);
241
+ assert.deepEqual(cleared, ["app cookie"]);
242
+ });
@@ -192,7 +192,7 @@ test("preview identity signs in as an existing oidc users row only", async (t) =
192
192
  await issuer.close();
193
193
  });
194
194
  const previewRequest = { ...requestAt(), headers: { host: "localhost:5173", "x-jskit-dev-auth-secret": "preview-secret-0123456789abcdef" } };
195
- await assert.rejects(rp.service.devLoginAs(previewRequest, { email: issuer.account.email }), {
195
+ await assert.rejects(rp.service.devLoginAs({ email: issuer.account.email }, previewRequest), {
196
196
  message: "User not found.",
197
197
  code: "auth.dev.userNotFound",
198
198
  details: {
@@ -203,9 +203,9 @@ test("preview identity signs in as an existing oidc users row only", async (t) =
203
203
 
204
204
  const { input, request } = await signInAtIssuer(rp);
205
205
  await rp.service.oauthComplete(input, request);
206
- const byEmail = await rp.service.devLoginAs(previewRequest, { email: issuer.account.email });
206
+ const byEmail = await rp.service.devLoginAs({ email: issuer.account.email }, previewRequest);
207
207
  assert.equal(byEmail.actor.providerUserId, issuer.account.sub);
208
- const bySubject = await rp.service.devLoginAs(previewRequest, { userId: issuer.account.sub });
208
+ const bySubject = await rp.service.devLoginAs({ userId: issuer.account.sub }, previewRequest);
209
209
  assert.equal(bySubject.actor.email, issuer.account.email);
210
210
 
211
211
  const signedIn = await rp.service.authenticateRequest({ ...previewRequest, cookies: { jskit_oidc_session: bySubject.session.token } });
@@ -53,7 +53,15 @@ function createProfileProjector(knex) {
53
53
  };
54
54
  }
55
55
 
56
- async function createRelyingParty({ issuer, env = {}, fetchImpl = null, now = Date.now } = {}) {
56
+ /**
57
+ * A relying party over an in-memory database, signing in at the given issuer.
58
+ * @param {object} options
59
+ * @param {Awaited<ReturnType<typeof import("./mockIssuer.js").startMockIssuer>>} options.issuer
60
+ * @param {Record<string, string>} [options.env] Env values over the test defaults.
61
+ * @param {typeof fetch} [options.fetchImpl]
62
+ * @param {() => number} [options.now]
63
+ */
64
+ async function createRelyingParty({ issuer, env = {}, fetchImpl = globalThis.fetch, now = Date.now }) {
57
65
  const appRoot = await mkdtemp(path.join(tmpdir(), "jskit-oidc-rp-"));
58
66
  const knex = await createDatabase();
59
67
  const config = resolveOidcConfig({
@@ -66,12 +74,14 @@ async function createRelyingParty({ issuer, env = {}, fetchImpl = null, now = Da
66
74
  }
67
75
  });
68
76
  const store = createOidcStore({ knex, now });
69
- const issuerClient = createIssuerClient({ config, store, fetchImpl, now });
77
+ const logger = { info() {}, warn() {} };
78
+ const issuerClient = createIssuerClient({ config, store, logger, fetchImpl, now });
70
79
  const service = createOidcAuthService({
71
80
  config,
72
81
  store,
73
82
  issuer: issuerClient,
74
83
  profileProjector: createProfileProjector(knex),
84
+ logger,
75
85
  now
76
86
  });
77
87
  const backchannel = createBackchannelLogout({ config, store, issuer: issuerClient, now });
@@ -81,7 +81,7 @@ async function startMockIssuer({ blocked = false, account = ACCOUNT, staticClien
81
81
  return new SignJWT(claims).setProtectedHeader({ alg: "RS256", kid: "test-key", typ }).sign(privateKey);
82
82
  },
83
83
  async close() {
84
- server.closeAllConnections?.();
84
+ server.closeAllConnections();
85
85
  server.close();
86
86
  await once(server, "close");
87
87
  }