@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
package/fabrika.config.ts CHANGED
@@ -6,10 +6,20 @@
6
6
  // them as plaintext. The Custom Domain route comes from `ctx.domain` (`FABRIKA_IAM_HOSTNAME` in the
7
7
  // standalone Oblaka adapter).
8
8
 
9
+ import { CONTROL_APP_ID, CONTROL_CLI_RESOURCES } from '@fabrika/control-contract'
9
10
  import { type EmailTransportConfig, readEmailTransportConfig } from '@fabrika/email'
10
11
  import { isHttpOrigin } from '@fabrika/email/platform'
11
12
  import { builtinEmailProviders } from '@fabrika/email/providers'
12
- import { D1Database, defineApp, platformNames, type ResourceContext, Worker } from '@fabrika/provider-cloudflare'
13
+ import type { OAuthResourceDto } from '@fabrika/iam-contract'
14
+ import {
15
+ D1Database,
16
+ defineApp,
17
+ NO_IMPORTABLE_ENV_FLAG,
18
+ NO_PROCESS_ENV_FLAG,
19
+ platformNames,
20
+ type ResourceContext,
21
+ Worker,
22
+ } from '@fabrika/provider-cloudflare'
13
23
 
14
24
  // Keep the legacy Oblaka namespace so the first fabrika deploy continues the existing cf-state.
15
25
  const IAM_APP_ID = 'propustka'
@@ -98,6 +108,26 @@ const controlUrl = (source: EnvironmentSource): string | undefined => {
98
108
  return raw
99
109
  }
100
110
 
111
+ /**
112
+ * IAM's `OAUTH_CONFIG` on a Cloudflare installation: the command-line client's resources on the console's origin,
113
+ * recomputed on every deploy so a release that changes the presets converges with no other step. No MCP client: a
114
+ * Worker console serves no `/mcp`. Without a console origin OAuth stays off.
115
+ */
116
+ const oauthConfig = (control: string | undefined): string => {
117
+ if (control === undefined) return ''
118
+ const resources: OAuthResourceDto[] = CONTROL_CLI_RESOURCES.map(({ path, grants }) => ({
119
+ app: CONTROL_APP_ID,
120
+ resource: `${control}${path}`,
121
+ scopeGrants: grants.map((grant) => ({
122
+ scope: grant.scope,
123
+ ...(grant.parameter === undefined ? {} : { parameter: grant.parameter }),
124
+ permissions: grant.actions.map((action) => ({ action })),
125
+ })),
126
+ client: 'cli',
127
+ }))
128
+ return JSON.stringify({ clients: [], resources })
129
+ }
130
+
101
131
  const remoteConfig = (env: string, domain: string | undefined, source: EnvironmentSource): RemoteConfig => {
102
132
  const authentication = authenticationConfig(source)
103
133
  const email = emailConfig(source)
@@ -161,11 +191,11 @@ const buildVars = (config: RemoteConfig | 'local', source: EnvironmentSource): R
161
191
 
162
192
  return {
163
193
  HUMAN_EMAIL_DOMAINS: config.humanEmailDomains,
164
- OAUTH_CONFIG: source['FABRIKA_IAM_OAUTH_CONFIG'] ?? '',
194
+ OAUTH_CONFIG: oauthConfig(config.controlUrl),
165
195
  // Only when named: an empty ADMIN_AUDIENCES means "no JWT may administer", so a `?? ''`
166
196
  // default would lock the console out of every install instead of falling back to its app id.
167
197
  ...(config.adminAudiences === undefined ? {} : { ADMIN_AUDIENCES: config.adminAudiences }),
168
- ...retentionVars(source),
198
+ ...settingVars(source),
169
199
  HUMAN_EMAILS: source['FABRIKA_IAM_HUMAN_EMAILS'] ?? '[]',
170
200
  IAM_BOOTSTRAP_ADMINS: source['FABRIKA_IAM_BOOTSTRAP_ADMINS'] ?? '[]',
171
201
  ISSUER: `https://${config.domain}`,
@@ -180,13 +210,18 @@ const buildVars = (config: RemoteConfig | 'local', source: EnvironmentSource): R
180
210
  }
181
211
  }
182
212
 
