@mnmal-ai/substrate 0.0.0 → 1.0.0-alpha.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 (46) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +118 -1
  3. package/dist/agent-token-BIboWOU0.js +200 -0
  4. package/dist/client.d.ts +782 -0
  5. package/dist/client.js +7 -0
  6. package/dist/cluster-worker.js +35 -0
  7. package/dist/content-type-C7T28xNb.js +25 -0
  8. package/dist/dataset-BXkus75W.js +1527 -0
  9. package/dist/env-utils-B7SGmoeJ.js +21 -0
  10. package/dist/errors-D4vKuwz8.d.ts +130 -0
  11. package/dist/fake-DUVtKVSE.js +36 -0
  12. package/dist/index-D7mSOFlM.d.ts +69 -0
  13. package/dist/pack.d.ts +192 -0
  14. package/dist/pack.js +5 -0
  15. package/dist/plugin-j1jt1l3n.js +3844 -0
  16. package/dist/plugin-t2g2wX0b.d.ts +1568 -0
  17. package/dist/proposals-bootstrap.js +37 -0
  18. package/dist/proposals.config.schema.json +20 -0
  19. package/dist/proposals.d.ts +118 -0
  20. package/dist/proposals.default-config.json +4 -0
  21. package/dist/proposals.js +4 -0
  22. package/dist/recall-bootstrap.js +451 -0
  23. package/dist/recall.config.schema.json +232 -0
  24. package/dist/recall.d.ts +1981 -0
  25. package/dist/recall.default-config.json +4 -0
  26. package/dist/recall.js +5 -0
  27. package/dist/repl-C52wyfMs.js +2213 -0
  28. package/dist/row-ByLFE2Wx.d.ts +719 -0
  29. package/dist/row-DK7lPZVe.js +732 -0
  30. package/dist/runtime-metrics-DwpDJ8vz.d.ts +159 -0
  31. package/dist/schema-g4FQLr0V.d.ts +433 -0
  32. package/dist/sdk.d.ts +694 -0
  33. package/dist/sdk.js +112 -0
  34. package/dist/src-C4DzaIQZ.js +837 -0
  35. package/dist/src-CrEgiMJQ.js +1015 -0
  36. package/dist/src-CzxvmhFn.js +2327 -0
  37. package/dist/src-D88LvCX8.js +1797 -0
  38. package/dist/src-D91yij6C.js +13523 -0
  39. package/dist/src-DuopV8u7.js +2408 -0
  40. package/dist/substrate-admin.js +808 -0
  41. package/dist/substrate.js +5477 -0
  42. package/dist/testing.d.ts +1240 -0
  43. package/dist/testing.js +702 -0
  44. package/dist/types-8c0gtnd2.d.ts +35 -0
  45. package/dist/ws-C72iVS5T.d.ts +143 -0
  46. package/package.json +117 -4
