@fabrika/iam-contract 0.9.0-dev.4 → 0.9.0-dev.41

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,48 @@
1
- import { isCimdClientId, isOAuthResourceUri, parseOAuthScopes } from '@fabrika/auth-core'
1
+ import { BUILTIN_ROLE_KEYS, isCimdClientId, isOAuthClientId, isOAuthResourceUri, parseOAuthScopes } from '@fabrika/auth-core'
2
2
  import type { KeyGrant } from '@fabrika/auth-core'
3
3
 
4
+ /**
5
+ * The kinds of managed client an installation registers. A label only: every kind gets the same authorization code
6
+ * flow with S256 PKCE, the same RFC 8707 resources and the same scope ceilings (ADR-0049).
7
+ */
8
+ export const OAUTH_CLIENT_PROVIDERS = ['claude', 'chatgpt', 'external'] as const
9
+ export type OAuthClientProvider = (typeof OAUTH_CLIENT_PROVIDERS)[number]
10
+
11
+ function isOAuthClientProvider(value: unknown): value is OAuthClientProvider {
12
+ return OAUTH_CLIENT_PROVIDERS.some((provider) => provider === value)
13
+ }
14
+
15
+ /**
16
+ * The one resource an identity-only client is served: its own, outside the installation. A token for it carries the
17
+ * person's identity and no permission, under `app`, an id no installation service or application holds. With `roles`,
18
+ * the application's roles are IAM's to grant: the token names those the person holds there, and a person holding none
19
+ * is refused.
20
+ */
21
+ export interface OAuthIdentityResource {
22
+ app: string
23
+ resource: string
24
+ roles?: OAuthIdentityRole[]
25
+ }
26
+
27
+ /** A role of an external application: IAM grants it and names it in the token; the application decides what it allows. */
28
+ export interface OAuthIdentityRole {
29
+ key: string
30
+ name: string
31
+ }
32
+
33
+ /** How many roles one external application declares. */
34
+ export const MAX_OAUTH_IDENTITY_ROLES = 32
35
+
36
+ /** The one scope of an identity resource: it names the person and grants nothing. */
37
+ export const OAUTH_IDENTITY_SCOPE = 'identity'
38
+
4
39
  /** Managed CIMD registrations only; public dynamic registration is not part of this contract. */
5
40
  export interface OAuthManagedClient {
6
- provider: 'chatgpt' | 'claude'
41
+ provider: OAuthClientProvider
7
42
  clientId: string
8
43
  redirectUris: string[]
44
+ /** Present only on an `external` client: it is served this resource alone, never a registered one. */
45
+ identity?: OAuthIdentityResource
9
46
  }
10
47
 
11
48
  /** RFC 7523 §2.2: the `client_assertion_type` of a JWT client assertion (`private_key_jwt`). */
@@ -36,13 +73,28 @@ export type OAuthClientMetadataDocument =
36
73
  /** How a token or revocation request authenticates its client: no credential, or a JWT assertion. */
37
74
  export type OAuthClientCredential = { method: 'none' } | { method: 'private_key_jwt'; assertion: string }
38
75
 
76
+ export interface OAuthScopeGrant {
77
+ scope: string
78
+ permissions: KeyGrant[]
79
+ /**
80
+ * A scope dimension type. Such a scope is requested only as `<scope>:<value>`, and each of its scope-less permissions
81
+ * is narrowed to `{ type: parameter, value }`: `deploy:alpha` with parameter `app` holds its actions at app `alpha` only.
82
+ */
83
+ parameter?: string
84
+ }
85
+
39
86
  export interface OAuthResourceDto {
40
87
  app: string
41
88
  resource: string
42
89
  /** IAM resolves these app-owned grants; OAuth scope text alone never authorizes an action. */
43
- scopeGrants: { scope: string; permissions: KeyGrant[] }[]
90
+ scopeGrants: OAuthScopeGrant[]
44
91
  /** Used only when scope is omitted. No configured default means invalid_scope, never all scopes. */
45
92
  defaultScopes?: string[]
93
+ /**
94
+ * `cli`: served only to the installation's command-line client, through the device grant. Absent: served only to the
95
+ * operator's managed clients, through an authorization code. A token for one never comes from the other's flow.
96
+ */
97
+ client?: 'cli'
46
98
  }
