@fabrika/iam-contract 0.9.0-dev.5 → 0.9.0-dev.50

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.
package/src/oauth.ts CHANGED
@@ -1,11 +1,57 @@
1
- import { isCimdClientId, isOAuthResourceUri, parseOAuthScopes } from '@fabrika/auth-core'
1
+ import {
2
+ AGENT_CLIENT_ID,
3
+ BUILTIN_ROLE_KEYS,
4
+ isAgentLabel,
5
+ isCimdClientId,
6
+ isOAuthClientId,
7
+ isOAuthResourceUri,
8
+ isScopeParameterText,
9
+ parseOAuthScopes,
10
+ } from '@fabrika/auth-core'
2
11
  import type { KeyGrant } from '@fabrika/auth-core'
3
12
 
13
+ /**
14
+ * The kinds of managed client an installation registers. A label only: every kind gets the same authorization code
15
+ * flow with S256 PKCE, the same RFC 8707 resources and the same scope ceilings (ADR-0049).
16
+ */
17
+ export const OAUTH_CLIENT_PROVIDERS = ['claude', 'chatgpt', 'external'] as const
18
+ export type OAuthClientProvider = (typeof OAUTH_CLIENT_PROVIDERS)[number]
19
+
20
+ function isOAuthClientProvider(value: unknown): value is OAuthClientProvider {
21
+ return OAUTH_CLIENT_PROVIDERS.some((provider) => provider === value)
22
+ }
23
+
24
+ /**
25
+ * The one resource an identity-only client is served: its own, outside the installation. A token for it carries the
26
+ * person's identity and no permission, under `app`, an id no installation service or application holds. With `roles`,
27
+ * the application's roles are IAM's to grant: the token names those the person holds there, and a person holding none
28
+ * is refused.
29
+ */
30
+ export interface OAuthIdentityResource {
31
+ app: string
32
+ resource: string
33
+ roles?: OAuthIdentityRole[]
34
+ }
35
+
36
+ /** A role of an external application: IAM grants it and names it in the token; the application decides what it allows. */
37
+ export interface OAuthIdentityRole {
38
+ key: string
39
+ name: string
40
+ }
41
+
42
+ /** How many roles one external application declares. */
43
+ export const MAX_OAUTH_IDENTITY_ROLES = 32
44
+
45
+ /** The one scope of an identity resource: it names the person and grants nothing. */
46
+ export const OAUTH_IDENTITY_SCOPE = 'identity'
47
+
4
48
  /** Managed CIMD registrations only; public dynamic registration is not part of this contract. */
5
49
  export interface OAuthManagedClient {
6
- provider: 'chatgpt' | 'claude'
50
+ provider: OAuthClientProvider
7
51
  clientId: string
8
52
  redirectUris: string[]
53
+ /** Present only on an `external` client: it is served this resource alone, never a registered one. */
54
+ identity?: OAuthIdentityResource
9
55
  }
10
56
 
11
57
  /** RFC 7523 §2.2: the `client_assertion_type` of a JWT client assertion (`private_key_jwt`). */
@@ -36,13 +82,28 @@ export type OAuthClientMetadataDocument =
36
82
  /** How a token or revocation request authenticates its client: no credential, or a JWT assertion. */
37
83
  export type OAuthClientCredential = { method: 'none' } | { method: 'private_key_jwt'; assertion: string }
38
84
 
85
+ export interface OAuthScopeGrant {
86
+ scope: string
87
+ permissions: KeyGrant[]
88
+ /**
89
+ * A scope dimension type. Such a scope is requested only as `<scope>:<value>`, and each of its scope-less permissions
90
+ * is narrowed to `{ type: parameter, value }`: `deploy:alpha` with parameter `app` holds its actions at app `alpha` only.
91
+ */
92
+ parameter?: string
93
+ }
94
+
39
95
  export interface OAuthResourceDto {
40
96
  app: string
41
97
  resource: string
42
98
  /** IAM resolves these app-owned grants; OAuth scope text alone never authorizes an action. */
43
- scopeGrants: { scope: string; permissions: KeyGrant[] }[]
99
+ scopeGrants: OAuthScopeGrant[]
44
100
  /** Used only when scope is omitted. No configured default means invalid_scope, never all scopes. */
45
101
  defaultScopes?: string[]
102
+ /**
103
+ * `cli`: served only to the installation's command-line client, through the device grant. Absent: served only to the
104
+ * operator's managed clients, through an authorization code. A token for one never comes from the other's flow.
105
+ */
106
+ client?: 'cli'
46
107
  }
