@fuzdev/fuz_app 0.181.0 → 0.182.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/actions/CLAUDE.md +24 -6
  2. package/dist/actions/action_rpc.d.ts +11 -1
  3. package/dist/actions/action_rpc.d.ts.map +1 -1
  4. package/dist/actions/action_rpc.js +3 -2
  5. package/dist/actions/action_types.d.ts +16 -1
  6. package/dist/actions/action_types.d.ts.map +1 -1
  7. package/dist/actions/action_types.js +1 -1
  8. package/dist/actions/notification_sender.d.ts +83 -0
  9. package/dist/actions/notification_sender.d.ts.map +1 -0
  10. package/dist/actions/notification_sender.js +85 -0
  11. package/dist/actions/perform_action.d.ts +9 -0
  12. package/dist/actions/perform_action.d.ts.map +1 -1
  13. package/dist/actions/perform_action.js +22 -13
  14. package/dist/actions/register_action_ws.d.ts +14 -0
  15. package/dist/actions/register_action_ws.d.ts.map +1 -1
  16. package/dist/actions/register_action_ws.js +3 -2
  17. package/dist/actions/ws_socket_session.d.ts +3 -0
  18. package/dist/actions/ws_socket_session.d.ts.map +1 -1
  19. package/dist/actions/ws_socket_session.js +2 -1
  20. package/dist/auth/CLAUDE.md +60 -41
  21. package/dist/auth/account_actions.d.ts.map +1 -1
  22. package/dist/auth/account_actions.js +13 -3
  23. package/dist/auth/account_queries.d.ts +158 -16
  24. package/dist/auth/account_queries.d.ts.map +1 -1
  25. package/dist/auth/account_queries.js +189 -18
  26. package/dist/auth/account_routes.d.ts +1 -1
  27. package/dist/auth/account_routes.d.ts.map +1 -1
  28. package/dist/auth/account_routes.js +27 -26
  29. package/dist/auth/admin_actions.d.ts.map +1 -1
  30. package/dist/auth/admin_actions.js +71 -28
  31. package/dist/auth/api_token_queries.d.ts +13 -5
  32. package/dist/auth/api_token_queries.d.ts.map +1 -1
  33. package/dist/auth/api_token_queries.js +24 -9
  34. package/dist/auth/bearer_auth.d.ts.map +1 -1
  35. package/dist/auth/bearer_auth.js +3 -2
  36. package/dist/auth/daemon_token_middleware.d.ts.map +1 -1
  37. package/dist/auth/daemon_token_middleware.js +12 -1
  38. package/dist/auth/deps.d.ts +10 -0
  39. package/dist/auth/deps.d.ts.map +1 -1
  40. package/dist/auth/request_context.d.ts +73 -73
  41. package/dist/auth/request_context.d.ts.map +1 -1
  42. package/dist/auth/request_context.js +78 -96
  43. package/dist/auth/resolved_auth.d.ts +10 -5
  44. package/dist/auth/resolved_auth.d.ts.map +1 -1
  45. package/dist/auth/resolved_auth.js +2 -2
  46. package/dist/auth/role_grant_offer_action_specs.d.ts +1 -1
  47. package/dist/auth/role_grant_offer_action_specs.d.ts.map +1 -1
  48. package/dist/auth/role_grant_offer_action_specs.js +2 -1
  49. package/dist/auth/role_grant_offer_actions.d.ts +7 -11
  50. package/dist/auth/role_grant_offer_actions.d.ts.map +1 -1
  51. package/dist/auth/role_grant_offer_actions.js +61 -93
  52. package/dist/auth/role_grant_offer_notifications.d.ts +87 -38
  53. package/dist/auth/role_grant_offer_notifications.d.ts.map +1 -1
  54. package/dist/auth/role_grant_offer_notifications.js +75 -22
  55. package/dist/auth/role_grant_offer_queries.d.ts +96 -15
  56. package/dist/auth/role_grant_offer_queries.d.ts.map +1 -1
  57. package/dist/auth/role_grant_offer_queries.js +185 -70
  58. package/dist/auth/role_grant_offer_schema.js +1 -1
  59. package/dist/auth/role_grant_queries.d.ts +52 -12
  60. package/dist/auth/role_grant_queries.d.ts.map +1 -1
  61. package/dist/auth/role_grant_queries.js +75 -24
  62. package/dist/auth/role_grant_sql.d.ts +21 -0
  63. package/dist/auth/role_grant_sql.d.ts.map +1 -1
  64. package/dist/auth/role_grant_sql.js +21 -0
  65. package/dist/auth/self_service_role_actions.d.ts.map +1 -1
  66. package/dist/auth/self_service_role_actions.js +9 -2
  67. package/dist/auth/session_queries.d.ts +34 -13
  68. package/dist/auth/session_queries.d.ts.map +1 -1
  69. package/dist/auth/session_queries.js +48 -18
  70. package/dist/auth/standard_rpc_actions.d.ts +6 -19
  71. package/dist/auth/standard_rpc_actions.d.ts.map +1 -1
  72. package/dist/auth/standard_rpc_actions.js +5 -6
  73. package/dist/auth/token_scope.d.ts +1 -1
  74. package/dist/auth/token_scope.js +1 -1
  75. package/dist/http/CLAUDE.md +7 -6
  76. package/dist/http/auth_shape.d.ts +1 -1
  77. package/dist/http/error_schemas.d.ts +9 -21
  78. package/dist/http/error_schemas.d.ts.map +1 -1
  79. package/dist/http/error_schemas.js +14 -24
  80. package/dist/http/route_spec.d.ts +2 -2
  81. package/dist/server/app_backend.d.ts.map +1 -1
  82. package/dist/server/app_backend.js +3 -1
  83. package/dist/server/app_server.d.ts +26 -16
  84. package/dist/server/app_server.d.ts.map +1 -1
  85. package/dist/server/app_server.js +17 -7
  86. package/dist/server/serve_fact_route.d.ts +3 -3
  87. package/dist/server/serve_fact_route.js +12 -12
  88. package/dist/testing/CLAUDE.md +5 -5
  89. package/dist/testing/app_server.d.ts.map +1 -1
  90. package/dist/testing/app_server.js +3 -1
  91. package/dist/testing/auth_apps.js +1 -1
  92. package/dist/testing/cross_backend/account_lifecycle.d.ts.map +1 -1
  93. package/dist/testing/cross_backend/account_lifecycle.js +43 -0
  94. package/dist/testing/cross_backend/default_spine_surface.d.ts +1 -26
  95. package/dist/testing/cross_backend/default_spine_surface.d.ts.map +1 -1
  96. package/dist/testing/cross_backend/default_spine_surface.js +2 -6
  97. package/dist/testing/cross_backend/full_spine_mount.d.ts +3 -10
  98. package/dist/testing/cross_backend/full_spine_mount.d.ts.map +1 -1
  99. package/dist/testing/cross_backend/full_spine_mount.js +4 -4
  100. package/dist/testing/cross_backend/role_grant_offer_notification_ws.d.ts +5 -4
  101. package/dist/testing/cross_backend/role_grant_offer_notification_ws.d.ts.map +1 -1
  102. package/dist/testing/cross_backend/role_grant_offer_notification_ws.js +183 -30
  103. package/dist/testing/cross_backend/session_cap.d.ts.map +1 -1
  104. package/dist/testing/cross_backend/session_cap.js +26 -5
  105. package/dist/testing/middleware.d.ts +1 -1
  106. package/dist/testing/middleware.js +5 -5
  107. package/dist/testing/resolved_auth.d.ts +3 -1
  108. package/dist/testing/resolved_auth.d.ts.map +1 -1
  109. package/dist/testing/resolved_auth.js +4 -4
  110. package/dist/testing/stubs.d.ts.map +1 -1
  111. package/dist/testing/stubs.js +5 -2
  112. package/dist/testing/ws_round_trip.d.ts.map +1 -1
  113. package/dist/testing/ws_round_trip.js +8 -4
  114. package/package.json +1 -1
