@leitwerk-dev/server 0.4.2 → 0.4.4

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 (67) hide show
  1. package/dist/app-2TCRADVA.js +8 -0
  2. package/dist/{app-CtlotzYm.d.ts → app-DZUsf76a.d.ts} +30 -1
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/auth/api-token-routes.d.ts.map +1 -1
  5. package/dist/auth/api-token-service.d.ts +4 -3
  6. package/dist/auth/api-token-service.d.ts.map +1 -1
  7. package/dist/auth/auth-client.d.ts +17 -12
  8. package/dist/auth/auth-client.d.ts.map +1 -1
  9. package/dist/auth/auth-config.d.ts +2 -1
  10. package/dist/auth/auth-config.d.ts.map +1 -1
  11. package/dist/auth/auth-service.d.ts +10 -10
  12. package/dist/auth/auth-service.d.ts.map +1 -1
  13. package/dist/auth/auth-test-helpers.d.ts +24 -0
  14. package/dist/auth/auth-test-helpers.d.ts.map +1 -1
  15. package/dist/auth/github-oauth-client.d.ts +3 -13
  16. package/dist/auth/github-oauth-client.d.ts.map +1 -1
  17. package/dist/auth/oidc-client.d.ts +6 -14
  18. package/dist/auth/oidc-client.d.ts.map +1 -1
  19. package/dist/auth/oidc-evidence.d.ts +22 -0
  20. package/dist/auth/oidc-evidence.d.ts.map +1 -0
  21. package/dist/auth/routes.d.ts.map +1 -1
  22. package/dist/{chunk-YLWY4UTT.js → chunk-6EEU4QOU.js} +162 -5
  23. package/dist/chunk-6EEU4QOU.js.map +1 -0
  24. package/dist/{chunk-OUA5EZS2.js → chunk-AJ2DQWI3.js} +225 -189
  25. package/dist/chunk-AJ2DQWI3.js.map +1 -0
  26. package/dist/config/config-loader.d.ts.map +1 -1
  27. package/dist/config/config-types.d.ts +17 -0
  28. package/dist/config/config-types.d.ts.map +1 -1
  29. package/dist/db/api-token-repo.d.ts +3 -0
  30. package/dist/db/api-token-repo.d.ts.map +1 -1
  31. package/dist/db/auth-repo.d.ts +5 -0
  32. package/dist/db/auth-repo.d.ts.map +1 -1
  33. package/dist/db/database.d.ts.map +1 -1
  34. package/dist/db/schema.d.ts +32 -0
  35. package/dist/db/schema.d.ts.map +1 -1
  36. package/dist/index.js +2 -2
  37. package/dist/launch-pipeline.d.ts.map +1 -1
  38. package/dist/main.js +3 -3
  39. package/dist/process-launcher-registry.d.ts +3 -0
  40. package/dist/process-launcher-registry.d.ts.map +1 -1
  41. package/dist/routes/launchers.d.ts.map +1 -1
  42. package/dist/testing.js +1 -1
  43. package/package.json +12 -12
  44. package/src/app.ts +1 -0
  45. package/src/auth/api-token-routes.ts +17 -18
  46. package/src/auth/api-token-service.ts +9 -10
  47. package/src/auth/auth-client.ts +18 -18
  48. package/src/auth/auth-config.ts +18 -19
  49. package/src/auth/auth-service.ts +54 -72
  50. package/src/auth/auth-test-helpers.ts +101 -0
  51. package/src/auth/github-oauth-client.ts +8 -22
  52. package/src/auth/oidc-client.ts +34 -28
  53. package/src/auth/oidc-evidence.ts +168 -0
  54. package/src/auth/routes.ts +22 -6
  55. package/src/config/config-loader.ts +34 -0
  56. package/src/config/config-types.ts +18 -0
  57. package/src/db/api-token-repo.ts +6 -1
  58. package/src/db/auth-repo.ts +7 -0
  59. package/src/db/database.ts +14 -0
  60. package/src/db/schema.ts +2 -0
  61. package/src/launch-pipeline.ts +6 -0
  62. package/src/process-launcher-registry.ts +56 -6
  63. package/src/routes/launchers.ts +35 -20
  64. package/dist/app-KR3N2JAE.js +0 -8
  65. package/dist/chunk-OUA5EZS2.js.map +0 -1
  66. package/dist/chunk-YLWY4UTT.js.map +0 -1
  67. /package/dist/{app-KR3N2JAE.js.map → app-2TCRADVA.js.map} +0 -0