47
108
 
48
109
  /** No access token, refresh token, hash, or authorization code appears in a grant DTO. */
@@ -76,9 +137,40 @@ export type OAuthAuthorizationParseResult =
76
137
  | { kind: 'invalid_scope'; coordinates: OAuthAuthorizationCoordinates; rawScope: string }
77
138
  | { kind: 'invalid_request' }
78
139
 
140
+ /** RFC 8628 §3.4: the grant type a device client polls the token endpoint with. */
141
+ export const OAUTH_DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code'
142
+
79
143
  export type OAuthTokenRequest =
80
144
  | { grant_type: 'authorization_code'; client_id: string; code: string; redirect_uri: string; code_verifier: string; resource: string }
81
145
  | { grant_type: 'refresh_token'; client_id: string; refresh_token: string; resource: string }
146
+ | { grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE; client_id: string; device_code: string; resource: string }
147
+
148
+ /** RFC 8628 §3.1, with every resource the grant is asked for (RFC 8707): each token names one of them. */
149
+ export interface OAuthDeviceAuthorizationRequest {
150
+ client_id: string
151
+ /** Empty only for the agent client, which then asks for its default scope (ADR-0090 §2). */
152
+ scope: string[]
153
+ resources: string[]
154
+ /** The agent client's name for itself, shown to the person as the agent's own words; ignored for any other client. */
155
+ agent_label?: string
156
+ }
157
+
158
+ /** RFC 8628 §3.2. */
159
+ export interface OAuthDeviceAuthorizationResponse {
160
+ device_code: string
161
+ user_code: string
162
+ verification_uri: string
163
+ verification_uri_complete: string
164
+ expires_in: number
165
+ interval: number
166
+ }
167
+
168
+ /** The lifetimes a person picks between when approving a device: an hour, a day, a week. */
169
+ export const OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS = [3600, 86_400, 604_800] as const
170
+ export type OAuthDeviceGrantLifetime = (typeof OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS)[number]
171
+
172
+ /** How many resources one device grant may name. */
173
+ export const MAX_OAUTH_DEVICE_RESOURCES = 8
82
174
 
