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

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
@@ -3,16 +3,20 @@ import {
3
3
  DEFAULT_TOKEN_TTL_SECONDS,
4
4
  type KeyGrant,
5
5
  narrowPermissions,
6
+ OAUTH_CLI_CLIENT_ID,
6
7
  parseOAuthScopes,
7
8
  type PermissionEntry,
8
9
  } from '@fabrika/auth-core'
9
- import type {
10
- OAuthAuthorizationRequest,
11
- OAuthClientMetadataDocument,
12
- OAuthResourceDto,
13
- OAuthRevocationRequest,
14
- OAuthTokenRequest,
15
- OAuthTokenResponse,
10
+ import {
11
+ OAUTH_DEVICE_CODE_GRANT_TYPE,
12
+ OAUTH_IDENTITY_SCOPE,
13
+ type OAuthAuthorizationRequest,
14
+ type OAuthClientMetadataDocument,
15
+ type OAuthResourceDto,
16
+ type OAuthRevocationRequest,
17
+ type OAuthTokenRequest,
18
+ type OAuthTokenResponse,
19
+ resolveOAuthScopeToken,
16
20
  } from '@fabrika/iam-contract'
17
21
  import { uuidv7 } from '@fabrika/platform'
18
22
  import { sessionEndsAt, sessionUsable } from './auth'
@@ -34,27 +38,58 @@ export const OAUTH_CODE_TTL_SECONDS = 60
34
38
 
35
39
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
36
40
 
37
- export interface EstablishedClient {
38
- registration: ManagedOAuthClient
39
- metadata: OAuthClientMetadataDocument
41
+ /**
42
+ * A client an authorization or token request comes from: an operator-registered CIMD client, or the installation's own
43
+ * command-line client, a public client IAM knows without a document. The CLI client has no redirect URI, so it never
44
+ * completes an authorization request; it redeems the grants IAM gives it otherwise and refreshes them.
45
+ */
46
+ export type EstablishedClient =
47
+ | { kind: 'managed'; registration: ManagedOAuthClient; metadata: OAuthClientMetadataDocument }
48
+ | { kind: 'cli'; clientId: string }
49
+
50
+ export type ManagedClient = Extract<EstablishedClient, { kind: 'managed' }>
51
+
52
+ /** The grant types a client may use at the token endpoint: its document's, or the CLI client's fixed set. */
53
+ function clientGrantTypes(client: EstablishedClient): readonly string[] {
54
+ return client.kind === 'cli' ? ['refresh_token'] : client.metadata.grant_types
55
+ }
56
+
57
+ /** Whether `resource` is served to the command-line client (`cli`) or to the managed clients; never to both. */
58
+ export function servesClient(resource: OAuthResourceDto, cli: boolean): boolean {
59
+ return (resource.client === 'cli') === cli
60
+ }
61
+
62
+ /** The resources a grant was given for: every token it mints names one of them. */
63
+ export function grantResources(grant: Pick<OAuthGrantRow, 'resource' | 'resources'>): string[] {
64
+ const stored = grant.resources === null ? null : storedResourceList(grant.resources)
65
+ return stored ?? [grant.resource]
66
+ }
67
+
68
+ /** A stored JSON list of resources, or null when it is not one. */
69
+ export function storedResourceList(text: string): string[] | null {
70
+ const value = parseJsonOrNull(text)
71
+ return Array.isArray(value) && value.length > 0 && value.every((entry): entry is string => typeof entry === 'string') ? value : null
40
72
  }
41
73
 
42
74
  /**
43
75
  * Resolve a client and its redirect URI. Until this succeeds nothing may be redirected to
44
76
  * `redirect_uri`. An unregistered client id is refused before any metadata fetch.
45
77
  */
46
- export async function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<EstablishedClient | null> {
78
+ export async function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<ManagedClient | null> {
47
79
  const registration = config.clients.find((client) => client.clientId === clientId)
48
80
  if (registration === undefined || !registration.redirectUris.includes(redirectUri)) return null
49
81
  const metadata = await clientMetadata(registration)
50
82
  if (metadata === null || !metadata.redirect_uris.includes(redirectUri)) return null
51
- return { registration, metadata }
83
+ return { kind: 'managed', registration, metadata }
52
84
  }
53
85
 
86
+ /** What a consent grants: a registered resource, or an identity-only client's own resource. */
87
+ export type AuthorizationTarget = Pick<OAuthResourceDto, 'app' | 'resource'>
88
+
54
89
  /** Record the consent and return the plaintext authorization code — the only time it exists. */
55
90
  export async function grantAuthorization(
56
91
  services: Services,
57
- input: { request: OAuthAuthorizationRequest; resource: OAuthResourceDto; scopes: string[]; session: SessionRow; requestId: string },
92
+ input: { request: OAuthAuthorizationRequest; resource: AuthorizationTarget; scopes: string[]; session: SessionRow; requestId: string },
58
93
  ): Promise<string> {
59
94
  const now = unixNow()
60
95
  const code = generateToken()
@@ -67,6 +102,7 @@ export async function grantAuthorization(
67
102
  client_id: input.request.client_id,
68
103
  app: input.resource.app,
69
104
  resource: input.resource.resource,
105
+ resources: null,
70
106
  scopes: JSON.stringify(input.scopes),
71
107
  created_at: now,
72
108
  expires_at: input.session.expires_at,
@@ -92,19 +128,32 @@ export async function grantAuthorization(
92
128
  return code
93
129
  }
94
130
 
95
- export type OAuthTokenOutcome = { ok: true; body: OAuthTokenResponse } | { ok: false; error: 'invalid_grant' }
131
+ /** RFC 6749 §5.2 and RFC 8628 §3.5: what a refused token request answers. */
132
+ export type OAuthTokenError =
133
+ | 'invalid_grant'
134
+ | 'invalid_target'
135
+ | 'unauthorized_client'
136
+ | 'authorization_pending'
137
+ | 'slow_down'
138
+ | 'access_denied'
139
+ | 'expired_token'
140
+
141
+ export type OAuthTokenOutcome = { ok: true; body: OAuthTokenResponse } | { ok: false; error: OAuthTokenError }
96
142
 
97
143
  /** Redeem a code or rotate a refresh token for a client `authenticateOAuthClient` established. */
98
144
  export async function exchangeOAuthToken(
99
145
  services: Services,
100
146
  env: SigningEnv,
101
147
  client: EstablishedClient,
102
- input: OAuthTokenRequest,
148
+ input: Exclude<OAuthTokenRequest, { grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE }>,
103
149
  requestId: string,
104
150
  ): Promise<OAuthTokenOutcome> {
105
- return input.grant_type === 'authorization_code'
106
- ? redeemCode(services, env, client.metadata, input, requestId)
107
- : rotateRefreshToken(services, env, client.metadata, input, requestId)
151
+ const grantTypes = clientGrantTypes(client)
152
+ if (input.grant_type === 'authorization_code') {
153
+ // RFC 6749 §5.2: the CLI client may not use this grant type; refused before the code is spent.
154
+ return client.kind === 'managed' ? redeemCode(services, env, client.metadata, input, requestId) : { ok: false, error: 'unauthorized_client' }
155
+ }
156
+ return rotateRefreshToken(services, env, grantTypes, input, requestId)
108
157
  }
109
158
 
110
159
  async function redeemCode(
@@ -128,12 +177,12 @@ async function redeemCode(
128
177
  const grant = await repository.grant(code.grant_id)
129
178
  const proof = timingSafeEqualHex(await hashToken(await pkceChallenge(input.code_verifier)), await hashToken(code.challenge))
130
179
  if (
131
- !proof || code.expires_at <= now || grant === null || grant.client_id !== input.client_id || grant.resource !== input.resource
180
+ !proof || code.expires_at <= now || grant === null || grant.client_id !== input.client_id || !grantResources(grant).includes(input.resource)
132
181
  || code.redirect_uri !== input.redirect_uri
133
182
  ) {
134
183
  return { ok: false, error: 'invalid_grant' }
135
184
  }
136
- const access = await mintForGrant(services, env, grant, now)
185
+ const access = await mintForGrant(services, env, grant, input.resource, now)
137
186
  if (access === null) return { ok: false, error: 'invalid_grant' }
138
187
  if (!metadata.grant_types.includes('refresh_token')) return { ok: true, body: access }
139
188
  const refreshToken = generateToken()
@@ -144,14 +193,22 @@ async function redeemCode(
144
193
  async function rotateRefreshToken(
145
194
  services: Services,
146
195
  env: SigningEnv,
147
- metadata: OAuthClientMetadataDocument,
196
+ grantTypes: readonly string[],
148
197
  input: Extract<OAuthTokenRequest, { grant_type: 'refresh_token' }>,
149
198
  requestId: string,
150
199
  ): Promise<OAuthTokenOutcome> {
151
- if (!metadata.grant_types.includes('refresh_token')) return { ok: false, error: 'invalid_grant' }
200
+ if (!grantTypes.includes('refresh_token')) return { ok: false, error: 'invalid_grant' }
152
201
  const repository = services.repositories.oauth
153
202
  const now = unixNow()
154
203
  const hash = await hashToken(input.refresh_token)
204
+ // RFC 8707: a live token asking for a resource its grant does not cover is refused unspent, so the client keeps it.
205
+ const unspent = await repository.refreshToken(hash)
206
+ if (unspent !== null && unspent.used_at === null) {
207
+ const covering = await repository.grant(unspent.grant_id)
208
+ if (covering !== null && covering.client_id === input.client_id && !grantResources(covering).includes(input.resource)) {
209
+ return { ok: false, error: 'invalid_target' }
210
+ }
211
+ }
155
212
  const presented = await repository.consumeRefreshToken(hash, now)
156
213
  if (presented === null) {
157
214
  const spent = await repository.refreshToken(hash)
@@ -160,10 +217,10 @@ async function rotateRefreshToken(
160
217
  return { ok: false, error: 'invalid_grant' }
161
218
  }
162
219
  const grant = await repository.grant(presented.grant_id)
163
- if (presented.expires_at <= now || grant === null || grant.client_id !== input.client_id || grant.resource !== input.resource) {
220
+ if (presented.expires_at <= now || grant === null || grant.client_id !== input.client_id || !grantResources(grant).includes(input.resource)) {
164
221
  return { ok: false, error: 'invalid_grant' }
165
222
  }
166
- const access = await mintForGrant(services, env, grant, now)
223
+ const access = await mintForGrant(services, env, grant, input.resource, now)
167
224
  if (access === null) return { ok: false, error: 'invalid_grant' }
168
225
  const next = generateToken()
169
226
  await repository.insertRefreshToken({ token_hash: await hashToken(next), grant_id: grant.id, expires_at: grant.expires_at })
@@ -190,8 +247,15 @@ export async function revokeOAuthToken(services: Services, env: SigningEnv, inpu
190
247
  }
191
248
  }
192
249
 
193
- async function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGrantRow, now: number): Promise<OAuthTokenResponse | null> {
194
- const authority = await grantAuthority(services, grant, now)
250
+ /** An access token for `resource`, one of the grant's resources, carrying the grant's live authority there. */
251
+ export async function mintForGrant(
252
+ services: Services,
253
+ env: SigningEnv,
254
+ grant: OAuthGrantRow,
255
+ resource: string,
256
+ now: number,
257
+ ): Promise<OAuthTokenResponse | null> {
258
+ const authority = await grantAuthority(services, grant, now, resource)
195
259
  if (authority === null) return null
196
260
  // A replay or a revocation may have landed while authority was resolved; read the grant once more.
197
261
  const current = await services.repositories.oauth.grant(grant.id)
@@ -200,7 +264,7 @@ async function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGra
200
264
  const claims = buildResourceAccessClaims({
201
265
  iss: services.config.issuer,
202
266
  app: grant.app,
203
- resource: grant.resource,
267
+ resource,
204
268
  subject: authority.principal.id,
205
269
  label: authority.principal.label,
206
270
  permissions: authority.permissions,
@@ -230,13 +294,12 @@ export async function grantAuthority(
230
294
  services: Services,
231
295
  grant: OAuthGrantRow,
232
296
  now: number,
297
+ resourceUri: string = grant.resource,
233
298
  ): Promise<{ principal: PrincipalRow; scopes: string[]; permissions: PermissionEntry[]; expiresAt: number | null } | null> {
234
299
  const config = services.config.oauth
235
- if (config === null || grant.revoked_at !== null || grant.expires_at <= now) return null
236
- const resource = config.resources.find((entry) => entry.resource === grant.resource && entry.app === grant.app)
237
- if (resource === undefined || !config.clients.some((client) => client.clientId === grant.client_id)) return null
300
+ if (config === null || grant.revoked_at !== null || grant.expires_at <= now || !grantResources(grant).includes(resourceUri)) return null
238
301
  const scopes = parseOAuthScopes(parseJsonOrNull(grant.scopes))
239
- const ceiling = scopes === null ? null : scopeCeiling(resource, scopes)
302
+ const ceiling = scopes === null ? null : grantCeiling(config, grant, resourceUri, scopes)
240
303
  if (scopes === null || ceiling === null) return null
241
304
  const session = await services.repositories.sessions.getActiveSessionById(grant.session_id)
242
305
  if (session === null || session.app !== null || session.principal_id !== grant.principal_id || !sessionUsable(session, services.config, now)) {
@@ -244,30 +307,60 @@ export async function grantAuthority(
244
307
  }
245
308
  const principal = await services.repositories.principals.getPrincipalById(grant.principal_id)
246
309
  if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') return null
310
+ // No grant is read for an identity resource: its token names the person and carries no permission.
311
+ if (ceiling.kind === 'identity') return { principal, scopes, permissions: [], expiresAt: sessionEndsAt(session, services.config) }
247
312
  const live = await resolveAuthorityAt(services, principal, grant.app)
248
- const permissions = narrowPermissions(live.permissions, ceiling)
313
+ const permissions = narrowPermissions(live.permissions, ceiling.permissions)
249
314
  // A refreshed token ends with its login too: an OIDC login issued before the cap stores a later expiry than its end.
250
315
  const expiresAt = Math.min(authorityDeadline(live, permissions, now) ?? Number.POSITIVE_INFINITY, sessionEndsAt(session, services.config))
251
316
  return { principal, scopes, permissions, expiresAt }
252
317
  }
253
318
 
319
+ /**
320
+ * What a grant's token may carry at `resourceUri` under the current configuration, or null when its client or resource
321
+ * is no longer configured for it. An identity-only client is served its own resource alone, so a grant it holds for
322
+ * any other one (given before it was bound) mints nothing, and a grant for an identity resource carries no permission.
323
+ */
324
+ function grantCeiling(
325
+ config: OAuthConfig,
326
+ grant: OAuthGrantRow,
327
+ resourceUri: string,
328
+ scopes: readonly string[],
329
+ ): { kind: 'identity' } | { kind: 'scoped'; permissions: KeyGrant[] } | null {
330
+ const cli = grant.client_id === OAUTH_CLI_CLIENT_ID
331
+ const client = config.clients.find((entry) => entry.clientId === grant.client_id)
332
+ if (!cli && client === undefined) return null
333
+ const identity = client?.identity
334
+ if (identity !== undefined) {
335
+ const matches = identity.resource === resourceUri && identity.app === grant.app && sameScopes(scopes, [OAUTH_IDENTITY_SCOPE])
336
+ return matches ? { kind: 'identity' } : null
337
+ }
338
+ const resource = config.resources.find((entry) => entry.resource === resourceUri && entry.app === grant.app && servesClient(entry, cli))
339
+ const permissions = resource === undefined ? null : scopeCeiling(resource, scopes)
340
+ return permissions === null ? null : { kind: 'scoped', permissions }
341
+ }
342
+
343
+ function sameScopes(scopes: readonly string[], expected: readonly string[]): boolean {
344
+ return scopes.length === expected.length && scopes.every((scope, index) => scope === expected[index])
345
+ }
346
+
254
347
  /** The union of the scopes' grants, or null when a scope is no longer configured. */
255
348
  export function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null {
256
349
  const ceiling: KeyGrant[] = []
257
350
  for (const scope of scopes) {
258
- const grant = resource.scopeGrants.find((entry) => entry.scope === scope)
259
- if (grant === undefined) return null
260
- ceiling.push(...grant.permissions)
351
+ const permissions = resolveOAuthScopeToken(scope, resource)
352
+ if (permissions === null) return null
353
+ ceiling.push(...permissions)
261
354
  }
262
355
  return ceiling
263
356
  }
264
357
 
265
358
  /** The record of a grant's revocation: by its client, or by IAM on a replayed code or refresh token. */
266
- function grantRevocation(
359
+ export function grantRevocation(
267
360
  requestId: string,
268
361
  grantId: string,
269
362
  clientId: string,
270
- reason: 'code_replay' | 'refresh_replay' | 'client_revocation',
363
+ reason: 'code_replay' | 'refresh_replay' | 'device_code_replay' | 'client_revocation',
271
364
  ): AuditEventInput {
272
365
  return {
273
366
  requestId,
@@ -124,8 +124,10 @@ const AUDIT_PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?'
124
124
  * The INSERT of one audit row, for the batch of an unconditional change it records: the row and the change commit
125
125
  * together, and a failed insert rolls the change back. Diff and metadata are stored JSON-encoded.
126
126
  */
127
- export function auditEventStatement(db: SqlDatabase, event: AuditEventInput): SqlStatement {
128
- return db.prepare(`INSERT INTO audit_events ${AUDIT_COLUMNS} VALUES (${AUDIT_PLACEHOLDERS})`).bind(...auditValues(uuidv7(), event))
127
+ /** The INSERT of one audit row; with `guard`, written only when the guard finds its row (see `SqlGuard`). */
128
+ export function auditEventStatement(db: SqlDatabase, event: AuditEventInput, guard?: SqlGuard): SqlStatement {
129
+ const insert = guardedInsert(`audit_events ${AUDIT_COLUMNS}`, AUDIT_PLACEHOLDERS, auditValues(uuidv7(), event), guard)
130
+ return db.prepare(insert.sql).bind(...insert.binds)
129
131
  }
130
132
 
131
133
  /**
@@ -1,5 +1,6 @@
1
1
  import type { SqlDatabase } from '@fabrika/platform'
2
- import { type AuditEventInput, auditEventStatement, AuditWriter } from './audit'
2
+ import { parseJsonOrNull } from '../json'
3
+ import { type AuditEventInput, auditEventStatement, AuditWriter, guardedInsert, type SqlGuard } from './audit'
3
4
 
4
5
  export interface OAuthGrantRow {
5
6
  id: string
@@ -7,7 +8,10 @@ export interface OAuthGrantRow {
7
8
  session_id: string
8
9
  client_id: string
9
10
  app: string
11
+ /** The grant's first resource; `resources` lists them all when it was given for several. */
10
12
  resource: string
13
+ /** JSON array of every resource of the grant, all of `app`; null when `resource` is the only one. */
14
+ resources: string | null
11
15
  /** JSON array of the consented scope names. */
12
16
  scopes: string
13
17
  created_at: number
@@ -31,6 +35,37 @@ export interface OAuthRefreshTokenRow {
31
35
  used_at: number | null
32
36
  }
33
37
 
38
+ /** An RFC 8628 attempt. `principal_id`, `session_id` and `grant_expires_at` are set by its approval, `grant_id` by its redemption. */
39
+ export interface OAuthDeviceAuthorizationRow {
40
+ device_code_hash: string
41
+ user_code_hash: string
42
+ client_id: string
43
+ app: string
44
+ /** JSON array of the resources the grant will cover, all of `app`. */
45
+ resources: string
46
+ /** JSON array of the requested scope tokens. */
47
+ scopes: string
48
+ interval_seconds: number
49
+ next_poll_at: number
50
+ created_at: number
51
+ expires_at: number
52
+ status: 'pending' | 'approved' | 'denied' | 'redeemed'
53
+ principal_id: string | null
54
+ session_id: string | null
55
+ grant_expires_at: number | null
56
+ grant_id: string | null
57
+ }
58
+
59
+ export type NewOAuthDeviceAuthorization = Pick<
60
+ OAuthDeviceAuthorizationRow,
61
+ 'device_code_hash' | 'user_code_hash' | 'client_id' | 'app' | 'resources' | 'scopes' | 'interval_seconds' | 'created_at' | 'expires_at'
62
+ >
63
+
64
+ /** A poll arriving this many seconds early still counts as on time, for a client whose timer runs a little fast. */
65
+ const POLL_TOLERANCE_SECONDS = 1
66
+ /** RFC 8628 §3.5: each `slow_down` adds five seconds; this is where it stops. */
67
+ const MAX_POLL_INTERVAL_SECONDS = 60
68
+
34
69
  /** Codes and refresh tokens are addressed by hash only; the plaintext never reaches this layer. */
35
70
  export class OAuthRepository {
36
71
  constructor(
@@ -40,15 +75,20 @@ export class OAuthRepository {
40
75
 
41
76
  /** Record a consent, its one authorization code and `audit` together. */
42
77
  async createGrant(grant: OAuthGrantRow, code: Omit<OAuthCodeRow, 'grant_id' | 'used_at'>, audit?: AuditEventInput): Promise<void> {
78
+ const listed = grant.resources === null ? null : parseJsonOrNull(grant.resources)
79
+ if (listed !== null && (!Array.isArray(listed) || listed[0] !== grant.resource)) {
80
+ throw new Error('an OAuth grant names its first resource as `resource`')
81
+ }
43
82
  await this.db.batch([
44
- this.db.prepare(`INSERT INTO oauth_grants (id, principal_id, session_id, client_id, app, resource, scopes, created_at, expires_at, revoked_at)
45
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`).bind(
83
+ this.db.prepare(`INSERT INTO oauth_grants (id, principal_id, session_id, client_id, app, resource, resources, scopes, created_at, expires_at,
84
+ revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`).bind(
46
85
  grant.id,
47
86
  grant.principal_id,
48
87
  grant.session_id,
49
88
  grant.client_id,
50
89
  grant.app,
51
90
  grant.resource,
91
+ grant.resources,
52
92
  grant.scopes,
53
93
  grant.created_at,
54
94
  grant.expires_at,
@@ -99,6 +139,132 @@ export class OAuthRepository {
99
139
  return this.db.prepare('SELECT * FROM oauth_refresh_tokens WHERE token_hash = ?').bind(tokenHash).first<OAuthRefreshTokenRow>()
100
140
  }
101
141
 
142
+ /** Record a device attempt. False when either code's hash is taken already, so the caller draws new codes. */
143
+ async startDeviceAuthorization(row: NewOAuthDeviceAuthorization): Promise<boolean> {
144
+ const inserted = await this.db.prepare(
145
+ `INSERT INTO oauth_device_authorizations (device_code_hash, user_code_hash, client_id, app, resources, scopes,
146
+ interval_seconds, next_poll_at, created_at, expires_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
147
+ ON CONFLICT DO NOTHING RETURNING device_code_hash`,
148
+ ).bind(
149
+ row.device_code_hash,
150
+ row.user_code_hash,
151
+ row.client_id,
152
+ row.app,
153
+ row.resources,
154
+ row.scopes,
155
+ row.interval_seconds,
156
+ row.created_at,
157
+ row.created_at,
158
+ row.expires_at,
159
+ ).first<{ device_code_hash: string }>()
160
+ return inserted !== null
161
+ }
162
+
163
+ deviceAuthorization(deviceCodeHash: string): Promise<OAuthDeviceAuthorizationRow | null> {
164
+ return this.db.prepare('SELECT * FROM oauth_device_authorizations WHERE device_code_hash = ?').bind(deviceCodeHash)
165
+ .first<OAuthDeviceAuthorizationRow>()
166
+ }
167
+
168
+ /** The attempt a person may still decide: pending and unexpired. */
169
+ pendingDeviceAuthorization(userCodeHash: string, now: number): Promise<OAuthDeviceAuthorizationRow | null> {
170
+ return this.db.prepare(`SELECT * FROM oauth_device_authorizations WHERE user_code_hash = ? AND status = 'pending' AND expires_at > ?`)
171
+ .bind(userCodeHash, now).first<OAuthDeviceAuthorizationRow>()
172
+ }
173
+
174
+ /** Approve a pending attempt under the approver's IAM session. False when it was decided, or expired, meanwhile. */
175
+ async approveDeviceAuthorization(
176
+ userCodeHash: string,
177
+ approval: { principalId: string; sessionId: string; grantExpiresAt: number },
178
+ now: number,
179
+ ): Promise<boolean> {
180
+ const row = await this.db.prepare(
181
+ `UPDATE oauth_device_authorizations SET status = 'approved', principal_id = ?, session_id = ?, grant_expires_at = ?
182
+ WHERE user_code_hash = ? AND status = 'pending' AND expires_at > ? RETURNING device_code_hash`,
183
+ )
184
+ .bind(approval.principalId, approval.sessionId, approval.grantExpiresAt, userCodeHash, now).first<{ device_code_hash: string }>()
185
+ return row !== null
186
+ }
187
+
188
+ async denyDeviceAuthorization(userCodeHash: string, now: number): Promise<boolean> {
189
+ const row = await this.db.prepare(`UPDATE oauth_device_authorizations SET status = 'denied'
190
+ WHERE user_code_hash = ? AND status = 'pending' AND expires_at > ? RETURNING device_code_hash`)
191
+ .bind(userCodeHash, now).first<{ device_code_hash: string }>()
192
+ return row !== null
193
+ }
194
+
195
+ /**
196
+ * Admit one poll of an attempt (RFC 8628 §3.5). A poll before the interval has passed is refused and lengthens the
197
+ * interval by five seconds, which the client is told to add with `slow_down`.
198
+ */
199
+ async admitDevicePoll(deviceCodeHash: string, now: number): Promise<boolean> {
200
+ const admitted = await this.db.prepare(`UPDATE oauth_device_authorizations SET next_poll_at = ? + interval_seconds - ?
201
+ WHERE device_code_hash = ? AND next_poll_at <= ? RETURNING device_code_hash`)
202
+ .bind(now, POLL_TOLERANCE_SECONDS, deviceCodeHash, now).first<{ device_code_hash: string }>()
203
+ if (admitted !== null) return true
204
+ await this.db.prepare(`UPDATE oauth_device_authorizations SET
205
+ interval_seconds = CASE WHEN interval_seconds + 5 > ? THEN ? ELSE interval_seconds + 5 END,
206
+ next_poll_at = ? + CASE WHEN interval_seconds + 5 > ? THEN ? ELSE interval_seconds + 5 END - ?
207
+ WHERE device_code_hash = ?`)
208
+ .bind(
209
+ MAX_POLL_INTERVAL_SECONDS,
210
+ MAX_POLL_INTERVAL_SECONDS,
211
+ now,
212
+ MAX_POLL_INTERVAL_SECONDS,
213
+ MAX_POLL_INTERVAL_SECONDS,
214
+ POLL_TOLERANCE_SECONDS,
215
+ deviceCodeHash,
216
+ ).run()
217
+ return false
218
+ }
219
+
220
+ /**
221
+ * Spend an approved attempt for `grant`: the claim, the grant, its record and its first refresh token in one batch.
222
+ * Every write after the claim requires the claim this batch made (`grant_id` names this grant), so exactly one poll
223
+ * gives a grant, and a refused or failed claim writes nothing. Answers the claimed row, or null.
224
+ */
225
+ async redeemDeviceAuthorization(
226
+ deviceCodeHash: string,
227
+ grant: OAuthGrantRow,
228
+ refreshTokenHash: string,
229
+ audit: AuditEventInput,
230
+ now: number,
231
+ ): Promise<OAuthDeviceAuthorizationRow | null> {
232
+ const claimed: SqlGuard = {
233
+ sql: 'SELECT 1 FROM oauth_device_authorizations WHERE device_code_hash = ? AND grant_id = ?',
234
+ binds: [deviceCodeHash, grant.id],
235
+ }
236
+ const grantInsert = guardedInsert(
237
+ 'oauth_grants (id, principal_id, session_id, client_id, app, resource, resources, scopes, created_at, expires_at, revoked_at)',
238
+ '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL',
239
+ [
240
+ grant.id,
241
+ grant.principal_id,
242
+ grant.session_id,
243
+ grant.client_id,
244
+ grant.app,
245
+ grant.resource,
246
+ grant.resources,
247
+ grant.scopes,
248
+ grant.created_at,
249
+ grant.expires_at,
250
+ ],
251
+ claimed,
252
+ )
253
+ const refreshInsert = guardedInsert('oauth_refresh_tokens (token_hash, grant_id, expires_at, used_at)', '?, ?, ?, NULL', [
254
+ refreshTokenHash,
255
+ grant.id,
256
+ grant.expires_at,
257
+ ], claimed)
258
+ const [claim] = await this.db.batch<OAuthDeviceAuthorizationRow>([
259
+ this.db.prepare(`UPDATE oauth_device_authorizations SET status = 'redeemed', grant_id = ?
260
+ WHERE device_code_hash = ? AND status = 'approved' AND expires_at > ? RETURNING *`).bind(grant.id, deviceCodeHash, now),
261
+ this.db.prepare(grantInsert.sql).bind(...grantInsert.binds),
262
+ auditEventStatement(this.db, audit, claimed),
263
+ this.db.prepare(refreshInsert.sql).bind(...refreshInsert.binds),
264
+ ])
265
+ return claim?.results[0] ?? null
266
+ }
267
+
102
268
  /** Record an accepted client assertion's `jti`. False when the client already presented it: a replay. */
103
269
  async recordClientAssertion(clientId: string, jti: string, expiresAt: number): Promise<boolean> {
104
270
  const row = await this.db.prepare(
@@ -109,7 +275,7 @@ export class OAuthRepository {
109
275
  }
110
276
 
111
277
  /**
112
- * Delete codes, refresh tokens and client assertion ids past expiry. Spent rows stay until then because they are what
278
+ * Delete codes, refresh tokens, client assertion ids and device attempts past expiry. Spent rows stay until then because they are what
113
279
  * detects a replay. Grants go with their session row (`ON DELETE CASCADE`), which shares their expiry.
114
280
  */
115
281
  async prune(now: number): Promise<void> {
@@ -117,6 +283,7 @@ export class OAuthRepository {
117
283
  this.db.prepare('DELETE FROM oauth_codes WHERE expires_at <= ?').bind(now),
118
284
  this.db.prepare('DELETE FROM oauth_refresh_tokens WHERE expires_at <= ?').bind(now),
119
285
  this.db.prepare('DELETE FROM oauth_client_assertions WHERE expires_at <= ?').bind(now),
286
+ this.db.prepare('DELETE FROM oauth_device_authorizations WHERE expires_at <= ?').bind(now),
120
287
  ])
121
288
  }
122
289
  }
package/src/services.ts CHANGED
@@ -97,7 +97,7 @@ const APP_ID = /^[a-z0-9][a-z0-9-]*$/
97
97
  * empty = no JWT may administer. A malformed entry is REFUSED rather than skipped: an entry no `aud`
98
98
  * can ever equal would otherwise read as a registry while admitting nobody.
99
99
  */
100
- function parseAdminAudiences(raw: string | undefined): ReadonlySet<string> {
100
+ export function parseAdminAudiences(raw: string | undefined): ReadonlySet<string> {
101
101
  if (raw === undefined) {
102
102
  return DEFAULT_ADMIN_AUDIENCES
103
103
  }
@@ -152,7 +152,7 @@ export function buildServices(env: Env): Services {
152
152
  oidc: { enabled: oidcEnabled, sessionCapSeconds: parseOidcSessionSeconds(env.OIDC_SESSION_HOURS) },
153
153
  password: { enabled: passwordEnabled, minLengthFloor: passwordMinLengthFloor(passwordCost) },
154
154
  },
155
- oauth: parseOAuthConfig(env.OAUTH_CONFIG),
155
+ oauth: parseOAuthConfig(env.OAUTH_CONFIG, platformAudiencesFor(adminAudiences)),
156
156
  retention: parseRetention({ authLogDays: env.AUTH_LOG_RETENTION_DAYS, auditDays: env.AUDIT_RETENTION_DAYS }),
157
157
  issuer: env.ISSUER,
158
158
  },
@@ -37,8 +37,9 @@ export interface Env {
37
37
  */
38
38
  ADMIN_AUDIENCES?: string;
39
39
  /**
40
- * JSON: the OAuth 2.1 authorization server for MCP clients (`src/oauth-config.ts`). Absent or empty
41
- * means OAuth is off and its routes 404. Deploy var `FABRIKA_IAM_OAUTH_CONFIG`. Malformed fails the boot.
40
+ * JSON: the OAuth 2.1 authorization server's clients and resources (`src/oauth-config.ts`). Absent or empty means
41
+ * OAuth is off and its routes 404. On Bun, `FABRIKA_IAM_OAUTH_CONFIG`; a Cloudflare deploy computes it in
42
+ * `fabrika.config.ts`. Malformed fails the boot.
42
43
  */
43
44
  OAUTH_CONFIG?: string;
44
45
  /**
@@ -9,8 +9,9 @@ export interface OAuthConfig {
9
9
  resources: OAuthResourceDto[];
10
10
  }
11
11
  /**
12
- * Parse `OAUTH_CONFIG`. Absent or empty disables OAuth; anything malformed THROWS, so a typo fails the
13
- * boot instead of quietly serving fewer clients or scopes than the operator wrote. Unknown keys are
14
- * refused for the same reason.
12
+ * Parse `OAUTH_CONFIG`. Absent or empty disables OAuth; anything malformed THROWS, so a typo fails the boot instead of
13
+ * quietly serving fewer clients or scopes than the operator wrote. Unknown keys are refused for the same reason.
14
+ * `clients` may be empty: the command-line client is IAM's own and never listed. A client's identity resource names
15
+ * neither a registered resource nor a `platformAudiences` app, so its token is never one an installation service accepts.
15
16
  */
16
- export declare function parseOAuthConfig(raw: string | undefined): OAuthConfig | null;
17
+ export declare function parseOAuthConfig(raw: string | undefined, platformAudiences: ReadonlySet<string>): OAuthConfig | null;
@@ -0,0 +1,7 @@
1
+ import type { OAuthConfig } from './oauth-config';
2
+ import type { Services } from './services';
3
+ /**
4
+ * `/oauth/device`: a signed-in person enters the code a device shows, reads what it asks for and decides. GET only
5
+ * renders the entry form, so a link can neither decide nor spend the person's code-entry budget.
6
+ */
7
+ export declare function handleDevicePage(request: Request, services: Services, config: OAuthConfig): Promise<Response>;
@@ -0,0 +1,51 @@
1
+ import { OAUTH_DEVICE_CODE_GRANT_TYPE, type OAuthDeviceAuthorizationRequest, type OAuthDeviceAuthorizationResponse, type OAuthTokenRequest } from '@fabrika/iam-contract';
2
+ import type { Env } from './env';
3
+ import { type EstablishedClient, type OAuthTokenOutcome } from './oauth';
4
+ import type { OAuthConfig } from './oauth-config';
5
+ import type { OAuthDeviceAuthorizationRow } from './repositories/oauth';
6
+ import type { Services } from './services';
7
+ type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>;
8
+ export declare const OAUTH_DEVICE_PATH = "/oauth/device";
9
+ /** RFC 8628 §3.2 `expires_in`: a person has five minutes to enter the code and decide. */
10
+ export declare const OAUTH_DEVICE_ATTEMPT_TTL_SECONDS = 300;
11
+ export declare const OAUTH_DEVICE_POLL_INTERVAL_SECONDS = 5;
12
+ export type DeviceStartOutcome = {
13
+ ok: true;
14
+ body: OAuthDeviceAuthorizationResponse;
15
+ } | {
16
+ ok: false;
17
+ error: 'unauthorized_client' | 'invalid_target' | 'invalid_scope' | 'temporarily_unavailable';
18
+ };
19
+ /** The user code as a person types it: upper case, without the separator or spaces. Null when it cannot be one. */
20
+ export declare function normalizeUserCode(raw: string): string | null;
21
+ export declare function formatUserCode(code: string): string;
22
+ export declare function userCodeHash(code: string): Promise<string>;
23
+ /** RFC 8628 §3.1–3.2: record an attempt for the CLI client and answer its codes. */
24
+ export declare function startDeviceAuthorization(services: Services, config: OAuthConfig, request: OAuthDeviceAuthorizationRequest, clientAddress: string | null): Promise<DeviceStartOutcome>;
25
+ export type CodeEntry = {
26
+ kind: 'found';
27
+ attempt: OAuthDeviceAuthorizationRow;
28
+ userCode: string;
29
+ } | {
30
+ kind: 'unknown';
31
+ } | {
32
+ kind: 'throttled';
33
+ };
34
+ /**
35
+ * The pending attempt a signed-in person's code names. Every entry counts against that person before the lookup, and
36
+ * once the budget is spent even a right code is refused until the block ends (RFC 8628 §5.1).
37
+ */
38
+ export declare function enterUserCode(services: Services, principalId: string, raw: string): Promise<CodeEntry>;
39
+ /** The attempt's stored scope tokens and resources, or null when either does not parse. */
40
+ export declare function attemptRequest(attempt: OAuthDeviceAuthorizationRow): {
41
+ scopes: string[];
42
+ resources: string[];
43
+ } | null;
44
+ /**
45
+ * RFC 8628 §3.4–3.5: one poll of the token endpoint. An approved attempt is spent for a new grant, bound to the IAM
46
+ * session it was approved under, and answers a token for the requested resource and the grant's first refresh token.
47
+ */
48
+ export declare function redeemDeviceCode(services: Services, env: SigningEnv, client: EstablishedClient, input: Extract<OAuthTokenRequest, {
49
+ grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE;
50
+ }>, requestId: string): Promise<OAuthTokenOutcome>;
51
+ export {};