@@ -0,0 +1,732 @@
1
+ import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
+ //#region ../../packages/substrate-policy/src/encoding.ts
3
+ /**
4
+ * Comma-separated string-list encoding. Spec §5.12.
5
+ *
6
+ * The `_system` namespace stores `Key.namespaces`, `Key.capabilities`,
7
+ * `Invite.namespaces`, and `Invite.capabilities` as comma-separated
8
+ * scalar strings rather than list-typed fields. The two helpers below are the
9
+ * only allowed encode/decode path — use sites must NOT hand-roll `.split(',')`
10
+ * because the empty-input → `[]` rule lives here.
11
+ */
12
+ /**
13
+ * Canonicalise a string array for persistence. Trims each entry, rejects
14
+ * embedded commas (no quoting in the substrate column), and joins with `,`.
15
+ * Empty input returns `''` — keeping the column non-null and trivially
16
+ * round-trippable through `decodeList`.
17
+ */
18
+ function encodeList(items) {
19
+ const out = [];
20
+ for (const raw of items) {
21
+ const item = raw.trim();
22
+ if (item.length === 0) continue;
23
+ if (item.includes(",")) throw new Error(`encodeList: item '${item}' contains a comma — embedded commas are not supported`);
24
+ out.push(item);
25
+ }
26
+ return out.join(",");
27
+ }
28
+ /**
29
+ * Inverse of `encodeList`. Accepts the stored scalar (possibly `''` for an
30
+ * empty list), splits on `,`, trims, drops empties. Non-string inputs — the
31
+ * dataset shouldn't emit these, but defence-in-depth — yield `[]`.
32
+ */
33
+ function decodeList(raw) {
34
+ if (typeof raw !== "string" || raw.length === 0) return [];
35
+ const out = [];
36
+ for (const part of raw.split(",")) {
37
+ const trimmed = part.trim();
38
+ if (trimmed.length === 0) continue;
39
+ out.push(trimmed);
40
+ }
41
+ return out;
42
+ }
43
+
44
+ //#endregion
45
+ //#region ../../packages/substrate-policy/src/grant.ts
46
+ /**
47
+ * The capabilities this grant confers in `ns`.
48
+ *
49
+ * An EXPLICIT entry beats the wildcard, which is what makes
50
+ * `--ns '*:read,tasks:read+mutate'` mean the obvious thing — read everywhere,
51
+ * and also write tasks — rather than being ambiguous about which entry wins.
52
+ */
53
+ function capabilitiesFor(grant, ns) {
54
+ return grant.get(ns) ?? grant.get("*") ?? /* @__PURE__ */ new Set();
55
+ }
56
+ /** The flat form, expanded. This is the cross product, stated as a map. */
57
+ function expandFlat(namespaces, capabilities) {
58
+ const caps = new Set(capabilities);
59
+ const out = /* @__PURE__ */ new Map();
60
+ for (const ns of namespaces) out.set(ns, caps);
61
+ return out;
62
+ }
63
+ /**
64
+ * Parses the CLI/route entry list. An entry without `:` takes
65
+ * `defaultCapabilities`, so a bare `--ns notes` keeps its flat meaning.
66
+ *
67
+ * @throws Error naming the entry when one has an empty namespace or no
68
+ * capabilities.
69
+ */
70
+ function parseGrantEntries(entries, defaultCapabilities) {
71
+ const out = /* @__PURE__ */ new Map();
72
+ for (const raw of entries) {
73
+ const entry = raw.trim();
74
+ if (entry.length === 0) continue;
75
+ const colon = entry.indexOf(":");
76
+ if (colon === -1) {
77
+ out.set(entry, new Set(defaultCapabilities));
78
+ continue;
79
+ }
80
+ const ns = entry.slice(0, colon).trim();
81
+ const caps = entry.slice(colon + 1).split("+").map((c) => c.trim()).filter((c) => c.length > 0);
82
+ if (ns.length === 0 || caps.length === 0) throw new Error(`invalid grant entry '${entry}': expected '<namespace>' or '<namespace>:<cap>[+<cap>...]'`);
83
+ out.set(ns, new Set(caps));
84
+ }
85
+ return out;
86
+ }
87
+ /**
88
+ * The reason this entry list will not parse, or `null` when it will.
89
+ *
90
+ * Validates by calling {@link parseGrantEntries} so the rules cannot drift
91
+ * from the parser. The message is the parser's own and carries no fix
92
+ * instruction; each caller appends its own vocabulary.
93
+ */
94
+ function grantEntryError(entries, defaultCapabilities) {
95
+ try {
96
+ parseGrantEntries(entries, defaultCapabilities);
97
+ return null;
98
+ } catch (err) {
99
+ return err instanceof Error ? err.message : String(err);
100
+ }
101
+ }
102
+ /**
103
+ * Back to entry form for storage. An entry whose capabilities equal
104
+ * `defaultCapabilities` emits BARE, so a flat grant round-trips to the exact
105
+ * csv it came from and an operator reading `substrate-admin list` sees no new
106
+ * syntax until someone actually uses it.
107
+ */
108
+ function encodeGrant(grant, defaultCapabilities) {
109
+ const dflt = new Set(defaultCapabilities);
110
+ const out = [];
111
+ for (const [ns, caps] of grant) out.push(sameSet(caps, dflt) ? ns : `${ns}:${[...caps].sort().join("+")}`);
112
+ return out;
113
+ }
114
+ /**
115
+ * Claim ∩ row, per namespace.
116
+ *
117
+ * A wildcard claim (`ns: ['*']`, what agent tokens send) yields the row's
118
+ * grant, via `capabilitiesFor` resolving `'*'` for every namespace the row
119
+ * names.
120
+ */
121
+ function intersectGrants(claim, row) {
122
+ const keys = /* @__PURE__ */ new Set([...claim.keys(), ...row.keys()]);
123
+ const out = /* @__PURE__ */ new Map();
124
+ const emptied = [];
125
+ for (const ns of keys) {
126
+ const claimed = capabilitiesFor(claim, ns);
127
+ const allowed = capabilitiesFor(row, ns);
128
+ const caps = /* @__PURE__ */ new Set();
129
+ for (const c of claimed) if (allowed.has(c)) caps.add(c);
130
+ if (caps.size > 0) out.set(ns, caps);
131
+ else if (ns !== "*") emptied.push(ns);
132
+ }
133
+ if (out.has("*")) for (const ns of emptied) out.set(ns, /* @__PURE__ */ new Set());
134
+ return out;
135
+ }
136
+ /**
137
+ * The flat compatibility view.
138
+ *
139
+ * `namespaces` is every namespace held at ANY level (§8.1) and
140
+ * `capabilities` is the UNION — which is what `withAuth`'s any-namespace
141
+ * pre-check needs. It is deliberately NOT the answer to "what am I granted";
142
+ * `grant` is. Consumers that render this to a human must consult
143
+ * {@link grantIsUniform} first.
144
+ */
145
+ function flattenGrant(grant) {
146
+ const capabilities = /* @__PURE__ */ new Set();
147
+ for (const caps of grant.values()) for (const c of caps) capabilities.add(c);
148
+ return {
149
+ namespaces: [...grant].filter(([, caps]) => caps.size > 0).map(([ns]) => ns),
150
+ capabilities: [...capabilities]
151
+ };
152
+ }
153
+ /**
154
+ * Does every namespace in this grant carry the same capabilities?
155
+ *
156
+ * When false, no single flat capability list is honest, and §8.1 renders
157
+ * `null` rather than picking one.
158
+ */
159
+ function grantIsUniform(grant) {
160
+ let first;
161
+ for (const caps of grant.values()) {
162
+ if (first === void 0) {
163
+ first = caps;
164
+ continue;
165
+ }
166
+ if (!sameSet(first, caps)) return false;
167
+ }
168
+ return true;
169
+ }
170
+ function sameSet(a, b) {
171
+ if (a.size !== b.size) return false;
172
+ for (const v of a) if (!b.has(v)) return false;
173
+ return true;
174
+ }
175
+
176
+ //#endregion
177
+ //#region ../../packages/substrate-policy/src/admin-key.ts
178
+ /** The kernel namespace holding Key, Invite and the admin routes' rows. */
179
+ const SYSTEM_NAMESPACE = "_system";
180
+ /**
181
+ * Does this row count as an ACTIVE ADMIN key? True when unrevoked, with a kid,
182
+ * and its grant confers `adminCapability` in `_system` (explicit entry, else the
183
+ * wildcard) — the same question `requireCapability` asks at dispatch, through
184
+ * the same parser. Admin scoped to another namespace (e.g. `tasks`) does not
185
+ * count.
186
+ */
187
+ function isActiveAdminKeyRow(row, adminCapability) {
188
+ if (row.revokedAt != null) return false;
189
+ const kid = row.kid;
190
+ if (typeof kid !== "string" || kid.length === 0) return false;
191
+ let grant;
192
+ try {
193
+ grant = parseGrantEntries(decodeList(row.namespaces), decodeList(row.capabilities));
194
+ } catch {
195
+ return false;
196
+ }
197
+ return capabilitiesFor(grant, SYSTEM_NAMESPACE).has(adminCapability);
198
+ }
199
+ /**
200
+ * The grant, one line per namespace, in the SAME syntax `--ns` accepts.
201
+ *
202
+ * `tasks:read+mutate` round-trips: paste a rendered line back into `--ns` and
203
+ * it means what it says here.
204
+ *
205
+ * TOTAL, and it has to be: this runs inside a formatter, after the write has
206
+ * already committed. `parseGrantEntries` throws on a malformed entry, and a
207
+ * throw here would lose the operator the record of an operation that SUCCEEDED.
208
+ * An unparseable grant falls back to naming the raw columns and saying so.
209
+ */
210
+ function describeGrant(namespaces, capabilities) {
211
+ let grant;
212
+ try {
213
+ grant = parseGrantEntries(decodeList(namespaces), decodeList(capabilities));
214
+ } catch (err) {
215
+ return [`UNPARSEABLE — stored as namespaces='${namespaces}' capabilities='${capabilities}'`, `(${err instanceof Error ? err.message : String(err)})`];
216
+ }
217
+ if (grant.size === 0) return ["(none — this key is granted nothing)"];
218
+ return [...grant].map(([ns, caps]) => `${ns}:${[...caps].join("+")}`);
219
+ }
220
+
221
+ //#endregion
222
+ //#region ../../packages/substrate-policy/src/combinators.ts
223
+ /**
224
+ * Evaluate one policy, catching throws and representing the outcome uniformly
225
+ * so combinators can reason about "genuine deny" vs "caught error" without
226
+ * leaking an extra field onto the public PolicyDecision shape.
227
+ */
228
+ function evaluate(p, ctx, args) {
229
+ try {
230
+ return {
231
+ decision: p(ctx, args),
232
+ caught: false
233
+ };
234
+ } catch {
235
+ return {
236
+ decision: {
237
+ allow: false,
238
+ reason: "policy error"
239
+ },
240
+ caught: true
241
+ };
242
+ }
243
+ }
244
+ /**
245
+ * Build a PolicyDecision while honouring invariant #4: omit `obligations`
246
+ * entirely when the merged array is empty (rather than emitting
247
+ * `obligations: []`).
248
+ */
249
+ function buildAllow(obligations) {
250
+ return obligations.length > 0 ? {
251
+ allow: true,
252
+ obligations
253
+ } : { allow: true };
254
+ }
255
+ /**
256
+ * AND combinator. Allow iff every policy allows; short-circuits on first deny.
257
+ * Empty `and()` is the identity element and returns allow (per §4.4).
258
+ */
259
+ function and(...policies) {
260
+ return (ctx, args) => {
261
+ const obligations = [];
262
+ for (const p of policies) {
263
+ const { decision } = evaluate(p, ctx, args);
264
+ if (!decision.allow) return decision;
265
+ if (decision.obligations && decision.obligations.length > 0) obligations.push(...decision.obligations);
266
+ }
267
+ return buildAllow(obligations);
268
+ };
269
+ }
270
+ /**
271
+ * OR combinator. Allow iff any policy allows; short-circuits on first allow.
272
+ * When all deny, the LAST deny's reason is returned — EXCEPT a caught
273
+ * `'policy error'` from any position always wins over sibling deny reasons
274
+ * (invariant #2).
275
+ */
276
+ function or(...policies) {
277
+ return (ctx, args) => {
278
+ if (policies.length === 0) return {
279
+ allow: false,
280
+ reason: "or(): no policies"
281
+ };
282
+ let sawCaught = false;
283
+ let lastDecision = null;
284
+ for (const p of policies) {
285
+ const { decision, caught } = evaluate(p, ctx, args);
286
+ if (decision.allow) return buildAllow(decision.obligations && decision.obligations.length > 0 ? [...decision.obligations] : []);
287
+ if (caught) sawCaught = true;
288
+ lastDecision = decision;
289
+ }
290
+ if (sawCaught) return {
291
+ allow: false,
292
+ reason: "policy error"
293
+ };
294
+ return lastDecision;
295
+ };
296
+ }
297
+ /**
298
+ * NOT combinator. Inverts allow/deny, EXCEPT caught errors propagate through
299
+ * unchanged (invariant #2). Preserves the inner decision's `reason` on the
300
+ * returned deny so callers can see it; omits `reason` entirely when the inner
301
+ * allow had no reason (invariant #5).
302
+ */
303
+ function not(p) {
304
+ return (ctx, args) => {
305
+ const { decision, caught } = evaluate(p, ctx, args);
306
+ if (caught) return {
307
+ allow: false,
308
+ reason: "policy error"
309
+ };
310
+ if (decision.allow) return decision.reason !== void 0 ? {
311
+ allow: false,
312
+ reason: decision.reason
313
+ } : { allow: false };
314
+ return decision.reason !== void 0 ? {
315
+ allow: true,
316
+ reason: decision.reason
317
+ } : { allow: true };
318
+ };
319
+ }
320
+
321
+ //#endregion
322
+ //#region ../../packages/substrate-policy/src/key-guards.ts
323
+ /**
324
+ * Shared refusal rules for mutating a `_system/Key`, used by both the
325
+ * `substrate-admin` CLI and the key routes so the lockout guard cannot drift.
326
+ *
327
+ * The READ is deliberately not shared: the CLI reads inside its own
328
+ * `withTransaction`; the route reads through `engine.query` so the registry
329
+ * interceptor fires. Each caller gathers the facts and hands them here.
330
+ *
331
+ * Refusals are RETURNED, not thrown. The CLI maps them to its exit codes and
332
+ * the route maps them to HTTP statuses; a shared thrower would force one
333
+ * caller's error vocabulary onto the other.
334
+ */
335
+ /** Normalise a `revokedAt` cell to an ISO string, or null when the key is live. */
336
+ function revokedAtIso(value) {
337
+ if (value === null || value === void 0) return null;
338
+ if (value instanceof Date) return value.toISOString();
339
+ const s = String(value);
340
+ return s.length === 0 ? null : s;
341
+ }
342
+ /**
343
+ * The revoke verdict.
344
+ *
345
+ * `activeAdminKids` is every kid that {@link isActiveAdminKeyRow} accepts,
346
+ * gathered by the caller. Passing an INCOMPLETE list silently weakens the
347
+ * lockout guard, so callers must read the whole key table, never a page of it.
348
+ */
349
+ function checkRevocable(input) {
350
+ if (!input.exists) return {
351
+ code: "unknown_kid",
352
+ message: `no Key with kid ${input.kid}`
353
+ };
354
+ const already = revokedAtIso(input.existingRevokedAt);
355
+ if (already !== null) return {
356
+ code: "already_revoked",
357
+ message: `Key ${input.kid} already revoked at ${already}`,
358
+ revokedAt: already
359
+ };
360
+ if (input.activeAdminKids.length === 1 && input.activeAdminKids[0] === input.kid) return {
361
+ code: "last_active_admin",
362
+ message: `refusing to revoke the last active admin Key (${input.kid}). Rotate instead via \`substrate-admin rotate\`.`
363
+ };
364
+ return null;
365
+ }
366
+ /** Does `granted` already cover `item`? A `*` grant covers everything. */
367
+ function grantCovers(granted, item) {
368
+ return granted.includes("*") || granted.includes(item);
369
+ }
370
+ /**
371
+ * Entries in `next` that `prev` did not already grant.
372
+ *
373
+ * This — not "is the new set a strict superset" — is the test that matters. A
374
+ * lateral change like `tasks` -> `notes` is neither a superset nor a subset,
375
+ * yet it hands the key an authority it did not hold. Empty result means the
376
+ * change grants nothing new, i.e. it narrows, and narrowing needs no flag.
377
+ */
378
+ function newlyGranted(prev, next) {
379
+ return next.filter((item) => !grantCovers(prev, item));
380
+ }
381
+ /**
382
+ * Entries in `next` that `prev` did not already grant, as `(ns, cap)` PAIRS
383
+ * (spec §6). A wildcard entry in `prev` covers any namespace at the
384
+ * capabilities it conferred. A pure narrowing yields the empty set.
385
+ *
386
+ * Returns entries GROUPED BY NAMESPACE in the CLI's own spelling —
387
+ * `recall:read+mutate`, not `recall:read, recall:mutate` — for the operator-
388
+ * facing refusal message.
389
+ */
390
+ function newlyGrantedPairs(prev, next) {
391
+ const covered = (ns, cap) => {
392
+ const direct = prev[ns];
393
+ if (Array.isArray(direct) && direct.includes(cap)) return true;
394
+ const wild = prev["*"];
395
+ return Array.isArray(wild) && wild.includes(cap);
396
+ };
397
+ const byNs = /* @__PURE__ */ new Map();
398
+ for (const [ns, caps] of Object.entries(next)) for (const cap of caps) {
399
+ if (covered(ns, cap)) continue;
400
+ const bucket = byNs.get(ns);
401
+ if (bucket === void 0) byNs.set(ns, [cap]);
402
+ else bucket.push(cap);
403
+ }
404
+ return [...byNs.entries()].map(([ns, caps]) => `${ns}:${[...caps].sort().join("+")}`).sort();
405
+ }
406
+ /**
407
+ * Parse an entry list + default capabilities, or `null` when it will not parse.
408
+ * Never throws: a malformed grant becomes a returned refusal, not an exception.
409
+ */
410
+ function tryParseGrant(entries, defaultCapabilities) {
411
+ try {
412
+ return parseGrantEntries(entries, defaultCapabilities);
413
+ } catch {
414
+ return null;
415
+ }
416
+ }
417
+ /** The `ns -> caps` shape {@link newlyGrantedPairs} compares. */
418
+ function grantAsRecord(grant) {
419
+ return Object.fromEntries([...grant].map(([ns, caps]) => [ns, [...caps]]));
420
+ }
421
+ /**
422
+ * Does this grant confer `capability` in ANY namespace?
423
+ *
424
+ * Deliberately NOT scoped to `_system` the way the lockout floor is. The floor
425
+ * asks "can this key administer the DEPLOYMENT"; the opt-in gate asks "is
426
+ * authority named `admin` being handed out" anywhere. Scoping the gate would
427
+ * make the namespace syntax a way around it.
428
+ */
429
+ function confersAnywhere$1(grant, capability) {
430
+ for (const caps of grant.values()) if (caps.has(capability)) return true;
431
+ return false;
432
+ }
433
+ /**
434
+ * Does this entry list confer `capability` in any namespace?
435
+ *
436
+ * The shared predicate behind the `--allow-admin` / `allowAdmin` opt-in, so
437
+ * `register` (CLI and route) and `update` cannot answer it differently. Reads
438
+ * the parsed grant, not the flat list, so `--ns '_system:admin' --caps read`
439
+ * still trips it.
440
+ *
441
+ * Returns `true` on an unparseable list: this is a confirmation gate, so the
442
+ * safe failure is asking for confirmation, never handing a privilege over
443
+ * unasked.
444
+ */
445
+ function grantEntriesConfer(entries, defaultCapabilities, capability) {
446
+ const grant = tryParseGrant(entries, defaultCapabilities);
447
+ return grant === null ? true : confersAnywhere$1(grant, capability);
448
+ }
449
+ /**
450
+ * The in-place update verdict. Returns the first refusal, or `null` if allowed.
451
+ *
452
+ * ORDER IS PART OF THE RULE: **unconditional refusals outrank confirmable
453
+ * ones.** One request can trip both the lockout and the widen gate; reporting
454
+ * the confirmable one first sends the operator to add the flag, re-run, and
455
+ * dead-end on the lockout.
456
+ */
457
+ function checkUpdatable(input) {
458
+ if (!input.exists) return {
459
+ code: "unknown_kid",
460
+ message: `no Key with kid ${input.kid}`
461
+ };
462
+ const already = revokedAtIso(input.existingRevokedAt);
463
+ if (already !== null) return {
464
+ code: "already_revoked",
465
+ message: `Key ${input.kid} was revoked at ${already} — update refuses a revoked key.`,
466
+ revokedAt: already
467
+ };
468
+ const prevGrant = tryParseGrant(input.prevNamespaces, input.prevCapabilities);
469
+ const nextGrant = tryParseGrant(input.nextNamespaces, input.nextCapabilities);
470
+ if (prevGrant === null || nextGrant === null) return {
471
+ code: "invalid_grant",
472
+ message: `Key ${input.kid}: ${prevGrant === null ? "the stored" : "the requested"} grant cannot be parsed — expected '<namespace>' or '<namespace>:<cap>[+<cap>...]' per entry.`
473
+ };
474
+ if (capabilitiesFor(prevGrant, "_system").has(input.adminCapability) && !capabilitiesFor(nextGrant, "_system").has(input.adminCapability) && input.activeAdminKids.length === 1 && input.activeAdminKids[0] === input.kid) return {
475
+ code: "last_admin_deadmin",
476
+ message: `refusing to drop '${input.adminCapability}' from the last active admin Key (${input.kid}) — that would lock every operator out of this store.`
477
+ };
478
+ const pairsGranted = newlyGrantedPairs(grantAsRecord(prevGrant), grantAsRecord(nextGrant));
479
+ const namespacesGranted = newlyGranted(input.prevNamespaces, input.nextNamespaces);
480
+ const capabilitiesGranted = newlyGranted(input.prevCapabilities, input.nextCapabilities);
481
+ if (!input.widen && pairsGranted.length > 0) {
482
+ const parts = [`grants +${pairsGranted.join(",")}`];
483
+ return {
484
+ code: "requires_widen",
485
+ message: `update would GRANT authority ${input.kid} does not have (${parts.join("; ")}).`,
486
+ namespacesGranted,
487
+ capabilitiesGranted
488
+ };
489
+ }
490
+ if (confersAnywhere$1(nextGrant, input.adminCapability) && !confersAnywhere$1(prevGrant, input.adminCapability) && !input.allowAdmin) return {
491
+ code: "requires_allow_admin",
492
+ message: "granting the 'admin' capability requires explicit confirmation"
493
+ };
494
+ return null;
495
+ }
496
+
497
+ //#endregion
498
+ //#region ../../packages/substrate-types/src/identity-grant.ts
499
+ function stringsOf(value) {
500
+ if (!Array.isArray(value)) return null;
501
+ return value.filter((v) => typeof v === "string");
502
+ }
503
+ /**
504
+ * The grant this identity carries, or `null` when it claims nothing (no
505
+ * identity, or `grants` absent or not an object — e.g. a bare `{ id }`).
506
+ *
507
+ * An array `grants` passes the `typeof` check and resolves to a table with no
508
+ * real namespace in it, which refuses: fail-closed on malformed data.
509
+ * Non-string capability entries are dropped.
510
+ */
511
+ function grantOf(identity) {
512
+ if (identity === null || identity === void 0) return null;
513
+ const grants = identity.grants;
514
+ if (grants !== null && grants !== void 0 && typeof grants === "object") {
515
+ const out = Object.create(null);
516
+ for (const [ns, caps] of Object.entries(grants)) out[ns] = stringsOf(caps) ?? [];
517
+ return out;
518
+ }
519
+ return null;
520
+ }
521
+ /** An OWN entry only: a grant built as a plain object literal still inherits `toString`. */
522
+ function entry(resolved, ns) {
523
+ return Object.hasOwn(resolved, ns) ? resolved[ns] : void 0;
524
+ }
525
+ /**
526
+ * Capabilities conferred in `ns` — explicit entry, else the wildcard.
527
+ *
528
+ * Restates `@mnmal-ai/substrate-policy`'s `grant.ts` `capabilitiesFor` at the zero-dep layer;
529
+ * substrate-policy's `test/grant-parity.test.ts` pins the two to identical verdicts.
530
+ */
531
+ function grantedIn(resolved, ns) {
532
+ if (resolved === null) return [];
533
+ return entry(resolved, ns) ?? entry(resolved, "*") ?? [];
534
+ }
535
+ /** Does the grant name `ns` at all, explicitly or by wildcard? */
536
+ function coversNamespace(resolved, ns) {
537
+ if (resolved === null) return false;
538
+ return entry(resolved, ns) !== void 0 || entry(resolved, "*") !== void 0;
539
+ }
540
+ /**
541
+ * Is `capability` conferred in ANY namespace?
542
+ *
543
+ * Only for the route gate, which runs before any frame is parsed and so has
544
+ * no namespace. For "what am I granted in `ns`", use `grantedIn`.
545
+ */
546
+ function confersAnywhere(resolved, capability) {
547
+ if (resolved === null) return false;
548
+ for (const caps of Object.values(resolved)) if (caps.includes(capability)) return true;
549
+ return false;
550
+ }
551
+ /** Every capability conferred anywhere — the union, for error messages only. */
552
+ function allCapabilities(resolved) {
553
+ return resolved === null ? [] : [...new Set(Object.values(resolved).flat())];
554
+ }
555
+
556
+ //#endregion
557
+ //#region ../../packages/substrate-policy/src/primitives.ts
558
+ /**
559
+ * Always allows. Useful as an explicit identity element for `and(...)` and as a
560
+ * default for resolvers that have no access constraints.
561
+ */
562
+ function allowAll() {
563
+ return () => ({ allow: true });
564
+ }
565
+ /**
566
+ * Always denies. Reason defaults to `'denyAll'` when none is supplied so the
567
+ * caller surface always has something to log.
568
+ */
569
+ function denyAll(reason) {
570
+ const finalReason = reason ?? "denyAll";
571
+ return () => ({
572
+ allow: false,
573
+ reason: finalReason
574
+ });
575
+ }
576
+ /**
577
+ * Returns a suffix for a no-identity refusal saying the deployment has auth
578
+ * disabled, so the reader stops checking a credential that was never examined.
579
+ *
580
+ * Only appended when `authEnabled` is explicitly `false`: undefined means the
581
+ * transport did not say, and a guess would point at the wrong layer.
582
+ */
583
+ function authDisabledSuffix(authEnabled) {
584
+ return authEnabled === false ? " — and this deployment has auth DISABLED, so no credential would have been accepted. Set SUBSTRATE_AUTH_MODE and restart; presenting a key changes nothing until you do." : "";
585
+ }
586
+ /**
587
+ * Allow when the request has a verified identity attached. The most common
588
+ * minimum bar for authenticated resolvers; composes with role / rate / row
589
+ * policies via `and(...)`.
590
+ */
591
+ function requireIdentity() {
592
+ return (ctx) => ctx.identity !== null ? { allow: true } : {
593
+ allow: false,
594
+ reason: `requireIdentity: no identity${authDisabledSuffix(ctx.authEnabled)}`
595
+ };
596
+ }
597
+ /**
598
+ * Allow when the identity carries the named capability in its
599
+ * `capabilities: string[]` claim. Admin gates on `purge<T>` and other
600
+ * sensitive mutations compose with this. Per §5.12, the capability name
601
+ * comes from `SUBSTRATE_ADMIN_CAPABILITY` (default `'admin'`).
602
+ *
603
+ * Rejects both when no identity is attached and when identity lacks the
604
+ * capability — callers don't need to stack `requireIdentity()` first.
605
+ */
606
+ function requireCapability(name) {
607
+ return (ctx) => {
608
+ const id = ctx.identity;
609
+ if (id === null) return {
610
+ allow: false,
611
+ reason: `requireCapability(${name}): no identity${authDisabledSuffix(ctx.authEnabled)}`
612
+ };
613
+ const grants = id.grants;
614
+ if (grants !== void 0 && grants !== null && typeof grants === "object") {
615
+ const table = grants;
616
+ const caps = table[ctx.namespace] ?? table["*"];
617
+ if (Array.isArray(caps) && caps.includes(name)) return { allow: true };
618
+ return {
619
+ allow: false,
620
+ reason: `requireCapability(${name}): not granted in namespace '${ctx.namespace}'`
621
+ };
622
+ }
623
+ return {
624
+ allow: false,
625
+ reason: `requireCapability(${name}): missing capability`
626
+ };
627
+ };
628
+ }
629
+ /**
630
+ * Allow when the identity's grant covers `ns` — explicit entry or wildcard.
631
+ * Resolved through `grantOf`, the same function the engine gate uses, so the
632
+ * two cannot disagree.
633
+ *
634
+ * Rejects when no identity is attached or when the grant does not cover `ns`;
635
+ * composes with `requireCapability` via `and` for resolver policies that need
636
+ * both a capability and a namespace grant.
637
+ */
638
+ function requireNamespace(ns) {
639
+ return (ctx) => {
640
+ const id = ctx.identity;
641
+ if (id === null) return {
642
+ allow: false,
643
+ reason: `requireNamespace(${ns}): no identity`
644
+ };
645
+ if (!coversNamespace(grantOf(id), ns)) return {
646
+ allow: false,
647
+ reason: `requireNamespace(${ns}): not in allowed namespaces`
648
+ };
649
+ return { allow: true };
650
+ };
651
+ }
652
+ /**
653
+ * Deny dispatches whose autoCRUD verb is in `verbs`; allow everything else.
654
+ * Keys on `ctx.verb` — the semantic verb the engine threads from
655
+ * the registry entry — so the intent survives entry renames. Entries WITHOUT
656
+ * a verb (type entries, custom mutations) are allowed by this primitive;
657
+ * gate those by `ctx.entry` name or compose additional policies.
658
+ *
659
+ * `purge<T>` is stamped `verb: 'delete'` by autoCRUD, so `denyVerbs(['delete'])`
660
+ * covers both soft- and hard-delete surfaces.
661
+ */
662
+ function denyVerbs(verbs, reason) {
663
+ const set = new Set(verbs);
664
+ return (ctx) => ctx.verb !== void 0 && set.has(ctx.verb) ? {
665
+ allow: false,
666
+ reason: reason ?? `denyVerbs: '${ctx.verb}' is denied`
667
+ } : { allow: true };
668
+ }
669
+ /**
670
+ * Allow ONLY dispatches whose autoCRUD verb is in `verbs`.
671
+ * Stricter complement of `denyVerbs`: entries WITHOUT a verb (type entries,
672
+ * custom mutations) are DENIED — an allow-list should not silently pass
673
+ * surfaces it cannot classify. Compose with `or(...)` if reads-via-type-entry
674
+ * must also pass: `or(allowVerbs(['get']), <type-entry policy>)`.
675
+ */
676
+ function allowVerbs(verbs, reason) {
677
+ const set = new Set(verbs);
678
+ return (ctx) => ctx.verb !== void 0 && set.has(ctx.verb) ? { allow: true } : {
679
+ allow: false,
680
+ reason: reason ?? `allowVerbs: '${ctx.verb ?? ctx.entry ?? "unknown"}' not in allow-list`
681
+ };
682
+ }
683
+
684
+ //#endregion
685
+ //#region ../../packages/substrate-policy/src/row.ts
686
+ /**
687
+ * Build a collection-time allow decision carrying a single row-filter
688
+ * obligation. Composes with `and`/`or` like any other policy.
689
+ */
690
+ function row(predicate) {
691
+ return () => ({
692
+ allow: true,
693
+ obligations: [{
694
+ kind: "row-filter",
695
+ predicate
696
+ }]
697
+ });
698
+ }
699
+ /**
700
+ * Type guard for row-filter obligations. Narrows to a predicate over
701
+ * `unknown` rows — callers supply the row array and are responsible for the
702
+ * T↔row relationship (the engine only ever hands rows back as `Row[]`).
703
+ */
704
+ function isRowFilter(obligation) {
705
+ return obligation.kind === "row-filter";
706
+ }
707
+ /**
708
+ * Apply every row-filter obligation on `decision` to `rows`, in insertion
709
+ * order. Per §4.4, row-scoped denies are silent — returning false OR throwing
710
+ * drops the row without surfacing a reason. A decision without obligations
711
+ * returns `rows` unchanged.
712
+ */
713
+ function applyRowFilters(decision, rows, ctx) {
714
+ const obligations = decision.obligations;
715
+ if (!obligations || obligations.length === 0) return rows;
716
+ let current = rows;
717
+ for (const obligation of obligations) {
718
+ if (!isRowFilter(obligation)) continue;
719
+ const predicate = obligation.predicate;
720
+ current = current.filter((item) => {
721
+ try {
722
+ return predicate(ctx, item);
723
+ } catch {
724
+ return false;
725
+ }
726
+ });
727
+ }
728
+ return current;
729
+ }
730
+
731
+ //#endregion
732
+ export { expandFlat as A, not as C, isActiveAdminKeyRow as D, describeGrant as E, parseGrantEntries as F, decodeList as I, encodeList as L, grantEntryError as M, grantIsUniform as N, capabilitiesFor as O, intersectGrants as P, and as S, SYSTEM_NAMESPACE as T, grantCovers as _, denyAll as a, newlyGrantedPairs as b, requireIdentity as c, confersAnywhere as d, coversNamespace as f, checkUpdatable as g, checkRevocable as h, allowVerbs as i, flattenGrant as j, encodeGrant as k, requireNamespace as l, grantedIn as m, row as n, denyVerbs as o, grantOf as p, allowAll as r, requireCapability as s, applyRowFilters as t, allCapabilities as u, grantEntriesConfer as v, or as w, revokedAtIso as x, newlyGranted as y };