@xtandard/permissions 0.1.0 → 0.2.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 (164) hide show
  1. package/README.md +5 -3
  2. package/dist/{better-auth-NO40ZqSM.mjs → better-auth-BEmX8qyz.mjs} +28 -8
  3. package/dist/better-auth-BEmX8qyz.mjs.map +1 -0
  4. package/dist/{better-auth-Bp9YVyQa.d.cts → better-auth-DQET1sXa.d.mts} +24 -5
  5. package/dist/{better-auth-DHyW5-yt.cjs → better-auth-MR7dBtpo.cjs} +28 -8
  6. package/dist/better-auth-MR7dBtpo.cjs.map +1 -0
  7. package/dist/{better-auth-NSXgt6ZU.d.mts → better-auth-vgRYgjYK.d.cts} +24 -5
  8. package/dist/cli.cjs +12 -6
  9. package/dist/cli.cjs.map +1 -1
  10. package/dist/cli.mjs +12 -6
  11. package/dist/cli.mjs.map +1 -1
  12. package/dist/{contract-BMiOmg2f.d.cts → contract-BAisPHBw.d.cts} +30 -2
  13. package/dist/{contract-Yc5AZuvv.mjs → contract-BganM0fx.mjs} +34 -2
  14. package/dist/contract-BganM0fx.mjs.map +1 -0
  15. package/dist/{contract-CPmJVoRx.cjs → contract-Brnu9XXo.cjs} +45 -1
  16. package/dist/contract-Brnu9XXo.cjs.map +1 -0
  17. package/dist/{contract-Dk6d2ylD.d.cts → contract-CXPMGuHk.d.cts} +18 -2
  18. package/dist/{contract-D32H1t0u.d.mts → contract-D6j-yrBL.d.mts} +30 -2
  19. package/dist/{contract-DUzgB-He.d.mts → contract-DhS23Pcp.d.mts} +18 -2
  20. package/dist/{create-fetch-handler-ojjpk1Iw.mjs → create-fetch-handler-B0twltQL.mjs} +43 -6
  21. package/dist/create-fetch-handler-B0twltQL.mjs.map +1 -0
  22. package/dist/{create-fetch-handler-BHDU4chu.d.mts → create-fetch-handler-B711wb64.d.mts} +4 -4
  23. package/dist/{create-fetch-handler-C-WyaRCR.cjs → create-fetch-handler-BHT4vSZs.cjs} +43 -6
  24. package/dist/create-fetch-handler-BHT4vSZs.cjs.map +1 -0
  25. package/dist/{create-fetch-handler-BtX64_rS.d.cts → create-fetch-handler-DxhvXuBA.d.cts} +4 -4
  26. package/dist/{elysia-shared-BUTFTeal.cjs → elysia-shared-BFcWzfc9.cjs} +3 -3
  27. package/dist/{elysia-shared-BUTFTeal.cjs.map → elysia-shared-BFcWzfc9.cjs.map} +1 -1
  28. package/dist/{elysia-shared-BM6cPoCU.mjs → elysia-shared-BwUYg0Ln.mjs} +3 -3
  29. package/dist/{elysia-shared-BM6cPoCU.mjs.map → elysia-shared-BwUYg0Ln.mjs.map} +1 -1
  30. package/dist/{elysia-shared-DtKViycb.d.cts → elysia-shared-C2LnDOj3.d.cts} +5 -5
  31. package/dist/{elysia-shared-g8zsb_pU.d.mts → elysia-shared-WuDr0jco.d.mts} +5 -5
  32. package/dist/{engine-bMoz3iW-.cjs → engine--C7zo-4M.cjs} +93 -13
  33. package/dist/engine--C7zo-4M.cjs.map +1 -0
  34. package/dist/{engine-CGGVDCqi.d.cts → engine-BTgwbHeO.d.cts} +49 -9
  35. package/dist/{engine-DpFIcbgh.d.mts → engine-C3xHfi3q.d.mts} +49 -9
  36. package/dist/{engine-Bufv0TbD.mjs → engine-CR75K253.mjs} +93 -13
  37. package/dist/engine-CR75K253.mjs.map +1 -0
  38. package/dist/entry-auth-better-auth.cjs +6 -3
  39. package/dist/entry-auth-better-auth.d.cts +4 -4
  40. package/dist/entry-auth-better-auth.d.mts +4 -4
  41. package/dist/entry-auth-better-auth.mjs +4 -4
  42. package/dist/entry-auth-jwt.cjs +6 -2
  43. package/dist/entry-auth-jwt.cjs.map +1 -1
  44. package/dist/entry-auth-jwt.d.cts +9 -3
  45. package/dist/entry-auth-jwt.d.mts +9 -3
  46. package/dist/entry-auth-jwt.mjs +4 -3
  47. package/dist/entry-auth-jwt.mjs.map +1 -1
  48. package/dist/entry-auth-session.cjs +6 -2
  49. package/dist/entry-auth-session.cjs.map +1 -1
  50. package/dist/entry-auth-session.d.cts +8 -3
  51. package/dist/entry-auth-session.d.mts +8 -3
  52. package/dist/entry-auth-session.mjs +4 -3
  53. package/dist/entry-auth-session.mjs.map +1 -1
  54. package/dist/entry-authorization-permissions.cjs +1 -1
  55. package/dist/entry-authorization-permissions.d.cts +1 -1
  56. package/dist/entry-authorization-permissions.d.mts +1 -1
  57. package/dist/entry-authorization-permissions.mjs +1 -1
  58. package/dist/entry-better-auth-client.d.cts +2 -2
  59. package/dist/entry-better-auth-client.d.mts +2 -2
  60. package/dist/entry-better-auth.cjs +1 -1
  61. package/dist/entry-better-auth.d.cts +2 -2
  62. package/dist/entry-better-auth.d.mts +2 -2
  63. package/dist/entry-better-auth.mjs +1 -1
  64. package/dist/entry-bridges-audit.d.cts +1 -1
  65. package/dist/entry-bridges-audit.d.mts +1 -1
  66. package/dist/entry-bridges-webhooks.d.cts +1 -1
  67. package/dist/entry-bridges-webhooks.d.mts +1 -1
  68. package/dist/entry-bun.cjs +2 -2
  69. package/dist/entry-bun.d.cts +4 -4
  70. package/dist/entry-bun.d.mts +4 -4
  71. package/dist/entry-bun.mjs +2 -2
  72. package/dist/entry-elysia.cjs +1 -1
  73. package/dist/entry-elysia.d.cts +4 -4
  74. package/dist/entry-elysia.d.mts +4 -4
  75. package/dist/entry-elysia.mjs +1 -1
  76. package/dist/entry-elysia2.cjs +1 -1
  77. package/dist/entry-elysia2.d.cts +4 -4
  78. package/dist/entry-elysia2.d.mts +4 -4
  79. package/dist/entry-elysia2.mjs +1 -1
  80. package/dist/entry-express.cjs +2 -2
  81. package/dist/entry-express.d.cts +4 -4
  82. package/dist/entry-express.d.mts +4 -4
  83. package/dist/entry-express.mjs +2 -2
  84. package/dist/entry-hono.cjs +2 -2
  85. package/dist/entry-hono.d.cts +4 -4
  86. package/dist/entry-hono.d.mts +4 -4
  87. package/dist/entry-hono.mjs +2 -2
  88. package/dist/entry-hooks-log.d.cts +1 -1
  89. package/dist/entry-hooks-log.d.mts +1 -1
  90. package/dist/entry-next.cjs +2 -2
  91. package/dist/entry-next.d.cts +5 -5
  92. package/dist/entry-next.d.mts +5 -5
  93. package/dist/entry-next.mjs +2 -2
  94. package/dist/entry-react.d.cts +2 -2
  95. package/dist/entry-react.d.mts +2 -2
  96. package/dist/{errors-bL3XQLfE.mjs → errors-CG_OLEEv.mjs} +12 -2
  97. package/dist/errors-CG_OLEEv.mjs.map +1 -0
  98. package/dist/{errors-vVYic8gz.cjs → errors-CjpymzFj.cjs} +17 -1
  99. package/dist/errors-CjpymzFj.cjs.map +1 -0
  100. package/dist/{guard-BOx5cnMP.mjs → guard-Bj8zk23F.mjs} +2 -2
  101. package/dist/{guard-BOx5cnMP.mjs.map → guard-Bj8zk23F.mjs.map} +1 -1
  102. package/dist/{guard-nwdOYe90.cjs → guard-DvaoUgjk.cjs} +2 -2
  103. package/dist/{guard-nwdOYe90.cjs.map → guard-DvaoUgjk.cjs.map} +1 -1
  104. package/dist/{guard-C3o7V14m.d.cts → guard-VEK0W8ug.d.cts} +4 -4
  105. package/dist/{guard-DCbTnqPz.d.mts → guard-k7A71SWC.d.mts} +4 -4
  106. package/dist/index.cjs +9 -6
  107. package/dist/index.d.cts +28 -10
  108. package/dist/index.d.mts +28 -10
  109. package/dist/index.mjs +7 -7
  110. package/dist/{kit-DMVBLBI9.d.mts → kit-51JtMxsn.d.mts} +8 -3
  111. package/dist/{kit-fzXHYb1l.mjs → kit-BM3uosfV.mjs} +23 -8
  112. package/dist/kit-BM3uosfV.mjs.map +1 -0
  113. package/dist/{kit-C7tepDB2.cjs → kit-BrqnCcDw.cjs} +28 -7
  114. package/dist/kit-BrqnCcDw.cjs.map +1 -0
  115. package/dist/{kit-qAROuhOI.d.cts → kit-DLF7DZrp.d.cts} +8 -3
  116. package/dist/{permissions-C9PjftY6.mjs → permissions-CeV6M3v7.mjs} +6 -3
  117. package/dist/permissions-CeV6M3v7.mjs.map +1 -0
  118. package/dist/{permissions-Cxri_P_k.cjs → permissions-DDEkHNvN.cjs} +6 -3
  119. package/dist/permissions-DDEkHNvN.cjs.map +1 -0
  120. package/dist/react-embed.js +1880 -1855
  121. package/dist/relationships-BLYEJ9tc.cjs.map +1 -1
  122. package/dist/relationships-BfLonEMI.mjs.map +1 -1
  123. package/dist/{routes-irNuuZqo.cjs → routes-B2LrYpT0.cjs} +15 -9
  124. package/dist/routes-B2LrYpT0.cjs.map +1 -0
  125. package/dist/{routes-DtRb3EO0.mjs → routes-Cx-kl4PY.mjs} +15 -9
  126. package/dist/routes-Cx-kl4PY.mjs.map +1 -0
  127. package/dist/{server-CJ7AIJpO.d.mts → server-Bn643UOy.d.mts} +4 -4
  128. package/dist/{server-C2F4H6bR.d.cts → server-YdH25OEA.d.cts} +4 -4
  129. package/dist/testing.cjs +1 -1
  130. package/dist/testing.d.cts +2 -2
  131. package/dist/testing.d.mts +2 -2
  132. package/dist/testing.mjs +1 -1
  133. package/dist/types-elysia2/auth-provider/contract.d.ts +28 -0
  134. package/dist/types-elysia2/auth-provider/kit.d.ts +5 -0
  135. package/dist/types-elysia2/engine.d.ts +49 -8
  136. package/dist/types-elysia2/errors.d.ts +8 -0
  137. package/dist/types-elysia2/schema.d.ts +16 -0
  138. package/dist/types-elysia2/server/routes.d.ts +16 -5
  139. package/dist/types-react/engine.d.ts +49 -8
  140. package/dist/types-react/errors.d.ts +8 -0
  141. package/dist/types-react/schema.d.ts +16 -0
  142. package/dist/types-react/ui/App.d.ts +6 -1
  143. package/dist/types-react/ui/components/perm-bits.d.ts +5 -1
  144. package/dist/types-react/ui/types.d.ts +11 -2
  145. package/dist/ui/assets/index-DdvxpphI.js +104 -0
  146. package/dist/ui/index.html +1 -1
  147. package/package.json +1 -1
  148. package/dist/better-auth-DHyW5-yt.cjs.map +0 -1
  149. package/dist/better-auth-NO40ZqSM.mjs.map +0 -1
  150. package/dist/contract-CPmJVoRx.cjs.map +0 -1
  151. package/dist/contract-Yc5AZuvv.mjs.map +0 -1
  152. package/dist/create-fetch-handler-C-WyaRCR.cjs.map +0 -1
  153. package/dist/create-fetch-handler-ojjpk1Iw.mjs.map +0 -1
  154. package/dist/engine-Bufv0TbD.mjs.map +0 -1
  155. package/dist/engine-bMoz3iW-.cjs.map +0 -1
  156. package/dist/errors-bL3XQLfE.mjs.map +0 -1
  157. package/dist/errors-vVYic8gz.cjs.map +0 -1
  158. package/dist/kit-C7tepDB2.cjs.map +0 -1
  159. package/dist/kit-fzXHYb1l.mjs.map +0 -1
  160. package/dist/permissions-C9PjftY6.mjs.map +0 -1
  161. package/dist/permissions-Cxri_P_k.cjs.map +0 -1
  162. package/dist/routes-DtRb3EO0.mjs.map +0 -1
  163. package/dist/routes-irNuuZqo.cjs.map +0 -1
  164. package/dist/ui/assets/index-uXGOtyuj.js +0 -104