@@ -1,17 +1,22 @@
1
- import type { Actor } from "@leitwerk-dev/domain";
1
+ import { type Actor, ADMIN_ACTOR } from "@leitwerk-dev/domain";
2
2
  import type { LeitwerkConfig } from "../config/config-types.js";
3
- import type { AuthLoginFlowRecord, RepositoryBundle } from "../db/repositories.js";
3
+ import type { ApiTokenOwner, RepositoryBundle } from "../db/repositories.js";
4
4
  import { resolveApiTokenPolicy } from "./api-token-policy.js";
5
- import { type ApiTokenService, createApiTokenService } from "./api-token-service.js";
6
- import { type AuthClient, createAuthClient } from "./auth-client.js";
5
+ import {
6
+ type ApiTokenService,
7
+ createApiTokenService,
8
+ tokenProviderBinding,
9
+ } from "./api-token-service.js";
10
+ import { createAuthClient } from "./auth-client.js";
7
11
  import {
8
12
  isActorAllowedByConfig,
9
13
  type ResolvedAuthConfig,
10
- type ResolvedAuthProvider,
11
14
  resolveAuthConfig,
12
15
  } from "./auth-config.js";
13
16
  import { generateOpaqueToken, hashOpaqueToken, isoFromNow } from "./auth-tokens.js";
14
- import { createOpenIdClient, type OidcClient } from "./oidc-client.js";
17
+ import type { GithubOauthClient } from "./github-oauth-client.js";
18
+ import type { OidcClient } from "./oidc-client.js";
19
+ import type { OidcEvidence } from "./oidc-evidence.js";
15
20
 