83
175
  export interface OAuthTokenResponse {
84
176
  access_token: string
@@ -99,9 +191,10 @@ export interface OAuthAuthorizationServerMetadata {
99
191
  authorization_endpoint: string
100
192
  token_endpoint: string
101
193
  revocation_endpoint: string
194
+ device_authorization_endpoint: string
102
195
  jwks_uri: string
103
196
  response_types_supported: ['code']
104
- grant_types_supported: ['authorization_code', 'refresh_token']
197
+ grant_types_supported: ['authorization_code', 'refresh_token', typeof OAUTH_DEVICE_CODE_GRANT_TYPE]
105
198
  code_challenge_methods_supported: ['S256']
106
199
  token_endpoint_auth_methods_supported: ['none', 'private_key_jwt']
107
200
  token_endpoint_auth_signing_alg_values_supported: OAuthClientAssertionAlgorithm[]
@@ -134,9 +227,70 @@ export function parseOAuthManagedClient(value: unknown): OAuthManagedClient | nu
134
227
  const provider = field(value, 'provider')
135
228
  const clientId = field(value, 'clientId')
136
229
  const uris = redirectUris(field(value, 'redirectUris'))
137
- return (provider === 'chatgpt' || provider === 'claude') && isCimdClientId(clientId) && uris !== null
138
- ? { provider, clientId, redirectUris: uris }
139
- : null
230
+ const rawIdentity = field(value, 'identity')
231
+ if (!isOAuthClientProvider(provider) || !isCimdClientId(clientId) || uris === null) return null
232
+ if (rawIdentity === undefined) return { provider, clientId, redirectUris: uris }
233
+ const identity = parseOAuthIdentityResource(rawIdentity)
234
+ // Claude and ChatGPT are authoring clients; only an external application signs people in for itself.
235
+ return identity === null || provider !== 'external' ? null : { provider, clientId, redirectUris: uris, identity }
236
+ }
237
+
238
+ const IDENTITY_KEYS = ['app', 'resource', 'roles']
239
+ const ROLE_KEYS = ['key', 'name']
240
+ /** An app id as every fabrika config writes one; no `@`, so never an application environment's id. */
241
+ const IDENTITY_APP = /^[a-z0-9][a-z0-9-]{0,62}$/
242
+ /** A role key; never a built-in one (`admin` means every action of an application). */
243
+ const IDENTITY_ROLE_KEY = /^[a-z0-9][a-z0-9-]{0,62}$/
244
+
245
+ /** An HTTPS URL without credentials or a fragment, where IAM may fetch a client's metadata document. */
246
+ export function isHttpsDocumentUrl(value: string): boolean {
247
+ try {
248
+ const url = new URL(value)
249
+ return url.protocol === 'https:' && url.username === '' && url.password === '' && url.hash === ''
250
+ } catch {
251
+ return false
252
+ }
253
+ }
254
+
255
+ /** An external application's id: lowercase, without `@`, at most 63 characters. */
256
+ export function isOAuthIdentityAppId(value: unknown): value is string {
257
+ return typeof value === 'string' && IDENTITY_APP.test(value)
258
+ }
259
+
260
+ /** A role key an external application may declare: lowercase like an app id, and no built-in role key. */
261
+ export function isOAuthIdentityRoleKey(value: unknown): value is string {
262
+ return typeof value === 'string' && IDENTITY_ROLE_KEY.test(value) && !BUILTIN_ROLE_KEYS.includes(value)
263
+ }
264
+
265
+ /** An identity resource binding `{ app, resource, roles? }`, or null when it is not one; unknown keys are refused. */
266
+ export function parseOAuthIdentityResource(value: unknown): OAuthIdentityResource | null {
267
+ const app = field(value, 'app')
268
+ const resource = field(value, 'resource')
269
+ const rawRoles = field(value, 'roles')
270
+ if (!hasOnlyKeys(value, IDENTITY_KEYS) || !isOAuthIdentityAppId(app) || !isOAuthResourceUri(resource)) return null
271
+ if (rawRoles === undefined) return { app, resource }
272
+ const roles = parseOAuthIdentityRoles(rawRoles)
273
+ return roles === null ? null : { app, resource, roles }
274
+ }
275
+
276
+ function parseOAuthIdentityRoles(value: unknown): OAuthIdentityRole[] | null {
277
+ if (!Array.isArray(value) || value.length === 0 || value.length > MAX_OAUTH_IDENTITY_ROLES) return null
278
+ const roles: OAuthIdentityRole[] = []
279
+ for (const entry of value) {
280
+ const key = field(entry, 'key')
281
+ const name = field(entry, 'name')
282
+ if (
283
+ !hasOnlyKeys(entry, ROLE_KEYS) || !isOAuthIdentityRoleKey(key) || !isNonemptyText(name)
284
+ || name.length > 100 || roles.some((role) => role.key === key)
285
+ ) return null
286
+ roles.push({ key, name })
287
+ }
288
+ return roles
289
+ }
290
+
291
+ /** The scopes an identity resource's authorization asks for: none, or exactly `identity`. */
292
+ export function resolveOAuthIdentityScopes(scope: string | undefined): string[] | null {
293
+ return scope === undefined || scope === OAUTH_IDENTITY_SCOPE ? [OAUTH_IDENTITY_SCOPE] : null
140
294
  }
141
295
 
142
296
  /** A fetched document cannot enlarge the managed registration's exact redirect allowlist. */
@@ -199,28 +353,54 @@ function parseClientGrantTypes(value: unknown): OAuthClientMetadataDocument['gra
199
353
  return grants.includes('authorization_code') ? grants : null
200
354
  }
201
355
 
356
+ const SCOPE_GRANT_KEYS = ['scope', 'permissions', 'parameter']
357
+ const PERMISSION_KEYS = ['action', 'scope']
358
+ const PERMISSION_SCOPE_KEYS = ['type', 'value']
359
+
360
+ function hasOnlyKeys(value: unknown, allowed: readonly string[]): boolean {
361
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).every((key) => allowed.includes(key))
362
+ }
363
+
202
364
  export function parseOAuthResourceDto(value: unknown): OAuthResourceDto | null {
203
365
  const app = field(value, 'app')
204
366
  const resource = field(value, 'resource')
205
367
  const rawGrants = field(value, 'scopeGrants')
206
368
  const rawDefaultScopes = field(value, 'defaultScopes')
369
+ const client = field(value, 'client')
370
+ if (client !== undefined && client !== 'cli') return null
207
371
  if (
208
372
  !isNonemptyText(app) || app.includes('*') || !isOAuthResourceUri(resource) || !Array.isArray(rawGrants) || rawGrants.length === 0
209
373
  || rawGrants.length > 64
210
374
  ) return null
211
- const scopeGrants: OAuthResourceDto['scopeGrants'] = []
375
+ const scopeGrants: OAuthScopeGrant[] = []
212
376
  for (const entry of rawGrants) {
377
+ // An unknown key is refused: a misspelled `parameter` would otherwise leave the scope unnarrowed.
378
+ if (!hasOnlyKeys(entry, SCOPE_GRANT_KEYS)) return null
213
379
  const scope = field(entry, 'scope')
214
380
  const permissions = parseResourcePermissions(field(entry, 'permissions'))
215
- if (typeof scope !== 'string' || parseOAuthScopes([scope]) === null || permissions === null || scopeGrants.some((grant) => grant.scope === scope)) {
381
+ const parameter = field(entry, 'parameter')
382
+ if (
383
+ typeof scope !== 'string' || parseOAuthScopes([scope]) === null || scope.includes(SCOPE_PARAMETER_SEPARATOR) || permissions === null
384
+ || scopeGrants.some((grant) => grant.scope === scope)
385
+ ) {
216
386
  return null
217
387
  }
218
- scopeGrants.push({ scope, permissions })
388
+ if (parameter === undefined) {
389
+ scopeGrants.push({ scope, permissions })
390
+ continue
391
+ }
392
+ // A parameter narrows scope-less permissions only; a permission that names its own scope would ignore it.
393
+ if (!isScopeParameterText(parameter) || permissions.some((permission) => permission.scope != null)) return null
394
+ scopeGrants.push({ scope, permissions, parameter })
219
395
  }
220
- const dto: OAuthResourceDto = { app, resource, scopeGrants }
396
+ const dto: OAuthResourceDto = { app, resource, scopeGrants, ...(client === undefined ? {} : { client }) }
221
397
  if (rawDefaultScopes !== undefined) {
222
398
  const defaultScopes = parseOAuthScopes(rawDefaultScopes)
223
- if (defaultScopes === null || !defaultScopes.every((scope) => scopeGrants.some((grant) => grant.scope === scope))) return null
399
+ if (
400
+ defaultScopes === null || !defaultScopes.every((scope) => scopeGrants.some((grant) => grant.scope === scope && grant.parameter === undefined))
401
+ ) {
402
+ return null
403
+ }
224
404
  dto.defaultScopes = defaultScopes
225
405
  }
226
406
  return dto
@@ -232,23 +412,42 @@ function parseResourcePermissions(value: unknown): KeyGrant[] | null {
232
412
  for (const entry of value) {
233
413
  const action = field(entry, 'action')
234
414
  const rawScope = field(entry, 'scope')
235
- if (!isNonemptyText(action)) return null
415
+ if (!hasOnlyKeys(entry, PERMISSION_KEYS) || !isNonemptyText(action)) return null
236
416
  if (rawScope === undefined) permissions.push({ action })
237
417
  else if (rawScope === null) permissions.push({ action, scope: null })
238
418
  else {
239
419
  const type = field(rawScope, 'type')
240
420
  const scopeValue = field(rawScope, 'value')
241
- if (!isNonemptyText(type) || !isNonemptyText(scopeValue)) return null
421
+ if (!hasOnlyKeys(rawScope, PERMISSION_SCOPE_KEYS) || !isNonemptyText(type) || !isNonemptyText(scopeValue)) return null
242
422
  permissions.push({ action, scope: { type, value: scopeValue } })
243
423
  }
244
424
  }
245
425
  return permissions
246
426
  }
247
427
 
428
+ /** Separates a parameterized scope from its value: `deploy:alpha`. */
429
+ export const SCOPE_PARAMETER_SEPARATOR = ':'
430
+
431
+ /**
432
+ * The resource's grant a requested scope token selects and the narrowed permissions it holds, or null when the token
433
+ * selects none: an unknown scope, a parameterized scope without its value, a value on a scope that takes none.
434
+ */
435
+ export function resolveOAuthScopeToken(token: string, resource: OAuthResourceDto): KeyGrant[] | null {
436
+ const separator = token.indexOf(SCOPE_PARAMETER_SEPARATOR)
437
+ const name = separator === -1 ? token : token.slice(0, separator)
438
+ const grant = resource.scopeGrants.find((entry) => entry.scope === name)
439
+ if (grant === undefined) return null
440
+ const type = grant.parameter
441
+ if (type === undefined) return separator === -1 ? grant.permissions : null
442
+ const value = separator === -1 ? null : token.slice(separator + 1)
443
+ if (value === null || !isScopeParameterText(value)) return null
444
+ return grant.permissions.map((permission) => ({ action: permission.action, scope: { type, value } }))
445
+ }
446
+
248
447
  export function resolveOAuthAuthorizationScopes(scope: string | undefined, resource: OAuthResourceDto): string[] | null {
249
448
  const scopes = scope === undefined ? resource.defaultScopes : parseOAuthScopes(scope.split(' '))
250
449
  if (!scopes || scopes.length === 0) return null
251
- return scopes.every((entry) => resource.scopeGrants.some((grant) => grant.scope === entry))
450
+ return scopes.every((entry) => resolveOAuthScopeToken(entry, resource) !== null)
252
451
  ? [...scopes]
253
452
  : null
254
453
  }
@@ -291,7 +490,7 @@ export function parseOAuthTokenRequest(value: unknown): OAuthTokenRequest | null
291
490
  const clientId = field(value, 'client_id')
292
491
  const resource = field(value, 'resource')
293
492
  const grantType = field(value, 'grant_type')
294
- if (!isCimdClientId(clientId) || !isOAuthResourceUri(resource)) return null
493
+ if (!isOAuthClientId(clientId) || !isOAuthResourceUri(resource)) return null
295
494
  if (grantType === 'authorization_code') {
296
495
  const code = field(value, 'code')
297
496
  const redirectUri = field(value, 'redirect_uri')
@@ -305,9 +504,44 @@ export function parseOAuthTokenRequest(value: unknown): OAuthTokenRequest | null
305
504
  const refreshToken = field(value, 'refresh_token')
306
505
  return isNonemptyText(refreshToken) ? { grant_type: grantType, client_id: clientId, refresh_token: refreshToken, resource } : null
307
506
  }
507
+ if (grantType === OAUTH_DEVICE_CODE_GRANT_TYPE) {
508
+ const deviceCode = field(value, 'device_code')
509
+ return isNonemptyText(deviceCode) && deviceCode.length <= 256
510
+ ? { grant_type: grantType, client_id: clientId, device_code: deviceCode, resource }
511
+ : null
512
+ }
308
513
  return null
309
514
  }
310
515
 
516
+ /**
517
+ * A device authorization request: its client, at least one scope (the agent client may name none) and one to
518
+ * `MAX_OAUTH_DEVICE_RESOURCES` distinct resources. `resource` is the one parameter that may repeat (RFC 8707 §2), so the
519
+ * caller collects it into a list.
520
+ */
521
+ export function parseOAuthDeviceAuthorizationRequest(
522
+ value: { fields: Record<string, string>; resources: string[] },
523
+ ): OAuthDeviceAuthorizationRequest | null {
524
+ const clientId = field(value.fields, 'client_id')
525
+ const scope = field(value.fields, 'scope')
526
+ if (!isOAuthClientId(clientId)) return null
527
+ const agent = clientId === AGENT_CLIENT_ID
528
+ // The agent client may omit the scope, and a parameter without a value is omitted (RFC 6749 §3.1); IAM then picks `read`.
529
+ const scopes = agent && (scope === undefined || scope === '') ? [] : typeof scope === 'string' ? parseOAuthScopes(scope.split(' ')) : null
530
+ const resources = value.resources
531
+ if (
532
+ scopes === null || (scopes.length === 0 && !agent) || resources.length === 0 || resources.length > MAX_OAUTH_DEVICE_RESOURCES
533
+ || !resources.every(isOAuthResourceUri) || new Set(resources).size !== resources.length
534
+ ) return null
535
+ const label = field(value.fields, 'agent_label')
536
+ if (!agent || label === undefined) return { client_id: clientId, scope: scopes, resources: [...resources] }
537
+ if (typeof label !== 'string' || !isAgentLabel(label)) return null
538
+ return { client_id: clientId, scope: scopes, resources: [...resources], agent_label: label }
539
+ }
540
+
541
+ export function isOAuthDeviceGrantLifetime(value: number): value is OAuthDeviceGrantLifetime {
542
+ return OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS.some((lifetime) => lifetime === value)
543
+ }
544
+
311
545
  const MAX_CLIENT_ASSERTION_LENGTH = 16_384
312
546
 
313
547
  /**
@@ -327,7 +561,7 @@ export function parseOAuthRevocationRequest(value: unknown): OAuthRevocationRequ
327
561
  const token = field(value, 'token')
328
562
  const hint = field(value, 'token_type_hint')
329
563
  if (
330
- !isCimdClientId(clientId) || typeof token !== 'string' || token.length === 0 || token.length > 32768
564
+ !isOAuthClientId(clientId) || typeof token !== 'string' || token.length === 0 || token.length > 32768
331
565
  || (hint !== undefined && (typeof hint !== 'string' || hint.length > 200))
332
566
  ) return null
333
567
  const request: OAuthRevocationRequest = { client_id: clientId, token }
@@ -0,0 +1,144 @@
1
+ // A person's passkeys (WebAuthn), kept by IAM. Every ceremony runs on IAM's own pages, under IAM's host as the RP ID: the
2
+ // person registers and removes passkeys on IAM's account page, and a step-up another service asks for is answered on
3
+ // IAM's step-up page. Every binary value travels base64url-encoded, as in WebAuthn's JSON encodings.
4
+
5
+ /** How long a ceremony's challenge can be answered, in seconds. */
6
+ export const PASSKEY_CHALLENGE_TTL_SECONDS = 300
7
+
8
+ /** The longest label a person may give a passkey, in characters. */
9
+ export const MAX_PASSKEY_LABEL_LENGTH = 64
10
+
11
+ /** The longest binding a challenge may carry. */
12
+ export const MAX_PASSKEY_BINDING_LENGTH = 512
13
+
14
+ /** How many passkeys one person may keep. */
15
+ export const MAX_PASSKEYS_PER_PERSON = 20
16
+
17
+ /** The error `type` of `passkeys.challenge`'s refusal to a person with no passkey, so a caller tells it from other 409s. */
18
+ export const NO_PASSKEY_ERROR = 'no_passkey'
19
+
20
+ /**
21
+ * The prefix of the bindings IAM's own pages use. Another service never asks a step-up with one, and IAM's step-up page
22
+ * never answers one, so a check IAM asks for itself is answered only on the page that asked it.
23
+ */
24
+ export const IAM_BINDING_PREFIX = 'iam:'
25
+
26
+ /** The binding of the assertion that registering another passkey takes, when the person already has one. */
27
+ export const PASSKEY_REGISTRATION_BINDING = `${IAM_BINDING_PREFIX}passkeys.register`
28
+
29
+ /** The binding of the assertion that removing the passkey `passkeyId` takes. */
30
+ export function passkeyRemovalBinding(passkeyId: string): string {
31
+ return `${IAM_BINDING_PREFIX}passkeys.remove:${passkeyId}`
32
+ }
33
+
34
+ /** A passkey as its owner and an installation administrator see it. No key material. */
35
+ export interface PasskeyDto {
36
+ id: string
37
+ label: string
38
+ /** Epoch seconds. */
39
+ createdAt: number
40
+ /** Epoch seconds of the last accepted assertion; null before the first. */
41
+ lastUsedAt: number | null
42
+ }
43
+
44
+ export interface PasskeyCredentialDescriptor {
45
+ type: 'public-key'
46
+ /** The credential id, base64url. */
47
+ id: string
48
+ transports?: string[]
49
+ }
50
+
51
+ /** `PublicKeyCredentialCreationOptions` in its JSON encoding: what `navigator.credentials.create` takes. */
52
+ export interface PasskeyCreationOptions {
53
+ rp: { id: string; name: string }
54
+ user: { id: string; name: string; displayName: string }
55
+ challenge: string
56
+ pubKeyCredParams: { type: 'public-key'; alg: number }[]
57
+ timeout: number
58
+ /** The person's passkeys, so an authenticator holding one of them does not register it again. */
59
+ excludeCredentials: PasskeyCredentialDescriptor[]
60
+ authenticatorSelection: { residentKey: 'preferred'; userVerification: 'required' }
61
+ attestation: 'none'
62
+ }
63
+
64
+ /** `PublicKeyCredentialRequestOptions` in its JSON encoding: what `navigator.credentials.get` takes. */
65
+ export interface PasskeyRequestOptions {
66
+ challenge: string
67
+ rpId: string
68
+ timeout: number
69
+ /** The person's own passkeys; no other credential can answer. */
70
+ allowCredentials: PasskeyCredentialDescriptor[]
71
+ userVerification: 'required'
72
+ }
73
+
74
+ /** A challenge IAM issued, to be answered once before `expiresAt` (epoch seconds). */
75
+ export interface PasskeyChallenge<Options> {
76
+ challengeId: string
77
+ expiresAt: number
78
+ options: Options
79
+ }
80
+
81
+ /** What `navigator.credentials.create` answered, in its JSON encoding. */
82
+ export interface PasskeyRegistrationCredential {
83
+ id: string
84
+ rawId: string
85
+ type: 'public-key'
86
+ response: {
87
+ clientDataJSON: string
88
+ attestationObject: string
89
+ transports?: string[]
90
+ }
91
+ }
92
+
93
+ /** What `navigator.credentials.get` answered, in its JSON encoding. */
94
+ export interface PasskeyAssertionCredential {
95
+ id: string
96
+ rawId: string
97
+ type: 'public-key'
98
+ response: {
99
+ clientDataJSON: string
100
+ authenticatorData: string
101
+ signature: string
102
+ userHandle?: string
103
+ }
104
+ }
105
+
106
+ /** An answered assertion challenge. */
107
+ export interface PasskeyAssertion {
108
+ challengeId: string
109
+ credential: PasskeyAssertionCredential
110
+ }
111
+
112
+ export interface IssuePasskeyChallengeRequest {
113
+ /** What the assertion is for, compared verbatim at verification. Opaque to IAM. */
114
+ binding: string
115
+ }
116
+
117
+ /**
118
+ * A step-up challenge IAM issued to the person: they answer it on IAM's page at `url` before `expiresAt` (epoch
119
+ * seconds), and its issuer then verifies it by `challengeId`.
120
+ */
121
+ export interface PasskeyStepUpChallenge {
122
+ challengeId: string
123
+ expiresAt: number
124
+ url: string
125
+ }
126
+
127
+ export interface VerifyPasskeyAssertionRequest {
128
+ /** The binding the challenge was issued with. */
129
+ binding: string
130
+ /** The challenge the person answered on IAM's step-up page. */
131
+ challengeId: string
132
+ }
133
+
134
+ /** A verified assertion: who answered, with which credential (its WebAuthn id, base64url), and when (epoch seconds). */
135
+ export interface VerifiedPasskeyAssertion {
136
+ principalId: string
137
+ credentialId: string
138
+ at: number
139
+ }
140
+
141
+ export interface PasskeyResetResponse {
142
+ /** How many passkeys the reset removed. */
143
+ removed: number
144
+ }
@@ -14,7 +14,7 @@ export const PASSWORD_MIN_LENGTH_FLOOR = 4
14
14
  /** The most code points a password may have, whatever the minimum. */
15
15
  export const PASSWORD_MAX_LENGTH = 256
16
16
 
17
- /** Below this NIST asks for a second factor, which IAM does not have; the console says so. */
17
+ /** Below this NIST asks for a second factor, which IAM gives only an enrolled administrator; the console says so. */
18
18
  export const PASSWORD_SINGLE_FACTOR_FLOOR = 8
19
19
 
20
20
  /** The password policy as IAM applies it now. */
@@ -0,0 +1,71 @@
1
+ // A key for someone else, asked for through a Control approval request (ADR-0083 §8): the agent that asks sends a public
2
+ // key, and IAM encrypts the key it issues to it before it answers, so the key's plaintext leaves IAM only as a JWE that
3
+ // the agent's private key opens. The request's id is the idempotency key: a repeat answers the same key.
4
+
5
+ import { canonicalJson, sha256Hex } from '@fabrika/auth-core'
6
+
7
+ /** The public keys a requested key may be encrypted to: P-256 or X25519, as a JWK without its private part. */
8
+ export type RecipientPublicKey =
9
+ | { readonly kty: 'EC'; readonly crv: 'P-256'; readonly x: string; readonly y: string }
10
+ | { readonly kty: 'OKP'; readonly crv: 'X25519'; readonly x: string }
11
+
12
+ export const RECIPIENT_CURVES = ['P-256', 'X25519'] as const
13
+
14
+ /** The JWE a requested key travels in: compact, key agreement `ECDH-ES` straight to the recipient, `A256GCM` content. */
15
+ export const REQUESTED_KEY_JWE = { alg: 'ECDH-ES', enc: 'A256GCM' } as const
16
+
17
+ /** The members of a recipient key its RFC 7638 thumbprint hashes: the required public ones, nothing else. */
18
+ function thumbprintMembers(key: RecipientPublicKey): Record<string, string> {
19
+ return key.kty === 'EC' ? { crv: key.crv, kty: key.kty, x: key.x, y: key.y } : { crv: key.crv, kty: key.kty, x: key.x }
20
+ }
21
+
22
+ /**
23
+ * The RFC 7638 thumbprint of a recipient key (SHA-256, base64url): what the approval page shows and the agent prints
24
+ * beside the link, and the `kid` of the JWE IAM answers.
25
+ */
26
+ export function recipientKeyThumbprint(key: RecipientPublicKey): string {
27
+ const hex = sha256Hex(canonicalJson(thumbprintMembers(key)))
28
+ let binary = ''
29
+ for (let i = 0; i < hex.length; i += 2) binary += String.fromCharCode(Number.parseInt(hex.slice(i, i + 2), 16))
30
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
31
+ }
32
+
33
+ /** Who asked for a requested key, as IAM records it beside the approver. */
34
+ export interface RequestedKeyApprovalRequest {
35
+ /** The Control approval request's id: the idempotency key of the issuance. At most 200 characters. */
36
+ id: string
37
+ requester: { id: string; label: string; clientId?: string }
38
+ }
39
+
40
+ /**
41
+ * `apiKeys.provisionRequested`: a service key a person approved in Control, issued by that person in a signed-in session.
42
+ * Its permissions are exact actions of `app`, in one scope value or global, and it expires at most 30 days ahead.
43
+ */
44
+ export interface ProvisionRequestedApiKeyRequest {
45
+ label: string
46
+ app: string
47
+ permissions: string[]
48
+ scopeType: string | null
49
+ scopeValue: string | null
50
+ /** Unix seconds; at most `MAX_KEY_LIFETIME_SECONDS` ahead. */
51
+ expiresAt: number
52
+ recipient: RecipientPublicKey
53
+ approvalRequest: RequestedKeyApprovalRequest
54
+ }
55
+
56
+ /** A requested key as IAM answers it: its service principal, and the key encrypted to the recipient. */
57
+ export interface RequestedApiKey {
58
+ principalId: string
59
+ /** The `px_` key, encrypted to the recipient (`REQUESTED_KEY_JWE`), whose thumbprint is the JWE's `kid`. */
60
+ jwe: string
61
+ expiresAt: number
62
+ }
63
+
64
+ export interface RequestedApiKeyInput {
65
+ approvalRequestId: string
66
+ }
67
+
68
+ /** `apiKeys.requested`: the key an approval request issued, or null when it issued none. */
69
+ export interface RequestedApiKeyResponse {
70
+ key: RequestedApiKey | null
71
+ }
package/src/scim.ts ADDED
@@ -0,0 +1,19 @@
1
+ // SCIM provisioning (ADR-0091): the organization's identity provider creates, updates and deprovisions the
2
+ // installation's users at IAM's `/scim/v2`, with one bearer token an installation administrator creates and rotates.
3
+
4
+ /** The installation's SCIM provisioning as the console shows it. */
5
+ export interface ScimSettingsDto {
6
+ /** The tenant URL an identity provider is configured with: IAM's origin and `/scim/v2`. */
7
+ endpoint: string
8
+ /** Whether a token exists; without one IAM refuses every SCIM request. */
9
+ configured: boolean
10
+ /** When the current token was created, in epoch seconds; null without one. */
11
+ createdAt: number | null
12
+ }
13
+
14
+ /** A token just created: the secret is in this answer and nowhere else, ever again. */
15
+ export interface ScimTokenIssuedDto extends ScimSettingsDto {
16
+ configured: true
17
+ createdAt: number
18
+ token: string
19
+ }