@fabrika/iam 0.9.0-dev.36 → 0.9.0-dev.38

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,4 +1,4 @@
1
- import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
1
+ import { type SqlDatabase, type SqlQueryResult, type SqlStatement, uuidv7 } from '@fabrika/platform'
2
2
  import { z } from 'zod'
3
3
  import { type AuditEventInput, AuditWriter, type SqlChange, type SqlDialect } from './audit'
4
4
  import type { GrantRequestRow } from './grant-requests'
@@ -79,6 +79,8 @@ export interface GrantRow {
79
79
  scope_type: string | null
80
80
  /** Opaque, app-owned scope value; NULL = global. */
81
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
82
84
  granted_by: string | null
83
85
  expires_at: number | null
84
86
  created_at: number
@@ -91,8 +93,23 @@ export interface CreateGrantInput {
91
93
  permissions?: string[] | null
92
94
  scopeType?: string | null
93
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
94
98
  grantedBy?: string | null
95
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
96
113
  }
97
114
 
98
115
  export class GrantRepository {
@@ -181,6 +198,25 @@ export class GrantRepository {
181
198
  return this.db.prepare('SELECT * FROM grants WHERE id = ?').bind(id).first<GrantRow>()
182
199
  }
183
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
+
184
220
  /**
185
221
  * Create a grant. EITHER `roleKey` (named role/policy) OR `permissions` (an inline
186
222
  * action-pattern set, JSON-encoded here) — the caller MUST supply exactly one; the
@@ -200,6 +236,93 @@ export class GrantRepository {
200
236
  return created
201
237
  }
202
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
+
203
326
  /** Whether `principalId` may hold this grant: it is internal, or the role is one its app declares external. */
204
327
  async isEligibleGrant(input: { principalId: string; app?: string | null; roleKey?: string | null }): Promise<boolean> {
205
328
  return (await this.db.prepare(`SELECT 1 AS eligible WHERE ${eligibleGrantSql('sqlite')}`).bind(...eligibleGrantBinds(input)).first()) !== null
@@ -334,8 +457,8 @@ export class GrantRepository {
334
457
 
335
458
  private grantChange(id: string, input: CreateGrantInput, onConflict: string, guard?: { sql: string; binds: (string | number)[] }): SqlChange {
336
459
  return {
337
- sql: `INSERT INTO grants (id, principal_id, app, role_key, permissions, scope_type, scope_value, granted_by, expires_at, created_at)
338
- 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)}${
339
462
  guard === undefined ? '' : ` AND ${guard.sql}`
340
463
  } ${onConflict} RETURNING *`,
341
464
  binds: [
@@ -346,9 +469,10 @@ export class GrantRepository {
346
469
  input.permissions == null ? null : JSON.stringify(input.permissions),
347
470
  input.scopeType ?? null,
348
471
  input.scopeValue ?? null,
472
+ input.scopeSet ?? null,
349
473
  input.grantedBy ?? null,
350
474
  input.expiresAt ?? null,
351
- unixNow(),
475
+ input.createdAt ?? unixNow(),
352
476
  ...eligibleGrantBinds(input),
353
477
  ...(guard?.binds ?? []),
354
478
  ],
@@ -358,13 +482,16 @@ export class GrantRepository {
358
482
  /**
359
483
  * Write the change an approved grant request asks for (ADR-0083), in one transaction with the approval's claim: the
360
484
  * request moves `pending` → `approved` under `decision.id`, and the change carries a guard on that claim, so of two
361
- * approvals one claims and writes, the other writes nothing. `current` is the grant an `update` edits as the approver's
362
- * checks read it; the edit applies only over it. `claimed` false: decided or lapsed meanwhile. `changed` null with
363
- * `claimed`: the change wrote nothing (a role grant already held, an ineligible grant, a grant gone or edited since).
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.
364
491
  */
365
492
  async applyRequest(
366
493
  request: GrantRequestRow,
367
- current: GrantRow | null,
494
+ current: GrantSetRead | null,
368
495
  decision: { readonly id: string; readonly by: string; readonly at: number },
369
496
  audit: (grantId: string) => AuditEventInput,
370
497
  ): Promise<{ claimed: boolean; changed: GrantRow | null }> {
@@ -373,112 +500,103 @@ export class GrantRepository {
373
500
  WHERE id = ? AND status = 'pending' AND expires_at > ? RETURNING id`)
374
501
  .bind(decision.id, decision.by, decision.at, request.id, decision.at)
375
502
  const guard = { sql: 'EXISTS (SELECT 1 FROM grant_requests WHERE id = ? AND decision_id = ?)', binds: [request.id, decision.id] }
376
- const input: CreateGrantInput = {
503
+ const scopeValues = requestScopeValues(request)
504
+ const input: CreateGrantSetInput = {
377
505
  principalId: request.principal_id,
378
506
  app: request.app,
379
507
  roleKey: request.role_key,
380
508
  permissions: request.permissions === null ? null : storedActions(request.permissions),
381
509
  scopeType: request.scope_type,
382
- scopeValue: request.scope_value,
510
+ scopeValues,
383
511
  grantedBy: decision.by,
384
512
  expiresAt: request.grant_expires_at,
385
513
  }
386
514
  let grantId = request.grant_id ?? uuidv7()
387
- let change: SqlChange
515
+ let changes: SqlChange[]
388
516
  const leading: SqlStatement[] = []
517
+ const trailing: SqlStatement[] = []
389
518
  if (request.kind === 'create') {
390
- let conflict = ''
391
- const conflictBinds: number[] = []
392
- if (input.roleKey !== null && input.scopeValue != null) {
393
- conflict =
394
- `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`
395
- } else if (input.roleKey !== null) {
396
- // As `createDelegatedRoleGrant`: an expired grant of the role is renewed in place, keeping its id.
397
- const expired = await this.db
398
- .prepare(`SELECT id FROM grants WHERE principal_id = ? AND role_key = ? AND app = ? AND scope_value IS NULL
399
- AND expires_at IS NOT NULL AND expires_at <= ?`)
400
- .bind(request.principal_id, input.roleKey, request.app, decision.at)
401
- .first<{ id: string }>()
402
- grantId = expired?.id ?? grantId
403
- conflict = `ON CONFLICT (principal_id, role_key, COALESCE(app, '*')) WHERE role_key IS NOT NULL AND scope_value IS NULL
404
- DO UPDATE SET expires_at = excluded.expires_at, granted_by = excluded.granted_by, created_at = excluded.created_at
405
- WHERE grants.expires_at IS NOT NULL AND grants.expires_at <= ?`
406
- conflictBinds.push(decision.at)
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] }]
407
543
  }
408
- const insert = this.grantChange(grantId, input, conflict, guard)
409
- change = { sql: insert.sql, binds: [...insert.binds, ...conflictBinds] }
544
+ leading.push(claim)
410
545
  } else if (request.kind === 'update') {
411
546
  if (current === null) return { claimed: false, changed: null }
412
- leading.push(grantRemovalStatement(this.db, { principalId: request.principal_id }))
413
- change = {
414
- sql: `UPDATE grants SET role_key = ?, permissions = ?, scope_type = ?, scope_value = ?, expires_at = ?
415
- WHERE id = ? AND app = ? AND role_key IS NOT DISTINCT FROM ? AND permissions IS NOT DISTINCT FROM ?
416
- AND scope_type IS NOT DISTINCT FROM ? AND scope_value IS NOT DISTINCT FROM ? AND expires_at IS NOT DISTINCT FROM ?
417
- AND ${eligibleGrantSql(this.writer.dialect)} AND ${guard.sql} RETURNING *`,
418
- binds: [
419
- input.roleKey ?? null,
420
- request.permissions,
421
- input.scopeType ?? null,
422
- input.scopeValue ?? null,
423
- input.expiresAt ?? null,
424
- current.id,
425
- request.app,
426
- current.role_key,
427
- current.permissions,
428
- current.scope_type,
429
- current.scope_value,
430
- current.expires_at,
431
- ...eligibleGrantBinds(input),
432
- ...guard.binds,
433
- ],
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],
434
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
+ )
435
573
  } else {
436
- leading.push(grantRemovalStatement(this.db, { principalId: request.principal_id }))
437
- change = {
438
- sql: `DELETE FROM grants WHERE id = ? AND app = ? AND principal_id = ? AND ${guard.sql} RETURNING *`,
439
- binds: [grantId, request.app, request.principal_id, ...guard.binds],
440
- }
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
+ }]
441
579
  }
442
- leading.push(claim)
443
- const audited = this.writer.changed([change], audit(grantId))
580
+ const claimAt = leading.indexOf(claim)
581
+ const audited = this.writer.changed(changes, audit(grantId))
444
582
  // A claim whose change wrote nothing (no record) closes the request `failed` in the same transaction.
445
583
  const failed = this.db
446
584
  .prepare(`UPDATE grant_requests SET status = 'failed' WHERE id = ? AND decision_id = ?
447
585
  AND NOT EXISTS (SELECT 1 FROM audit_events WHERE id = ?)`)
448
586
  .bind(request.id, decision.id, audited.recordId)
449
- const results = await this.db.batch<GrantRow>([...leading, ...audited.statements, failed])
450
- const claimed = (results[leading.length - 1]?.results.length ?? 0) > 0
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
451
597
  return { claimed, changed: audited.rows(results, leading.length)[0] ?? null }
452
598
  }
453
599
 
454
- /** Keep the audit's before-value true if another administrator edited this grant after it was read. */
455
- async updateGrant(grant: GrantRow, input: CreateGrantInput, audit: AuditEventInput): Promise<GrantRow | null> {
456
- await this.refuseWorkload(grant.principal_id)
457
- const update = this.writer.changed([{
458
- sql: `UPDATE grants SET role_key = ?, permissions = ?, scope_type = ?, scope_value = ?, expires_at = ?
459
- WHERE id = ? AND role_key IS NOT DISTINCT FROM ? AND permissions IS NOT DISTINCT FROM ?
460
- AND scope_type IS NOT DISTINCT FROM ? AND scope_value IS NOT DISTINCT FROM ? AND expires_at IS NOT DISTINCT FROM ?
461
- AND ${eligibleGrantSql(this.writer.dialect)} RETURNING *`,
462
- binds: [
463
- input.roleKey ?? null,
464
- input.permissions === null || input.permissions === undefined ? null : JSON.stringify(input.permissions),
465
- input.scopeType ?? null,
466
- input.scopeValue ?? null,
467
- input.expiresAt ?? null,
468
- grant.id,
469
- grant.role_key,
470
- grant.permissions,
471
- grant.scope_type,
472
- grant.scope_value,
473
- grant.expires_at,
474
- ...eligibleGrantBinds(input),
475
- ],
476
- }], audit)
477
- // Editing can remove authority too. Invalidate pending delegation checks before changing the grant.
478
- const results = await this.db.batch<GrantRow>([grantRemovalStatement(this.db, { principalId: grant.principal_id }), ...update.statements])
479
- return update.rows(results, 1)[0] ?? null
480
- }
481
-
482
600
  /** Delete a grant, after its principal's revision. */
483
601
  async deleteGrant(id: string, audit?: AuditEventInput): Promise<boolean> {
484
602
  const removal = this.writer.changed([{ sql: 'DELETE FROM grants WHERE id = ? RETURNING id', binds: [id] }], audit)
@@ -502,8 +620,15 @@ export class GrantRepository {
502
620
  }
503
621
 
504
622
  const storedActionsSchema = z.array(z.string())
623
+ const storedScopeValuesSchema = z.array(z.string()).min(2)
505
624
 
506
625
  /** A stored inline action set (a JSON array of patterns), read once where it leaves the row. */
507
626
  function storedActions(json: string): string[] {
508
627
  return storedActionsSchema.parse(JSON.parse(json))
509
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
+ }
@@ -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
package/types/src/db.d.ts CHANGED
@@ -23,7 +23,7 @@ export { type InstallationBrandImages, InstallationBrandRepository, type Install
23
23
  export { type CredentialGrantRow, CredentialRepository, type CredentialRow } from './repositories/credentials';
24
24
  export { DeviceAuthorizationRepository, type DeviceAuthorizationRow, type DeviceReceiptRow } from './repositories/device';
25
25
  export { type CreateGrantRequestInput, GrantRequestRepository, type GrantRequestRow } from './repositories/grant-requests';
26
- export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow } from './repositories/grants';
26
+ export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow, type GrantSetRead } from './repositories/grants';
27
27
  export { type AuthCodeRow, HandoffRepository } from './repositories/handoff';
28
28
  export { type DelegationGrantRow, type InvitationAcceptance, type InvitationRow, type InviterCheck, type MemberGrantRow, MembershipRepository, type MembershipRepositoryOptions, type NewPrincipalAcceptance, type NewPrincipalEvents, } from './repositories/membership';
29
29
  export { MembershipTransportKeyRepository, type MembershipTransportKeyRow } from './repositories/membership-transport';
@@ -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: {
@@ -15,7 +15,10 @@ export interface GrantRequestRow {
15
15
  /** Inline action-pattern set (JSON array); XOR `role_key`. */
16
16
  permissions: string | null;
17
17
  scope_type: string | null;
18
+ /** The first of the requested values, or the only one; null for a global grant. */
18
19
  scope_value: string | null;
20
+ /** Every requested value (JSON array) when there are several (ADR-0085); read through `requestScopeValues`. */
21
+ scope_values: string | null;
19
22
  grant_expires_at: number | null;
20
23
  requested_by: string;
21
24
  requested_at: number;
@@ -34,7 +37,8 @@ export interface CreateGrantRequestInput {
34
37
  roleKey: string | null;
35
38
  permissions: string[] | null;
36
39
  scopeType: string | null;
37
- scopeValue: string | null;
40
+ /** Sorted and distinct; null for a global grant. */
41
+ scopeValues: string[] | null;
38
42
  grantExpiresAt: number | null;
39
43
  requestedBy: string;
40
44
  requestedAt: number;
@@ -63,6 +63,8 @@ export interface GrantRow {
63
63
  scope_type: string | null;
64
64
  /** Opaque, app-owned scope value; NULL = global. */
65
65
  scope_value: string | null;
66
+ /** 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). */
67
+ scope_set: string | null;
66
68
  granted_by: string | null;
67
69
  expires_at: number | null;
68
70
  created_at: number;
@@ -74,8 +76,21 @@ export interface CreateGrantInput {
74
76
  permissions?: string[] | null;
75
77
  scopeType?: string | null;
76
78
  scopeValue?: string | null;
79
+ /** The grant id every row of a grant of several values shares (ADR-0085); null or omitted for a grant of one. */
80
+ scopeSet?: string | null;
77
81
  grantedBy?: string | null;
78
82
  expiresAt?: number | null;
83
+ /** When the grant was first written; an edit keeps it. Omitted = now. */
84
+ createdAt?: number;
85
+ }
86
+ /** A grant of one or more values of one dimension, or a global one (`scopeType` and `scopeValues` null). */
87
+ export interface CreateGrantSetInput extends Omit<CreateGrantInput, 'scopeValue' | 'scopeSet'> {
88
+ scopeValues: readonly string[] | null;
89
+ }
90
+ /** The rows of one grant (ADR-0085) and its principal's grant revision, read by one statement. */
91
+ export interface GrantSetRead {
92
+ readonly rows: [GrantRow, ...GrantRow[]];
93
+ readonly grantRevision: number;
79
94
  }
80
95
  export declare class GrantRepository {
81
96
  protected readonly db: SqlDatabase;
@@ -103,6 +118,11 @@ export declare class GrantRepository {
103
118
  */
104
119
  listGrantsFor(principalIds: readonly string[]): Promise<GrantRow[]>;
105
120
  getGrantById(id: string): Promise<GrantRow | null>;
121
+ /**
122
+ * Every row of the grant `grantId` belongs to (ADR-0085), whichever of its rows the id names, with the principal's
123
+ * grant revision read in the same statement, so a removal after this read moves the revision `replaceGrantSet` checks.
124
+ */
125
+ getGrantSet(grantId: string): Promise<GrantSetRead | null>;
106
126
  /**
107
127
  * Create a grant. EITHER `roleKey` (named role/policy) OR `permissions` (an inline
108
128
  * action-pattern set, JSON-encoded here) — the caller MUST supply exactly one; the
@@ -112,6 +132,28 @@ export declare class GrantRepository {
112
132
  * nothing, for a grant the principal may not hold (ADR-0051).
113
133
  */
114
134
  createGrant(input: CreateGrantInput, audit?: (grantId: string) => AuditEventInput): Promise<GrantRow>;
135
+ /**
136
+ * Create a grant of several values of one dimension: one row per value, sharing `scope_set` (ADR-0085), all written or
137
+ * none, with ONE record. A duplicate role grant fails the unique index and throws, rolling the batch back. Throws
138
+ * `ExternalGrantError`, writing nothing, for a grant the principal may not hold.
139
+ */
140
+ createGrantSet(input: CreateGrantSetInput, audit: (grantId: string) => AuditEventInput): Promise<GrantRow[]>;
141
+ /** The INSERTs of a grant's rows with a caller-generated grant id, for a batch that also writes its principal and record. */
142
+ grantSetStatements(id: string, input: CreateGrantSetInput): SqlStatement[];
143
+ /**
144
+ * 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
145
+ * value, and a global one, is one row without `scope_set`, as every grant before ADR-0085.
146
+ */
147
+ private grantSetChanges;
148
+ /**
149
+ * Replace the rows of the grant `read` names with `input`, keeping its id, in one transaction with ONE record: null
150
+ * when the principal's grants changed since the read (its grant revision moved). Moves the revision first, because an
151
+ * edit can remove authority. A duplicate role grant fails the unique index and throws; a grant the principal may not
152
+ * hold throws `ExternalGrantError`; both roll the batch back.
153
+ */
154
+ replaceGrantSet(read: GrantSetRead, input: CreateGrantSetInput, audit: AuditEventInput): Promise<GrantRow[] | null>;
155
+ /** Delete every row of the grant `grantId` names (ADR-0085), after its principal's revision, with ONE record. */
156
+ deleteGrantSet(grantId: string, principalId: string, audit: AuditEventInput): Promise<boolean>;
115
157
  /** Whether `principalId` may hold this grant: it is internal, or the role is one its app declares external. */
116
158
  isEligibleGrant(input: {
117
159
  principalId: string;
@@ -167,11 +209,14 @@ export declare class GrantRepository {
167
209
  /**
168
210
  * Write the change an approved grant request asks for (ADR-0083), in one transaction with the approval's claim: the
169
211
  * request moves `pending` → `approved` under `decision.id`, and the change carries a guard on that claim, so of two
170
- * approvals one claims and writes, the other writes nothing. `current` is the grant an `update` edits as the approver's
171
- * checks read it; the edit applies only over it. `claimed` false: decided or lapsed meanwhile. `changed` null with
172
- * `claimed`: the change wrote nothing (a role grant already held, an ineligible grant, a grant gone or edited since).
212
+ * approvals one claims and writes, the other writes nothing. `current` is the grant an `update` edits or a `revoke`
213
+ * removes, as the approver's checks read it; an edit applies only while the principal's grants are as read. A grant of
214
+ * several values is written, replaced or removed whole (ADR-0085). `claimed` false: decided or lapsed meanwhile.
215
+ * `changed` null with `claimed`: the change wrote nothing (a role grant already held, a grant gone or edited since).
216
+ * A value of a new set the principal already holds the role in fails the unique index, and a replacement the principal
217
+ * may not hold throws `ExternalGrantError`; both roll the approval back and leave the request open.
173
218
  */
174
- applyRequest(request: GrantRequestRow, current: GrantRow | null, decision: {
219
+ applyRequest(request: GrantRequestRow, current: GrantSetRead | null, decision: {
175
220
  readonly id: string;
176
221
  readonly by: string;
177
222
  readonly at: number;
@@ -179,8 +224,6 @@ export declare class GrantRepository {
179
224
  claimed: boolean;
180
225
  changed: GrantRow | null;
181
226
  }>;
182
- /** Keep the audit's before-value true if another administrator edited this grant after it was read. */
183
- updateGrant(grant: GrantRow, input: CreateGrantInput, audit: AuditEventInput): Promise<GrantRow | null>;
184
227
  /** Delete a grant, after its principal's revision. */
185
228
  deleteGrant(id: string, audit?: AuditEventInput): Promise<boolean>;
186
229
  /** Delete all grants for a principal (revocation), after its revision (`grantRemovalStatement`). */
@@ -191,3 +234,5 @@ export declare class GrantRepository {
191
234
  */
192
235
  deleteGrantsForPrincipalChange(principalId: string): SqlChange;
193
236
  }
237
+ /** The values a grant request asks for (ADR-0085): its set, or its one value; null for a global grant. */
238
+ export declare function requestScopeValues(request: Pick<GrantRequestRow, 'scope_value' | 'scope_values'>): string[] | null;