47
99
 
48
100
  /** No access token, refresh token, hash, or authorization code appears in a grant DTO. */
@@ -76,9 +128,37 @@ export type OAuthAuthorizationParseResult =
76
128
  | { kind: 'invalid_scope'; coordinates: OAuthAuthorizationCoordinates; rawScope: string }
77
129
  | { kind: 'invalid_request' }
78
130
 
131
+ /** RFC 8628 §3.4: the grant type a device client polls the token endpoint with. */
132
+ export const OAUTH_DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code'
133
+
79
134
  export type OAuthTokenRequest =
80
135
  | { grant_type: 'authorization_code'; client_id: string; code: string; redirect_uri: string; code_verifier: string; resource: string }
81
136
  | { grant_type: 'refresh_token'; client_id: string; refresh_token: string; resource: string }
137
+ | { grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE; client_id: string; device_code: string; resource: string }
138
+
139
+ /** RFC 8628 §3.1, with every resource the grant is asked for (RFC 8707): each token names one of them. */
140
+ export interface OAuthDeviceAuthorizationRequest {
141
+ client_id: string
142
+ scope: string[]
143
+ resources: string[]
144
+ }
145
+
146
+ /** RFC 8628 §3.2. */
147
+ export interface OAuthDeviceAuthorizationResponse {
148
+ device_code: string
149
+ user_code: string
150
+ verification_uri: string
151
+ verification_uri_complete: string
152
+ expires_in: number
153
+ interval: number
154
+ }
155
+
156
+ /** The lifetimes a person picks between when approving a device: an hour, a day, a week. */
157
+ export const OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS = [3600, 86_400, 604_800] as const
158
+ export type OAuthDeviceGrantLifetime = (typeof OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS)[number]
159
+
160
+ /** How many resources one device grant may name. */
161
+ export const MAX_OAUTH_DEVICE_RESOURCES = 8
82
162
 
