@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
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { A as revokeInputSchema, C as historyQuerySchema, M as upsertSubjectInputSchema, S as grantInputSchema, T as listQuerySchema, _ as defaultHookErrorReporter, a as isWatchable, b as runBefore, c as grantsPrefix, d as parseKey, f as subjectGrantsPrefix, h as subjectsPrefix, j as setRoleInputSchema, l as historyKey, m as subjectKey, o as ROOT, p as subjectHistoryPrefix, r as isCompareAndSwap, s as grantKey, t as createRelationships, u as historyPrefix, v as normalizeHooks, y as runAfter } from "./relationships-BfLonEMI.mjs";
3
- import { a as UnknownPermissionError, i as ReadonlyError, n as NoSubjectError, o as UnknownRoleError } from "./errors-bL3XQLfE.mjs";
3
+ import { a as ReadonlyError, o as UnknownPermissionError, r as NoSubjectError, s as UnknownRoleError, t as ExternalRolesError } from "./errors-CG_OLEEv.mjs";
4
4
  import { createIdGenerator } from "@xtandard/kit/util/core";
5
5
  import { ValidationError, parseInput } from "@xtandard/kit/util";
6
6
  //#region src/engine.ts
@@ -9,7 +9,8 @@ import { ValidationError, parseInput } from "@xtandard/kit/util";
9
9
  *
10
10
  * Writes (grant, revoke, role assignment, subject records) go to the storage
11
11
  * under the `perm/` key root (ADR 0003) and fire the hooks. Checks load the
12
- * subject's stored role and grants (async, cached per subject), then evaluate
12
+ * subject's stored role and grants (async, cached per subject), resolve the
13
+ * effective role from the `roleSource` (ADR 0014), then evaluate
13
14
  * the catalog's rules **synchronously** with `@xtandard/lib/policy/permix`
14
15
  * (ADR 0005).
15
16
  *
