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

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,7 @@
1
- import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
1
+ import { type SqlDatabase, type SqlQueryResult, type SqlStatement, uuidv7 } from '@fabrika/platform'
2
+ import { z } from 'zod'
2
3
  import { type AuditEventInput, AuditWriter, type SqlChange, type SqlDialect } from './audit'
4
+ import type { GrantRequestRow } from './grant-requests'
3
5
  import { unixNow } from './sql'
4
6
 
5
7
  /** A grant written for a workload principal: its authority is its declared actions, never a grant. */
@@ -77,6 +79,8 @@ export interface GrantRow {
77
79
  scope_type: string | null
78
80
  /** Opaque, app-owned scope value; NULL = global. */
79
81
  scope_value: string | null
82
+ /** The grant this row is one value of, shared by every row of a grant of several values; NULL = a grant of one (ADR-0085). */
83
+ scope_set: string | null
80
84
  granted_by: string | null
81
85
  expires_at: number | null
82
86
  created_at: number
@@ -89,8 +93,23 @@ export interface CreateGrantInput {
89
93
  permissions?: string[] | null
90
94
  scopeType?: string | null
91
95
  scopeValue?: string | null
96
+ /** The grant id every row of a grant of several values shares (ADR-0085); null or omitted for a grant of one. */
97
+ scopeSet?: string | null
92
98
  grantedBy?: string | null
93
99
  expiresAt?: number | null
100
+ /** When the grant was first written; an edit keeps it. Omitted = now. */
101
+ createdAt?: number
102
+ }
103
+
104
+ /** A grant of one or more values of one dimension, or a global one (`scopeType` and `scopeValues` null). */
105
+ export interface CreateGrantSetInput extends Omit<CreateGrantInput, 'scopeValue' | 'scopeSet'> {
106
+ scopeValues: readonly string[] | null
107
+ }
108
+
109
+ /** The rows of one grant (ADR-0085) and its principal's grant revision, read by one statement. */
110
+ export interface GrantSetRead {
111
+ readonly rows: [GrantRow, ...GrantRow[]]
112
+ readonly grantRevision: number
94
113
  }
95
114
 
96
115
  export class GrantRepository {
@@ -179,6 +198,25 @@ export class GrantRepository {
179
198
  return this.db.prepare('SELECT * FROM grants WHERE id = ?').bind(id).first<GrantRow>()
180
199
  }
181
200
 
201
+ /**
202
+ * Every row of the grant `grantId` belongs to (ADR-0085), whichever of its rows the id names, with the principal's
203
+ * grant revision read in the same statement, so a removal after this read moves the revision `replaceGrantSet` checks.
204
+ */
205
+ async getGrantSet(grantId: string): Promise<GrantSetRead | null> {
206
+ const { results } = await this.db
207
+ .prepare(`SELECT g.*, p.grant_revision AS principal_grant_revision
208
+ FROM (SELECT COALESCE(scope_set, id) AS grant_id FROM grants WHERE id = ?) named
209
+ JOIN grants g ON g.id = named.grant_id OR g.scope_set = named.grant_id
210
+ JOIN principals p ON p.id = g.principal_id
211
+ ORDER BY g.scope_value, g.id`)
212
+ .bind(grantId)
213
+ .all<GrantRow & { principal_grant_revision: number }>()
214
+ const rows = results.map(({ principal_grant_revision: _revision, ...row }) => row)
215
+ const [first, ...rest] = rows
216
+ const revision = results[0]?.principal_grant_revision
217
+ return first === undefined || revision === undefined ? null : { rows: [first, ...rest], grantRevision: Number(revision) }
218
+ }
219
+
182
220
  /**
183
221
  * Create a grant. EITHER `roleKey` (named role/policy) OR `permissions` (an inline
184
222
  * action-pattern set, JSON-encoded here) — the caller MUST supply exactly one; the
@@ -198,6 +236,93 @@ export class GrantRepository {
198
236
  return created
199
237
  }
200
238
 
239
+ /**
240
+ * Create a grant of several values of one dimension: one row per value, sharing `scope_set` (ADR-0085), all written or
241
+ * none, with ONE record. A duplicate role grant fails the unique index and throws, rolling the batch back. Throws
242
+ * `ExternalGrantError`, writing nothing, for a grant the principal may not hold.
243
+ */
244
+ async createGrantSet(input: CreateGrantSetInput, audit: (grantId: string) => AuditEventInput): Promise<GrantRow[]> {
245
+ await this.refuseWorkload(input.principalId)
246
+ const id = uuidv7()
247
+ const change = this.writer.changed(this.grantSetChanges(id, input), audit(id))
248
+ await this.db.batch(change.statements)
249
+ const written = await this.getGrantSet(id)
250
+ if (written === null) {
251
+ // Every insert carries the eligibility condition, which is the same for each value.
252
+ throw new ExternalGrantError()
253
+ }
254
+ return written.rows
255
+ }
256
+
257
+ /** The INSERTs of a grant's rows with a caller-generated grant id, for a batch that also writes its principal and record. */
258
+ grantSetStatements(id: string, input: CreateGrantSetInput): SqlStatement[] {
259
+ return this.grantSetChanges(id, input).map((change) => this.db.prepare(change.sql).bind(...change.binds))
260
+ }
261
+
262
+ /**
263
+ * One row per value; the first keeps the grant id, so a grant's id stays what it was through an edit. A grant of one
264
+ * value, and a global one, is one row without `scope_set`, as every grant before ADR-0085.
265
+ */
266
+ private grantSetChanges(id: string, input: CreateGrantSetInput, guard?: { sql: string; binds: (string | number)[] }): SqlChange[] {
267
+ const { scopeValues, ...grant } = input
268
+ if (scopeValues === null || scopeValues.length <= 1) {
269
+ return [this.grantChange(id, { ...grant, scopeValue: scopeValues?.[0] ?? null }, '', guard)]
270
+ }
271
+ return scopeValues.map((scopeValue, index) => this.grantChange(index === 0 ? id : uuidv7(), { ...grant, scopeValue, scopeSet: id }, '', guard))
272
+ }
273
+
274
+ /**
275
+ * Replace the rows of the grant `read` names with `input`, keeping its id, in one transaction with ONE record: null
276
+ * when the principal's grants changed since the read (its grant revision moved). Moves the revision first, because an
277
+ * edit can remove authority. A duplicate role grant fails the unique index and throws; a grant the principal may not
278
+ * hold throws `ExternalGrantError`; both roll the batch back.
279
+ */
280
+ async replaceGrantSet(read: GrantSetRead, input: CreateGrantSetInput, audit: AuditEventInput): Promise<GrantRow[] | null> {
281
+ const [first] = read.rows
282
+ await this.refuseWorkload(first.principal_id)
283
+ const id = first.scope_set ?? first.id
284
+ // The revision statement moved it by one, so an unchanged principal reads exactly one more than the read.
285
+ const guard = {
286
+ sql: '(SELECT grant_revision FROM principals WHERE id = ?) = ?',
287
+ binds: [first.principal_id, read.grantRevision + 1],
288
+ }
289
+ const removal = this.db
290
+ .prepare(`DELETE FROM grants WHERE (id = ? OR scope_set = ?) AND ${guard.sql}`)
291
+ .bind(id, id, ...guard.binds)
292
+ const insert = this.writer.changed(this.grantSetChanges(id, input, guard), audit)
293
+ // The old rows are gone and no new one was written: only the eligibility condition refuses that, so roll back.
294
+ const rollback = this.db
295
+ .prepare(`INSERT INTO contract_apps (app, created_at) SELECT ?, NULL
296
+ WHERE ${guard.sql} AND NOT EXISTS (SELECT 1 FROM grants WHERE id = ? OR scope_set = ?)`)
297
+ .bind(`grant-set:${id}`, ...guard.binds, id, id)
298
+ let results: SqlQueryResult<GrantRow>[]
299
+ try {
300
+ results = await this.db.batch<GrantRow>([
301
+ grantRemovalStatement(this.db, { principalId: first.principal_id }),
302
+ removal,
303
+ ...insert.statements,
304
+ rollback,
305
+ ])
306
+ } catch (cause) {
307
+ if (!(await this.isEligibleGrant({ principalId: first.principal_id, app: input.app ?? null, roleKey: input.roleKey ?? null }))) {
308
+ throw new ExternalGrantError()
309
+ }
310
+ throw cause
311
+ }
312
+ if (insert.rows(results, 2).length === 0) return null
313
+ return (await this.getGrantSet(id))?.rows ?? null
314
+ }
315
+
316
+ /** Delete every row of the grant `grantId` names (ADR-0085), after its principal's revision, with ONE record. */
317
+ async deleteGrantSet(grantId: string, principalId: string, audit: AuditEventInput): Promise<boolean> {
318
+ const removal = this.writer.changed(
319
+ [{ sql: 'DELETE FROM grants WHERE (id = ? OR scope_set = ?) AND principal_id = ? RETURNING id', binds: [grantId, grantId, principalId] }],
320
+ audit,
321
+ )
322
+ const results = await this.db.batch([grantRemovalStatement(this.db, { principalId }), ...removal.statements])
323
+ return removal.rows(results, 1).length > 0
324
+ }
325
+
201
326
  /** Whether `principalId` may hold this grant: it is internal, or the role is one its app declares external. */
202
327
  async isEligibleGrant(input: { principalId: string; app?: string | null; roleKey?: string | null }): Promise<boolean> {
203
328
  return (await this.db.prepare(`SELECT 1 AS eligible WHERE ${eligibleGrantSql('sqlite')}`).bind(...eligibleGrantBinds(input)).first()) !== null
@@ -332,8 +457,8 @@ export class GrantRepository {
332
457
 
333
458
  private grantChange(id: string, input: CreateGrantInput, onConflict: string, guard?: { sql: string; binds: (string | number)[] }): SqlChange {
334
459
  return {
335
- sql: `INSERT INTO grants (id, principal_id, app, role_key, permissions, scope_type, scope_value, granted_by, expires_at, created_at)
336
- SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE ${eligibleGrantSql(this.writer.dialect)}${
460
+ sql: `INSERT INTO grants (id, principal_id, app, role_key, permissions, scope_type, scope_value, scope_set, granted_by, expires_at, created_at)
461
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE ${eligibleGrantSql(this.writer.dialect)}${
337
462
  guard === undefined ? '' : ` AND ${guard.sql}`
338
463
  } ${onConflict} RETURNING *`,
339
464
  binds: [
@@ -344,41 +469,132 @@ export class GrantRepository {
344
469
  input.permissions == null ? null : JSON.stringify(input.permissions),
345
470
  input.scopeType ?? null,
346
471
  input.scopeValue ?? null,
472
+ input.scopeSet ?? null,
347
473
  input.grantedBy ?? null,
348
474
  input.expiresAt ?? null,
349
- unixNow(),
475
+ input.createdAt ?? unixNow(),
350
476
  ...eligibleGrantBinds(input),
351
477
  ...(guard?.binds ?? []),
352
478
  ],
353
479
  }
354
480
  }
355
481
 
356
- /** Keep the audit's before-value true if another administrator edited this grant after it was read. */
357
- async updateGrant(grant: GrantRow, input: CreateGrantInput, audit: AuditEventInput): Promise<GrantRow | null> {
358
- await this.refuseWorkload(grant.principal_id)
359
- const update = this.writer.changed([{
360
- sql: `UPDATE grants SET role_key = ?, permissions = ?, scope_type = ?, scope_value = ?, expires_at = ?
361
- WHERE id = ? AND role_key IS NOT DISTINCT FROM ? AND permissions IS NOT DISTINCT FROM ?
362
- AND scope_type IS NOT DISTINCT FROM ? AND scope_value IS NOT DISTINCT FROM ? AND expires_at IS NOT DISTINCT FROM ?
363
- AND ${eligibleGrantSql(this.writer.dialect)} RETURNING *`,
364
- binds: [
365
- input.roleKey ?? null,
366
- input.permissions === null || input.permissions === undefined ? null : JSON.stringify(input.permissions),
367
- input.scopeType ?? null,
368
- input.scopeValue ?? null,
369
- input.expiresAt ?? null,
370
- grant.id,
371
- grant.role_key,
372
- grant.permissions,
373
- grant.scope_type,
374
- grant.scope_value,
375
- grant.expires_at,
376
- ...eligibleGrantBinds(input),
377
- ],
378
- }], audit)
379
- // Editing can remove authority too. Invalidate pending delegation checks before changing the grant.
380
- const results = await this.db.batch<GrantRow>([grantRemovalStatement(this.db, { principalId: grant.principal_id }), ...update.statements])
381
- return update.rows(results, 1)[0] ?? null
482
+ /**
483
+ * Write the change an approved grant request asks for (ADR-0083), in one transaction with the approval's claim: the
484
+ * request moves `pending` → `approved` under `decision.id`, and the change carries a guard on that claim, so of two
485
+ * approvals one claims and writes, the other writes nothing. `current` is the grant an `update` edits or a `revoke`
486
+ * removes, as the approver's checks read it; an edit applies only while the principal's grants are as read. A grant of
487
+ * several values is written, replaced or removed whole (ADR-0085). `claimed` false: decided or lapsed meanwhile.
488
+ * `changed` null with `claimed`: the change wrote nothing (a role grant already held, a grant gone or edited since).
489
+ * A value of a new set the principal already holds the role in fails the unique index, and a replacement the principal
490
+ * may not hold throws `ExternalGrantError`; both roll the approval back and leave the request open.
491
+ */
492
+ async applyRequest(
493
+ request: GrantRequestRow,
494
+ current: GrantSetRead | null,
495
+ decision: { readonly id: string; readonly by: string; readonly at: number },
496
+ audit: (grantId: string) => AuditEventInput,
497
+ ): Promise<{ claimed: boolean; changed: GrantRow | null }> {
498
+ const claim = this.db
499
+ .prepare(`UPDATE grant_requests SET status = 'approved', decision_id = ?, decided_by = ?, decided_at = ?
500
+ WHERE id = ? AND status = 'pending' AND expires_at > ? RETURNING id`)
501
+ .bind(decision.id, decision.by, decision.at, request.id, decision.at)
502
+ const guard = { sql: 'EXISTS (SELECT 1 FROM grant_requests WHERE id = ? AND decision_id = ?)', binds: [request.id, decision.id] }
503
+ const scopeValues = requestScopeValues(request)
504
+ const input: CreateGrantSetInput = {
505
+ principalId: request.principal_id,
506
+ app: request.app,
507
+ roleKey: request.role_key,
508
+ permissions: request.permissions === null ? null : storedActions(request.permissions),
509
+ scopeType: request.scope_type,
510
+ scopeValues,
511
+ grantedBy: decision.by,
512
+ expiresAt: request.grant_expires_at,
513
+ }
514
+ let grantId = request.grant_id ?? uuidv7()
515
+ let changes: SqlChange[]
516
+ const leading: SqlStatement[] = []
517
+ const trailing: SqlStatement[] = []
518
+ if (request.kind === 'create') {
519
+ if (scopeValues !== null && scopeValues.length > 1) {
520
+ changes = this.grantSetChanges(grantId, input, guard)
521
+ } else {
522
+ const single: CreateGrantInput = { ...input, scopeValue: scopeValues?.[0] ?? null }
523
+ let conflict = ''
524
+ const conflictBinds: number[] = []
525
+ if (single.roleKey !== null && single.scopeValue != null) {
526
+ conflict =
527
+ `ON CONFLICT (principal_id, role_key, scope_type, scope_value, COALESCE(app, '*')) WHERE role_key IS NOT NULL AND scope_value IS NOT NULL DO NOTHING`
528
+ } else if (single.roleKey !== null) {
529
+ // As `createDelegatedRoleGrant`: an expired grant of the role is renewed in place, keeping its id.
530
+ const expired = await this.db
531
+ .prepare(`SELECT id FROM grants WHERE principal_id = ? AND role_key = ? AND app = ? AND scope_value IS NULL
532
+ AND expires_at IS NOT NULL AND expires_at <= ?`)
533
+ .bind(request.principal_id, single.roleKey, request.app, decision.at)
534
+ .first<{ id: string }>()
535
+ grantId = expired?.id ?? grantId
536
+ conflict = `ON CONFLICT (principal_id, role_key, COALESCE(app, '*')) WHERE role_key IS NOT NULL AND scope_value IS NULL
537
+ DO UPDATE SET expires_at = excluded.expires_at, granted_by = excluded.granted_by, created_at = excluded.created_at
538
+ WHERE grants.expires_at IS NOT NULL AND grants.expires_at <= ?`
539
+ conflictBinds.push(decision.at)
540
+ }
541
+ const insert = this.grantChange(grantId, single, conflict, guard)
542
+ changes = [{ sql: insert.sql, binds: [...insert.binds, ...conflictBinds] }]
543
+ }
544
+ leading.push(claim)
545
+ } else if (request.kind === 'update') {
546
+ if (current === null) return { claimed: false, changed: null }
547
+ const [first] = current.rows
548
+ grantId = first.scope_set ?? first.id
549
+ // The revision statement moves it by one: an unchanged principal reads one more than the approver's checks read.
550
+ const unchanged = {
551
+ sql: `${guard.sql} AND (SELECT grant_revision FROM principals WHERE id = ?) = ?`,
552
+ binds: [...guard.binds, request.principal_id, current.grantRevision + 1],
553
+ }
554
+ leading.push(
555
+ grantRemovalStatement(this.db, { principalId: request.principal_id }),
556
+ claim,
557
+ this.db
558
+ .prepare(`DELETE FROM grants WHERE (id = ? OR scope_set = ?) AND app = ? AND principal_id = ? AND ${unchanged.sql}`)
559
+ .bind(grantId, grantId, request.app, request.principal_id, ...unchanged.binds),
560
+ )
561
+ changes = this.grantSetChanges(grantId, {
562
+ ...input,
563
+ grantedBy: first.granted_by,
564
+ createdAt: Math.min(...current.rows.map((row) => row.created_at)),
565
+ }, unchanged)
566
+ // The old rows are gone and no new one was written: only the eligibility condition refuses that, so roll back.
567
+ trailing.push(
568
+ this.db
569
+ .prepare(`INSERT INTO contract_apps (app, created_at) SELECT ?, NULL
570
+ WHERE ${unchanged.sql} AND NOT EXISTS (SELECT 1 FROM grants WHERE id = ? OR scope_set = ?)`)
571
+ .bind(`grant-set:${grantId}`, ...unchanged.binds, grantId, grantId),
572
+ )
573
+ } else {
574
+ leading.push(grantRemovalStatement(this.db, { principalId: request.principal_id }), claim)
575
+ changes = [{
576
+ sql: `DELETE FROM grants WHERE (id = ? OR scope_set = ?) AND app = ? AND principal_id = ? AND ${guard.sql} RETURNING *`,
577
+ binds: [grantId, grantId, request.app, request.principal_id, ...guard.binds],
578
+ }]
579
+ }
580
+ const claimAt = leading.indexOf(claim)
581
+ const audited = this.writer.changed(changes, audit(grantId))
582
+ // A claim whose change wrote nothing (no record) closes the request `failed` in the same transaction.
583
+ const failed = this.db
584
+ .prepare(`UPDATE grant_requests SET status = 'failed' WHERE id = ? AND decision_id = ?
585
+ AND NOT EXISTS (SELECT 1 FROM audit_events WHERE id = ?)`)
586
+ .bind(request.id, decision.id, audited.recordId)
587
+ let results: SqlQueryResult<GrantRow>[]
588
+ try {
589
+ results = await this.db.batch<GrantRow>([...leading, ...audited.statements, ...trailing, failed])
590
+ } catch (cause) {
591
+ if (!(await this.isEligibleGrant({ principalId: request.principal_id, app: request.app, roleKey: request.role_key }))) {
592
+ throw new ExternalGrantError()
593
+ }
594
+ throw cause
595
+ }
596
+ const claimed = (results[claimAt]?.results.length ?? 0) > 0
597
+ return { claimed, changed: audited.rows(results, leading.length)[0] ?? null }
382
598
  }
383
599
 
384
600
  /** Delete a grant, after its principal's revision. */
@@ -402,3 +618,17 @@ export class GrantRepository {
402
618
  return { sql: 'DELETE FROM grants WHERE principal_id = ? RETURNING id', binds: [principalId] }
403
619
  }
404
620
  }
621
+
622
+ const storedActionsSchema = z.array(z.string())
623
+ const storedScopeValuesSchema = z.array(z.string()).min(2)
624
+
625
+ /** A stored inline action set (a JSON array of patterns), read once where it leaves the row. */
626
+ function storedActions(json: string): string[] {
627
+ return storedActionsSchema.parse(JSON.parse(json))
628
+ }
629
+
630
+ /** The values a grant request asks for (ADR-0085): its set, or its one value; null for a global grant. */
631
+ export function requestScopeValues(request: Pick<GrantRequestRow, 'scope_value' | 'scope_values'>): string[] | null {
632
+ if (request.scope_values !== null) return storedScopeValuesSchema.parse(JSON.parse(request.scope_values))
633
+ return request.scope_value === null ? null : [request.scope_value]
634
+ }
@@ -1,4 +1,4 @@
1
- import { parseJsonStringArray } from '@fabrika/auth-core'
1
+ import { type DimensionValue, dimensionValuesProblem, parseJsonStringArray } from '@fabrika/auth-core'
2
2
 
3
3
  /** A role's stored `via`: relation → actions. A malformed row contributes nothing, as an unparseable grant does. */
4
4
  export function parseStoredVia(json: string | null): Record<string, string[]> {
@@ -32,3 +32,27 @@ export function delegatedActions(role: { readonly permissions: string; readonly
32
32
  for (const held of Object.values(parseStoredVia(role.via))) actions.push(...held)
33
33
  return actions
34
34
  }
35
+
36
+ /**
37
+ * A scope's stored `value_list` (ADR-0085), or null for none. A row that is not a list `dimensionValuesProblem` admits
38
+ * lists none: the console then takes free text, which is what it did before any list.
39
+ */
40
+ export function parseStoredValueList(json: string | null): DimensionValue[] | null {
41
+ if (json === null) return null
42
+ let value: unknown
43
+ try {
44
+ value = JSON.parse(json)
45
+ } catch {
46
+ return null
47
+ }
48
+ if (!Array.isArray(value)) return null
49
+ const values: DimensionValue[] = []
50
+ for (const entry of value) {
51
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return null
52
+ const listed: unknown = Reflect.get(entry, 'value')
53
+ const label: unknown = Reflect.get(entry, 'label')
54
+ if (typeof listed !== 'string' || (label !== undefined && typeof label !== 'string')) return null
55
+ values.push(label === undefined ? { value: listed } : { value: listed, label })
56
+ }
57
+ return dimensionValuesProblem(values) === null ? values : null
58
+ }
package/src/tokens.ts CHANGED
@@ -457,7 +457,7 @@ export async function resolveCredential(services: Services, cred: CredentialRow,
457
457
  * A user's mailbox for its token: `principals.email`, normalized by `PrincipalRepository`, the address the person signs
458
458
  * in with. An application mails it as `ctx.principal.email`, so it is never `label`, the spelling the person sees.
459
459
  */
460
- function mailboxClaim(principal: PrincipalRow): { email?: string } {
460
+ export function mailboxClaim(principal: PrincipalRow): { email?: string } {
461
461
  return principal.type === 'user' && principal.email !== null ? { email: principal.email } : {}
462
462
  }
463
463
 
@@ -0,0 +1,42 @@
1
+ import { type DecideGrantRequestInput, type GrantRequestDto, type ListGrantRequestsInput, type SetGrantApprovalRequest } from '@fabrika/iam-contract';
2
+ import { type AuditEventInput, type CreateGrantRequestInput } from '../db';
3
+ import type { Services } from '../services';
4
+ import { type AdminContext } from './context';
5
+ import type { ResolvedAdmin } from './router';
6
+ /** Whether a grant change at `app` waits; a cross-app grant reaches no application and never does. */
7
+ export declare function grantsWait(services: Services, app: string | null): Promise<boolean>;
8
+ /** What a grant change asks for, before IAM records it; the request's timestamps are IAM's. */
9
+ export type GrantChangeRequest = Omit<CreateGrantRequestInput, 'requestedAt' | 'expiresAt'>;
10
+ /** Record the change as a request, with its `iam.grant.request` record built by `event`, and answer it. */
11
+ export declare function requestGrantChange(services: Services, change: GrantChangeRequest, event: (requestId: string, metadata: Record<string, unknown>) => AuditEventInput): Promise<GrantRequestDto>;
12
+ /** The open requests at the applications the caller administers, the oldest first. */
13
+ export declare function listGrantRequestsUseCase(c: AdminContext, input: ListGrantRequestsInput): Promise<{
14
+ items: GrantRequestDto[];
15
+ }>;
16
+ /**
17
+ * Approve or reject one open request. Only a person in a signed-in session decides (`person`), never a `px_` key; an
18
+ * application the caller does not administer and an unknown request are one 404. The requester may reject (withdraw)
19
+ * their own request, never approve it.
20
+ */
21
+ export declare function decideGrantRequestUseCase(c: AdminContext, person: boolean, input: DecideGrantRequestInput): Promise<GrantRequestDto>;
22
+ /** The caller of a grant request procedure who administers no IAM application: an application's own administrator. */
23
+ export interface GrantRequester {
24
+ readonly services: Services;
25
+ readonly requestId: string;
26
+ readonly admin: ResolvedAdmin;
27
+ }
28
+ /** A requester without IAM administration sees only the requests they made (an application administrator's own). */
29
+ export declare function listOwnGrantRequestsUseCase(c: GrantRequester, input: ListGrantRequestsInput): Promise<{
30
+ items: GrantRequestDto[];
31
+ }>;
32
+ /**
33
+ * A requester without IAM administration withdraws a request they made, as a person in a signed-in session; any other
34
+ * request, and approving, is the 404 of an unknown one. The record is filed under the request's application.
35
+ */
36
+ export declare function withdrawOwnGrantRequestUseCase(c: GrantRequester, input: DecideGrantRequestInput): Promise<GrantRequestDto>;
37
+ /**
38
+ * Make grant changes at `app` wait, or apply at once again (ADR-0083 §4). Only Control sets it, with the provisioning
39
+ * key, when an environment chooses or drops the `grants` category: an installation administrator who could switch it
40
+ * off could grant past it. Only an application environment id qualifies.
41
+ */
42
+ export declare function setGrantApprovalUseCase(c: AdminContext, input: SetGrantApprovalRequest): Promise<SetGrantApprovalRequest>;
@@ -18,8 +18,16 @@ export declare class RoleKnownCache {
18
18
  /** True iff `roleKey` resolves for `app` — a built-in, or a row in the app's roles. */
19
19
  isKnown(roleKey: string, app: string | null): Promise<boolean>;
20
20
  }
21
- export declare function toGrantDto(row: GrantRow, roleCache: RoleKnownCache): Promise<GrantDto>;
22
- /** Map a list of grant rows to DTOs sharing one role-known cache (one query per app). */
21
+ /** The id of the grant a row belongs to: its set's, or its own for a grant of one value (ADR-0085). */
22
+ export declare function grantIdOf(row: Pick<GrantRow, 'id' | 'scope_set'>): string;
23
+ /** Rows grouped into grants by `grantIdOf`, in the order each grant's first row appears. */
24
+ export declare function grantSets(rows: readonly GrantRow[]): GrantRow[][];
25
+ /**
26
+ * One grant's DTO from the rows of its set. A row an assignment renewed may expire later than the rest, so the latest
27
+ * expiry counts (none wins): the grant reads as expired only once none of its values grants anything.
28
+ */
29
+ export declare function toGrantDto(rows: readonly [GrantRow, ...GrantRow[]], roleCache: RoleKnownCache): Promise<GrantDto>;
30
+ /** Map grant rows to one DTO per grant, sharing one role-known cache (one query per app). */
23
31
  export declare function toGrantDtos(rows: GrantRow[], services: Services, cache?: RoleKnownCache): Promise<GrantDto[]>;
24
32
  /** The label of each principal who granted one of `rows`; an author no longer known reads as its id. */
25
33
  export declare function grantAuthorLabels(rows: GrantRow[], services: Services): Promise<Map<string, string>>;
@@ -35,15 +43,16 @@ export declare function appField(c: AdminContext, body: Pick<CreateGrantRequest,
35
43
  /** A `roles` row → core `RoleDef` for resolution. */
36
44
  export declare function dbRoleToDef(row: RoleRow): RoleDef;
37
45
  /**
38
- * Validate the scope coordinate on a grant/key request: `scopeType`/`scopeValue` are
39
- * both-or-neither (both null = global). A half-set pair is a 400.
46
+ * Validate the scope coordinate on a grant/key request: `scopeType` with `scopeValue` or `scopeValues` (ADR-0085), or
47
+ * none of them (global). The values come back sorted, so a set reads the same whatever order the request listed.
40
48
  */
41
- export declare function parseScope(body: Pick<CreateGrantRequest, 'scopeType' | 'scopeValue'>): {
49
+ export declare function parseScope(body: Pick<CreateGrantRequest, 'scopeType' | 'scopeValue' | 'scopeValues'>): {
42
50
  ok: true;
43
51
  scopeType: string | null;
44
- scopeValue: string | null;
52
+ scopeValues: string[] | null;
45
53
  } | {
46
54
  ok: false;
55
+ message: string;
47
56
  };
48
57
  /**
49
58
  * Validate the role-or-inline choice for a grant/key against the app: EXACTLY one of
@@ -1,8 +1,8 @@
1
- import { type CreateGrantRequest, type GrantDto, type OkResponse, type UpdateGrantInput } from '@fabrika/iam-contract';
1
+ import { type CreateGrantRequest, type GrantChangeResponse, type OkResponse, type PendingGrantChange, type UpdateGrantInput } from '@fabrika/iam-contract';
2
2
  import { type AdminContext } from './context';
3
- export declare function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantDto>;
3
+ export declare function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantChangeResponse>;
4
4
  export declare function deleteGrantUseCase(c: AdminContext, input: {
5
5
  id: string;
6
- }): Promise<OkResponse>;
6
+ }): Promise<OkResponse & Partial<PendingGrantChange>>;
7
7
  /** Edit a grant in place within its original application. Both paths use the same role, scope and external-person rules. */
8
- export declare function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<GrantDto>;
8
+ export declare function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<GrantChangeResponse>;
package/types/src/db.d.ts CHANGED
@@ -5,6 +5,7 @@ import { AuditRepository, type SqlDialect } from './repositories/audit';
5
5
  import { InstallationBrandRepository } from './repositories/brand';
6
6
  import { CredentialRepository } from './repositories/credentials';
7
7
  import { DeviceAuthorizationRepository } from './repositories/device';
8
+ import { GrantRequestRepository } from './repositories/grant-requests';
8
9
  import { GrantRepository } from './repositories/grants';
9
10
  import { HandoffRepository } from './repositories/handoff';
10
11
  import { MembershipRepository } from './repositories/membership';
@@ -21,7 +22,8 @@ export { type AuditedChange, type AuditEventInput, type AuditEventRow, auditEven
21
22
  export { type InstallationBrandImages, InstallationBrandRepository, type InstallationBrandRow } from './repositories/brand';
22
23
  export { type CredentialGrantRow, CredentialRepository, type CredentialRow } from './repositories/credentials';
23
24
  export { DeviceAuthorizationRepository, type DeviceAuthorizationRow, type DeviceReceiptRow } from './repositories/device';
24
- export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow } from './repositories/grants';
25
+ export { type CreateGrantRequestInput, GrantRequestRepository, type GrantRequestRow } from './repositories/grant-requests';
26
+ export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow, type GrantSetRead } from './repositories/grants';
25
27
  export { type AuthCodeRow, HandoffRepository } from './repositories/handoff';
26
28
  export { type DelegationGrantRow, type InvitationAcceptance, type InvitationRow, type InviterCheck, type MemberGrantRow, MembershipRepository, type MembershipRepositoryOptions, type NewPrincipalAcceptance, type NewPrincipalEvents, } from './repositories/membership';
27
29
  export { MembershipTransportKeyRepository, type MembershipTransportKeyRow } from './repositories/membership-transport';
@@ -37,6 +39,7 @@ export interface IamRepositories {
37
39
  device: DeviceAuthorizationRepository;
38
40
  principals: PrincipalRepository;
39
41
  grants: GrantRepository;
42
+ grantRequests: GrantRequestRepository;
40
43
  appSchema: AppSchemaRepository;
41
44
  credentials: CredentialRepository;
42
45
  sessions: SessionRepository;
@@ -1,5 +1,5 @@
1
1
  import { type KeyGrant, type PermissionEntry } from '@fabrika/auth-core';
2
- import { OAUTH_DEVICE_CODE_GRANT_TYPE, type OAuthAuthorizationRequest, type OAuthClientMetadataDocument, type OAuthResourceDto, type OAuthRevocationRequest, type OAuthTokenRequest, type OAuthTokenResponse } from '@fabrika/iam-contract';
2
+ import { OAUTH_DEVICE_CODE_GRANT_TYPE, type OAuthAuthorizationRequest, type OAuthClientMetadataDocument, type OAuthIdentityRole, type OAuthResourceDto, type OAuthRevocationRequest, type OAuthTokenRequest, type OAuthTokenResponse } from '@fabrika/iam-contract';
3
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';
@@ -61,16 +61,30 @@ export declare function exchangeOAuthToken(services: Services, env: SigningEnv,
61
61
  export declare function revokeOAuthToken(services: Services, env: SigningEnv, input: OAuthRevocationRequest, requestId: string): Promise<void>;
62
62
  /** An access token for `resource`, one of the grant's resources, carrying the grant's live authority there. */
63
63
  export declare function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGrantRow, resource: string, now: number): Promise<OAuthTokenResponse | null>;
64
+ /** What a grant's next token carries. `identity` is present on an identity resource's: its roles, when it declares them. */
65
+ export interface GrantAuthority {
66
+ principal: PrincipalRow;
67
+ scopes: string[];
68
+ permissions: PermissionEntry[];
69
+ expiresAt: number | null;
70
+ identity?: {
71
+ roles?: string[];
72
+ };
73
+ }
64
74
  /**
65
75
  * Everything a grant needs to still mean something, checked at every code exchange and refresh: the
66
76
  * grant live, its client and resource still configured, the IAM session it was given under live and
67
77
  * usable, the principal an active user. The permissions are resolved live, never from the consent.
68
78
  */
69
- export declare function grantAuthority(services: Services, grant: OAuthGrantRow, now: number, resourceUri?: string): Promise<{
70
- principal: PrincipalRow;
71
- scopes: string[];
72
- permissions: PermissionEntry[];
73
- expiresAt: number | null;
79
+ export declare function grantAuthority(services: Services, grant: OAuthGrantRow, now: number, resourceUri?: string): Promise<GrantAuthority | null>;
80
+ /**
81
+ * The declared roles `principal` holds at an external application, in declared order, and when the earliest of them
82
+ * ends (null: none ends); null when it holds none. Only a global grant of a declared role counts, and only for an
83
+ * internal principal: an external one holds nothing but roles its application declares external (ADR-0051).
84
+ */
85
+ export declare function heldIdentityRoles(services: Services, principal: PrincipalRow, app: string, declared: readonly OAuthIdentityRole[]): Promise<{
86
+ keys: string[];
87
+ until: number | null;
74
88
  } | null>;
75
89
  /** The union of the scopes' grants, or null when a scope is no longer configured. */
76
90
  export declare function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null;
@@ -1,4 +1,4 @@
1
- import { type WorkloadKind } from '@fabrika/auth-core';
1
+ import { type DimensionValue, type WorkloadKind } from '@fabrika/auth-core';
2
2
  import { type SqlDatabase } from '@fabrika/platform';
3
3
  import { type AuditEventInput, AuditWriter } from './audit';
4
4
  /** A role/policy bundle row (the `roles` table). `permissions` is a JSON array string. */
@@ -36,6 +36,8 @@ export interface AppScopeRow {
36
36
  members_directory: 'labels' | null;
37
37
  /** A JSON array of the actions that look up one member (`findMember`), or null for none. */
38
38
  members_lookup: string | null;
39
+ /** A JSON array of the `{ value, label? }` the console offers for a grant here (ADR-0085), or null for none. */
40
+ value_list: string | null;
39
41
  }
40
42
  /** A share-link mount (the `app_link_mounts` table). `grants` is a JSON array of exact actions. */
41
43
  export interface LinkMountRow {
@@ -187,6 +189,7 @@ export declare class AppSchemaRepository {
187
189
  list: string;
188
190
  } | null;
189
191
  directory?: 'labels' | null;
192
+ values?: readonly DimensionValue[] | null;
190
193
  lookups?: string[] | null;
191
194
  }[];
192
195
  actions: {
@@ -104,6 +104,8 @@ export interface AuditedChange {
104
104
  readonly statements: SqlStatement[];
105
105
  /** The rows the LAST change returned, read from the results of a batch whose statements start at `offset`. */
106
106
  rows<T>(results: SqlQueryResult<T>[], offset?: number): T[];
107
+ /** The id of the record, which exists after the batch exactly when the change changed a row; null without a record. */
108
+ readonly recordId: string | null;
107
109
  }
108
110
  /**
109
111
  * Writes the record of a guarded change exactly when the change changed a row, decided by the change itself and never