@leitwerk-dev/server 0.4.2 → 0.4.3

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.
Files changed (55) hide show
  1. package/dist/{app-CtlotzYm.d.ts → app-DZUsf76a.d.ts} +30 -1
  2. package/dist/app-MELYT4QS.js +8 -0
  3. package/dist/auth/api-token-routes.d.ts.map +1 -1
  4. package/dist/auth/api-token-service.d.ts +2 -1
  5. package/dist/auth/api-token-service.d.ts.map +1 -1
  6. package/dist/auth/auth-client.d.ts +2 -4
  7. package/dist/auth/auth-client.d.ts.map +1 -1
  8. package/dist/auth/auth-config.d.ts +2 -1
  9. package/dist/auth/auth-config.d.ts.map +1 -1
  10. package/dist/auth/auth-service.d.ts +3 -1
  11. package/dist/auth/auth-service.d.ts.map +1 -1
  12. package/dist/auth/auth-test-helpers.d.ts +17 -0
  13. package/dist/auth/auth-test-helpers.d.ts.map +1 -1
  14. package/dist/auth/oidc-client.d.ts +2 -0
  15. package/dist/auth/oidc-client.d.ts.map +1 -1
  16. package/dist/auth/oidc-evidence.d.ts +18 -0
  17. package/dist/auth/oidc-evidence.d.ts.map +1 -0
  18. package/dist/auth/routes.d.ts.map +1 -1
  19. package/dist/{chunk-YLWY4UTT.js → chunk-2OC3SK6F.js} +115 -5
  20. package/dist/chunk-2OC3SK6F.js.map +1 -0
  21. package/dist/{chunk-OUA5EZS2.js → chunk-SKQGTUDA.js} +108 -61
  22. package/dist/chunk-SKQGTUDA.js.map +1 -0
  23. package/dist/config/config-loader.d.ts.map +1 -1
  24. package/dist/config/config-types.d.ts +17 -0
  25. package/dist/config/config-types.d.ts.map +1 -1
  26. package/dist/db/api-token-repo.d.ts +3 -0
  27. package/dist/db/api-token-repo.d.ts.map +1 -1
  28. package/dist/db/auth-repo.d.ts +5 -0
  29. package/dist/db/auth-repo.d.ts.map +1 -1
  30. package/dist/db/database.d.ts.map +1 -1
  31. package/dist/db/schema.d.ts +32 -0
  32. package/dist/db/schema.d.ts.map +1 -1
  33. package/dist/index.js +2 -2
  34. package/dist/main.js +3 -3
  35. package/dist/testing.js +1 -1
  36. package/package.json +12 -12
  37. package/src/auth/api-token-routes.ts +5 -2
  38. package/src/auth/api-token-service.ts +16 -4
  39. package/src/auth/auth-client.ts +2 -2
  40. package/src/auth/auth-config.ts +18 -19
  41. package/src/auth/auth-service.ts +56 -22
  42. package/src/auth/auth-test-helpers.ts +71 -0
  43. package/src/auth/oidc-client.ts +30 -12
  44. package/src/auth/oidc-evidence.ts +113 -0
  45. package/src/auth/routes.ts +22 -6
  46. package/src/config/config-loader.ts +34 -0
  47. package/src/config/config-types.ts +18 -0
  48. package/src/db/api-token-repo.ts +6 -1
  49. package/src/db/auth-repo.ts +7 -0
  50. package/src/db/database.ts +14 -0
  51. package/src/db/schema.ts +2 -0
  52. package/dist/app-KR3N2JAE.js +0 -8
  53. package/dist/chunk-OUA5EZS2.js.map +0 -1
  54. package/dist/chunk-YLWY4UTT.js.map +0 -1
  55. /package/dist/{app-KR3N2JAE.js.map → app-MELYT4QS.js.map} +0 -0