183
- /** The operator's retention settings, only where set: unset keeps IAM's defaults (30 days, audit kept). */
184
- const retentionVars = (source: EnvironmentSource): Record<string, string> => {
213
+ /**
214
+ * The operator's retention and OIDC session settings, only where set: unset keeps IAM's defaults (30 days, audit
215
+ * kept, a 12-hour OIDC login).
216
+ */
217
+ const settingVars = (source: EnvironmentSource): Record<string, string> => {
185
218
  const authLog = source['FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS']
186
219
  const audit = source['FABRIKA_IAM_AUDIT_RETENTION_DAYS']
220
+ const oidcSession = source['FABRIKA_IAM_OIDC_SESSION_HOURS']
187
221
  return {
188
222
  ...(authLog === undefined || authLog === '' ? {} : { AUTH_LOG_RETENTION_DAYS: authLog }),
189
223
  ...(audit === undefined || audit === '' ? {} : { AUDIT_RETENTION_DAYS: audit }),
224
+ ...(oidcSession === undefined || oidcSession === '' ? {} : { OIDC_SESSION_HOURS: oidcSession }),
190
225
  }
191
226
  }
192
227
 
@@ -195,9 +230,9 @@ export const iamPipelineVars = (source: EnvironmentSource): string[] => {
195
230
  const email = emailConfig(source)
196
231
  return [
197
232
  'FABRIKA_IAM_ADMIN_AUDIENCES',
198
- 'FABRIKA_IAM_OAUTH_CONFIG',
199
233
  'FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS',
200
234
  'FABRIKA_IAM_AUDIT_RETENTION_DAYS',
235
+ 'FABRIKA_IAM_OIDC_SESSION_HOURS',
201
236
  'FABRIKA_IAM_OIDC_ENABLED',
202
237
  'FABRIKA_IAM_PASSWORD_ENABLED',
203
238
  'FABRIKA_EMAIL_PROVIDER',
@@ -215,6 +250,8 @@ export const iamPipelineSecrets = (source: EnvironmentSource): string[] => {
215
250
  return [
216
251
  'FABRIKA_IAM_SIGNING_KEYS',
217
252
  'FABRIKA_IAM_PROVISIONING_KEY',
253
+ // Optional: an installation from before TOTP has none until its operator adds it, and must keep deploying.
254
+ ...(source['FABRIKA_IAM_DATA_KEY'] ? ['FABRIKA_IAM_DATA_KEY'] : []),
218
255
  ...(authentication.oidcEnabled ? ['OIDC_CLIENT_SECRET'] : []),
219
256
  ...emailVariableNames(email, true),
220
257
  ]
@@ -238,7 +275,10 @@ export const buildIamWorker = (ctx: ResourceContext, source: EnvironmentSource =
238
275
  dir: '.',
239
276
  name: names.iamWorker,
240
277
  main: './src/index.ts',
241
- compatibility_flags: ['nodejs_compat_v2'],
278
+ // `process.env` and the importable `env` of `cloudflare:workers` stay empty: otherwise each could hold every secret,
279
+ // the signing keys included, for any bundled module to read (`nodejs_compat_v2` alone already leaves `process.env`
280
+ // empty). IAM reads its configuration from the Worker's `env` only.
281
+ compatibility_flags: ['nodejs_compat_v2', NO_PROCESS_ENV_FLAG, NO_IMPORTABLE_ENV_FLAG],
242
282
  compatibility_date: '2025-10-01',
243
283
  // This is the public auth surface. Control reaches admin APIs over a service binding.
244
284
  routes: domain === undefined ? [] : [{ pattern: domain, custom_domain: true }],
@@ -0,0 +1,29 @@
1
+ -- A person's second factor: one TOTP authenticator and its one-time recovery codes. SQLite/D1 dialect;
2
+ -- `../migrations-postgres/0032_second_factor.sql` states the same outcome.
3
+ --
4
+ -- The TOTP secret is sealed under `FABRIKA_IAM_DATA_KEY` (`src/data-key.ts`): a fresh data key per value encrypts it
5
+ -- (AES-256-GCM), the installation's key wraps that data key, and the principal id is the associated data of both, so a
6
+ -- sealed value moved into another principal's row does not open. `confirmed_at` is NULL while the enrolment waits for
7
+ -- its first valid code; only a confirmed row asks a sign-in for a code. `last_step` is the TOTP time step of the last
8
+ -- accepted code, so a code is accepted once. `confirmation_id` names the one confirmation that wrote the
9
+ -- recovery codes, so a repeated confirmation in the same second writes none. A recovery code is stored as its SHA-256 hash only.
10
+ CREATE TABLE second_factors (
11
+ principal_id TEXT PRIMARY KEY REFERENCES principals(id) ON DELETE CASCADE,
12
+ ciphertext TEXT NOT NULL,
13
+ value_iv TEXT NOT NULL,
14
+ wrapped_dek TEXT NOT NULL,
15
+ dek_iv TEXT NOT NULL,
16
+ created_at INTEGER NOT NULL,
17
+ confirmed_at INTEGER,
18
+ last_step INTEGER,
19
+ confirmation_id TEXT
20
+ );
21
+
22
+ CREATE TABLE second_factor_recovery_codes (
23
+ code_hash TEXT PRIMARY KEY,
24
+ principal_id TEXT NOT NULL REFERENCES principals(id) ON DELETE CASCADE,
25
+ created_at INTEGER NOT NULL,
26
+ used_at INTEGER
27
+ );
28
+
29
+ CREATE INDEX idx_second_factor_recovery_codes_principal ON second_factor_recovery_codes(principal_id);
@@ -0,0 +1,6 @@
1
+ -- An OAuth grant given for several resources of one app. SQLite/D1 dialect;
2
+ -- `../migrations-postgres/0033_oauth_grant_resources.sql` states the same outcome.
3
+ --
4
+ -- `resources` is a JSON array of every resource the grant covers; each token it mints names one of them. NULL keeps
5
+ -- the meaning every earlier grant has: `resource` is the only one.
6
+ ALTER TABLE oauth_grants ADD COLUMN resources TEXT;
@@ -0,0 +1,24 @@
1
+ -- RFC 8628 device authorization attempts of the OAuth server. SQLite/D1 dialect;
2
+ -- `../migrations-postgres/0034_oauth_device_authorizations.sql` states the same outcome.
3
+ --
4
+ -- Only hashes of the device code and the user code are stored. An attempt lives five minutes. A person approving it
5
+ -- binds it to their IAM session and picks the grant's end; the grant itself is written when the device redeems the
6
+ -- approval, and `grant_id` names it then, so a device code presented again revokes that grant.
7
+ CREATE TABLE oauth_device_authorizations (
8
+ device_code_hash TEXT PRIMARY KEY,
9
+ user_code_hash TEXT NOT NULL UNIQUE,
10
+ client_id TEXT NOT NULL,
11
+ app TEXT NOT NULL,
12
+ resources TEXT NOT NULL,
13
+ scopes TEXT NOT NULL,
14
+ interval_seconds INTEGER NOT NULL,
15
+ next_poll_at INTEGER NOT NULL,
16
+ created_at INTEGER NOT NULL,
17
+ expires_at INTEGER NOT NULL,
18
+ status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'denied', 'redeemed')),
19
+ principal_id TEXT REFERENCES principals(id) ON DELETE CASCADE,
20
+ session_id TEXT REFERENCES sessions(id) ON DELETE CASCADE,
21
+ grant_expires_at INTEGER,
22
+ grant_id TEXT
23
+ );
24
+ CREATE INDEX idx_oauth_device_authorizations_expires ON oauth_device_authorizations(expires_at);
@@ -0,0 +1,29 @@
1
+ -- A person's second factor: one TOTP authenticator and its one-time recovery codes. Postgres dialect;
2
+ -- `../migrations/0032_second_factor.sql` states the same outcome.
3
+ --
4
+ -- The TOTP secret is sealed under `FABRIKA_IAM_DATA_KEY` (`src/data-key.ts`): a fresh data key per value encrypts it
5
+ -- (AES-256-GCM), the installation's key wraps that data key, and the principal id is the associated data of both, so a
6
+ -- sealed value moved into another principal's row does not open. `confirmed_at` is NULL while the enrolment waits for
7
+ -- its first valid code; only a confirmed row asks a sign-in for a code. `last_step` is the TOTP time step of the last
8
+ -- accepted code, so a code is accepted once. `confirmation_id` names the one confirmation that wrote the
9
+ -- recovery codes, so a repeated confirmation in the same second writes none. A recovery code is stored as its SHA-256 hash only.
10
+ CREATE TABLE second_factors (
11
+ principal_id TEXT PRIMARY KEY REFERENCES principals(id) ON DELETE CASCADE,
12
+ ciphertext TEXT NOT NULL,
13
+ value_iv TEXT NOT NULL,
14
+ wrapped_dek TEXT NOT NULL,
15
+ dek_iv TEXT NOT NULL,
16
+ created_at INTEGER NOT NULL,
17
+ confirmed_at INTEGER,
18
+ last_step INTEGER,
19
+ confirmation_id TEXT
20
+ );
21
+
22
+ CREATE TABLE second_factor_recovery_codes (
23
+ code_hash TEXT PRIMARY KEY,
24
+ principal_id TEXT NOT NULL REFERENCES principals(id) ON DELETE CASCADE,
25
+ created_at INTEGER NOT NULL,
26
+ used_at INTEGER
27
+ );
28
+
29
+ CREATE INDEX idx_second_factor_recovery_codes_principal ON second_factor_recovery_codes(principal_id);
@@ -0,0 +1,6 @@
1
+ -- An OAuth grant given for several resources of one app. Postgres dialect;
2
+ -- `../migrations/0033_oauth_grant_resources.sql` states the same outcome.
3
+ --
4
+ -- `resources` is a JSON array of every resource the grant covers; each token it mints names one of them. NULL keeps
5
+ -- the meaning every earlier grant has: `resource` is the only one.
6
+ ALTER TABLE oauth_grants ADD COLUMN resources TEXT;
@@ -0,0 +1,24 @@
1
+ -- RFC 8628 device authorization attempts of the OAuth server. Postgres dialect;
2
+ -- `../migrations/0034_oauth_device_authorizations.sql` states the same outcome.
3
+ --
4
+ -- Only hashes of the device code and the user code are stored. An attempt lives five minutes. A person approving it
5
+ -- binds it to their IAM session and picks the grant's end; the grant itself is written when the device redeems the
6
+ -- approval, and `grant_id` names it then, so a device code presented again revokes that grant.
7
+ CREATE TABLE oauth_device_authorizations (
8
+ device_code_hash TEXT PRIMARY KEY,
9
+ user_code_hash TEXT NOT NULL UNIQUE,
10
+ client_id TEXT NOT NULL,
11
+ app TEXT NOT NULL,
12
+ resources TEXT NOT NULL,
13
+ scopes TEXT NOT NULL,
14
+ interval_seconds INTEGER NOT NULL,
15
+ next_poll_at INTEGER NOT NULL,
16
+ created_at INTEGER NOT NULL,
17
+ expires_at INTEGER NOT NULL,
18
+ status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'denied', 'redeemed')),
19
+ principal_id TEXT REFERENCES principals(id) ON DELETE CASCADE,
20
+ session_id TEXT REFERENCES sessions(id) ON DELETE CASCADE,
21
+ grant_expires_at INTEGER,
22
+ grant_id TEXT
23
+ );
24
+ CREATE INDEX idx_oauth_device_authorizations_expires ON oauth_device_authorizations(expires_at);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/iam",
3
- "version": "0.9.0-dev.32",
3
+ "version": "0.9.0-dev.34",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/contember/fabrika-platform.git",
@@ -56,16 +56,18 @@
56
56
  "prune:auth-log": "bun src/node/prune.ts"
57
57
  },
