@fabrika/iam 0.9.0-dev.31 → 0.9.0-dev.33

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 (64) hide show
  1. package/fabrika.config.ts +11 -3
  2. package/migrations/0032_second_factor.sql +29 -0
  3. package/migrations-postgres/0032_second_factor.sql +29 -0
  4. package/package.json +11 -10
  5. package/src/admin/api-keys.ts +15 -5
  6. package/src/admin/grant-support.ts +10 -0
  7. package/src/admin/grants.ts +5 -2
  8. package/src/admin/handlers.ts +3 -0
  9. package/src/admin/principals.ts +2 -5
  10. package/src/admin/rpc.ts +8 -0
  11. package/src/admin/second-factor.ts +39 -0
  12. package/src/admin/sessions.ts +4 -4
  13. package/src/auth/failure.ts +5 -0
  14. package/src/auth/http.ts +1 -1
  15. package/src/auth/invitations.ts +11 -3
  16. package/src/auth/login.ts +3 -2
  17. package/src/auth/oidc.ts +1 -1
  18. package/src/auth/password.ts +6 -6
  19. package/src/auth/routes.ts +11 -3
  20. package/src/auth/second-factor-challenge.ts +114 -0
  21. package/src/auth/second-factor.ts +276 -0
  22. package/src/auth/sessions.ts +72 -21
  23. package/src/auth.ts +19 -4
  24. package/src/catalog/cs.ts +32 -0
  25. package/src/catalog/en.ts +33 -0
  26. package/src/catalog/index.ts +28 -0
  27. package/src/catalog/uk.ts +33 -0
  28. package/src/data-key.ts +92 -0
  29. package/src/db.ts +12 -1
  30. package/src/env.ts +12 -0
  31. package/src/node/runtime.ts +7 -0
  32. package/src/oauth.ts +7 -3
  33. package/src/oidc-session.ts +25 -0
  34. package/src/repositories/second-factors.ts +165 -0
  35. package/src/repositories/sessions.ts +17 -9
  36. package/src/second-factor-pages.ts +129 -0
  37. package/src/services.ts +11 -2
  38. package/src/signing.ts +13 -5
  39. package/src/tokens.ts +18 -11
  40. package/src/totp.ts +132 -0
  41. package/types/src/admin/api-keys.d.ts +3 -3
  42. package/types/src/admin/grant-support.d.ts +2 -0
  43. package/types/src/admin/handlers.d.ts +3 -0
  44. package/types/src/admin/second-factor.d.ts +5 -0
  45. package/types/src/auth/failure.d.ts +10 -0
  46. package/types/src/auth/http.d.ts +1 -1
  47. package/types/src/auth/invitations.d.ts +2 -1
  48. package/types/src/auth/password.d.ts +1 -1
  49. package/types/src/auth/second-factor-challenge.d.ts +34 -0
  50. package/types/src/auth/second-factor.d.ts +19 -0
  51. package/types/src/auth/sessions.d.ts +22 -9
  52. package/types/src/auth.d.ts +9 -3
  53. package/types/src/catalog/index.d.ts +28 -0
  54. package/types/src/data-key.d.ts +19 -0
  55. package/types/src/db.d.ts +4 -1
  56. package/types/src/env.d.ts +12 -0
  57. package/types/src/oidc-session.d.ts +12 -0
  58. package/types/src/repositories/second-factors.d.ts +68 -0
  59. package/types/src/repositories/sessions.d.ts +7 -3
  60. package/types/src/second-factor-pages.d.ts +42 -0
  61. package/types/src/services.d.ts +4 -0
  62. package/types/src/signing.d.ts +4 -4
  63. package/types/src/tokens.d.ts +5 -2
  64. package/types/src/totp.d.ts +32 -0
@@ -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/signing.ts CHANGED
@@ -12,7 +12,15 @@
12
12
  * One Signer per isolate, memoised like the `JwtValidator` (jose imports the key once).
13
13
  */
14
14
 
