@fabrika/iam 0.9.0-dev.32 → 0.9.0-dev.34

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 (81) hide show
  1. package/fabrika.config.ts +47 -7
  2. package/migrations/0032_second_factor.sql +29 -0
  3. package/migrations/0033_oauth_grant_resources.sql +6 -0
  4. package/migrations/0034_oauth_device_authorizations.sql +24 -0
  5. package/migrations-postgres/0032_second_factor.sql +29 -0
  6. package/migrations-postgres/0033_oauth_grant_resources.sql +6 -0
  7. package/migrations-postgres/0034_oauth_device_authorizations.sql +24 -0
  8. package/package.json +12 -10
  9. package/src/admin/api-keys.ts +15 -5
  10. package/src/admin/grant-support.ts +10 -0
  11. package/src/admin/grants.ts +5 -2
  12. package/src/admin/handlers.ts +3 -0
  13. package/src/admin/principals.ts +2 -5
  14. package/src/admin/rpc.ts +8 -0
  15. package/src/admin/second-factor.ts +39 -0
  16. package/src/admin/sessions.ts +4 -4
  17. package/src/app.ts +1 -1
  18. package/src/auth/failure.ts +5 -0
  19. package/src/auth/http.ts +1 -1
  20. package/src/auth/invitations.ts +11 -3
  21. package/src/auth/login.ts +3 -2
  22. package/src/auth/oidc.ts +1 -1
  23. package/src/auth/password.ts +6 -6
  24. package/src/auth/routes.ts +11 -3
  25. package/src/auth/second-factor-challenge.ts +114 -0
  26. package/src/auth/second-factor.ts +276 -0
  27. package/src/auth/sessions.ts +72 -21
  28. package/src/auth.ts +19 -4
  29. package/src/catalog/cs.ts +32 -0
  30. package/src/catalog/en.ts +33 -0
  31. package/src/catalog/index.ts +28 -0
  32. package/src/catalog/uk.ts +33 -0
  33. package/src/data-key.ts +92 -0
  34. package/src/db.ts +12 -1
  35. package/src/env.ts +15 -2
  36. package/src/node/runtime.ts +7 -0
  37. package/src/oauth-client-auth.ts +6 -2
  38. package/src/oauth-config.ts +5 -5
  39. package/src/oauth-device-page.ts +173 -0
  40. package/src/oauth-device.ts +265 -0
  41. package/src/oauth-http.ts +53 -7
  42. package/src/oauth.ts +105 -37
  43. package/src/oidc-session.ts +25 -0
  44. package/src/repositories/audit.ts +4 -2
  45. package/src/repositories/oauth.ts +171 -4
  46. package/src/repositories/second-factors.ts +165 -0
  47. package/src/repositories/sessions.ts +17 -9
  48. package/src/second-factor-pages.ts +129 -0
  49. package/src/services.ts +11 -2
  50. package/src/tokens.ts +3 -3
  51. package/src/totp.ts +132 -0
  52. package/types/src/admin/api-keys.d.ts +3 -3
  53. package/types/src/admin/grant-support.d.ts +2 -0
  54. package/types/src/admin/handlers.d.ts +3 -0
  55. package/types/src/admin/second-factor.d.ts +5 -0
  56. package/types/src/auth/failure.d.ts +10 -0
  57. package/types/src/auth/http.d.ts +1 -1
  58. package/types/src/auth/invitations.d.ts +2 -1
  59. package/types/src/auth/password.d.ts +1 -1
  60. package/types/src/auth/second-factor-challenge.d.ts +34 -0
  61. package/types/src/auth/second-factor.d.ts +19 -0
  62. package/types/src/auth/sessions.d.ts +22 -9
  63. package/types/src/auth.d.ts +9 -3
  64. package/types/src/catalog/index.d.ts +28 -0
  65. package/types/src/data-key.d.ts +19 -0
  66. package/types/src/db.d.ts +4 -1
  67. package/types/src/env.d.ts +15 -2
  68. package/types/src/oauth-config.d.ts +3 -3
  69. package/types/src/oauth-device-page.d.ts +7 -0
  70. package/types/src/oauth-device.d.ts +51 -0
  71. package/types/src/oauth-http.d.ts +5 -2
  72. package/types/src/oauth.d.ts +34 -8
  73. package/types/src/oidc-session.d.ts +12 -0
  74. package/types/src/repositories/audit.d.ts +2 -1
  75. package/types/src/repositories/oauth.d.ts +48 -1
  76. package/types/src/repositories/second-factors.d.ts +68 -0
  77. package/types/src/repositories/sessions.d.ts +7 -3
  78. package/types/src/rpc-inputs.d.ts +23 -23
  79. package/types/src/second-factor-pages.d.ts +42 -0
  80. package/types/src/services.d.ts +4 -0
  81. package/types/src/totp.d.ts +32 -0
@@ -15,7 +15,7 @@ import { type Config, type Services } from '../services'
15
15
  import type { AuthFailure } from './failure'
16
16
  import { handoffOf, handoffRedirectOr, loginDestinationFields, readHandoff } from './handoff'
17
17
  import { methodNotAllowed, readForm, sameOrigin, stringValue } from './http'