58
58
  "dependencies": {
59
- "@fabrika/app": "0.9.0-dev.32",
60
- "@fabrika/auth": "0.9.0-dev.32",
61
- "@fabrika/auth-core": "0.9.0-dev.32",
62
- "@fabrika/email": "0.9.0-dev.32",
63
- "@fabrika/iam-contract": "0.9.0-dev.32",
64
- "@fabrika/platform": "0.9.0-dev.32",
65
- "@fabrika/platform-node": "0.9.0-dev.32",
66
- "@fabrika/provider-cloudflare": "0.9.0-dev.32",
67
- "@fabrika/proxy-core": "0.9.0-dev.32",
59
+ "@fabrika/app": "0.9.0-dev.34",
60
+ "@fabrika/auth": "0.9.0-dev.34",
61
+ "@fabrika/auth-core": "0.9.0-dev.34",
62
+ "@fabrika/control-contract": "0.9.0-dev.34",
63
+ "@fabrika/email": "0.9.0-dev.34",
64
+ "@fabrika/iam-contract": "0.9.0-dev.34",
65
+ "@fabrika/platform": "0.9.0-dev.34",
66
+ "@fabrika/platform-node": "0.9.0-dev.34",
67
+ "@fabrika/provider-cloudflare": "0.9.0-dev.34",
68
+ "@fabrika/proxy-core": "0.9.0-dev.34",
68
69
  "jose": "^5.9.0",
70
+ "uqr": "^0.1.3",
69
71
  "zod": "^3.25.76"
70
72
  }
