@fabrika/iam 0.9.0-dev.33 → 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.
@@ -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
  }
@@ -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,8 @@ 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.
15
15
  */
16
16
  export declare function parseOAuthConfig(raw: string | undefined): 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 {};
@@ -2,6 +2,9 @@ import type { Env } from './env';
2
2
  import type { Services } from './services';
3
3
  export declare const OAUTH_METADATA_PATH = "/.well-known/oauth-authorization-server";
4
4
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>;
5
- /** The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. */
6
- export declare function handleOAuth(request: Request, services: Services, env: SigningEnv, requestId: string): Promise<Response>;
5
+ /**
6
+ * The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. `clientAddress` is the
7
+ * composition's client coordinate (`client-address.ts`), null where it names none.
8
+ */
9
+ export declare function handleOAuth(request: Request, services: Services, env: SigningEnv, requestId: string, clientAddress: string | null): Promise<Response>;
7
10
  export {};
@@ -1,21 +1,39 @@
1
1
  import { type KeyGrant, type PermissionEntry } from '@fabrika/auth-core';
2
- import type { OAuthAuthorizationRequest, OAuthClientMetadataDocument, OAuthResourceDto, OAuthRevocationRequest, OAuthTokenRequest, OAuthTokenResponse } from '@fabrika/iam-contract';
3
- import { type OAuthGrantRow, type PrincipalRow, type SessionRow } from './db';
2
+ import { OAUTH_DEVICE_CODE_GRANT_TYPE, type OAuthAuthorizationRequest, type OAuthClientMetadataDocument, type OAuthResourceDto, type OAuthRevocationRequest, type OAuthTokenRequest, type OAuthTokenResponse } from '@fabrika/iam-contract';
3
+ import { type AuditEventInput, type OAuthGrantRow, type PrincipalRow, type SessionRow } from './db';
4
4
  import type { Env } from './env';
5
5
  import type { ManagedOAuthClient, OAuthConfig } from './oauth-config';
6
6
  import type { Services } from './services';
7
7
  /** An authorization code is redeemed by the client's back end within seconds of the redirect. */
8
8
  export declare const OAUTH_CODE_TTL_SECONDS = 60;
9
9
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>;
10
- export interface EstablishedClient {
10
+ /**
11
+ * A client an authorization or token request comes from: an operator-registered CIMD client, or the installation's own
12
+ * command-line client, a public client IAM knows without a document. The CLI client has no redirect URI, so it never
13
+ * completes an authorization request; it redeems the grants IAM gives it otherwise and refreshes them.
14
+ */
15
+ export type EstablishedClient = {
16
+ kind: 'managed';
11
17
  registration: ManagedOAuthClient;
12
18
  metadata: OAuthClientMetadataDocument;
13
- }
19
+ } | {
20
+ kind: 'cli';
21
+ clientId: string;
22
+ };
23
+ export type ManagedClient = Extract<EstablishedClient, {
24
+ kind: 'managed';
25
+ }>;
26
+ /** Whether `resource` is served to the command-line client (`cli`) or to the managed clients; never to both. */
27
+ export declare function servesClient(resource: OAuthResourceDto, cli: boolean): boolean;
28
+ /** The resources a grant was given for: every token it mints names one of them. */
29
+ export declare function grantResources(grant: Pick<OAuthGrantRow, 'resource' | 'resources'>): string[];
30
+ /** A stored JSON list of resources, or null when it is not one. */
31
+ export declare function storedResourceList(text: string): string[] | null;
14
32
  /**
15
33
  * Resolve a client and its redirect URI. Until this succeeds nothing may be redirected to
16
34
  * `redirect_uri`. An unregistered client id is refused before any metadata fetch.
17
35
  */
18
- export declare function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<EstablishedClient | null>;
36
+ export declare function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<ManagedClient | null>;
19
37
  /** Record the consent and return the plaintext authorization code — the only time it exists. */
