@fabrika/iam 0.9.0-dev.32 → 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 (61) 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/tokens.ts +3 -3
  39. package/src/totp.ts +132 -0
  40. package/types/src/admin/api-keys.d.ts +3 -3
  41. package/types/src/admin/grant-support.d.ts +2 -0
  42. package/types/src/admin/handlers.d.ts +3 -0
  43. package/types/src/admin/second-factor.d.ts +5 -0
  44. package/types/src/auth/failure.d.ts +10 -0
  45. package/types/src/auth/http.d.ts +1 -1
  46. package/types/src/auth/invitations.d.ts +2 -1
  47. package/types/src/auth/password.d.ts +1 -1
  48. package/types/src/auth/second-factor-challenge.d.ts +34 -0
  49. package/types/src/auth/second-factor.d.ts +19 -0
  50. package/types/src/auth/sessions.d.ts +22 -9
  51. package/types/src/auth.d.ts +9 -3
  52. package/types/src/catalog/index.d.ts +28 -0
  53. package/types/src/data-key.d.ts +19 -0
  54. package/types/src/db.d.ts +4 -1
  55. package/types/src/env.d.ts +12 -0
  56. package/types/src/oidc-session.d.ts +12 -0
  57. package/types/src/repositories/second-factors.d.ts +68 -0
  58. package/types/src/repositories/sessions.d.ts +7 -3
  59. package/types/src/second-factor-pages.d.ts +42 -0
  60. package/types/src/services.d.ts +4 -0
  61. package/types/src/totp.d.ts +32 -0
package/src/catalog/en.ts CHANGED
@@ -90,6 +90,12 @@ export const en: Catalog = {
90
90
  return 'Enrolment is unavailable. Try again later.'
91
91
  case 'terminal_completion_refused':
92
92
  return 'This sign-in has expired or was already used. Identify again.'
93
+ case 'second_factor_expired':
94
+ return 'Your sign-in expired before the code was entered. Sign in again.'
95
+ case 'second_factor_not_allowed':
96
+ return 'Sign in with an administrator account to set up two-step sign-in.'
97
+ case 'second_factor_unavailable':
98
+ return 'Two-step sign-in is unavailable. Try again later.'
93
99
  }
94
100
  },
95
101
  },
@@ -113,6 +119,33 @@ export const en: Catalog = {
113
119
  enrolledTitle: 'Terminal enrolled',
114
120
  enrolledText: (label) => `This browser is now the terminal ${label}. You are signed out. An administrator sets which applications it serves.`,
115
121
  },