71
73
  }
@@ -5,6 +5,7 @@ import {
5
5
  type ApiKeyDto,
6
6
  type ApiKeyIdInput,
7
7
  type CursorList,
8
+ type GetApiKeyResponse,
8
9
  type ListApiKeysInput,
9
10
  type OkResponse,
10
11
  type ProvisionApiKeyRequest,
@@ -18,7 +19,7 @@ import { contractGrantProblem } from '../contract-rules'
18
19
  import { type CredentialRow, type GrantRow, type PrincipalRow, principalStatus } from '../db'
19
20
  import { generateToken, hashToken } from '../secret'
20
21
  import { type AdminContext, adminEvent, fail } from './context'
21
- import { appField, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDtos } from './grant-support'
22
+ import { appField, grantAuthorLabels, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDtos } from './grant-support'
22
23
  import { cursorOf, groupBy, normalizeLimit } from './pagination'
23
24
 
24
25
  /**
@@ -67,8 +68,8 @@ async function apiKeyPrincipal(c: AdminContext, principalId: string): Promise<Pr
67
68
  return principal
68
69
  }
69
70
 
70
- /** One key with its grants and its live credential, for the console's key page. */
71
- export async function getApiKeyUseCase(c: AdminContext, input: ApiKeyIdInput): Promise<ApiKeyDetail> {
71
+ /** One key with its grants, each naming who granted it, and its live credential, for the console's key page. */
72
+ export async function getApiKeyUseCase(c: AdminContext, input: ApiKeyIdInput): Promise<GetApiKeyResponse> {
72
73
  const { principalId } = input
73
74
  const { grants, credentials } = c.services.repositories
74
75
  const principal = await apiKeyPrincipal(c, principalId)
@@ -77,8 +78,17 @@ export async function getApiKeyUseCase(c: AdminContext, input: ApiKeyIdInput): P
77
78
  }
78
79
  // `listCredentialsForPrincipal` is newest-first and rotation revokes every older key, so this is the live one.
79
80
  const live = (await credentials.listCredentialsForPrincipal(principalId)).find((row) => row.revoked_at === null)
80
- const dto = await toApiKeyDto(c, principal, await grants.listGrants(principalId), new RoleKnownCache(c.services))
81
- return { ...dto, credential: credentialDto(live) }
81
+ const rows = await grants.listGrants(principalId)
82
+ const dto = await toApiKeyDto(c, principal, rows, new RoleKnownCache(c.services))
83
+ const authors = await grantAuthorLabels(rows, c.services)
84
+ return {
85
+ ...dto,
86
+ grants: dto.grants.map((grant) => ({
87
+ ...grant,
88
+ grantedByLabel: grant.grantedBy === null ? null : authors.get(grant.grantedBy) ?? grant.grantedBy,
89
+ })),
90
+ credential: credentialDto(live),
91
+ }
82
92
  }
83
93
 
84
94
  function credentialDto(live: CredentialRow | undefined): ApiKeyDetail['credential'] {
@@ -70,6 +70,16 @@ export async function toGrantDtos(rows: GrantRow[], services: Services, cache: R
70
70
  return out
71
71
  }
72
72
 
73
+ /** The label of each principal who granted one of `rows`; an author no longer known reads as its id. */
74
+ export async function grantAuthorLabels(rows: GrantRow[], services: Services): Promise<Map<string, string>> {
75
+ const authors = [...new Set(rows.flatMap((row) => row.granted_by === null ? [] : [row.granted_by]))]
76
+ return new Map(
77
+ await Promise.all(
78
+ authors.map(async (author) => [author, (await services.repositories.principals.getPrincipalById(author))?.label ?? author] as const),
79
+ ),
80
+ )
81
+ }
82
+
73
83
  /** The set of app ids IAM knows about — the live registry derived from the schema tables. */
74
84
  export function knownApps(c: AdminContext): Promise<string[]> {
75
85
  return c.services.repositories.appSchema.listKnownApps()
@@ -147,7 +147,10 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
147
147
  other.id !== grant.id && other.app === grant.app && other.role_key === authorization.roleKey
148
148
  && other.scope_type === scope.scopeType && other.scope_value === scope.scopeValue
149
149
  )
150
- if (await duplicate()) return fail(409, 'This user already has that role in this scope. Edit the existing access instead.')
150
+ const held = principal.type === 'user'
151
+ ? 'This user already has that role in this scope. Edit the existing access instead.'
152
+ : 'This key already has that role in this scope. Edit the existing grant instead.'
153
+ if (await duplicate()) return fail(409, held)
151
154
  let updated: GrantRow | null
152
155
  try {
153
156
  updated = await c.services.repositories.grants.updateGrant(
@@ -177,7 +180,7 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
177
180
  }),
178
181
  )
179
182
  } catch (cause) {
180
- if (await duplicate()) return fail(409, 'This user already has that role in this scope. Edit the existing access instead.')
183
+ if (await duplicate()) return fail(409, held)
181
184
  throw cause
182
185
  }
