@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
@@ -0,0 +1,165 @@
1
+ import { type SqlDatabase, uuidv7 } from '@fabrika/platform'
2
+ import type { SealedValue } from '../data-key'
3
+ import { type AuditEventInput, AuditWriter, guardedInsert } from './audit'
4
+ import { principalLockStatements } from './principals'
5
+ import { unixNow } from './sql'
6
+
7
+ /** A row of `second_factors` (migration 0032): one TOTP authenticator per principal, its secret sealed. */
8
+ export interface SecondFactorRow {
9
+ principal_id: string
10
+ ciphertext: string
11
+ value_iv: string
12
+ wrapped_dek: string
13
+ dek_iv: string
14
+ created_at: number
15
+ /** NULL while the enrolment waits for its first valid code. Only a confirmed factor is asked for at sign-in. */
16
+ confirmed_at: number | null
17
+ /** The time step of the last accepted code; a code of that step or an earlier one is never accepted again. */
18
+ last_step: number | null
19
+ /** The confirmation that wrote the recovery codes; NULL until one did. */
20
+ confirmation_id: string | null
21
+ }
22
+
23
+ /** What an administrator sees of a principal's second factor. */
24
+ export interface SecondFactorStatus {
25
+ readonly confirmedAt: number | null
26
+ readonly recoveryCodesLeft: number
27
+ }
28
+
29
+ export function sealedValueOf(row: SecondFactorRow): SealedValue {
30
+ return { ciphertext: row.ciphertext, valueIv: row.value_iv, wrappedDek: row.wrapped_dek, dekIv: row.dek_iv }
31
+ }
32
+
33
+ /**
34
+ * A person's TOTP authenticator and recovery codes. Every write that touches more than one of a principal's rows locks
35
+ * the principal row first on Postgres (`principalLockStatements`), the order every writer of a principal's rows keeps.
36
+ */
37
+ export class SecondFactorRepository {
38
+ constructor(
39
+ protected readonly db: SqlDatabase,
40
+ private readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
41
+ ) {}
42
+
43
+ async get(principalId: string): Promise<SecondFactorRow | null> {
44
+ return this.db.prepare('SELECT * FROM second_factors WHERE principal_id = ?').bind(principalId).first<SecondFactorRow>()
45
+ }
46
+
47
+ /** Whether a sign-in of the principal needs its second factor. */
48
+ async isConfirmed(principalId: string): Promise<boolean> {
49
+ const row = await this.db
50
+ .prepare('SELECT 1 AS confirmed FROM second_factors WHERE principal_id = ? AND confirmed_at IS NOT NULL')
51
+ .bind(principalId)
52
+ .first<{ confirmed: number }>()
53
+ return row !== null
54
+ }
55
+
56
+ async status(principalId: string): Promise<SecondFactorStatus> {
57
+ const [factor, codes] = await Promise.all([
58
+ this.get(principalId),
59
+ this.db
60
+ .prepare('SELECT COUNT(*) AS left_count FROM second_factor_recovery_codes WHERE principal_id = ? AND used_at IS NULL')
61
+ .bind(principalId)
62
+ .first<{ left_count: number | string }>(),
63
+ ])
64
+ const confirmedAt = factor?.confirmed_at ?? null
65
+ return { confirmedAt, recoveryCodesLeft: confirmedAt === null ? 0 : Number(codes?.left_count ?? 0) }
66
+ }
67
+
68
+ /**
69
+ * Store a new secret that waits for its first code, replacing one that still waits. A confirmed factor is never
70
+ * replaced here (false): only an administrator's reset removes it. Nothing is recorded: an unconfirmed secret asks
71
+ * nobody for anything; its confirmation is the enrolment, and that is recorded.
72
+ */
73
+ async begin(principalId: string, sealed: SealedValue): Promise<boolean> {
74
+ const row = await this.db
75
+ .prepare(`INSERT INTO second_factors (principal_id, ciphertext, value_iv, wrapped_dek, dek_iv, created_at, confirmed_at, last_step)
76
+ VALUES (?, ?, ?, ?, ?, ?, NULL, NULL)
77
+ ON CONFLICT (principal_id) DO UPDATE SET
78
+ ciphertext = excluded.ciphertext, value_iv = excluded.value_iv, wrapped_dek = excluded.wrapped_dek,
79
+ dek_iv = excluded.dek_iv, created_at = excluded.created_at, last_step = NULL
80
+ WHERE second_factors.confirmed_at IS NULL
81
+ RETURNING principal_id`)
82
+ .bind(principalId, sealed.ciphertext, sealed.valueIv, sealed.wrappedDek, sealed.dekIv, unixNow())
83
+ .first<{ principal_id: string }>()
84
+ return row !== null
85
+ }
86
+
87
+ /**
88
+ * Confirm the waiting secret whose ciphertext the caller checked the code against, with its record, and replace the
89
+ * principal's recovery codes with `recoveryCodeHashes`, in one transaction. The codes are written only when the
90
+ * confirmation changed the row, so a secret replaced in between confirms nothing (false) and issues no code. The guard
91
+ * reads this attempt's own `confirmation_id`, never the timestamp: a second confirmation in the same second must not
92
+ * replace the codes the first one showed.
93
+ */
94
+ async confirm(
95
+ input: { principalId: string; ciphertext: string; step: number; recoveryCodeHashes: readonly string[] },
96
+ audit: AuditEventInput,
97
+ ): Promise<boolean> {
98
+ const now = unixNow()
99
+ const confirmationId = uuidv7()
100
+ const { principalId } = input
101
+ const lock = principalLockStatements(this.db, this.writer.dialect, { sql: '?', binds: [principalId] })
102
+ const confirmation = this.writer.changed([{
103
+ sql: `UPDATE second_factors SET confirmed_at = ?, last_step = ?, confirmation_id = ?
104
+ WHERE principal_id = ? AND confirmed_at IS NULL AND ciphertext = ? RETURNING principal_id`,
105
+ binds: [now, input.step, confirmationId, principalId, input.ciphertext],
106
+ }], audit)
107
+ const guard = {
108
+ sql: 'SELECT 1 FROM second_factors WHERE principal_id = ? AND confirmation_id = ?',
109
+ binds: [principalId, confirmationId],
110
+ }
111
+ const replaced = this.db
112
+ .prepare(`DELETE FROM second_factor_recovery_codes WHERE principal_id = ? AND EXISTS (${guard.sql})`)
113
+ .bind(principalId, ...guard.binds)
114
+ const codes = input.recoveryCodeHashes.map((hash) => {
115
+ const insert = guardedInsert('second_factor_recovery_codes (code_hash, principal_id, created_at, used_at)', '?, ?, ?, NULL', [
116
+ hash,
117
+ principalId,
118
+ now,
119
+ ], guard)
120
+ return this.db.prepare(insert.sql).bind(...insert.binds)
121
+ })
122
+ const results = await this.db.batch([...lock, ...confirmation.statements, replaced, ...codes])
123
+ return confirmation.rows(results, lock.length).length > 0
124
+ }
125
+
126
+ /**
127
+ * Accept a code of `step` for a confirmed factor: true only when no code of this step or a later one was accepted
128
+ * before. The guard is the statement itself, so two submissions of one code accept it once.
129
+ */
130
+ async acceptStep(principalId: string, step: number): Promise<boolean> {
131
+ const row = await this.db
132
+ .prepare(`UPDATE second_factors SET last_step = ?
133
+ WHERE principal_id = ? AND confirmed_at IS NOT NULL AND (last_step IS NULL OR last_step < ?) RETURNING principal_id`)
134
+ .bind(step, principalId, step)
135
+ .first<{ principal_id: string }>()
136
+ return row !== null
137
+ }
138
+
139
+ /** Spend one unused recovery code of a confirmed factor, with its record; false when the code is not one. */
140
+ async spendRecoveryCode(principalId: string, codeHash: string, audit: AuditEventInput): Promise<boolean> {
141
+ const rows = await this.writer.run([{
142
+ sql: `UPDATE second_factor_recovery_codes SET used_at = ?
143
+ WHERE code_hash = ? AND principal_id = ? AND used_at IS NULL
144
+ AND EXISTS (SELECT 1 FROM second_factors WHERE principal_id = ? AND confirmed_at IS NOT NULL)
145
+ RETURNING code_hash`,
146
+ binds: [unixNow(), codeHash, principalId, principalId],
147
+ }], audit)
148
+ return rows.length > 0
149
+ }
150
+
151
+ /**
152
+ * Remove the principal's authenticator and recovery codes, with one record, so its next sign-in asks for no second
153
+ * factor and it may enrol again. False when it had neither, and nothing is recorded.
154
+ */
155
+ async reset(principalId: string, audit: AuditEventInput): Promise<boolean> {
156
+ const lock = principalLockStatements(this.db, this.writer.dialect, { sql: '?', binds: [principalId] })
157
+ const removal = this.writer.changed([
158
+ { sql: 'DELETE FROM second_factor_recovery_codes WHERE principal_id = ? RETURNING code_hash', binds: [principalId] },
159
+ { sql: 'DELETE FROM second_factors WHERE principal_id = ? RETURNING principal_id', binds: [principalId] },
160
+ ], audit)
161
+ const results = await this.db.batch([...lock, ...removal.statements])
162
+ // The record is written when either delete removed a row; the answer says whether an authenticator was removed.
163
+ return removal.rows(results, lock.length).length > 0
164
+ }
165
+ }
@@ -36,7 +36,12 @@ export interface SessionRow {
36
36
  terminal_generation: number | null
37
37
  }
