@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/src/oauth.ts CHANGED
@@ -3,19 +3,22 @@ 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
+ type OAuthAuthorizationRequest,
13
+ type OAuthClientMetadataDocument,
14
+ type OAuthResourceDto,
15
+ type OAuthRevocationRequest,
16
+ type OAuthTokenRequest,
17
+ type OAuthTokenResponse,
18
+ resolveOAuthScopeToken,
16
19
  } from '@fabrika/iam-contract'
17
20
  import { uuidv7 } from '@fabrika/platform'
18
- import { sessionUsable } from './auth'
21
+ import { sessionEndsAt, sessionUsable } from './auth'
19
22
  import { type AuditEventInput, type OAuthGrantRow, type PrincipalRow, principalStatus, type SessionRow } from './db'
20
23
  import type { Env } from './env'
21
24
  import { parseJsonOrNull } from './json'
@@ -34,21 +37,49 @@ export const OAUTH_CODE_TTL_SECONDS = 60
34
37
 
35
38
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
36
39
 
37
- export interface EstablishedClient {
38
- registration: ManagedOAuthClient
39
- metadata: OAuthClientMetadataDocument
40
+ /**
41
+ * A client an authorization or token request comes from: an operator-registered CIMD client, or the installation's own
42
+ * command-line client, a public client IAM knows without a document. The CLI client has no redirect URI, so it never
43
+ * completes an authorization request; it redeems the grants IAM gives it otherwise and refreshes them.
44
+ */
45
+ export type EstablishedClient =
46
+ | { kind: 'managed'; registration: ManagedOAuthClient; metadata: OAuthClientMetadataDocument }
47
+ | { kind: 'cli'; clientId: string }
48
+
49
+ export type ManagedClient = Extract<EstablishedClient, { kind: 'managed' }>
50
+
51
+ /** The grant types a client may use at the token endpoint: its document's, or the CLI client's fixed set. */
52
+ function clientGrantTypes(client: EstablishedClient): readonly string[] {
53
+ return client.kind === 'cli' ? ['refresh_token'] : client.metadata.grant_types
54
+ }
55
+
56
+ /** Whether `resource` is served to the command-line client (`cli`) or to the managed clients; never to both. */
57
+ export function servesClient(resource: OAuthResourceDto, cli: boolean): boolean {
58
+ return (resource.client === 'cli') === cli
59
+ }
60
+
61
+ /** The resources a grant was given for: every token it mints names one of them. */
62
+ export function grantResources(grant: Pick<OAuthGrantRow, 'resource' | 'resources'>): string[] {
63
+ const stored = grant.resources === null ? null : storedResourceList(grant.resources)
64
+ return stored ?? [grant.resource]
65
+ }
66
+
67
+ /** A stored JSON list of resources, or null when it is not one. */
68
+ export function storedResourceList(text: string): string[] | null {
69
+ const value = parseJsonOrNull(text)
70
+ return Array.isArray(value) && value.length > 0 && value.every((entry): entry is string => typeof entry === 'string') ? value : null
40
71
  }
41
72
 
42
73
  /**
43
74
  * Resolve a client and its redirect URI. Until this succeeds nothing may be redirected to
44
75
  * `redirect_uri`. An unregistered client id is refused before any metadata fetch.
45
76
  */
46
- export async function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<EstablishedClient | null> {
77
+ export async function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<ManagedClient | null> {
47
78
  const registration = config.clients.find((client) => client.clientId === clientId)
48
79
  if (registration === undefined || !registration.redirectUris.includes(redirectUri)) return null
49
80
  const metadata = await clientMetadata(registration)
50
81
  if (metadata === null || !metadata.redirect_uris.includes(redirectUri)) return null
51
- return { registration, metadata }
82
+ return { kind: 'managed', registration, metadata }
52
83
  }
53
84
 
54
85
  /** Record the consent and return the plaintext authorization code — the only time it exists. */
@@ -67,6 +98,7 @@ export async function grantAuthorization(
67
98
  client_id: input.request.client_id,
68
99
  app: input.resource.app,
69
100
  resource: input.resource.resource,
101
+ resources: null,
70
102
  scopes: JSON.stringify(input.scopes),
71
103
  created_at: now,
72
104
  expires_at: input.session.expires_at,
@@ -92,19 +124,32 @@ export async function grantAuthorization(
92
124
  return code
93
125
  }
94
126
 
95
- export type OAuthTokenOutcome = { ok: true; body: OAuthTokenResponse } | { ok: false; error: 'invalid_grant' }
127
+ /** RFC 6749 §5.2 and RFC 8628 §3.5: what a refused token request answers. */
128
+ export type OAuthTokenError =
129
+ | 'invalid_grant'
130
+ | 'invalid_target'
131
+ | 'unauthorized_client'
132
+ | 'authorization_pending'
133
+ | 'slow_down'
134
+ | 'access_denied'
135
+ | 'expired_token'
136
+
137
+ export type OAuthTokenOutcome = { ok: true; body: OAuthTokenResponse } | { ok: false; error: OAuthTokenError }
96
138
 
97
139
  /** Redeem a code or rotate a refresh token for a client `authenticateOAuthClient` established. */
98
140
  export async function exchangeOAuthToken(
99
141
  services: Services,
100
142
  env: SigningEnv,
101
143
  client: EstablishedClient,
102
- input: OAuthTokenRequest,
144
+ input: Exclude<OAuthTokenRequest, { grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE }>,
103
145
  requestId: string,
104
146
  ): 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)
147
+ const grantTypes = clientGrantTypes(client)
148
+ if (input.grant_type === 'authorization_code') {
149
+ // RFC 6749 §5.2: the CLI client may not use this grant type; refused before the code is spent.
150
+ return client.kind === 'managed' ? redeemCode(services, env, client.metadata, input, requestId) : { ok: false, error: 'unauthorized_client' }
151
+ }
152
+ return rotateRefreshToken(services, env, grantTypes, input, requestId)
108
153
  }
109
154
 
110
155
  async function redeemCode(
@@ -128,12 +173,12 @@ async function redeemCode(
128
173
  const grant = await repository.grant(code.grant_id)
129
174
  const proof = timingSafeEqualHex(await hashToken(await pkceChallenge(input.code_verifier)), await hashToken(code.challenge))
130
175
  if (
131
- !proof || code.expires_at <= now || grant === null || grant.client_id !== input.client_id || grant.resource !== input.resource
176
+ !proof || code.expires_at <= now || grant === null || grant.client_id !== input.client_id || !grantResources(grant).includes(input.resource)
132
177
  || code.redirect_uri !== input.redirect_uri
133
178
  ) {
134
179
  return { ok: false, error: 'invalid_grant' }
135
180
  }
136
- const access = await mintForGrant(services, env, grant, now)
181
+ const access = await mintForGrant(services, env, grant, input.resource, now)
137
182
  if (access === null) return { ok: false, error: 'invalid_grant' }
138
183
  if (!metadata.grant_types.includes('refresh_token')) return { ok: true, body: access }
139
184
  const refreshToken = generateToken()
@@ -144,14 +189,22 @@ async function redeemCode(
144
189
  async function rotateRefreshToken(
145
190
  services: Services,
146
191
  env: SigningEnv,
147
- metadata: OAuthClientMetadataDocument,
192
+ grantTypes: readonly string[],
148
193
  input: Extract<OAuthTokenRequest, { grant_type: 'refresh_token' }>,
149
194
  requestId: string,
150
195
  ): Promise<OAuthTokenOutcome> {
151
- if (!metadata.grant_types.includes('refresh_token')) return { ok: false, error: 'invalid_grant' }
196
+ if (!grantTypes.includes('refresh_token')) return { ok: false, error: 'invalid_grant' }
152
197
  const repository = services.repositories.oauth
153
198
  const now = unixNow()
154
199
  const hash = await hashToken(input.refresh_token)
200
+ // RFC 8707: a live token asking for a resource its grant does not cover is refused unspent, so the client keeps it.
201
+ const unspent = await repository.refreshToken(hash)
202
+ if (unspent !== null && unspent.used_at === null) {
203
+ const covering = await repository.grant(unspent.grant_id)
204
+ if (covering !== null && covering.client_id === input.client_id && !grantResources(covering).includes(input.resource)) {
205
+ return { ok: false, error: 'invalid_target' }
206
+ }
207
+ }
155
208
  const presented = await repository.consumeRefreshToken(hash, now)
156
209
  if (presented === null) {
157
210
  const spent = await repository.refreshToken(hash)
@@ -160,10 +213,10 @@ async function rotateRefreshToken(
160
213
  return { ok: false, error: 'invalid_grant' }
161
214
  }
162
215
  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) {
216
+ if (presented.expires_at <= now || grant === null || grant.client_id !== input.client_id || !grantResources(grant).includes(input.resource)) {
164
217
  return { ok: false, error: 'invalid_grant' }
165
218
  }
166
- const access = await mintForGrant(services, env, grant, now)
219
+ const access = await mintForGrant(services, env, grant, input.resource, now)
167
220
  if (access === null) return { ok: false, error: 'invalid_grant' }
168
221
  const next = generateToken()
169
222
  await repository.insertRefreshToken({ token_hash: await hashToken(next), grant_id: grant.id, expires_at: grant.expires_at })
@@ -190,8 +243,15 @@ export async function revokeOAuthToken(services: Services, env: SigningEnv, inpu
190
243
  }
191
244
  }
192
245
 
193
- async function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGrantRow, now: number): Promise<OAuthTokenResponse | null> {
194
- const authority = await grantAuthority(services, grant, now)
246
+ /** An access token for `resource`, one of the grant's resources, carrying the grant's live authority there. */
247
+ export async function mintForGrant(
248
+ services: Services,
249
+ env: SigningEnv,
250
+ grant: OAuthGrantRow,
251
+ resource: string,
252
+ now: number,
253
+ ): Promise<OAuthTokenResponse | null> {
254
+ const authority = await grantAuthority(services, grant, now, resource)
195
255
  if (authority === null) return null
196
256
  // A replay or a revocation may have landed while authority was resolved; read the grant once more.
197
257
  const current = await services.repositories.oauth.grant(grant.id)
@@ -200,7 +260,7 @@ async function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGra
200
260
  const claims = buildResourceAccessClaims({
201
261
  iss: services.config.issuer,
202
262
  app: grant.app,
203
- resource: grant.resource,
263
+ resource,
204
264
  subject: authority.principal.id,
205
265
  label: authority.principal.label,
206
266
  permissions: authority.permissions,
@@ -230,40 +290,48 @@ export async function grantAuthority(
230
290
  services: Services,
231
291
  grant: OAuthGrantRow,
232
292
  now: number,
293
+ resourceUri: string = grant.resource,
233
294
  ): Promise<{ principal: PrincipalRow; scopes: string[]; permissions: PermissionEntry[]; expiresAt: number | null } | null> {
234
295
  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
296
+ if (config === null || grant.revoked_at !== null || grant.expires_at <= now || !grantResources(grant).includes(resourceUri)) return null
297
+ const resource = config.resources.find((entry) =>
298
+ entry.resource === resourceUri && entry.app === grant.app && servesClient(entry, grant.client_id === OAUTH_CLI_CLIENT_ID)
299
+ )
300
+ const clientKnown = grant.client_id === OAUTH_CLI_CLIENT_ID || config.clients.some((client) => client.clientId === grant.client_id)
301
+ if (resource === undefined || !clientKnown) return null
238
302
  const scopes = parseOAuthScopes(parseJsonOrNull(grant.scopes))
239
303
  const ceiling = scopes === null ? null : scopeCeiling(resource, scopes)
240
304
  if (scopes === null || ceiling === null) return null
241
305
  const session = await services.repositories.sessions.getActiveSessionById(grant.session_id)
242
- if (session === null || session.app !== null || session.principal_id !== grant.principal_id || !sessionUsable(session, services.config)) return null
306
+ if (session === null || session.app !== null || session.principal_id !== grant.principal_id || !sessionUsable(session, services.config, now)) {
307
+ return null
308
+ }
243
309
  const principal = await services.repositories.principals.getPrincipalById(grant.principal_id)
244
310
  if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') return null
245
311
  const live = await resolveAuthorityAt(services, principal, grant.app)
246
312
  const permissions = narrowPermissions(live.permissions, ceiling)
247
- return { principal, scopes, permissions, expiresAt: authorityDeadline(live, permissions, now) }
313
+ // A refreshed token ends with its login too: an OIDC login issued before the cap stores a later expiry than its end.
314
+ const expiresAt = Math.min(authorityDeadline(live, permissions, now) ?? Number.POSITIVE_INFINITY, sessionEndsAt(session, services.config))
315
+ return { principal, scopes, permissions, expiresAt }
248
316
  }
249
317
 
250
318
  /** The union of the scopes' grants, or null when a scope is no longer configured. */
251
319
  export function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null {
252
320
  const ceiling: KeyGrant[] = []
253
321
  for (const scope of scopes) {
254
- const grant = resource.scopeGrants.find((entry) => entry.scope === scope)
255
- if (grant === undefined) return null
256
- ceiling.push(...grant.permissions)
322
+ const permissions = resolveOAuthScopeToken(scope, resource)
323
+ if (permissions === null) return null
324
+ ceiling.push(...permissions)
257
325
  }
258
326
  return ceiling
259
327
  }
260
328
 
261
329
  /** The record of a grant's revocation: by its client, or by IAM on a replayed code or refresh token. */
262
- function grantRevocation(
330
+ export function grantRevocation(
263
331
  requestId: string,
264
332
  grantId: string,
265
333
  clientId: string,
266
- reason: 'code_replay' | 'refresh_replay' | 'client_revocation',
334
+ reason: 'code_replay' | 'refresh_replay' | 'device_code_replay' | 'client_revocation',
267
335
  ): AuditEventInput {
268
336
  return {
269
337
  requestId,
@@ -0,0 +1,25 @@
1
+ /**
2
+ * How long an OIDC login lasts before IAM sends its holder back to the provider, in hours. The provider is where an
3
+ * organization blocks a person, so this bounds how long a person blocked there keeps fabrika access.
4
+ */
5
+ export const DEFAULT_OIDC_SESSION_HOURS = 12
6
+
7
+ /** The longest cap: the lifetime of every IAM login (`SESSION_TTL_SECONDS`, 30 days). */
8
+ export const MAX_OIDC_SESSION_HOURS = 30 * 24
9
+
10
+ const HOURS = /^[1-9][0-9]{0,2}$/
11
+
12
+ /**
13
+ * Parse the cap into seconds. Unset or empty means the default; anything but a whole number of hours from 1 to 720 is
14
+ * refused, so a typo fails the boot instead of capping at a value nobody chose.
15
+ */
16
+ export function parseOidcSessionSeconds(raw: string | undefined, name = 'OIDC_SESSION_HOURS'): number {
17
+ if (raw === undefined || raw.trim() === '') {
18
+ return DEFAULT_OIDC_SESSION_HOURS * 3600
19
+ }
20
+ const value = raw.trim()
21
+ if (!HOURS.test(value) || Number.parseInt(value, 10) > MAX_OIDC_SESSION_HOURS) {
22
+ throw new Error(`${name} must be a whole number of hours from 1 to ${MAX_OIDC_SESSION_HOURS}`)
23
+ }
24
+ return Number.parseInt(value, 10) * 3600
25
+ }
@@ -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
  }