@@ -106,12 +106,16 @@ export declare class RoleGrantOfferActorAccountMismatchError extends Error {
106
106
  constructor();
107
107
  }
108
108
  /**
109
- * Error thrown by `query_role_grant_offer_create` when the recipient is not an
110
- * active account: `to_account_id` names no account, a soft-deleted one, or one
111
- * with no active actor. A deleted recipient and one that never existed are the
112
- * one refusal, so a caller learns nothing from it that a missing id wouldn't
113
- * tell; the handler answers it as `role_grant_assign` answers the same
114
- * recipient. Twin of the Rust `RoleGrantOfferError::RecipientNotActive`.
109
+ * Error thrown when the recipient is not an active account.
110
+ *
111
+ * By `query_role_grant_offer_create`: `to_account_id` names no account, a
112
+ * soft-deleted one, or one with no active actor. A deleted recipient and one
113
+ * that never existed are the one refusal, so a caller learns nothing from it
114
+ * that a missing id wouldn't tell; the handler answers it as
115
+ * `role_grant_assign` answers the same recipient. By `query_accept_offer`: the
116
+ * accepting account — the caller — was deleted or purged after its credential
117
+ * was read, and its handler answers the dead credential. Twin of the Rust
118
+ * `RoleGrantOfferError::RecipientNotActive`.
115
119
  */