@@ -1,6 +1,6 @@
1
1
  const require_chunk = require("./chunk-DakpK96I.cjs");
2
2
  const require_relationships = require("./relationships-BLYEJ9tc.cjs");
3
- const require_errors = require("./errors-vVYic8gz.cjs");
3
+ const require_errors = require("./errors-CjpymzFj.cjs");
4
4
  let _xtandard_kit_util_core = require("@xtandard/kit/util/core");
5
5
  let _xtandard_kit_util = require("@xtandard/kit/util");
6
6
  let _xtandard_kit_hooks = require("@xtandard/kit/hooks");
@@ -11,7 +11,8 @@ let _xtandard_kit_storage = require("@xtandard/kit/storage");
11
11
  *
12
12
  * Writes (grant, revoke, role assignment, subject records) go to the storage
13
13
  * under the `perm/` key root (ADR 0003) and fire the hooks. Checks load the
14
- * subject's stored role and grants (async, cached per subject), then evaluate
14
+ * subject's stored role and grants (async, cached per subject), resolve the
15
+ * effective role from the `roleSource` (ADR 0014), then evaluate
15
16
  * the catalog's rules **synchronously** with `@xtandard/lib/policy/permix`
16
17
  * (ADR 0005).
17
18
  *
@@ -73,6 +74,9 @@ function createPermissions(options) {
73
74
  const cacheEnabled = options.cache !== false;
74
75
  const cacheTtl = (options.cache ? options.cache.ttlMs : void 0) ?? 5e3;
75
76
  const cacheMax = (options.cache ? options.cache.max : void 0) ?? 1e4;
77
+ const roleSource = options.roleSource ?? "stored";
78
+ if (roleSource !== "stored" && roleSource !== "external") throw new TypeError(`createPermissions: roleSource must be "stored" or "external"`);
79
+ const lookupSubject = options.lookupSubject;
76
80
  const ids = (0, _xtandard_kit_util_core.createIdGenerator)({ format: "ulid-lower22" });
77
81
  const nowIso = () => new Date(now()).toISOString();
78
82
  const active = (grant) => grant.expiresAt === void 0 || grant.expiresAt === null || Date.parse(grant.expiresAt) > now();
@@ -109,6 +113,8 @@ function createPermissions(options) {
109
113
  return true;
110
114
  }
111
115
  const cache = /* @__PURE__ */ new Map();
116
+ /** `lookupSubject` results: same TTL, size bound and invalidation as {@link cache}. */
117
+ const lookups = /* @__PURE__ */ new Map();
112
118
  const generations = /* @__PURE__ */ new Map();
113
119
  const inflight = /* @__PURE__ */ new Map();
114
120
  let unwatch = null;
@@ -116,11 +122,13 @@ function createPermissions(options) {
116
122
  const invalidate = (subject) => {
117
123
  if (subject === void 0) {
118
124
  cache.clear();
125
+ lookups.clear();
119
126
  inflight.clear();
120
127
  for (const key of generations.keys()) generations.set(key, (generations.get(key) ?? 0) + 1);
121
128
  return;
122
129
  }
123
130
  cache.delete(subject);
131
+ lookups.delete(subject);
124
132
  inflight.delete(subject);
125
133
  generations.set(subject, (generations.get(subject) ?? 0) + 1);
126
134
  };
@@ -179,28 +187,84 @@ function createPermissions(options) {
179
187
  await storage.setItem(require_relationships.historyKey(entry.subject, at, id), full);
180
188
  }
181
189
  const storedRole = (record) => record?.role !== void 0 && catalog.isRole(record.role) && record.role !== catalog.guestRole ? record.role : null;
190
+ /** The provider's identity of `id` from `lookupSubject` (cached; `null` without one). */
191
+ function lookup(id) {
192
+ if (!lookupSubject) return Promise.resolve(null);
193
+ const cached = cacheEnabled ? lookups.get(id) : void 0;
194
+ if (cached && now() - cached.at < cacheTtl) return cached.identity;
195
+ const identity = Promise.resolve().then(() => lookupSubject(id)).then((found) => found && typeof found === "object" ? found : null);
196
+ if (cacheEnabled) {
197
+ lookups.delete(id);
198
+ lookups.set(id, {
199
+ identity,
200
+ at: now()
201
+ });
202
+ while (lookups.size > cacheMax) lookups.delete(lookups.keys().next().value);
203
+ identity.catch(() => {
204
+ if (lookups.get(id)?.identity === identity) lookups.delete(id);
205
+ });
206
+ }
207
+ return identity;
208
+ }
209
+ /** True when a raw provider role names a known, non-guest role (else `defaultRole` applies). */
210
+ const knownRole = (raw) => {
211
+ return (typeof raw === "string" ? raw.split(",").map((s) => s.trim()) : Array.isArray(raw) ? raw : []).some((c) => catalog.isRole(c) && c !== catalog.guestRole);
212
+ };
213
+ /**
214
+ * The effective role (ADR 0014). `external`: the provider's role (passed with the identity, else
215
+ * looked up), else `defaultRole`. `stored`: the stored role, else the same. The lookup runs only
216
+ * when the identity carries no `role` (`null` means "the provider says none": no lookup).
217
+ */
218
+ async function decideRole(id, record, identity, lookupFailed) {
219
+ if (roleSource === "stored") {
220
+ const stored = storedRole(record);
221
+ if (stored !== null) return {
222
+ role: stored,
223
+ source: "stored",
224
+ looked: null
225
+ };
226
+ }
227
+ let looked = null;
228
+ let raw = identity?.role;
229
+ if (raw === void 0) {
230
+ looked = lookupFailed ? await lookup(id).catch(lookupFailed) : await lookup(id);
231
+ raw = looked?.role;
232
+ }
233
+ return knownRole(raw) ? {
234
+ role: catalog.effectiveRole(raw),
235
+ source: "provider",
236
+ looked
237
+ } : {
238
+ role: catalog.defaultRole,
239
+ source: "default",
240
+ looked
241
+ };
242
+ }
182
243
  async function resolve(input) {
183
244
  if (input === null || input === void 0) return {
184
245
  id: null,
185
246
  role: catalog.guestRole,
247
+ roleSource: void 0,
186
248
  user: void 0,
187
249
  grants: []
188
250
  };
189
251
  const identity = typeof input === "string" ? { id: input } : input;
190
252
  const id = requireSubjectId(identity.id);
191
253
  const entry = await load(id);
192
- const role = storedRole(entry.record) ?? catalog.effectiveRole(identity.role ?? null);
193
- const name = identity.name ?? entry.record?.name;
194
- const email = identity.email ?? entry.record?.email;
254
+ const { role, source, looked } = await decideRole(id, entry.record, identity);
255
+ const name = identity.name ?? entry.record?.name ?? looked?.name;
256
+ const email = identity.email ?? entry.record?.email ?? looked?.email;
257
+ const attributes = identity.attributes ?? looked?.attributes;
195
258
  return {
196
259
  id,
197
260
  role,
261
+ roleSource: source,
198
262
  user: {
199
263
  id,
200
264
  role,
201
265
  ...name !== void 0 ? { name } : {},
202
266
  ...email !== void 0 ? { email } : {},
203
- ...identity.attributes !== void 0 ? { attributes: identity.attributes } : {}
267
+ ...attributes !== void 0 ? { attributes } : {}
204
268
  },
205
269
  grants: entry.grants.filter(active)
206
270
  };
@@ -217,6 +281,7 @@ function createPermissions(options) {
217
281
  path,
218
282
  subject: resolved.id,
219
283
  role: ability.role,
284
+ ...resolved.roleSource !== void 0 ? { roleSource: resolved.roleSource } : {},
220
285
  explanation
221
286
  };
222
287
  if (catalog.directGrants && resolved.id !== null && ability.permissions.has(path)) return {
@@ -361,6 +426,7 @@ function createPermissions(options) {
361
426
  });
362
427
  }
363
428
  async function setRole(input) {
429
+ if (roleSource === "external") throw new require_errors.ExternalRolesError();
364
430
  assertWritable("set role");
365
431
  const subject = requireSubjectId(input?.subject);
366
432
  const role = input.role;
@@ -469,12 +535,15 @@ function createPermissions(options) {
469
535
  async function getSubject(id, opts = {}) {
470
536
  const subject = requireSubjectId(id);
471
537
  const { record, grants } = await readSubject(subject);
538
+ const { role, source } = await decideRole(subject, record, null);
472
539
  const shown = opts.includeExpired ? grants : grants.filter(active);
473
540
  shown.sort((a, b) => a.permission < b.permission ? -1 : a.permission > b.permission ? 1 : 0);
474
541
  return {
475
542
  id: subject,
476
543
  record,
477
544
  role: storedRole(record),
545
+ effectiveRole: role,
546
+ roleSource: source,
478
547
  grants: shown
479
548
  };
480
549
  }
@@ -492,16 +561,25 @@ function createPermissions(options) {
492
561
  const record = await storage.getItem(key);
493
562
  if (record) records.set(parsed.subject, record);
494
563
  }));
495
- return [...new Set([...records.keys(), ...counts.keys()])].sort().map((id) => {
496
- const record = records.get(id);
564
+ const ids = [...new Set([...records.keys(), ...counts.keys()])].sort();
565
+ return Promise.all(ids.map(async (id) => {
566
+ const record = records.get(id) ?? null;
567
+ const { role, source, looked } = await decideRole(id, record, null, (error) => {
568
+ logger.warn(`lookupSubject("${id}") failed; listing its default role`, error);
569
+ return null;
570
+ });
571
+ const name = record?.name ?? looked?.name;
572
+ const email = record?.email ?? looked?.email;
497
573
  return {
498
574
  id,
499
575
  role: record?.role ?? null,
500
- ...record?.name !== void 0 ? { name: record.name } : {},
501
- ...record?.email !== void 0 ? { email: record.email } : {},
576
+ effectiveRole: role,
577
+ roleSource: source,
578
+ ...name !== void 0 ? { name } : {},
579
+ ...email !== void 0 ? { email } : {},
502
580
  grantCount: counts.get(id) ?? 0
503
581
  };
504
- });
582
+ }));
505
583
  }
506
584
  async function history(query = {}) {
507
585
  const parsed = (0, _xtandard_kit_util.parseInput)(require_relationships.historyQuerySchema, query);
@@ -539,6 +617,7 @@ function createPermissions(options) {
539
617
  catalog,
540
618
  storage,
541
619
  readonly,
620
+ roleSource,
542
621
  grant,
543
622
  revoke,
544
623
  list,
@@ -556,7 +635,8 @@ function createPermissions(options) {
556
635
  return {
557
636
  subject: {
558
637
  id: resolved.id,
559
- role: resolved.role
638
+ role: resolved.role,
639
+ ...resolved.roleSource !== void 0 ? { roleSource: resolved.roleSource } : {}
560
640
  },
561
641
  permissions
562
642
  };
@@ -584,4 +664,4 @@ Object.defineProperty(exports, "engine_exports", {
584
664
  }
585
665
  });
586
666
 
587
- //# sourceMappingURL=engine-bMoz3iW-.cjs.map
667
+ //# sourceMappingURL=engine--C7zo-4M.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine--C7zo-4M.cjs","names":["NoSubjectError","defaultHookErrorReporter","ReadonlyError","UnknownPermissionError","ROOT","parseKey","subjectKey","subjectGrantsPrefix","historyKey","grantInputSchema","ValidationError","grantKey","revokeInputSchema","ExternalRolesError","UnknownRoleError","setRoleInputSchema","upsertSubjectInputSchema","listQuerySchema","grantsPrefix","subjectsPrefix","historyQuerySchema","subjectHistoryPrefix","historyPrefix","createRelationships"],"sources":["../src/engine.ts"],"sourcesContent":["/**\n * The engine: `createPermissions({ catalog, storage, hooks, cache, now, readonly })`.\n *\n * Writes (grant, revoke, role assignment, subject records) go to the storage\n * under the `perm/` key root (ADR 0003) and fire the hooks. Checks load the\n * subject's stored role and grants (async, cached per subject), resolve the\n * effective role from the `roleSource` (ADR 0014), then evaluate\n * the catalog's rules **synchronously** with `@xtandard/lib/policy/permix`\n * (ADR 0005).\n *\n * @example\n * ```ts\n * import { createPermissions } from \"@xtandard/permissions\";\n * import { createMemoryStorage } from \"@xtandard/permissions/storage/memory\";\n * import { permissions } from \"./permissions.ts\"; // definePermissions(...)\n *\n * const perms = createPermissions({ catalog: permissions, storage: createMemoryStorage() });\n * await perms.grant({ subject: \"user_1\", permission: \"post:moderate\", actor: \"admin_1\" });\n * await perms.can({ id: \"user_1\", role: \"member\" }, \"post.publish\", post); // true\n * ```\n *\n * @module\n */\n\nimport { createIdGenerator } from \"@xtandard/kit/util/core\";\nimport { parseInput, ValidationError } from \"@xtandard/kit/util\";\nimport type { PermissionsCatalog, PermissionsSubject, SubjectIdentity } from \"./catalog.ts\";\n\nexport type { SubjectIdentity } from \"./catalog.ts\";\nimport {\n ExternalRolesError,\n NoSubjectError,\n ReadonlyError,\n UnknownPermissionError,\n UnknownRoleError,\n} from \"./errors.ts\";\nimport {\n defaultHookErrorReporter,\n normalizeHooks,\n runAfter,\n runBefore,\n type HookErrorReporter,\n type PermissionsHooksInput,\n} from \"./hooks/contract.ts\";\nimport {\n grantKey,\n grantsPrefix,\n historyKey,\n historyPrefix,\n parseKey,\n ROOT,\n subjectGrantsPrefix,\n subjectHistoryPrefix,\n subjectKey,\n subjectsPrefix,\n} from \"./keys.ts\";\nimport type { Ability, DataAtPath, Definition, RelationSchema, RulesPaths } from \"./policy.ts\";\nimport {\n createRelationships,\n type RelationshipsApi,\n type RelationsOptions,\n} from \"./relationships.ts\";\nimport {\n grantInputSchema,\n historyQuerySchema,\n listQuerySchema,\n revokeInputSchema,\n setRoleInputSchema,\n upsertSubjectInputSchema,\n type Actor,\n type CheckResult,\n type Grant,\n type GrantInput,\n type HistoryEntry,\n type HistoryPage,\n type HistoryQuery,\n type InstantInput,\n type ListQuery,\n type PermissionsSnapshot,\n type RevokeInput,\n type RoleSource,\n type RoleSourceMode,\n type SetRoleInput,\n type SubjectRecord,\n type UpsertSubjectInput,\n} from \"./schema.ts\";\nimport { isCompareAndSwap, isWatchable, type PermissionsStorage } from \"./storage/contract.ts\";\n\n// ─── Public types ───────────────────────────────────────────────────────────────────────────\n\n/** Options for {@link createPermissions}. */\nexport interface PermissionsOptions<\n D extends Definition = Definition,\n R extends string = string,\n P extends string = string,\n X = undefined,\n S extends RelationSchema = RelationSchema,\n> {\n /** The catalog from `definePermissions()`. */\n catalog: PermissionsCatalog<D, R, P, X, S>;\n /** Where grants, role assignments and history live (any `@xtandard/permissions/storage/*`). */\n storage: PermissionsStorage;\n /** `before` (veto) / `after` (side effects) hooks around grant, revoke and role writes. */\n hooks?: PermissionsHooksInput;\n /** Receives errors thrown by `after` hooks. Default: a prefixed `console.warn`. */\n onHookError?: HookErrorReporter;\n /**\n * Per-subject cache of the stored role and grants used by checks (and of `lookupSubject`\n * results). Entries expire after `ttlMs`\n * (default 5 000), are dropped on this engine's writes and, when the storage is watchable, on\n * every change it reports. `false` disables it (every check reads the storage).\n */\n cache?: false | { ttlMs?: number; max?: number };\n /** Clock (unix ms). Default `Date.now`. Decides grant expiry and every stored timestamp. */\n now?: () => number;\n /** When `true`, every write throws {@link ReadonlyError}. */\n readonly?: boolean;\n /** Where operational warnings go. Default: a prefixed `console.warn`. */\n logger?: { warn(message: string, error?: unknown): void };\n /** ReBAC tuning (the catalog's `relations`): `maxDepth` of checks and listing walks. */\n relations?: RelationsOptions;\n /**\n * Who owns roles (ADR 0014). `\"stored\"` (default, the 0.1 behaviour): a role set with\n * `setRole()` wins over the auth provider's. `\"external\"`: the auth provider owns roles; stored\n * roles are ignored and `setRole()` throws {@link ExternalRolesError}.\n */\n roleSource?: RoleSourceMode;\n /**\n * Resolve a subject by id when a check (or the panel) only has the id, not a session: returns\n * the auth provider's identity (`role`, `name`, `email`). Used in both role-source modes, only\n * when the identity passed carries no `role`; cached with the per-subject cache. Needed for the\n * panel to show the provider's role of subjects other than the caller. Every bundled auth\n * provider can supply one (`provider.lookupSubject`).\n */\n lookupSubject?: SubjectLookup | undefined;\n}\n\n/**\n * Looks a subject up by id in the auth provider (see {@link PermissionsOptions.lookupSubject}).\n * `null` = unknown subject (the catalog's `defaultRole` applies). A throw fails the check.\n */\nexport type SubjectLookup = (\n id: string,\n) => SubjectIdentity | null | undefined | Promise<SubjectIdentity | null | undefined>;\n\n/** A subject id, an identity, or `null` / `undefined` for a guest (no session). */\nexport type SubjectInput = string | SubjectIdentity | null | undefined;\n\n/** The app context argument of checks: required when the catalog's context type is. */\nexport type FactsArgs<X> = undefined extends X ? [facts?: { ctx?: X }] : [facts: { ctx: X }];\n\n/** The data a typed check at `Path` takes (`undefined` when the action takes none). */\nexport type PathData<D extends Definition, Path extends string> =\n DataAtPath<D, Path> extends readonly [] ? undefined : DataAtPath<D, Path>[0];\n\n/** The lib `Ability` of one subject, plus the engine's decision with reasons. */\nexport interface PermissionsAbility<\n D extends Definition = Definition,\n R extends string = string,\n P extends string = string,\n> extends Ability<D, R, P, PermissionsSubject> {\n /** The subject id, `null` for a guest. */\n subject: string | null;\n /** The non-expired grants the ability was built from (assignable or not). */\n grants: readonly Grant<P>[];\n /**\n * Decide `path` with reasons (see {@link CheckResult}). Takes an untyped path (e.g. from an HTTP\n * request); an unknown path is denied with `reason: \"unknown-path\"`. Throws `AsyncRuleError` when\n * the rule returns a Promise (the check denies).\n */\n check(path: string, data?: unknown): CheckResult<R, P>;\n /**\n * Like {@link check}, and also evaluates rules wrapped in the lib's `asyncRule()` (which the\n * synchronous `check` refuses with `AsyncRuleError`). The engine's `check()` / `can()` use it.\n */\n checkAsync(path: string, data?: unknown): Promise<CheckResult<R, P>>;\n}\n\n/** What `revoke()` returns. */\nexport interface RevokeResult<P extends string = string> {\n /** `false` when there was nothing to revoke. */\n removed: boolean;\n /** The revoked grant, when there was one. */\n grant: Grant<P> | null;\n}\n\n/** What `setRole()` returns. */\nexport interface SetRoleResult {\n /** The subject record after the write (`null` when none exists and the role was cleared). */\n record: SubjectRecord | null;\n /** `false` when the stored role already was the requested one. */\n changed: boolean;\n}\n\n/** A subject as stored: its record and grants. */\nexport interface SubjectView<R extends string = string, P extends string = string> {\n id: string;\n /** The stored record, `null` when the subject has none. */\n record: SubjectRecord | null;\n /**\n * The stored role assignment when it is a known, assignable role; else `null`. Ignored by checks\n * when the engine's `roleSource` is `\"external\"`.\n */\n role: R | null;\n /** The role checks use: see {@link roleSource} for what decided it. */\n effectiveRole: R;\n /** Which source decided {@link effectiveRole}. */\n roleSource: RoleSource;\n /** The subject's grants (non-expired unless `includeExpired`). */\n grants: Grant<P>[];\n}\n\n/** One row of `listSubjects()`. */\nexport interface SubjectSummary {\n id: string;\n /** The stored role assignment, if any (ignored by checks when `roleSource` is `\"external\"`). */\n role: string | null;\n /** The role checks use (the stored role, the auth provider's, or `defaultRole`). */\n effectiveRole: string;\n /** Which source decided {@link effectiveRole}. */\n roleSource: RoleSource;\n name?: string;\n email?: string;\n /** Stored grants (expired ones included). */\n grantCount: number;\n}\n\n/**\n * The engine. The relationship methods (`writeRelationship`, `checkRelation`, `listObjects`, …;\n * see {@link RelationshipsApi}) need the catalog's `relations`.\n */\nexport interface Permissions<\n D extends Definition = Definition,\n R extends string = string,\n P extends string = string,\n X = undefined,\n S extends RelationSchema = RelationSchema,\n> extends RelationshipsApi<S> {\n readonly catalog: PermissionsCatalog<D, R, P, X, S>;\n readonly storage: PermissionsStorage;\n readonly readonly: boolean;\n /** Who owns roles: `\"stored\"` (default) or `\"external\"` (the auth provider; ADR 0014). */\n readonly roleSource: RoleSourceMode;\n\n /**\n * Grant a permission. Idempotent: re-granting returns the existing grant with `created: false`\n * (no history entry, no hooks). An **expired** existing grant is replaced (`created: true`).\n *\n * @throws {NoSubjectError} empty subject. {@link UnknownPermissionError} not assignable.\n * `ValidationError` malformed input or `expiresAt` not in the future. {@link ReadonlyError}.\n */\n grant(input: GrantInput<P>): Promise<{ grant: Grant<P>; created: boolean }>;\n /** Revoke a permission. Idempotent (`removed: false` when absent). Validates like `grant`. */\n revoke(input: RevokeInput<P>): Promise<RevokeResult<P>>;\n /**\n * Grants by subject, by permission (a key scan with a suffix filter), both, or all. Expired\n * grants are left out unless `includeExpired`. Sorted by subject, then permission.\n */\n list(query?: ListQuery<P>): Promise<Grant<P>[]>;\n /**\n * Store a role assignment (overrides the auth provider's role); `role: null` clears it.\n *\n * @throws {UnknownRoleError} not one of `roles`, or the guest role. {@link ExternalRolesError}\n * when `roleSource` is `\"external\"` (the auth provider owns roles).\n */\n setRole(input: SetRoleInput<R>): Promise<SetRoleResult>;\n /**\n * A subject's stored record and grants (an empty view when nothing is stored), with its effective\n * role and the source that decided it (the auth provider's role comes from `lookupSubject`).\n */\n getSubject(id: string, options?: { includeExpired?: boolean }): Promise<SubjectView<R, P>>;\n /**\n * Every subject with a record or a grant, sorted by id, with effective roles. A failing\n * `lookupSubject` is logged and reported as `roleSource: \"default\"` (the list still loads).\n */\n listSubjects(): Promise<SubjectSummary[]>;\n /** Create or update a subject's display fields (`null` clears one). Keeps the stored role. */\n upsertSubject(input: UpsertSubjectInput): Promise<SubjectRecord>;\n /** The grant / revoke / role history, newest first, paginated by `cursor`. */\n history(query?: HistoryQuery): Promise<HistoryPage>;\n\n /**\n * A synchronous ability for many checks against one loaded snapshot of the subject. `null` /\n * `undefined` is a guest (the guest role, no grants).\n */\n ability(subject: SubjectInput, ...facts: FactsArgs<X>): Promise<PermissionsAbility<D, R, P>>;\n /** Decide one typed path with reasons. */\n check<Path extends RulesPaths<D>>(\n subject: SubjectInput,\n path: Path,\n data?: PathData<D, Path>,\n ...facts: FactsArgs<X>\n ): Promise<CheckResult<R, P>>;\n /** `(await check(...)).allowed`. */\n can<Path extends RulesPaths<D>>(\n subject: SubjectInput,\n path: Path,\n data?: PathData<D, Path>,\n ...facts: FactsArgs<X>\n ): Promise<boolean>;\n /** The effective role and active assignable permissions, for client hydration (ADR 0009). */\n snapshot(subject: SubjectInput): Promise<PermissionsSnapshot<R, P>>;\n\n /** Drop one subject's cache entry, or all of them. */\n invalidate(subject?: string): void;\n /** Stop watching the storage. */\n close(): Promise<void>;\n}\n\n/** Any engine, generics erased (for integrations: auth providers, servers, bridges). */\n// oxlint-disable-next-line typescript/no-explicit-any -- variance: the catalog's rules are contravariant in the role type.\nexport type AnyPermissions = Permissions<any, any, any, any, any>;\n\n// ─── Implementation ─────────────────────────────────────────────────────────────────────────\n\ninterface CacheEntry {\n record: SubjectRecord | null;\n grants: Grant[];\n loadedAt: number;\n}\n\nconst DEFAULT_HISTORY_LIMIT = 50;\nconst CAS_ATTEMPTS = 8;\n\nconst isNonEmptyString = (value: unknown): value is string =>\n typeof value === \"string\" && value.length > 0;\n\nfunction requireSubjectId(value: unknown): string {\n if (!isNonEmptyString(value)) throw new NoSubjectError();\n return value;\n}\n\nfunction toActor(actor: string | Actor | null | undefined): Actor | null {\n if (actor === undefined || actor === null) return null;\n return typeof actor === \"string\" ? { id: actor } : actor;\n}\n\nfunction toIso(at: InstantInput): string {\n const ms = typeof at === \"number\" ? at : typeof at === \"string\" ? Date.parse(at) : at.getTime();\n return new Date(ms).toISOString();\n}\n\n/** Last segment of a history key, decoded: the `{at}-{id}` sort token. */\nfunction historyToken(key: string): string {\n const segment = key.slice(key.lastIndexOf(\"/\") + 1);\n try {\n return `${decodeURIComponent(segment)}\\u0000${key}`;\n } catch {\n return `\\u0000${key}`;\n }\n}\n\n/**\n * Create the engine.\n *\n * @example\n * ```ts\n * const perms = createPermissions({ catalog, storage, cache: { ttlMs: 5_000 } });\n * const decision = await perms.check({ id: \"u1\", role: \"member\" }, \"post.publish\", post);\n * // { allowed, path, subject, role, reason: \"role-rule\" | \"denied-by-rule\" | …, explanation }\n * ```\n */\nexport function createPermissions<\n D extends Definition,\n R extends string,\n P extends string,\n X,\n S extends RelationSchema = RelationSchema,\n>(options: PermissionsOptions<D, R, P, X, S>): Permissions<D, R, P, X, S> {\n const { catalog, storage } = options;\n const now = options.now ?? Date.now;\n const readonly = options.readonly ?? false;\n const hooks = normalizeHooks(options.hooks);\n const onHookError = options.onHookError ?? defaultHookErrorReporter;\n const logger = options.logger ?? {\n warn: (message: string, error?: unknown) =>\n console.warn(`[@xtandard/permissions] ${message}`, ...(error === undefined ? [] : [error])),\n };\n const cacheEnabled = options.cache !== false;\n const cacheTtl = (options.cache ? options.cache.ttlMs : undefined) ?? 5_000;\n const cacheMax = (options.cache ? options.cache.max : undefined) ?? 10_000;\n const roleSource: RoleSourceMode = options.roleSource ?? \"stored\";\n if (roleSource !== \"stored\" && roleSource !== \"external\") {\n throw new TypeError(`createPermissions: roleSource must be \"stored\" or \"external\"`);\n }\n const lookupSubject = options.lookupSubject;\n const ids = createIdGenerator({ format: \"ulid-lower22\" });\n const nowIso = () => new Date(now()).toISOString();\n const active = (grant: Grant) =>\n grant.expiresAt === undefined ||\n grant.expiresAt === null ||\n Date.parse(grant.expiresAt) > now();\n\n const assertWritable = (operation: string) => {\n if (readonly) throw new ReadonlyError(operation);\n };\n const requirePermission = (permission: unknown): P => {\n if (!catalog.isAssignable(permission)) throw new UnknownPermissionError(permission);\n return permission;\n };\n\n // --- per-key in-process lock ----------------------------------------------------------------\n\n const locks = new Map<string, Promise<unknown>>();\n async function withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = locks.get(key) ?? Promise.resolve();\n let release!: () => void;\n const mine = new Promise<void>((resolve) => (release = resolve));\n const chained = prev.then(() => mine);\n locks.set(key, chained);\n await prev.catch(() => {});\n try {\n return await fn();\n } finally {\n release();\n if (locks.get(key) === chained) locks.delete(key);\n }\n }\n\n /** Write `next` if the key still holds `expected` (CAS), or unconditionally without CAS. */\n async function swap<T>(key: string, expected: T | null, next: T): Promise<boolean> {\n if (isCompareAndSwap(storage)) return storage.compareAndSwap({ key, expected, next });\n await storage.setItem(key, next);\n return true;\n }\n\n // --- subject cache --------------------------------------------------------------------------\n\n const cache = new Map<string, CacheEntry>();\n /** `lookupSubject` results: same TTL, size bound and invalidation as {@link cache}. */\n const lookups = new Map<string, { identity: Promise<SubjectIdentity | null>; at: number }>();\n const generations = new Map<string, number>();\n const inflight = new Map<string, Promise<CacheEntry>>();\n let unwatch: (() => void) | null = null;\n let watching: Promise<void> | null = null;\n\n const invalidate = (subject?: string) => {\n if (subject === undefined) {\n cache.clear();\n lookups.clear();\n inflight.clear();\n for (const key of generations.keys()) generations.set(key, (generations.get(key) ?? 0) + 1);\n return;\n }\n cache.delete(subject);\n lookups.delete(subject);\n inflight.delete(subject);\n generations.set(subject, (generations.get(subject) ?? 0) + 1);\n };\n\n const ensureWatch = () => {\n if (watching || !cacheEnabled || !isWatchable(storage)) return;\n watching = storage\n .watch(`${ROOT}/`, (event) => {\n const parsed = parseKey(event.key);\n if (parsed && parsed.area !== \"history\") invalidate(parsed.subject);\n })\n .then((off) => {\n unwatch = off;\n })\n .catch((error) => logger.warn(\"storage watch failed; relying on the cache TTL\", error));\n };\n\n async function readSubject(subject: string): Promise<Omit<CacheEntry, \"loadedAt\">> {\n const [record, keys] = await Promise.all([\n storage.getItem<SubjectRecord>(subjectKey(subject)),\n storage.getKeys(subjectGrantsPrefix(subject)),\n ]);\n const grants = (await Promise.all(keys.map((key) => storage.getItem<Grant>(key)))).filter(\n (grant): grant is Grant => grant !== null && typeof grant === \"object\",\n );\n return { record: record ?? null, grants };\n }\n\n function load(subject: string): Promise<CacheEntry> {\n if (!cacheEnabled) return readSubject(subject).then((e) => ({ ...e, loadedAt: now() }));\n ensureWatch();\n const cached = cache.get(subject);\n if (cached && now() - cached.loadedAt < cacheTtl) return Promise.resolve(cached);\n const pending = inflight.get(subject);\n if (pending) return pending;\n const generation = generations.get(subject) ?? 0;\n const promise = readSubject(subject)\n .then((data) => {\n const entry: CacheEntry = { ...data, loadedAt: now() };\n // A write (or a watch event) during the read makes it stale: serve it, don't keep it.\n if ((generations.get(subject) ?? 0) === generation) {\n cache.delete(subject);\n cache.set(subject, entry);\n while (cache.size > cacheMax) cache.delete(cache.keys().next().value as string);\n }\n return entry;\n })\n .finally(() => {\n if (inflight.get(subject) === promise) inflight.delete(subject);\n });\n inflight.set(subject, promise);\n return promise;\n }\n\n // --- history --------------------------------------------------------------------------------\n\n async function appendHistory(entry: Omit<HistoryEntry, \"id\" | \"at\">, at: string): Promise<void> {\n const id = ids.newId(\"hst\", Date.parse(at));\n const full = { id, at, ...entry } as HistoryEntry;\n await storage.setItem(historyKey(entry.subject, at, id), full);\n }\n\n // --- subject resolution ---------------------------------------------------------------------\n\n const storedRole = (record: SubjectRecord | null): R | null =>\n record?.role !== undefined && catalog.isRole(record.role) && record.role !== catalog.guestRole\n ? record.role\n : null;\n\n /** The provider's identity of `id` from `lookupSubject` (cached; `null` without one). */\n function lookup(id: string): Promise<SubjectIdentity | null> {\n if (!lookupSubject) return Promise.resolve(null);\n const cached = cacheEnabled ? lookups.get(id) : undefined;\n if (cached && now() - cached.at < cacheTtl) return cached.identity;\n const identity = Promise.resolve()\n .then(() => lookupSubject(id))\n .then((found) => (found && typeof found === \"object\" ? found : null));\n if (cacheEnabled) {\n // Kept until invalidated (a write, a watch event) or expired; a failure is not kept.\n lookups.delete(id);\n lookups.set(id, { identity, at: now() });\n while (lookups.size > cacheMax) lookups.delete(lookups.keys().next().value as string);\n identity.catch(() => {\n if (lookups.get(id)?.identity === identity) lookups.delete(id);\n });\n }\n return identity;\n }\n\n /** True when a raw provider role names a known, non-guest role (else `defaultRole` applies). */\n const knownRole = (raw: SubjectIdentity[\"role\"]): boolean => {\n const candidates =\n typeof raw === \"string\" ? raw.split(\",\").map((s) => s.trim()) : Array.isArray(raw) ? raw : [];\n return candidates.some((c) => catalog.isRole(c) && c !== catalog.guestRole);\n };\n\n interface RoleDecision {\n role: R;\n source: RoleSource;\n /** The `lookupSubject` result, when it was consulted. */\n looked: SubjectIdentity | null;\n }\n\n /**\n * The effective role (ADR 0014). `external`: the provider's role (passed with the identity, else\n * looked up), else `defaultRole`. `stored`: the stored role, else the same. The lookup runs only\n * when the identity carries no `role` (`null` means \"the provider says none\": no lookup).\n */\n async function decideRole(\n id: string,\n record: SubjectRecord | null,\n identity: SubjectIdentity | null,\n lookupFailed?: (error: unknown) => SubjectIdentity | null,\n ): Promise<RoleDecision> {\n if (roleSource === \"stored\") {\n const stored = storedRole(record);\n if (stored !== null) return { role: stored, source: \"stored\", looked: null };\n }\n let looked: SubjectIdentity | null = null;\n let raw = identity?.role;\n if (raw === undefined) {\n looked = lookupFailed ? await lookup(id).catch(lookupFailed) : await lookup(id);\n raw = looked?.role;\n }\n return knownRole(raw)\n ? { role: catalog.effectiveRole(raw), source: \"provider\", looked }\n : { role: catalog.defaultRole, source: \"default\", looked };\n }\n\n interface Resolved {\n id: string | null;\n role: R;\n /** `undefined` for a guest. */\n roleSource: RoleSource | undefined;\n user: PermissionsSubject | undefined;\n grants: Grant<P>[];\n }\n\n async function resolve(input: SubjectInput): Promise<Resolved> {\n if (input === null || input === undefined) {\n return {\n id: null,\n role: catalog.guestRole,\n roleSource: undefined,\n user: undefined,\n grants: [],\n };\n }\n const identity: SubjectIdentity = typeof input === \"string\" ? { id: input } : input;\n const id = requireSubjectId(identity.id);\n const entry = await load(id);\n const { role, source, looked } = await decideRole(id, entry.record, identity);\n const name = identity.name ?? entry.record?.name ?? looked?.name;\n const email = identity.email ?? entry.record?.email ?? looked?.email;\n const attributes = identity.attributes ?? looked?.attributes;\n const user: PermissionsSubject = {\n id,\n role,\n ...(name !== undefined ? { name } : {}),\n ...(email !== undefined ? { email } : {}),\n ...(attributes !== undefined ? { attributes } : {}),\n };\n return {\n id,\n role,\n roleSource: source,\n user,\n grants: entry.grants.filter(active) as Grant<P>[],\n };\n }\n\n async function buildAbility(\n input: SubjectInput,\n facts: { ctx?: X } | undefined,\n ): Promise<PermissionsAbility<D, R, P>> {\n const resolved = await resolve(input);\n const createAbility = catalog.authorization.createAbility as (\n user: PermissionsSubject | undefined,\n facts: { permissions: string[]; ctx?: X },\n ) => Ability<D, R, P, PermissionsSubject>;\n const ability = createAbility(resolved.user, {\n permissions: resolved.grants.map((grant) => grant.permission),\n ...(facts && \"ctx\" in facts ? { ctx: facts.ctx } : {}),\n });\n const decide = (\n path: string,\n explanation: CheckResult<R, P>[\"explanation\"],\n ): CheckResult<R, P> => {\n const base = {\n path,\n subject: resolved.id,\n role: ability.role,\n ...(resolved.roleSource !== undefined ? { roleSource: resolved.roleSource } : {}),\n explanation,\n };\n if (catalog.directGrants && resolved.id !== null && ability.permissions.has(path as P)) {\n return { ...base, allowed: true, reason: \"grant\" };\n }\n if (explanation.type === \"allowed\") return { ...base, allowed: true, reason: \"role-rule\" };\n if (explanation.type === \"unknown_path\") {\n return { ...base, allowed: false, reason: \"unknown-path\" };\n }\n return {\n ...base,\n allowed: false,\n reason: explanation.decidedBy === \"threw\" ? \"rule-threw\" : \"denied-by-rule\",\n };\n };\n // Always evaluate the rule, even when a direct grant would allow: an async rule outside\n // `asyncRule()` is a bug, and must surface as AsyncRuleError.\n const check = (path: string, data?: unknown): CheckResult<R, P> =>\n decide(path, ability.explain({ path, data }));\n const checkAsync = async (path: string, data?: unknown): Promise<CheckResult<R, P>> =>\n decide(path, await ability.explainAsync({ path, data }));\n return { ...ability, subject: resolved.id, grants: resolved.grants, check, checkAsync };\n }\n\n // --- writes ---------------------------------------------------------------------------------\n\n async function grant(input: GrantInput<P>): Promise<{ grant: Grant<P>; created: boolean }> {\n assertWritable(\"grant\");\n const subject = requireSubjectId(input?.subject);\n const permission = requirePermission(input.permission);\n const parsed = parseInput(grantInputSchema, input);\n const actor = toActor(parsed.actor);\n const expiresAt =\n parsed.expiresAt === undefined || parsed.expiresAt === null ? null : toIso(parsed.expiresAt);\n if (expiresAt !== null && Date.parse(expiresAt) <= now()) {\n throw new ValidationError([{ path: \"expiresAt\", message: \"must be in the future\" }]);\n }\n const key = grantKey(subject, permission);\n return withLock(key, async () => {\n for (let attempt = 0; attempt < CAS_ATTEMPTS; attempt++) {\n const existing = await storage.getItem<Grant<P>>(key);\n if (existing && active(existing)) return { grant: existing, created: false };\n const at = nowIso();\n const next: Grant<P> = {\n subject,\n permission,\n grantedBy: actor?.id ?? null,\n grantedAt: at,\n ...(parsed.reason !== undefined ? { reason: parsed.reason } : {}),\n ...(expiresAt !== null ? { expiresAt } : {}),\n };\n await runBefore(hooks, { type: \"grant.create\", subject, grant: next, actor });\n // Another process may have written the key meanwhile: re-read and decide again.\n if (!(await swap(key, existing ?? null, next))) continue;\n invalidate(subject);\n await appendHistory(\n {\n type: \"grant\",\n subject,\n permission,\n actor: actor?.id ?? null,\n ...(parsed.reason !== undefined ? { reason: parsed.reason } : {}),\n ...(expiresAt !== null ? { expiresAt } : {}),\n },\n at,\n );\n await runAfter(\n hooks,\n { type: \"grant.created\", subject, grant: next, actor, at },\n onHookError,\n );\n return { grant: next, created: true };\n }\n throw new Error(`grant: storage kept changing \"${key}\"; giving up`);\n });\n }\n\n async function revoke(input: RevokeInput<P>): Promise<RevokeResult<P>> {\n assertWritable(\"revoke\");\n const subject = requireSubjectId(input?.subject);\n const permission = requirePermission(input.permission);\n const parsed = parseInput(revokeInputSchema, input);\n const actor = toActor(parsed.actor);\n const key = grantKey(subject, permission);\n return withLock(key, async () => {\n const existing = await storage.getItem<Grant<P>>(key);\n if (!existing) return { removed: false, grant: null };\n const reason = parsed.reason !== undefined ? { reason: parsed.reason } : {};\n await runBefore(hooks, { type: \"grant.revoke\", subject, grant: existing, actor, ...reason });\n await storage.removeItem(key);\n invalidate(subject);\n const at = nowIso();\n await appendHistory(\n { type: \"revoke\", subject, permission, actor: actor?.id ?? null, ...reason },\n at,\n );\n await runAfter(\n hooks,\n { type: \"grant.revoked\", subject, grant: existing, actor, ...reason, at },\n onHookError,\n );\n return { removed: true, grant: existing };\n });\n }\n\n async function setRole(input: SetRoleInput<R>): Promise<SetRoleResult> {\n if (roleSource === \"external\") throw new ExternalRolesError();\n assertWritable(\"set role\");\n const subject = requireSubjectId(input?.subject);\n const role = input.role;\n if (role !== null) {\n if (!catalog.isRole(role)) throw new UnknownRoleError(role);\n if (role === catalog.guestRole) {\n throw new UnknownRoleError(\n role,\n `The guest role \"${role}\" can't be assigned to a subject.`,\n );\n }\n }\n const parsed = parseInput(setRoleInputSchema, input);\n const actor = toActor(parsed.actor);\n const reason = parsed.reason !== undefined ? { reason: parsed.reason } : {};\n const key = subjectKey(subject);\n return withLock(key, async () => {\n for (let attempt = 0; attempt < CAS_ATTEMPTS; attempt++) {\n const current = await storage.getItem<SubjectRecord>(key);\n const previous = current?.role ?? null;\n if (previous === role) return { record: current ?? null, changed: false };\n const at = nowIso();\n const { role: _old, ...rest } = current ?? { id: subject };\n const next: SubjectRecord = {\n ...rest,\n id: subject,\n ...(role !== null ? { role } : {}),\n updatedAt: at,\n };\n await runBefore(hooks, { type: \"role.set\", subject, role, previous, actor, ...reason });\n if (!(await swap(key, current ?? null, next))) continue;\n invalidate(subject);\n await appendHistory(\n {\n type: \"role\",\n subject,\n role,\n previousRole: previous,\n actor: actor?.id ?? null,\n ...reason,\n },\n at,\n );\n await runAfter(\n hooks,\n { type: \"role.changed\", subject, role, previous, record: next, actor, ...reason, at },\n onHookError,\n );\n return { record: next, changed: true };\n }\n throw new Error(`setRole: storage kept changing \"${key}\"; giving up`);\n });\n }\n\n async function upsertSubject(input: UpsertSubjectInput): Promise<SubjectRecord> {\n assertWritable(\"update subject\");\n const subject = requireSubjectId(input?.id);\n const parsed = parseInput(upsertSubjectInputSchema, input);\n const key = subjectKey(subject);\n return withLock(key, async () => {\n for (let attempt = 0; attempt < CAS_ATTEMPTS; attempt++) {\n const current = await storage.getItem<SubjectRecord>(key);\n const next: SubjectRecord = { ...current, id: subject, updatedAt: nowIso() };\n for (const field of [\"name\", \"email\"] as const) {\n const value = parsed[field];\n if (value === null) delete next[field];\n else if (value !== undefined) next[field] = value;\n }\n if (!(await swap(key, current ?? null, next))) continue;\n invalidate(subject);\n return next;\n }\n throw new Error(`upsertSubject: storage kept changing \"${key}\"; giving up`);\n });\n }\n\n // --- reads ----------------------------------------------------------------------------------\n\n async function list(query: ListQuery<P> = {}): Promise<Grant<P>[]> {\n const parsed = parseInput(listQuerySchema, query);\n let keys: string[];\n if (parsed.subject !== undefined && parsed.permission !== undefined) {\n keys = [grantKey(parsed.subject, parsed.permission)];\n } else if (parsed.subject !== undefined) {\n keys = await storage.getKeys(subjectGrantsPrefix(parsed.subject));\n } else {\n keys = await storage.getKeys(grantsPrefix());\n if (parsed.permission !== undefined) {\n const permission = parsed.permission;\n keys = keys.filter((key) => {\n const p = parseKey(key);\n return p?.area === \"grants\" && p.rest === permission;\n });\n }\n }\n const grants = (await Promise.all(keys.map((key) => storage.getItem<Grant<P>>(key)))).filter(\n (grant): grant is Grant<P> =>\n grant !== null &&\n typeof grant === \"object\" &&\n (parsed.includeExpired === true || active(grant)),\n );\n return grants.sort((a, b) =>\n a.subject === b.subject\n ? a.permission < b.permission\n ? -1\n : a.permission > b.permission\n ? 1\n : 0\n : a.subject < b.subject\n ? -1\n : 1,\n );\n }\n\n async function getSubject(\n id: string,\n opts: { includeExpired?: boolean } = {},\n ): Promise<SubjectView<R, P>> {\n const subject = requireSubjectId(id);\n const { record, grants } = await readSubject(subject);\n const { role, source } = await decideRole(subject, record, null);\n const shown = (opts.includeExpired ? grants : grants.filter(active)) as Grant<P>[];\n shown.sort((a, b) => (a.permission < b.permission ? -1 : a.permission > b.permission ? 1 : 0));\n return {\n id: subject,\n record,\n role: storedRole(record),\n effectiveRole: role,\n roleSource: source,\n grants: shown,\n };\n }\n\n async function listSubjects(): Promise<SubjectSummary[]> {\n const [recordKeys, grantKeys] = await Promise.all([\n storage.getKeys(subjectsPrefix()),\n storage.getKeys(grantsPrefix()),\n ]);\n const counts = new Map<string, number>();\n for (const key of grantKeys) {\n const parsed = parseKey(key);\n if (parsed?.area === \"grants\")\n counts.set(parsed.subject, (counts.get(parsed.subject) ?? 0) + 1);\n }\n const records = new Map<string, SubjectRecord>();\n await Promise.all(\n recordKeys.map(async (key) => {\n const parsed = parseKey(key);\n if (parsed?.area !== \"subjects\" || parsed.rest !== undefined) return;\n const record = await storage.getItem<SubjectRecord>(key);\n if (record) records.set(parsed.subject, record);\n }),\n );\n const ids = [...new Set([...records.keys(), ...counts.keys()])].sort();\n return Promise.all(\n ids.map(async (id) => {\n const record = records.get(id) ?? null;\n const { role, source, looked } = await decideRole(id, record, null, (error) => {\n logger.warn(`lookupSubject(\"${id}\") failed; listing its default role`, error);\n return null;\n });\n const name = record?.name ?? looked?.name;\n const email = record?.email ?? looked?.email;\n return {\n id,\n role: record?.role ?? null,\n effectiveRole: role,\n roleSource: source,\n ...(name !== undefined ? { name } : {}),\n ...(email !== undefined ? { email } : {}),\n grantCount: counts.get(id) ?? 0,\n };\n }),\n );\n }\n\n async function history(query: HistoryQuery = {}): Promise<HistoryPage> {\n const parsed = parseInput(historyQuerySchema, query);\n const limit = parsed.limit ?? DEFAULT_HISTORY_LIMIT;\n const keys = await storage.getKeys(\n parsed.subject !== undefined ? subjectHistoryPrefix(parsed.subject) : historyPrefix(),\n );\n let tokens = keys.map((key) => ({ key, token: historyToken(key) }));\n tokens.sort((a, b) => (a.token < b.token ? 1 : a.token > b.token ? -1 : 0));\n if (parsed.cursor !== undefined) {\n const after = historyToken(parsed.cursor);\n tokens = tokens.filter((t) => t.token < after);\n }\n const page = tokens.slice(0, limit);\n const entries = (\n await Promise.all(page.map((t) => storage.getItem<HistoryEntry>(t.key)))\n ).filter((entry): entry is HistoryEntry => entry !== null && typeof entry === \"object\");\n const last = page[page.length - 1];\n return { entries, nextCursor: tokens.length > limit && last ? last.key : null };\n }\n\n // --- checks ---------------------------------------------------------------------------------\n\n const relationships = createRelationships<S>({\n storage,\n schema: catalog.relations,\n options: options.relations,\n hooks,\n onHookError,\n nowIso,\n assertWritable,\n withLock,\n appendHistory,\n toActor,\n });\n\n const engine: Permissions<D, R, P, X, S> = {\n ...relationships,\n catalog,\n storage,\n readonly,\n roleSource,\n grant,\n revoke,\n list,\n setRole,\n getSubject,\n listSubjects,\n upsertSubject,\n history,\n ability: (subject, ...[facts]) => buildAbility(subject, facts),\n check: async (subject, path, data, ...[facts]) =>\n (await buildAbility(subject, facts)).checkAsync(path, data),\n can: async (subject, path, data, ...[facts]) =>\n (await (await buildAbility(subject, facts)).checkAsync(path, data)).allowed,\n async snapshot(subject) {\n const resolved = await resolve(subject);\n const permissions = [\n ...new Set(resolved.grants.map((grant) => grant.permission).filter(catalog.isAssignable)),\n ].sort();\n const who = {\n id: resolved.id,\n role: resolved.role,\n ...(resolved.roleSource !== undefined ? { roleSource: resolved.roleSource } : {}),\n };\n return { subject: who, permissions };\n },\n invalidate,\n async close() {\n // Unsubscribe exactly once: a driver's unwatch may throw when called twice (node-redis\n // rejects disconnecting a closed client). Wait for a pending subscription first.\n await watching;\n const off = unwatch;\n unwatch = null;\n off?.();\n },\n };\n return engine;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiUA,MAAM,wBAAwB;AAC9B,MAAM,eAAe;AAErB,MAAM,oBAAoB,UACxB,OAAO,UAAU,YAAY,MAAM,SAAS;AAE9C,SAAS,iBAAiB,OAAwB;CAChD,IAAI,CAAC,iBAAiB,KAAK,GAAG,MAAM,IAAIA,eAAAA,eAAe;CACvD,OAAO;AACT;AAEA,SAAS,QAAQ,OAAwD;CACvE,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,OAAO,OAAO,UAAU,WAAW,EAAE,IAAI,MAAM,IAAI;AACrD;AAEA,SAAS,MAAM,IAA0B;CACvC,MAAM,KAAK,OAAO,OAAO,WAAW,KAAK,OAAO,OAAO,WAAW,KAAK,MAAM,EAAE,IAAI,GA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MAAM,GAAG,CAAC,YACpC,MAAM,aAAa,SAAS,KAAK,GAAG,WAAW,MAAM,IAAI;EAC5D,KAAK,OAAO,SAAS,MAAM,MAAM,GAAG,CAAC,YAClC,OAAO,MAAM,aAAa,SAAS,KAAK,GAAG,WAAW,MAAM,IAAI,GAAG;EACtE,MAAM,SAAS,SAAS;GACtB,MAAM,WAAW,MAAM,QAAQ,OAAO;GACtC,MAAM,cAAc,CAClB,GAAG,IAAI,IAAI,SAAS,OAAO,KAAK,UAAU,MAAM,UAAU,EAAE,OAAO,QAAQ,YAAY,CAAC,CAC1F,EAAE,KAAK;GAMP,OAAO;IAAE,SAAS;KAJhB,IAAI,SAAS;KACb,MAAM,SAAS;KACf,GAAI,SAAS,eAAe,KAAA,IAAY,EAAE,YAAY,SAAS,WAAW,IAAI,CAAC;IAE7D;IAAG;GAAY;EACrC;EACA;EACA,MAAM,QAAQ;GAGZ,MAAM;GACN,MAAM,MAAM;GACZ,UAAU;GACV,MAAM;EACR;CAEU;AACd"}
@@ -1,7 +1,7 @@
1
1
  import { b as SubjectRef, c as ObjectRef, d as RelationExplanation, h as RelationTuple, o as DataAtPath, p as RelationSchema, s as Definition, t as Ability, x as TupleReadContext, y as RulesPaths } from "./policy-DFq_SYR3.cjs";
2
2
  import { f as PermissionsSubject, h as SubjectIdentity, u as PermissionsCatalog } from "./catalog-DA_d1SdC.cjs";
3
3
  import { n as PermissionsStorage } from "./contract-RMkmERhT.cjs";
4
- import { A as SetRoleInput, C as ListQuery, D as RelationshipPage, E as RelationshipInput, M as UpsertSubjectInput, O as RelationshipQuery, T as Relationship, _ as GrantInput, b as HistoryQuery, c as PermissionsHooksInput, g as Grant, h as CheckResult, j as SubjectRecord, k as RevokeInput, o as HookErrorReporter, w as PermissionsSnapshot, y as HistoryPage } from "./contract-Dk6d2ylD.cjs";
4
+ import { A as RoleSource, C as ListQuery, D as RelationshipPage, E as RelationshipInput, M as SetRoleInput, N as SubjectRecord, O as RelationshipQuery, P as UpsertSubjectInput, T as Relationship, _ as GrantInput, b as HistoryQuery, c as PermissionsHooksInput, g as Grant, h as CheckResult, j as RoleSourceMode, k as RevokeInput, o as HookErrorReporter, w as PermissionsSnapshot, y as HistoryPage } from "./contract-CXPMGuHk.cjs";
5
5
  //#region src/relationships.d.ts
6
6
  /** A relationship check: does `subject` have `relation` on `object`? */
7
7
  interface RelationCheckQuery<S extends RelationSchema = RelationSchema> {
@@ -139,7 +139,8 @@ interface PermissionsOptions<D extends Definition = Definition, R extends string
139
139
  /** Receives errors thrown by `after` hooks. Default: a prefixed `console.warn`. */
140
140
  onHookError?: HookErrorReporter;
141
141
  /**
142
- * Per-subject cache of the stored role and grants used by checks. Entries expire after `ttlMs`
142
+ * Per-subject cache of the stored role and grants used by checks (and of `lookupSubject`
143
+ * results). Entries expire after `ttlMs`
143
144
  * (default 5 000), are dropped on this engine's writes and, when the storage is watchable, on
144
145
  * every change it reports. `false` disables it (every check reads the storage).
145
146
  */
@@ -157,7 +158,26 @@ interface PermissionsOptions<D extends Definition = Definition, R extends string
157
158
  };
158
159
  /** ReBAC tuning (the catalog's `relations`): `maxDepth` of checks and listing walks. */
159
160
  relations?: RelationsOptions;
161
+ /**
162
+ * Who owns roles (ADR 0014). `"stored"` (default, the 0.1 behaviour): a role set with
163
+ * `setRole()` wins over the auth provider's. `"external"`: the auth provider owns roles; stored
164
+ * roles are ignored and `setRole()` throws {@link ExternalRolesError}.
165
+ */
166
+ roleSource?: RoleSourceMode;
167
+ /**
168
+ * Resolve a subject by id when a check (or the panel) only has the id, not a session: returns
169
+ * the auth provider's identity (`role`, `name`, `email`). Used in both role-source modes, only
170
+ * when the identity passed carries no `role`; cached with the per-subject cache. Needed for the
171
+ * panel to show the provider's role of subjects other than the caller. Every bundled auth
172
+ * provider can supply one (`provider.lookupSubject`).
173
+ */
174
+ lookupSubject?: SubjectLookup | undefined;
160
175
  }
176
+ /**
177
+ * Looks a subject up by id in the auth provider (see {@link PermissionsOptions.lookupSubject}).
178
+ * `null` = unknown subject (the catalog's `defaultRole` applies). A throw fails the check.
179
+ */
180
+ type SubjectLookup = (id: string) => SubjectIdentity | null | undefined | Promise<SubjectIdentity | null | undefined>;
161
181
  /** A subject id, an identity, or `null` / `undefined` for a guest (no session). */
162
182
  type SubjectInput = string | SubjectIdentity | null | undefined;
163
183
  /** The app context argument of checks: required when the catalog's context type is. */
@@ -205,16 +225,27 @@ interface SubjectView<R extends string = string, P extends string = string> {
205
225
  id: string;
206
226
  /** The stored record, `null` when the subject has none. */
207
227
  record: SubjectRecord | null;
208
- /** The stored role assignment when it is a known, assignable role; else `null`. */
228
+ /**
229
+ * The stored role assignment when it is a known, assignable role; else `null`. Ignored by checks
230
+ * when the engine's `roleSource` is `"external"`.
231
+ */
209
232
  role: R | null;
233
+ /** The role checks use: see {@link roleSource} for what decided it. */
234
+ effectiveRole: R;
235
+ /** Which source decided {@link effectiveRole}. */
236
+ roleSource: RoleSource;
210
237
  /** The subject's grants (non-expired unless `includeExpired`). */
211
238
  grants: Grant<P>[];
212
239
  }
213
240
  /** One row of `listSubjects()`. */
214
241
  interface SubjectSummary {
215
242
  id: string;
216
- /** The stored role assignment, if any. */
243
+ /** The stored role assignment, if any (ignored by checks when `roleSource` is `"external"`). */
217
244
  role: string | null;
245
+ /** The role checks use (the stored role, the auth provider's, or `defaultRole`). */
246
+ effectiveRole: string;
247
+ /** Which source decided {@link effectiveRole}. */
248
+ roleSource: RoleSource;
218
249
  name?: string;
219
250
  email?: string;
220
251
  /** Stored grants (expired ones included). */
@@ -228,6 +259,8 @@ interface Permissions<D extends Definition = Definition, R extends string = stri
228
259
  readonly catalog: PermissionsCatalog<D, R, P, X, S>;
229
260
  readonly storage: PermissionsStorage;
230
261
  readonly readonly: boolean;
262
+ /** Who owns roles: `"stored"` (default) or `"external"` (the auth provider; ADR 0014). */
263
+ readonly roleSource: RoleSourceMode;
231
264
  /**
232
265
  * Grant a permission. Idempotent: re-granting returns the existing grant with `created: false`
233
266
  * (no history entry, no hooks). An **expired** existing grant is replaced (`created: true`).
@@ -249,14 +282,21 @@ interface Permissions<D extends Definition = Definition, R extends string = stri
249
282
  /**
250
283
  * Store a role assignment (overrides the auth provider's role); `role: null` clears it.
251
284
  *
252
- * @throws {UnknownRoleError} not one of `roles`, or the guest role.
285
+ * @throws {UnknownRoleError} not one of `roles`, or the guest role. {@link ExternalRolesError}
286
+ * when `roleSource` is `"external"` (the auth provider owns roles).
253
287
  */
254
288
  setRole(input: SetRoleInput<R>): Promise<SetRoleResult>;
255
- /** A subject's stored record and grants (an empty view when nothing is stored). */
289
+ /**
290
+ * A subject's stored record and grants (an empty view when nothing is stored), with its effective
291
+ * role and the source that decided it (the auth provider's role comes from `lookupSubject`).
292
+ */
256
293
  getSubject(id: string, options?: {
257
294
  includeExpired?: boolean;
258
295
  }): Promise<SubjectView<R, P>>;
259
- /** Every subject with a record or a grant, sorted by id. */
296
+ /**
297
+ * Every subject with a record or a grant, sorted by id, with effective roles. A failing
298
+ * `lookupSubject` is logged and reported as `roleSource: "default"` (the list still loads).
299
+ */
260
300
  listSubjects(): Promise<SubjectSummary[]>;
261
301
  /** Create or update a subject's display fields (`null` clears one). Keeps the stored role. */
262
302
  upsertSubject(input: UpsertSubjectInput): Promise<SubjectRecord>;
@@ -292,5 +332,5 @@ type AnyPermissions = Permissions<any, any, any, any, any>;
292
332
  */
293
333
  declare function createPermissions<D extends Definition, R extends string, P extends string, X, S extends RelationSchema = RelationSchema>(options: PermissionsOptions<D, R, P, X, S>): Permissions<D, R, P, X, S>;
294
334
  //#endregion
295
- export { RepairReport as C, RelationshipsApi as S, RelationCheckQuery as _, PermissionsAbility as a, RelationTypeView as b, SetRoleResult as c, SubjectView as d, createPermissions as f, LoadRelationsOptions as g, ListRelationSubjectsQuery as h, Permissions as i, SubjectInput as l, ListObjectsQuery as m, FactsArgs as n, PermissionsOptions as o, DeleteRelationshipResult as p, PathData as r, RevokeResult as s, AnyPermissions as t, SubjectSummary as u, RelationCheckResult as v, WriteRelationshipResult as w, RelationsOptions as x, RelationFacts as y };
296
- //# sourceMappingURL=engine-CGGVDCqi.d.cts.map
335
+ export { RelationshipsApi as C, RelationsOptions as S, WriteRelationshipResult as T, LoadRelationsOptions as _, PermissionsAbility as a, RelationFacts as b, SetRoleResult as c, SubjectSummary as d, SubjectView as f, ListRelationSubjectsQuery as g, ListObjectsQuery as h, Permissions as i, SubjectInput as l, DeleteRelationshipResult as m, FactsArgs as n, PermissionsOptions as o, createPermissions as p, PathData as r, RevokeResult as s, AnyPermissions as t, SubjectLookup as u, RelationCheckQuery as v, RepairReport as w, RelationTypeView as x, RelationCheckResult as y };
336
+ //# sourceMappingURL=engine-BTgwbHeO.d.cts.map
@@ -1,7 +1,7 @@
1
1
  import { b as SubjectRef, c as ObjectRef, d as RelationExplanation, h as RelationTuple, o as DataAtPath, p as RelationSchema, s as Definition, t as Ability, x as TupleReadContext, y as RulesPaths } from "./policy-CGA6QD0a.mjs";
2
2
  import { f as PermissionsSubject, h as SubjectIdentity, u as PermissionsCatalog } from "./catalog-DJcJ3ycq.mjs";
3
3
  import { n as PermissionsStorage } from "./contract-RMkmERhT.mjs";
4
- import { A as SetRoleInput, C as ListQuery, D as RelationshipPage, E as RelationshipInput, M as UpsertSubjectInput, O as RelationshipQuery, T as Relationship, _ as GrantInput, b as HistoryQuery, c as PermissionsHooksInput, g as Grant, h as CheckResult, j as SubjectRecord, k as RevokeInput, o as HookErrorReporter, w as PermissionsSnapshot, y as HistoryPage } from "./contract-DUzgB-He.mjs";
4
+ import { A as RoleSource, C as ListQuery, D as RelationshipPage, E as RelationshipInput, M as SetRoleInput, N as SubjectRecord, O as RelationshipQuery, P as UpsertSubjectInput, T as Relationship, _ as GrantInput, b as HistoryQuery, c as PermissionsHooksInput, g as Grant, h as CheckResult, j as RoleSourceMode, k as RevokeInput, o as HookErrorReporter, w as PermissionsSnapshot, y as HistoryPage } from "./contract-DhS23Pcp.mjs";
5
5
  //#region src/relationships.d.ts
6
6
  /** A relationship check: does `subject` have `relation` on `object`? */
7
7
  interface RelationCheckQuery<S extends RelationSchema = RelationSchema> {
@@ -139,7 +139,8 @@ interface PermissionsOptions<D extends Definition = Definition, R extends string
139
139
  /** Receives errors thrown by `after` hooks. Default: a prefixed `console.warn`. */
140
140
  onHookError?: HookErrorReporter;
141
141
  /**
142
- * Per-subject cache of the stored role and grants used by checks. Entries expire after `ttlMs`
142
+ * Per-subject cache of the stored role and grants used by checks (and of `lookupSubject`
143
+ * results). Entries expire after `ttlMs`
143
144
  * (default 5 000), are dropped on this engine's writes and, when the storage is watchable, on
144
145
  * every change it reports. `false` disables it (every check reads the storage).
145
146
  */
@@ -157,7 +158,26 @@ interface PermissionsOptions<D extends Definition = Definition, R extends string
157
158
  };
158
159
  /** ReBAC tuning (the catalog's `relations`): `maxDepth` of checks and listing walks. */
159
160
  relations?: RelationsOptions;
161
+ /**
162
+ * Who owns roles (ADR 0014). `"stored"` (default, the 0.1 behaviour): a role set with
163
+ * `setRole()` wins over the auth provider's. `"external"`: the auth provider owns roles; stored
164
+ * roles are ignored and `setRole()` throws {@link ExternalRolesError}.
165
+ */
166
+ roleSource?: RoleSourceMode;
167
+ /**
168
+ * Resolve a subject by id when a check (or the panel) only has the id, not a session: returns
169
+ * the auth provider's identity (`role`, `name`, `email`). Used in both role-source modes, only
170
+ * when the identity passed carries no `role`; cached with the per-subject cache. Needed for the
171
+ * panel to show the provider's role of subjects other than the caller. Every bundled auth
172
+ * provider can supply one (`provider.lookupSubject`).
173
+ */
174
+ lookupSubject?: SubjectLookup | undefined;
160
175
  }
176
+ /**
177
+ * Looks a subject up by id in the auth provider (see {@link PermissionsOptions.lookupSubject}).
178
+ * `null` = unknown subject (the catalog's `defaultRole` applies). A throw fails the check.
179
+ */
180
+ type SubjectLookup = (id: string) => SubjectIdentity | null | undefined | Promise<SubjectIdentity | null | undefined>;
161
181
  /** A subject id, an identity, or `null` / `undefined` for a guest (no session). */
162
182
  type SubjectInput = string | SubjectIdentity | null | undefined;
163
183
  /** The app context argument of checks: required when the catalog's context type is. */
@@ -205,16 +225,27 @@ interface SubjectView<R extends string = string, P extends string = string> {
205
225
  id: string;
206
226
  /** The stored record, `null` when the subject has none. */
207
227
  record: SubjectRecord | null;
208
- /** The stored role assignment when it is a known, assignable role; else `null`. */
228
+ /**
229
+ * The stored role assignment when it is a known, assignable role; else `null`. Ignored by checks
230
+ * when the engine's `roleSource` is `"external"`.
231
+ */
209
232
  role: R | null;
233
+ /** The role checks use: see {@link roleSource} for what decided it. */
234
+ effectiveRole: R;
235
+ /** Which source decided {@link effectiveRole}. */
236
+ roleSource: RoleSource;
210
237
  /** The subject's grants (non-expired unless `includeExpired`). */
211
238
  grants: Grant<P>[];
212
239
  }
213
240
  /** One row of `listSubjects()`. */
214
241
  interface SubjectSummary {
215
242
  id: string;
216
- /** The stored role assignment, if any. */
243
+ /** The stored role assignment, if any (ignored by checks when `roleSource` is `"external"`). */
217
244
  role: string | null;
245
+ /** The role checks use (the stored role, the auth provider's, or `defaultRole`). */
246
+ effectiveRole: string;
247
+ /** Which source decided {@link effectiveRole}. */
248
+ roleSource: RoleSource;
218
249
  name?: string;
219
250
  email?: string;
220
251
  /** Stored grants (expired ones included). */
@@ -228,6 +259,8 @@ interface Permissions<D extends Definition = Definition, R extends string = stri
228
259
  readonly catalog: PermissionsCatalog<D, R, P, X, S>;
229
260
  readonly storage: PermissionsStorage;
230
261
  readonly readonly: boolean;
262
+ /** Who owns roles: `"stored"` (default) or `"external"` (the auth provider; ADR 0014). */
263
+ readonly roleSource: RoleSourceMode;
231
264
  /**
232
265
  * Grant a permission. Idempotent: re-granting returns the existing grant with `created: false`
233
266
  * (no history entry, no hooks). An **expired** existing grant is replaced (`created: true`).
@@ -249,14 +282,21 @@ interface Permissions<D extends Definition = Definition, R extends string = stri
249
282
  /**
250
283
  * Store a role assignment (overrides the auth provider's role); `role: null` clears it.
251
284
  *
252
- * @throws {UnknownRoleError} not one of `roles`, or the guest role.
285
+ * @throws {UnknownRoleError} not one of `roles`, or the guest role. {@link ExternalRolesError}
286
+ * when `roleSource` is `"external"` (the auth provider owns roles).
253
287
  */
254
288
  setRole(input: SetRoleInput<R>): Promise<SetRoleResult>;
255
- /** A subject's stored record and grants (an empty view when nothing is stored). */
289
+ /**
290
+ * A subject's stored record and grants (an empty view when nothing is stored), with its effective
291
+ * role and the source that decided it (the auth provider's role comes from `lookupSubject`).
292
+ */
256
293
  getSubject(id: string, options?: {
257
294
  includeExpired?: boolean;
258
295
  }): Promise<SubjectView<R, P>>;
259
- /** Every subject with a record or a grant, sorted by id. */
296
+ /**
297
+ * Every subject with a record or a grant, sorted by id, with effective roles. A failing
298
+ * `lookupSubject` is logged and reported as `roleSource: "default"` (the list still loads).
299
+ */
260
300
  listSubjects(): Promise<SubjectSummary[]>;
261
301
  /** Create or update a subject's display fields (`null` clears one). Keeps the stored role. */
262
302
  upsertSubject(input: UpsertSubjectInput): Promise<SubjectRecord>;
@@ -292,5 +332,5 @@ type AnyPermissions = Permissions<any, any, any, any, any>;
292
332
  */
293
333
  declare function createPermissions<D extends Definition, R extends string, P extends string, X, S extends RelationSchema = RelationSchema>(options: PermissionsOptions<D, R, P, X, S>): Permissions<D, R, P, X, S>;
294
334
  //#endregion
295
- export { RepairReport as C, RelationshipsApi as S, RelationCheckQuery as _, PermissionsAbility as a, RelationTypeView as b, SetRoleResult as c, SubjectView as d, createPermissions as f, LoadRelationsOptions as g, ListRelationSubjectsQuery as h, Permissions as i, SubjectInput as l, ListObjectsQuery as m, FactsArgs as n, PermissionsOptions as o, DeleteRelationshipResult as p, PathData as r, RevokeResult as s, AnyPermissions as t, SubjectSummary as u, RelationCheckResult as v, WriteRelationshipResult as w, RelationsOptions as x, RelationFacts as y };
296
- //# sourceMappingURL=engine-DpFIcbgh.d.mts.map
335
+ export { RelationshipsApi as C, RelationsOptions as S, WriteRelationshipResult as T, LoadRelationsOptions as _, PermissionsAbility as a, RelationFacts as b, SetRoleResult as c, SubjectSummary as d, SubjectView as f, ListRelationSubjectsQuery as g, ListObjectsQuery as h, Permissions as i, SubjectInput as l, DeleteRelationshipResult as m, FactsArgs as n, PermissionsOptions as o, createPermissions as p, PathData as r, RevokeResult as s, AnyPermissions as t, SubjectLookup as u, RelationCheckQuery as v, RepairReport as w, RelationTypeView as x, RelationCheckResult as y };
336
+ //# sourceMappingURL=engine-C3xHfi3q.d.mts.map