16
21
  export interface CreatedLoginFlow {
17
22
  cookieValue: string;
@@ -36,70 +41,40 @@ export interface AuthService {
36
41
  startLogin(): Promise<CreatedLoginFlow>;
37
42
  completeLogin(input: { loginCookieValue: string; callbackUrl: URL }): Promise<CompletedLogin>;
38
43
  resolveSession(cookieValue: string | undefined): Actor | null;
44
+ /** @internal */
45
+ tokenOwnerForSession(cookieValue: string | undefined): ApiTokenOwner | null;
46
+ userInformation(cookieValue: string | undefined): OidcEvidence | null;
39
47
  logout(cookieValue: string | undefined): void;
40
48
  sweepExpiredAuthState(): AuthSweepResult;
41
49
  startExpiredAuthStateSweep(intervalMs?: number): () => void;
42
50
  }
43
51
 
44
- function pickDisplayName(claims: Record<string, unknown>, identity: string): string | undefined {
45
- for (const key of ["name", "preferred_username", "email"] as const) {
46
- const value = claims[key];
47
- if (typeof value === "string" && value.trim() !== "") {
48
- return value;
49
- }
50
- }
51
- return identity;
52
- }
53
-
54
- export function actorFromOidcClaims(input: {
55
- provider: ResolvedAuthProvider;
56
- claims: Record<string, unknown>;
57
- }): Actor | null {
58
- const rawIdentity = input.claims[input.provider.identity_claim];
59
- const identity = typeof rawIdentity === "string" ? rawIdentity.trim() : "";
60
- if (identity === "") {
61
- return null;
62
- }
63
- return {
64
- id: `${input.provider.id}:${identity}`,
65
- kind: "user",
66
- provider: input.provider.id,
67
- displayName: pickDisplayName(input.claims, identity),
68
- };
69
- }
70
-
71
52
  const DEFAULT_AUTH_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
72
53
 
73
- function consumeValidFlow(
74
- repos: Pick<RepositoryBundle, "authLoginFlows">,
75
- cookieValue: string,
76
- ): AuthLoginFlowRecord | null {
77
- const idHash = hashOpaqueToken(cookieValue);
78
- const flow = repos.authLoginFlows.getValid(idHash);
79
- if (flow) {
80
- repos.authLoginFlows.delete(idHash);
81
- }
82
- return flow;
83
- }
84
-
85
54
  export function createAuthService(input: {
86
55
  config: LeitwerkConfig;
87
56
  repos: Pick<RepositoryBundle, "authSessions" | "authLoginFlows" | "apiTokens">;
88
57
  oidcClient?: OidcClient;
89
- authClient?: AuthClient;
58
+ githubClient?: GithubOauthClient;
90
59
  }): AuthService {
91
60
  const auth = resolveAuthConfig(input.config);
92
- const authClient =
93
- input.authClient ??
94
- createAuthClient({
95
- oidc: input.oidcClient ?? createOpenIdClient(),
96
- });
61
+ const authClient = createAuthClient({ oidc: input.oidcClient, github: input.githubClient });
97
62
  const sweepExpiredAuthState = (): AuthSweepResult => ({
98
63
  sessions: input.repos.authSessions.deleteExpired(),
99
64
  loginFlows: input.repos.authLoginFlows.deleteExpired(),
100
65
  });
101
66
  sweepExpiredAuthState();
102
67
 
68
+ function resolveSessionRecord(cookieValue: string | undefined) {
69
+ if (!auth.enabled || !cookieValue) return null;
70
+ const idHash = hashOpaqueToken(cookieValue);
71
+ const session = input.repos.authSessions.getValid(idHash);
72
+ if (!session) return null;
73
+ if (isActorAllowedByConfig(session.actor, auth, session.oidcEvidence)) return session;
74
+ input.repos.authSessions.delete(idHash);
75
+ return null;
76
+ }
77
+
103
78
  return {
104
79
  config: auth,
105
80
  apiTokens: createApiTokenService({
@@ -131,10 +106,12 @@ export function createAuthService(input: {
131
106
  if (!auth.enabled) {
132
107
  throw new Error("Authentication is not enabled");
133
108
  }
134
- const flow = consumeValidFlow(input.repos, loginCookieValue);
109
+ const flowHash = hashOpaqueToken(loginCookieValue);
110
+ const flow = input.repos.authLoginFlows.getValid(flowHash);
135
111
  if (!flow) {
136
112
  throw new Error("Login flow expired or was not found");
137
113
  }
114
+ input.repos.authLoginFlows.delete(flowHash);
138
115
  const provider = auth.providers.find((p) => p.id === flow.providerId) ?? null;
139
116
  if (!provider) {
140
117
  throw new Error("Login provider is no longer configured");
@@ -142,43 +119,48 @@ export function createAuthService(input: {
142
119
  if (callbackUrl.searchParams.get("state") !== flow.state) {
143
120
  throw new Error("Invalid authentication state");
144
121
  }
145
- const exchanged = await authClient.exchangeCallback({
122
+ const { actor, oidcEvidence } = await authClient.exchangeCallback({
146
123
  provider,
147
124
  callbackUrl,
148
125
  state: flow.state,
149
126
  pkceVerifier: flow.pkceVerifier,
150
127
  });
151
- const actor = actorFromOidcClaims({ provider, claims: exchanged.claims });
152
- if (!actor) {
153
- throw new Error(`Authentication identity claim ${provider.identity_claim} was not present`);
154
- }
155
- if (!isActorAllowedByConfig(actor, auth)) {
156
- throw new Error("Authenticated user is not allowlisted");
128
+ if (!isActorAllowedByConfig(actor, auth, oidcEvidence)) {
129
+ throw new Error("Authenticated user does not satisfy admission policy");
157
130
  }
158
131
  const sessionCookieValue = generateOpaqueToken();
159
132
  const expiresAt = isoFromNow(auth.sessionTtlMs);
160
133
  input.repos.authSessions.create({
161
134
  idHash: hashOpaqueToken(sessionCookieValue),
162
135
  actor,
136
+ oidcEvidence,
163
137
  expiresAt,
164
138
  });
165
139
  return { sessionCookieValue, actor, expiresAt };
166
140
  },
167
141
 
168
142
  resolveSession(cookieValue) {
169
- if (!auth.enabled || !cookieValue) {
170
- return null;
171
- }
172
- const idHash = hashOpaqueToken(cookieValue);
173
- const session = input.repos.authSessions.getValid(idHash);
174
- if (!session) {
175
- return null;
176
- }
177
- if (!isActorAllowedByConfig(session.actor, auth)) {
178
- input.repos.authSessions.delete(idHash);
179
- return null;
180
- }
181
- return session.actor;
143
+ return resolveSessionRecord(cookieValue)?.actor ?? null;
144
+ },
145
+
146
+ tokenOwnerForSession(cookieValue) {
147
+ if (!auth.enabled)
148
+ return { kind: "anonymous", id: "anonymous", actor: ADMIN_ACTOR, providerBinding: null };
149
+ const session = resolveSessionRecord(cookieValue);
150
+ if (!session) return null;
151
+ const provider = auth.providers.find((p) => p.id === session.actor.provider);
152
+ if (!provider) return null;
153
+ return {
154
+ kind: "user",
155
+ id: session.actor.id,
156
+ actor: session.actor,
157
+ providerBinding: tokenProviderBinding(provider),
158
+ oidcEvidence: session.oidcEvidence,
159
+ };
160
+ },
161
+
162
+ userInformation(cookieValue) {
163
+ return resolveSessionRecord(cookieValue)?.oidcEvidence ?? null;
182
164
  },
183
165
 
184
166
  logout(cookieValue) {
@@ -1,9 +1,68 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { Actor } from "@leitwerk-dev/domain";
1
3
  import { getDefaultConfig } from "../config/config-loader.js";
2
4
  import type {
3
5
  AuthConfig,
4
6
  AuthOidcProviderConfig,
5
7
  AuthSessionConfig,
6
8
  } from "../config/config-types.js";
9
+ import { createAllRepos, type RepositoryBundle } from "../db/repositories.js";
10
+ import { createOwnedInMemoryDatabase } from "../test-helpers/owned-test-deps.js";
11
+ import { type AuthService, createAuthService } from "./auth-service.js";
12
+ import { hashOpaqueToken } from "./auth-tokens.js";
13
+ import type { OidcClient } from "./oidc-client.js";
14
+ import type { OidcEvidence } from "./oidc-evidence.js";
15
+
16
+ /** @internal */
17
+ export function createTestOidcClient(options: {
18
+ state?: string;
19
+ idTokenClaims?: Record<string, unknown>;
20
+ userInfoClaims?: Record<string, unknown> | null;
21
+ startError?: Error;
22
+ callbackError?: Error;
23
+ }): OidcClient {
24
+ return {
25
+ async createAuthorizationRequest() {
26
+ if (options.startError) throw options.startError;
27
+ const state = options.state ?? "state";
28
+ return {
29
+ state,
30
+ pkceVerifier: `verifier-${state}`,
31
+ redirectUrl: "https://identity.example.test/oauth/authorize",
32
+ };
33
+ },
34
+ async exchangeCallback() {
35
+ if (options.callbackError) throw options.callbackError;
36
+ if (!options.idTokenClaims) throw new Error("not used");
37
+ return {
38
+ idTokenClaims: options.idTokenClaims,
39
+ userInfoClaims: options.userInfoClaims ?? null,
40
+ };
41
+ },
42
+ };
43
+ }
44
+
45
+ /** @internal */
46
+ export function createTestOidcLogin(
47
+ config: ReturnType<typeof testAuthConfig>,
48
+ options: Parameters<typeof createTestOidcClient>[0],
49
+ ) {
50
+ const repos = createAllRepos(createOwnedInMemoryDatabase());
51
+ const auth = createAuthService({ config, repos, oidcClient: createTestOidcClient(options) });
52
+ return {
53
+ auth,
54
+ repos,
55
+ async completeLogin() {
56
+ const flow = await auth.startLogin();
57
+ const callbackUrl = new URL("/auth/callback", config.server.base_url);
58
+ callbackUrl.search = new URLSearchParams({
59
+ code: "c",
60
+ state: options.state ?? "state",
61
+ }).toString();
62
+ return auth.completeLogin({ loginCookieValue: flow.cookieValue, callbackUrl });
63
+ },
64
+ };
65
+ }
7
66
 
8
67
  export function testAuthConfig(overrides?: {
9
68
  cookieName?: string;
@@ -37,6 +96,48 @@ export function testAuthConfig(overrides?: {
37
96
  return config;
38
97
  }
39
98
 
99
+ export function testOidcEvidence(
100
+ identity = "alice",
101
+ claims: Record<string, unknown> = {},
102
+ ): OidcEvidence {
103
+ return {
104
+ providerId: "identity",
105
+ issuer: "https://identity.example.test",
106
+ identityClaim: "preferred_username",
107
+ subject: `subject-${identity}`,
108
+ loginAt: "2026-01-01T00:00:00.000Z",
109
+ idTokenClaims: { sub: `subject-${identity}`, preferred_username: identity, ...claims },
110
+ userInfoClaims: null,
111
+ facts: { identity, email: null, emailVerified: false, groups: [] },
112
+ };
113
+ }
114
+
115
+ /** @internal */
116
+ export function createTestSession(
117
+ repos: Pick<RepositoryBundle, "authSessions">,
118
+ actor: Actor,
119
+ oidcEvidence: OidcEvidence | null = null,
120
+ ) {
121
+ const cookie = randomUUID();
122
+ repos.authSessions.create({
123
+ idHash: hashOpaqueToken(cookie),
124
+ actor,
125
+ oidcEvidence,
126
+ expiresAt: new Date(Date.now() + 60000).toISOString(),
127
+ });
128
+ return cookie;
129
+ }
130
+
131
+ /** @internal */
132
+ export function createTestSessionOwner(
133
+ auth: AuthService,
134
+ ...session: Parameters<typeof createTestSession>
135
+ ) {
136
+ const owner = auth.tokenOwnerForSession(createTestSession(...session));
137
+ if (!owner) throw new Error("Expected session token owner");
138
+ return owner;
139
+ }
140
+
40
141
  export function setCookieValues(headers: string | string[] | undefined): string[] {
41
142
  return Array.isArray(headers) ? headers : headers ? [headers] : [];
42
143
  }
@@ -1,30 +1,17 @@
1
- import { randomBytes } from "node:crypto";
1
+ import type { AuthAuthorizationRequest, AuthCallbackRequest } from "./auth-client.js";
2
2
  import type { ResolvedGithubProvider } from "./auth-config.js";
3
+ import { generateOpaqueToken } from "./auth-tokens.js";
3
4
 
4
5
  const GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
5
6
  const GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token";
6
7
  const GITHUB_API_URL = "https://api.github.com";
7
8
  const GITHUB_API_VERSION = "2022-11-28";
8
9
 
9
- export interface GithubAuthorizationRequest {
10
- provider: ResolvedGithubProvider;
11
- state: string;
12
- pkceVerifier: string;
13
- redirectUrl: string;
14
- }
15
-
16
10
  export interface GithubOauthClient {
17
- createAuthorizationRequest(provider: ResolvedGithubProvider): Promise<GithubAuthorizationRequest>;
18
- exchangeCallback(input: {
19
- provider: ResolvedGithubProvider;
20
- callbackUrl: URL;
21
- state: string;
22
- pkceVerifier: string;
23
- }): Promise<{ claims: Record<string, unknown> }>;
24
- }
25
-
26
- function opaqueValue(): string {
27
- return randomBytes(32).toString("base64url");
11
+ createAuthorizationRequest(provider: ResolvedGithubProvider): Promise<AuthAuthorizationRequest>;
12
+ exchangeCallback(
13
+ input: AuthCallbackRequest<ResolvedGithubProvider>,
14
+ ): Promise<{ claims: Record<string, unknown> }>;
28
15
  }
29
16
 
30
17
  function githubHeaders(accessToken?: string): HeadersInit {
@@ -51,18 +38,17 @@ async function jsonObject(
51
38
  export function createGithubOauthClient(fetchImpl: typeof fetch = fetch): GithubOauthClient {
52
39
  return {
53
40
  async createAuthorizationRequest(provider) {
54
- const state = opaqueValue();
41
+ const state = generateOpaqueToken();
55
42
  const redirectUrl = new URL(GITHUB_AUTHORIZE_URL);
56
43
  redirectUrl.searchParams.set("client_id", provider.client_id);
57
44
  redirectUrl.searchParams.set("redirect_uri", provider.redirect_uri);
58
45
  redirectUrl.searchParams.set("scope", provider.scopes.join(" "));
59
46
  redirectUrl.searchParams.set("state", state);
60
47
  return {
61
- provider,
62
48
  state,
63
49
  // The persisted login-flow schema requires a verifier. GitHub OAuth Apps
64
50
  // authenticate this confidential client with its secret instead of PKCE.
65
- pkceVerifier: opaqueValue(),
51
+ pkceVerifier: generateOpaqueToken(),
66
52
  redirectUrl: redirectUrl.toString(),
67
53
  };
68
54
  },
@@ -2,6 +2,7 @@ import {
2
2
  allowInsecureRequests,
3
3
  authorizationCodeGrant,
4
4
  buildAuthorizationUrl,
5
+ ClientError,
5
6
  ClientSecretPost,
6
7
  type Configuration,
7
8
  calculatePKCECodeChallenge,
@@ -9,30 +10,20 @@ import {
9
10
  fetchUserInfo,
10
11
  randomPKCECodeVerifier,
11
12
  randomState,
12
- skipSubjectCheck,
13
13
  } from "openid-client";
14
14
  import { isLoopbackHttpUrl } from "../config/url-policy.js";
15
+ import type { AuthAuthorizationRequest, AuthCallbackRequest } from "./auth-client.js";
15
16
  import type { ResolvedOidcProvider } from "./auth-config.js";
16
17
 
17
- export interface OidcAuthorizationRequest {
18
- provider: ResolvedOidcProvider;
19
- state: string;
20
- pkceVerifier: string;
21
- redirectUrl: string;
22
- }
23
-
18
+ /** @internal */
24
19
  export interface OidcTokensAndClaims {
25
- claims: Record<string, unknown>;
20
+ idTokenClaims: Record<string, unknown>;
21
+ userInfoClaims: Record<string, unknown> | null;
26
22
  }
27
23
 
28
24
  export interface OidcClient {
29
- createAuthorizationRequest(provider: ResolvedOidcProvider): Promise<OidcAuthorizationRequest>;
30
- exchangeCallback(input: {
31
- provider: ResolvedOidcProvider;
32
- callbackUrl: URL;
33
- state: string;
34
- pkceVerifier: string;
35
- }): Promise<OidcTokensAndClaims>;
25
+ createAuthorizationRequest(provider: ResolvedOidcProvider): Promise<AuthAuthorizationRequest>;
26
+ exchangeCallback(input: AuthCallbackRequest<ResolvedOidcProvider>): Promise<OidcTokensAndClaims>;
36
27
  }
37
28
 
38
29
  export function createOpenIdClient(): OidcClient {
@@ -70,7 +61,7 @@ export function createOpenIdClient(): OidcClient {
70
61
  code_challenge: codeChallenge,
71
62
  code_challenge_method: "S256",
72
63
  }).toString();
73
- return { provider, state, pkceVerifier, redirectUrl };
64
+ return { state, pkceVerifier, redirectUrl };
74
65
  },
75
66
 
76
67
  async exchangeCallback(input) {
@@ -85,21 +76,36 @@ export function createOpenIdClient(): OidcClient {
85
76
  { redirect_uri: input.provider.redirect_uri },
86
77
  );
87
78
  const idClaims = tokens.claims() as Record<string, unknown> | undefined;
79
+ if (!idClaims || typeof idClaims.sub !== "string" || !idClaims.sub.trim()) {
80
+ throw new Error("OIDC ID token requires a valid subject");
81
+ }
82
+ let userInfo: Record<string, unknown> | null = null;
88
83
  if (tokens.access_token) {
89
- const expectedSubject = typeof idClaims?.sub === "string" ? idClaims.sub : skipSubjectCheck;
84
+ // Fetch without suppressing subject mismatch errors as optional network failures.
90
85
  try {
91
- const userInfo = (await fetchUserInfo(
92
- config,
93
- tokens.access_token,
94
- expectedSubject,
95
- )) as Record<string, unknown>;
96
- return { claims: { ...(idClaims ?? {}), ...userInfo } };
97
- } catch {
98
- // best-effort: fall through to idClaims
86
+ userInfo = (await fetchUserInfo(config, tokens.access_token, idClaims.sub)) as Record<
87
+ string,
88
+ unknown
89
+ >;
90
+ } catch (error) {
91
+ // Only availability failures are optional. Invalid responses fail closed.
92
+ if (
93
+ !(error instanceof TypeError) &&
94
+ !(
95
+ error instanceof ClientError &&
96
+ (error.code === "OAUTH_TIMEOUT" ||
97
+ (error.cause instanceof Response && error.cause.status >= 500))
98
+ )
99
+ )
100
+ throw new Error("OIDC UserInfo validation failed");
99
101
  }
102
+ if (userInfo && userInfo.sub !== idClaims.sub)
103
+ throw new Error("OIDC UserInfo subject mismatch");
100
104
  }
101
- if (idClaims) return { claims: idClaims };
102
- throw new Error("OIDC token response did not include an access token or id_token claims");
105
+ return {
106
+ idTokenClaims: idClaims,
107
+ userInfoClaims: userInfo,
108
+ };
103
109
  },
104
110
  };
105
111
  }
@@ -0,0 +1,168 @@
1
+ import type { Actor } from "@leitwerk-dev/domain";
2
+ import type { UserInformationResponseBody } from "@leitwerk-dev/protocol/http-contracts";
3
+ import type { OidcAccessPolicy } from "../config/config-types.js";
4
+ import type { ResolvedAuthProvider, ResolvedOidcProvider } from "./auth-config.js";
5
+ import type { OidcTokensAndClaims } from "./oidc-client.js";
6
+
7
+ /** Session/token evidence, never attached to an Actor. @internal */
8
+ export interface OidcEvidence extends UserInformationResponseBody {
9
+ /** @internal */
10
+ identityClaim: string;
11
+ }
12
+
13
+ /** Exclude credential-shaped claims even when returned by a custom provider. */
14
+ function safeClaims(claims: Record<string, unknown>): Record<string, unknown> {
15
+ return JSON.parse(
16
+ JSON.stringify(claims, (key, value) =>
17
+ /^(access_token|refresh_token|id_token|client_secret|authorization)$/i.test(key)
18
+ ? undefined
19
+ : value,
20
+ ),
21
+ );
22
+ }
23
+
24
+ /** @internal */
25
+ export function actorFromClaims(
26
+ provider: ResolvedAuthProvider,
27
+ claims: Record<string, unknown>,
28
+ ): Actor {
29
+ const rawIdentity = claims[provider.identity_claim];
30
+ const identity = typeof rawIdentity === "string" ? rawIdentity.trim() : "";
31
+ if (!identity) {
32
+ throw new Error(`Authentication identity claim ${provider.identity_claim} was not present`);
33
+ }
34
+ const displayName =
35
+ [claims.name, claims.preferred_username, claims.email].find(
36
+ (value): value is string => typeof value === "string" && value.trim() !== "",
37
+ ) ?? identity;
38
+ return {
39
+ id: `${provider.id}:${identity}`,
40
+ kind: "user",
41
+ provider: provider.id,
42
+ displayName,
43
+ };
44
+ }
45
+
46
+ /** @internal */
47
+ export function interpretOidcLogin(
48
+ provider: ResolvedOidcProvider,
49
+ exchange: OidcTokensAndClaims,
50
+ ): { actor: Actor; oidcEvidence: OidcEvidence } {
51
+ const idTokenClaims = safeClaims(exchange.idTokenClaims);
52
+ const userInfoClaims = exchange.userInfoClaims ? safeClaims(exchange.userInfoClaims) : null;
53
+ if (
54
+ typeof idTokenClaims.sub !== "string" ||
55
+ !idTokenClaims.sub.trim() ||
56
+ (userInfoClaims && userInfoClaims.sub !== idTokenClaims.sub)
57
+ )
58
+ throw new Error("Invalid OIDC subject evidence");
59
+ const claims = { ...idTokenClaims, ...userInfoClaims };
60
+ const actor = actorFromClaims(provider, claims);
61
+ const groups = claims[provider.access?.groups_claim ?? "groups"];
62
+ return {
63
+ actor,
64
+ oidcEvidence: {
65
+ providerId: provider.id,
66
+ issuer: provider.issuer,
67
+ identityClaim: provider.identity_claim,
68
+ subject: idTokenClaims.sub,
69
+ loginAt: new Date().toISOString(),
70
+ idTokenClaims,
71
+ userInfoClaims,
72
+ facts: {
73
+ identity: actor.id.slice(provider.id.length + 1),
74
+ email: typeof claims.email === "string" ? claims.email : null,
75
+ emailVerified: claims.email_verified === true,
76
+ groups:
77
+ Array.isArray(groups) && groups.every((group) => typeof group === "string") ? groups : [],
78
+ },
79
+ },
80
+ };
81
+ }
82
+
83
+ function validDomain(domain: string): boolean {
84
+ return (
85
+ domain.length <= 253 &&
86
+ domain.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))
87
+ );
88
+ }
89
+
90
+ /** @internal */
91
+ export function policyErrors(policy: OidcAccessPolicy, legacy: boolean): string[] {
92
+ const errors: string[] = [];
93
+ if (legacy) errors.push("cannot combine access with deprecated auth.allowlist");
94
+ const lists = [policy.users, policy.groups, policy.email_domains];
95
+ if (
96
+ policy.mode === "all" &&
97
+ (lists.some((list) => list !== undefined) ||
98
+ policy.match !== undefined ||
99
+ policy.groups_claim !== undefined)
100
+ )
101
+ errors.push("access mode all cannot include restrictions, match, or groups_claim");
102
+ if (policy.mode === "restricted" && !lists.some((list) => list && list.length > 0))
103
+ errors.push("restricted access requires at least one non-empty criterion");
104
+ if (
105
+ lists.some(
106
+ (list) => list !== undefined && (list.length === 0 || list.some((item) => !item.trim())),
107
+ )
108
+ )
109
+ errors.push("access criteria must be non-empty lists of non-empty strings");
110
+ if (policy.email_domains?.some((domain) => !validDomain(domain)))
111
+ errors.push("access email_domains must contain exact domain names");
112
+ return errors;
113
+ }
114
+
115
+ /** @internal */
116
+ export function evidenceAllows(
117
+ actor: Actor,
118
+ provider: ResolvedOidcProvider,
119
+ evidence: OidcEvidence | null | undefined,
120
+ allowlist: Set<string>,
121
+ ): boolean {
122
+ if (
123
+ !evidence ||
124
+ evidence.providerId !== provider.id ||
125
+ evidence.issuer !== provider.issuer ||
126
+ evidence.identityClaim !== provider.identity_claim ||
127
+ typeof evidence.subject !== "string" ||
128
+ !evidence.subject.trim() ||
129
+ evidence.idTokenClaims.sub !== evidence.subject ||
130
+ (evidence.userInfoClaims !== null && evidence.userInfoClaims.sub !== evidence.subject)
131
+ )
132
+ return false;
133
+ const claims = { ...evidence.idTokenClaims, ...evidence.userInfoClaims };
134
+ const identity =
135
+ typeof claims[provider.identity_claim] === "string"
136
+ ? (claims[provider.identity_claim] as string).trim()
137
+ : "";
138
+ if (!identity || actor.id !== `${provider.id}:${identity}`) return false;
139
+ const policy = provider.access;
140
+ if (!policy) return allowlist.has(identity);
141
+ if (policy.mode === "all") return true;
142
+ const matches: boolean[] = [];
143
+ if (policy.users) matches.push(policy.users.includes(identity));
144
+ if (policy.groups) {
145
+ const groups = claims[policy.groups_claim ?? "groups"];
146
+ matches.push(
147
+ Array.isArray(groups) &&
148
+ groups.every((group) => typeof group === "string") &&
149
+ policy.groups.some((group) => groups.includes(group)),
150
+ );
151
+ }
152
+ if (policy.email_domains) {
153
+ const email = claims.email;
154
+ const domain =
155
+ typeof email === "string" && /^[^\s@]+@[^\s@]+$/.test(email)
156
+ ? email.split("@")[1]?.toLowerCase()
157
+ : undefined;
158
+ matches.push(
159
+ claims.email_verified === true &&
160
+ domain !== undefined &&
161
+ validDomain(domain) &&
162
+ policy.email_domains.some((allowed) => allowed.toLowerCase() === domain),
163
+ );
164
+ }
165
+ return (
166
+ matches.length > 0 && (policy.match === "any" ? matches.some(Boolean) : matches.every(Boolean))
167
+ );
168
+ }