15
- import { type AccessTokenClaims, type Jwks, parseAccessClaims, type PublicJwk, RESOURCE_ACCESS_TOKEN_TYP, TOKEN_ALG } from '@fabrika/auth-core'
15
+ import {
16
+ type AccessTokenClaims,
17
+ type AccessTokenPayload,
18
+ type Jwks,
19
+ parseAccessClaims,
20
+ type PublicJwk,
21
+ RESOURCE_ACCESS_TOKEN_TYP,
22
+ TOKEN_ALG,
23
+ } from '@fabrika/auth-core'
16
24
  import {
17
25
  calculateJwkThumbprint,
18
26
  createLocalJWKSet,
@@ -43,15 +51,15 @@ export class Signer {
43
51
  private constructor(private readonly keys: LoadedKey[]) {}
44
52
 
45
53
  /**
46
- * Sign a claims object with the ACTIVE key. The `kid` goes in the protected header so the SDK
47
- * picks the matching public JWK. The claims already carry `iss`/`aud`/`exp` (built in core).
54
+ * Sign an access token payload (`accessTokenPayload`) with the ACTIVE key. The `kid` goes in the protected header so
55
+ * the SDK picks the matching public JWK. The claims already carry `iss`/`aud`/`exp` (built in core).
48
56
  */
49
- sign(claims: AccessTokenClaims): Promise<string> {
57
+ sign(payload: AccessTokenPayload): Promise<string> {
50
58
  const active = this.keys[0]
51
59
  if (!active) {
52
60
  throw new Error('Signer has no keys')
53
61
  }
54
- return new SignJWT({ ...claims })
62
+ return new SignJWT({ ...payload })
55
63
  .setProtectedHeader({ alg: TOKEN_ALG, kid: active.kid })
56
64
  .sign(active.key)
57
65
  }
package/src/tokens.ts CHANGED
@@ -28,9 +28,10 @@ import {
28
28
  type PermissionEntry,
29
29
  permits,
30
30
  type Scope,
31
+ signAccessClaims,
31
32
  type TokenPrincipalType,
32
33
  } from '@fabrika/auth-core'
33
- import { sessionUsable } from './auth'
34
+ import { sessionEndsAt, sessionUsable } from './auth'
34
35
  import type { CredentialGrantRow, CredentialRow, PrincipalRow, SessionTerminal } from './db'
35
36
  import { principalStatus, sessionTerminal } from './db'
36
37
  import { issuerAuthority, issuerCoverage } from './delegation'
@@ -86,7 +87,7 @@ export async function mintToken(services: Services, env: MintEnv, input: MintTok
86
87
  return refused('invalid_session', session.principal_id)
87
88
  }
88
89
  // A session outlives the configuration that issued it; refuse it once its method is off.
89
- if (!sessionUsable(session, services.config)) {
90
+ if (!sessionUsable(session, services.config, Math.floor(Date.now() / 1000))) {
90
91
  return refused('invalid_session', session.principal_id)
91
92
  }
92
93
 
@@ -114,12 +115,13 @@ export async function mintToken(services: Services, env: MintEnv, input: MintTok
114
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.
115
116
  const expiresAt = Math.min(
116
117
  now + DEFAULT_TOKEN_TTL_SECONDS,
117
- session.expires_at,
118
+ sessionEndsAt(session, services.config),
118
119
  authorityDeadline(authority, onTerminal === null ? permissions : narrowPermissions(authority.permissions, onTerminal.ceiling), now)
119
120
  ?? Number.POSITIVE_INFINITY,
120
121
  // A terminal's own entries are its principal's grants, and end with them.
121
122
  (onTerminal === null ? null : authorityDeadline(onTerminal.authority, onTerminal.additions, now)) ?? Number.POSITIVE_INFINITY,
122
123
  )
124
+ const bound = await proxyMintedBound(services, input.app)
123
125
  const token = await boundedToken(
124
126
  signAccessToken(services, env, {
125
127
  app: input.app,
@@ -132,8 +134,8 @@ export async function mintToken(services: Services, env: MintEnv, input: MintTok
132
134
  permissions,
133
135
  issuedAt: now,
134
136
  expiresAt,
135
- }),
136
- { app: input.app, subject: principal.id, bytes: await proxyMintedBound(services, input.app) },
137
+ }, bound),
138
+ { app: input.app, subject: principal.id, bytes: bound },
137
139
  )
138
140
  if (token === null) {
139
141
  return refused('token_too_large', principal.id)
@@ -249,6 +251,7 @@ export async function mintFromKey(
249
251
  cred.expires_at ?? Number.POSITIVE_INFINITY,
250
252
  effective.expiresAt ?? Number.POSITIVE_INFINITY,
251
253
  )
254
+ const bound = await proxyMintedBound(services, input.app)
252
255
  const token = await boundedToken(
253
256
  signAccessToken(services, env, {
254
257
  app: input.app,
@@ -261,8 +264,8 @@ export async function mintFromKey(
261
264
  ...(effective.link === undefined ? {} : { link: effective.link }),
262
265
  issuedAt: now,
263
266
  expiresAt,
264
- }),
265
- { app: input.app, subject: effective.subject, bytes: await proxyMintedBound(services, input.app) },
267
+ }, bound),
268
+ { app: input.app, subject: effective.subject, bytes: bound },
266
269
  )
267
270
  if (token === null) {
268
271
  return { result: { ok: false, reason: 'token_too_large' }, principalId: cred.principal_id, credentialId: cred.id }
@@ -302,8 +305,8 @@ export async function mintFromWorkloadKey(services: Services, env: MintEnv, inpu
302
305
  permissions: effective.permissions,
303
306
  issuedAt: now,
304
307
  expiresAt,
305
- }),
306
- { app: input.app, subject: effective.subject },
308
+ }, MAX_ACCESS_TOKEN_BYTES),
309
+ { app: input.app, subject: effective.subject, bytes: MAX_ACCESS_TOKEN_BYTES },
307
310
  )
308
311
  if (token === null) {
309
312
  return refused
@@ -494,13 +497,17 @@ export async function boundedToken(
494
497
  return null
495
498
  }
496
499
 
497
- /** Sign an access token with the isolate's active signing key. Shared by every mint front. */
500
+ /**
501
+ * Sign an access token with the isolate's active signing key, in the compact layout only when the entries layout is
502
+ * above `bound` (`signAccessClaims`); `boundedToken` refuses one still above it. Shared by every mint front.
503
+ */
498
504
  export async function signAccessToken(
499
505
  services: Services,
500
506
  env: MintEnv,
501
507
  params: Omit<Parameters<typeof buildAccessClaims>[0], 'iss'>,
508
+ bound: number,
502
509
  ): Promise<string> {
503
510
  const signer = await getSigner(env)
504
511
  const claims: AccessTokenClaims = buildAccessClaims({ ...params, iss: services.config.issuer })
505
- return signer.sign(claims)
512
+ return signAccessClaims(claims, bound, (payload) => signer.sign(payload))
506
513
  }
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';
@@ -21,7 +21,7 @@ export declare function stringValue(value: string | null): string | null;
21
21
  export declare function methodNotAllowed(): Response;
22
22
  /**
23
23
  * Headers for a 302 out of this surface. `no-store` belongs on every one of them, not just the
24
- * password pages: these are the responses that carry the 30-day session cookie and, on the handoff
24
+ * password pages: these are the responses that carry the session cookie and, on the handoff
25
25
  * path, the single-use code in the `Location` itself.
26
26
  */
27
27
  export declare function redirectHeaders(location: string): Headers;
@@ -1,5 +1,6 @@
1
1
  import { type RequestContext } from '../env';
2
2
  import type { Services } from '../services';
3
+ import type { AuthEnv } from './oidc-flight';
3
4
  /**
4
5
  * `GET|POST /auth/invitations/accept`. The emailed link opens the GET page; its fragment carries the
5
6
  * one-time token, which never reaches a server log. Accepting is a POST from that page, same-origin
@@ -15,4 +16,4 @@ import type { Services } from '../services';
15
16
  * The link's `?app=` picks the page's language; an accepted invitation lands on its own application's
16
17
  * registered origin, where the application's proxy signs the browser in through the normal handoff.
17
18
  */
18
- export declare function handleInvitation(request: Request, services: Services, ctx: RequestContext, requestId: string): Promise<Response>;
19
+ export declare function handleInvitation(request: Request, services: Services, env: AuthEnv, ctx: RequestContext, requestId: string): Promise<Response>;
@@ -4,4 +4,4 @@ import { type Services } from '../services';
4
4
  import type { AuthEnv } from './oidc-flight';
5
5
  export declare function handlePasswordLogin(request: Request, services: Services, env: AuthEnv, ctx: RequestContext, clientAddress: string | null, requestId: string): Promise<Response>;
6
6
  export declare function handleForgotPassword(request: Request, services: Services, ctx: RequestContext, clientAddress: string | null, requestId: string): Promise<Response>;
7
- export declare function handlePasswordAction(request: Request, services: Services, ctx: RequestContext, purpose: PasswordActionPurpose, requestId: string): Promise<Response>;
7
+ export declare function handlePasswordAction(request: Request, services: Services, env: AuthEnv, ctx: RequestContext, purpose: PasswordActionPurpose, requestId: string): Promise<Response>;
@@ -0,0 +1,34 @@
1
+ import { type ChallengeProblem } from '../second-factor-pages';
2
+ import type { Services } from '../services';
3
+ import type { Handoff } from './handoff';
4
+ import type { AuthEnv } from './oidc-flight';
5
+ /** Host-only on IAM's host, outside the `__Host-px_` prefix the proxy strips upstream, so no application receives it. */
6
+ export declare const SECOND_FACTOR_COOKIE = "__Host-fabrika_second_factor";
7
+ /** Long enough to open an authenticator app and type a code; a sign-in that takes longer proves its first factor again. */
8
+ export declare const SECOND_FACTOR_CHALLENGE_TTL_SECONDS: number;
9
+ /** The login a verified code opens: what `issueSession` was given, less the request's own id. */
10
+ export interface PendingLogin {
11
+ readonly principalId: string;
12
+ readonly idpSub: string | null;
13
+ readonly email: string | null;
14
+ readonly authenticationMethod: 'oidc' | 'password';
15
+ readonly redirect: string | null;
16
+ readonly reason: string;
17
+ readonly handoff: Handoff | null;
18
+ /** A password login earns the known-device cookie once it is recorded. */
19
+ readonly rememberDevice: boolean;
20
+ }
21
+ /** The pending login the request's challenge cookie proves, or null when it is absent, forged, expired or malformed. */
22
+ export declare function readPendingLogin(env: AuthEnv, request: Request): Promise<PendingLogin | null>;
23
+ /**
24
+ * Answer a first factor with the code form and the cookie that holds the pending login. An OIDC flight is spent here,
25
+ * as on every other end of its callback.
26
+ */
27
+ export declare function challengeSecondFactor(services: Services, env: AuthEnv, request: Request, pending: PendingLogin): Promise<Response>;
28
+ /**
29
+ * The code form for `pending`, again with `problem`. Its `form-action` admits the one origin the verified login lands
30
+ * on: the handoff's registered origin, the IAM-chosen landing, or the console for a login with no destination.
31
+ */
32
+ export declare function challengePage(services: Services, request: Request, pending: PendingLogin, problem?: ChallengeProblem): Promise<Response>;
33
+ /** The `Set-Cookie` that spends the challenge. */
34
+ export declare function endingChallengeCookie(): string;
@@ -0,0 +1,19 @@
1
+ import type { RequestContext } from '../env';
2
+ import type { Services } from '../services';
3
+ import type { AuthEnv } from './oidc-flight';
4
+ /** Codes one account may try in a window before the next waits out the block: a burst, not a person mistyping. */
5
+ export declare const SECOND_FACTOR_MAX_ATTEMPTS = 5;
6
+ /**
7
+ * The code form's POST. The pending login comes from the challenge cookie only. Each attempt is counted per account
8
+ * before the code is checked, from the row the counting statement returns, so a parallel burst gets no more than
9
+ * `SECOND_FACTOR_MAX_ATTEMPTS` checks; the attempt that starts a block writes `iam.second_factor.throttle` to the
10
+ * audit log. Every refusal writes its `auth_log` row; an accepted code opens the login through `issueSession`.
11
+ */
12
+ export declare function handleSecondFactor(request: Request, services: Services, env: AuthEnv, ctx: RequestContext, requestId: string): Promise<Response>;
13
+ /**
14
+ * Enrolment, on IAM's host, for a signed-in principal that administers (`administersIam`). `GET` shows the state;
15
+ * `POST step=start` seals a new secret that waits for its first code and shows it; `POST step=confirm` checks that
16
+ * code, confirms the factor, replaces the recovery codes and records `iam.second_factor.enrol` in one transaction, and
17
+ * shows the codes once. A confirmed factor is never replaced here: only an administrator's reset removes it.
18
+ */
19
+ export declare function handleSecondFactorEnrolment(request: Request, services: Services, requestId: string): Promise<Response>;