@@ -71,6 +72,9 @@ function createPermissions(options) {
71
72
  const cacheEnabled = options.cache !== false;
72
73
  const cacheTtl = (options.cache ? options.cache.ttlMs : void 0) ?? 5e3;
73
74
  const cacheMax = (options.cache ? options.cache.max : void 0) ?? 1e4;
75
+ const roleSource = options.roleSource ?? "stored";
76
+ if (roleSource !== "stored" && roleSource !== "external") throw new TypeError(`createPermissions: roleSource must be "stored" or "external"`);
77
+ const lookupSubject = options.lookupSubject;
74
78
  const ids = createIdGenerator({ format: "ulid-lower22" });
75
79
  const nowIso = () => new Date(now()).toISOString();
76
80
  const active = (grant) => grant.expiresAt === void 0 || grant.expiresAt === null || Date.parse(grant.expiresAt) > now();
@@ -107,6 +111,8 @@ function createPermissions(options) {
107
111
  return true;
108
112
  }
109
113
  const cache = /* @__PURE__ */ new Map();
114
+ /** `lookupSubject` results: same TTL, size bound and invalidation as {@link cache}. */
115
+ const lookups = /* @__PURE__ */ new Map();
110
116
  const generations = /* @__PURE__ */ new Map();
111
117
  const inflight = /* @__PURE__ */ new Map();
112
118
  let unwatch = null;
@@ -114,11 +120,13 @@ function createPermissions(options) {
114
120
  const invalidate = (subject) => {
115
121
  if (subject === void 0) {
116
122
  cache.clear();
123
+ lookups.clear();
117
124
  inflight.clear();
118
125
  for (const key of generations.keys()) generations.set(key, (generations.get(key) ?? 0) + 1);
119
126
  return;
120
127
  }
121
128
  cache.delete(subject);
129
+ lookups.delete(subject);
122
130
  inflight.delete(subject);
123
131
  generations.set(subject, (generations.get(subject) ?? 0) + 1);
124
132
  };
@@ -177,28 +185,84 @@ function createPermissions(options) {
177
185
  await storage.setItem(historyKey(entry.subject, at, id), full);
178
186
  }
179
187
  const storedRole = (record) => record?.role !== void 0 && catalog.isRole(record.role) && record.role !== catalog.guestRole ? record.role : null;
188
+ /** The provider's identity of `id` from `lookupSubject` (cached; `null` without one). */
189
+ function lookup(id) {
190
+ if (!lookupSubject) return Promise.resolve(null);
191
+ const cached = cacheEnabled ? lookups.get(id) : void 0;
192
+ if (cached && now() - cached.at < cacheTtl) return cached.identity;
193
+ const identity = Promise.resolve().then(() => lookupSubject(id)).then((found) => found && typeof found === "object" ? found : null);
194
+ if (cacheEnabled) {
195
+ lookups.delete(id);
196
+ lookups.set(id, {
197
+ identity,
198
+ at: now()
199
+ });
200
+ while (lookups.size > cacheMax) lookups.delete(lookups.keys().next().value);
201
+ identity.catch(() => {
202
+ if (lookups.get(id)?.identity === identity) lookups.delete(id);
203
+ });
204
+ }
205
+ return identity;
206
+ }
207
+ /** True when a raw provider role names a known, non-guest role (else `defaultRole` applies). */
208
+ const knownRole = (raw) => {
209
+ return (typeof raw === "string" ? raw.split(",").map((s) => s.trim()) : Array.isArray(raw) ? raw : []).some((c) => catalog.isRole(c) && c !== catalog.guestRole);
210
+ };
211
+ /**
212
+ * The effective role (ADR 0014). `external`: the provider's role (passed with the identity, else
213
+ * looked up), else `defaultRole`. `stored`: the stored role, else the same. The lookup runs only
214
+ * when the identity carries no `role` (`null` means "the provider says none": no lookup).
215
+ */
216
+ async function decideRole(id, record, identity, lookupFailed) {
217
+ if (roleSource === "stored") {
218
+ const stored = storedRole(record);
219
+ if (stored !== null) return {
220
+ role: stored,
221
+ source: "stored",
222
+ looked: null
223
+ };
224
+ }
225
+ let looked = null;
226
+ let raw = identity?.role;
227
+ if (raw === void 0) {
228
+ looked = lookupFailed ? await lookup(id).catch(lookupFailed) : await lookup(id);
229
+ raw = looked?.role;
230
+ }
231
+ return knownRole(raw) ? {
232
+ role: catalog.effectiveRole(raw),
233
+ source: "provider",
234
+ looked
235
+ } : {
236
+ role: catalog.defaultRole,
237
+ source: "default",
238
+ looked
239
+ };
240
+ }
180
241
  async function resolve(input) {
181
242
  if (input === null || input === void 0) return {
182
243
  id: null,
183
244
  role: catalog.guestRole,
245
+ roleSource: void 0,
184
246
  user: void 0,
185
247
  grants: []
186
248
  };
187
249
  const identity = typeof input === "string" ? { id: input } : input;
188
250
  const id = requireSubjectId(identity.id);
189
251
  const entry = await load(id);
190
- const role = storedRole(entry.record) ?? catalog.effectiveRole(identity.role ?? null);
191
- const name = identity.name ?? entry.record?.name;
192
- const email = identity.email ?? entry.record?.email;
252
+ const { role, source, looked } = await decideRole(id, entry.record, identity);
253
+ const name = identity.name ?? entry.record?.name ?? looked?.name;
254
+ const email = identity.email ?? entry.record?.email ?? looked?.email;
255
+ const attributes = identity.attributes ?? looked?.attributes;
193
256
  return {
194
257
  id,
195
258
  role,
259
+ roleSource: source,
196
260
  user: {
197
261
  id,
198
262
  role,
199
263
  ...name !== void 0 ? { name } : {},
200
264
  ...email !== void 0 ? { email } : {},
201
- ...identity.attributes !== void 0 ? { attributes: identity.attributes } : {}
265
+ ...attributes !== void 0 ? { attributes } : {}
202
266
  },
203
267
  grants: entry.grants.filter(active)
204
268
  };
@@ -215,6 +279,7 @@ function createPermissions(options) {
215
279
  path,
216
280
  subject: resolved.id,
217
281
  role: ability.role,
282
+ ...resolved.roleSource !== void 0 ? { roleSource: resolved.roleSource } : {},
218
283
  explanation
219
284
  };
220
285
  if (catalog.directGrants && resolved.id !== null && ability.permissions.has(path)) return {
@@ -359,6 +424,7 @@ function createPermissions(options) {
359
424
  });
360
425
  }
361
426
  async function setRole(input) {
427
+ if (roleSource === "external") throw new ExternalRolesError();
362
428
  assertWritable("set role");
363
429
  const subject = requireSubjectId(input?.subject);
364
430
  const role = input.role;
@@ -467,12 +533,15 @@ function createPermissions(options) {
467
533
  async function getSubject(id, opts = {}) {
468
534
  const subject = requireSubjectId(id);
469
535
  const { record, grants } = await readSubject(subject);
536
+ const { role, source } = await decideRole(subject, record, null);
470
537
  const shown = opts.includeExpired ? grants : grants.filter(active);
471
538
  shown.sort((a, b) => a.permission < b.permission ? -1 : a.permission > b.permission ? 1 : 0);
472
539
  return {
473
540
  id: subject,
474
541
  record,
475
542
  role: storedRole(record),
543
+ effectiveRole: role,
544
+ roleSource: source,
476
545
  grants: shown
477
546
  };
478
547
  }
@@ -490,16 +559,25 @@ function createPermissions(options) {
490
559
  const record = await storage.getItem(key);
491
560
  if (record) records.set(parsed.subject, record);
492
561
  }));
493
- return [...new Set([...records.keys(), ...counts.keys()])].sort().map((id) => {
494
- const record = records.get(id);
562
+ const ids = [...new Set([...records.keys(), ...counts.keys()])].sort();
563
+ return Promise.all(ids.map(async (id) => {
564
+ const record = records.get(id) ?? null;
565
+ const { role, source, looked } = await decideRole(id, record, null, (error) => {
566
+ logger.warn(`lookupSubject("${id}") failed; listing its default role`, error);
567
+ return null;
568
+ });
569
+ const name = record?.name ?? looked?.name;
570
+ const email = record?.email ?? looked?.email;
495
571
  return {
496
572
  id,
497
573
  role: record?.role ?? null,
498
- ...record?.name !== void 0 ? { name: record.name } : {},
499
- ...record?.email !== void 0 ? { email: record.email } : {},
574
+ effectiveRole: role,
575
+ roleSource: source,
576
+ ...name !== void 0 ? { name } : {},
577
+ ...email !== void 0 ? { email } : {},
500
578
  grantCount: counts.get(id) ?? 0
501
579
  };
502
- });
580
+ }));
503
581
  }
504
582
  async function history(query = {}) {
505
583
  const parsed = parseInput(historyQuerySchema, query);
@@ -537,6 +615,7 @@ function createPermissions(options) {
537
615
  catalog,
538
616
  storage,
539
617
  readonly,
618
+ roleSource,
540
619
  grant,
541
620
  revoke,
542
621
  list,
@@ -554,7 +633,8 @@ function createPermissions(options) {
554
633
  return {
555
634
  subject: {
556
635
  id: resolved.id,
557
- role: resolved.role
636
+ role: resolved.role,
637
+ ...resolved.roleSource !== void 0 ? { roleSource: resolved.roleSource } : {}
558
638
  },
559
639
  permissions
560
640
  };
@@ -571,4 +651,4 @@ function createPermissions(options) {
571
651
  //#endregion
572
652
  export { engine_exports as n, createPermissions as t };
573
653
 
574
- //# sourceMappingURL=engine-Bufv0TbD.mjs.map
654
+ //# sourceMappingURL=engine-CR75K253.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-CR75K253.mjs","names":[],"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,IAAI,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,O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,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,10 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_contract = require("./contract-CPmJVoRx.cjs");
3
- const require_kit = require("./kit-C7tepDB2.cjs");
4
- const require_better_auth = require("./better-auth-DHyW5-yt.cjs");
2
+ const require_contract = require("./contract-Brnu9XXo.cjs");
3
+ const require_kit = require("./kit-BrqnCcDw.cjs");
4
+ const require_better_auth = require("./better-auth-MR7dBtpo.cjs");
5
5
  exports.asBetterAuthSession = require_better_auth.asBetterAuthSession;
6
6
  exports.betterAuthProvider = require_better_auth.betterAuthProvider;
7
+ exports.externalRoles = require_contract.externalRoles;
7
8
  exports.identity = require_contract.identity;
9
+ exports.identityOf = require_kit.identityOf;
10
+ exports.mappedLookup = require_contract.mappedLookup;
8
11
  exports.normalizeRoles = require_contract.normalizeRoles;
9
12
  exports.splitRoles = require_contract.splitRoles;
10
13
  exports.stringField = require_contract.stringField;
@@ -1,5 +1,5 @@
1
1
  import { f as PermissionsSubject, h as SubjectIdentity } from "./catalog-DA_d1SdC.cjs";
2
- import { a as normalizeRoles, i as identity, n as ProviderRoleOptions, o as splitRoles, r as RoleMapper, s as stringField, t as PermissionsAuthProvider } from "./contract-BMiOmg2f.cjs";
3
- import { a as betterAuthProvider, i as asBetterAuthSession, n as BetterAuthProviderOptions, r as BetterAuthSessionLike, t as BetterAuthLike } from "./better-auth-Bp9YVyQa.cjs";
4
- import { a as toKitAuth, i as subjectOf, n as KitAuthEngine, r as ToKitAuthOptions, t as KitAuth } from "./kit-qAROuhOI.cjs";
5
- export { type BetterAuthLike, type BetterAuthProviderOptions, type BetterAuthSessionLike, KitAuth, KitAuthEngine, PermissionsAuthProvider, type PermissionsSubject, ProviderRoleOptions, RoleMapper, type SubjectIdentity, ToKitAuthOptions, asBetterAuthSession, betterAuthProvider, identity, normalizeRoles, splitRoles, stringField, subjectOf, toKitAuth };
2
+ import { a as externalRoles, c as normalizeRoles, i as SubjectLookupFn, l as splitRoles, n as ProviderRoleOptions, o as identity, r as RoleMapper, s as mappedLookup, t as PermissionsAuthProvider, u as stringField } from "./contract-BAisPHBw.cjs";
3
+ import { a as asBetterAuthSession, i as BetterAuthSessionLike, n as BetterAuthPermissionsProvider, o as betterAuthProvider, r as BetterAuthProviderOptions, t as BetterAuthLike } from "./better-auth-vgRYgjYK.cjs";
4
+ import { a as subjectOf, i as identityOf, n as KitAuthEngine, o as toKitAuth, r as ToKitAuthOptions, t as KitAuth } from "./kit-DLF7DZrp.cjs";
5
+ export { type BetterAuthLike, type BetterAuthPermissionsProvider, type BetterAuthProviderOptions, type BetterAuthSessionLike, KitAuth, KitAuthEngine, PermissionsAuthProvider, type PermissionsSubject, ProviderRoleOptions, RoleMapper, type SubjectIdentity, SubjectLookupFn, ToKitAuthOptions, asBetterAuthSession, betterAuthProvider, externalRoles, identity, identityOf, mappedLookup, normalizeRoles, splitRoles, stringField, subjectOf, toKitAuth };
@@ -1,5 +1,5 @@
1
1
  import { f as PermissionsSubject, h as SubjectIdentity } from "./catalog-DJcJ3ycq.mjs";
2
- import { a as normalizeRoles, i as identity, n as ProviderRoleOptions, o as splitRoles, r as RoleMapper, s as stringField, t as PermissionsAuthProvider } from "./contract-D32H1t0u.mjs";
3
- import { a as betterAuthProvider, i as asBetterAuthSession, n as BetterAuthProviderOptions, r as BetterAuthSessionLike, t as BetterAuthLike } from "./better-auth-NSXgt6ZU.mjs";
4
- import { a as toKitAuth, i as subjectOf, n as KitAuthEngine, r as ToKitAuthOptions, t as KitAuth } from "./kit-DMVBLBI9.mjs";
5
- export { type BetterAuthLike, type BetterAuthProviderOptions, type BetterAuthSessionLike, KitAuth, KitAuthEngine, PermissionsAuthProvider, type PermissionsSubject, ProviderRoleOptions, RoleMapper, type SubjectIdentity, ToKitAuthOptions, asBetterAuthSession, betterAuthProvider, identity, normalizeRoles, splitRoles, stringField, subjectOf, toKitAuth };
2
+ import { a as externalRoles, c as normalizeRoles, i as SubjectLookupFn, l as splitRoles, n as ProviderRoleOptions, o as identity, r as RoleMapper, s as mappedLookup, t as PermissionsAuthProvider, u as stringField } from "./contract-D6j-yrBL.mjs";
3
+ import { a as asBetterAuthSession, i as BetterAuthSessionLike, n as BetterAuthPermissionsProvider, o as betterAuthProvider, r as BetterAuthProviderOptions, t as BetterAuthLike } from "./better-auth-DQET1sXa.mjs";
4
+ import { a as subjectOf, i as identityOf, n as KitAuthEngine, o as toKitAuth, r as ToKitAuthOptions, t as KitAuth } from "./kit-51JtMxsn.mjs";
5
+ export { type BetterAuthLike, type BetterAuthPermissionsProvider, type BetterAuthProviderOptions, type BetterAuthSessionLike, KitAuth, KitAuthEngine, PermissionsAuthProvider, type PermissionsSubject, ProviderRoleOptions, RoleMapper, type SubjectIdentity, SubjectLookupFn, ToKitAuthOptions, asBetterAuthSession, betterAuthProvider, externalRoles, identity, identityOf, mappedLookup, normalizeRoles, splitRoles, stringField, subjectOf, toKitAuth };
@@ -1,4 +1,4 @@
1
- import { i as stringField, n as normalizeRoles, r as splitRoles, t as identity } from "./contract-Yc5AZuvv.mjs";
2
- import { n as toKitAuth, t as subjectOf } from "./kit-fzXHYb1l.mjs";
3
- import { r as betterAuthProvider, t as asBetterAuthSession } from "./better-auth-NO40ZqSM.mjs";
4
- export { asBetterAuthSession, betterAuthProvider, identity, normalizeRoles, splitRoles, stringField, subjectOf, toKitAuth };
1
+ import { a as splitRoles, i as normalizeRoles, n as identity, o as stringField, r as mappedLookup, t as externalRoles } from "./contract-BganM0fx.mjs";
2
+ import { n as subjectOf, r as toKitAuth, t as identityOf } from "./kit-BM3uosfV.mjs";
3
+ import { r as betterAuthProvider, t as asBetterAuthSession } from "./better-auth-BEmX8qyz.mjs";
4
+ export { asBetterAuthSession, betterAuthProvider, externalRoles, identity, identityOf, mappedLookup, normalizeRoles, splitRoles, stringField, subjectOf, toKitAuth };
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_contract = require("./contract-CPmJVoRx.cjs");
3
- const require_kit = require("./kit-C7tepDB2.cjs");
2
+ const require_contract = require("./contract-Brnu9XXo.cjs");
3
+ const require_kit = require("./kit-BrqnCcDw.cjs");
4
4
  let _xtandard_kit_storage = require("@xtandard/kit/storage");
5
5
  //#region src/auth-provider/jwt.ts
6
6
  /**
@@ -101,11 +101,15 @@ function jwtProvider(options) {
101
101
  });
102
102
  } };
103
103
  if (options.canManage) provider.canManage = options.canManage;
104
+ if (options.lookup) provider.lookupSubject = require_contract.mappedLookup(options.lookup, options.mapRole);
104
105
  return provider;
105
106
  }
106
107
  //#endregion
108
+ exports.externalRoles = require_contract.externalRoles;
107
109
  exports.identity = require_contract.identity;
110
+ exports.identityOf = require_kit.identityOf;
108
111
  exports.jwtProvider = jwtProvider;
112
+ exports.mappedLookup = require_contract.mappedLookup;
109
113
  exports.normalizeRoles = require_contract.normalizeRoles;
110
114
  exports.readToken = readToken;
111
115
  exports.splitRoles = require_contract.splitRoles;
@@ -1 +1 @@
1
- {"version":3,"file":"entry-auth-jwt.cjs","names":["stringField","identity","normalizeRoles"],"sources":["../src/auth-provider/jwt.ts"],"sourcesContent":["/**\n * A Bearer / cookie JWT as a {@link PermissionsAuthProvider} (ADR 0006), verified with `jose` (an\n * optional peer, imported on first use): an HS256 shared secret, or a JWKS (remote URL or inline\n * key set) for asymmetric tokens from an identity provider.\n *\n * An invalid, expired or wrongly-signed token is \"no session\" (`null` → guest / 401), never a 500.\n * A JWKS endpoint that times out is an error (500): it says nothing about the caller.\n *\n * @module\n */\n\nimport { importPeer } from \"@xtandard/kit/storage\";\nimport {\n identity,\n normalizeRoles,\n stringField,\n type PermissionsAuthProvider,\n type ProviderRoleOptions,\n type SubjectIdentity,\n} from \"./contract.ts\";\n\n/** Verified JWT claims. */\nexport type JwtClaims = Record<string, unknown> & {\n sub?: string;\n iss?: string;\n aud?: string | string[];\n exp?: number;\n iat?: number;\n};\n\n/** A JSON Web Key Set (`{ keys: [...] }`). */\nexport interface JsonWebKeySet {\n keys: Record<string, unknown>[];\n}\n\ninterface JwtProviderBase extends ProviderRoleOptions {\n /** Expected `iss`. */\n issuer?: string | string[];\n /** Expected `aud`. */\n audience?: string | string[];\n /** Accepted algorithms. Default: `[\"HS256\"]` with `secret`; the key set's with `jwks`. */\n algorithms?: string[];\n /** Clock skew tolerance, seconds or a `jose` duration string (`\"30s\"`). */\n clockTolerance?: number | string;\n /** Read the token from this cookie when there is no `Authorization: Bearer` header. */\n cookie?: string;\n /** Read `Authorization: Bearer <token>`. Default `true`. */\n header?: boolean;\n /** Claim holding the role(s). Default: `role`, then `roles`. */\n roleClaim?: string;\n /**\n * Map verified claims to a subject. Default: `sub` → id, the role claim, `name`, `email`.\n * Return `null` to treat a valid token as no session (e.g. a machine token without `sub`).\n */\n map?(claims: JwtClaims, request: Request): SubjectIdentity | null | undefined;\n}\n\n/** Options for {@link jwtProvider}: exactly one of `secret` or `jwks`. */\nexport type JwtProviderOptions =\n | (JwtProviderBase & { secret: string | Uint8Array; jwks?: never })\n | (JwtProviderBase & { jwks: string | URL | JsonWebKeySet; secret?: never });\n\ntype Jose = typeof import(\"jose\");\ntype VerifyKey = Parameters<Jose[\"jwtVerify\"]>[1];\n\nconst SUBPATH = \"@xtandard/permissions/auth/jwt\";\n\n/** The token of a request: the Bearer header first, then the cookie. */\nexport function readToken(\n request: Request,\n options: { cookie?: string | undefined; header?: boolean | undefined },\n): string | null {\n if (options.header !== false) {\n const match = /^Bearer\\s+(\\S+)\\s*$/i.exec(request.headers.get(\"authorization\") ?? \"\");\n if (match) return match[1]!;\n }\n if (options.cookie) {\n for (const part of (request.headers.get(\"cookie\") ?? \"\").split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1 || part.slice(0, eq).trim() !== options.cookie) continue;\n const value = part.slice(eq + 1).trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n }\n }\n return null;\n}\n\n/** The default claims → identity mapping. */\nfunction defaultMap(claims: JwtClaims, roleClaim: string | undefined): SubjectIdentity | null {\n const id = stringField(claims, \"sub\");\n if (!id) return null;\n const role = roleClaim ? claims[roleClaim] : (claims.role ?? claims.roles);\n return identity({\n id,\n role: role as string | string[] | undefined,\n name: stringField(claims, \"name\"),\n email: stringField(claims, \"email\"),\n });\n}\n\n/** True for a `jose` error that means \"this token is not valid\" (not an infrastructure failure). */\nfunction isInvalidToken(jose: Jose, error: unknown): boolean {\n return error instanceof jose.errors.JOSEError && !(error instanceof jose.errors.JWKSTimeout);\n}\n\n/**\n * A {@link PermissionsAuthProvider} that verifies a JWT from the request.\n *\n * @example\n * ```ts\n * import { jwtProvider } from \"@xtandard/permissions/auth/jwt\";\n *\n * jwtProvider({ secret: process.env.JWT_SECRET!, issuer: \"my-app\", cookie: \"token\" });\n * jwtProvider({ jwks: \"https://idp.example.com/.well-known/jwks.json\", audience: \"api\" });\n * ```\n */\nexport function jwtProvider(options: JwtProviderOptions): PermissionsAuthProvider {\n if (!options.secret && !options.jwks) {\n throw new TypeError(\"jwtProvider: pass `secret` (HS256) or `jwks`\");\n }\n if (options.secret && options.jwks) {\n throw new TypeError(\"jwtProvider: pass either `secret` or `jwks`, not both\");\n }\n let ready: Promise<{ jose: Jose; key: VerifyKey }> | undefined;\n const load = () =>\n (ready ??= importPeer(\"jose\", SUBPATH, () => import(\"jose\")).then((jose) => {\n let key: VerifyKey;\n if (options.secret !== undefined) {\n key =\n typeof options.secret === \"string\"\n ? new TextEncoder().encode(options.secret)\n : options.secret;\n } else if (typeof options.jwks === \"string\" || options.jwks instanceof URL) {\n key = jose.createRemoteJWKSet(new URL(options.jwks));\n } else {\n key = jose.createLocalJWKSet(options.jwks as Parameters<Jose[\"createLocalJWKSet\"]>[0]);\n }\n return { jose, key };\n })).catch((error: unknown) => {\n ready = undefined; // a missing peer may be installed later; don't cache the failure\n throw error;\n });\n\n const algorithms = options.algorithms ?? (options.secret !== undefined ? [\"HS256\"] : undefined);\n const verifyOptions: Record<string, unknown> = {};\n if (algorithms) verifyOptions.algorithms = algorithms;\n if (options.issuer !== undefined) verifyOptions.issuer = options.issuer;\n if (options.audience !== undefined) verifyOptions.audience = options.audience;\n if (options.clockTolerance !== undefined) verifyOptions.clockTolerance = options.clockTolerance;\n\n const provider: PermissionsAuthProvider = {\n async getSubject(request) {\n const token = readToken(request, options);\n if (!token) return null;\n const { jose, key } = await load();\n let claims: JwtClaims;\n try {\n claims = (await jose.jwtVerify(token, key, verifyOptions)).payload as JwtClaims;\n } catch (error) {\n if (isInvalidToken(jose, error)) return null;\n throw error;\n }\n const mapped = options.map\n ? options.map(claims, request)\n : defaultMap(claims, options.roleClaim);\n if (!mapped) return null;\n return identity({ ...mapped, role: normalizeRoles(mapped.role, options.mapRole) });\n },\n };\n if (options.canManage) provider.canManage = options.canManage;\n return provider;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiEA,MAAM,UAAU;;AAGhB,SAAgB,UACd,SACA,SACe;CACf,IAAI,QAAQ,WAAW,OAAO;EAC5B,MAAM,QAAQ,uBAAuB,KAAK,QAAQ,QAAQ,IAAI,eAAe,KAAK,EAAE;EACpF,IAAI,OAAO,OAAO,MAAM;CAC1B;CACA,IAAI,QAAQ,QACV,KAAK,MAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK,IAAI,MAAM,GAAG,GAAG;EACnE,MAAM,KAAK,KAAK,QAAQ,GAAG;EAC3B,IAAI,OAAO,MAAM,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK,MAAM,QAAQ,QAAQ;EAC9D,MAAM,QAAQ,KAAK,MAAM,KAAK,CAAC,EAAE,KAAK;EACtC,IAAI,CAAC,OAAO,OAAO;EACnB,IAAI;GACF,OAAO,mBAAmB,KAAK;EACjC,QAAQ;GACN,OAAO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Aa;CAC3C,IAAI,QAAQ,WAAW,KAAA,GAAW,cAAc,SAAS,QAAQ;CACjE,IAAI,QAAQ,aAAa,KAAA,GAAW,cAAc,WAAW,QAAQ;CACrE,IAAI,QAAQ,mBAAmB,KAAA,GAAW,cAAc,iBAAiB,QAAQ;CAEjF,MAAM,WAAoC,EACxC,MAAM,WAAW,SAAS;EACxB,MAAM,QAAQ,UAAU,SAAS,OAAO;EACxC,IAAI,CAAC,OAAO,OAAO;EACnB,MAAM,EAAE,MAAM,QAAQ,MAAM,KAAK;EACjC,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,KAAK,UAAU,OAAO,KAAK,aAAa,GAAG;EAC7D,SAAS,OAAO;GACd,IAAI,eAAe,MAAM,KAAK,GAAG,OAAO;GACxC,MAAM;EACR;EACA,MAAM,SAAS,QAAQ,MACnB,QAAQ,IAAI,QAAQ,OAAO,IAC3B,WAAW,QAAQ,QAAQ,SAAS;EACxC,IAAI,CAAC,QAAQ,OAAO;EACpB,OAAOC,iBAAAA,SAAS;GAAE,GAAG;GAAQ,MAAMC,iBAAAA,eAAe,OAAO,MAAM,QAAQ,OAAO;EAAE,CAAC;CACnF,EACF;CACA,IAAI,QAAQ,WAAW,SAAS,YAAY,QAAQ;CACpD,OAAO;AACT"}
1
+ {"version":3,"file":"entry-auth-jwt.cjs","names":["stringField","identity","normalizeRoles","mappedLookup"],"sources":["../src/auth-provider/jwt.ts"],"sourcesContent":["/**\n * A Bearer / cookie JWT as a {@link PermissionsAuthProvider} (ADR 0006), verified with `jose` (an\n * optional peer, imported on first use): an HS256 shared secret, or a JWKS (remote URL or inline\n * key set) for asymmetric tokens from an identity provider.\n *\n * An invalid, expired or wrongly-signed token is \"no session\" (`null` → guest / 401), never a 500.\n * A JWKS endpoint that times out is an error (500): it says nothing about the caller.\n *\n * @module\n */\n\nimport { importPeer } from \"@xtandard/kit/storage\";\nimport {\n identity,\n mappedLookup,\n normalizeRoles,\n stringField,\n type PermissionsAuthProvider,\n type ProviderRoleOptions,\n type SubjectIdentity,\n type SubjectLookupFn,\n} from \"./contract.ts\";\n\n/** Verified JWT claims. */\nexport type JwtClaims = Record<string, unknown> & {\n sub?: string;\n iss?: string;\n aud?: string | string[];\n exp?: number;\n iat?: number;\n};\n\n/** A JSON Web Key Set (`{ keys: [...] }`). */\nexport interface JsonWebKeySet {\n keys: Record<string, unknown>[];\n}\n\ninterface JwtProviderBase extends ProviderRoleOptions {\n /** Expected `iss`. */\n issuer?: string | string[];\n /** Expected `aud`. */\n audience?: string | string[];\n /** Accepted algorithms. Default: `[\"HS256\"]` with `secret`; the key set's with `jwks`. */\n algorithms?: string[];\n /** Clock skew tolerance, seconds or a `jose` duration string (`\"30s\"`). */\n clockTolerance?: number | string;\n /** Read the token from this cookie when there is no `Authorization: Bearer` header. */\n cookie?: string;\n /** Read `Authorization: Bearer <token>`. Default `true`. */\n header?: boolean;\n /** Claim holding the role(s). Default: `role`, then `roles`. */\n roleClaim?: string;\n /**\n * Map verified claims to a subject. Default: `sub` → id, the role claim, `name`, `email`.\n * Return `null` to treat a valid token as no session (e.g. a machine token without `sub`).\n */\n map?(claims: JwtClaims, request: Request): SubjectIdentity | null | undefined;\n /**\n * Look a subject up by id without a token (a token only describes its bearer): your user table\n * or identity provider's admin API. Becomes the provider's `lookupSubject`; `role` is split and\n * mapped like the claims'. ADR 0014.\n */\n lookup?: SubjectLookupFn;\n}\n\n/** Options for {@link jwtProvider}: exactly one of `secret` or `jwks`. */\nexport type JwtProviderOptions =\n | (JwtProviderBase & { secret: string | Uint8Array; jwks?: never })\n | (JwtProviderBase & { jwks: string | URL | JsonWebKeySet; secret?: never });\n\ntype Jose = typeof import(\"jose\");\ntype VerifyKey = Parameters<Jose[\"jwtVerify\"]>[1];\n\nconst SUBPATH = \"@xtandard/permissions/auth/jwt\";\n\n/** The token of a request: the Bearer header first, then the cookie. */\nexport function readToken(\n request: Request,\n options: { cookie?: string | undefined; header?: boolean | undefined },\n): string | null {\n if (options.header !== false) {\n const match = /^Bearer\\s+(\\S+)\\s*$/i.exec(request.headers.get(\"authorization\") ?? \"\");\n if (match) return match[1]!;\n }\n if (options.cookie) {\n for (const part of (request.headers.get(\"cookie\") ?? \"\").split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1 || part.slice(0, eq).trim() !== options.cookie) continue;\n const value = part.slice(eq + 1).trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n }\n }\n return null;\n}\n\n/** The default claims → identity mapping. */\nfunction defaultMap(claims: JwtClaims, roleClaim: string | undefined): SubjectIdentity | null {\n const id = stringField(claims, \"sub\");\n if (!id) return null;\n const role = roleClaim ? claims[roleClaim] : (claims.role ?? claims.roles);\n return identity({\n id,\n role: role as string | string[] | undefined,\n name: stringField(claims, \"name\"),\n email: stringField(claims, \"email\"),\n });\n}\n\n/** True for a `jose` error that means \"this token is not valid\" (not an infrastructure failure). */\nfunction isInvalidToken(jose: Jose, error: unknown): boolean {\n return error instanceof jose.errors.JOSEError && !(error instanceof jose.errors.JWKSTimeout);\n}\n\n/**\n * A {@link PermissionsAuthProvider} that verifies a JWT from the request.\n *\n * @example\n * ```ts\n * import { jwtProvider } from \"@xtandard/permissions/auth/jwt\";\n *\n * jwtProvider({ secret: process.env.JWT_SECRET!, issuer: \"my-app\", cookie: \"token\" });\n * jwtProvider({ jwks: \"https://idp.example.com/.well-known/jwks.json\", audience: \"api\" });\n * ```\n */\nexport function jwtProvider(options: JwtProviderOptions): PermissionsAuthProvider {\n if (!options.secret && !options.jwks) {\n throw new TypeError(\"jwtProvider: pass `secret` (HS256) or `jwks`\");\n }\n if (options.secret && options.jwks) {\n throw new TypeError(\"jwtProvider: pass either `secret` or `jwks`, not both\");\n }\n let ready: Promise<{ jose: Jose; key: VerifyKey }> | undefined;\n const load = () =>\n (ready ??= importPeer(\"jose\", SUBPATH, () => import(\"jose\")).then((jose) => {\n let key: VerifyKey;\n if (options.secret !== undefined) {\n key =\n typeof options.secret === \"string\"\n ? new TextEncoder().encode(options.secret)\n : options.secret;\n } else if (typeof options.jwks === \"string\" || options.jwks instanceof URL) {\n key = jose.createRemoteJWKSet(new URL(options.jwks));\n } else {\n key = jose.createLocalJWKSet(options.jwks as Parameters<Jose[\"createLocalJWKSet\"]>[0]);\n }\n return { jose, key };\n })).catch((error: unknown) => {\n ready = undefined; // a missing peer may be installed later; don't cache the failure\n throw error;\n });\n\n const algorithms = options.algorithms ?? (options.secret !== undefined ? [\"HS256\"] : undefined);\n const verifyOptions: Record<string, unknown> = {};\n if (algorithms) verifyOptions.algorithms = algorithms;\n if (options.issuer !== undefined) verifyOptions.issuer = options.issuer;\n if (options.audience !== undefined) verifyOptions.audience = options.audience;\n if (options.clockTolerance !== undefined) verifyOptions.clockTolerance = options.clockTolerance;\n\n const provider: PermissionsAuthProvider = {\n async getSubject(request) {\n const token = readToken(request, options);\n if (!token) return null;\n const { jose, key } = await load();\n let claims: JwtClaims;\n try {\n claims = (await jose.jwtVerify(token, key, verifyOptions)).payload as JwtClaims;\n } catch (error) {\n if (isInvalidToken(jose, error)) return null;\n throw error;\n }\n const mapped = options.map\n ? options.map(claims, request)\n : defaultMap(claims, options.roleClaim);\n if (!mapped) return null;\n return identity({ ...mapped, role: normalizeRoles(mapped.role, options.mapRole) });\n },\n };\n if (options.canManage) provider.canManage = options.canManage;\n if (options.lookup) provider.lookupSubject = mappedLookup(options.lookup, options.mapRole);\n return provider;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyEA,MAAM,UAAU;;AAGhB,SAAgB,UACd,SACA,SACe;CACf,IAAI,QAAQ,WAAW,OAAO;EAC5B,MAAM,QAAQ,uBAAuB,KAAK,QAAQ,QAAQ,IAAI,eAAe,KAAK,EAAE;EACpF,IAAI,OAAO,OAAO,MAAM;CAC1B;CACA,IAAI,QAAQ,QACV,KAAK,MAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK,IAAI,MAAM,GAAG,GAAG;EACnE,MAAM,KAAK,KAAK,QAAQ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itRoles, r as RoleMapper, s as stringField, t as PermissionsAuthProvider } from "./contract-BMiOmg2f.cjs";
3
- import { a as toKitAuth, i as subjectOf, n as KitAuthEngine, r as ToKitAuthOptions, t as KitAuth } from "./kit-qAROuhOI.cjs";
2
+ import { a as externalRoles, c as normalizeRoles, i as SubjectLookupFn, l as splitRoles, n as ProviderRoleOptions, o as identity, r as RoleMapper, s as mappedLookup, t as PermissionsAuthProvider, u as stringField } from "./contract-BAisPHBw.cjs";
3
+ import { a as subjectOf, i as identityOf, n as KitAuthEngine, o as toKitAuth, r as ToKitAuthOptions, t as KitAuth } from "./kit-DLF7DZrp.cjs";
4
4
  //#region src/auth-provider/jwt.d.ts
5
5
  /** Verified JWT claims. */
6
6
  type JwtClaims = Record<string, unknown> & {
@@ -34,6 +34,12 @@ interface JwtProviderBase extends ProviderRoleOptions {
34
34
  * Return `null` to treat a valid token as no session (e.g. a machine token without `sub`).
35
35
  */
36
36
  map?(claims: JwtClaims, request: Request): SubjectIdentity | null | undefined;
37
+ /**
38
+ * Look a subject up by id without a token (a token only describes its bearer): your user table
39
+ * or identity provider's admin API. Becomes the provider's `lookupSubject`; `role` is split and
40
+ * mapped like the claims'. ADR 0014.
41
+ */
42
+ lookup?: SubjectLookupFn;
37
43
  }
38
44
  /** Options for {@link jwtProvider}: exactly one of `secret` or `jwks`. */
39
45
  type JwtProviderOptions = (JwtProviderBase & {
@@ -61,5 +67,5 @@ declare function readToken(request: Request, options: {
61
67
  */
62
68
  declare function jwtProvider(options: JwtProviderOptions): PermissionsAuthProvider;
63
69
  //#endregion
64
- export { type JsonWebKeySet, type JwtClaims, type JwtProviderOptions, KitAuth, KitAuthEngine, PermissionsAuthProvider, type PermissionsSubject, ProviderRoleOptions, RoleMapper, type SubjectIdentity, ToKitAuthOptions, identity, jwtProvider, normalizeRoles, readToken, splitRoles, stringField, subjectOf, toKitAuth };
70
+ export { type JsonWebKeySet, type JwtClaims, type JwtProviderOptions, KitAuth, KitAuthEngine, PermissionsAuthProvider, type PermissionsSubject, ProviderRoleOptions, RoleMapper, type SubjectIdentity, SubjectLookupFn, ToKitAuthOptions, externalRoles, identity, identityOf, jwtProvider, mappedLookup, normalizeRoles, readToken, splitRoles, stringField, subjectOf, toKitAuth };
65
71
  //# sourceMappingURL=entry-auth-jwt.d.cts.map
@@ -1,6 +1,6 @@
1
1
  import { f as PermissionsSubject, h as SubjectIdentity } from "./catalog-DJcJ3ycq.mjs";
2
- import { a as normalizeRoles, i as identity, n as ProviderRoleOptions, o as splitRoles, r as RoleMapper, s as stringField, t as PermissionsAuthProvider } from "./contract-D32H1t0u.mjs";
3
- import { a as toKitAuth, i as subjectOf, n as KitAuthEngine, r as ToKitAuthOptions, t as KitAuth } from "./kit-DMVBLBI9.mjs";
2
+ import { a as externalRoles, c as normalizeRoles, i as SubjectLookupFn, l as splitRoles, n as ProviderRoleOptions, o as identity, r as RoleMapper, s as mappedLookup, t as PermissionsAuthProvider, u as stringField } from "./contract-D6j-yrBL.mjs";
3
+ import { a as subjectOf, i as identityOf, n as KitAuthEngine, o as toKitAuth, r as ToKitAuthOptions, t as KitAuth } from "./kit-51JtMxsn.mjs";
4
4
  //#region src/auth-provider/jwt.d.ts
5
5
  /** Verified JWT claims. */
6
6
  type JwtClaims = Record<string, unknown> & {
@@ -34,6 +34,12 @@ interface JwtProviderBase extends ProviderRoleOptions {
34
34
  * Return `null` to treat a valid token as no session (e.g. a machine token without `sub`).
35
35
  */
36
36
  map?(claims: JwtClaims, request: Request): SubjectIdentity | null | undefined;
37
+ /**
38
+ * Look a subject up by id without a token (a token only describes its bearer): your user table
39
+ * or identity provider's admin API. Becomes the provider's `lookupSubject`; `role` is split and
40
+ * mapped like the claims'. ADR 0014.
41
+ */
42
+ lookup?: SubjectLookupFn;
37
43
  }
38
44
  /** Options for {@link jwtProvider}: exactly one of `secret` or `jwks`. */
39
45
  type JwtProviderOptions = (JwtProviderBase & {
@@ -61,5 +67,5 @@ declare function readToken(request: Request, options: {
61
67
  */
62
68
  declare function jwtProvider(options: JwtProviderOptions): PermissionsAuthProvider;
63
69
  //#endregion
64
- export { type JsonWebKeySet, type JwtClaims, type JwtProviderOptions, KitAuth, KitAuthEngine, PermissionsAuthProvider, type PermissionsSubject, ProviderRoleOptions, RoleMapper, type SubjectIdentity, ToKitAuthOptions, identity, jwtProvider, normalizeRoles, readToken, splitRoles, stringField, subjectOf, toKitAuth };
70
+ export { type JsonWebKeySet, type JwtClaims, type JwtProviderOptions, KitAuth, KitAuthEngine, PermissionsAuthProvider, type PermissionsSubject, ProviderRoleOptions, RoleMapper, type SubjectIdentity, SubjectLookupFn, ToKitAuthOptions, externalRoles, identity, identityOf, jwtProvider, mappedLookup, normalizeRoles, readToken, splitRoles, stringField, subjectOf, toKitAuth };
65
71
  //# sourceMappingURL=entry-auth-jwt.d.mts.map
@@ -1,5 +1,5 @@
1
- import { i as stringField, n as normalizeRoles, r as splitRoles, t as identity } from "./contract-Yc5AZuvv.mjs";
2
- import { n as toKitAuth, t as subjectOf } from "./kit-fzXHYb1l.mjs";
1
+ import { a as splitRoles, i as normalizeRoles, n as identity, o as stringField, r as mappedLookup, t as externalRoles } from "./contract-BganM0fx.mjs";
2
+ import { n as subjectOf, r as toKitAuth, t as identityOf } from "./kit-BM3uosfV.mjs";
3
3
  import { importPeer } from "@xtandard/kit/storage";
4
4
  //#region src/auth-provider/jwt.ts
5
5
  /**
@@ -100,9 +100,10 @@ function jwtProvider(options) {
100
100
  });
101
101
  } };
102
102
  if (options.canManage) provider.canManage = options.canManage;
103
+ if (options.lookup) provider.lookupSubject = mappedLookup(options.lookup, options.mapRole);
103
104
  return provider;
104
105
  }
105
106
  //#endregion
106
- export { identity, jwtProvider, normalizeRoles, readToken, splitRoles, stringField, subjectOf, toKitAuth };
107
+ export { externalRoles, identity, identityOf, jwtProvider, mappedLookup, normalizeRoles, readToken, splitRoles, stringField, subjectOf, toKitAuth };
107
108
 
108
109
  //# sourceMappingURL=entry-auth-jwt.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"entry-auth-jwt.mjs","names":[],"sources":["../src/auth-provider/jwt.ts"],"sourcesContent":["/**\n * A Bearer / cookie JWT as a {@link PermissionsAuthProvider} (ADR 0006), verified with `jose` (an\n * optional peer, imported on first use): an HS256 shared secret, or a JWKS (remote URL or inline\n * key set) for asymmetric tokens from an identity provider.\n *\n * An invalid, expired or wrongly-signed token is \"no session\" (`null` → guest / 401), never a 500.\n * A JWKS endpoint that times out is an error (500): it says nothing about the caller.\n *\n * @module\n */\n\nimport { importPeer } from \"@xtandard/kit/storage\";\nimport {\n identity,\n normalizeRoles,\n stringField,\n type PermissionsAuthProvider,\n type ProviderRoleOptions,\n type SubjectIdentity,\n} from \"./contract.ts\";\n\n/** Verified JWT claims. */\nexport type JwtClaims = Record<string, unknown> & {\n sub?: string;\n iss?: string;\n aud?: string | string[];\n exp?: number;\n iat?: number;\n};\n\n/** A JSON Web Key Set (`{ keys: [...] }`). */\nexport interface JsonWebKeySet {\n keys: Record<string, unknown>[];\n}\n\ninterface JwtProviderBase extends ProviderRoleOptions {\n /** Expected `iss`. */\n issuer?: string | string[];\n /** Expected `aud`. */\n audience?: string | string[];\n /** Accepted algorithms. Default: `[\"HS256\"]` with `secret`; the key set's with `jwks`. */\n algorithms?: string[];\n /** Clock skew tolerance, seconds or a `jose` duration string (`\"30s\"`). */\n clockTolerance?: number | string;\n /** Read the token from this cookie when there is no `Authorization: Bearer` header. */\n cookie?: string;\n /** Read `Authorization: Bearer <token>`. Default `true`. */\n header?: boolean;\n /** Claim holding the role(s). Default: `role`, then `roles`. */\n roleClaim?: string;\n /**\n * Map verified claims to a subject. Default: `sub` → id, the role claim, `name`, `email`.\n * Return `null` to treat a valid token as no session (e.g. a machine token without `sub`).\n */\n map?(claims: JwtClaims, request: Request): SubjectIdentity | null | undefined;\n}\n\n/** Options for {@link jwtProvider}: exactly one of `secret` or `jwks`. */\nexport type JwtProviderOptions =\n | (JwtProviderBase & { secret: string | Uint8Array; jwks?: never })\n | (JwtProviderBase & { jwks: string | URL | JsonWebKeySet; secret?: never });\n\ntype Jose = typeof import(\"jose\");\ntype VerifyKey = Parameters<Jose[\"jwtVerify\"]>[1];\n\nconst SUBPATH = \"@xtandard/permissions/auth/jwt\";\n\n/** The token of a request: the Bearer header first, then the cookie. */\nexport function readToken(\n request: Request,\n options: { cookie?: string | undefined; header?: boolean | undefined },\n): string | null {\n if (options.header !== false) {\n const match = /^Bearer\\s+(\\S+)\\s*$/i.exec(request.headers.get(\"authorization\") ?? \"\");\n if (match) return match[1]!;\n }\n if (options.cookie) {\n for (const part of (request.headers.get(\"cookie\") ?? \"\").split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1 || part.slice(0, eq).trim() !== options.cookie) continue;\n const value = part.slice(eq + 1).trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n }\n }\n return null;\n}\n\n/** The default claims → identity mapping. */\nfunction defaultMap(claims: JwtClaims, roleClaim: string | undefined): SubjectIdentity | null {\n const id = stringField(claims, \"sub\");\n if (!id) return null;\n const role = roleClaim ? claims[roleClaim] : (claims.role ?? claims.roles);\n return identity({\n id,\n role: role as string | string[] | undefined,\n name: stringField(claims, \"name\"),\n email: stringField(claims, \"email\"),\n });\n}\n\n/** True for a `jose` error that means \"this token is not valid\" (not an infrastructure failure). */\nfunction isInvalidToken(jose: Jose, error: unknown): boolean {\n return error instanceof jose.errors.JOSEError && !(error instanceof jose.errors.JWKSTimeout);\n}\n\n/**\n * A {@link PermissionsAuthProvider} that verifies a JWT from the request.\n *\n * @example\n * ```ts\n * import { jwtProvider } from \"@xtandard/permissions/auth/jwt\";\n *\n * jwtProvider({ secret: process.env.JWT_SECRET!, issuer: \"my-app\", cookie: \"token\" });\n * jwtProvider({ jwks: \"https://idp.example.com/.well-known/jwks.json\", audience: \"api\" });\n * ```\n */\nexport function jwtProvider(options: JwtProviderOptions): PermissionsAuthProvider {\n if (!options.secret && !options.jwks) {\n throw new TypeError(\"jwtProvider: pass `secret` (HS256) or `jwks`\");\n }\n if (options.secret && options.jwks) {\n throw new TypeError(\"jwtProvider: pass either `secret` or `jwks`, not both\");\n }\n let ready: Promise<{ jose: Jose; key: VerifyKey }> | undefined;\n const load = () =>\n (ready ??= importPeer(\"jose\", SUBPATH, () => import(\"jose\")).then((jose) => {\n let key: VerifyKey;\n if (options.secret !== undefined) {\n key =\n typeof options.secret === \"string\"\n ? new TextEncoder().encode(options.secret)\n : options.secret;\n } else if (typeof options.jwks === \"string\" || options.jwks instanceof URL) {\n key = jose.createRemoteJWKSet(new URL(options.jwks));\n } else {\n key = jose.createLocalJWKSet(options.jwks as Parameters<Jose[\"createLocalJWKSet\"]>[0]);\n }\n return { jose, key };\n })).catch((error: unknown) => {\n ready = undefined; // a missing peer may be installed later; don't cache the failure\n throw error;\n });\n\n const algorithms = options.algorithms ?? (options.secret !== undefined ? [\"HS256\"] : undefined);\n const verifyOptions: Record<string, unknown> = {};\n if (algorithms) verifyOptions.algorithms = algorithms;\n if (options.issuer !== undefined) verifyOptions.issuer = options.issuer;\n if (options.audience !== undefined) verifyOptions.audience = options.audience;\n if (options.clockTolerance !== undefined) verifyOptions.clockTolerance = options.clockTolerance;\n\n const provider: PermissionsAuthProvider = {\n async getSubject(request) {\n const token = readToken(request, options);\n if (!token) return null;\n const { jose, key } = await load();\n let claims: JwtClaims;\n try {\n claims = (await jose.jwtVerify(token, key, verifyOptions)).payload as JwtClaims;\n } catch (error) {\n if (isInvalidToken(jose, error)) return null;\n throw error;\n }\n const mapped = options.map\n ? options.map(claims, request)\n : defaultMap(claims, options.roleClaim);\n if (!mapped) return null;\n return identity({ ...mapped, role: normalizeRoles(mapped.role, options.mapRole) });\n },\n };\n if (options.canManage) provider.canManage = options.canManage;\n return provider;\n}\n"],"mappings":";;;;;;;;;;;;;;AAiEA,MAAM,UAAU;;AAGhB,SAAgB,UACd,SACA,SACe;CACf,IAAI,QAAQ,WAAW,OAAO;EAC5B,MAAM,QAAQ,uBAAuB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ourcesContent":["/**\n * A Bearer / cookie JWT as a {@link PermissionsAuthProvider} (ADR 0006), verified with `jose` (an\n * optional peer, imported on first use): an HS256 shared secret, or a JWKS (remote URL or inline\n * key set) for asymmetric tokens from an identity provider.\n *\n * An invalid, expired or wrongly-signed token is \"no session\" (`null` → guest / 401), never a 500.\n * A JWKS endpoint that times out is an error (500): it says nothing about the caller.\n *\n * @module\n */\n\nimport { importPeer } from \"@xtandard/kit/storage\";\nimport {\n identity,\n mappedLookup,\n normalizeRoles,\n stringField,\n type PermissionsAuthProvider,\n type ProviderRoleOptions,\n type SubjectIdentity,\n type SubjectLookupFn,\n} from \"./contract.ts\";\n\n/** Verified JWT claims. */\nexport type JwtClaims = Record<string, unknown> & {\n sub?: string;\n iss?: string;\n aud?: string | string[];\n exp?: number;\n iat?: number;\n};\n\n/** A JSON Web Key Set (`{ keys: [...] }`). */\nexport interface JsonWebKeySet {\n keys: Record<string, unknown>[];\n}\n\ninterface JwtProviderBase extends ProviderRoleOptions {\n /** Expected `iss`. */\n issuer?: string | string[];\n /** Expected `aud`. */\n audience?: string | string[];\n /** Accepted algorithms. Default: `[\"HS256\"]` with `secret`; the key set's with `jwks`. */\n algorithms?: string[];\n /** Clock skew tolerance, seconds or a `jose` duration string (`\"30s\"`). */\n clockTolerance?: number | string;\n /** Read the token from this cookie when there is no `Authorization: Bearer` header. */\n cookie?: string;\n /** Read `Authorization: Bearer <token>`. Default `true`. */\n header?: boolean;\n /** Claim holding the role(s). Default: `role`, then `roles`. */\n roleClaim?: string;\n /**\n * Map verified claims to a subject. Default: `sub` → id, the role claim, `name`, `email`.\n * Return `null` to treat a valid token as no session (e.g. a machine token without `sub`).\n */\n map?(claims: JwtClaims, request: Request): SubjectIdentity | null | undefined;\n /**\n * Look a subject up by id without a token (a token only describes its bearer): your user table\n * or identity provider's admin API. Becomes the provider's `lookupSubject`; `role` is split and\n * mapped like the claims'. ADR 0014.\n */\n lookup?: SubjectLookupFn;\n}\n\n/** Options for {@link jwtProvider}: exactly one of `secret` or `jwks`. */\nexport type JwtProviderOptions =\n | (JwtProviderBase & { secret: string | Uint8Array; jwks?: never })\n | (JwtProviderBase & { jwks: string | URL | JsonWebKeySet; secret?: never });\n\ntype Jose = typeof import(\"jose\");\ntype VerifyKey = Parameters<Jose[\"jwtVerify\"]>[1];\n\nconst SUBPATH = \"@xtandard/permissions/auth/jwt\";\n\n/** The token of a request: the Bearer header first, then the cookie. */\nexport function readToken(\n request: Request,\n options: { cookie?: string | undefined; header?: boolean | undefined },\n): string | null {\n if (options.header !== false) {\n const match = /^Bearer\\s+(\\S+)\\s*$/i.exec(request.headers.get(\"authorization\") ?? \"\");\n if (match) return match[1]!;\n }\n if (options.cookie) {\n for (const part of (request.headers.get(\"cookie\") ?? \"\").split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1 || part.slice(0, eq).trim() !== options.cookie) continue;\n const value = part.slice(eq + 1).trim();\n if (!value) return null;\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n }\n }\n return null;\n}\n\n/** The default claims → identity mapping. */\nfunction defaultMap(claims: JwtClaims, roleClaim: string | undefined): SubjectIdentity | null {\n const id = stringField(claims, \"sub\");\n if (!id) return null;\n const role = roleClaim ? claims[roleClaim] : (claims.role ?? claims.roles);\n return identity({\n id,\n role: role as string | string[] | undefined,\n name: stringField(claims, \"name\"),\n email: stringField(claims, \"email\"),\n });\n}\n\n/** True for a `jose` error that means \"this token is not valid\" (not an infrastructure failure). */\nfunction isInvalidToken(jose: Jose, error: unknown): boolean {\n return error instanceof jose.errors.JOSEError && !(error instanceof jose.errors.JWKSTimeout);\n}\n\n/**\n * A {@link PermissionsAuthProvider} that verifies a JWT from the request.\n *\n * @example\n * ```ts\n * import { jwtProvider } from \"@xtandard/permissions/auth/jwt\";\n *\n * jwtProvider({ secret: process.env.JWT_SECRET!, issuer: \"my-app\", cookie: \"token\" });\n * jwtProvider({ jwks: \"https://idp.example.com/.well-known/jwks.json\", audience: \"api\" });\n * ```\n */\nexport function jwtProvider(options: JwtProviderOptions): PermissionsAuthProvider {\n if (!options.secret && !options.jwks) {\n throw new TypeError(\"jwtProvider: pass `secret` (HS256) or `jwks`\");\n }\n if (options.secret && options.jwks) {\n throw new TypeError(\"jwtProvider: pass either `secret` or `jwks`, not both\");\n }\n let ready: Promise<{ jose: Jose; key: VerifyKey }> | undefined;\n const load = () =>\n (ready ??= importPeer(\"jose\", SUBPATH, () => import(\"jose\")).then((jose) => {\n let key: VerifyKey;\n if (options.secret !== undefined) {\n key =\n typeof options.secret === \"string\"\n ? new TextEncoder().encode(options.secret)\n : options.secret;\n } else if (typeof options.jwks === \"string\" || options.jwks instanceof URL) {\n key = jose.createRemoteJWKSet(new URL(options.jwks));\n } else {\n key = jose.createLocalJWKSet(options.jwks as Parameters<Jose[\"createLocalJWKSet\"]>[0]);\n }\n return { jose, key };\n })).catch((error: unknown) => {\n ready = undefined; // a missing peer may be installed later; don't cache the failure\n throw error;\n });\n\n const algorithms = options.algorithms ?? (options.secret !== undefined ? [\"HS256\"] : undefined);\n const verifyOptions: Record<string, unknown> = {};\n if (algorithms) verifyOptions.algorithms = algorithms;\n if (options.issuer !== undefined) verifyOptions.issuer = options.issuer;\n if (options.audience !== undefined) verifyOptions.audience = options.audience;\n if (options.clockTolerance !== undefined) verifyOptions.clockTolerance = options.clockTolerance;\n\n const provider: PermissionsAuthProvider = {\n async getSubject(request) {\n const token = readToken(request, options);\n if (!token) return null;\n const { jose, key } = await load();\n let claims: JwtClaims;\n try {\n claims = (await jose.jwtVerify(token, key, verifyOptions)).payload as JwtClaims;\n } catch (error) {\n if (isInvalidToken(jose, error)) return null;\n throw error;\n }\n const mapped = options.map\n ? options.map(claims, request)\n : defaultMap(claims, options.roleClaim);\n if (!mapped) return null;\n return identity({ ...mapped, role: normalizeRoles(mapped.role, options.mapRole) });\n },\n };\n if (options.canManage) provider.canManage = options.canManage;\n if (options.lookup) provider.lookupSubject = mappedLookup(options.lookup, options.mapRole);\n return provider;\n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