18
- import { knownDeviceCookie, readKnownDevice } from './known-device'
18
+ import { readKnownDevice } from './known-device'
19
19
  import type { AuthEnv } from './oidc-flight'
20
20
  import { issueSession, type LoginRefusal, refuseLogin } from './sessions'
21
21
 
@@ -202,7 +202,8 @@ export async function handlePasswordLogin(
202
202
  services.repositories.passwords.clearLoginFailures(accountKey),
203
203
  deviceKey === null ? Promise.resolve() : services.repositories.passwords.clearLoginFailures(deviceKey),
204
204
  ])
205
- const session = await issueSession(request, services, ctx, {
205
+ // Only a recorded login earns a device cookie: `issueSession` sets it on its 302, after the second factor if any.
206
+ return issueSession(request, services, env, ctx, {
206
207
  principalId: lookup.principal.id,
207
208
  email: lookup.principal.email,
208
209
  authenticationMethod: 'password',
@@ -210,10 +211,8 @@ export async function handlePasswordLogin(
210
211
  reason: 'password_login',
211
212
  requestId,
212
213
  handoff,
214
+ rememberDevice: true,
213
215
  })
214
- // Only a recorded login (the 302) earns a device cookie; a 503 issued no session.
215
- if (session.status === 302) session.headers.append('Set-Cookie', await knownDeviceCookie(env, lookup.principal.id))
216
- return session
217
216
  }
218
217
 
219
218
  // A known device's attempt is already counted in its own bucket.
@@ -335,6 +334,7 @@ async function safelyCreateBootstrapPrincipal(services: Services, email: string,
335
334
  export async function handlePasswordAction(
336
335
  request: Request,
337
336
  services: Services,
337
+ env: AuthEnv,
338
338
  ctx: RequestContext,
339
339
  purpose: PasswordActionPurpose,
340
340
  requestId: string,
@@ -381,7 +381,7 @@ export async function handlePasswordAction(
381
381
  // An action that keeps an application lands on its registered origin, any other on the installation's landing
382
382
  // (`issueSession`); that application's proxy then signs the browser in through the normal handoff, which the
383
383
  // session issued here makes silent.
384
- return issueSession(request, services, ctx, {
384
+ return issueSession(request, services, env, ctx, {
385
385
  principalId: completedPrincipal.id,
386
386
  email: completedPrincipal.email,
387
387
  authenticationMethod: 'password',
@@ -10,6 +10,7 @@ import { INVITATION_ACCEPT_PATH } from '../membership'
10
10
  import { ACCOUNT_CHOICE_PATH, logoutPage, TERMINAL_ENROL_PATH } from '../password-pages'
11
11
  import { readerLocale } from '../person-locale'
12
12
  import { generateRequestId } from '../request-id'
13
+ import { SECOND_FACTOR_ENROL_PATH, SECOND_FACTOR_PATH } from '../second-factor-pages'
13
14
  import type { Services } from '../services'
14
15
  import { getSigner } from '../signing'
15
16
  import { methodNotAllowed, safeRedirect } from './http'
@@ -18,6 +19,7 @@ import { handleAccountChoice, handleLogin } from './login'
18
19
  import { handleCallback, handleOidcStart } from './oidc'
19
20
  import type { AuthEnv } from './oidc-flight'
20
21
  import { handleForgotPassword, handlePasswordAction, handlePasswordLogin } from './password'
22
+ import { handleSecondFactor, handleSecondFactorEnrolment } from './second-factor'
21
23
  import { handleLogout } from './sessions'
22
24
  import { handleTerminalCompletion, handleTerminalEnrolment, handleTerminalRelease, TERMINAL_RELEASE_PATH } from './terminals'
23
25
 
@@ -62,13 +64,13 @@ export async function handleAuth(
62
64
  return handleForgotPassword(request, services, ctx, clientAddress, requestId)
63
65
  }
64
66
  if (url.pathname === '/auth/password/enroll') {
65
- return handlePasswordAction(request, services, ctx, 'enrollment', requestId)
67
+ return handlePasswordAction(request, services, env, ctx, 'enrollment', requestId)
66
68
  }
67
69
  if (url.pathname === '/auth/password/reset') {
68
- return handlePasswordAction(request, services, ctx, 'reset', requestId)
70
+ return handlePasswordAction(request, services, env, ctx, 'reset', requestId)
69
71
  }
70
72
  if (url.pathname === INVITATION_ACCEPT_PATH) {
71
- return handleInvitation(request, services, ctx, requestId)
73
+ return handleInvitation(request, services, env, ctx, requestId)
72
74
  }
73
75
  if (url.pathname === TERMINAL_ENROL_PATH) {
74
76
  return request.method === 'GET' || request.method === 'POST' ? handleTerminalEnrolment(request, services, requestId) : methodNotAllowed()
@@ -79,6 +81,12 @@ export async function handleAuth(
79
81
  if (url.pathname === TERMINAL_RELEASE_PATH) {
80
82
  return request.method === 'GET' ? handleTerminalRelease(request, services, requestId) : methodNotAllowed()
81
83
  }
84
+ if (url.pathname === SECOND_FACTOR_PATH) {
85
+ return request.method === 'POST' ? handleSecondFactor(request, services, env, ctx, requestId) : methodNotAllowed()
86
+ }
87
+ if (url.pathname === SECOND_FACTOR_ENROL_PATH) {
88
+ return request.method === 'GET' || request.method === 'POST' ? handleSecondFactorEnrolment(request, services, requestId) : methodNotAllowed()
89
+ }
82
90
  if (url.pathname === '/auth/logout') {
83
91
  // Logging out is a state change, so it needs a method that can carry an origin check. A GET
84
92
  // stays usable — it renders the same-origin form that posts — because a cross-site
@@ -0,0 +1,114 @@
1
+ // A sign-in that proved its first factor and waits for its second. What it would open rides in a signed `__Host-` cookie
2
+ // for five minutes, like the OIDC flight: the signature proves IAM wrote it, the prefix that this browser holds it. The
3
+ // code form carries nothing of it, so a posted form names no principal and no destination.
4
+
5
+ import { z } from 'zod'
6
+ import { installationConsole, presentationFor } from '../app-presentation'
7
+ import { normalizeOrigin } from '../handoff'
8
+ import { type ChallengeProblem, secondFactorChallengePage } from '../second-factor-pages'
9
+ import type { Services } from '../services'
10
+ import { getSigner, verifyInternal } from '../signing'
11
+ import { clearCookie, readCookie, serializeCookie } from './cookies'
12
+ import type { Handoff } from './handoff'
13
+ import { endingFlightCookies } from './oidc-flight'
14
+ import type { AuthEnv } from './oidc-flight'
15
+
16
+ /** Host-only on IAM's host, outside the `__Host-px_` prefix the proxy strips upstream, so no application receives it. */
17
+ export const SECOND_FACTOR_COOKIE = '__Host-fabrika_second_factor'
18
+
19
+ /** Long enough to open an authenticator app and type a code; a sign-in that takes longer proves its first factor again. */
20
+ export const SECOND_FACTOR_CHALLENGE_TTL_SECONDS = 5 * 60
21
+
22
+ /** Audience of the challenge token — never an app id, so it passes as no access token, flight or device cookie. */
23
+ const SECOND_FACTOR_AUDIENCE = 'fabrika:iam:second-factor'
24
+
25
+ /** The login a verified code opens: what `issueSession` was given, less the request's own id. */
26
+ export interface PendingLogin {
27
+ readonly principalId: string
28
+ readonly idpSub: string | null
29
+ readonly email: string | null
30
+ readonly authenticationMethod: 'oidc' | 'password'
31
+ readonly redirect: string | null
32
+ readonly reason: string
33
+ readonly handoff: Handoff | null
34
+ /** A password login earns the known-device cookie once it is recorded. */
35
+ readonly rememberDevice: boolean
36
+ }
37
+
38
+ const handoffSchema = z.object({ app: z.string(), returnUrl: z.string(), state: z.string(), challenge: z.string() })
39
+ const pendingSchema = z.object({
40
+ sub: z.string().min(1),
41
+ idp: z.string().nullable(),
42
+ em: z.string().nullable(),
43
+ am: z.enum(['oidc', 'password']),
44
+ rd: z.string().nullable(),
45
+ rs: z.string(),
46
+ ho: handoffSchema.nullable(),
47
+ dv: z.boolean(),
48
+ })
49
+
50
+ /** The pending login the request's challenge cookie proves, or null when it is absent, forged, expired or malformed. */
51
+ export async function readPendingLogin(env: AuthEnv, request: Request): Promise<PendingLogin | null> {
52
+ const raw = readCookie(request.headers.get('cookie'), SECOND_FACTOR_COOKIE)
53
+ if (raw === null || raw === '') return null
54
+ const parsed = pendingSchema.safeParse(await verifyInternal(await getSigner(env), raw, SECOND_FACTOR_AUDIENCE))
55
+ if (!parsed.success) return null
56
+ const { sub, idp, em, am, rd, rs, ho, dv } = parsed.data
57
+ return { principalId: sub, idpSub: idp, email: em, authenticationMethod: am, redirect: rd, reason: rs, handoff: ho, rememberDevice: dv }
58
+ }
59
+
60
+ /**
61
+ * Answer a first factor with the code form and the cookie that holds the pending login. An OIDC flight is spent here,
62
+ * as on every other end of its callback.
63
+ */
64
+ export async function challengeSecondFactor(services: Services, env: AuthEnv, request: Request, pending: PendingLogin): Promise<Response> {
65
+ const token = await (await getSigner(env)).signInternal(
66
+ {
67
+ sub: pending.principalId,
68
+ idp: pending.idpSub,
69
+ em: pending.email,
70
+ am: pending.authenticationMethod,
71
+ rd: pending.redirect,
72
+ rs: pending.reason,
73
+ ho: pending.handoff,
74
+ dv: pending.rememberDevice,
75
+ },
76
+ SECOND_FACTOR_AUDIENCE,
77
+ SECOND_FACTOR_CHALLENGE_TTL_SECONDS,
78
+ )
79
+ const response = await challengePage(services, request, pending)
80
+ response.headers.append(
81
+ 'Set-Cookie',
82
+ serializeCookie(SECOND_FACTOR_COOKIE, token, {
83
+ httpOnly: true,
84
+ secure: true,
85
+ sameSite: 'Lax',
86
+ maxAge: SECOND_FACTOR_CHALLENGE_TTL_SECONDS,
87
+ path: '/',
88
+ }),
89
+ )
90
+ if (pending.authenticationMethod === 'oidc') {
91
+ for (const cookie of endingFlightCookies()) response.headers.append('Set-Cookie', cookie)
92
+ }
93
+ return response
94
+ }
95
+
96
+ /**
97
+ * The code form for `pending`, again with `problem`. Its `form-action` admits the one origin the verified login lands
98
+ * on: the handoff's registered origin, the IAM-chosen landing, or the console for a login with no destination.
99
+ */
100
+ export async function challengePage(services: Services, request: Request, pending: PendingLogin, problem?: ChallengeProblem): Promise<Response> {
101
+ const presentation = await presentationFor(services, pending.handoff?.app ?? null, { request })
102
+ const destination = pending.handoff?.returnUrl ?? pending.redirect ?? await installationConsole(services)
103
+ const origin = destination === null ? null : normalizeOrigin(destination)
104
+ return secondFactorChallengePage({
105
+ presentation,
106
+ ...(origin === null ? {} : { redirectOrigin: origin }),
107
+ ...(problem === undefined ? {} : { problem }),
108
+ })
109
+ }
110
+
111
+ /** The `Set-Cookie` that spends the challenge. */
112
+ export function endingChallengeCookie(): string {
113
+ return clearCookie(SECOND_FACTOR_COOKIE, { path: '/' })
114
+ }
@@ -0,0 +1,276 @@
1
+ // The second factor: verifying the code of a sign-in that proved its first factor, and enrolling an authenticator app.
2
+ // A TOTP secret is sealed under `FABRIKA_IAM_DATA_KEY` (`src/data-key.ts`); recovery codes are stored as hashes only.
3
+
4
+ import { IAM_APP } from '../admin/router'
5
+ import { type AppPresentation, INSTALLATION_PRESENTATION, installationLanding } from '../app-presentation'
6
+ import { openValue, sealValue } from '../data-key'
7
+ import type { AuditEventInput, PrincipalRow } from '../db'
8
+ import type { RequestContext } from '../env'
9
+ import { installationBrand } from '../installation-brand'
10
+ import { logError } from '../log'
11
+ import { authFailurePage } from '../password-pages'
12
+ import { readerLocale } from '../person-locale'
13
+ import { sealedValueOf } from '../repositories/second-factors'
14
+ import { unixNow } from '../repositories/sql'
15
+ import {
16
+ type EnrolPageBase,
17
+ recoveryCodesPage,
18
+ SECOND_FACTOR_ENROL_PATH,
19
+ secondFactorEnrolledPage,
20
+ secondFactorEnrolPage,
21
+ secondFactorIntroPage,
22
+ secondFactorUnavailablePage,
23
+ } from '../second-factor-pages'
24
+ import { hashToken } from '../secret'
25
+ import type { Services } from '../services'
26
+ import {
27
+ base32,
28
+ generateRecoveryCodes,
29
+ generateTotpSecret,
30
+ matchingStep,
31
+ otpauthUri,
32
+ parseRecoveryCode,
33
+ parseTotpCode,
34
+ qrCodeDataUri,
35
+ recoveryCodeHash,
36
+ } from '../totp'
37
+ import { readForm, redirectHeaders, sameOrigin, stringValue } from './http'
38
+ import type { AuthEnv } from './oidc-flight'
39
+ import { challengePage, type PendingLogin, readPendingLogin } from './second-factor-challenge'
40
+ import { administersIam, type CurrentLogin, currentLogin, issueSession, refuseLogin } from './sessions'
41
+
42
+ /** Codes one account may try in a window before the next waits out the block: a burst, not a person mistyping. */
43
+ export const SECOND_FACTOR_MAX_ATTEMPTS = 5
44
+ const SECOND_FACTOR_WINDOW_SECONDS = 15 * 60
45
+ const SECOND_FACTOR_BLOCK_SECONDS = 15 * 60
46
+
47
+ /**
48
+ * The code form's POST. The pending login comes from the challenge cookie only. Each attempt is counted per account
49
+ * before the code is checked, from the row the counting statement returns, so a parallel burst gets no more than
50
+ * `SECOND_FACTOR_MAX_ATTEMPTS` checks; the attempt that starts a block writes `iam.second_factor.throttle` to the
51
+ * audit log. Every refusal writes its `auth_log` row; an accepted code opens the login through `issueSession`.
52
+ */
53
+ export async function handleSecondFactor(
54
+ request: Request,
55
+ services: Services,
56
+ env: AuthEnv,
57
+ ctx: RequestContext,
58
+ requestId: string,
59
+ ): Promise<Response> {
60
+ const readerFailure = (): AppPresentation => ({ ...INSTALLATION_PRESENTATION, locale: readerLocale(request) })
61
+ if (!sameOrigin(request, services.config)) {
62
+ return refuseLogin(
63
+ services,
64
+ request,
65
+ { requestId, principalId: null, reason: 'login_cross_origin' },
66
+ () => authFailurePage(readerFailure(), { kind: 'cross_origin' }, 403),
67
+ )
68
+ }
69
+ const pending = await readPendingLogin(env, request)
70
+ if (pending === null) {
71
+ return refuseLogin(
72
+ services,
73
+ request,
74
+ { requestId, principalId: null, reason: 'second_factor_expired' },
75
+ () => authFailurePage(readerFailure(), { kind: 'second_factor_expired' }, 400),
76
+ )
77
+ }
78
+ // The held login is up to five minutes old: a principal disabled, or a method switched off, since then signs in no more.
79
+ const principal = await services.repositories.principals.getPrincipalById(pending.principalId)
80
+ const methodEnabled = pending.authenticationMethod === 'oidc'
81
+ ? services.config.authentication.oidc.enabled
82
+ : services.config.authentication.password.enabled
83
+ if (principal === null || principal.disabled_at !== null || !methodEnabled) {
84
+ return refuseLogin(
85
+ services,
86
+ request,
87
+ { requestId, principalId: principal === null ? null : pending.principalId, reason: 'second_factor_expired' },
88
+ () => authFailurePage(readerFailure(), { kind: 'second_factor_expired' }, 400),
89
+ )
90
+ }
91
+ const form = await readForm(request)
92
+ const submitted = stringValue(form?.get('code') ?? null) ?? ''
93
+ const refuse = (reason: 'second_factor_invalid' | 'second_factor_throttled', problem: 'invalid' | 'throttled' | 'app_codes_unavailable') =>
94
+ refuseLogin(services, request, { requestId, principalId: pending.principalId, reason }, () => challengePage(services, request, pending, problem))
95
+
96
+ const attempt = await countAttempt(services, pending.principalId, requestId)
97
+ if (attempt === 'blocked') return refuse('second_factor_throttled', 'throttled')
98
+
99
+ const outcome = await verifySecondFactor(services, pending, submitted, requestId)
100
+ if (outcome === 'app_codes_unavailable') return refuse('second_factor_invalid', 'app_codes_unavailable')
101
+ if (outcome === 'invalid') return refuse('second_factor_invalid', 'invalid')
102
+
103
+ await services.repositories.passwords.clearLoginFailures(await attemptKey(pending.principalId))
104
+ return issueSession(request, services, env, ctx, {
105
+ principalId: pending.principalId,
106
+ idpSub: pending.idpSub,
107
+ email: pending.email,
108
+ authenticationMethod: pending.authenticationMethod,
109
+ redirect: pending.redirect,
110
+ reason: pending.reason,
111
+ requestId,
112
+ handoff: pending.handoff,
113
+ rememberDevice: pending.rememberDevice,
114
+ secondFactor: 'verified',
115
+ })
116
+ }
117
+
118
+ function attemptKey(principalId: string): Promise<string> {
119
+ return hashToken(`second-factor:account:${principalId}`)
120
+ }
121
+
122
+ /**
123
+ * Count one attempt and decide from the row the counting statement returns. The attempt that turns the bucket from
124
+ * open to blocked records the burst; the ones refused after it do not, so a burst is one audit row.
125
+ */
126
+ async function countAttempt(services: Services, principalId: string, requestId: string): Promise<'admitted' | 'blocked'> {
127
+ const key = await attemptKey(principalId)
128
+ const now = unixNow()
129
+ const before = await services.repositories.passwords.getLoginThrottle(key)
130
+ const row = await services.repositories.passwords.recordLoginFailure({
131
+ loginKeyHash: key,
132
+ windowSeconds: SECOND_FACTOR_WINDOW_SECONDS,
133
+ // The attempt that reaches the limit is the first one refused, so the limit is one past the admitted attempts.
134
+ maxAttempts: SECOND_FACTOR_MAX_ATTEMPTS + 1,
135
+ blockSeconds: SECOND_FACTOR_BLOCK_SECONDS,
136
+ })
137
+ if ((row.blocked_until ?? 0) <= now) return 'admitted'
138
+ if ((before?.blocked_until ?? 0) <= now) {
139
+ await services.repositories.audit.writeAuditEvent(selfEvent(requestId, principalId, 'iam.second_factor.throttle', {
140
+ attempts: SECOND_FACTOR_MAX_ATTEMPTS,
141
+ blockedUntil: row.blocked_until,
142
+ }))
143
+ }
144
+ return 'blocked'
145
+ }
146
+
147
+ /**
148
+ * A six-digit code is checked against the sealed secret and accepted once per time step; anything shaped like a
149
+ * recovery code spends one. A code the data key cannot check (unset, or a key that does not open the secret) is
150
+ * `app_codes_unavailable`, so a recovery code still signs the person in.
151
+ */
152
+ async function verifySecondFactor(
153
+ services: Services,
154
+ pending: PendingLogin,
155
+ submitted: string,
156
+ requestId: string,
157
+ ): Promise<'verified' | 'invalid' | 'app_codes_unavailable'> {
158
+ const code = parseTotpCode(submitted)
159
+ if (code !== null) {
160
+ const factor = await services.repositories.secondFactors.get(pending.principalId)
161
+ if (factor === null || factor.confirmed_at === null) return 'invalid'
162
+ if (services.dataKey === null) return 'app_codes_unavailable'
163
+ let secret: Uint8Array<ArrayBuffer>
164
+ try {
165
+ secret = await openValue(services.dataKey, pending.principalId, sealedValueOf(factor))
166
+ } catch (err) {
167
+ logError(`the authenticator of request '${requestId}' could not be opened with FABRIKA_IAM_DATA_KEY`, err)
168
+ return 'app_codes_unavailable'
169
+ }
170
+ const step = await matchingStep(secret, code, unixNow(), factor.last_step)
171
+ if (step === null) return 'invalid'
172
+ return await services.repositories.secondFactors.acceptStep(pending.principalId, step) ? 'verified' : 'invalid'
173
+ }
174
+ if (parseRecoveryCode(submitted) !== null) {
175
+ const spent = await services.repositories.secondFactors.spendRecoveryCode(
176
+ pending.principalId,
177
+ await recoveryCodeHash(pending.principalId, submitted),
178
+ selfEvent(requestId, pending.principalId, 'iam.second_factor.recovery_code.use'),
179
+ )
180
+ return spent ? 'verified' : 'invalid'
181
+ }
182
+ return 'invalid'
183
+ }
184
+
185
+ /**
186
+ * Enrolment, on IAM's host, for a signed-in principal that administers (`administersIam`). `GET` shows the state;
187
+ * `POST step=start` seals a new secret that waits for its first code and shows it; `POST step=confirm` checks that
188
+ * code, confirms the factor, replaces the recovery codes and records `iam.second_factor.enrol` in one transaction, and
189
+ * shows the codes once. A confirmed factor is never replaced here: only an administrator's reset removes it.
190
+ */
191
+ export async function handleSecondFactorEnrolment(request: Request, services: Services, requestId: string): Promise<Response> {
192
+ const locale = readerLocale(request)
193
+ const readerFailure: AppPresentation = { ...INSTALLATION_PRESENTATION, locale }
194
+ if (request.method === 'POST' && !sameOrigin(request, services.config)) {
195
+ return authFailurePage(readerFailure, { kind: 'cross_origin' }, 403)
196
+ }
197
+ const login = await currentLogin(request, services)
198
+ if (login === null) {
199
+ if (request.method === 'POST') return authFailurePage(readerFailure, { kind: 'second_factor_not_allowed' }, 403)
200
+ const back = new URL(SECOND_FACTOR_ENROL_PATH, services.config.issuer).toString()
201
+ return new Response(null, { status: 302, headers: redirectHeaders(`/auth/login?redirect=${encodeURIComponent(back)}`) })
202
+ }
203
+ if (!await administersIam(services, login.principal.id)) {
204
+ return authFailurePage(readerFailure, { kind: 'second_factor_not_allowed' }, 403)
205
+ }
206
+ const brand = await installationBrand(services)
207
+ const page = { brand, locale }
208
+ const status = await services.repositories.secondFactors.status(login.principal.id)
209
+ if (status.confirmedAt !== null) {
210
+ return secondFactorEnrolledPage({ ...page, confirmedAt: status.confirmedAt, recoveryCodesLeft: status.recoveryCodesLeft })
211
+ }
212
+ const dataKey = services.dataKey
213
+ if (dataKey === null) return secondFactorUnavailablePage(page)
214
+ if (request.method === 'GET') return secondFactorIntroPage(page)
215
+
216
+ const form = await readForm(request)
217
+ const step = stringValue(form?.get('step') ?? null)
218
+ if (step === 'start') {
219
+ const secret = generateTotpSecret()
220
+ if (!await services.repositories.secondFactors.begin(login.principal.id, await sealValue(dataKey, login.principal.id, secret))) {
221
+ return authFailurePage(readerFailure, { kind: 'second_factor_unavailable' }, 409)
222
+ }
223
+ return enrolPage(services, login, secret, page)
224
+ }
225
+ if (step !== 'confirm') return authFailurePage(readerFailure, { kind: 'malformed_form' }, 400)
226
+
227
+ const factor = await services.repositories.secondFactors.get(login.principal.id)
228
+ if (factor === null) return secondFactorIntroPage(page)
229
+ let secret: Uint8Array<ArrayBuffer>
230
+ try {
231
+ secret = await openValue(dataKey, login.principal.id, sealedValueOf(factor))
232
+ } catch (err) {
233
+ logError(`a waiting authenticator could not be opened for request '${requestId}'`, err)
234
+ return authFailurePage(readerFailure, { kind: 'second_factor_unavailable' }, 503)
235
+ }
236
+ const code = parseTotpCode(stringValue(form?.get('code') ?? null) ?? '')
237
+ const matched = code === null ? null : await matchingStep(secret, code, unixNow(), null)
238
+ if (matched === null) return enrolPage(services, login, secret, page, true)
239
+
240
+ const codes = generateRecoveryCodes()
241
+ const confirmed = await services.repositories.secondFactors.confirm(
242
+ {
243
+ principalId: login.principal.id,
244
+ ciphertext: factor.ciphertext,
245
+ step: matched,
246
+ recoveryCodeHashes: await Promise.all(codes.map((recovery) => recoveryCodeHash(login.principal.id, recovery))),
247
+ },
248
+ selfEvent(requestId, login.principal.id, 'iam.second_factor.enrol', { recoveryCodes: codes.length }),
249
+ )
250
+ if (!confirmed) return authFailurePage(readerFailure, { kind: 'second_factor_unavailable' }, 409)
251
+ return recoveryCodesPage({ ...page, codes, landing: await installationLanding(services) })
252
+ }
253
+
254
+ function enrolPage(services: Services, login: CurrentLogin, secret: Uint8Array<ArrayBuffer>, page: EnrolPageBase, invalidCode?: boolean): Response {
255
+ const uri = otpauthUri({ issuer: new URL(services.config.issuer).hostname, account: accountName(login.principal), secret })
256
+ return secondFactorEnrolPage({ ...page, qrCode: qrCodeDataUri(uri), key: base32(secret), ...(invalidCode === true ? { invalidCode } : {}) })
257
+ }
258
+
259
+ /** What the authenticator app lists the entry as: the person's sign-in address, as the person knows it. */
260
+ function accountName(principal: PrincipalRow): string {
261
+ return principal.label ?? principal.email ?? principal.id
262
+ }
263
+
264
+ /** A principal's own change to its second factor: by it, about it, with no email in it. */
265
+ function selfEvent(requestId: string, principalId: string, action: string, metadata?: unknown): AuditEventInput {
266
+ return {
267
+ requestId,
268
+ principalId,
269
+ principalLabel: principalId,
270
+ app: IAM_APP,
271
+ action,
272
+ resourceType: 'principal',
273
+ resourceId: principalId,
274
+ ...(metadata === undefined ? {} : { metadata }),
275
+ }
276
+ }
@@ -17,7 +17,9 @@ import { type Handoff, handoffLocation } from './handoff'
17
17
  import { authFailurePage } from '../password-pages'
18
18
  import { redirectHeaders, safeRedirect, sameOrigin } from './http'
19
19
 
20
- import { endingFlightCookies } from './oidc-flight'
20
+ import { knownDeviceCookie } from './known-device'
21
+ import { type AuthEnv, endingFlightCookies } from './oidc-flight'
22
+ import { challengeSecondFactor, endingChallengeCookie } from './second-factor-challenge'
21
23
 
22
24
  /** SSO session lifetime — the long-lived credential a browser carries (30 days). */
23
25
  const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
@@ -37,7 +39,7 @@ export async function currentSession(request: Request, services: Services) {
37
39
  return null
38
40
  }
39
41
  // And a session whose method is no longer enabled must not silently father a handoff.
40
- return sessionUsable(session, services.config) ? session : null
42
+ return sessionUsable(session, services.config, Math.floor(Date.now() / 1000)) ? session : null
41
43
  }
42
44
 
43
45
  /** A login a handoff may continue: the browser's IAM session and its principal, an active user. */
@@ -55,32 +57,72 @@ export async function currentLogin(request: Request, services: Services): Promis
55
57
  return { session, principal }
56
58
  }
57
59
 
60
+ /** A login a proven first factor opens. */
61
+ export interface LoginInput {
62
+ principalId: string
63
+ idpSub?: string | null
64
+ email?: string | null
65
+ authenticationMethod?: AuthenticationMethod
66
+ /** Where the login lands; null for no destination of its own, which is the installation's landing. */
67
+ redirect: string | null
68
+ reason: string
69
+ /** The correlation id the composition root allowed; see `src/request-id.ts`. */
70
+ requestId: string
71
+ clearOidc?: boolean
72
+ /** When set, land on the app's callback with a code instead of on `redirect` (ADR-0022). */
73
+ handoff?: Handoff | null
74
+ /** Set the known-device cookie once the login is recorded: a password login's (`auth/known-device.ts`). */
75
+ rememberDevice?: boolean
76
+ /** Set only by the second-factor form, after the principal's code or recovery code was accepted. */
77
+ secondFactor?: 'verified'
78
+ }
79
+
58
80
  /**
59
81
  * Open a login: the session and its `auth_log` row are written in one batch, before the answer. A login that cannot
60
82
  * be logged opens no session and answers 503. A principal that administers at IAM, the installation or the people of
61
83
  * an application (ADR-0058), is logged `privileged`.
84
+ *
85
+ * A principal with a confirmed second factor gets no session here until its code is verified: the answer is the code
86
+ * form and a challenge cookie holding this login (`second-factor-challenge.ts`). Every password, OIDC, password-action
87
+ * and invitation login passes through here, so none skips the factor; only the local-dev bypass does, which no
88
+ * installation outside `ENVIRONMENT=local` serves. A terminal's assertion (`identification.ts`) opens no session here
89
+ * and asks no factor: it reaches only the asserting application, never IAM's administration.
62
90
  */
63
91
  export async function issueSession(
64
92
  request: Request,
65
93
  services: Services,
94
+ env: AuthEnv,
66
95
  ctx: RequestContext,
67
- input: {
68
- principalId: string
69
- idpSub?: string | null
70
- email?: string | null
71
- authenticationMethod?: AuthenticationMethod
72
- /** Where the login lands; null for no destination of its own, which is the installation's landing. */
73
- redirect: string | null
74
- reason: string
75
- /** The correlation id the composition root allowed; see `src/request-id.ts`. */
76
- requestId: string
77
- clearOidc?: boolean
78
- /** When set, land on the app's callback with a code instead of on `redirect` (ADR-0022). */
79
- handoff?: Handoff | null
80
- },
96
+ input: LoginInput,
81
97
  ): Promise<Response> {
98
+ const method = input.authenticationMethod ?? 'oidc'
99
+ if (input.secondFactor !== 'verified' && (method === 'oidc' || method === 'password')) {
100
+ let required: boolean
101
+ try {
102
+ required = await services.repositories.secondFactors.isConfirmed(input.principalId)
103
+ } catch (err) {
104
+ logError(`the second factor of login for request '${input.requestId}' could not be read`, err)
105
+ return authFailurePage(await installationPresentation(services, { request }), { kind: 'login_unavailable' }, 503)
106
+ }
107
+ if (required) {
108
+ return challengeSecondFactor(services, env, request, {
109
+ principalId: input.principalId,
110
+ idpSub: input.idpSub ?? null,
111
+ email: input.email ?? null,
112
+ authenticationMethod: method,
113
+ redirect: input.redirect,
114
+ reason: input.reason,
115
+ handoff: input.handoff ?? null,
116
+ rememberDevice: input.rememberDevice === true,
117
+ })
118
+ }
119
+ }
82
120
  const sessionToken = randomToken(32)
83
- const expiresAt = Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS
121
+ // An OIDC login stores the installation's cap as its expiry, so its app sessions, OAuth grants and cookie end with it.
122
+ const lifetime = (input.authenticationMethod ?? 'oidc') === 'oidc'
123
+ ? Math.min(SESSION_TTL_SECONDS, services.config.authentication.oidc.sessionCapSeconds)
124
+ : SESSION_TTL_SECONDS
125
+ const expiresAt = Math.floor(Date.now() / 1000) + lifetime
84
126
  let sessionId: string
85
127
  try {
86
128
  sessionId = await services.repositories.sessions.createSession({
@@ -110,7 +152,7 @@ export async function issueSession(
110
152
  ? input.redirect ?? await installationLanding(services)
111
153
  : await handoffLocation(services, input.handoff, sessionId)
112
154
  const headers = redirectHeaders(location)
113
- headers.append('Set-Cookie', sessionCookie(sessionToken))
155
+ headers.append('Set-Cookie', sessionCookie(sessionToken, lifetime))
114
156
  // A person with a language of their own keeps it on this browser's next sign-in page here (`LOCALE_COOKIE`); one
115
157
  // without clears the language a previous person left on a shared browser.
116
158
  // The session has committed and the cookie picks words only: a failed read leaves the remembered language as it is.
@@ -129,6 +171,12 @@ export async function issueSession(
129
171
  headers.append('Set-Cookie', cookie)
130
172
  }
131
173
  }
174
+ if (input.secondFactor === 'verified') {
175
+ headers.append('Set-Cookie', endingChallengeCookie())
176
+ }
177
+ if (input.rememberDevice === true) {
178
+ headers.append('Set-Cookie', await knownDeviceCookie(env, input.principalId))
179
+ }
132
180
  return new Response(null, { status: 302, headers })
133
181
  }
134
182
 
@@ -151,6 +199,9 @@ export type LoginRefusal =
151
199
  | 'oidc_unknown_principal'
152
200
  | 'oidc_external_principal'
153
201
  | 'local_login_refused'
202
+ | 'second_factor_invalid'
203
+ | 'second_factor_throttled'
204
+ | 'second_factor_expired'
154
205
 
155
206
  export async function refuseLogin(
156
207
  services: Services,
@@ -236,14 +287,14 @@ export function signedOutRedirect(location: string): Response {
236
287
  * TLS-TERMINATING BALANCER (the socket is plain HTTP, the browser spoke HTTPS) and over plain HTTP on
237
288
  * `localhost` / `*.localhost`, which browsers treat as potentially trustworthy. An installation
238
289
  * served over cleartext HTTP on a public hostname can hold no session at all — which is the correct
239
- * outcome for a 30-day credential, not a regression to work around.
290
+ * outcome for a credential that lasts up to 30 days, not a regression to work around.
240
291
  */
241
- function sessionCookie(value: string): string {
292
+ function sessionCookie(value: string, maxAge: number): string {
242
293
  return serializeCookie(SESSION_COOKIE, value, {
243
294
  httpOnly: true,
244
295
  secure: true,
245
296
  sameSite: 'Lax',
246
- maxAge: SESSION_TTL_SECONDS,
297
+ maxAge,
247
298
  path: '/',
248
299
  })
249
300
  }