122
+ secondFactor: {
123
+ challengeTitle: 'Two-step sign-in',
124
+ challengeText: 'Enter the 6-digit code from your authenticator app, or one of your recovery codes.',
125
+ codeLabel: 'Code',
126
+ submit: 'Verify',
127
+ invalidCode: 'This code is not valid. Enter the current code, or a recovery code you have not used.',
128
+ throttled: 'Too many wrong codes. Wait 15 minutes, then try again.',
129
+ appCodesUnavailable: 'Codes from the authenticator app cannot be checked here right now. Use a recovery code, or ask an administrator.',
130
+ startOver: 'Sign in again',
131
+ enrolTitle: 'Set up two-step sign-in',
132
+ enrolText:
133
+ 'After the password or single sign-on, every sign-in to this account will ask for a code from an authenticator app on your phone. You will also get recovery codes for when the phone is not at hand.',
134
+ start: 'Set up an authenticator app',
135
+ scanText: 'Scan the QR code with your authenticator app, or type the key into it. Then enter the 6-digit code it shows.',
136
+ secretLabel: 'Key',
137
+ confirmLabel: 'Code from the app',
138
+ confirm: 'Turn on two-step sign-in',
139
+ enrolledTitle: 'Two-step sign-in is on',
140
+ enrolledText: (enrolledOn, left) =>
141
+ `Since ${enrolledOn} every sign-in to this account asks for a code. Recovery codes left: ${left}. To move to a new phone, ask an administrator to reset your authenticator.`,
142
+ recoveryTitle: 'Save your recovery codes',
143
+ recoveryText:
144
+ 'Each code signs you in once when your phone is not at hand. They are shown only now: store them somewhere safe, apart from your phone.',
145
+ continue: 'Continue',
146
+ unavailableTitle: 'Two-step sign-in is unavailable',
147
+ unavailableText: 'This installation cannot store authenticator keys yet. Ask its operator to set it up.',
148
+ },
116
149
  invitation: {
117
150
  title: 'Accept invitation',
118
151
  text:
@@ -75,6 +75,34 @@ export interface PageText {
75
75
  readonly enrolledTitle: string
76
76
  readonly enrolledText: (label: string) => string
77
77
  }
78
+ /** The second factor (TOTP): the code a sign-in asks for, and enrolling an authenticator app. */
79
+ readonly secondFactor: {
80
+ readonly challengeTitle: string
81
+ readonly challengeText: string
82
+ readonly codeLabel: string
83
+ readonly submit: string
84
+ readonly invalidCode: string
85
+ /** Too many wrong codes for this account; the next attempt waits. */
86
+ readonly throttled: string
87
+ /** The data key is unset or does not open the secret: only a recovery code signs in. */
88
+ readonly appCodesUnavailable: string
89
+ readonly startOver: string
90
+ readonly enrolTitle: string
91
+ readonly enrolText: string
92
+ readonly start: string
93
+ readonly scanText: string
94
+ readonly secretLabel: string
95
+ readonly confirmLabel: string
96
+ readonly confirm: string
97
+ readonly enrolledTitle: string
98
+ /** `enrolledOn` is an ISO date; `left` the recovery codes not used yet. */
99
+ readonly enrolledText: (enrolledOn: string, left: number) => string
100
+ readonly recoveryTitle: string
101
+ readonly recoveryText: string
102
+ readonly continue: string
103
+ readonly unavailableTitle: string
104
+ readonly unavailableText: string
105
+ }
78
106
  readonly invitation: {
79
107
  readonly title: string
80
108
  readonly text: string
package/src/catalog/uk.ts CHANGED
@@ -91,6 +91,12 @@ export const uk: Catalog = {
91
91
  return 'Реєстрація зараз недоступна. Спробуйте пізніше.'
92
92
  case 'terminal_completion_refused':
93
93
  return 'Цей вхід застарів або вже використаний. Ідентифікуйтеся ще раз.'
94
+ case 'second_factor_expired':
95
+ return 'Вхід завершився раніше, ніж ви ввели код. Увійдіть ще раз.'
96
+ case 'second_factor_not_allowed':
97
+ return 'Щоб налаштувати двоетапний вхід, увійдіть з обліковим записом адміністратора.'
98
+ case 'second_factor_unavailable':
99
+ return 'Двоетапний вхід зараз недоступний. Спробуйте пізніше.'
94
100
  }
95
101
  },
96
102
  },
@@ -114,6 +120,33 @@ export const uk: Catalog = {
114
120
  enrolledTitle: 'Термінал зареєстровано',
115
121
  enrolledText: (label) => `Цей браузер тепер є терміналом «${label}». Ви вийшли. Які застосунки він обслуговує, визначає адміністратор.`,
116
122
  },