38
38
 
39
- export interface ListedSessionRow extends SessionRow {
39
+ /** A session as a lookup returns it: with the time its login signed in, the parent's for a child session. */
40
+ export interface SignedInSessionRow extends SessionRow {
41
+ signed_in_at: number
42
+ }
43
+
44
+ export interface ListedSessionRow extends SignedInSessionRow {
40
45
  parent_expires_at: number | null
41
46
  parent_revoked_at: number | null
42
47
  }
@@ -80,6 +85,9 @@ const SUBJECTLESS_METHODS: readonly AuthenticationMethod[] = ['password', 'termi
80
85
  const TERMINAL_ENROLLED = `AND (COALESCE(s.terminal_id, p.terminal_id) IS NULL
81
86
  OR (t.principal_id IS NOT NULL AND t.revoked_at IS NULL AND t.generation = COALESCE(s.terminal_generation, p.terminal_generation)))`
82
87
 
88
+ /** When the login of `s` signed in: its parent's creation for a child session (`p`), its own for a login. */
89
+ const SIGNED_IN_AT = 'COALESCE(p.created_at, s.created_at) AS signed_in_at'
90
+
83
91
  export class SessionRepository {
84
92
  constructor(
85
93
  protected readonly db: SqlDatabase,
@@ -162,34 +170,34 @@ export class SessionRepository {
162
170
  * A session on a terminal is valid only while that terminal is enrolled, and so is a child whose parent is on one: a
163
171
  * revoked terminal ends them at once, with no sweep (ADR-0067).
164
172
  */
165
- async getActiveSessionByHash(tokenHash: string): Promise<SessionRow | null> {
173
+ async getActiveSessionByHash(tokenHash: string): Promise<SignedInSessionRow | null> {
166
174
  const now = unixNow()
167
175
  return this.db
168
- .prepare(`SELECT s.* FROM sessions s
176
+ .prepare(`SELECT s.*, ${SIGNED_IN_AT} FROM sessions s
169
177
  LEFT JOIN sessions p ON p.id = s.parent_session_id
170
178
  LEFT JOIN terminals t ON t.principal_id = COALESCE(s.terminal_id, p.terminal_id)
171
179
  WHERE s.token_hash = ? AND s.revoked_at IS NULL AND s.expires_at > ?
172
180
  AND (s.parent_session_id IS NULL OR (p.revoked_at IS NULL AND p.expires_at > ?))
173
181
  ${TERMINAL_ENROLLED}`)
174
182
  .bind(tokenHash, now, now)
175
- .first<SessionRow>()
183
+ .first<SignedInSessionRow>()
176
184
  }
177
185
 
178
186
  /**
179
187
  * The same validity rule as `getActiveSessionByHash`, addressed by id — how a handoff code reaches
180
188
  * the login it was issued against, which it holds by id rather than by a hash it must not store.
181
189
  */
182
- async getActiveSessionById(id: string): Promise<SessionRow | null> {
190
+ async getActiveSessionById(id: string): Promise<SignedInSessionRow | null> {
183
191
  const now = unixNow()
184
192
  return this.db
185
- .prepare(`SELECT s.* FROM sessions s
193
+ .prepare(`SELECT s.*, ${SIGNED_IN_AT} FROM sessions s
186
194
  LEFT JOIN sessions p ON p.id = s.parent_session_id
187
195
  LEFT JOIN terminals t ON t.principal_id = COALESCE(s.terminal_id, p.terminal_id)
188
196
  WHERE s.id = ? AND s.revoked_at IS NULL AND s.expires_at > ?
189
197
  AND (s.parent_session_id IS NULL OR (p.revoked_at IS NULL AND p.expires_at > ?))
190
198
  ${TERMINAL_ENROLLED}`)
191
199
  .bind(id, now, now)
192
- .first<SessionRow>()
200
+ .first<SignedInSessionRow>()
193
201
  }
194
202
 
195
203
  /**
@@ -268,7 +276,7 @@ export class SessionRepository {
268
276
  const where = options.before === undefined ? '' : ' AND s.id < ?'
269
277
  const bindings = options.before === undefined ? [principalId, options.limit] : [principalId, options.before, options.limit]
270
278
  const { results } = await this.db
271
- .prepare(`SELECT s.*, p.expires_at AS parent_expires_at, p.revoked_at AS parent_revoked_at FROM sessions s
279
+ .prepare(`SELECT s.*, ${SIGNED_IN_AT}, p.expires_at AS parent_expires_at, p.revoked_at AS parent_revoked_at FROM sessions s
272
280
  LEFT JOIN sessions p ON p.id = s.parent_session_id
273
281
  WHERE s.principal_id = ?${where}${options.signInsOnly ? ' AND s.parent_session_id IS NULL' : ''} ORDER BY s.id DESC LIMIT ?`)
274
282
  .bind(...bindings)
@@ -278,7 +286,7 @@ export class SessionRepository {
278
286
 
279
287
  async listChildren(parentIds: string[]): Promise<ListedSessionRow[]> {
280
288
  if (parentIds.length === 0) return []
281
- const { results } = await this.db.prepare(`SELECT s.*, p.expires_at AS parent_expires_at, p.revoked_at AS parent_revoked_at
289
+ const { results } = await this.db.prepare(`SELECT s.*, ${SIGNED_IN_AT}, p.expires_at AS parent_expires_at, p.revoked_at AS parent_revoked_at
282
290
  FROM sessions s JOIN sessions p ON p.id = s.parent_session_id
283
291
  WHERE s.parent_session_id IN (${parentIds.map(() => '?').join(', ')}) ORDER BY s.id DESC`).bind(...parentIds).all<ListedSessionRow>()
284
292
  return results
@@ -0,0 +1,129 @@
1
+ import type { Locale } from '@fabrika/auth-core'
2
+ import { SECOND_FACTOR_ENROL_PATH } from '@fabrika/iam-contract'
3
+ import type { InstallationBrand } from '@fabrika/proxy-core/brand'
4
+ import { type AppPresentation, localeQuery } from './app-presentation'
5
+ import { catalogFor } from './catalog'
6
+ import { escapeHtml } from './html'
7
+ import { htmlPage } from './password-pages'
8
+
9
+ export { SECOND_FACTOR_ENROL_PATH }
10
+
11
+ /** Where a sign-in waiting for its second factor posts the code. */
12
+ export const SECOND_FACTOR_PATH = '/auth/second-factor'
13
+
14
+ /** Why the code form is shown again. */
15
+ export type ChallengeProblem = 'invalid' | 'throttled' | 'app_codes_unavailable'
16
+
17
+ /**
18
+ * The code a sign-in asks for after its first factor. The pending sign-in rides in the challenge cookie, never in the
19
+ * form. A verified code answers the login's own 302, to the handoff's registered origin, which `form-action` admits.
20
+ */
21
+ export function secondFactorChallengePage(input: {
22
+ readonly presentation: AppPresentation
23
+ readonly redirectOrigin?: string
24
+ readonly problem?: ChallengeProblem
25
+ }): Response {
26
+ const { presentation } = input
27
+ const text = catalogFor(presentation.locale).pages.secondFactor
28
+ const problem = input.problem === undefined
29
+ ? ''
30
+ : `<p role="alert" class="error">${
31
+ escapeHtml(input.problem === 'invalid' ? text.invalidCode : input.problem === 'throttled' ? text.throttled : text.appCodesUnavailable)
32
+ }</p>`
33
+ return htmlPage({
34
+ locale: presentation.locale,
35
+ brand: presentation.brand,
36
+ title: text.challengeTitle,
37
+ content: `<h1>${escapeHtml(text.challengeTitle)}</h1>${problem}<p>${escapeHtml(text.challengeText)}</p>
38
+ <form method="post" action="${escapeHtml(`${SECOND_FACTOR_PATH}${localeQuery(presentation)}`)}">
39
+ <label>${
40
+ escapeHtml(text.codeLabel)
41
+ }<input name="code" type="text" inputmode="text" autocomplete="one-time-code" autocapitalize="none" spellcheck="false" maxlength="32" required autofocus></label>
42
+ <button type="submit">${escapeHtml(text.submit)}</button>
43
+ </form>
44
+ <p><a href="${escapeHtml(`/auth/login${localeQuery(presentation)}`)}">${escapeHtml(text.startOver)}</a></p>`,
45
+ status: input.problem === undefined ? 200 : input.problem === 'throttled' ? 429 : input.problem === 'invalid' ? 401 : 503,
46
+ formActionOrigin: input.redirectOrigin,
47
+ })
48
+ }
49
+
50
+ export interface EnrolPageBase {
51
+ readonly brand: InstallationBrand | null
52
+ readonly locale: Locale
53
+ }
54
+
55
+ /** The start of an enrolment: what two-step sign-in asks of the person, and the button that issues a key. */
56
+ export function secondFactorIntroPage(input: EnrolPageBase): Response {
57
+ const text = catalogFor(input.locale).pages.secondFactor
58
+ return htmlPage({
59
+ locale: input.locale,
60
+ brand: input.brand,
61
+ title: text.enrolTitle,
62
+ content: `<h1>${escapeHtml(text.enrolTitle)}</h1><p>${escapeHtml(text.enrolText)}</p>
63
+ <form method="post" action="${SECOND_FACTOR_ENROL_PATH}">
64
+ <button type="submit" name="step" value="start">${escapeHtml(text.start)}</button>
65
+ </form>`,
66
+ })
67
+ }
68
+
69
+ /** The key to enrol, as a QR code and as text, and the form that confirms it with the first code. */
70
+ export function secondFactorEnrolPage(
71
+ input: EnrolPageBase & { readonly qrCode: string; readonly key: string; readonly invalidCode?: boolean },
72
+ ): Response {
73
+ const text = catalogFor(input.locale).pages.secondFactor
74
+ const grouped = input.key.match(/.{1,4}/g)?.join(' ') ?? input.key
75
+ return htmlPage({
76
+ locale: input.locale,
77
+ brand: input.brand,
78
+ title: text.enrolTitle,
79
+ content: `<h1>${escapeHtml(text.enrolTitle)}</h1>${
80
+ input.invalidCode === true ? `<p role="alert" class="error">${escapeHtml(text.invalidCode)}</p>` : ''
81
+ }<p>${escapeHtml(text.scanText)}</p>
82
+ <p><img src="${escapeHtml(input.qrCode)}" alt="QR" width="240" height="240"></p>
83
+ <p>${escapeHtml(text.secretLabel)}: <code>${escapeHtml(grouped)}</code></p>
84
+ <form method="post" action="${SECOND_FACTOR_ENROL_PATH}">
85
+ <label>${
86
+ escapeHtml(text.confirmLabel)
87
+ }<input name="code" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="8" required autofocus></label>
88
+ <button type="submit" name="step" value="confirm">${escapeHtml(text.confirm)}</button>
89
+ </form>`,
90
+ status: input.invalidCode === true ? 400 : 200,
91
+ })
92
+ }
93
+
94
+ /** The recovery codes, shown once, at the confirmed enrolment. `landing` is where the person continues. */
95
+ export function recoveryCodesPage(input: EnrolPageBase & { readonly codes: readonly string[]; readonly landing: string }): Response {
96
+ const text = catalogFor(input.locale).pages.secondFactor
97
+ return htmlPage({
98
+ locale: input.locale,
99
+ brand: input.brand,
100
+ title: text.recoveryTitle,
101
+ content: `<h1>${escapeHtml(text.recoveryTitle)}</h1><p>${escapeHtml(text.recoveryText)}</p>
102
+ <ul>${input.codes.map((code) => `<li><code>${escapeHtml(code)}</code></li>`).join('')}</ul>
103
+ <p><a class="button" href="${escapeHtml(input.landing)}">${escapeHtml(text.continue)}</a></p>`,
104
+ })
105
+ }
106
+
107
+ /** An authenticator is already enrolled: since when, and how many recovery codes are left. */
108
+ export function secondFactorEnrolledPage(input: EnrolPageBase & { readonly confirmedAt: number; readonly recoveryCodesLeft: number }): Response {
109
+ const text = catalogFor(input.locale).pages.secondFactor
110
+ const enrolledOn = new Date(input.confirmedAt * 1000).toISOString().slice(0, 10)
111
+ return htmlPage({
112
+ locale: input.locale,
113
+ brand: input.brand,
114
+ title: text.enrolledTitle,
115
+ content: `<h1>${escapeHtml(text.enrolledTitle)}</h1><p>${escapeHtml(text.enrolledText(enrolledOn, input.recoveryCodesLeft))}</p>`,
116
+ })
117
+ }
118
+
119
+ /** The installation holds no data key, so no authenticator can be enrolled. */
120
+ export function secondFactorUnavailablePage(input: EnrolPageBase): Response {
121
+ const text = catalogFor(input.locale).pages.secondFactor
122
+ return htmlPage({
123
+ locale: input.locale,
124
+ brand: input.brand,
125
+ title: text.unavailableTitle,
126
+ content: `<h1>${escapeHtml(text.unavailableTitle)}</h1><p>${escapeHtml(text.unavailableText)}</p>`,
127
+ status: 503,
128
+ })
129
+ }
package/src/services.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import { LOCAL_ENVIRONMENT, parseJsonStringArray, readEnvironmentName } from '@fabrika/auth-core'
2
2
  import { type EmailSender, emailSenderFromEnv, readEmailTransportConfig } from '@fabrika/email'
3
3
  import { uuidv7 } from '@fabrika/platform'
4
+ import { parseDataKey } from './data-key'
4
5
  import type { IamRepositories } from './db'
5
6
  import { normalizeEmailIdentity } from './email-identity'
6
7
  import type { Env } from './env'
7
8
  import { type OAuthConfig, parseOAuthConfig } from './oauth-config'
8
9
  import { OidcClient } from './oidc'
10
+ import { parseOidcSessionSeconds } from './oidc-session'
9
11
  import { BUN_PBKDF2_COST, type PasswordHasher, WebCryptoPasswordHasher } from './password-crypto'
10
12
  import { passwordMinLengthFloor } from './password-minimum'
11
13
  import { relayFallbackEvent, relayWithFallback } from './relay-mail'
@@ -22,6 +24,8 @@ export interface Services {
22
24
  readonly oidc: OidcClient | null
23
25
  readonly passwordHasher: PasswordHasher
24
26
  readonly email: EmailSender | null
27
+ /** `FABRIKA_IAM_DATA_KEY`, which seals TOTP secrets (`src/data-key.ts`); null when unset, and TOTP enrolment is unavailable. */
28
+ readonly dataKey: Uint8Array<ArrayBuffer> | null
25
29
  readonly config: Config
26
30
  }
27
31
 
@@ -51,7 +55,11 @@ export interface Config {
51
55
  /** Create a real local admin session without contacting an external OIDC provider. */
52
56
  readonly localDevLogin: boolean
53
57
  readonly authentication: {
54
- readonly oidc: { readonly enabled: boolean }
58
+ readonly oidc: {
59
+ readonly enabled: boolean
60
+ /** How long after its sign-in an OIDC login is usable (`OIDC_SESSION_HOURS`); then the provider is asked again. */
61
+ readonly sessionCapSeconds: number
62
+ }
55
63
  readonly password: {
56
64
  readonly enabled: boolean
57
65
  /** The lowest minimum length an administrator may set here (`passwordMinLengthFloor` of the hasher's cost). */
@@ -129,6 +137,7 @@ export function buildServices(env: Env): Services {
129
137
  oidc,
130
138
  passwordHasher: new WebCryptoPasswordHasher(passwordCost),
131
139
  email: buildEmailSender(env, environment),
140
+ dataKey: parseDataKey(env.FABRIKA_IAM_DATA_KEY),
132
141
  config: {
133
142
  human: {
134
143
  emailDomains: parseJsonStringArray(env.HUMAN_EMAIL_DOMAINS),
@@ -140,7 +149,7 @@ export function buildServices(env: Env): Services {
140
149
  environment,
141
150
  localDevLogin: environment === LOCAL_ENVIRONMENT && env.LOCAL_DEV_LOGIN === 'true',
142
151
  authentication: {
143
- oidc: { enabled: oidcEnabled },
152
+ oidc: { enabled: oidcEnabled, sessionCapSeconds: parseOidcSessionSeconds(env.OIDC_SESSION_HOURS) },
144
153
  password: { enabled: passwordEnabled, minLengthFloor: passwordMinLengthFloor(passwordCost) },
145
154
  },
146
155
  oauth: parseOAuthConfig(env.OAUTH_CONFIG),
package/src/tokens.ts CHANGED
@@ -31,7 +31,7 @@ import {
31
31
  signAccessClaims,
32
32
  type TokenPrincipalType,
33
33
  } from '@fabrika/auth-core'
34
- import { sessionUsable } from './auth'
34
+ import { sessionEndsAt, sessionUsable } from './auth'
35
35
  import type { CredentialGrantRow, CredentialRow, PrincipalRow, SessionTerminal } from './db'
36
36
  import { principalStatus, sessionTerminal } from './db'
37
37
  import { issuerAuthority, issuerCoverage } from './delegation'
@@ -87,7 +87,7 @@ export async function mintToken(services: Services, env: MintEnv, input: MintTok
87
87
  return refused('invalid_session', session.principal_id)
88
88
  }
89
89
  // A session outlives the configuration that issued it; refuse it once its method is off.
90
- if (!sessionUsable(session, services.config)) {
90
+ if (!sessionUsable(session, services.config, Math.floor(Date.now() / 1000))) {
91
91
  return refused('invalid_session', session.principal_id)
92
92
  }
93
93
 
@@ -115,7 +115,7 @@ export async function mintToken(services: Services, env: MintEnv, input: MintTok
115
115
  // In a grant's last 30 s (the proxy's TOKEN_REFRESH_SKEW_SECONDS) the proxy re-mints per request; cache.test.ts pins it.
116
116
  const expiresAt = Math.min(
117
117
  now + DEFAULT_TOKEN_TTL_SECONDS,
118
- session.expires_at,
118
+ sessionEndsAt(session, services.config),
119
119
  authorityDeadline(authority, onTerminal === null ? permissions : narrowPermissions(authority.permissions, onTerminal.ceiling), now)
120
120
  ?? Number.POSITIVE_INFINITY,
121
121
  // A terminal's own entries are its principal's grants, and end with them.
package/src/totp.ts ADDED
@@ -0,0 +1,132 @@
1
+ // TOTP (RFC 6238 over RFC 4226): HMAC-SHA1, 30-second steps, 6 digits — the parameters every authenticator app reads
2
+ // from an `otpauth://` URI without asking. Pure functions over WebCrypto, so both runtimes run the same code.
3
+
4
+ import { renderSVG } from 'uqr'
5
+ import { hashToken } from './secret'
6
+
7
+ export const TOTP_PERIOD_SECONDS = 30
8
+ export const TOTP_DIGITS = 6
9
+ /** 160 bits, RFC 4226's recommended secret length for HMAC-SHA1. */
10
+ const SECRET_BYTES = 20
11
+ /** One step either side of now: an authenticator whose clock is up to 30 s off still signs in. */
12
+ const ACCEPTED_DRIFT_STEPS = 1
13
+
14
+ /** Recovery codes issued at enrolment; each signs in once in place of a code. */
15
+ export const RECOVERY_CODE_COUNT = 10
16
+ /** 16 base32 characters, 80 bits: a stolen hash is not worth brute-forcing. */
17
+ const RECOVERY_CODE_CHARACTERS = 16
18
+
19
+ const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
20
+
21
+ export function generateTotpSecret(): Uint8Array<ArrayBuffer> {
22
+ return crypto.getRandomValues(new Uint8Array(new ArrayBuffer(SECRET_BYTES)))
23
+ }
24
+
25
+ /** RFC 4648 base32 without padding: what an authenticator app expects in `secret=` and what a person types. */
26
+ export function base32(bytes: Uint8Array): string {
27
+ let bits = 0
28
+ let value = 0
29
+ let out = ''
30
+ for (const byte of bytes) {
31
+ value = (value << 8) | byte
32
+ bits += 8
33
+ while (bits >= 5) {
34
+ out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31]
35
+ bits -= 5
36
+ }
37
+ }
38
+ if (bits > 0) out += BASE32_ALPHABET[(value << (5 - bits)) & 31]
39
+ return out
40
+ }
41
+
42
+ /** The time step `unixSeconds` falls in. */
43
+ export function totpStep(unixSeconds: number): number {
44
+ return Math.floor(unixSeconds / TOTP_PERIOD_SECONDS)
45
+ }
46
+
47
+ /** The code of `step` (RFC 4226 dynamic truncation), zero-padded to six digits. */
48
+ export async function totpCode(secret: Uint8Array<ArrayBuffer>, step: number): Promise<string> {
49
+ const counter = new Uint8Array(new ArrayBuffer(8))
50
+ new DataView(counter.buffer).setBigUint64(0, BigInt(step))
51
+ const key = await crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-1' }, false, ['sign'])
52
+ const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, counter))
53
+ const offset = (mac[mac.length - 1] ?? 0) & 0x0f
54
+ const binary = (((mac[offset] ?? 0) & 0x7f) << 24) | ((mac[offset + 1] ?? 0) << 16) | ((mac[offset + 2] ?? 0) << 8) | (mac[offset + 3] ?? 0)
55
+ return String(binary % 10 ** TOTP_DIGITS).padStart(TOTP_DIGITS, '0')
56
+ }
57
+
58
+ /** Six digits, as a person types them: spaces are dropped, anything else is not a code. */
59
+ export function parseTotpCode(input: string): string | null {
60
+ const code = input.replaceAll(/\s/g, '')
61
+ return /^\d{6}$/.test(code) ? code : null
62
+ }
63
+
64
+ /**
65
+ * The step `code` belongs to, within the accepted drift of `now` and after `lastStep`, or null. A step at or before
66
+ * `lastStep` is refused, so an accepted code — and every earlier one — is never accepted again.
67
+ */
68
+ export async function matchingStep(
69
+ secret: Uint8Array<ArrayBuffer>,
70
+ code: string,
71
+ unixSeconds: number,
72
+ lastStep: number | null,
73
+ ): Promise<number | null> {
74
+ const now = totpStep(unixSeconds)
75
+ let matched: number | null = null
76
+ // Every candidate is computed and compared, so the time taken says nothing about which one matched.
77
+ for (let step = now - ACCEPTED_DRIFT_STEPS; step <= now + ACCEPTED_DRIFT_STEPS; step++) {
78
+ const equal = constantTimeEqual(await totpCode(secret, step), code)
79
+ if (equal && (lastStep === null || step > lastStep) && matched === null) matched = step
80
+ }
81
+ return matched
82
+ }
83
+
84
+ /** The URI an authenticator app enrols from, as a QR code or typed in. `issuer` names the installation, `account` the person. */
85
+ export function otpauthUri(input: { readonly issuer: string; readonly account: string; readonly secret: Uint8Array }): string {
86
+ const label = `${encodeURIComponent(input.issuer)}:${encodeURIComponent(input.account)}`
87
+ const query = new URLSearchParams({
88
+ secret: base32(input.secret),
89
+ issuer: input.issuer,
90
+ algorithm: 'SHA1',
91
+ digits: String(TOTP_DIGITS),
92
+ period: String(TOTP_PERIOD_SECONDS),
93
+ })
94
+ return `otpauth://totp/${label}?${query.toString()}`
95
+ }
96
+
97
+ /** The URI as a QR code: an SVG `data:` URI, which the page CSP's `img-src data:` admits and which runs no script. */
98
+ export function qrCodeDataUri(text: string): string {
99
+ const svg = renderSVG(text, { ecc: 'M', border: 2, pixelSize: 6 })
100
+ let binary = ''
101
+ for (const byte of new TextEncoder().encode(svg)) binary += String.fromCharCode(byte)
102
+ return `data:image/svg+xml;base64,${btoa(binary)}`
103
+ }
104
+
105
+ /** Fresh recovery codes, grouped by four for reading: `abcd-efgh-ijkl-mnop`. */
106
+ export function generateRecoveryCodes(): string[] {
107
+ return Array.from({ length: RECOVERY_CODE_COUNT }, () => {
108
+ const bytes = crypto.getRandomValues(new Uint8Array(RECOVERY_CODE_CHARACTERS))
109
+ const characters = Array.from(bytes, (byte) => BASE32_ALPHABET[byte & 31]).join('').toLowerCase()
110
+ return characters.match(/.{4}/g)?.join('-') ?? characters
111
+ })
112
+ }
113
+
114
+ /** A recovery code as typed: case, spaces and dashes do not matter; anything else is not one. */
115
+ export function parseRecoveryCode(input: string): string | null {
116
+ const code = input.replaceAll(/[\s-]/g, '').toLowerCase()
117
+ return new RegExp(`^[a-z2-7]{${RECOVERY_CODE_CHARACTERS}}$`).test(code) ? code : null
118
+ }
119
+
120
+ /** The stored form of a recovery code: its hash, bound to its principal, so no code is stored and none spends elsewhere. */
121
+ export function recoveryCodeHash(principalId: string, code: string): Promise<string> {
122
+ const parsed = parseRecoveryCode(code)
123
+ if (parsed === null) throw new Error('not a recovery code')
124
+ return hashToken(`second-factor-recovery:${principalId}:${parsed}`)
125
+ }
126
+
127
+ function constantTimeEqual(a: string, b: string): boolean {
128
+ if (a.length !== b.length) return false
129
+ let difference = 0
130
+ for (let index = 0; index < a.length; index++) difference |= a.charCodeAt(index) ^ b.charCodeAt(index)
131
+ return difference === 0
132
+ }
@@ -1,4 +1,4 @@
1
- import { type ApiKeyDetail, type ApiKeyIdInput, type CursorList, type ListApiKeysInput, type OkResponse, type ProvisionApiKeyRequest, type ProvisionApiKeyResponse, type RotateApiKeyInput, type RotateApiKeyResponse } from '@fabrika/iam-contract';
1
+ import { type ApiKeyDetail, type ApiKeyIdInput, type CursorList, type GetApiKeyResponse, type ListApiKeysInput, type OkResponse, type ProvisionApiKeyRequest, type ProvisionApiKeyResponse, type RotateApiKeyInput, type RotateApiKeyResponse } from '@fabrika/iam-contract';
2
2
  import { type AdminContext } from './context';
3
3
  /**
4
4
  * One page of service principals with their grants and live credentials. THREE queries per page, whatever the page
@@ -6,8 +6,8 @@ import { type AdminContext } from './context';
6
6
  * roster, with no pagination at all (SEC-22).
7
7
  */
8
8
  export declare function listApiKeysUseCase(c: AdminContext, input: ListApiKeysInput): Promise<CursorList<ApiKeyDetail>>;
9
- /** One key with its grants and its live credential, for the console's key page. */
10
- export declare function getApiKeyUseCase(c: AdminContext, input: ApiKeyIdInput): Promise<ApiKeyDetail>;
9
+ /** One key with its grants, each naming who granted it, and its live credential, for the console's key page. */
10
+ export declare function getApiKeyUseCase(c: AdminContext, input: ApiKeyIdInput): Promise<GetApiKeyResponse>;
11
11
  export declare function provisionApiKeyUseCase(c: AdminContext, input: ProvisionApiKeyRequest): Promise<ProvisionApiKeyResponse>;
12
12
  export declare function revokeApiKeyUseCase(c: AdminContext, input: {
13
13
  principalId: string;
@@ -21,6 +21,8 @@ export declare class RoleKnownCache {
21
21
  export declare function toGrantDto(row: GrantRow, roleCache: RoleKnownCache): Promise<GrantDto>;
22
22
  /** Map a list of grant rows to DTOs sharing one role-known cache (one query per app). */
23
23
  export declare function toGrantDtos(rows: GrantRow[], services: Services, cache?: RoleKnownCache): Promise<GrantDto[]>;
24
+ /** The label of each principal who granted one of `rows`; an author no longer known reads as its id. */
25
+ export declare function grantAuthorLabels(rows: GrantRow[], services: Services): Promise<Map<string, string>>;
24
26
  /** The set of app ids IAM knows about — the live registry derived from the schema tables. */
25
27
  export declare function knownApps(c: AdminContext): Promise<string[]>;
26
28
  /** Validate an admin-supplied `app`: null (all apps) or a known (registered) app. */
@@ -9,6 +9,7 @@ import { getPasswordPolicyUseCase, setPasswordPolicyUseCase } from './password-p
9
9
  import { disablePasswordUseCase, issuePasswordEnrollmentUseCase, issuePasswordResetUseCase } from './passwords';
10
10
  import { createPolicyUseCase, deletePolicyUseCase, listPoliciesUseCase, updatePolicyUseCase } from './policies';
11
11
  import { getPrincipalUseCase, invitePrincipalUseCase, listPrincipalsUseCase, me, promotePrincipalUseCase, updatePrincipalUseCase } from './principals';
12
+ import { getSecondFactorUseCase, resetSecondFactorUseCase } from './second-factor';
12
13
  import { listSessionsUseCase, revokeSessionsForPrincipalUseCase, revokeSessionUseCase } from './sessions';
13
14
  import { createShareLinkUseCase, listShareLinksUseCase, revokeShareLinkUseCase } from './share-links';
14
15
  import { listTerminalsUseCase, revokeTerminalUseCase, setTerminalProfileUseCase } from './terminals';
@@ -74,6 +75,8 @@ export declare const adminUseCases: {
74
75
  clearInstallationBrand: typeof clearInstallationBrandUseCase;
75
76
  getPasswordPolicy: typeof getPasswordPolicyUseCase;
76
77
  setPasswordPolicy: typeof setPasswordPolicyUseCase;
78
+ getSecondFactor: typeof getSecondFactorUseCase;
79
+ resetSecondFactor: typeof resetSecondFactorUseCase;
77
80
  listTerminals: typeof listTerminalsUseCase;
78
81
  setTerminalProfile: typeof setTerminalProfileUseCase;
79
82
  revokeTerminal: typeof revokeTerminalUseCase;
@@ -0,0 +1,5 @@
1
+ import type { PrincipalIdInput, SecondFactorDto } from '@fabrika/iam-contract';
2
+ import { type AdminContext } from './context';
3
+ export declare function getSecondFactorUseCase(c: AdminContext, input: PrincipalIdInput): Promise<SecondFactorDto>;
4
+ /** Remove the authenticator and recovery codes, recorded as `iam.second_factor.reset`; a principal without one records nothing. */
5
+ export declare function resetSecondFactorUseCase(c: AdminContext, input: PrincipalIdInput): Promise<SecondFactorDto>;
@@ -40,6 +40,16 @@ export type AuthFailure = {
40
40
  | {
41
41
  readonly kind: 'terminal_completion_refused';
42
42
  }
43
+ /** The challenge cookie of a sign-in waiting for its second factor is missing, forged or older than its five minutes. */
44
+ | {
45
+ readonly kind: 'second_factor_expired';
46
+ }
47
+ /** The browser holds no login of a principal that may enrol an authenticator. */
48
+ | {
49
+ readonly kind: 'second_factor_not_allowed';
50
+ } | {
51
+ readonly kind: 'second_factor_unavailable';
52
+ }
43
53
  /** A refusal of the principal resolution; `reason` is its fixed code, never what the caller sent. */
44
54
  | {
45
55
  readonly kind: 'login_refused';