@better-forge/auth 0.1.0 → 0.1.1

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/src/oidc.ts CHANGED
@@ -1,291 +1,291 @@
1
- import { randomBytes, randomUUID } from 'node:crypto'
2
- import bcrypt from 'bcryptjs'
3
- import * as client from 'openid-client'
4
- import { and, eq, sql } from 'drizzle-orm'
5
- import { users } from './tables.js'
6
- import type { AuthOptions } from './context.js'
7
- import { ADMIN_ROLE } from './roles.js'
8
- import type { OidcConfig } from './oidcConfig.js'
9
- import type { SignInAudit } from './signInAudit.js'
10
-
11
- type User = typeof users.$inferSelect
12
-
13
- export interface OidcFlowState {
14
- state: string
15
- nonce: string
16
- codeVerifier: string
17
- }
18
-
19
- /** An SSO confirmation must come from a sign-in at the provider no older than this (the ID token's auth_time). */
20
- export const OIDC_CONFIRMATION_MAX_AGE_SECONDS = 5 * 60
21
-
22
- /** Why an SSO sign-in was refused. The user only sees a generic message; the audit log gets the code and detail. */
23
- export type OidcDenialCode =
24
- | 'discovery_failed'
25
- | 'flow_expired'
26
- | 'idp_error'
27
- | 'token_exchange_failed'
28
- | 'no_email_claim'
29
- | 'email_not_verified'
30
- | 'no_matching_account'
31
- | 'subject_mismatch'
32
- | 'confirmation_mismatch'
33
-
34
- export interface OidcDenial {
35
- code: OidcDenialCode
36
- reason: string
37
- email?: string
38
- }
39
-
40
- /** An account an SSO sign-in may create, bound to this identity. The application decides who qualifies and the role (see `resolveUnknownSsoUser`). */
41
- export interface SsoProvisioning {
42
- email: string
43
- subject: string
44
- role: string
45
- }
46
-
47
- /**
48
- * The outcome for a set of validated ID token claims. `link` means the user was matched by email and the
49
- * identity (issuer + subject) should now be bound to them, so later sign-ins no longer depend on the email.
50
- * A denial for an unknown email carries `provision` when a sign-in may create an account instead.
51
- */
52
- export type OidcDecision =
53
- | { user: User; link: boolean; subject: string; denial?: undefined; provision?: undefined }
54
- | { user: null; denial: OidcDenial; provision?: SsoProvisioning | undefined }
55
-
56
- // Some providers send booleans as strings ("true").
57
- const isTrue = (value: unknown) => value === true || value === 'true'
58
-
59
- const isFalse = (value: unknown) => value === false || value === 'false'
60
-
61
- /**
62
- * Whether the email claim may be trusted. `email_verified` is the standard claim; Microsoft Entra ID never
63
- * sends it but offers the optional `xms_edov` claim (email domain owner verified) instead. An explicit
64
- * `false` from either claim is never overridden by `allowUnverifiedEmail`.
65
- */
66
- export function checkEmailVerified(claims: Record<string, unknown>, allowUnverifiedEmail: boolean): string | null {
67
- const standard = claims['email_verified']
68
- const entra = claims['xms_edov']
69
- if (isTrue(standard) || isTrue(entra)) return null
70
- if (isFalse(standard)) return 'The identity provider reports the email as unverified (email_verified is false).'
71
- if (isFalse(entra)) return 'Microsoft Entra ID reports that the email domain is not verified (xms_edov is false).'
72
- if (allowUnverifiedEmail && standard === undefined && entra === undefined) return null
73
- return 'The ID token has neither an email_verified nor an xms_edov claim. For Microsoft Entra ID, add the xms_edov optional claim to the ID token. '
74
- + 'For other providers, enable "Accept identity providers that omit email_verified" only if their email claim is trustworthy.'
75
- }
76
-
77
- // ── Test sign-in ────────────────────────────────────────────────────────────
78
- // An administrator runs the real flow to see the claims and what would happen, without signing anyone in.
79
-
80
- export interface OidcTestResult {
81
- issuer: string
82
- testedAt: number
83
- claims: Record<string, unknown> | null
84
- /** `provision`: the sign-in would create an account. */
85
- outcome: 'sign_in' | 'link' | 'provision' | 'deny'
86
- user: string | null
87
- denial: OidcDenial | null
88
- }
89
-
90
- const TEST_RESULT_TTL_MS = 10 * 60 * 1000
91
-
92
- export function createOidc(ctx: AuthOptions, signInAudit: SignInAudit) {
93
- const { db, audit } = ctx
94
- const hooks = ctx.hooks ?? {}
95
- const { auditSignInDenial } = signInAudit
96
-
97
- let cached: { key: string; config: Promise<client.Configuration> } | null = null
98
-
99
- function runDiscovery(cfg: OidcConfig): Promise<client.Configuration> {
100
- const issuer = new URL(cfg.issuer)
101
- // The client library refuses plain http; allow it only for issuers configured that way (e.g. a local Keycloak).
102
- const options = issuer.protocol === 'http:' ? { execute: [client.allowInsecureRequests] } : undefined
103
- return client.discovery(issuer, cfg.clientId, cfg.clientSecret || undefined, undefined, options)
104
- }
105
-
106
- function discover(cfg: OidcConfig): Promise<client.Configuration> {
107
- const key = `${cfg.issuer}|${cfg.clientId}|${cfg.clientSecret}`
108
- if (cached?.key !== key) {
109
- const config = runDiscovery(cfg)
110
- config.catch(() => { if (cached?.key === key) cached = null })
111
- cached = { key, config }
112
- }
113
- return cached.config
114
- }
115
-
116
- /**
117
- * Builds the provider redirect. `confirm` asks the provider to authenticate the user again (`prompt=login`)
118
- * and to report when it did (`max_age`), so the callback can require a fresh `auth_time`.
119
- */
120
- async function beginOidcLogin(cfg: OidcConfig, options: { confirm?: boolean } = {}): Promise<{ url: string; flow: OidcFlowState }> {
121
- const config = await discover(cfg)
122
- const flow: OidcFlowState = {
123
- state: client.randomState(),
124
- nonce: client.randomNonce(),
125
- codeVerifier: client.randomPKCECodeVerifier(),
126
- }
127
- const url = client.buildAuthorizationUrl(config, {
128
- redirect_uri: cfg.redirectUri,
129
- scope: cfg.scopes,
130
- state: flow.state,
131
- nonce: flow.nonce,
132
- code_challenge: await client.calculatePKCECodeChallenge(flow.codeVerifier),
133
- code_challenge_method: 'S256',
134
- ...(options.confirm ? { prompt: 'login', max_age: String(OIDC_CONFIRMATION_MAX_AGE_SECONDS) } : {}),
135
- })
136
- return { url: url.href, flow }
137
- }
138
-
139
- /**
140
- * Completes the code exchange and returns the validated ID token claims, or why that failed. With `maxAge`
141
- * the ID token must carry an `auth_time` no older than that many seconds.
142
- */
143
- async function exchangeOidcCode(
144
- cfg: OidcConfig, callbackUrl: URL, flow: OidcFlowState, maxAge?: number,
145
- ): Promise<{ claims: Record<string, unknown>; denial?: undefined } | { claims?: undefined; denial: OidcDenial }> {
146
- const config = await discover(cfg)
147
- try {
148
- const tokens = await client.authorizationCodeGrant(config, callbackUrl, {
149
- pkceCodeVerifier: flow.codeVerifier,
150
- expectedState: flow.state,
151
- expectedNonce: flow.nonce,
152
- idTokenExpected: true,
153
- ...(maxAge !== undefined ? { maxAge } : {}),
154
- })
155
- return { claims: tokens.claims() ?? {} }
156
- } catch (error) {
157
- return { denial: describeExchangeError(error) }
158
- }
159
- }
160
-
161
- /**
162
- * Finds the local user for validated claims without changing anything. An identity already bound to a
163
- * user wins; otherwise the verified email is matched, but never onto a user bound to another identity at
164
- * the same provider, so an email address given to someone else cannot take over the account.
165
- */
166
- async function evaluateOidcClaims(cfg: OidcConfig, claims: Record<string, unknown>): Promise<OidcDecision> {
167
- const subject = typeof claims['sub'] === 'string' ? claims['sub'] : ''
168
- if (subject) {
169
- const bound = (await db.select().from(users)
170
- .where(and(eq(users.oidcIssuer, cfg.issuer), eq(users.oidcSubject, subject))))[0]
171
- if (bound) return { user: bound, link: false, subject }
172
- }
173
-
174
- const email = typeof claims['email'] === 'string' ? claims['email'].trim().toLowerCase() : ''
175
- if (!email) {
176
- return {
177
- user: null,
178
- denial: {
179
- code: 'no_email_claim',
180
- reason: `The ID token has no email claim. Request the "email" scope and, for Microsoft Entra ID, add the email optional claim. Claims received: ${Object.keys(claims).join(', ') || 'none'}.`,
181
- },
182
- }
183
- }
184
- const unverified = checkEmailVerified(claims, cfg.allowUnverifiedEmail)
185
- if (unverified) return { user: null, denial: { code: 'email_not_verified', reason: unverified, email } }
186
- const user = (await db.select().from(users).where(sql`lower(${users.email}) = ${email}`))[0]
187
- if (!user) {
188
- const resolved = subject ? await hooks.resolveUnknownSsoUser?.({ email, subject, issuer: cfg.issuer }) : null
189
- // A role the application did not register, or admin, is never handed out by a sign-in: no account is created.
190
- const provision = subject && resolved && ctx.roles.isValid(resolved.role) && resolved.role !== ADMIN_ROLE ? { email, subject, role: resolved.role } : undefined
191
- return { user: null, denial: { code: 'no_matching_account', reason: `No user has the email ${email}. Create the user first.`, email }, provision }
192
- }
193
- if (user.oidcSubject && user.oidcIssuer === cfg.issuer) {
194
- return {
195
- user: null,
196
- denial: {
197
- code: 'subject_mismatch',
198
- reason: `${user.email} is linked to another identity at this provider (subject ${user.oidcSubject}; this sign-in: ${subject || 'none'}). `
199
- + 'The email address may have been given to someone else.',
200
- email,
201
- },
202
- }
203
- }
204
- return { user, link: true, subject }
205
- }
206
-
207
- /** Binds the provider identity to the user and records it; a binding to a previous issuer is replaced. */
208
- async function linkOidcIdentity(cfg: OidcConfig, user: User, subject: string): Promise<void> {
209
- await db.update(users).set({ oidcIssuer: cfg.issuer, oidcSubject: subject }).where(eq(users.id, user.id))
210
- await audit.write(
211
- { userId: user.id, userEmail: user.email },
212
- 'update', 'user-security', user.id, user.email,
213
- { ssoLinked: { from: user.oidcIssuer, to: cfg.issuer }, subject },
214
- )
215
- }
216
-
217
- /**
218
- * Creates the account of a first SSO sign-in, already bound to the identity.
219
- * Its password is random and never handed out: the account signs in through SSO only.
220
- */
221
- async function provisionSsoUser(cfg: OidcConfig, provision: SsoProvisioning): Promise<User> {
222
- const passwordHash = await bcrypt.hash(randomBytes(32).toString('base64url'), 10)
223
- const [user] = await db.insert(users).values({
224
- email: provision.email,
225
- passwordHash,
226
- role: provision.role,
227
- createdAt: Date.now(),
228
- oidcIssuer: cfg.issuer,
229
- oidcSubject: provision.subject,
230
- }).returning()
231
- await audit.write(
232
- { userId: user!.id, userEmail: user!.email },
233
- 'create', 'user', user!.id, user!.email,
234
- { email: user!.email, role: provision.role, createdBy: 'sso', issuer: cfg.issuer },
235
- )
236
- return user!
237
- }
238
-
239
- /** Records a refused SSO sign-in or confirmation as a 'sign_in' denial, with the issuer. */
240
- async function auditOidcDenial(cfg: OidcConfig, denial: OidcDenial): Promise<void> {
241
- await auditSignInDenial('sso', denial, { issuer: cfg.issuer })
242
- }
243
-
244
- function describeExchangeError(error: unknown): OidcDenial {
245
- if (error instanceof client.AuthorizationResponseError) {
246
- const description = error.error_description ? `: ${error.error_description}` : ''
247
- return { code: 'idp_error', reason: `The identity provider returned ${error.error}${description}`.slice(0, 1000) }
248
- }
249
- const message = error instanceof Error ? error.message : String(error)
250
- return { code: 'token_exchange_failed', reason: `Code exchange or ID token validation failed: ${message}`.slice(0, 1000) }
251
- }
252
-
253
- /** Runs OIDC discovery against the issuer without caching, to validate settings before saving them. */
254
- async function testOidcDiscovery(cfg: OidcConfig): Promise<{ issuer: string; authorizationEndpoint: string | null }> {
255
- const config = await runDiscovery(cfg)
256
- const meta = config.serverMetadata()
257
- return { issuer: meta.issuer, authorizationEndpoint: meta.authorization_endpoint ?? null }
258
- }
259
-
260
- const testResults = new Map<string, { adminUserId: number; expiresAt: number; result: OidcTestResult }>()
261
-
262
- function storeOidcTestResult(adminUserId: number, result: OidcTestResult): string {
263
- const now = Date.now()
264
- for (const [id, entry] of testResults) if (entry.expiresAt <= now) testResults.delete(id)
265
- const id = randomUUID()
266
- testResults.set(id, { adminUserId, expiresAt: now + TEST_RESULT_TTL_MS, result })
267
- return id
268
- }
269
-
270
- /** Only the administrator who started the test can read its result. */
271
- function readOidcTestResult(id: string, adminUserId: number): OidcTestResult | null {
272
- const entry = testResults.get(id)
273
- if (!entry || entry.expiresAt <= Date.now() || entry.adminUserId !== adminUserId) return null
274
- return entry.result
275
- }
276
-
277
- async function runOidcTest(cfg: OidcConfig, callbackUrl: URL, flow: OidcFlowState): Promise<OidcTestResult> {
278
- const base = { issuer: cfg.issuer, testedAt: Date.now() }
279
- const exchanged = await exchangeOidcCode(cfg, callbackUrl, flow)
280
- .catch((error: unknown) => ({ claims: undefined, denial: describeExchangeError(error) }))
281
- if (exchanged.denial) return { ...base, claims: null, outcome: 'deny', user: null, denial: exchanged.denial }
282
- const decision = await evaluateOidcClaims(cfg, exchanged.claims)
283
- if (decision.provision) return { ...base, claims: exchanged.claims, outcome: 'provision', user: decision.provision.email, denial: null }
284
- if (decision.denial) return { ...base, claims: exchanged.claims, outcome: 'deny', user: null, denial: decision.denial }
285
- return { ...base, claims: exchanged.claims, outcome: decision.link ? 'link' : 'sign_in', user: decision.user.email, denial: null }
286
- }
287
-
288
- return { beginOidcLogin, exchangeOidcCode, evaluateOidcClaims, linkOidcIdentity, provisionSsoUser, auditOidcDenial, testOidcDiscovery, storeOidcTestResult, readOidcTestResult, runOidcTest }
289
- }
290
-
291
- export type Oidc = ReturnType<typeof createOidc>
1
+ import { randomBytes, randomUUID } from 'node:crypto'
2
+ import bcrypt from 'bcryptjs'
3
+ import * as client from 'openid-client'
4
+ import { and, eq, sql } from 'drizzle-orm'
5
+ import { users } from './tables.js'
6
+ import type { AuthOptions } from './context.js'
7
+ import { ADMIN_ROLE } from './roles.js'
8
+ import type { OidcConfig } from './oidcConfig.js'
9
+ import type { SignInAudit } from './signInAudit.js'
10
+
11
+ type User = typeof users.$inferSelect
12
+
13
+ export interface OidcFlowState {
14
+ state: string
15
+ nonce: string
16
+ codeVerifier: string
17
+ }
18
+
19
+ /** An SSO confirmation must come from a sign-in at the provider no older than this (the ID token's auth_time). */
20
+ export const OIDC_CONFIRMATION_MAX_AGE_SECONDS = 5 * 60
21
+
22
+ /** Why an SSO sign-in was refused. The user only sees a generic message; the audit log gets the code and detail. */
23
+ export type OidcDenialCode =
24
+ | 'discovery_failed'
25
+ | 'flow_expired'
26
+ | 'idp_error'
27
+ | 'token_exchange_failed'
28
+ | 'no_email_claim'
29
+ | 'email_not_verified'
30
+ | 'no_matching_account'
31
+ | 'subject_mismatch'
32
+ | 'confirmation_mismatch'
33
+
34
+ export interface OidcDenial {
35
+ code: OidcDenialCode
36
+ reason: string
37
+ email?: string
38
+ }
39
+
40
+ /** An account an SSO sign-in may create, bound to this identity. The application decides who qualifies and the role (see `resolveUnknownSsoUser`). */
41
+ export interface SsoProvisioning {
42
+ email: string
43
+ subject: string
44
+ role: string
45
+ }
46
+
47
+ /**
48
+ * The outcome for a set of validated ID token claims. `link` means the user was matched by email and the
49
+ * identity (issuer + subject) should now be bound to them, so later sign-ins no longer depend on the email.
50
+ * A denial for an unknown email carries `provision` when a sign-in may create an account instead.
51
+ */
52
+ export type OidcDecision =
53
+ | { user: User; link: boolean; subject: string; denial?: undefined; provision?: undefined }
54
+ | { user: null; denial: OidcDenial; provision?: SsoProvisioning | undefined }
55
+
56
+ // Some providers send booleans as strings ("true").
57
+ const isTrue = (value: unknown) => value === true || value === 'true'
58
+
59
+ const isFalse = (value: unknown) => value === false || value === 'false'
60
+
61
+ /**
62
+ * Whether the email claim may be trusted. `email_verified` is the standard claim; Microsoft Entra ID never
63
+ * sends it but offers the optional `xms_edov` claim (email domain owner verified) instead. An explicit
64
+ * `false` from either claim is never overridden by `allowUnverifiedEmail`.
65
+ */
66
+ export function checkEmailVerified(claims: Record<string, unknown>, allowUnverifiedEmail: boolean): string | null {
67
+ const standard = claims['email_verified']
68
+ const entra = claims['xms_edov']
69
+ if (isTrue(standard) || isTrue(entra)) return null
70
+ if (isFalse(standard)) return 'The identity provider reports the email as unverified (email_verified is false).'
71
+ if (isFalse(entra)) return 'Microsoft Entra ID reports that the email domain is not verified (xms_edov is false).'
72
+ if (allowUnverifiedEmail && standard === undefined && entra === undefined) return null
73
+ return 'The ID token has neither an email_verified nor an xms_edov claim. For Microsoft Entra ID, add the xms_edov optional claim to the ID token. '
74
+ + 'For other providers, enable "Accept identity providers that omit email_verified" only if their email claim is trustworthy.'
75
+ }
76
+
77
+ // ── Test sign-in ────────────────────────────────────────────────────────────
78
+ // An administrator runs the real flow to see the claims and what would happen, without signing anyone in.
79
+
80
+ export interface OidcTestResult {
81
+ issuer: string
82
+ testedAt: number
83
+ claims: Record<string, unknown> | null
84
+ /** `provision`: the sign-in would create an account. */
85
+ outcome: 'sign_in' | 'link' | 'provision' | 'deny'
86
+ user: string | null
87
+ denial: OidcDenial | null
88
+ }
89
+
90
+ const TEST_RESULT_TTL_MS = 10 * 60 * 1000
91
+
92
+ export function createOidc(ctx: AuthOptions, signInAudit: SignInAudit) {
93
+ const { db, audit } = ctx
94
+ const hooks = ctx.hooks ?? {}
95
+ const { auditSignInDenial } = signInAudit
96
+
97
+ let cached: { key: string; config: Promise<client.Configuration> } | null = null
98
+
99
+ function runDiscovery(cfg: OidcConfig): Promise<client.Configuration> {
100
+ const issuer = new URL(cfg.issuer)
101
+ // The client library refuses plain http; allow it only for issuers configured that way (e.g. a local Keycloak).
102
+ const options = issuer.protocol === 'http:' ? { execute: [client.allowInsecureRequests] } : undefined
103
+ return client.discovery(issuer, cfg.clientId, cfg.clientSecret || undefined, undefined, options)
104
+ }
105
+
106
+ function discover(cfg: OidcConfig): Promise<client.Configuration> {
107
+ const key = `${cfg.issuer}|${cfg.clientId}|${cfg.clientSecret}`
108
+ if (cached?.key !== key) {
109
+ const config = runDiscovery(cfg)
110
+ config.catch(() => { if (cached?.key === key) cached = null })
111
+ cached = { key, config }
112
+ }
113
+ return cached.config
114
+ }
115
+
116
+ /**
117
+ * Builds the provider redirect. `confirm` asks the provider to authenticate the user again (`prompt=login`)
118
+ * and to report when it did (`max_age`), so the callback can require a fresh `auth_time`.
119
+ */
120
+ async function beginOidcLogin(cfg: OidcConfig, options: { confirm?: boolean } = {}): Promise<{ url: string; flow: OidcFlowState }> {
121
+ const config = await discover(cfg)
122
+ const flow: OidcFlowState = {
123
+ state: client.randomState(),
124
+ nonce: client.randomNonce(),
125
+ codeVerifier: client.randomPKCECodeVerifier(),
126
+ }
127
+ const url = client.buildAuthorizationUrl(config, {
128
+ redirect_uri: cfg.redirectUri,
129
+ scope: cfg.scopes,
130
+ state: flow.state,
131
+ nonce: flow.nonce,
132
+ code_challenge: await client.calculatePKCECodeChallenge(flow.codeVerifier),
133
+ code_challenge_method: 'S256',
134
+ ...(options.confirm ? { prompt: 'login', max_age: String(OIDC_CONFIRMATION_MAX_AGE_SECONDS) } : {}),
135
+ })
136
+ return { url: url.href, flow }
137
+ }
138
+
139
+ /**
140
+ * Completes the code exchange and returns the validated ID token claims, or why that failed. With `maxAge`
141
+ * the ID token must carry an `auth_time` no older than that many seconds.
142
+ */
143
+ async function exchangeOidcCode(
144
+ cfg: OidcConfig, callbackUrl: URL, flow: OidcFlowState, maxAge?: number,
145
+ ): Promise<{ claims: Record<string, unknown>; denial?: undefined } | { claims?: undefined; denial: OidcDenial }> {
146
+ const config = await discover(cfg)
147
+ try {
148
+ const tokens = await client.authorizationCodeGrant(config, callbackUrl, {
149
+ pkceCodeVerifier: flow.codeVerifier,
150
+ expectedState: flow.state,
151
+ expectedNonce: flow.nonce,
152
+ idTokenExpected: true,
153
+ ...(maxAge !== undefined ? { maxAge } : {}),
154
+ })
155
+ return { claims: tokens.claims() ?? {} }
156
+ } catch (error) {
157
+ return { denial: describeExchangeError(error) }
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Finds the local user for validated claims without changing anything. An identity already bound to a
163
+ * user wins; otherwise the verified email is matched, but never onto a user bound to another identity at
164
+ * the same provider, so an email address given to someone else cannot take over the account.
165
+ */
166
+ async function evaluateOidcClaims(cfg: OidcConfig, claims: Record<string, unknown>): Promise<OidcDecision> {
167
+ const subject = typeof claims['sub'] === 'string' ? claims['sub'] : ''
168
+ if (subject) {
169
+ const bound = (await db.select().from(users)
170
+ .where(and(eq(users.oidcIssuer, cfg.issuer), eq(users.oidcSubject, subject))))[0]
171
+ if (bound) return { user: bound, link: false, subject }
172
+ }
173
+
174
+ const email = typeof claims['email'] === 'string' ? claims['email'].trim().toLowerCase() : ''
175
+ if (!email) {
176
+ return {
177
+ user: null,
178
+ denial: {
179
+ code: 'no_email_claim',
180
+ reason: `The ID token has no email claim. Request the "email" scope and, for Microsoft Entra ID, add the email optional claim. Claims received: ${Object.keys(claims).join(', ') || 'none'}.`,
181
+ },
182
+ }
183
+ }
184
+ const unverified = checkEmailVerified(claims, cfg.allowUnverifiedEmail)
185
+ if (unverified) return { user: null, denial: { code: 'email_not_verified', reason: unverified, email } }
186
+ const user = (await db.select().from(users).where(sql`lower(${users.email}) = ${email}`))[0]
187
+ if (!user) {
188
+ const resolved = subject ? await hooks.resolveUnknownSsoUser?.({ email, subject, issuer: cfg.issuer }) : null
189
+ // A role the application did not register, or admin, is never handed out by a sign-in: no account is created.
190
+ const provision = subject && resolved && ctx.roles.isValid(resolved.role) && resolved.role !== ADMIN_ROLE ? { email, subject, role: resolved.role } : undefined
191
+ return { user: null, denial: { code: 'no_matching_account', reason: `No user has the email ${email}. Create the user first.`, email }, provision }
192
+ }
193
+ if (user.oidcSubject && user.oidcIssuer === cfg.issuer) {
194
+ return {
195
+ user: null,
196
+ denial: {
197
+ code: 'subject_mismatch',
198
+ reason: `${user.email} is linked to another identity at this provider (subject ${user.oidcSubject}; this sign-in: ${subject || 'none'}). `
199
+ + 'The email address may have been given to someone else.',
200
+ email,
201
+ },
202
+ }
203
+ }
204
+ return { user, link: true, subject }
205
+ }
206
+
207
+ /** Binds the provider identity to the user and records it; a binding to a previous issuer is replaced. */
208
+ async function linkOidcIdentity(cfg: OidcConfig, user: User, subject: string): Promise<void> {
209
+ await db.update(users).set({ oidcIssuer: cfg.issuer, oidcSubject: subject }).where(eq(users.id, user.id))
210
+ await audit.write(
211
+ { userId: user.id, userEmail: user.email },
212
+ 'update', 'user-security', user.id, user.email,
213
+ { ssoLinked: { from: user.oidcIssuer, to: cfg.issuer }, subject },
214
+ )
215
+ }
216
+
217
+ /**
218
+ * Creates the account of a first SSO sign-in, already bound to the identity.
219
+ * Its password is random and never handed out: the account signs in through SSO only.
220
+ */
221
+ async function provisionSsoUser(cfg: OidcConfig, provision: SsoProvisioning): Promise<User> {
222
+ const passwordHash = await bcrypt.hash(randomBytes(32).toString('base64url'), 10)
223
+ const [user] = await db.insert(users).values({
224
+ email: provision.email,
225
+ passwordHash,
226
+ role: provision.role,
227
+ createdAt: Date.now(),
228
+ oidcIssuer: cfg.issuer,
229
+ oidcSubject: provision.subject,
230
+ }).returning()
231
+ await audit.write(
232
+ { userId: user!.id, userEmail: user!.email },
233
+ 'create', 'user', user!.id, user!.email,
234
+ { email: user!.email, role: provision.role, createdBy: 'sso', issuer: cfg.issuer },
235
+ )
236
+ return user!
237
+ }
238
+
239
+ /** Records a refused SSO sign-in or confirmation as a 'sign_in' denial, with the issuer. */
240
+ async function auditOidcDenial(cfg: OidcConfig, denial: OidcDenial): Promise<void> {
241
+ await auditSignInDenial('sso', denial, { issuer: cfg.issuer })
242
+ }
243
+
244
+ function describeExchangeError(error: unknown): OidcDenial {
245
+ if (error instanceof client.AuthorizationResponseError) {
246
+ const description = error.error_description ? `: ${error.error_description}` : ''
247
+ return { code: 'idp_error', reason: `The identity provider returned ${error.error}${description}`.slice(0, 1000) }
248
+ }
249
+ const message = error instanceof Error ? error.message : String(error)
250
+ return { code: 'token_exchange_failed', reason: `Code exchange or ID token validation failed: ${message}`.slice(0, 1000) }
251
+ }
252
+
253
+ /** Runs OIDC discovery against the issuer without caching, to validate settings before saving them. */
254
+ async function testOidcDiscovery(cfg: OidcConfig): Promise<{ issuer: string; authorizationEndpoint: string | null }> {
255
+ const config = await runDiscovery(cfg)
256
+ const meta = config.serverMetadata()
257
+ return { issuer: meta.issuer, authorizationEndpoint: meta.authorization_endpoint ?? null }
258
+ }
259
+
260
+ const testResults = new Map<string, { adminUserId: number; expiresAt: number; result: OidcTestResult }>()
261
+
262
+ function storeOidcTestResult(adminUserId: number, result: OidcTestResult): string {
263
+ const now = Date.now()
264
+ for (const [id, entry] of testResults) if (entry.expiresAt <= now) testResults.delete(id)
265
+ const id = randomUUID()
266
+ testResults.set(id, { adminUserId, expiresAt: now + TEST_RESULT_TTL_MS, result })
267
+ return id
268
+ }
269
+
270
+ /** Only the administrator who started the test can read its result. */
271
+ function readOidcTestResult(id: string, adminUserId: number): OidcTestResult | null {
272
+ const entry = testResults.get(id)
273
+ if (!entry || entry.expiresAt <= Date.now() || entry.adminUserId !== adminUserId) return null
274
+ return entry.result
275
+ }
276
+
277
+ async function runOidcTest(cfg: OidcConfig, callbackUrl: URL, flow: OidcFlowState): Promise<OidcTestResult> {
278
+ const base = { issuer: cfg.issuer, testedAt: Date.now() }
279
+ const exchanged = await exchangeOidcCode(cfg, callbackUrl, flow)
280
+ .catch((error: unknown) => ({ claims: undefined, denial: describeExchangeError(error) }))
281
+ if (exchanged.denial) return { ...base, claims: null, outcome: 'deny', user: null, denial: exchanged.denial }
282
+ const decision = await evaluateOidcClaims(cfg, exchanged.claims)
283
+ if (decision.provision) return { ...base, claims: exchanged.claims, outcome: 'provision', user: decision.provision.email, denial: null }
284
+ if (decision.denial) return { ...base, claims: exchanged.claims, outcome: 'deny', user: null, denial: decision.denial }
285
+ return { ...base, claims: exchanged.claims, outcome: decision.link ? 'link' : 'sign_in', user: decision.user.email, denial: null }
286
+ }
287
+
288
+ return { beginOidcLogin, exchangeOidcCode, evaluateOidcClaims, linkOidcIdentity, provisionSsoUser, auditOidcDenial, testOidcDiscovery, storeOidcTestResult, readOidcTestResult, runOidcTest }
289
+ }
290
+
291
+ export type Oidc = ReturnType<typeof createOidc>