123
+ secondFactor: {
124
+ challengeTitle: 'Двоетапний вхід',
125
+ challengeText: 'Введіть шестизначний код із застосунку автентифікації або один зі своїх резервних кодів.',
126
+ codeLabel: 'Код',
127
+ submit: 'Підтвердити',
128
+ invalidCode: 'Цей код недійсний. Введіть поточний код або резервний код, який ви ще не використали.',
129
+ throttled: 'Забагато неправильних кодів. Зачекайте 15 хвилин і спробуйте ще раз.',
130
+ appCodesUnavailable: 'Коди із застосунку автентифікації зараз не можна перевірити. Використайте резервний код або зверніться до адміністратора.',
131
+ startOver: 'Увійти ще раз',
132
+ enrolTitle: 'Налаштувати двоетапний вхід',
133
+ enrolText:
134
+ 'Після пароля або єдиного входу кожен вхід до цього облікового запису вимагатиме код із застосунку автентифікації на вашому телефоні. Ви також отримаєте резервні коди на випадок, коли телефона немає під рукою.',
135
+ start: 'Налаштувати застосунок автентифікації',
136
+ scanText: 'Відскануйте QR-код застосунком автентифікації або введіть у нього ключ. Потім введіть шестизначний код, який він покаже.',
137
+ secretLabel: 'Ключ',
138
+ confirmLabel: 'Код із застосунку',
139
+ confirm: 'Увімкнути двоетапний вхід',
140
+ enrolledTitle: 'Двоетапний вхід увімкнено',
141
+ enrolledText: (enrolledOn, left) =>
142
+ `Від ${enrolledOn} кожен вхід до цього облікового запису вимагає код. Залишилося резервних кодів: ${left}. Щоб перейти на новий телефон, попросіть адміністратора скинути застосунок автентифікації.`,
143
+ recoveryTitle: 'Збережіть резервні коди',
144
+ recoveryText:
145
+ 'Кожен код один раз впустить вас, коли телефона немає під рукою. Вони показуються лише зараз: збережіть їх у безпечному місці окремо від телефона.',
146
+ continue: 'Продовжити',
147
+ unavailableTitle: 'Двоетапний вхід недоступний',
148
+ unavailableText: 'Ця інсталяція ще не вміє зберігати ключі застосунків автентифікації. Попросіть її оператора налаштувати це.',
149
+ },
117
150
  invitation: {
118
151
  title: 'Прийняття запрошення',
119
152
  text:
@@ -0,0 +1,92 @@
1
+ // IAM's one value it must read back and so cannot hash: a TOTP secret. Sealed with Control's vault construction
2
+ // (`packages/control/src/vault.ts`): AES-256-GCM under a fresh data key per value, that data key wrapped by the
3
+ // installation's `FABRIKA_IAM_DATA_KEY`. Unlike the vault, both layers carry associated data naming the value's owner,
4
+ // so a writer of IAM's database who moves a sealed value into another row moves nothing that opens there.
5
+
6
+ const ALG = 'AES-GCM'
7
+ /** GCM's standard nonce, fresh per encryption. */
8
+ const IV_BYTES = 12
9
+ /** AES-256: the installation's key and each data key. */
10
+ export const DATA_KEY_BYTES = 32
11
+
12
+ /** The sealed pieces as stored: all base64, never a plaintext value or data key. */
13
+ export interface SealedValue {
14
+ readonly ciphertext: string
15
+ readonly valueIv: string
16
+ readonly wrappedDek: string
17
+ readonly dekIv: string
18
+ }
19
+
20
+ /**
21
+ * Parse `FABRIKA_IAM_DATA_KEY` (base64 of 32 random bytes) once at boot. Unset or empty is null: nothing can be sealed,
22
+ * so TOTP enrolment is unavailable. Anything else that is not 32 bytes fails the boot; a short key would be a weak key
23
+ * nobody notices.
24
+ */
25
+ export function parseDataKey(raw: string | undefined): Uint8Array<ArrayBuffer> | null {
26
+ if (raw === undefined || raw.trim() === '') return null
27
+ let decoded: Uint8Array<ArrayBuffer>
28
+ try {
29
+ decoded = fromBase64(raw.trim())
30
+ } catch {
31
+ throw new Error('FABRIKA_IAM_DATA_KEY is not base64 — generate it with: head -c 32 /dev/urandom | base64')
32
+ }
33
+ if (decoded.length !== DATA_KEY_BYTES) {
34
+ throw new Error(`FABRIKA_IAM_DATA_KEY must be ${DATA_KEY_BYTES} bytes — generate it with: head -c 32 /dev/urandom | base64`)
35
+ }
36
+ return decoded
37
+ }
38
+
39
+ /** Seal `value` for `owner` (the associated data of both layers). */
40
+ export async function sealValue(dataKey: Uint8Array<ArrayBuffer>, owner: string, value: Uint8Array<ArrayBuffer>): Promise<SealedValue> {
41
+ const additionalData = utf8(owner)
42
+ const kek = await importKey(dataKey, ['encrypt'])
43
+ const dek = await crypto.subtle.generateKey({ name: ALG, length: 256 }, true, ['encrypt', 'decrypt'])
44
+ const valueIv = randomIv()
45
+ const ciphertext = await crypto.subtle.encrypt({ name: ALG, iv: valueIv, additionalData }, dek, value)
46
+ const dekIv = randomIv()
47
+ const wrappedDek = await crypto.subtle.encrypt({ name: ALG, iv: dekIv, additionalData }, kek, copy(await crypto.subtle.exportKey('raw', dek)))
48
+ return { ciphertext: toBase64(ciphertext), valueIv: toBase64(valueIv), wrappedDek: toBase64(wrappedDek), dekIv: toBase64(dekIv) }
49
+ }
50
+
51
+ /** Open a value `sealValue` sealed for `owner`. A wrong key, another owner or any tampered piece throws. */
52
+ export async function openValue(dataKey: Uint8Array<ArrayBuffer>, owner: string, sealed: SealedValue): Promise<Uint8Array<ArrayBuffer>> {
53
+ const additionalData = utf8(owner)
54
+ const kek = await importKey(dataKey, ['decrypt'])
55
+ const dekRaw = await crypto.subtle.decrypt({ name: ALG, iv: fromBase64(sealed.dekIv), additionalData }, kek, fromBase64(sealed.wrappedDek))
56
+ const dek = await crypto.subtle.importKey('raw', copy(dekRaw), { name: ALG }, false, ['decrypt'])
57
+ const value = await crypto.subtle.decrypt({ name: ALG, iv: fromBase64(sealed.valueIv), additionalData }, dek, fromBase64(sealed.ciphertext))
58
+ return copy(value)
59
+ }
60
+
61
+ function importKey(raw: Uint8Array<ArrayBuffer>, usages: KeyUsage[]): Promise<CryptoKey> {
62
+ return crypto.subtle.importKey('raw', raw, { name: ALG }, false, usages)
63
+ }
64
+
65
+ function randomIv(): Uint8Array<ArrayBuffer> {
66
+ return crypto.getRandomValues(new Uint8Array(new ArrayBuffer(IV_BYTES)))
67
+ }
68
+
69
+ function utf8(text: string): Uint8Array<ArrayBuffer> {
70
+ return copy(new TextEncoder().encode(text))
71
+ }
72
+
73
+ /** A copy backed by a fresh `ArrayBuffer`, which WebCrypto's `BufferSource` requires. */
74
+ function copy(view: Uint8Array | ArrayBuffer): Uint8Array<ArrayBuffer> {
75
+ const source = view instanceof ArrayBuffer ? new Uint8Array(view) : view
76
+ const out = new Uint8Array(new ArrayBuffer(source.byteLength))
77
+ out.set(source)
78
+ return out
79
+ }
80
+
81
+ function toBase64(view: Uint8Array | ArrayBuffer): string {
82
+ let binary = ''
83
+ for (const byte of view instanceof ArrayBuffer ? new Uint8Array(view) : view) binary += String.fromCharCode(byte)
84
+ return btoa(binary)
85
+ }
86
+
87
+ function fromBase64(value: string): Uint8Array<ArrayBuffer> {
88
+ const binary = atob(value)
89
+ const out = new Uint8Array(new ArrayBuffer(binary.length))
90
+ for (let index = 0; index < binary.length; index++) out[index] = binary.charCodeAt(index)
91
+ return out
92
+ }
package/src/db.ts CHANGED
@@ -12,6 +12,7 @@ import { MembershipTransportKeyRepository } from './repositories/membership-tran
12
12
  import { OAuthRepository } from './repositories/oauth'
13
13
  import { PasswordPolicyRepository } from './repositories/password-policy'
14
14
  import { PrincipalRepository } from './repositories/principals'
15
+ import { SecondFactorRepository } from './repositories/second-factors'
15
16
  import { SessionRepository } from './repositories/sessions'
16
17
  import { TerminalRepository } from './repositories/terminals'
17
18
  import { WorkloadRepository } from './repositories/workloads'
@@ -60,7 +61,15 @@ export { MembershipTransportKeyRepository, type MembershipTransportKeyRow } from
60
61
  export { type OAuthCodeRow, type OAuthGrantRow, type OAuthRefreshTokenRow, OAuthRepository } from './repositories/oauth'
61
62
  export { PasswordPolicyRepository, type PasswordPolicyRow } from './repositories/password-policy'
62
63
  export { PrincipalRepository, type PrincipalRow, type PrincipalStatus, principalStatus } from './repositories/principals'
63
- export { type AuthenticationMethod, SessionRepository, type SessionRow, type SessionTerminal, sessionTerminal } from './repositories/sessions'
64
+ export { SecondFactorRepository, type SecondFactorRow, type SecondFactorStatus } from './repositories/second-factors'
65
+ export {
66
+ type AuthenticationMethod,
67
+ SessionRepository,
68
+ type SessionRow,
69
+ type SessionTerminal,
70
+ sessionTerminal,
71
+ type SignedInSessionRow,
72
+ } from './repositories/sessions'
64
73
  export {
65
74
  DEFAULT_TERMINAL_SESSION_TTL_SECONDS,
66
75
  MAX_TERMINAL_SESSION_TTL_SECONDS,
@@ -90,6 +99,7 @@ export interface IamRepositories {
90
99
  membershipTransport: MembershipTransportKeyRepository
91
100
  brand: InstallationBrandRepository
92
101
  passwordPolicy: PasswordPolicyRepository
102
+ secondFactors: SecondFactorRepository
93
103
  }
94
104
 
95
105
  /**
@@ -119,6 +129,7 @@ export function createIamRepositories(
119
129
  membershipTransport: replacements.membershipTransport ?? new MembershipTransportKeyRepository(db),
120
130
  brand: replacements.brand ?? new InstallationBrandRepository(db, writer),
121
131
  passwordPolicy: replacements.passwordPolicy ?? new PasswordPolicyRepository(db, writer),
132
+ secondFactors: replacements.secondFactors ?? new SecondFactorRepository(db, writer),
122
133
  }
123
134
  }
124
135
 
package/src/env.ts CHANGED
@@ -52,6 +52,11 @@ export interface Env {
52
52
  * `FABRIKA_IAM_AUDIT_RETENTION_DAYS`. A value that is not a whole number of days fails the boot.
53
53
  */
54
54
  AUDIT_RETENTION_DAYS?: string
55
+ /**
56
+ * Hours an OIDC login stays usable after its sign-in; unset means 12. Deploy var `FABRIKA_IAM_OIDC_SESSION_HOURS`.
57
+ * Anything but a whole number of hours from 1 to 720 fails the boot.
58
+ */
59
+ OIDC_SESSION_HOURS?: string
55
60
  /** `local` / `stage` / `prod`. */
56
61
  ENVIRONMENT: string
57
62
  /** Explicit local-only human login bypass. Ignored unless `ENVIRONMENT=local`. */
@@ -104,6 +109,13 @@ export interface Env {
104
109
  * `vars`. Rotate by changing the env value.
105
110
  */
106
111
  FABRIKA_IAM_PROVISIONING_KEY: string
112
+ /**
113
+ * **Secret.** Base64 of 32 random bytes: the key that seals the one value IAM must read back, a person's TOTP secret
114
+ * (`src/data-key.ts`). Unset makes TOTP enrolment unavailable; a value that is not 32 bytes fails the boot. Losing it
115
+ * makes every enrolled authenticator unreadable, so those people sign in with a recovery code or an administrator's
116
+ * reset. Never placed in `vars`.
117
+ */
118
+ FABRIKA_IAM_DATA_KEY?: string
107
119
  /**
108
120
  * OIDC provider issuer URL (e.g. `https://accounts.google.com`, an Auth0/Okta/Keycloak/Entra
109
121
  * tenant). IAM discovers the endpoints from `${OIDC_ISSUER}/.well-known/openid-configuration`
@@ -15,9 +15,11 @@ import { type EmailProviderRegistry, type EmailSender, emailSenderFromEnv, pickE
15
15
  import { installationMailSender, isHttpOrigin } from '@fabrika/email/platform'
16
16
  import { builtinEmailProviders } from '@fabrika/email/providers'
17
17
  import { createBackgroundTasks, PostgresDatabase } from '@fabrika/platform-node'
18
+ import { parseDataKey } from '../data-key'
18
19
  import { createPostgresIamRepositories } from '../db'
19
20
  import type { Env, RequestContext } from '../env'
20
21
  import { parseOAuthConfig } from '../oauth-config'
22
+ import { parseOidcSessionSeconds } from '../oidc-session'
21
23
  import { BUN_PBKDF2_COST } from '../password-crypto'
22
24
  import { parseRetention } from '../retention'
23
25
 
@@ -107,6 +109,9 @@ export async function createRuntime(source: Record<string, string | undefined> =
107
109
  { authLogDays: authLogRetentionDays, auditDays: auditRetentionDays },
108
110
  { authLogDays: 'FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS', auditDays: 'FABRIKA_IAM_AUDIT_RETENTION_DAYS' },
109
111
  )
112
+ const oidcSessionHours = source['FABRIKA_IAM_OIDC_SESSION_HOURS']
113
+ parseOidcSessionSeconds(oidcSessionHours, 'FABRIKA_IAM_OIDC_SESSION_HOURS')
114
+ parseDataKey(source['FABRIKA_IAM_DATA_KEY'])
110
115
 
111
116
  const config: ProcessConfig = {
112
117
  port: parsePort(source['PORT']),
@@ -132,12 +137,14 @@ export async function createRuntime(source: Record<string, string | undefined> =
132
137
  OAUTH_CONFIG: source['FABRIKA_IAM_OAUTH_CONFIG'] ?? '',
133
138
  AUTH_LOG_RETENTION_DAYS: authLogRetentionDays,
134
139
  AUDIT_RETENTION_DAYS: auditRetentionDays,
140
+ OIDC_SESSION_HOURS: oidcSessionHours,
135
141
  ENVIRONMENT: environment,
136
142
  LOCAL_DEV_LOGIN: source['LOCAL_DEV_LOGIN'] ?? '',
137
143
  ISSUER: issuer,
138
144
  // Empty off-local is refused by `getSigner`, not here — one owner for that rule.
139
145
  FABRIKA_IAM_SIGNING_KEYS: source['FABRIKA_IAM_SIGNING_KEYS'] ?? '',
140
146
  FABRIKA_IAM_PROVISIONING_KEY: source['FABRIKA_IAM_PROVISIONING_KEY'] ?? '',
147
+ FABRIKA_IAM_DATA_KEY: source['FABRIKA_IAM_DATA_KEY'],
141
148
  OIDC_ENABLED: String(oidcEnabled),
142
149
  PASSWORD_ENABLED: String(passwordEnabled),
143
150
  OIDC_ISSUER: oidcIssuer,
package/src/oauth.ts CHANGED
@@ -15,7 +15,7 @@ import type {
15
15
  OAuthTokenResponse,
16
16
  } from '@fabrika/iam-contract'
17
17
  import { uuidv7 } from '@fabrika/platform'
18
- import { sessionUsable } from './auth'
18
+ import { sessionEndsAt, sessionUsable } from './auth'
19
19
  import { type AuditEventInput, type OAuthGrantRow, type PrincipalRow, principalStatus, type SessionRow } from './db'
20
20
  import type { Env } from './env'
21
21
  import { parseJsonOrNull } from './json'
@@ -239,12 +239,16 @@ export async function grantAuthority(
239
239
  const ceiling = scopes === null ? null : scopeCeiling(resource, scopes)
240
240
  if (scopes === null || ceiling === null) return null
241
241
  const session = await services.repositories.sessions.getActiveSessionById(grant.session_id)
242
- if (session === null || session.app !== null || session.principal_id !== grant.principal_id || !sessionUsable(session, services.config)) return null
242
+ if (session === null || session.app !== null || session.principal_id !== grant.principal_id || !sessionUsable(session, services.config, now)) {
243
+ return null
244
+ }
243
245
  const principal = await services.repositories.principals.getPrincipalById(grant.principal_id)
244
246
  if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') return null
245
247
  const live = await resolveAuthorityAt(services, principal, grant.app)
246
248
  const permissions = narrowPermissions(live.permissions, ceiling)
247
- return { principal, scopes, permissions, expiresAt: authorityDeadline(live, permissions, now) }
249
+ // A refreshed token ends with its login too: an OIDC login issued before the cap stores a later expiry than its end.
250
+ const expiresAt = Math.min(authorityDeadline(live, permissions, now) ?? Number.POSITIVE_INFINITY, sessionEndsAt(session, services.config))
251
+ return { principal, scopes, permissions, expiresAt }
248
252
  }
249
253
 
250
254
  /** The union of the scopes' grants, or null when a scope is no longer configured. */
@@ -0,0 +1,25 @@
1
+ /**
2
+ * How long an OIDC login lasts before IAM sends its holder back to the provider, in hours. The provider is where an
3
+ * organization blocks a person, so this bounds how long a person blocked there keeps fabrika access.
4
+ */
5
+ export const DEFAULT_OIDC_SESSION_HOURS = 12
6
+
7
+ /** The longest cap: the lifetime of every IAM login (`SESSION_TTL_SECONDS`, 30 days). */
8
+ export const MAX_OIDC_SESSION_HOURS = 30 * 24
9
+
10
+ const HOURS = /^[1-9][0-9]{0,2}$/
11
+
12
+ /**
13
+ * Parse the cap into seconds. Unset or empty means the default; anything but a whole number of hours from 1 to 720 is
14
+ * refused, so a typo fails the boot instead of capping at a value nobody chose.
15
+ */
16
+ export function parseOidcSessionSeconds(raw: string | undefined, name = 'OIDC_SESSION_HOURS'): number {
17
+ if (raw === undefined || raw.trim() === '') {
18
+ return DEFAULT_OIDC_SESSION_HOURS * 3600
19
+ }
20
+ const value = raw.trim()
21
+ if (!HOURS.test(value) || Number.parseInt(value, 10) > MAX_OIDC_SESSION_HOURS) {
22
+ throw new Error(`${name} must be a whole number of hours from 1 to ${MAX_OIDC_SESSION_HOURS}`)
23
+ }
24
+ return Number.parseInt(value, 10) * 3600
25
+ }
@@ -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