20
38
  export declare function grantAuthorization(services: Services, input: {
21
39
  request: OAuthAuthorizationRequest;
@@ -24,23 +42,29 @@ export declare function grantAuthorization(services: Services, input: {
24
42
  session: SessionRow;
25
43
  requestId: string;
26
44
  }): Promise<string>;
45
+ /** RFC 6749 §5.2 and RFC 8628 §3.5: what a refused token request answers. */
46
+ export type OAuthTokenError = 'invalid_grant' | 'invalid_target' | 'unauthorized_client' | 'authorization_pending' | 'slow_down' | 'access_denied' | 'expired_token';
27
47
  export type OAuthTokenOutcome = {
28
48
  ok: true;
29
49
  body: OAuthTokenResponse;
30
50
  } | {
31
51
  ok: false;
32
- error: 'invalid_grant';
52
+ error: OAuthTokenError;
33
53
  };
34
54
  /** Redeem a code or rotate a refresh token for a client `authenticateOAuthClient` established. */
35
- export declare function exchangeOAuthToken(services: Services, env: SigningEnv, client: EstablishedClient, input: OAuthTokenRequest, requestId: string): Promise<OAuthTokenOutcome>;
55
+ export declare function exchangeOAuthToken(services: Services, env: SigningEnv, client: EstablishedClient, input: Exclude<OAuthTokenRequest, {
56
+ grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE;
57
+ }>, requestId: string): Promise<OAuthTokenOutcome>;
36
58
  /** RFC 7009: revoking either token kind revokes its grant. An unknown or foreign token is a silent no-op. */
37
59
  export declare function revokeOAuthToken(services: Services, env: SigningEnv, input: OAuthRevocationRequest, requestId: string): Promise<void>;
60
+ /** An access token for `resource`, one of the grant's resources, carrying the grant's live authority there. */
61
+ export declare function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGrantRow, resource: string, now: number): Promise<OAuthTokenResponse | null>;
38
62
  /**
39
63
  * Everything a grant needs to still mean something, checked at every code exchange and refresh: the
40
64
  * grant live, its client and resource still configured, the IAM session it was given under live and
41
65
  * usable, the principal an active user. The permissions are resolved live, never from the consent.
42
66
  */
43
- export declare function grantAuthority(services: Services, grant: OAuthGrantRow, now: number): Promise<{
67
+ export declare function grantAuthority(services: Services, grant: OAuthGrantRow, now: number, resourceUri?: string): Promise<{
44
68
  principal: PrincipalRow;
45
69
  scopes: string[];
46
70
  permissions: PermissionEntry[];
@@ -48,4 +72,6 @@ export declare function grantAuthority(services: Services, grant: OAuthGrantRow,
48
72
  } | null>;
49
73
  /** The union of the scopes' grants, or null when a scope is no longer configured. */
50
74
  export declare function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null;
75
+ /** The record of a grant's revocation: by its client, or by IAM on a replayed code or refresh token. */
76
+ export declare function grantRevocation(requestId: string, grantId: string, clientId: string, reason: 'code_replay' | 'refresh_replay' | 'device_code_replay' | 'client_revocation'): AuditEventInput;
51
77
  export {};
@@ -92,7 +92,8 @@ export type SqlDialect = 'sqlite' | 'postgres';
92
92
  * The INSERT of one audit row, for the batch of an unconditional change it records: the row and the change commit
93
93
  * together, and a failed insert rolls the change back. Diff and metadata are stored JSON-encoded.
94
94
  */
95
- export declare function auditEventStatement(db: SqlDatabase, event: AuditEventInput): SqlStatement;
95
+ /** The INSERT of one audit row; with `guard`, written only when the guard finds its row (see `SqlGuard`). */
96
+ export declare function auditEventStatement(db: SqlDatabase, event: AuditEventInput, guard?: SqlGuard): SqlStatement;
96
97
  /**
97
98
  * `auditEventStatement` whose `resource_id` is read in the batch by `resourceId`, a one-row SELECT of one column: for
98
99
  * a resource whose id the batch itself settles, such as a principal another writer may have created first.
@@ -6,7 +6,10 @@ export interface OAuthGrantRow {
6
6
  session_id: string;
7
7
  client_id: string;
8
8
  app: string;
9
+ /** The grant's first resource; `resources` lists them all when it was given for several. */
9
10
  resource: string;
11
+ /** JSON array of every resource of the grant, all of `app`; null when `resource` is the only one. */
12
+ resources: string | null;
10
13
  /** JSON array of the consented scope names. */
11
14
  scopes: string;
12
15
  created_at: number;
@@ -27,6 +30,27 @@ export interface OAuthRefreshTokenRow {
27
30
  expires_at: number;
28
31
  used_at: number | null;
29
32
  }
33
+ /** An RFC 8628 attempt. `principal_id`, `session_id` and `grant_expires_at` are set by its approval, `grant_id` by its redemption. */
34
+ export interface OAuthDeviceAuthorizationRow {
35
+ device_code_hash: string;
36
+ user_code_hash: string;
37
+ client_id: string;
38
+ app: string;
39
+ /** JSON array of the resources the grant will cover, all of `app`. */
40
+ resources: string;
41
+ /** JSON array of the requested scope tokens. */
42
+ scopes: string;
43
+ interval_seconds: number;
44
+ next_poll_at: number;
45
+ created_at: number;
46
+ expires_at: number;
47
+ status: 'pending' | 'approved' | 'denied' | 'redeemed';
48
+ principal_id: string | null;
49
+ session_id: string | null;
50
+ grant_expires_at: number | null;
51
+ grant_id: string | null;
52
+ }
53
+ export type NewOAuthDeviceAuthorization = Pick<OAuthDeviceAuthorizationRow, 'device_code_hash' | 'user_code_hash' | 'client_id' | 'app' | 'resources' | 'scopes' | 'interval_seconds' | 'created_at' | 'expires_at'>;
30
54
  /** Codes and refresh tokens are addressed by hash only; the plaintext never reaches this layer. */
31
55
  export declare class OAuthRepository {
32
56
  private readonly db;
@@ -45,10 +69,33 @@ export declare class OAuthRepository {
45
69
  /** Spend a refresh token for rotation. A second presentation gets null and finds the spent row via `refreshToken`. */
46
70
  consumeRefreshToken(tokenHash: string, now: number): Promise<OAuthRefreshTokenRow | null>;
47
71
  refreshToken(tokenHash: string): Promise<OAuthRefreshTokenRow | null>;
72
+ /** Record a device attempt. False when either code's hash is taken already, so the caller draws new codes. */
73
+ startDeviceAuthorization(row: NewOAuthDeviceAuthorization): Promise<boolean>;
74
+ deviceAuthorization(deviceCodeHash: string): Promise<OAuthDeviceAuthorizationRow | null>;
75
+ /** The attempt a person may still decide: pending and unexpired. */
76
+ pendingDeviceAuthorization(userCodeHash: string, now: number): Promise<OAuthDeviceAuthorizationRow | null>;
77
+ /** Approve a pending attempt under the approver's IAM session. False when it was decided, or expired, meanwhile. */
78
+ approveDeviceAuthorization(userCodeHash: string, approval: {
79
+ principalId: string;
80
+ sessionId: string;
81
+ grantExpiresAt: number;
82
+ }, now: number): Promise<boolean>;
83
+ denyDeviceAuthorization(userCodeHash: string, now: number): Promise<boolean>;
84
+ /**
85
+ * Admit one poll of an attempt (RFC 8628 §3.5). A poll before the interval has passed is refused and lengthens the
86
+ * interval by five seconds, which the client is told to add with `slow_down`.
87
+ */
88
+ admitDevicePoll(deviceCodeHash: string, now: number): Promise<boolean>;
89
+ /**
90
+ * Spend an approved attempt for `grant`: the claim, the grant, its record and its first refresh token in one batch.
91
+ * Every write after the claim requires the claim this batch made (`grant_id` names this grant), so exactly one poll
92
+ * gives a grant, and a refused or failed claim writes nothing. Answers the claimed row, or null.
93
+ */
94
+ redeemDeviceAuthorization(deviceCodeHash: string, grant: OAuthGrantRow, refreshTokenHash: string, audit: AuditEventInput, now: number): Promise<OAuthDeviceAuthorizationRow | null>;
48
95
  /** Record an accepted client assertion's `jti`. False when the client already presented it: a replay. */
49
96
  recordClientAssertion(clientId: string, jti: string, expiresAt: number): Promise<boolean>;
50
97
  /**
51
- * Delete codes, refresh tokens and client assertion ids past expiry. Spent rows stay until then because they are what
98
+ * Delete codes, refresh tokens, client assertion ids and device attempts past expiry. Spent rows stay until then because they are what
52
99
  * detects a replay. Grants go with their session row (`ON DELETE CASCADE`), which shares their expiry.
53
100
  */
54
101
  prune(now: number): Promise<void>;
@@ -31,14 +31,14 @@ export declare const exchangeAuthCodeSchema: z.ZodCatch<z.ZodObject<{
31
31
  verifier: z.ZodString;
32
32
  requestId: z.ZodString;
33
33
  }, "strip", z.ZodTypeAny, {
34
- code: string;
35
34
  app: string;
36
35
  requestId: string;
36
+ code: string;
37
37
  verifier: string;
38
38
  }, {
39
- code: string;
40
39
  app: string;
41
40
  requestId: string;
41
+ code: string;
42
42
  verifier: string;
43
43
  }>>;
44
44
  export declare const issueKeySchema: z.ZodCatch<z.ZodEffects<z.ZodObject<{
@@ -154,8 +154,8 @@ export declare const issueKeySchema: z.ZodCatch<z.ZodEffects<z.ZodObject<{
154
154
  label: z.ZodEffects<z.ZodOptional<z.ZodNullable<z.ZodString>>, string | undefined, string | null | undefined>;
155
155
  expiresAt: z.ZodNumber;
156
156
  }, "strip", z.ZodTypeAny, {
157
- expiresAt: number;
158
157
  app: string;
158
+ expiresAt: number;
159
159
  credential: string | null;
160
160
  requestId: string;
161
161
  service?: {
@@ -176,8 +176,8 @@ export declare const issueKeySchema: z.ZodCatch<z.ZodEffects<z.ZodObject<{
176
176
  }[] | undefined;
177
177
  principalId?: string | undefined;
178
178
  }, {
179
- expiresAt: number;
180
179
  app: string;
180
+ expiresAt: number;
181
181
  credential: string | null;
182
182
  requestId: string;
183
183
  service?: {
@@ -220,8 +220,8 @@ export declare const issueKeySchema: z.ZodCatch<z.ZodEffects<z.ZodObject<{
220
220
  credential: string | null;
221
221
  requestId: string;
222
222
  }, {
223
- expiresAt: number;
224
223
  app: string;
224
+ expiresAt: number;
225
225
  credential: string | null;
226
226
  requestId: string;
227
227
  service?: {
@@ -248,13 +248,13 @@ export declare const revokeKeySchema: z.ZodCatch<z.ZodObject<{
248
248
  credential: z.ZodNullable<z.ZodString>;
249
249
  requestId: z.ZodString;
250
250
  }, "strip", z.ZodTypeAny, {
251
- id: string;
252
251
  app: string;
252
+ id: string;
253
253
  credential: string | null;
254
254
  requestId: string;
255
255
  }, {
256
- id: string;
257
256
  app: string;
257
+ id: string;
258
258
  credential: string | null;
259
259
  requestId: string;
260
260
  }>>;
@@ -394,15 +394,15 @@ export declare const assignMemberSchema: z.ZodCatch<z.ZodObject<{
394
394
  resend: z.ZodOptional<z.ZodBoolean>;
395
395
  locale: z.ZodOptional<z.ZodEnum<["en", "cs", "uk"]>>;
396
396
  }, "strict", z.ZodTypeAny, {
397
- message?: string | undefined;
398
- resend?: boolean | undefined;
399
397
  locale?: "en" | "cs" | "uk" | undefined;
400
- label?: string | undefined;
401
- }, {
402
398
  message?: string | undefined;
399
+ label?: string | undefined;
403
400
  resend?: boolean | undefined;
401
+ }, {
404
402
  locale?: "en" | "cs" | "uk" | undefined;
403
+ message?: string | undefined;
405
404
  label?: string | undefined;
405
+ resend?: boolean | undefined;
406
406
  }>>;
407
407
  app: z.ZodString;
408
408
  credential: z.ZodNullable<z.ZodString>;
@@ -423,10 +423,10 @@ export declare const assignMemberSchema: z.ZodCatch<z.ZodObject<{
423
423
  delegation: string;
424
424
  role: string;
425
425
  invitation?: {
426
- message?: string | undefined;
427
- resend?: boolean | undefined;
428
426
  locale?: "en" | "cs" | "uk" | undefined;
427
+ message?: string | undefined;
429
428
  label?: string | undefined;
429
+ resend?: boolean | undefined;
430
430
  } | undefined;
431
431
  }, {
432
432
  app: string;
@@ -444,10 +444,10 @@ export declare const assignMemberSchema: z.ZodCatch<z.ZodObject<{
444
444
  delegation: string;
445
445
  role: string;
446
446
  invitation?: {
447
- message?: string | undefined;
448
- resend?: boolean | undefined;
449
447
  locale?: "en" | "cs" | "uk" | undefined;
448
+ message?: string | undefined;
450
449
  label?: string | undefined;
450
+ resend?: boolean | undefined;
451
451
  } | undefined;
452
452
  }>>;
453
453
  export declare const revokeMemberSchema: z.ZodCatch<z.ZodObject<{
@@ -642,13 +642,13 @@ export declare const revokeLinkSchema: z.ZodCatch<z.ZodObject<{
642
642
  credential: z.ZodNullable<z.ZodString>;
643
643
  requestId: z.ZodString;
644
644
  }, "strip", z.ZodTypeAny, {
645
- id: string;
646
645
  app: string;
646
+ id: string;
647
647
  credential: string | null;
648
648
  requestId: string;
649
649
  }, {
650
- id: string;
651
650
  app: string;
651
+ id: string;
652
652
  credential: string | null;
653
653
  requestId: string;
654
654
  }>>;
@@ -658,13 +658,13 @@ export declare const inspectIdentificationSchema: z.ZodCatch<z.ZodObject<{
658
658
  credential: z.ZodNullable<z.ZodString>;
659
659
  requestId: z.ZodString;
660
660
  }, "strip", z.ZodTypeAny, {
661
- id: string;
662
661
  app: string;
662
+ id: string;
663
663
  credential: string | null;
664
664
  requestId: string;
665
665
  }, {
666
- id: string;
667
666
  app: string;
667
+ id: string;
668
668
  credential: string | null;
669
669
  requestId: string;
670
670
  }>>;
@@ -675,14 +675,14 @@ export declare const assertIdentitySchema: z.ZodCatch<z.ZodObject<{
675
675
  credential: z.ZodNullable<z.ZodString>;
676
676
  requestId: z.ZodString;
677
677
  }, "strip", z.ZodTypeAny, {
678
- id: string;
679
678
  app: string;
679
+ id: string;
680
680
  principalId: string;
681
681
  credential: string | null;
682
682
  requestId: string;
683
683
  }, {
684
- id: string;
685
684
  app: string;
685
+ id: string;
686
686
  principalId: string;
687
687
  credential: string | null;
688
688
  requestId: string;
@@ -693,13 +693,13 @@ export declare const cancelIdentificationSchema: z.ZodCatch<z.ZodObject<{
693
693
  credential: z.ZodNullable<z.ZodString>;
694
694
  requestId: z.ZodString;
695
695
  }, "strip", z.ZodTypeAny, {
696
- id: string;
697
696
  app: string;
697
+ id: string;
698
698
  credential: string | null;
699
699
  requestId: string;
700
700
  }, {
701
- id: string;
702
701
  app: string;
702
+ id: string;
703
703
  credential: string | null;
704
704
  requestId: string;
705
705
  }>>;