83
163
  export interface OAuthTokenResponse {
84
164
  access_token: string
@@ -99,9 +179,10 @@ export interface OAuthAuthorizationServerMetadata {
99
179
  authorization_endpoint: string
100
180
  token_endpoint: string
101
181
  revocation_endpoint: string
182
+ device_authorization_endpoint: string
102
183
  jwks_uri: string
103
184
  response_types_supported: ['code']
104
- grant_types_supported: ['authorization_code', 'refresh_token']
185
+ grant_types_supported: ['authorization_code', 'refresh_token', typeof OAUTH_DEVICE_CODE_GRANT_TYPE]
105
186
  code_challenge_methods_supported: ['S256']
106
187
  token_endpoint_auth_methods_supported: ['none', 'private_key_jwt']
107
188
  token_endpoint_auth_signing_alg_values_supported: OAuthClientAssertionAlgorithm[]
@@ -134,9 +215,50 @@ export function parseOAuthManagedClient(value: unknown): OAuthManagedClient | nu
134
215
  const provider = field(value, 'provider')
135
216
  const clientId = field(value, 'clientId')
136
217
  const uris = redirectUris(field(value, 'redirectUris'))
137
- return (provider === 'chatgpt' || provider === 'claude') && isCimdClientId(clientId) && uris !== null
138
- ? { provider, clientId, redirectUris: uris }
139
- : null
218
+ const rawIdentity = field(value, 'identity')
219
+ if (!isOAuthClientProvider(provider) || !isCimdClientId(clientId) || uris === null) return null
220
+ if (rawIdentity === undefined) return { provider, clientId, redirectUris: uris }
221
+ const identity = parseOAuthIdentityResource(rawIdentity)
222
+ // Claude and ChatGPT are authoring clients; only an external application signs people in for itself.
223
+ return identity === null || provider !== 'external' ? null : { provider, clientId, redirectUris: uris, identity }
224
+ }
225
+
226
+ const IDENTITY_KEYS = ['app', 'resource', 'roles']
227
+ const ROLE_KEYS = ['key', 'name']
228
+ /** An app id as every fabrika config writes one; no `@`, so never an application environment's id. */
229
+ const IDENTITY_APP = /^[a-z0-9][a-z0-9-]{0,62}$/
230
+ /** A role key; never a built-in one (`admin` means every action of an application). */
231
+ const IDENTITY_ROLE_KEY = /^[a-z0-9][a-z0-9-]{0,62}$/
232
+
233
+ function parseOAuthIdentityResource(value: unknown): OAuthIdentityResource | null {
234
+ const app = field(value, 'app')
235
+ const resource = field(value, 'resource')
236
+ const rawRoles = field(value, 'roles')
237
+ if (!hasOnlyKeys(value, IDENTITY_KEYS) || typeof app !== 'string' || !IDENTITY_APP.test(app) || !isOAuthResourceUri(resource)) return null
238
+ if (rawRoles === undefined) return { app, resource }
239
+ const roles = parseOAuthIdentityRoles(rawRoles)
240
+ return roles === null ? null : { app, resource, roles }
241
+ }
242
+
243
+ function parseOAuthIdentityRoles(value: unknown): OAuthIdentityRole[] | null {
244
+ if (!Array.isArray(value) || value.length === 0 || value.length > MAX_OAUTH_IDENTITY_ROLES) return null
245
+ const roles: OAuthIdentityRole[] = []
246
+ for (const entry of value) {
247
+ const key = field(entry, 'key')
248
+ const name = field(entry, 'name')
249
+ if (
250
+ !hasOnlyKeys(entry, ROLE_KEYS) || typeof key !== 'string' || !IDENTITY_ROLE_KEY.test(key) || BUILTIN_ROLE_KEYS.includes(key)
251
+ || !isNonemptyText(name)
252
+ || name.length > 100 || roles.some((role) => role.key === key)
253
+ ) return null
254
+ roles.push({ key, name })
255
+ }
256
+ return roles
257
+ }
258
+
259
+ /** The scopes an identity resource's authorization asks for: none, or exactly `identity`. */
260
+ export function resolveOAuthIdentityScopes(scope: string | undefined): string[] | null {
261
+ return scope === undefined || scope === OAUTH_IDENTITY_SCOPE ? [OAUTH_IDENTITY_SCOPE] : null
140
262
  }
141
263
 
142
264
  /** A fetched document cannot enlarge the managed registration's exact redirect allowlist. */
@@ -199,28 +321,54 @@ function parseClientGrantTypes(value: unknown): OAuthClientMetadataDocument['gra
199
321
  return grants.includes('authorization_code') ? grants : null
200
322
  }
201
323
 
324
+ const SCOPE_GRANT_KEYS = ['scope', 'permissions', 'parameter']
325
+ const PERMISSION_KEYS = ['action', 'scope']
326
+ const PERMISSION_SCOPE_KEYS = ['type', 'value']
327
+
328
+ function hasOnlyKeys(value: unknown, allowed: readonly string[]): boolean {
329
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).every((key) => allowed.includes(key))
330
+ }
331
+
202
332
  export function parseOAuthResourceDto(value: unknown): OAuthResourceDto | null {
203
333
  const app = field(value, 'app')
204
334
  const resource = field(value, 'resource')
205
335
  const rawGrants = field(value, 'scopeGrants')
206
336
  const rawDefaultScopes = field(value, 'defaultScopes')
337
+ const client = field(value, 'client')
338
+ if (client !== undefined && client !== 'cli') return null
207
339
  if (
208
340
  !isNonemptyText(app) || app.includes('*') || !isOAuthResourceUri(resource) || !Array.isArray(rawGrants) || rawGrants.length === 0
209
341
  || rawGrants.length > 64
210
342
  ) return null
211
- const scopeGrants: OAuthResourceDto['scopeGrants'] = []
343
+ const scopeGrants: OAuthScopeGrant[] = []
212
344
  for (const entry of rawGrants) {
345
+ // An unknown key is refused: a misspelled `parameter` would otherwise leave the scope unnarrowed.
346
+ if (!hasOnlyKeys(entry, SCOPE_GRANT_KEYS)) return null
213
347
  const scope = field(entry, 'scope')
214
348
  const permissions = parseResourcePermissions(field(entry, 'permissions'))
215
- if (typeof scope !== 'string' || parseOAuthScopes([scope]) === null || permissions === null || scopeGrants.some((grant) => grant.scope === scope)) {
349
+ const parameter = field(entry, 'parameter')
350
+ if (
351
+ typeof scope !== 'string' || parseOAuthScopes([scope]) === null || scope.includes(SCOPE_PARAMETER_SEPARATOR) || permissions === null
352
+ || scopeGrants.some((grant) => grant.scope === scope)
353
+ ) {
216
354
  return null
217
355
  }
218
- scopeGrants.push({ scope, permissions })
356
+ if (parameter === undefined) {
357
+ scopeGrants.push({ scope, permissions })
358
+ continue
359
+ }
360
+ // A parameter narrows scope-less permissions only; a permission that names its own scope would ignore it.
361
+ if (!isScopeParameterText(parameter) || permissions.some((permission) => permission.scope != null)) return null
362
+ scopeGrants.push({ scope, permissions, parameter })
219
363
  }
220
- const dto: OAuthResourceDto = { app, resource, scopeGrants }
364
+ const dto: OAuthResourceDto = { app, resource, scopeGrants, ...(client === undefined ? {} : { client }) }
221
365
  if (rawDefaultScopes !== undefined) {
222
366
  const defaultScopes = parseOAuthScopes(rawDefaultScopes)
223
- if (defaultScopes === null || !defaultScopes.every((scope) => scopeGrants.some((grant) => grant.scope === scope))) return null
367
+ if (
368
+ defaultScopes === null || !defaultScopes.every((scope) => scopeGrants.some((grant) => grant.scope === scope && grant.parameter === undefined))
369
+ ) {
370
+ return null
371
+ }
224
372
  dto.defaultScopes = defaultScopes
225
373
  }
226
374
  return dto
@@ -232,23 +380,47 @@ function parseResourcePermissions(value: unknown): KeyGrant[] | null {
232
380
  for (const entry of value) {
233
381
  const action = field(entry, 'action')
234
382
  const rawScope = field(entry, 'scope')
235
- if (!isNonemptyText(action)) return null
383
+ if (!hasOnlyKeys(entry, PERMISSION_KEYS) || !isNonemptyText(action)) return null
236
384
  if (rawScope === undefined) permissions.push({ action })
237
385
  else if (rawScope === null) permissions.push({ action, scope: null })
238
386
  else {
239
387
  const type = field(rawScope, 'type')
240
388
  const scopeValue = field(rawScope, 'value')
241
- if (!isNonemptyText(type) || !isNonemptyText(scopeValue)) return null
389
+ if (!hasOnlyKeys(rawScope, PERMISSION_SCOPE_KEYS) || !isNonemptyText(type) || !isNonemptyText(scopeValue)) return null
242
390
  permissions.push({ action, scope: { type, value: scopeValue } })
243
391
  }
244
392
  }
245
393
  return permissions
246
394
  }
247
395
 
396
+ /** Separates a parameterized scope from its value: `deploy:alpha`. */
397
+ export const SCOPE_PARAMETER_SEPARATOR = ':'
398
+
399
+ /** A scope dimension type, or a value of one, as a scope token may carry it. */
400
+ function isScopeParameterText(value: unknown): value is string {
401
+ return typeof value === 'string' && value.length <= 100 && /^[A-Za-z0-9][A-Za-z0-9._@-]*$/.test(value)
402
+ }
403
+
404
+ /**
405
+ * The resource's grant a requested scope token selects and the narrowed permissions it holds, or null when the token
406
+ * selects none: an unknown scope, a parameterized scope without its value, a value on a scope that takes none.
407
+ */
408
+ export function resolveOAuthScopeToken(token: string, resource: OAuthResourceDto): KeyGrant[] | null {
409
+ const separator = token.indexOf(SCOPE_PARAMETER_SEPARATOR)
410
+ const name = separator === -1 ? token : token.slice(0, separator)
411
+ const grant = resource.scopeGrants.find((entry) => entry.scope === name)
412
+ if (grant === undefined) return null
413
+ const type = grant.parameter
414
+ if (type === undefined) return separator === -1 ? grant.permissions : null
415
+ const value = separator === -1 ? null : token.slice(separator + 1)
416
+ if (value === null || !isScopeParameterText(value)) return null
417
+ return grant.permissions.map((permission) => ({ action: permission.action, scope: { type, value } }))
418
+ }
419
+
248
420
  export function resolveOAuthAuthorizationScopes(scope: string | undefined, resource: OAuthResourceDto): string[] | null {
249
421
  const scopes = scope === undefined ? resource.defaultScopes : parseOAuthScopes(scope.split(' '))
250
422
  if (!scopes || scopes.length === 0) return null
251
- return scopes.every((entry) => resource.scopeGrants.some((grant) => grant.scope === entry))
423
+ return scopes.every((entry) => resolveOAuthScopeToken(entry, resource) !== null)
252
424
  ? [...scopes]
253
425
  : null
254
426
  }
@@ -291,7 +463,7 @@ export function parseOAuthTokenRequest(value: unknown): OAuthTokenRequest | null
291
463
  const clientId = field(value, 'client_id')
292
464
  const resource = field(value, 'resource')
293
465
  const grantType = field(value, 'grant_type')
294
- if (!isCimdClientId(clientId) || !isOAuthResourceUri(resource)) return null
466
+ if (!isOAuthClientId(clientId) || !isOAuthResourceUri(resource)) return null
295
467
  if (grantType === 'authorization_code') {
296
468
  const code = field(value, 'code')
297
469
  const redirectUri = field(value, 'redirect_uri')
@@ -305,9 +477,38 @@ export function parseOAuthTokenRequest(value: unknown): OAuthTokenRequest | null
305
477
  const refreshToken = field(value, 'refresh_token')
306
478
  return isNonemptyText(refreshToken) ? { grant_type: grantType, client_id: clientId, refresh_token: refreshToken, resource } : null
307
479
  }
480
+ if (grantType === OAUTH_DEVICE_CODE_GRANT_TYPE) {
481
+ const deviceCode = field(value, 'device_code')
482
+ return isNonemptyText(deviceCode) && deviceCode.length <= 256
483
+ ? { grant_type: grantType, client_id: clientId, device_code: deviceCode, resource }
484
+ : null
485
+ }
308
486
  return null
309
487
  }
310
488
 
489
+ /**
490
+ * A device authorization request: its client, at least one scope and one to `MAX_OAUTH_DEVICE_RESOURCES` distinct
491
+ * resources. `resource` is the one parameter that may repeat (RFC 8707 §2), so the caller collects it into a list.
492
+ */
493
+ export function parseOAuthDeviceAuthorizationRequest(
494
+ value: { fields: Record<string, string>; resources: string[] },
495
+ ): OAuthDeviceAuthorizationRequest | null {
496
+ const clientId = field(value.fields, 'client_id')
497
+ const scope = field(value.fields, 'scope')
498
+ if (!isOAuthClientId(clientId) || typeof scope !== 'string') return null
499
+ const scopes = parseOAuthScopes(scope.split(' '))
500
+ const resources = value.resources
501
+ if (
502
+ scopes === null || scopes.length === 0 || resources.length === 0 || resources.length > MAX_OAUTH_DEVICE_RESOURCES
503
+ || !resources.every(isOAuthResourceUri) || new Set(resources).size !== resources.length
504
+ ) return null
505
+ return { client_id: clientId, scope: scopes, resources: [...resources] }
506
+ }
507
+
508
+ export function isOAuthDeviceGrantLifetime(value: number): value is OAuthDeviceGrantLifetime {
509
+ return OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS.some((lifetime) => lifetime === value)
510
+ }
511
+
311
512
  const MAX_CLIENT_ASSERTION_LENGTH = 16_384
312
513
 
313
514
  /**
@@ -327,7 +528,7 @@ export function parseOAuthRevocationRequest(value: unknown): OAuthRevocationRequ
327
528
  const token = field(value, 'token')
328
529
  const hint = field(value, 'token_type_hint')
329
530
  if (
330
- !isCimdClientId(clientId) || typeof token !== 'string' || token.length === 0 || token.length > 32768
531
+ !isOAuthClientId(clientId) || typeof token !== 'string' || token.length === 0 || token.length > 32768
331
532
  || (hint !== undefined && (typeof hint !== 'string' || hint.length > 200))
332
533
  ) return null
333
534
  const request: OAuthRevocationRequest = { client_id: clientId, token }
@@ -0,0 +1,43 @@
1
+ // The installation's password policy (ADR-0020): one minimum length for every principal of the installation, which an
2
+ // installation administrator may lower from the default down to the runtime's floor. IAM checks every value again; the
3
+ // console reads these numbers only to say what IAM will accept.
4
+
5
+ /** The minimum of an installation that never set one: NIST SP 800-63B's for a password that is the only factor. */
6
+ export const PASSWORD_DEFAULT_MIN_LENGTH = 15
7
+
8
+ /**
9
+ * The lowest minimum IAM accepts on a runtime whose verifiers meet OWASP's PBKDF2 cost. Below it a password is a PIN, and
10
+ * no throttle makes it one a person can be trusted with.
11
+ */
12
+ export const PASSWORD_MIN_LENGTH_FLOOR = 4
13
+
14
+ /** The most code points a password may have, whatever the minimum. */
15
+ export const PASSWORD_MAX_LENGTH = 256
16
+
17
+ /** Below this NIST asks for a second factor, which IAM gives only an enrolled administrator; the console says so. */
18
+ export const PASSWORD_SINGLE_FACTOR_FLOOR = 8
19
+
20
+ /** The password policy as IAM applies it now. */
21
+ export interface PasswordPolicyDto {
22
+ /** The minimum length in Unicode code points that IAM applies to every new password. */
23
+ minLength: number
24
+ /** The minimum of an installation that never set one, `PASSWORD_DEFAULT_MIN_LENGTH`. */
25
+ defaultMinLength: number
26
+ /**
27
+ * The lowest minimum this IAM accepts. `PASSWORD_MIN_LENGTH_FLOOR` where verifiers meet OWASP's PBKDF2 cost; the
28
+ * default on a runtime whose cost is lower (a Cloudflare Worker, backlog 201), where a short password is cheap to
29
+ * crack offline.
30
+ */
31
+ minLengthFloor: number
32
+ /** The most code points a password may have. */
33
+ maxLength: number
34
+ /** Whether the installation enables password sign-in at all; the minimum waits for it when it does not. */
35
+ passwordEnabled: boolean
36
+ /** When an administrator last changed the minimum, in epoch seconds; null when nobody ever did. */
37
+ updatedAt: number | null
38
+ }
39
+
40
+ export interface SetPasswordPolicyRequest {
41
+ /** A whole number from `minLengthFloor` to `maxLength`. */
42
+ minLength: number
43
+ }
@@ -6,6 +6,8 @@ export declare const IAM_ACTIONS: Readonly<{
6
6
  ADMIN: "iam.admin";
7
7
  /** Manage the people of applications, never of the installation's own apps. Global, or in `app` values. */
8
8
  USERS_MANAGE: "iam.users.manage";
9
+ /** Enrol a browser as a terminal (ADR-0067). Global only; its profile and revocation stay `iam.admin`'s. */
10
+ TERMINALS_MANAGE: "iam.terminals.manage";
9
11
  }>;
10
12
  export declare const IAM_SCOPES: Readonly<{
11
13
  /** One application environment, by its IAM id `<app>@<env>`. */