@@ -46,6 +46,7 @@ import {
46
46
  defaultWorkerRuntimeProfile,
47
47
  deferTurnWaitStarts,
48
48
  evaluateAtStableAvailabilityRevision,
49
+ evidenceAllows,
49
50
  failLaunchRun,
50
51
  finishLaunchRun,
51
52
  generateId,
@@ -108,6 +109,7 @@ import {
108
109
  resolveRegisteredProviderOptions,
109
110
  resolveWorkerPiAgentDir,
110
111
  routeConfig,
112
+ safeClaims,
111
113
  selectWorkerRuntimeProfile,
112
114
  sendActionRequestNormalizationError,
113
115
  sendLauncherLookupFailure,
@@ -130,7 +132,7 @@ import {
130
132
  verifyOpaqueToken,
131
133
  withTimeout,
132
134
  writeTurnWait
133
- } from "./chunk-YLWY4UTT.js";
135
+ } from "./chunk-2OC3SK6F.js";
134
136
 
135
137
  // src/app.ts
136
138
  import path10 from "node:path";
@@ -162,19 +164,15 @@ var DEFAULT_LOGIN_FLOW_TTL_MS = 10 * 60 * 1e3;
162
164
  function resolveAuthConfig(config) {
163
165
  const auth = config.auth;
164
166
  const serverBaseUrl = new URL(config.server.base_url);
165
- const providers = (auth?.providers ?? []).map(
166
- (provider) => provider.kind === "oidc" ? {
167
+ const providers = (auth?.providers ?? []).map((provider) => {
168
+ const redirect_uri = provider.redirect_uri ?? new URL("/auth/callback", serverBaseUrl).toString();
169
+ return provider.kind === "oidc" ? {
167
170
  ...provider,
168
- redirect_uri: provider.redirect_uri ?? new URL("/auth/callback", serverBaseUrl).toString(),
171
+ redirect_uri,
169
172
  scopes: provider.scopes ?? ["openid", "profile", "email"],
170
173
  identity_claim: provider.identity_claim ?? "preferred_username"
171
- } : {
172
- ...provider,
173
- redirect_uri: provider.redirect_uri ?? new URL("/auth/callback", serverBaseUrl).toString(),
174
- scopes: ["read:org"],
175
- identity_claim: "login"
176
- }
177
- );
174
+ } : { ...provider, redirect_uri, scopes: ["read:org"], identity_claim: "login" };
175
+ });
178
176
  const sessionCookieName = auth?.session?.cookie_name ?? DEFAULT_SESSION_COOKIE_NAME;
179
177
  return {
180
178
  enabled: auth?.enabled === true && providers.length > 0,
@@ -194,20 +192,16 @@ function resolveAuthConfig(config) {
194
192
  allowlist: new Set(auth?.allowlist ?? [])
195
193
  };
196
194
  }
197
- function isActorAllowedByConfig(actor, auth) {
195
+ function isActorAllowedByConfig(actor, auth, evidence) {
198
196
  if (!auth.enabled) {
199
197
  return true;
200
198
  }
201
199
  if (actor.kind !== "user" || actor.provider === null) {
202
200
  return false;
203
201
  }
204
- if (!auth.providers.some((provider2) => provider2.id === actor.provider)) {
205
- return false;
206
- }
207
- const prefix = `${actor.provider}:`;
208
- if (!actor.id.startsWith(prefix)) return false;
209
202
  const provider = auth.providers.find((candidate) => candidate.id === actor.provider);
210
- return provider?.kind === "oauth2" || auth.allowlist.has(actor.id.slice(prefix.length));
203
+ if (!provider || !actor.id.startsWith(`${actor.provider}:`)) return false;
204
+ return provider.kind === "oauth2" || provider.kind === "oidc" && evidenceAllows(actor, provider, evidence, auth.allowlist);
211
205
  }
212
206
 
213
207
  // src/auth/api-token-service.ts
@@ -235,12 +229,19 @@ function createApiTokenService(input) {
235
229
  if (auth.enabled) repo.revokeAnonymous((/* @__PURE__ */ new Date()).toISOString());
236
230
  return {
237
231
  policy,
238
- ownerForActor(actor) {
232
+ ownerForActor(actor, oidcEvidence) {
239
233
  if (!auth.enabled)
240
234
  return { kind: "anonymous", id: "anonymous", actor: ADMIN_ACTOR, providerBinding: null };
241
235
  const provider = auth.providers.find((p) => p.id === actor.provider);
242
- if (!provider || !isActorAllowedByConfig(actor, auth)) throw new Error("Invalid token owner");
243
- return { kind: "user", id: actor.id, actor, providerBinding: binding(provider) };
236
+ if (!provider || !isActorAllowedByConfig(actor, auth, oidcEvidence))
237
+ throw new Error("Invalid token owner");
238
+ return {
239
+ kind: "user",
240
+ id: actor.id,
241
+ actor,
242
+ providerBinding: binding(provider),
243
+ oidcEvidence
244
+ };
244
245
  },
245
246
  create(owner, name, expiresAt) {
246
247
  if (!policy.enabled) throw new ApiTokenValidationError("API token issuance is disabled");
@@ -283,7 +284,8 @@ function createApiTokenService(input) {
283
284
  if (token.owner.kind === "anonymous") {
284
285
  if (auth.enabled) return denied;
285
286
  } else {
286
- if (!auth.enabled || !isActorAllowedByConfig(token.owner.actor, auth)) return denied;
287
+ if (!auth.enabled || !isActorAllowedByConfig(token.owner.actor, auth, token.owner.oidcEvidence))
288
+ return denied;
287
289
  const provider = auth.providers.find((p) => p.id === token.owner.actor.provider);
288
290
  if (!provider || JSON.stringify(binding(provider)) !== JSON.stringify(token.owner.providerBinding))
289
291
  return denied;
@@ -384,13 +386,13 @@ import {
384
386
  allowInsecureRequests,
385
387
  authorizationCodeGrant,
386
388
  buildAuthorizationUrl,
389
+ ClientError,
387
390
  ClientSecretPost,
388
391
  calculatePKCECodeChallenge,
389
392
  discovery,
390
393
  fetchUserInfo,
391
394
  randomPKCECodeVerifier,
392
- randomState,
393
- skipSubjectCheck
395
+ randomState
394
396
  } from "openid-client";
395
397
  function createOpenIdClient() {
396
398
  const configs = /* @__PURE__ */ new Map();
@@ -439,20 +441,25 @@ function createOpenIdClient() {
439
441
  { redirect_uri: input.provider.redirect_uri }
440
442
  );
441
443
  const idClaims = tokens.claims();
444
+ if (!idClaims || typeof idClaims.sub !== "string" || !idClaims.sub.trim()) {
445
+ throw new Error("OIDC ID token requires a valid subject");
446
+ }
447
+ let userInfo = null;
442
448
  if (tokens.access_token) {
443
- const expectedSubject = typeof idClaims?.sub === "string" ? idClaims.sub : skipSubjectCheck;
444
449
  try {
445
- const userInfo = await fetchUserInfo(
446
- config,
447
- tokens.access_token,
448
- expectedSubject
449
- );
450
- return { claims: { ...idClaims ?? {}, ...userInfo } };
451
- } catch {
450
+ userInfo = await fetchUserInfo(config, tokens.access_token, idClaims.sub);
451
+ } catch (error) {
452
+ if (!(error instanceof TypeError) && !(error instanceof ClientError && (error.code === "OAUTH_TIMEOUT" || error.cause instanceof Response && error.cause.status >= 500)))
453
+ throw new Error("OIDC UserInfo validation failed");
452
454
  }
455
+ if (userInfo && userInfo.sub !== idClaims.sub)
456
+ throw new Error("OIDC UserInfo subject mismatch");
453
457
  }
454
- if (idClaims) return { claims: idClaims };
455
- throw new Error("OIDC token response did not include an access token or id_token claims");
458
+ return {
459
+ claims: userInfo ? { ...idClaims, ...userInfo } : idClaims,
460
+ idTokenClaims: idClaims,
461
+ userInfoClaims: userInfo
462
+ };
456
463
  }
457
464
  };
458
465
  }
@@ -505,14 +512,21 @@ function consumeValidFlow(repos, cookieValue) {
505
512
  }
506
513
  function createAuthService(input) {
507
514
  const auth = resolveAuthConfig(input.config);
508
- const authClient = input.authClient ?? createAuthClient({
509
- oidc: input.oidcClient ?? createOpenIdClient()
510
- });
515
+ const authClient = input.authClient ?? createAuthClient({ oidc: input.oidcClient });
511
516
  const sweepExpiredAuthState = () => ({
512
517
  sessions: input.repos.authSessions.deleteExpired(),
513
518
  loginFlows: input.repos.authLoginFlows.deleteExpired()
514
519
  });
515
520
  sweepExpiredAuthState();
521
+ function resolveSessionRecord(cookieValue) {
522
+ if (!auth.enabled || !cookieValue) return null;
523
+ const idHash = hashOpaqueToken(cookieValue);
524
+ const session = input.repos.authSessions.getValid(idHash);
525
+ if (!session) return null;
526
+ if (isActorAllowedByConfig(session.actor, auth, session.oidcEvidence)) return session;
527
+ input.repos.authSessions.delete(idHash);
528
+ return null;
529
+ }
516
530
  return {
517
531
  config: auth,
518
532
  apiTokens: createApiTokenService({
@@ -560,36 +574,52 @@ function createAuthService(input) {
560
574
  state: flow.state,
561
575
  pkceVerifier: flow.pkceVerifier
562
576
  });
563
- const actor = actorFromOidcClaims({ provider, claims: exchanged.claims });
577
+ const actor = actorFromOidcClaims({ provider, claims: safeClaims(exchanged.claims) });
564
578
  if (!actor) {
565
579
  throw new Error(`Authentication identity claim ${provider.identity_claim} was not present`);
566
580
  }
567
- if (!isActorAllowedByConfig(actor, auth)) {
568
- throw new Error("Authenticated user is not allowlisted");
581
+ let oidcEvidence = null;
582
+ if (provider.kind === "oidc") {
583
+ const idTokenClaims = safeClaims(exchanged.idTokenClaims ?? {});
584
+ const userInfoClaims = exchanged.userInfoClaims ? safeClaims(exchanged.userInfoClaims) : null;
585
+ if (typeof idTokenClaims.sub !== "string" || !idTokenClaims.sub.trim() || userInfoClaims && userInfoClaims.sub !== idTokenClaims.sub)
586
+ throw new Error("Invalid OIDC subject evidence");
587
+ const claims = { ...idTokenClaims, ...userInfoClaims };
588
+ const groups = claims[provider.access?.groups_claim ?? "groups"];
589
+ oidcEvidence = {
590
+ providerId: provider.id,
591
+ issuer: provider.issuer,
592
+ identityClaim: provider.identity_claim,
593
+ subject: idTokenClaims.sub,
594
+ loginAt: (/* @__PURE__ */ new Date()).toISOString(),
595
+ idTokenClaims,
596
+ userInfoClaims,
597
+ facts: {
598
+ identity: actor.id.slice(provider.id.length + 1),
599
+ email: typeof claims.email === "string" ? claims.email : null,
600
+ emailVerified: claims.email_verified === true,
601
+ groups: Array.isArray(groups) && groups.every((group) => typeof group === "string") ? groups : []
602
+ }
603
+ };
604
+ }
605
+ if (!isActorAllowedByConfig(actor, auth, oidcEvidence)) {
606
+ throw new Error("Authenticated user does not satisfy admission policy");
569
607
  }
570
608
  const sessionCookieValue = generateOpaqueToken();
571
609
  const expiresAt = isoFromNow(auth.sessionTtlMs);
572
610
  input.repos.authSessions.create({
573
611
  idHash: hashOpaqueToken(sessionCookieValue),
574
612
  actor,
613
+ oidcEvidence,
575
614
  expiresAt
576
615
  });
577
616
  return { sessionCookieValue, actor, expiresAt };
578
617
  },
579
618
  resolveSession(cookieValue) {
580
- if (!auth.enabled || !cookieValue) {
581
- return null;
582
- }
583
- const idHash = hashOpaqueToken(cookieValue);
584
- const session = input.repos.authSessions.getValid(idHash);
585
- if (!session) {
586
- return null;
587
- }
588
- if (!isActorAllowedByConfig(session.actor, auth)) {
589
- input.repos.authSessions.delete(idHash);
590
- return null;
591
- }
592
- return session.actor;
619
+ return resolveSessionRecord(cookieValue)?.actor ?? null;
620
+ },
621
+ userInformation(cookieValue) {
622
+ return resolveSessionRecord(cookieValue)?.oidcEvidence ?? null;
593
623
  },
594
624
  logout(cookieValue) {
595
625
  if (cookieValue) {
@@ -13946,7 +13976,10 @@ import { createHmac, timingSafeEqual } from "node:crypto";
13946
13976
  function registerApiTokenRoutes(app, auth) {
13947
13977
  const ownerForRequest = (request) => {
13948
13978
  if (!request.actor) throw new Error("Browser authentication context is missing");
13949
- return auth.apiTokens.ownerForActor(request.actor);
13979
+ return auth.apiTokens.ownerForActor(
13980
+ request.actor,
13981
+ auth.userInformation(request.cookies?.[auth.config.sessionCookieName])
13982
+ );
13950
13983
  };
13951
13984
  const csrfKey = generateOpaqueToken();
13952
13985
  const anonymousCookie = `${auth.config.sessionCookieName}_token_csrf`;
@@ -13961,7 +13994,7 @@ function registerApiTokenRoutes(app, auth) {
13961
13994
  };
13962
13995
  const actor = authenticateBrowserRequest(auth, request);
13963
13996
  if (!actor) return reply.code(401).send({ error: "Browser access required" });
13964
- const owner = auth.apiTokens.ownerForActor(actor);
13997
+ const owner = ownerForRequest(request);
13965
13998
  if (request.tokenAudit) Object.assign(request.tokenAudit, { actor, ownerKind: owner.kind });
13966
13999
  if (request.method === "GET") return;
13967
14000
  const supplied = request.headers["x-csrf-token"];
@@ -14045,12 +14078,26 @@ function cookieOptions(input) {
14045
14078
  }
14046
14079
  function registerAuthRoutes(app, auth) {
14047
14080
  registerApiTokenRoutes(app, auth);
14081
+ app.get("/api/auth/user-information", async (request, reply) => {
14082
+ reply.header("Cache-Control", "no-store");
14083
+ if (hasAuthorization(request))
14084
+ return reply.code(401).send({ error: "Session access required" });
14085
+ const information = auth.userInformation(request.cookies?.[auth.config.sessionCookieName]);
14086
+ if (!information) return reply.code(401).send({ error: "OIDC session required" });
14087
+ return reply.send(information);
14088
+ });
14048
14089
  app.get("/api/auth/me", async (request, reply) => {
14049
14090
  const actor = authenticateRequest(auth, request);
14050
14091
  if (!actor) {
14051
14092
  return reply.code(401).send({ authEnabled: auth.config.enabled, actor: null });
14052
14093
  }
14053
- return reply.send({ authEnabled: auth.config.enabled, actor });
14094
+ return reply.send({
14095
+ authEnabled: auth.config.enabled,
14096
+ actor,
14097
+ userInformationAvailable: !request.headers.authorization && auth.config.providers.some(
14098
+ (provider) => provider.kind === "oidc" && provider.id === actor.provider
14099
+ )
14100
+ });
14054
14101
  });
14055
14102
  app.get("/auth/login", async (_request, reply) => {
14056
14103
  if (!auth.config.enabled) {
@@ -14067,8 +14114,8 @@ function registerAuthRoutes(app, auth) {
14067
14114
  })
14068
14115
  );
14069
14116
  return reply.redirect(login.redirectUrl);
14070
- } catch (error) {
14071
- app.log.warn({ err: error }, "Failed to start OIDC login");
14117
+ } catch {
14118
+ app.log.warn("Failed to start OIDC login");
14072
14119
  return reply.code(503).send({ error: "Login is temporarily unavailable" });
14073
14120
  }
14074
14121
  });
@@ -14095,8 +14142,8 @@ function registerAuthRoutes(app, auth) {
14095
14142
  })
14096
14143
  );
14097
14144
  return reply.redirect("/");
14098
- } catch (error) {
14099
- app.log.warn({ err: error }, "Failed to complete OIDC login");
14145
+ } catch {
14146
+ app.log.warn("Failed to complete OIDC login");
14100
14147
  reply.clearCookie(auth.config.loginFlowCookieName, { path: "/" });
14101
14148
  return reply.code(403).send({ error: "Login failed" });
14102
14149
  }
@@ -22015,4 +22062,4 @@ ${configErrors.join("\n")}`);
22015
22062
  export {
22016
22063
  createAppContext
22017
22064
  };
22018
- //# sourceMappingURL=chunk-OUA5EZS2.js.map
22065
+ //# sourceMappingURL=chunk-SKQGTUDA.js.map