116
120
  export declare class RoleGrantOfferRecipientNotActiveError extends Error {
117
121
  constructor();
@@ -231,8 +235,11 @@ export declare const query_role_grant_offer_history_for_account: (deps: QueryDep
231
235
  * caller's `role_grant_offer_expire` audit inserts — committed together, or
232
236
  * rolled back together so the next sweep retries. Concurrent sweeps claim
233
237
  * disjoint rows: a row another sweep has stamped but not committed blocks on
234
- * its row lock, then fails the re-checked `expire_audited_at IS NULL`.
235
- * `cleanup_expired_role_grant_offers` is the caller.
238
+ * its row lock, then fails the re-checked `expire_audited_at IS NULL`. The
239
+ * rows are locked in id order (`offer_rows_locked_in_id_order`), as every
240
+ * multi-row offer write takes them, so a sweep and a delete, purge, revoke or
241
+ * accept over the same expired offers never wait on each other in opposite
242
+ * orders. `cleanup_expired_role_grant_offers` is the caller.
236
243
  *
237
244
  * @mutates `role_grant_offer` rows - stamps `expire_audited_at` on each claimed row
238
245
  */
@@ -261,6 +268,12 @@ export interface AcceptOfferInput {
261
268
  export interface AcceptOfferResult {
262
269
  role_grant: RoleGrant;
263
270
  offer: RoleGrantOffer;
271
+ /**
272
+ * The grantor's account (the offer's `from_actor_id` → account), read on the
273
+ * claimed row, so the caller can tell the grantor without a second read.
274
+ * Twin of the Rust `AcceptOfferResult::from_account_id`.
275
+ */
276
+ from_account_id: Uuid;
264
277
  /** `true` if this call is the one that accepted the offer (new role_grant inserted); `false` on a replay (or a race loser) returning the already-created, still-held role_grant — the caller then audits and notifies nothing. */
265
278
  created: boolean;
266
279
  /**
@@ -286,9 +299,29 @@ export interface AcceptOfferResult {
286
299
  * creating a duplicate or throwing — while that grant is still held. A grant
287
300
  * revoked since the accept, or gone, makes the offer terminal.
288
301
  *
302
+ * Lock order — accounts, then offers, then the grant: the recipient's account
303
+ * row (and, for an unscoped `admin` offer, the grantor's) in id order
304
+ * (`query_account_lock_for_offer_accept`), then the offer and the pending
305
+ * siblings it supersedes in one id-ordered claim, then the grant insert. The
306
+ * accounts first, as every removal of either account takes them first, so a
307
+ * removal and an accept never meet at the offers, the actor, or a grant a
308
+ * purge's cascade reaches; two accepts by one recipient take turns. The
309
+ * offers in id order, as every transaction that writes several offer rows
310
+ * locks them all first in one id-ordered statement (a delete, a purge, a
311
+ * revoke, the expiry sweep). The grantor's authority is read unlocked after
312
+ * the grantor's account lock — the invariant it rests on: every write that
313
+ * ends a grantor's global `admin` takes the grantor's account row first (a
314
+ * revoke of the grant through `query_account_lock_for_revoke`, whether or not
315
+ * its last-admin guard ran; a delete through its write of the row; a purge
316
+ * through `query_account_lock_admins_for_purge` and
317
+ * `query_account_lock_for_purge`; the DB browser's delete, which takes none of
318
+ * them, excepted).
319
+ *
289
320
  * Error map:
290
321
  * - `RoleGrantOfferNotFoundError` — offer does not exist, or belongs to a
291
322
  * different recipient (IDOR guard). The offer row is untouched.
323
+ * - `RoleGrantOfferRecipientNotActiveError` — the recipient's account was
324
+ * deleted or purged since the caller's credential was read.
292
325
  * - `RoleGrantOfferAlreadyTerminalError` — offer is declined, retracted, or
293
326
  * superseded; or accepted, and its grant revoked, gone, or bound to another
294
327
  * actor.
@@ -296,8 +329,8 @@ export interface AcceptOfferResult {
296
329
  * - `RoleGrantOfferActorMismatchError` — actor-targeted offer, different actor.
297
330
  * - `RoleGrantOfferBuiltinRefusedError` — a builtin-role offer that must not
298
331
  * mint: `keeper` at all, a builtin bound to a scope, or one whose grantor no
299
- * longer holds an active global `admin` (read under `FOR SHARE`). The offer
300
- * stays pending.
332
+ * longer holds an active global `admin` (read under the grantor's account
333
+ * lock). The offer stays pending.
301
334
  *
302
335
  * Sibling supersede is what closes the "accept a pre-revoke sibling offer
303
336
  * to bypass a revoke" path: once A is accepted, B/C/... can no longer be
@@ -308,6 +341,7 @@ export interface AcceptOfferResult {
308
341
  * @mutates `role_grant_offer` siblings - stamps `superseded_at` on every other pending offer for the tuple
309
342
  * @mutates `audit_log` table - emits `role_grant_offer_accept` + `role_grant_create` + one `role_grant_offer_supersede` per sibling
310
343
  * @throws RoleGrantOfferNotFoundError if the offer is missing or belongs to another recipient
344
+ * @throws RoleGrantOfferRecipientNotActiveError if the recipient's account is deleted or gone
311
345
  * @throws RoleGrantOfferAlreadyTerminalError if the offer is declined, retracted, or superseded, or accepted with its grant revoked, gone, or bound to another actor
312
346
  * @throws RoleGrantOfferExpiredError if the offer is pending but past `expires_at`
313
347
  * @throws RoleGrantOfferActorMismatchError if the offer is actor-targeted to a different actor
@@ -325,8 +359,11 @@ export declare const query_accept_offer: (deps: QueryDeps, input: AcceptOfferInp
325
359
  * (`account_delete` / `account_purge`, every actor of the account) end the
326
360
  * grantor's outgoing pending offers in the same transaction. Each row carries
327
361
  * the grantor's `from_account_id`, as every supersede cascade's does; the
328
- * caller emits a `role_grant_offer_supersede` audit event per entry, and the
329
- * revoke caller also sends the supersede notification. Twin of the Rust
362
+ * caller emits a `role_grant_offer_supersede` audit event per entry and
363
+ * queues its notifications (`queue_supersede_notifications`). The rows are
364
+ * taken in id order; a caller that writes other offers too locks them all
365
+ * first (`query_role_grant_offer_lock_for_account_removal`,
366
+ * `query_role_grant_offer_lock_for_revoke`). Twin of the Rust
330
367
  * `query_role_grant_offer_supersede_outgoing`.
331
368
  *
332
369
  * @param deps - query dependencies
@@ -337,7 +374,7 @@ export declare const query_accept_offer: (deps: QueryDeps, input: AcceptOfferInp
337
374
  export declare const query_role_grant_offer_supersede_outgoing: (deps: QueryDeps, from_actor_ids: ReadonlyArray<Uuid>) => Promise<Array<SupersededOffer>>;
338
375
  /**
339
376
  * Supersede every pending offer **made to** `to_account_id` — the
340
- * recipient-side cascade of an account delete.
377
+ * recipient-side cascade of an account delete or purge.
341
378
  *
342
379
  * An undelete restores the account, so an offer left pending through the
343
380
  * delete would come back with it and could then be accepted; superseding it
@@ -345,8 +382,11 @@ export declare const query_role_grant_offer_supersede_outgoing: (deps: QueryDeps
345
382
  * `to_account_id` alone covers the actor-addressed offers too: an offer's
346
383
  * `to_actor_id` is bound to its `to_account_id` at create. Each row carries
347
384
  * the grantor's `from_account_id`, as every supersede cascade's does; the
348
- * caller emits a `role_grant_offer_supersede` audit event per entry. Twin of
349
- * the Rust `query_role_grant_offer_supersede_incoming`.
385
+ * caller emits a `role_grant_offer_supersede` audit event per entry and
386
+ * queues its notifications (`queue_supersede_notifications`). The rows are
387
+ * taken in id order, after the caller's
388
+ * `query_role_grant_offer_lock_for_account_removal`. Twin of the Rust
389
+ * `query_role_grant_offer_supersede_incoming`.
350
390
  *
351
391
  * @param deps - query dependencies
352
392
  * @param to_account_id - the recipient account whose pending offers end
@@ -354,4 +394,45 @@ export declare const query_role_grant_offer_supersede_outgoing: (deps: QueryDeps
354
394
  * @mutates `role_grant_offer` rows - stamps `superseded_at` on every pending offer to `to_account_id`
355
395
  */
356
396
  export declare const query_role_grant_offer_supersede_incoming: (deps: QueryDeps, to_account_id: Uuid) => Promise<Array<SupersededOffer>>;
397
+ /**
398
+ * Lock every pending offer an account removal supersedes — the ones its actors
399
+ * made and the ones made to it — in one statement, in id order.
400
+ *
401
+ * A delete or a purge writes those offers in two statements, the outgoing
402
+ * then the incoming; taken that way, each could hold rows another writer of
403
+ * both sets (a revoke of the account's grant, the expiry sweep) waits on while
404
+ * waiting on rows that writer holds. Locked together first, in the order every
405
+ * multi-row offer write takes its rows, the two supersedes then write rows
406
+ * this transaction already holds. No offer to or from the account can be made
407
+ * meanwhile: an offer create takes both parties' account rows, which the
408
+ * removal has written or locked. Twin of the Rust
409
+ * `query_role_grant_offer_lock_for_account_removal`.
410
+ *
411
+ * @param deps - query dependencies (must be the removal's transaction)
412
+ * @param to_account_id - the removed account
413
+ * @param from_actor_ids - the removed account's actors
414
+ * @mutates `role_grant_offer` rows - row-locks every pending offer to the account or from its actors
415
+ */
416
+ export declare const query_role_grant_offer_lock_for_account_removal: (deps: QueryDeps, to_account_id: Uuid, from_actor_ids: ReadonlyArray<Uuid>) => Promise<void>;
417
+ /**
418
+ * Lock every pending offer `role_grant_revoke` supersedes — the revokee
419
+ * account's incoming offers of the revoked grant's role and scope, and every
420
+ * offer the revokee's actor made — in one statement, in id order.
421
+ *
422
+ * Taken after the revokee's account row (`query_account_lock_for_revoke`),
423
+ * which keeps any new offer to or from the account out, and before the grant's
424
+ * update: an accept claims its offers before it inserts its grant (whose unique
425
+ * slot waits on a revoke's uncommitted update of the same grant), so a revoke
426
+ * updating the grant first and then reaching the offers the accept holds would
427
+ * close a cycle. Then the revoke's two supersedes write rows it already holds,
428
+ * in the order every multi-row offer write takes its rows. Twin of the Rust
429
+ * `query_role_grant_offer_lock_for_revoke`.
430
+ *
431
+ * @param deps - query dependencies (must be the revoke's transaction)
432
+ * @param actor_id - the revokee actor
433
+ * @param role - the revoked grant's role
434
+ * @param scope_id - the revoked grant's scope, `null` for global
435
+ * @mutates `role_grant_offer` rows - row-locks the pending offers the revoke supersedes
436
+ */
437
+ export declare const query_role_grant_offer_lock_for_revoke: (deps: QueryDeps, actor_id: Uuid, role: string, scope_id: Uuid | null) => Promise<void>;
357
438
  //# sourceMappingURL=role_grant_offer_queries.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"role_grant_offer_queries.d.ts","sourceRoot":"","sources":["../../src/lib/auth/role_grant_offer_queries.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAEpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAGrD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAUrD,OAAO,KAAK,EACX,yBAAyB,EACzB,cAAc,EACd,eAAe,EACf,MAAM,8BAA8B,CAAC;AAGtC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAG3D;;;;;GAKG;AACH,qBAAa,kCAAmC,SAAQ,KAAK;gBAChD,QAAQ,EAAE,MAAM;CAI5B;AAED;;;;;GAKG;AACH,qBAAa,0BAA2B,SAAQ,KAAK;gBACxC,QAAQ,EAAE,MAAM;CAI5B;AAED;;;;;GAKG;AACH,qBAAa,2BAA4B,SAAQ,KAAK;gBACzC,QAAQ,EAAE,MAAM;CAI5B;AAED;;;;;;;;GAQG;AACH,qBAAa,6BAA8B,SAAQ,KAAK;;CAKvD;AAED;;;;;;;GAOG;AACH,qBAAa,gCAAiC,SAAQ,KAAK;gBAC9C,QAAQ,EAAE,MAAM;CAI5B;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,mBAAmB,GAAG,gBAAgB,GAAG,QAAQ,GAAG,wBAAw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AAI,CAWd,CAAC"}
@@ -15,9 +15,9 @@ import { assert_row } from '../db/assert_row.js';
15
15
  import { columns_sql, qualify_columns } from '../db/sql_columns.js';
16
16
  import { ROLE_GRANT_OFFER_COLUMNS, role_grant_offer_expr, ROLE_GRANT_OFFER_SCOPE_KIND_GLOBAL_TOKEN, ROLE_GRANT_OFFER_SCOPE_SENTINEL_UUID, ROLE_GRANT_OFFER_WITH_GRANTOR_SELECT } from './role_grant_offer_ddl.js';
17
17
  import { query_create_role_grant, query_role_grant_by_id } from './role_grant_queries.js';
18
- import { offer_pending_predicate, role_grant_active_sql } from './role_grant_sql.js';
18
+ import { offer_pending_predicate, offer_rows_locked_in_id_order, role_grant_active_sql } from './role_grant_sql.js';
19
19
  import { query_audit_log } from './audit_log_queries.js';
20
- import { query_account_lock_live_many } from './account_queries.js';
20
+ import { query_account_lock_for_offer_accept, query_account_lock_live_many } from './account_queries.js';
21
21
  import { is_builtin_role, ROLE_ADMIN, ROLE_KEEPER } from './role_schema.js';
22
22
  /**
23
23
  * Error thrown by offer-lifecycle queries when the offer is in a non-pending
@@ -114,12 +114,16 @@ export class RoleGrantOfferActorAccountMismatchError extends Error {
114
114
  }
115
115
  }
116
116
  /**
117
- * Error thrown by `query_role_grant_offer_create` when the recipient is not an
118
- * active account: `to_account_id` names no account, a soft-deleted one, or one
119
- * with no active actor. A deleted recipient and one that never existed are the
120
- * one refusal, so a caller learns nothing from it that a missing id wouldn't
121
- * tell; the handler answers it as `role_grant_assign` answers the same
122
- * recipient. Twin of the Rust `RoleGrantOfferError::RecipientNotActive`.
117
+ * Error thrown when the recipient is not an active account.
118
+ *
119
+ * By `query_role_grant_offer_create`: `to_account_id` names no account, a
120
+ * soft-deleted one, or one with no active actor. A deleted recipient and one
121
+ * that never existed are the one refusal, so a caller learns nothing from it
122
+ * that a missing id wouldn't tell; the handler answers it as
123
+ * `role_grant_assign` answers the same recipient. By `query_accept_offer`: the
124
+ * accepting account — the caller — was deleted or purged after its credential
125
+ * was read, and its handler answers the dead credential. Twin of the Rust
126
+ * `RoleGrantOfferError::RecipientNotActive`.
123
127
  */
124
128
  export class RoleGrantOfferRecipientNotActiveError extends Error {
125
129
  constructor() {
@@ -354,8 +358,11 @@ export const query_role_grant_offer_history_for_account = async (deps, account_i
354
358
  * caller's `role_grant_offer_expire` audit inserts — committed together, or
355
359
  * rolled back together so the next sweep retries. Concurrent sweeps claim
356
360
  * disjoint rows: a row another sweep has stamped but not committed blocks on
357
- * its row lock, then fails the re-checked `expire_audited_at IS NULL`.
358
- * `cleanup_expired_role_grant_offers` is the caller.
361
+ * its row lock, then fails the re-checked `expire_audited_at IS NULL`. The
362
+ * rows are locked in id order (`offer_rows_locked_in_id_order`), as every
363
+ * multi-row offer write takes them, so a sweep and a delete, purge, revoke or
364
+ * accept over the same expired offers never wait on each other in opposite
365
+ * orders. `cleanup_expired_role_grant_offers` is the caller.
359
366
  *
360
367
  * @mutates `role_grant_offer` rows - stamps `expire_audited_at` on each claimed row
361
368
  */
@@ -363,9 +370,7 @@ export const query_role_grant_offer_sweep_expired = async (deps) => {
363
370
  return deps.db.query(`WITH claimed AS (
364
371
  UPDATE role_grant_offer
365
372
  SET expire_audited_at = NOW()
366
- WHERE ${offer_pending_predicate('')}
367
- AND expires_at <= NOW()
368
- AND expire_audited_at IS NULL
373
+ WHERE ${offer_rows_locked_in_id_order('', `${offer_pending_predicate('')} AND expires_at <= NOW() AND expire_audited_at IS NULL`)}
369
374
  -- raw columns; the outer select formats them
370
375
  RETURNING ${columns_sql(ROLE_GRANT_OFFER_COLUMNS)}
371
376
  )
@@ -378,14 +383,14 @@ export const query_role_grant_offer_sweep_expired = async (deps) => {
378
383
  * actor of an active account — the authority a builtin-role offer needs at the
379
384
  * moment its grant is minted.
380
385
  *
381
- * A locking read: `FOR SHARE OF rg` takes a share lock on the grant row that
382
- * admits, so a concurrent revoke (an `UPDATE` of that row) is strictly ordered
383
- * against this accept — it either commits first, and the recheck of the locked
384
- * row sees `revoked_at` set and excludes it, or it waits for this transaction
385
- * to commit the grant it authorized. A plain `EXISTS` could read the grant as
386
- * active while a revoke commits in between. The actor and account tombstones
387
- * are read but not locked — ordering a delete racing an accept isn't worth
388
- * locking two more tables. Twin of the Rust `grantor_holds_global_admin`.
386
+ * An unlocked read, run after `query_account_lock_for_offer_accept` has taken
387
+ * the grantor's account row `FOR SHARE` in the accept's transaction: every
388
+ * write that ends a grantor's global `admin` takes that row first — a revoke of
389
+ * the grant through `query_account_lock_for_revoke`, a delete through its write
390
+ * of the row, a purge through `query_account_lock_admins_for_purge` and
391
+ * `query_account_lock_for_purge` — so one that committed first is
392
+ * seen here (each statement reads afresh), and one that came later waits for
393
+ * the accept to commit. Twin of the Rust `grantor_holds_global_admin`.
389
394
  */
390
395
  const query_grantor_holds_global_admin = async (deps, grantor_actor_id) => {
391
396
  const row = await deps.db.query_one(`SELECT 1 AS held FROM role_grant rg
@@ -397,8 +402,7 @@ const query_grantor_holds_global_admin = async (deps, grantor_actor_id) => {
397
402
  AND ${role_grant_active_sql('rg')}
398
403
  AND act.deleted_at IS NULL
399
404
  AND a.deleted_at IS NULL
400
- LIMIT 1
401
- FOR SHARE OF rg`, [grantor_actor_id, ROLE_ADMIN]);
405
+ LIMIT 1`, [grantor_actor_id, ROLE_ADMIN]);
402
406
  return row != null;
403
407
  };
404
408
  /**
@@ -414,9 +418,29 @@ const query_grantor_holds_global_admin = async (deps, grantor_actor_id) => {
414
418
  * creating a duplicate or throwing — while that grant is still held. A grant
415
419
  * revoked since the accept, or gone, makes the offer terminal.
416
420
  *
421
+ * Lock order — accounts, then offers, then the grant: the recipient's account
422
+ * row (and, for an unscoped `admin` offer, the grantor's) in id order
423
+ * (`query_account_lock_for_offer_accept`), then the offer and the pending
424
+ * siblings it supersedes in one id-ordered claim, then the grant insert. The
425
+ * accounts first, as every removal of either account takes them first, so a
426
+ * removal and an accept never meet at the offers, the actor, or a grant a
427
+ * purge's cascade reaches; two accepts by one recipient take turns. The
428
+ * offers in id order, as every transaction that writes several offer rows
429
+ * locks them all first in one id-ordered statement (a delete, a purge, a
430
+ * revoke, the expiry sweep). The grantor's authority is read unlocked after
431
+ * the grantor's account lock — the invariant it rests on: every write that
432
+ * ends a grantor's global `admin` takes the grantor's account row first (a
433
+ * revoke of the grant through `query_account_lock_for_revoke`, whether or not
434
+ * its last-admin guard ran; a delete through its write of the row; a purge
435
+ * through `query_account_lock_admins_for_purge` and
436
+ * `query_account_lock_for_purge`; the DB browser's delete, which takes none of
437
+ * them, excepted).
438
+ *
417
439
  * Error map:
418
440
  * - `RoleGrantOfferNotFoundError` — offer does not exist, or belongs to a
419
441
  * different recipient (IDOR guard). The offer row is untouched.
442
+ * - `RoleGrantOfferRecipientNotActiveError` — the recipient's account was
443
+ * deleted or purged since the caller's credential was read.
420
444
  * - `RoleGrantOfferAlreadyTerminalError` — offer is declined, retracted, or
421
445
  * superseded; or accepted, and its grant revoked, gone, or bound to another
422
446
  * actor.
@@ -424,8 +448,8 @@ const query_grantor_holds_global_admin = async (deps, grantor_actor_id) => {
424
448
  * - `RoleGrantOfferActorMismatchError` — actor-targeted offer, different actor.
425
449
  * - `RoleGrantOfferBuiltinRefusedError` — a builtin-role offer that must not
426
450
  * mint: `keeper` at all, a builtin bound to a scope, or one whose grantor no
427
- * longer holds an active global `admin` (read under `FOR SHARE`). The offer
428
- * stays pending.
451
+ * longer holds an active global `admin` (read under the grantor's account
452
+ * lock). The offer stays pending.
429
453
  *
430
454
  * Sibling supersede is what closes the "accept a pre-revoke sibling offer
431
455
  * to bypass a revoke" path: once A is accepted, B/C/... can no longer be
@@ -436,6 +460,7 @@ const query_grantor_holds_global_admin = async (deps, grantor_actor_id) => {
436
460
  * @mutates `role_grant_offer` siblings - stamps `superseded_at` on every other pending offer for the tuple
437
461
  * @mutates `audit_log` table - emits `role_grant_offer_accept` + `role_grant_create` + one `role_grant_offer_supersede` per sibling
438
462
  * @throws RoleGrantOfferNotFoundError if the offer is missing or belongs to another recipient
463
+ * @throws RoleGrantOfferRecipientNotActiveError if the recipient's account is deleted or gone
439
464
  * @throws RoleGrantOfferAlreadyTerminalError if the offer is declined, retracted, or superseded, or accepted with its grant revoked, gone, or bound to another actor
440
465
  * @throws RoleGrantOfferExpiredError if the offer is pending but past `expires_at`
441
466
  * @throws RoleGrantOfferActorMismatchError if the offer is actor-targeted to a different actor
@@ -444,29 +469,57 @@ const query_grantor_holds_global_admin = async (deps, grantor_actor_id) => {
444
469
  */
445
470
  export const query_accept_offer = async (deps, input) => {
446
471
  const { offer_id, to_account_id, actor_id, ip } = input;
447
- // Claim the offer with a row-level lock. Subsequent concurrent callers
448
- // block on the lock until this transaction commits/rolls back; after commit
449
- // they see the new state (accepted or terminal) and branch idempotently.
450
- // We defer writing `accepted_at` until the role_grant row exists — the
451
- // `role_grant_offer_role_grant_iff_accepted` CHECK constraint demands both be set
452
- // (or neither) at row-visibility time.
472
+ // The grantor, role and scope are written once with the offer and never
473
+ // updated, so they are read without a lock: they name the rows to lock.
474
+ // Everything the claim checks is checked on the claimed row.
475
+ const head = await deps.db.query_one(`SELECT o.from_actor_id, o.role, o.scope_id, grantor.account_id AS from_account_id
476
+ FROM role_grant_offer o
477
+ JOIN actor grantor ON grantor.id = o.from_actor_id
478
+ WHERE o.id = $1 AND o.to_account_id = $2`, [offer_id, to_account_id]);
479
+ if (!head) {
480
+ throw new RoleGrantOfferNotFoundError(offer_id);
481
+ }
482
+ // An unscoped `admin` offer's grantor must still hold a global `admin` when
483
+ // the grant is minted.
484
+ const needs_grantor_admin = head.role === ROLE_ADMIN && head.scope_id === null;
485
+ if (!(await query_account_lock_for_offer_accept(deps, to_account_id, needs_grantor_admin ? head.from_account_id : null))) {
486
+ throw new RoleGrantOfferRecipientNotActiveError();
487
+ }
488
+ const grantor_holds_admin = needs_grantor_admin
489
+ ? await query_grantor_holds_global_admin(deps, head.from_actor_id)
490
+ : null;
491
+ // Claim the offer and every pending sibling it may supersede — one
492
+ // statement, in id order. A concurrent caller on any of these rows blocks
493
+ // until this transaction ends, then sees the new state. No sibling can be
494
+ // added meanwhile: an offer to the recipient takes its account row, which
495
+ // this transaction holds. We defer writing `accepted_at` until the
496
+ // role_grant row exists — the `role_grant_offer_role_grant_iff_accepted`
497
+ // CHECK constraint demands both be set (or neither) at row-visibility time.
453
498
  //
454
- // Trailing `expires_at > NOW() AS still_valid` rides on the FOR UPDATE row
455
- // so the expiry branch below compares the **raw** column on Postgres' clock
456
- // — the projected `expires_at` is floored to the second, so comparing it in
499
+ // Trailing `expires_at > NOW() AS still_valid` rides on the locked row so
500
+ // the expiry branch below compares the **raw** column on Postgres' clock —
501
+ // the projected `expires_at` is floored to the second, so comparing it in
457
502
  // JS would report expiry up to a second early. Twin of the Rust
458
503
  // `query_accept_offer`'s `o.expires_at > NOW() AS still_valid`.
459
- const locked_row = await deps.db.query_one(`SELECT ${columns_sql(ROLE_GRANT_OFFER_COLUMNS, role_grant_offer_expr(''))},
460
- role_grant_offer.expires_at > NOW() AS still_valid
461
- FROM role_grant_offer
462
- WHERE id = $1 AND to_account_id = $2
463
- FOR UPDATE`, [offer_id, to_account_id]);
504
+ const claimed = await deps.db.query(`SELECT ${qualify_columns(ROLE_GRANT_OFFER_COLUMNS, 'o', role_grant_offer_expr('o'))},
505
+ o.expires_at > NOW() AS still_valid,
506
+ grantor.account_id AS from_account_id
507
+ FROM role_grant_offer o
508
+ JOIN actor grantor ON grantor.id = o.from_actor_id
509
+ WHERE o.to_account_id = $2
510
+ AND (o.id = $1
511
+ OR (o.role = $3 AND o.scope_id IS NOT DISTINCT FROM $4
512
+ AND ${offer_pending_predicate('o')}))
513
+ ORDER BY o.id
514
+ FOR UPDATE OF o`, [offer_id, to_account_id, head.role, head.scope_id]);
515
+ const locked_row = claimed.find((row) => row.id === offer_id);
464
516
  if (!locked_row) {
465
517
  throw new RoleGrantOfferNotFoundError(offer_id);
466
518
  }
467
- // `still_valid` is the comparison result, not a column of the offer — split
468
- // it off so `locked` stays exactly `ROLE_GRANT_OFFER_COLUMNS`.
469
- const { still_valid, ...locked } = locked_row;
519
+ const sibling_ids = claimed.filter((row) => row.id !== offer_id).map((row) => row.id);
520
+ // `still_valid` and `from_account_id` are not columns of the offer — split
521
+ // them off so `locked` stays exactly `ROLE_GRANT_OFFER_COLUMNS`.
522
+ const { still_valid, from_account_id, ...locked } = locked_row;
470
523
  if (locked.accepted_at) {
471
524
  // Already accepted (a replay, or a race winner already committed);
472
525
  // return the pre-existing role_grant.
@@ -488,6 +541,7 @@ export const query_accept_offer = async (deps, input) => {
488
541
  return {
489
542
  role_grant,
490
543
  offer: locked,
544
+ from_account_id,
491
545
  created: false,
492
546
  superseded_offers: [],
493
547
  audit_events: []
@@ -498,7 +552,7 @@ export const query_accept_offer = async (deps, input) => {
498
552
  }
499
553
  // Expiry check AFTER the accepted-path: a validly-accepted offer past its
500
554
  // expires_at still returns the role_grant idempotently. Only pending offers
501
- // past expiry reach this branch. `still_valid` rode on the FOR UPDATE row
555
+ // past expiry reach this branch. `still_valid` rode on the claimed row
502
556
  // above, so the comparison stays on the raw column and Postgres' clock.
503
557
  if (!still_valid) {
504
558
  throw new RoleGrantOfferExpiredError(offer_id);
@@ -538,7 +592,9 @@ export const query_accept_offer = async (deps, input) => {
538
592
  // Builtin roles are global-only.
539
593
  refusal = 'scoped';
540
594
  }
541
- else if (!(await query_grantor_holds_global_admin(deps, locked.from_actor_id))) {
595
+ else if (grantor_holds_admin !== true) {
596
+ // read under the grantor's account lock before the claim, on the same
597
+ // immutable grantor the claimed row carries
542
598
  refusal = 'grantor_not_authorized';
543
599
  }
544
600
  if (refusal !== null) {
@@ -571,23 +627,22 @@ export const query_accept_offer = async (deps, input) => {
571
627
  WHERE id = $1
572
628
  RETURNING ${columns_sql(ROLE_GRANT_OFFER_COLUMNS, role_grant_offer_expr(''))}`, [locked.id, role_grant.id]);
573
629
  const offer = assert_row(offer_accepted, 'mark offer accepted');
574
- // Supersede sibling pending offers for the same (to_account, role, scope).
575
- // Forecloses the "accept this other sibling later to get the role back
576
- // after a revoke" path — any pending offer for this tuple at accept time
577
- // is obsoleted by the accept. CTE joins `actor` to surface each sibling's
578
- // grantor `account_id` for the caller's notification fan-out.
579
- const superseded = await deps.db.query(`WITH updated AS (
580
- UPDATE role_grant_offer
581
- SET superseded_at = NOW()
582
- WHERE to_account_id = $1
583
- AND role = $2
584
- AND scope_id IS NOT DISTINCT FROM $3
585
- AND id <> $4
586
- AND ${offer_pending_predicate('')}
587
- -- raw columns; the outer grantor select formats them
588
- RETURNING ${columns_sql(ROLE_GRANT_OFFER_COLUMNS)}
589
- )
590
- ${ROLE_GRANT_OFFER_WITH_GRANTOR_SELECT}`, [to_account_id, offer.role, offer.scope_id, offer.id]);
630
+ // Supersede the sibling pending offers for the same (to_account, role,
631
+ // scope), the rows the claim locked. Forecloses the "accept this other
632
+ // sibling later to get the role back after a revoke" path — any pending
633
+ // offer for this tuple at accept time is obsoleted by the accept. CTE joins
634
+ // `actor` to surface each sibling's grantor `account_id` for the caller's
635
+ // notification fan-out.
636
+ const superseded = sibling_ids.length === 0
637
+ ? []
638
+ : await deps.db.query(`WITH updated AS (
639
+ UPDATE role_grant_offer
640
+ SET superseded_at = NOW()
641
+ WHERE id = ANY($1) AND ${offer_pending_predicate('')}
642
+ -- raw columns; the outer grantor select formats them
643
+ RETURNING ${columns_sql(ROLE_GRANT_OFFER_COLUMNS)}
644
+ )
645
+ ${ROLE_GRANT_OFFER_WITH_GRANTOR_SELECT}`, [sibling_ids]);
591
646
  // Emit audit events in-transaction (atomic with the role_grant insert).
592
647
  // The `RETURNING` after the SET guarantees `offer.resulting_role_grant_id === role_grant.id`.
593
648
  // Accept binds the actor deterministically — populate both target
@@ -650,6 +705,7 @@ export const query_accept_offer = async (deps, input) => {
650
705
  return {
651
706
  role_grant,
652
707
  offer,
708
+ from_account_id,
653
709
  created: true,
654
710
  superseded_offers: superseded,
655
711
  audit_events: [offer_accept_event, role_grant_create_event, ...supersede_events]
@@ -665,8 +721,11 @@ export const query_accept_offer = async (deps, input) => {
665
721
  * (`account_delete` / `account_purge`, every actor of the account) end the
666
722
  * grantor's outgoing pending offers in the same transaction. Each row carries
667
723
  * the grantor's `from_account_id`, as every supersede cascade's does; the
668
- * caller emits a `role_grant_offer_supersede` audit event per entry, and the
669
- * revoke caller also sends the supersede notification. Twin of the Rust
724
+ * caller emits a `role_grant_offer_supersede` audit event per entry and
725
+ * queues its notifications (`queue_supersede_notifications`). The rows are
726
+ * taken in id order; a caller that writes other offers too locks them all
727
+ * first (`query_role_grant_offer_lock_for_account_removal`,
728
+ * `query_role_grant_offer_lock_for_revoke`). Twin of the Rust
670
729
  * `query_role_grant_offer_supersede_outgoing`.
671
730
  *
672
731
  * @param deps - query dependencies
@@ -680,8 +739,7 @@ export const query_role_grant_offer_supersede_outgoing = async (deps, from_actor
680
739
  return deps.db.query(`WITH updated AS (
681
740
  UPDATE role_grant_offer
682
741
  SET superseded_at = NOW()
683
- WHERE from_actor_id = ANY($1)
684
- AND ${offer_pending_predicate('')}
742
+ WHERE ${offer_rows_locked_in_id_order('', `from_actor_id = ANY($1) AND ${offer_pending_predicate('')}`)}
685
743
  -- raw columns; the outer grantor select formats them
686
744
  RETURNING ${columns_sql(ROLE_GRANT_OFFER_COLUMNS)}
687
745
  )
@@ -689,7 +747,7 @@ export const query_role_grant_offer_supersede_outgoing = async (deps, from_actor
689
747
  };
690
748
  /**
691
749
  * Supersede every pending offer **made to** `to_account_id` — the
692
- * recipient-side cascade of an account delete.
750
+ * recipient-side cascade of an account delete or purge.
693
751
  *
694
752
  * An undelete restores the account, so an offer left pending through the
695
753
  * delete would come back with it and could then be accepted; superseding it
@@ -697,8 +755,11 @@ export const query_role_grant_offer_supersede_outgoing = async (deps, from_actor
697
755
  * `to_account_id` alone covers the actor-addressed offers too: an offer's
698
756
  * `to_actor_id` is bound to its `to_account_id` at create. Each row carries
699
757
  * the grantor's `from_account_id`, as every supersede cascade's does; the
700
- * caller emits a `role_grant_offer_supersede` audit event per entry. Twin of
701
- * the Rust `query_role_grant_offer_supersede_incoming`.
758
+ * caller emits a `role_grant_offer_supersede` audit event per entry and
759
+ * queues its notifications (`queue_supersede_notifications`). The rows are
760
+ * taken in id order, after the caller's
761
+ * `query_role_grant_offer_lock_for_account_removal`. Twin of the Rust
762
+ * `query_role_grant_offer_supersede_incoming`.
702
763
  *
703
764
  * @param deps - query dependencies
704
765
  * @param to_account_id - the recipient account whose pending offers end
@@ -709,10 +770,64 @@ export const query_role_grant_offer_supersede_incoming = async (deps, to_account
709
770
  return deps.db.query(`WITH updated AS (
710
771
  UPDATE role_grant_offer
711
772
  SET superseded_at = NOW()
712
- WHERE to_account_id = $1
713
- AND ${offer_pending_predicate('')}
773
+ WHERE ${offer_rows_locked_in_id_order('', `to_account_id = $1 AND ${offer_pending_predicate('')}`)}
714
774
  -- raw columns; the outer grantor select formats them
715
775
  RETURNING ${columns_sql(ROLE_GRANT_OFFER_COLUMNS)}
716
776
  )
717
777
  ${ROLE_GRANT_OFFER_WITH_GRANTOR_SELECT}`, [to_account_id]);
718
778
  };
779
+ /**
780
+ * Lock every pending offer an account removal supersedes — the ones its actors
781
+ * made and the ones made to it — in one statement, in id order.
782
+ *
783
+ * A delete or a purge writes those offers in two statements, the outgoing
784
+ * then the incoming; taken that way, each could hold rows another writer of
785
+ * both sets (a revoke of the account's grant, the expiry sweep) waits on while
786
+ * waiting on rows that writer holds. Locked together first, in the order every
787
+ * multi-row offer write takes its rows, the two supersedes then write rows
788
+ * this transaction already holds. No offer to or from the account can be made
789
+ * meanwhile: an offer create takes both parties' account rows, which the
790
+ * removal has written or locked. Twin of the Rust
791
+ * `query_role_grant_offer_lock_for_account_removal`.
792
+ *
793
+ * @param deps - query dependencies (must be the removal's transaction)
794
+ * @param to_account_id - the removed account
795
+ * @param from_actor_ids - the removed account's actors
796
+ * @mutates `role_grant_offer` rows - row-locks every pending offer to the account or from its actors
797
+ */
798
+ export const query_role_grant_offer_lock_for_account_removal = async (deps, to_account_id, from_actor_ids) => {
799
+ await deps.db.query(`SELECT id FROM role_grant_offer
800
+ WHERE (to_account_id = $1 OR from_actor_id = ANY($2))
801
+ AND ${offer_pending_predicate('')}
802
+ ORDER BY id
803
+ FOR UPDATE`, [to_account_id, from_actor_ids]);
804
+ };
805
+ /**
806
+ * Lock every pending offer `role_grant_revoke` supersedes — the revokee
807
+ * account's incoming offers of the revoked grant's role and scope, and every
808
+ * offer the revokee's actor made — in one statement, in id order.
809
+ *
810
+ * Taken after the revokee's account row (`query_account_lock_for_revoke`),
811
+ * which keeps any new offer to or from the account out, and before the grant's
812
+ * update: an accept claims its offers before it inserts its grant (whose unique
813
+ * slot waits on a revoke's uncommitted update of the same grant), so a revoke
814
+ * updating the grant first and then reaching the offers the accept holds would
815
+ * close a cycle. Then the revoke's two supersedes write rows it already holds,
816
+ * in the order every multi-row offer write takes its rows. Twin of the Rust
817
+ * `query_role_grant_offer_lock_for_revoke`.
818
+ *
819
+ * @param deps - query dependencies (must be the revoke's transaction)
820
+ * @param actor_id - the revokee actor
821
+ * @param role - the revoked grant's role
822
+ * @param scope_id - the revoked grant's scope, `null` for global
823
+ * @mutates `role_grant_offer` rows - row-locks the pending offers the revoke supersedes
824
+ */
825
+ export const query_role_grant_offer_lock_for_revoke = async (deps, actor_id, role, scope_id) => {
826
+ await deps.db.query(`SELECT id FROM role_grant_offer
827
+ WHERE ((to_account_id = (SELECT account_id FROM actor WHERE id = $1)
828
+ AND role = $2 AND scope_id IS NOT DISTINCT FROM $3)
829
+ OR from_actor_id = $1)
830
+ AND ${offer_pending_predicate('')}
831
+ ORDER BY id
832
+ FOR UPDATE`, [actor_id, role, scope_id]);
833
+ };
@@ -59,7 +59,7 @@ export const RoleGrantOfferJson = meta(object({
59
59
  description: 'ISO timestamp when the grantor retracted the offer.'
60
60
  }),
61
61
  superseded_at: meta(nullable(Timestamp), {
62
- description: 'ISO timestamp when this offer was obsoleted by a sibling accept or by revoke of the resulting role_grant.'
62
+ description: 'ISO timestamp when a cascade ended this pending offer: a sibling accept, a revoke of the recipient’s grant of its role and scope, an admin revoke of any grant of its grantor’s actor, the removal of either party’s account, or the teardown of its scope.'
63
63
  }),
64
64
  resulting_role_grant_id: meta(nullable(UuidSchema), {
65
65
  description: 'Role grant produced by accepting this offer. `null` until/unless accepted.'