@better-forge/auth 0.0.0-stage → 0.1.0

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 (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -3
  3. package/dist/apiTokenRoutes.d.ts +8 -0
  4. package/dist/apiTokenRoutes.d.ts.map +1 -0
  5. package/dist/apiTokenRoutes.js +67 -0
  6. package/dist/apiTokenRoutes.js.map +1 -0
  7. package/dist/apiTokens.d.ts +25 -0
  8. package/dist/apiTokens.d.ts.map +1 -0
  9. package/dist/apiTokens.js +50 -0
  10. package/dist/apiTokens.js.map +1 -0
  11. package/dist/authRoutes.d.ts +37 -0
  12. package/dist/authRoutes.d.ts.map +1 -0
  13. package/dist/authRoutes.js +403 -0
  14. package/dist/authRoutes.js.map +1 -0
  15. package/dist/context.d.ts +98 -0
  16. package/dist/context.d.ts.map +1 -0
  17. package/dist/context.js +2 -0
  18. package/dist/context.js.map +1 -0
  19. package/dist/createAuth.d.ts +146 -0
  20. package/dist/createAuth.d.ts.map +1 -0
  21. package/dist/createAuth.js +52 -0
  22. package/dist/createAuth.js.map +1 -0
  23. package/dist/identityConfirmation.d.ts +13 -0
  24. package/dist/identityConfirmation.d.ts.map +1 -0
  25. package/dist/identityConfirmation.js +37 -0
  26. package/dist/identityConfirmation.js.map +1 -0
  27. package/dist/index.d.ts +18 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +14 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/middleware.d.ts +41 -0
  32. package/dist/middleware.d.ts.map +1 -0
  33. package/dist/middleware.js +100 -0
  34. package/dist/middleware.js.map +1 -0
  35. package/dist/migrations.d.ts +4 -0
  36. package/dist/migrations.d.ts.map +1 -0
  37. package/dist/migrations.js +77 -0
  38. package/dist/migrations.js.map +1 -0
  39. package/dist/module.d.ts +8 -0
  40. package/dist/module.d.ts.map +1 -0
  41. package/dist/module.js +5 -0
  42. package/dist/module.js.map +1 -0
  43. package/dist/oidc.d.ts +85 -0
  44. package/dist/oidc.d.ts.map +1 -0
  45. package/dist/oidc.js +213 -0
  46. package/dist/oidc.js.map +1 -0
  47. package/dist/oidcConfig.d.ts +39 -0
  48. package/dist/oidcConfig.d.ts.map +1 -0
  49. package/dist/oidcConfig.js +72 -0
  50. package/dist/oidcConfig.js.map +1 -0
  51. package/dist/oidcSettings.d.ts +15 -0
  52. package/dist/oidcSettings.d.ts.map +1 -0
  53. package/dist/oidcSettings.js +51 -0
  54. package/dist/oidcSettings.js.map +1 -0
  55. package/dist/oidcSettingsRoutes.d.ts +19 -0
  56. package/dist/oidcSettingsRoutes.d.ts.map +1 -0
  57. package/dist/oidcSettingsRoutes.js +133 -0
  58. package/dist/oidcSettingsRoutes.js.map +1 -0
  59. package/dist/roles.d.ts +25 -0
  60. package/dist/roles.d.ts.map +1 -0
  61. package/dist/roles.js +44 -0
  62. package/dist/roles.js.map +1 -0
  63. package/dist/routeScope.d.ts +34 -0
  64. package/dist/routeScope.d.ts.map +1 -0
  65. package/dist/routeScope.js +32 -0
  66. package/dist/routeScope.js.map +1 -0
  67. package/dist/sessions.d.ts +46 -0
  68. package/dist/sessions.d.ts.map +1 -0
  69. package/dist/sessions.js +159 -0
  70. package/dist/sessions.js.map +1 -0
  71. package/dist/setupRoutes.d.ts +37 -0
  72. package/dist/setupRoutes.d.ts.map +1 -0
  73. package/dist/setupRoutes.js +70 -0
  74. package/dist/setupRoutes.js.map +1 -0
  75. package/dist/signInAudit.d.ts +19 -0
  76. package/dist/signInAudit.d.ts.map +1 -0
  77. package/dist/signInAudit.js +16 -0
  78. package/dist/signInAudit.js.map +1 -0
  79. package/dist/tables.d.ts +716 -0
  80. package/dist/tables.d.ts.map +1 -0
  81. package/dist/tables.js +56 -0
  82. package/dist/tables.js.map +1 -0
  83. package/dist/tokenCatalogue.d.ts +21 -0
  84. package/dist/tokenCatalogue.d.ts.map +1 -0
  85. package/dist/tokenCatalogue.js +27 -0
  86. package/dist/tokenCatalogue.js.map +1 -0
  87. package/dist/totp.d.ts +12 -0
  88. package/dist/totp.d.ts.map +1 -0
  89. package/dist/totp.js +93 -0
  90. package/dist/totp.js.map +1 -0
  91. package/dist/twoFactor.d.ts +10 -0
  92. package/dist/twoFactor.d.ts.map +1 -0
  93. package/dist/twoFactor.js +43 -0
  94. package/dist/twoFactor.js.map +1 -0
  95. package/dist/userRoutes.d.ts +13 -0
  96. package/dist/userRoutes.d.ts.map +1 -0
  97. package/dist/userRoutes.js +135 -0
  98. package/dist/userRoutes.js.map +1 -0
  99. package/package.json +68 -6
  100. package/src/apiTokenRoutes.ts +82 -0
  101. package/src/apiTokens.ts +62 -0
  102. package/src/authRoutes.ts +452 -0
  103. package/src/context.ts +85 -0
  104. package/src/createAuth.ts +58 -0
  105. package/src/identityConfirmation.ts +50 -0
  106. package/src/index.ts +17 -0
  107. package/src/middleware.ts +123 -0
  108. package/src/migrations.ts +77 -0
  109. package/src/module.ts +6 -0
  110. package/src/oidc.ts +291 -0
  111. package/src/oidcConfig.ts +96 -0
  112. package/src/oidcSettings.ts +60 -0
  113. package/src/oidcSettingsRoutes.ts +165 -0
  114. package/src/roles.ts +60 -0
  115. package/src/routeScope.ts +50 -0
  116. package/src/sessions.ts +209 -0
  117. package/src/setupRoutes.ts +100 -0
  118. package/src/signInAudit.ts +43 -0
  119. package/src/tables.ts +59 -0
  120. package/src/tokenCatalogue.ts +42 -0
  121. package/src/totp.ts +96 -0
  122. package/src/twoFactor.ts +49 -0
  123. package/src/userRoutes.ts +144 -0
package/src/oidc.ts ADDED
@@ -0,0 +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>
@@ -0,0 +1,96 @@
1
+ export const DEFAULT_OIDC_SCOPES = 'openid email profile'
2
+ export const DEFAULT_OIDC_BUTTON_LABEL = 'Sign in with SSO'
3
+
4
+ export interface OidcConfig {
5
+ issuer: string
6
+ clientId: string
7
+ clientSecret: string
8
+ scopes: string
9
+ redirectUri: string
10
+ buttonLabel: string
11
+ allowUnverifiedEmail: boolean
12
+ disablePasswordLogin: boolean
13
+ }
14
+
15
+ /** Raw, unvalidated OIDC settings from either source (environment or the database). */
16
+ export interface OidcSettingsInput {
17
+ issuer?: string | undefined
18
+ clientId?: string | undefined
19
+ clientSecret?: string | undefined
20
+ scopes?: string | undefined
21
+ redirectUri?: string | undefined
22
+ buttonLabel?: string | undefined
23
+ allowUnverifiedEmail?: boolean | undefined
24
+ disablePasswordLogin?: boolean | undefined
25
+ }
26
+
27
+ function flag(value: string | undefined): boolean {
28
+ return ['1', 'true', 'yes'].includes((value ?? '').trim().toLowerCase())
29
+ }
30
+
31
+ export function isHttpUrl(value: string): boolean {
32
+ try {
33
+ const url = new URL(value)
34
+ return url.protocol === 'https:' || url.protocol === 'http:'
35
+ } catch {
36
+ return false
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Settings validation and the environment variables, for an application whose public address is `publicUrl(env)` and
42
+ * whose provider redirects back to `callbackPath`.
43
+ */
44
+ export function createOidcConfigResolver(options: { publicUrl: (env: NodeJS.ProcessEnv) => string; callbackPath: string }) {
45
+ /** Callback URL derived from the public URL, or '' when that is not set. */
46
+ function defaultOidcRedirectUri(env: NodeJS.ProcessEnv = process.env): string {
47
+ const publicUrl = options.publicUrl(env)
48
+ return publicUrl ? `${publicUrl}${options.callbackPath}` : ''
49
+ }
50
+
51
+ /** Validates raw settings and fills defaults. Returns null when they do not describe a usable setup. */
52
+ function buildOidcConfig(input: OidcSettingsInput, env: NodeJS.ProcessEnv = process.env): OidcConfig | null {
53
+ const issuer = (input.issuer ?? '').trim()
54
+ const clientId = (input.clientId ?? '').trim()
55
+ if (!issuer || !clientId || !isHttpUrl(issuer)) return null
56
+ const redirectUri = (input.redirectUri ?? '').trim() || defaultOidcRedirectUri(env)
57
+ if (!redirectUri || !isHttpUrl(redirectUri)) return null
58
+ return {
59
+ issuer,
60
+ clientId,
61
+ clientSecret: (input.clientSecret ?? '').trim(),
62
+ scopes: (input.scopes ?? '').trim() || DEFAULT_OIDC_SCOPES,
63
+ redirectUri,
64
+ buttonLabel: (input.buttonLabel ?? '').trim() || DEFAULT_OIDC_BUTTON_LABEL,
65
+ allowUnverifiedEmail: input.allowUnverifiedEmail === true,
66
+ disablePasswordLogin: input.disablePasswordLogin === true,
67
+ }
68
+ }
69
+
70
+ /**
71
+ * OIDC settings from environment variables, which override anything saved in the admin UI
72
+ * (for IaC deployments). Returns null when OIDC_ISSUER / OIDC_CLIENT_ID are not both set.
73
+ */
74
+ function resolveOidcConfigFromEnv(env: NodeJS.ProcessEnv = process.env): OidcConfig | null {
75
+ if (!(env['OIDC_ISSUER'] ?? '').trim() || !(env['OIDC_CLIENT_ID'] ?? '').trim()) return null
76
+ const config = buildOidcConfig({
77
+ issuer: env['OIDC_ISSUER'],
78
+ clientId: env['OIDC_CLIENT_ID'],
79
+ clientSecret: env['OIDC_CLIENT_SECRET'],
80
+ scopes: env['OIDC_SCOPES'],
81
+ redirectUri: env['OIDC_REDIRECT_URI'],
82
+ buttonLabel: env['OIDC_BUTTON_LABEL'],
83
+ allowUnverifiedEmail: flag(env['OIDC_ALLOW_UNVERIFIED_EMAIL']),
84
+ disablePasswordLogin: flag(env['OIDC_DISABLE_PASSWORD_LOGIN']),
85
+ }, env)
86
+ if (!config) console.warn('OIDC_* environment variables are set but incomplete or invalid (issuer, client id and a redirect URI or PUBLIC_URL are required) — OIDC sign-in is disabled')
87
+ return config
88
+ }
89
+
90
+ return { defaultOidcRedirectUri, buildOidcConfig, resolveOidcConfigFromEnv }
91
+ }
92
+
93
+ /** Password sign-in can only be turned off while OIDC is usable, so nobody is locked out by a typo. */
94
+ export function passwordLoginEnabled(config: OidcConfig | null): boolean {
95
+ return !(config && config.disablePasswordLogin)
96
+ }
@@ -0,0 +1,60 @@
1
+ import { eq } from 'drizzle-orm'
2
+ import { oidcSettings } from './tables.js'
3
+ import type { AuthOptions } from './context.js'
4
+ import type { OidcConfig, createOidcConfigResolver } from './oidcConfig.js'
5
+
6
+ export type OidcSettingsRow = typeof oidcSettings.$inferSelect
7
+
8
+ export function createOidcSettings(ctx: AuthOptions, resolver: ReturnType<typeof createOidcConfigResolver>) {
9
+ const { db, secretBox } = ctx
10
+ const { buildOidcConfig, resolveOidcConfigFromEnv } = resolver
11
+
12
+ async function getOidcSettingsRow(): Promise<OidcSettingsRow | null> {
13
+ return (await db.select().from(oidcSettings).where(eq(oidcSettings.id, 1)))[0] ?? null
14
+ }
15
+
16
+ function oidcConfigFromRow(row: OidcSettingsRow): OidcConfig | null {
17
+ return buildOidcConfig({
18
+ issuer: row.issuer,
19
+ clientId: row.clientId,
20
+ clientSecret: row.clientSecret ? secretBox.decrypt(row.clientSecret) : '',
21
+ scopes: row.scopes,
22
+ redirectUri: row.redirectUri,
23
+ buttonLabel: row.buttonLabel,
24
+ allowUnverifiedEmail: !!row.allowUnverifiedEmail,
25
+ disablePasswordLogin: !!row.disablePasswordLogin,
26
+ })
27
+ }
28
+
29
+ /** OIDC_FORCE_PASSWORD_LOGIN=true is the break-glass switch when the IdP is down and password sign-in was disabled. */
30
+ function withPasswordOverride(config: OidcConfig): OidcConfig {
31
+ return ['1', 'true', 'yes'].includes((process.env['OIDC_FORCE_PASSWORD_LOGIN'] ?? '').trim().toLowerCase())
32
+ ? { ...config, disablePasswordLogin: false }
33
+ : config
34
+ }
35
+
36
+ /**
37
+ * The OIDC configuration in effect: environment variables win (deployment-managed), otherwise the
38
+ * settings saved in the admin UI when enabled. Read per request, so saving takes effect without a restart.
39
+ */
40
+ async function getOidcConfig(): Promise<{ config: OidcConfig | null; source: 'env' | 'database' | 'none' }> {
41
+ const fromEnv = resolveOidcConfigFromEnv()
42
+ if (fromEnv) return { config: withPasswordOverride(fromEnv), source: 'env' }
43
+ const row = await getOidcSettingsRow()
44
+ if (!row?.enabled) return { config: null, source: 'none' }
45
+ const config = oidcConfigFromRow(row)
46
+ return { config: config && withPasswordOverride(config), source: config ? 'database' : 'none' }
47
+ }
48
+
49
+ /** Settings a test sign-in runs against: the environment, or the saved settings even while SSO is switched off. */
50
+ async function getOidcTestConfig(): Promise<OidcConfig | null> {
51
+ const fromEnv = resolveOidcConfigFromEnv()
52
+ if (fromEnv) return fromEnv
53
+ const row = await getOidcSettingsRow()
54
+ return row ? oidcConfigFromRow(row) : null
55
+ }
56
+
57
+ return { getOidcSettingsRow, oidcConfigFromRow, getOidcConfig, getOidcTestConfig }
58
+ }
59
+
60
+ export type OidcSettings = ReturnType<typeof createOidcSettings>
@@ -0,0 +1,165 @@
1
+ import type { FastifyInstance, FastifyReply } from 'fastify'
2
+ import { oidcSettings } from './tables.js'
3
+ import { requestIdentity } from './middleware.js'
4
+ import type { AuthOptions } from './context.js'
5
+ import type { IdentityConfirmation } from './identityConfirmation.js'
6
+ import type { Oidc } from './oidc.js'
7
+ import type { OidcSettings, OidcSettingsRow } from './oidcSettings.js'
8
+ import type { OidcConfig, createOidcConfigResolver } from './oidcConfig.js'
9
+
10
+ interface SettingsBody {
11
+ enabled?: boolean
12
+ issuer?: string
13
+ clientId?: string
14
+ /** Non-empty replaces the stored secret; omitted or empty keeps it, unless the issuer or client ID changed. */
15
+ clientSecret?: string
16
+ scopes?: string
17
+ redirectUri?: string
18
+ buttonLabel?: string
19
+ allowUnverifiedEmail?: boolean
20
+ disablePasswordLogin?: boolean
21
+ currentPassword?: string
22
+ }
23
+
24
+ export function createOidcSettingsRoutes(ctx: AuthOptions, parts: {
25
+ identityConfirmation: IdentityConfirmation
26
+ oidc: Oidc
27
+ oidcSettings: OidcSettings
28
+ resolver: ReturnType<typeof createOidcConfigResolver>
29
+ startOidcFlow: (app: FastifyInstance, reply: FastifyReply, cfg: OidcConfig, extra: { purpose?: 'oidc-flow' | 'oidc-test' | 'oidc-confirm'; adminUserId?: number }) => Promise<unknown>
30
+ }) {
31
+ const { db, audit, secretBox } = ctx
32
+ const { confirmIdentity } = parts.identityConfirmation
33
+ const { readOidcTestResult, storeOidcTestResult, testOidcDiscovery } = parts.oidc
34
+ const { getOidcConfig, getOidcSettingsRow, getOidcTestConfig, oidcConfigFromRow } = parts.oidcSettings
35
+ const { buildOidcConfig, defaultOidcRedirectUri } = parts.resolver
36
+ const { startOidcFlow } = parts
37
+
38
+ function publicView(row: OidcSettingsRow | null) {
39
+ return {
40
+ enabled: !!row?.enabled,
41
+ issuer: row?.issuer ?? '',
42
+ clientId: row?.clientId ?? '',
43
+ hasClientSecret: !!row?.clientSecret,
44
+ scopes: row?.scopes ?? '',
45
+ redirectUri: row?.redirectUri ?? '',
46
+ buttonLabel: row?.buttonLabel ?? '',
47
+ allowUnverifiedEmail: !!row?.allowUnverifiedEmail,
48
+ disablePasswordLogin: !!row?.disablePasswordLogin,
49
+ }
50
+ }
51
+
52
+ /** Fields that appear in the audit diff; the secret is only recorded as changed, never its value. */
53
+ function auditView(row: OidcSettingsRow | null, secretChanged = false) {
54
+ const { hasClientSecret: _has, ...rest } = publicView(row)
55
+ return { ...rest, clientSecretChanged: secretChanged }
56
+ }
57
+
58
+ async function discoveryError(config: OidcConfig): Promise<string | null> {
59
+ try {
60
+ await testOidcDiscovery(config)
61
+ return null
62
+ } catch (error) {
63
+ return error instanceof Error ? error.message : 'Discovery failed'
64
+ }
65
+ }
66
+
67
+ async function oidcSettingsRoutes(app: FastifyInstance) {
68
+ app.get('/', async () => {
69
+ const [row, active] = await Promise.all([getOidcSettingsRow(), getOidcConfig()])
70
+ return {
71
+ source: active.source,
72
+ envManaged: active.source === 'env',
73
+ defaultRedirectUri: defaultOidcRedirectUri(),
74
+ settings: publicView(row),
75
+ }
76
+ })
77
+
78
+ app.put<{ Body: SettingsBody }>('/', { config: { rateLimit: ctx.rateLimits.sensitiveAction } }, async (req, reply) => {
79
+ if ((await getOidcConfig()).source === 'env') {
80
+ return reply.code(409).send({ error: 'OIDC is configured through environment variables and cannot be changed here' })
81
+ }
82
+ const body = req.body ?? {}
83
+ const identity = requestIdentity(req)
84
+ if (!await confirmIdentity(identity, body.currentPassword, reply)) return reply
85
+
86
+ const previous = await getOidcSettingsRow()
87
+ const secretChanged = !!body.clientSecret?.trim()
88
+ // The stored secret is sent to the issuer's token endpoint, so it must not follow a changed target.
89
+ if (previous?.clientSecret && !secretChanged && (
90
+ (body.issuer ?? '').trim() !== previous.issuer || (body.clientId ?? '').trim() !== previous.clientId
91
+ )) {
92
+ return reply.code(400).send({ error: 'Re-enter the client secret when changing the issuer URL or client ID' })
93
+ }
94
+ const clientSecret = secretChanged ? secretBox.encrypt(body.clientSecret!.trim()) : previous?.clientSecret ?? ''
95
+ const next: OidcSettingsRow = {
96
+ id: 1,
97
+ enabled: body.enabled ? 1 : 0,
98
+ issuer: (body.issuer ?? '').trim(),
99
+ clientId: (body.clientId ?? '').trim(),
100
+ clientSecret,
101
+ scopes: (body.scopes ?? '').trim(),
102
+ redirectUri: (body.redirectUri ?? '').trim(),
103
+ buttonLabel: (body.buttonLabel ?? '').trim(),
104
+ allowUnverifiedEmail: body.allowUnverifiedEmail ? 1 : 0,
105
+ disablePasswordLogin: body.disablePasswordLogin ? 1 : 0,
106
+ updatedAt: Date.now(),
107
+ }
108
+
109
+ if (next.enabled) {
110
+ const config = oidcConfigFromRow(next)
111
+ if (!config) {
112
+ return reply.code(400).send({ error: 'Issuer URL, client ID and a redirect URI (or PUBLIC_URL) are required and must be valid http(s) URLs' })
113
+ }
114
+ // Never persist a setup that could lock everyone out: with password login off, the IdP must be reachable.
115
+ if (config.disablePasswordLogin) {
116
+ const failure = await discoveryError(config)
117
+ if (failure) return reply.code(400).send({ error: `Password sign-in can only be disabled after OIDC discovery succeeds: ${failure}` })
118
+ }
119
+ } else {
120
+ next.disablePasswordLogin = 0
121
+ }
122
+
123
+ await db.insert(oidcSettings).values(next).onConflictDoUpdate({ target: oidcSettings.id, set: { ...next } })
124
+ await audit.write(audit.actor(identity), previous ? 'update' : 'create', 'oidc_settings', 1, 'OIDC sign-in',
125
+ audit.diffObjects(auditView(previous), auditView(next, secretChanged)))
126
+ return publicView(next)
127
+ })
128
+
129
+ // Opened in a new tab: runs the real sign-in with the saved settings and shows the outcome instead of signing in.
130
+ app.get('/test-sign-in', { config: { rateLimit: ctx.rateLimits.sensitiveAction } }, async (req, reply) => {
131
+ const cfg = await getOidcTestConfig()
132
+ if (!cfg) return reply.code(400).send({ error: 'Save a valid issuer URL, client ID and redirect URI first' })
133
+ try {
134
+ return await startOidcFlow(app, reply, cfg, { purpose: 'oidc-test', adminUserId: requestIdentity(req).userId })
135
+ } catch (error) {
136
+ const result = {
137
+ issuer: cfg.issuer, testedAt: Date.now(), claims: null, outcome: 'deny' as const, user: null,
138
+ denial: { code: 'discovery_failed' as const, reason: `OIDC discovery against the issuer failed: ${error instanceof Error ? error.message : String(error)}` },
139
+ }
140
+ return reply.redirect(`${ctx.urls.ssoTest}?result=${storeOidcTestResult(requestIdentity(req).userId, result)}`)
141
+ }
142
+ })
143
+
144
+ app.get<{ Params: { id: string } }>('/test-sign-in/:id', async (req, reply) => {
145
+ const result = readOidcTestResult(req.params.id, requestIdentity(req).userId)
146
+ if (!result) return reply.code(404).send({ error: 'The test result has expired. Run the test sign-in again.' })
147
+ return result
148
+ })
149
+
150
+ app.post<{ Body: SettingsBody }>('/test', { config: { rateLimit: ctx.rateLimits.sensitiveAction } }, async (req, reply) => {
151
+ const body = req.body ?? {}
152
+ const config = buildOidcConfig({
153
+ issuer: body.issuer,
154
+ clientId: body.clientId,
155
+ redirectUri: body.redirectUri,
156
+ })
157
+ if (!config) return reply.code(400).send({ error: 'Enter a valid issuer URL, client ID and a redirect URI (or set PUBLIC_URL)' })
158
+ const failure = await discoveryError(config)
159
+ if (failure) return reply.code(400).send({ error: `Discovery failed: ${failure}` })
160
+ return { ok: true, ...(await testOidcDiscovery(config)) }
161
+ })
162
+ }
163
+
164
+ return { oidcSettingsRoutes }
165
+ }
package/src/roles.ts ADDED
@@ -0,0 +1,60 @@
1
+ /** The role that may do everything; it exists in every application. */
2
+ export const ADMIN_ROLE = 'admin'
3
+
4
+ export interface RoleRegistry {
5
+ /**
6
+ * Adds the application's roles to `admin`. `fallback` is what a stored value that is not a role normalises to,
7
+ * and `defaultForNewUsers` is the role an account gets when none is asked for.
8
+ */
9
+ register(roles: readonly string[], options: { fallback: string; defaultForNewUsers: string }): void
10
+ /** Normalizes a stored role value, including the legacy JSON-array format. */
11
+ normalize(raw: string): string
12
+ isValid(role: string): boolean
13
+ /** Every role, `admin` first, in the order they were registered. */
14
+ list(): readonly string[]
15
+ readonly defaultForNewUsers: string
16
+ /**
17
+ * Called by createAuth: after this, registering throws, so the set of roles cannot change under a running app.
18
+ * It also throws when the application never registered its roles, because the fallback would then be `admin`.
19
+ */
20
+ freeze(): void
21
+ }
22
+
23
+ export function createRoleRegistry(): RoleRegistry {
24
+ const roles: string[] = [ADMIN_ROLE]
25
+ let fallback: string = ADMIN_ROLE
26
+ let defaultForNewUsers: string = ADMIN_ROLE
27
+ let frozen = false
28
+ let registered = false
29
+
30
+ const isValid = (role: string) => roles.includes(role)
31
+
32
+ return {
33
+ register(added, options) {
34
+ if (frozen) throw new Error('Roles cannot be registered after the auth module was created')
35
+ for (const role of added) if (!roles.includes(role)) roles.push(role)
36
+ if (!roles.includes(options.fallback) || !roles.includes(options.defaultForNewUsers)) {
37
+ throw new Error('The fallback and the default role for new users must be registered roles')
38
+ }
39
+ fallback = options.fallback
40
+ defaultForNewUsers = options.defaultForNewUsers
41
+ registered = true
42
+ },
43
+ normalize(raw) {
44
+ try {
45
+ const parsed: unknown = JSON.parse(raw)
46
+ const role = Array.isArray(parsed) ? parsed[0] : raw
47
+ return typeof role === 'string' && isValid(role) ? role : fallback
48
+ } catch {
49
+ return isValid(raw) ? raw : fallback
50
+ }
51
+ },
52
+ isValid,
53
+ list: () => roles,
54
+ get defaultForNewUsers() { return defaultForNewUsers },
55
+ freeze() {
56
+ if (!registered) throw new Error('Register the application roles before creating the auth module: without them every unknown role would be an administrator')
57
+ frozen = true
58
+ },
59
+ }
60
+ }