183
186
  if (updated === null) return fail(409, 'The access changed or is no longer allowed. Refresh and try again.')
@@ -17,6 +17,7 @@ import { getPasswordPolicyUseCase, setPasswordPolicyUseCase } from './password-p
17
17
  import { disablePasswordUseCase, issuePasswordEnrollmentUseCase, issuePasswordResetUseCase } from './passwords'
18
18
  import { createPolicyUseCase, deletePolicyUseCase, listPoliciesUseCase, updatePolicyUseCase } from './policies'
19
19
  import { getPrincipalUseCase, invitePrincipalUseCase, listPrincipalsUseCase, me, promotePrincipalUseCase, updatePrincipalUseCase } from './principals'
20
+ import { getSecondFactorUseCase, resetSecondFactorUseCase } from './second-factor'
20
21
  import { listSessionsUseCase, revokeSessionsForPrincipalUseCase, revokeSessionUseCase } from './sessions'
21
22
  import { createShareLinkUseCase, listShareLinksUseCase, revokeShareLinkUseCase } from './share-links'
22
23
  import { listTerminalsUseCase, revokeTerminalUseCase, setTerminalProfileUseCase } from './terminals'
@@ -93,6 +94,8 @@ export const adminUseCases = {
93
94
  clearInstallationBrand: clearInstallationBrandUseCase,
94
95
  getPasswordPolicy: getPasswordPolicyUseCase,
95
96
  setPasswordPolicy: setPasswordPolicyUseCase,
97
+ getSecondFactor: getSecondFactorUseCase,
98
+ resetSecondFactor: resetSecondFactorUseCase,
96
99
  listTerminals: listTerminalsUseCase,
97
100
  setTerminalProfile: setTerminalProfileUseCase,
98
101
  revokeTerminal: revokeTerminalUseCase,
@@ -14,7 +14,7 @@ import { normalizeEmailIdentity } from '../email-identity'
14
14
  import { resolvePermissionsAt } from '../resolve'
15
15
  import { listRolesUseCase } from './app-schema'
16
16
  import { type AdminContext, adminEvent, fail } from './context'
17
- import { toGrantDtos } from './grant-support'
17
+ import { grantAuthorLabels, toGrantDtos } from './grant-support'
18
18
  import { cursorOf, normalizeLimit } from './pagination'
19
19
  import { canManagePrincipal, managesApp, requireActableTarget, requireInvitableMailbox } from './user-admin'
20
20
 
@@ -79,10 +79,7 @@ export async function getPrincipalUseCase(c: AdminContext, input: PrincipalIdInp
79
79
  const roles = new Map(
80
80
  await Promise.all([...new Set(grants.map((grant) => grant.app))].map(async (app) => [app, (await listRolesUseCase(c, { app })).items] as const)),
81
81
  )
82
- const authors = new Map(
83
- await Promise.all([...new Set(grants.flatMap((grant) => grant.granted_by === null ? [] : [grant.granted_by]))]
84
- .map(async (author) => [author, (await c.services.repositories.principals.getPrincipalById(author))?.label ?? author] as const)),
85
- )
82
+ const authors = await grantAuthorLabels(grants, c.services)
86
83
  const grantDetails: PrincipalGrantDto[] = (await toGrantDtos(grants, c.services)).map((grant) => {
87
84
  const role = roles.get(grant.app)?.find((role) => role.key === grant.roleKey)
88
85
  return {
package/src/admin/rpc.ts CHANGED
@@ -253,6 +253,14 @@ export const adminRpcRouter: RpcRouterFor<IamAppContext, IamAdminRpcContract> =
253
253
  .require(ADMIN_ACTION)
254
254
  .mutation(({ ctx, input }) => adminUseCases.setPasswordPolicy(context(ctx), input)),
255
255
  }),
256
+ // A person's authenticator: `iam.admin` only, to read and to reset. The reset is the operator's path for a lost phone.
257
+ secondFactor: t.router({
258
+ get: t.procedure.input(principalIdInput).require(ADMIN_ACTION).query(({ ctx, input }) => adminUseCases.getSecondFactor(context(ctx), input)),
259
+ reset: t.procedure
260
+ .input(principalIdInput)
261
+ .require(ADMIN_ACTION)
262
+ .mutation(({ ctx, input }) => adminUseCases.resetSecondFactor(context(ctx), input)),
263
+ }),
256
264
  })
257
265
 
258
266
  /** Resolve the admin behind an `/admin/rpc` request, then run `next` with it on `ctx`; anyone else is refused. */
@@ -0,0 +1,39 @@
1
+ // A person's second factor (TOTP), as an installation administrator reads and resets it. The reset is the operator's
2
+ // path for a lost phone: it removes the authenticator and every recovery code, so the next sign-in asks for no code
3
+ // and the person enrols again at IAM's `/auth/second-factor/enrol`.
4
+
5
+ import type { PrincipalIdInput, SecondFactorDto } from '@fabrika/iam-contract'
6
+ import { type AdminContext, adminEvent, fail } from './context'
7
+
8
+ export async function getSecondFactorUseCase(c: AdminContext, input: PrincipalIdInput): Promise<SecondFactorDto> {
9
+ requireInstallationAdmin(c)
10
+ await requirePrincipal(c, input.principalId)
11
+ return secondFactorDto(c, input.principalId)
12
+ }
13
+
14
+ /** Remove the authenticator and recovery codes, recorded as `iam.second_factor.reset`; a principal without one records nothing. */
15
+ export async function resetSecondFactorUseCase(c: AdminContext, input: PrincipalIdInput): Promise<SecondFactorDto> {
16
+ requireInstallationAdmin(c)
17
+ await requirePrincipal(c, input.principalId)
18
+ await c.services.repositories.secondFactors.reset(
19
+ input.principalId,
20
+ adminEvent(c, { action: 'iam.second_factor.reset', resourceType: 'principal', resourceId: input.principalId }),
21
+ )
22
+ return secondFactorDto(c, input.principalId)
23
+ }
24
+
25
+ async function secondFactorDto(c: AdminContext, principalId: string): Promise<SecondFactorDto> {
26
+ const status = await c.services.repositories.secondFactors.status(principalId)
27
+ return { enrolledAt: status.confirmedAt, recoveryCodesLeft: status.recoveryCodesLeft, available: c.services.dataKey !== null }
28
+ }
29
+
30
+ async function requirePrincipal(c: AdminContext, principalId: string): Promise<void> {
31
+ if (await c.services.repositories.principals.getPrincipalById(principalId) === null) fail(404, 'principal not found')
32
+ }
33
+
34
+ /** `.require(iam.admin)` gates these procedures already; a direct caller of a use case meets the same rule. */
35
+ function requireInstallationAdmin(c: AdminContext): void {
36
+ if (c.administration.kind !== 'installation') {
37
+ return fail(403, 'a second factor is read and reset only by an installation administrator')
38
+ }
39
+ }
@@ -6,7 +6,7 @@ import {
6
6
  type SessionIdInput,
7
7
  type SessionList,
8
8
  } from '@fabrika/iam-contract'
9
- import { sessionUsable } from '../auth'
9
+ import { sessionEndsAt, sessionUsable } from '../auth'
10
10
  import type { ListedSessionRow } from '../repositories/sessions'
11
11
 
12
12
  import { type AdminContext, adminEvent, fail } from './context'
@@ -18,13 +18,13 @@ import { requireActableTarget } from './user-admin'
18
18
  function toSessionDto(c: AdminContext, row: ListedSessionRow, now: number, disabled: boolean): SessionDto {
19
19
  const unavailableReason = row.revoked_at !== null
20
20
  ? 'revoked'
21
- : row.expires_at <= now
21
+ : sessionEndsAt(row, c.services.config) <= now
22
22
  ? 'expired'
23
23
  : row.parent_session_id !== null && (row.parent_expires_at === null || row.parent_expires_at <= now || row.parent_revoked_at !== null)
24
24
  ? 'parent_ended'
25
25
  : disabled
26
26
  ? 'account_disabled'
27
- : !sessionUsable(row, c.services.config)
27
+ : !sessionUsable(row, c.services.config, now)
28
28
  ? 'method_disabled'
29
29
  : null
30
30
  return {
@@ -35,7 +35,7 @@ function toSessionDto(c: AdminContext, row: ListedSessionRow, now: number, disab
35
35
  parentSessionId: row.parent_session_id,
36
36
  status: row.revoked_at !== null ? 'revoked' : row.expires_at <= now ? 'expired' : 'active',
37
37
  createdAt: row.created_at,
38
- expiresAt: row.expires_at,
38
+ expiresAt: sessionEndsAt(row, c.services.config),
39
39
  revokedAt: row.revoked_at,
40
40
  unavailableReason,
41
41
  }
package/src/app.ts CHANGED
@@ -96,7 +96,7 @@ export function createIamApp(options: IamAppOptions = {}): FetchService<Env> {
96
96
  const serve = (handle: (ctx: IamAppContext) => Response | Promise<Response>): ServiceHandler<Env> => async ({ request, env, exec }) =>
97
97
  handle(await context(request, env, exec))
98
98
  const auth = serve((ctx) => handleAuth(ctx.request, ctx.services, ctx.env, ctx.exec, ctx.clientAddress, ctx.requestId))
99
- const oauth = serve((ctx) => handleOAuth(ctx.request, ctx.services, ctx.env, ctx.requestId))
99
+ const oauth = serve((ctx) => handleOAuth(ctx.request, ctx.services, ctx.env, ctx.requestId, ctx.clientAddress))
100
100
  const admin = serve((ctx) => handleAdmin(ctx.request, ctx.services, ctx.env, ctx.exec, ctx.requestId))
101
101
  const mint = serve((ctx) => handleMintHttp(ctx.request, createIamRpc(ctx.env, ctx.exec), options.proxyKey ?? ''))
102
102
  const rpc = serve((ctx) => handleRpcHttp(ctx.request, createIamRpc(ctx.env, ctx.exec), options.rpcKey ?? ''))
@@ -21,5 +21,10 @@ export type AuthFailure =
21
21
  | { readonly kind: 'terminal_enrolment_unavailable' }
22
22
  /** A terminal identification completed by another browser, twice, too late, or after its login ended. */
23
23
  | { readonly kind: 'terminal_completion_refused' }
24
+ /** The challenge cookie of a sign-in waiting for its second factor is missing, forged or older than its five minutes. */
25
+ | { readonly kind: 'second_factor_expired' }
26
+ /** The browser holds no login of a principal that may enrol an authenticator. */
27
+ | { readonly kind: 'second_factor_not_allowed' }
28
+ | { readonly kind: 'second_factor_unavailable' }
24
29
  /** A refusal of the principal resolution; `reason` is its fixed code, never what the caller sent. */
25
30
  | { readonly kind: 'login_refused'; readonly reason: string }
package/src/auth/http.ts CHANGED
@@ -75,7 +75,7 @@ export function methodNotAllowed(): Response {
75
75
 
76
76
  /**
77
77
  * Headers for a 302 out of this surface. `no-store` belongs on every one of them, not just the
78
- * password pages: these are the responses that carry the 30-day session cookie and, on the handoff
78
+ * password pages: these are the responses that carry the session cookie and, on the handoff
79
79
  * path, the single-use code in the `Location` itself.
80
80
  */
81
81
  export function redirectHeaders(location: string): Headers {
@@ -10,6 +10,7 @@ import { validatePassword } from '../password-policy'
10
10
  import { parseLocale, rememberLocaleCookie } from '../person-locale'
11
11
  import type { Services } from '../services'
12
12
  import { methodNotAllowed, readForm, redirectHeaders, sameOrigin, stringValue } from './http'
13
+ import type { AuthEnv } from './oidc-flight'
13
14
  import { currentSession, issueSession } from './sessions'
14
15
 
15
16
  const tokenSchema = z.string().max(512).regex(/^[A-Za-z0-9_-]{32,}$/)
@@ -29,7 +30,13 @@ const tokenSchema = z.string().max(512).regex(/^[A-Za-z0-9_-]{32,}$/)
29
30
  * The link's `?app=` picks the page's language; an accepted invitation lands on its own application's
30
31
  * registered origin, where the application's proxy signs the browser in through the normal handoff.
31
32
  */
32
- export async function handleInvitation(request: Request, services: Services, ctx: RequestContext, requestId: string): Promise<Response> {
33
+ export async function handleInvitation(
34
+ request: Request,
35
+ services: Services,
36
+ env: AuthEnv,
37
+ ctx: RequestContext,
38
+ requestId: string,
39
+ ): Promise<Response> {
33
40
  const linked = await presentationFor(services, new URL(request.url).searchParams.get('app'), { request })
34
41
  if (request.method === 'GET') {
35
42
  return invitationPage(linked)
@@ -66,7 +73,7 @@ export async function handleInvitation(request: Request, services: Services, ctx
66
73
  }
67
74
  const password = stringValue(form?.get('password') ?? null)
68
75
  if (password !== null) {
69
- return createAndAccept(request, services, ctx, { invitation: offer.invitation, token: token.data, password, requestId, brand: linked.brand })
76
+ return createAndAccept(request, services, env, ctx, { invitation: offer.invitation, token: token.data, password, requestId, brand: linked.brand })
70
77
  }
71
78
  const presentation = await presentationFor(services, offer.invitation.app, { request, brand: linked.brand, locale: offer.invitation.locale })
72
79
  return invitationPasswordPage({
@@ -131,6 +138,7 @@ export async function handleInvitation(request: Request, services: Services, ctx
131
138
  async function createAndAccept(
132
139
  request: Request,
133
140
  services: Services,
141
+ env: AuthEnv,
134
142
  ctx: RequestContext,
135
143
  input: {
136
144
  readonly invitation: InvitationRow
@@ -159,7 +167,7 @@ async function createAndAccept(
159
167
  if (!outcome.ok) {
160
168
  return creationRefused(services, presentation, outcome.reason)
161
169
  }
162
- return issueSession(request, services, ctx, {
170
+ return issueSession(request, services, env, ctx, {
163
171
  principalId: outcome.principal.id,
164
172
  email: outcome.principal.email,
165
173
  authenticationMethod: 'password',
package/src/auth/login.ts CHANGED
@@ -66,7 +66,7 @@ export async function handleLogin(
66
66
  }
67
67
 
68
68
  if (services.config.localDevLogin) {
69
- return handleLocalLogin(request, services, ctx, requestId, redirect, handoff, presentation)
69
+ return handleLocalLogin(request, services, env, ctx, requestId, redirect, handoff, presentation)
70
70
  }
71
71
  if (services.config.authentication.password.enabled) {
72
72
  return loginPage({
@@ -133,6 +133,7 @@ export async function handleAccountChoice(request: Request, services: Services,
133
133
  async function handleLocalLogin(
134
134
  request: Request,
135
135
  services: Services,
136
+ env: AuthEnv,
136
137
  ctx: RequestContext,
137
138
  requestId: string,
138
139
  redirect: string | null,
@@ -148,7 +149,7 @@ async function handleLocalLogin(
148
149
  () => authFailurePage(presentation, { kind: 'login_refused', reason: `local ${resolved.reason}` }, 403),
149
150
  )
150
151
  }
151
- return issueSession(request, services, ctx, {
152
+ return issueSession(request, services, env, ctx, {
152
153
  principalId: resolved.principal.id,
153
154
  idpSub: LOCAL_DEV_ADMIN_ID,
154
155
  email: LOCAL_DEV_ADMIN_EMAIL,
package/src/auth/oidc.ts CHANGED
@@ -135,7 +135,7 @@ export async function handleCallback(
135
135
  return refuse('handoff_refused', reading.failure, 400)
136
136
  }
137
137
 
138
- return issueSession(request, services, ctx, {
138
+ return issueSession(request, services, env, ctx, {
139
139
  principalId: resolved.principal.id,
140
140
  idpSub: identity.sub,
141
141
  email: identity.email,