@remnic/core 9.24.0 → 9.25.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 (149) hide show
  1. package/dist/access-admin-ops-surface.js +21 -21
  2. package/dist/access-authorization-probe.d.ts +122 -0
  3. package/dist/access-authorization-probe.js +154 -0
  4. package/dist/access-authorization-probe.js.map +1 -0
  5. package/dist/access-boundary.js +21 -21
  6. package/dist/access-cli.js +68 -67
  7. package/dist/access-cli.js.map +1 -1
  8. package/dist/access-http.js +28 -27
  9. package/dist/access-identity-continuity-surface.js +21 -21
  10. package/dist/access-lcm-surface.js +21 -21
  11. package/dist/access-mcp.js +26 -26
  12. package/dist/access-namespace-preflight.js +21 -21
  13. package/dist/access-observe-write-surface.js +21 -21
  14. package/dist/access-operations-batch.js +23 -23
  15. package/dist/access-operations.d.ts +3 -3
  16. package/dist/access-operations.js +24 -24
  17. package/dist/access-recall-concurrency.js +21 -21
  18. package/dist/access-recall-response.js +21 -21
  19. package/dist/access-recall-surface.js +21 -21
  20. package/dist/access-schema.d.ts +76 -76
  21. package/dist/access-service.js +21 -21
  22. package/dist/access-token-capabilities.d.ts +15 -1
  23. package/dist/access-token-capabilities.js +3 -1
  24. package/dist/active-recall.js +5 -5
  25. package/dist/auto-sync-5OE5QOZB.js +1 -1
  26. package/dist/briefing.js +7 -7
  27. package/dist/causal-consolidation.js +8 -8
  28. package/dist/{chunk-34RC5RT7.js → chunk-2SA56WMI.js} +4 -4
  29. package/dist/{chunk-NM7SKDZM.js → chunk-3CDMIR3C.js} +2 -2
  30. package/dist/{chunk-V4MAO2Y4.js → chunk-3I35RLJW.js} +17 -5
  31. package/dist/chunk-3I35RLJW.js.map +1 -0
  32. package/dist/{chunk-XBRPEGXF.js → chunk-3UOSVTFR.js} +5 -5
  33. package/dist/{chunk-7IECFM4E.js → chunk-5ZGWA4AG.js} +10 -10
  34. package/dist/{chunk-WNSQOXWS.js → chunk-6LRTGCRV.js} +6 -6
  35. package/dist/{chunk-2NAFR36N.js → chunk-AGR7MGUX.js} +2 -2
  36. package/dist/{chunk-ZLNOX7B2.js → chunk-AL4TZWI3.js} +2 -2
  37. package/dist/{chunk-ECG64R7B.js → chunk-AT6DNUCM.js} +2 -2
  38. package/dist/{chunk-WO7KBATL.js → chunk-CKMO4RDY.js} +2 -2
  39. package/dist/{chunk-DFTCJVXI.js → chunk-DPYYSG6F.js} +8 -8
  40. package/dist/{chunk-MX4TUDMB.js → chunk-FIGDB2HR.js} +2 -2
  41. package/dist/{chunk-NHPROHJD.js → chunk-GNFZFJBJ.js} +2 -2
  42. package/dist/{chunk-TBJV4BZE.js → chunk-IE4HB6O5.js} +10 -10
  43. package/dist/chunk-JMDZDT24.js +38 -0
  44. package/dist/chunk-JMDZDT24.js.map +1 -0
  45. package/dist/{chunk-TGHUJC64.js → chunk-LARPWF3S.js} +3 -3
  46. package/dist/{chunk-M6ZJR6HU.js → chunk-LFHMUWA2.js} +67 -67
  47. package/dist/{chunk-L7DTBRTI.js → chunk-LXKJNUND.js} +2 -2
  48. package/dist/{chunk-BHKDCWGH.js → chunk-MNLZGCM2.js} +7 -7
  49. package/dist/{chunk-3FLPLDIL.js → chunk-MPDX5QMH.js} +2 -2
  50. package/dist/{chunk-7AMFUATK.js → chunk-MZWSOLMT.js} +14 -1
  51. package/dist/chunk-MZWSOLMT.js.map +1 -0
  52. package/dist/{chunk-SGMORUEU.js → chunk-NMGO2HAZ.js} +2 -2
  53. package/dist/{chunk-XHYCPA5C.js → chunk-NVYCTASB.js} +2 -2
  54. package/dist/{chunk-ONHRRJZM.js → chunk-QJAQNXWI.js} +6 -6
  55. package/dist/{chunk-GCKIDUHE.js → chunk-RROMWDDC.js} +22 -33
  56. package/dist/{chunk-GCKIDUHE.js.map → chunk-RROMWDDC.js.map} +1 -1
  57. package/dist/{chunk-4KAIGQVU.js → chunk-SZN6XVFC.js} +2 -2
  58. package/dist/{chunk-RENY3AIW.js → chunk-TG2DJFH7.js} +51 -51
  59. package/dist/{chunk-Z3B4V4YI.js → chunk-THHPDPMS.js} +5 -5
  60. package/dist/{chunk-WMR5WPZU.js → chunk-U37RGPJT.js} +2 -2
  61. package/dist/{chunk-FHH6R3QI.js → chunk-UGH6VPPO.js} +2 -2
  62. package/dist/{chunk-EFYACT2X.js → chunk-VY6SDKWZ.js} +2 -2
  63. package/dist/{chunk-NQ7E27HN.js → chunk-W4ZDTHWZ.js} +3 -3
  64. package/dist/{chunk-2WSX7U2N.js → chunk-X6ROIHFE.js} +2 -2
  65. package/dist/{chunk-AVPXXV6J.js → chunk-XKGPIWGI.js} +4 -4
  66. package/dist/{chunk-7CP7SO32.js → chunk-XTAAG4SQ.js} +11 -11
  67. package/dist/{chunk-A5N6ISRK.js → chunk-ZN4UZWMT.js} +2 -2
  68. package/dist/cli.js +48 -47
  69. package/dist/compounding/engine.js +7 -7
  70. package/dist/config.js +2 -2
  71. package/dist/connectors/codex-materialize-runner.js +7 -7
  72. package/dist/connectors/index.js +10 -10
  73. package/dist/consolidation-provenance-check.js +2 -2
  74. package/dist/contradiction/index.js +1 -1
  75. package/dist/corpus-watermark.js +16 -16
  76. package/dist/entity-retrieval.js +7 -7
  77. package/dist/explicit-capture.js +1 -1
  78. package/dist/extraction.js +1 -1
  79. package/dist/index.d.ts +388 -388
  80. package/dist/index.js +113 -112
  81. package/dist/lcm/index.js +3 -3
  82. package/dist/maintenance/memory-governance.js +7 -7
  83. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +7 -7
  84. package/dist/maintenance/rebuild-memory-projection.js +8 -8
  85. package/dist/namespaces/migrate.js +14 -14
  86. package/dist/namespaces/search.js +6 -6
  87. package/dist/namespaces/storage.js +7 -7
  88. package/dist/offline-sync-impression-drain.js +4 -4
  89. package/dist/operator-doctor-corpus.js +17 -17
  90. package/dist/operator-toolkit.js +22 -22
  91. package/dist/orchestration/maintenance.js +13 -13
  92. package/dist/orchestrator.js +68 -67
  93. package/dist/qmd.js +4 -4
  94. package/dist/resolution-3K27T4VO.js +1 -1
  95. package/dist/resume-bundles.js +2 -2
  96. package/dist/salvage-envelope.js +1 -1
  97. package/dist/schemas.d.ts +76 -76
  98. package/dist/search/factory.js +5 -5
  99. package/dist/search/index.js +9 -9
  100. package/dist/semantic-consolidation.js +12 -12
  101. package/dist/semantic-rule-promotion.js +7 -7
  102. package/dist/semantic-rule-verifier.js +7 -7
  103. package/dist/shared-context/manager.d.ts +8 -8
  104. package/dist/storage.js +6 -6
  105. package/dist/tokens.js +2 -2
  106. package/dist/transfer/types.d.ts +66 -66
  107. package/dist/verified-recall.js +7 -7
  108. package/dist/write-envelope.js +1 -1
  109. package/package.json +2 -2
  110. package/src/access-authorization-probe.ts +43 -0
  111. package/src/access-boundary.ts +2 -31
  112. package/src/access-http.test.ts +76 -0
  113. package/src/access-http.ts +11 -0
  114. package/src/access-surface-catalog.test.ts +4 -3
  115. package/src/access-token-capabilities.ts +31 -0
  116. package/dist/chunk-7AMFUATK.js.map +0 -1
  117. package/dist/chunk-V4MAO2Y4.js.map +0 -1
  118. /package/dist/{chunk-34RC5RT7.js.map → chunk-2SA56WMI.js.map} +0 -0
  119. /package/dist/{chunk-NM7SKDZM.js.map → chunk-3CDMIR3C.js.map} +0 -0
  120. /package/dist/{chunk-XBRPEGXF.js.map → chunk-3UOSVTFR.js.map} +0 -0
  121. /package/dist/{chunk-7IECFM4E.js.map → chunk-5ZGWA4AG.js.map} +0 -0
  122. /package/dist/{chunk-WNSQOXWS.js.map → chunk-6LRTGCRV.js.map} +0 -0
  123. /package/dist/{chunk-2NAFR36N.js.map → chunk-AGR7MGUX.js.map} +0 -0
  124. /package/dist/{chunk-ZLNOX7B2.js.map → chunk-AL4TZWI3.js.map} +0 -0
  125. /package/dist/{chunk-ECG64R7B.js.map → chunk-AT6DNUCM.js.map} +0 -0
  126. /package/dist/{chunk-WO7KBATL.js.map → chunk-CKMO4RDY.js.map} +0 -0
  127. /package/dist/{chunk-DFTCJVXI.js.map → chunk-DPYYSG6F.js.map} +0 -0
  128. /package/dist/{chunk-MX4TUDMB.js.map → chunk-FIGDB2HR.js.map} +0 -0
  129. /package/dist/{chunk-NHPROHJD.js.map → chunk-GNFZFJBJ.js.map} +0 -0
  130. /package/dist/{chunk-TBJV4BZE.js.map → chunk-IE4HB6O5.js.map} +0 -0
  131. /package/dist/{chunk-TGHUJC64.js.map → chunk-LARPWF3S.js.map} +0 -0
  132. /package/dist/{chunk-M6ZJR6HU.js.map → chunk-LFHMUWA2.js.map} +0 -0
  133. /package/dist/{chunk-L7DTBRTI.js.map → chunk-LXKJNUND.js.map} +0 -0
  134. /package/dist/{chunk-BHKDCWGH.js.map → chunk-MNLZGCM2.js.map} +0 -0
  135. /package/dist/{chunk-3FLPLDIL.js.map → chunk-MPDX5QMH.js.map} +0 -0
  136. /package/dist/{chunk-SGMORUEU.js.map → chunk-NMGO2HAZ.js.map} +0 -0
  137. /package/dist/{chunk-XHYCPA5C.js.map → chunk-NVYCTASB.js.map} +0 -0
  138. /package/dist/{chunk-ONHRRJZM.js.map → chunk-QJAQNXWI.js.map} +0 -0
  139. /package/dist/{chunk-4KAIGQVU.js.map → chunk-SZN6XVFC.js.map} +0 -0
  140. /package/dist/{chunk-RENY3AIW.js.map → chunk-TG2DJFH7.js.map} +0 -0
  141. /package/dist/{chunk-Z3B4V4YI.js.map → chunk-THHPDPMS.js.map} +0 -0
  142. /package/dist/{chunk-WMR5WPZU.js.map → chunk-U37RGPJT.js.map} +0 -0
  143. /package/dist/{chunk-FHH6R3QI.js.map → chunk-UGH6VPPO.js.map} +0 -0
  144. /package/dist/{chunk-EFYACT2X.js.map → chunk-VY6SDKWZ.js.map} +0 -0
  145. /package/dist/{chunk-NQ7E27HN.js.map → chunk-W4ZDTHWZ.js.map} +0 -0
  146. /package/dist/{chunk-2WSX7U2N.js.map → chunk-X6ROIHFE.js.map} +0 -0
  147. /package/dist/{chunk-AVPXXV6J.js.map → chunk-XKGPIWGI.js.map} +0 -0
  148. /package/dist/{chunk-7CP7SO32.js.map → chunk-XTAAG4SQ.js.map} +0 -0
  149. /package/dist/{chunk-A5N6ISRK.js.map → chunk-ZN4UZWMT.js.map} +0 -0
@@ -2978,3 +2978,79 @@ test("HTTP meetings get returns 400 (not 500) for a malformed percent-encoded id
2978
2978
  await server.stop();
2979
2979
  }
2980
2980
  });
2981
+
2982
+ test("HTTP authorization probe verifies requested operation grants without invoking operations (issue #2129)", async () => {
2983
+ const service = {
2984
+ configRef: parseConfig({ memoryDir: "/tmp/remnic-http-authorization-probe", defaultNamespace: "default" }),
2985
+ } as unknown as EngramAccessService;
2986
+ const server = new EngramAccessHttpServer({
2987
+ service,
2988
+ port: 0,
2989
+ authTokenEntriesGetter: () => [
2990
+ {
2991
+ token: "delegate-token",
2992
+ capabilities: { version: 1, ops: ["recall", "observe", "lcm_compaction_flush"] },
2993
+ },
2994
+ { token: "recall-only-token", capabilities: { version: 1, ops: ["recall"] } },
2995
+ { token: "observe-only-token", capabilities: { version: 1, ops: ["observe"] } },
2996
+ {
2997
+ token: "fleet-scoped-token",
2998
+ capabilities: {
2999
+ version: 1,
3000
+ ops: ["continuity_audit_generate"],
3001
+ namespaces: ["default"],
3002
+ },
3003
+ },
3004
+ ],
3005
+ adminConsoleEnabled: false,
3006
+ });
3007
+ const status = await server.start();
3008
+ const probe = (token: string, operations: string[]) => {
3009
+ const query = new URLSearchParams();
3010
+ for (const operation of operations) query.append("op", operation);
3011
+ return fetch(`http://127.0.0.1:${status.port}/engram/v1/authorization?${query}`, {
3012
+ headers: { authorization: `Bearer ${token}` },
3013
+ });
3014
+ };
3015
+ const delegateOperations = ["recall", "observe", "lcm_compaction_flush"];
3016
+ try {
3017
+ const authorized = await probe("delegate-token", [...delegateOperations, "recall"]);
3018
+ assert.equal(authorized.status, 200);
3019
+ assert.equal(authorized.headers.get("cache-control"), "no-store");
3020
+ assert.deepEqual(await authorized.json(), { authorized: true, operations: delegateOperations });
3021
+
3022
+ const alternateGrant = await probe("observe-only-token", ["namespace_writable"]);
3023
+ assert.equal(alternateGrant.status, 200);
3024
+ await alternateGrant.text();
3025
+
3026
+ const fleetWide = await probe("fleet-scoped-token", ["continuity_audit_generate"]);
3027
+ assert.equal(fleetWide.status, 403);
3028
+ assert.equal(fleetWide.headers.get("cache-control"), "no-store");
3029
+ await fleetWide.text();
3030
+
3031
+ const denied = await probe("recall-only-token", delegateOperations);
3032
+ assert.equal(
3033
+ denied.status,
3034
+ 403,
3035
+ "a token missing any requested operation is rejected without running it",
3036
+ );
3037
+ assert.equal(denied.headers.get("cache-control"), "no-store");
3038
+ await denied.text();
3039
+
3040
+ const wrongToken = await probe("wrong-token", delegateOperations);
3041
+ assert.equal(wrongToken.status, 401);
3042
+ await wrongToken.text();
3043
+
3044
+ const empty = await probe("delegate-token", []);
3045
+ assert.equal(empty.status, 400);
3046
+ assert.equal(empty.headers.get("cache-control"), "no-store");
3047
+ await empty.text();
3048
+
3049
+ const unknown = await probe("delegate-token", ["not_an_operation"]);
3050
+ assert.equal(unknown.status, 400);
3051
+ assert.equal(unknown.headers.get("cache-control"), "no-store");
3052
+ await unknown.text();
3053
+ } finally {
3054
+ await server.stop();
3055
+ }
3056
+ });
@@ -38,6 +38,7 @@ import {
38
38
  import { expandTildePath } from "./utils/path.js";
39
39
  import { projectTagProjectId } from "./coding/coding-namespace.js";
40
40
  import { getOperation, type OperationName } from "./access-boundary.js";
41
+ import { probeOperationAuthorization } from "./access-authorization-probe.js";
41
42
  import { resolveQueryNamespaceWritablePreflight } from "./access-namespace-preflight.js";
42
43
  import {
43
44
  assertOperationAllowed,
@@ -889,6 +890,16 @@ export class EngramAccessHttpServer {
889
890
  return;
890
891
  }
891
892
 
893
+ if (req.method === "GET" && pathname === "/engram/v1/authorization") {
894
+ res.setHeader("cache-control", "no-store");
895
+ this.respondJson(
896
+ res,
897
+ 200,
898
+ probeOperationAuthorization(tokenCapabilityStore.getStore(), parsed.searchParams.getAll("op")),
899
+ );
900
+ return;
901
+ }
902
+
892
903
  if (req.method === "GET" && pathname === "/engram/v1/adapters") {
893
904
  // Issue #1850 round 5 (finding 1): adapter metadata is served after
894
905
  // auth but was NOT op-gated, so a deny-all or narrow-ops token reached
@@ -493,9 +493,9 @@ test("MCP tools/list matches the catalog exactly (no untracked handlers)", async
493
493
  * patterns from the source and compares against HTTP_ROUTES so a new
494
494
  * service-invoking route cannot land without a catalog entry.
495
495
  *
496
- * Infrastructure routes (health, admin console, UI assets, MCP delegate) are
497
- * excluded — they carry no user-validated request envelope. (Adapters was
498
- * migrated into the catalog in issue #1850 round 5.)
496
+ * Infrastructure routes (health, auth capability probes, admin console, UI
497
+ * assets, MCP delegate) are excluded — they do not invoke an access-service
498
+ * method. (Adapters was migrated into the catalog in issue #1850 round 5.)
499
499
  */
500
500
  test("HTTP handler source routes match the catalog (static completeness)", () => {
501
501
  const httpSource = readFileSync(
@@ -534,6 +534,7 @@ test("HTTP handler source routes match the catalog (static completeness)", () =>
534
534
 
535
535
  const INFRA = [
536
536
  /^\/engram\/v1\/health$/,
537
+ /^\/engram\/v1\/authorization$/,
537
538
  /^\/engram\/v1\/admin\//,
538
539
  /^\/engram\/ui/,
539
540
  /^\/mcp$/,
@@ -249,6 +249,37 @@ export function capabilityAllowsOp(caps: TokenCapabilities | undefined | null, o
249
249
  return caps.ops.includes(op);
250
250
  }
251
251
 
252
+ /**
253
+ * The operation policy that all access surfaces use to decide whether a token
254
+ * can invoke an operation.
255
+ */
256
+ export interface OperationAuthorizationPolicy {
257
+ readonly name: string;
258
+ readonly allowedByOps?: readonly string[];
259
+ readonly fleetWide?: boolean;
260
+ }
261
+
262
+ /**
263
+ * Apply an operation's alternate grant and fleet-wide restrictions without
264
+ * invoking its handler.
265
+ */
266
+ export function assertOperationAuthorizationAllowed(
267
+ caps: TokenCapabilities | undefined | null,
268
+ operation: OperationAuthorizationPolicy,
269
+ ): void {
270
+ if (operation.allowedByOps && operation.allowedByOps.length > 0) {
271
+ if (!operation.allowedByOps.some((allowedOperation) => capabilityAllowsOp(caps, allowedOperation))) {
272
+ throw new EngramAccessForbiddenError(`token is not permitted to call operation: ${operation.name}`);
273
+ }
274
+ } else {
275
+ assertOperationAllowed(caps, operation.name);
276
+ }
277
+
278
+ if (operation.fleetWide) {
279
+ assertFleetWideOperationAllowed(caps);
280
+ }
281
+ }
282
+
252
283
  /**
253
284
  * True when `caps` permits `namespace`.
254
285
  * - record ABSENT / namespaces axis ABSENT ⇒ unrestricted (true).
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/access-token-capabilities.ts"],"sourcesContent":["/**\n * Per-token capabilities (issue #1837).\n *\n * A token entry MAY carry an explicit, versioned capabilities record. The\n * record's PRESENCE is mechanically detectable, which is load-bearing for\n * security:\n *\n * - ABSENT `capabilities` field ⇒ a PRE-FEATURE legacy entry (minted\n * before this feature). It is UNRESTRICTED — full access — purely for\n * backward compatibility. This is the ONLY path by which \"full access\"\n * is granted by omission.\n *\n * - PRESENT `capabilities` record (always carries a `version` marker) ⇒ a\n * token minted by the capability-aware path. Even a new token minted\n * without `--ops`/`--namespaces` records an EXPLICIT unrestricted record\n * (`{ version: 1 }`) — a deliberate, auditable choice, never an\n * accidentally-omitted field. Within the record, the two axes follow\n * absent-vs-present semantics:\n * * axis ABSENT (e.g. no `ops` key) ⇒ unrestricted on that axis.\n * * axis PRESENT and empty (`ops: []`) ⇒ deny all (fail-closed).\n * * axis PRESENT and non-empty ⇒ allow only the listed values.\n *\n * Malformed capability input at mint time (bad version, non-array axes,\n * non-string elements, unknown op names against the catalog, malformed\n * namespace values) is REJECTED — a token is never created from invalid\n * input (rule: invalid input rejected, not defaulted).\n *\n * This module owns the pure capability logic (shape validation, allow-list\n * checks) and the per-request AsyncLocalStorage carrying the presenting\n * token's resolved capabilities down to the access boundary. It imports\n * nothing else in the package except the forbidden-error class, so it can be\n * reused by the token store, the boundary, and the HTTP/MCP surfaces without\n * cycles.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { EngramAccessForbiddenError } from \"./access-errors.js\";\n\n/** Current capability-record schema version. */\nexport const TOKEN_CAPABILITIES_VERSION = 1 as const;\n\n/**\n * Versioned capabilities record stored on a token entry. Presence of this\n * record (vs. an absent field) is what distinguishes a capability-aware\n * token from a pre-feature legacy entry.\n */\nexport interface TokenCapabilities {\n readonly version: typeof TOKEN_CAPABILITIES_VERSION;\n /**\n * Operations allow-list. `undefined` (key absent) ⇒ unrestricted on this\n * axis. `[]` ⇒ deny all ops (fail-closed). Non-empty ⇒ allow only listed.\n */\n ops?: string[];\n /**\n * Namespaces allow-list. `undefined` ⇒ unrestricted. `[]` ⇒ deny all.\n * Non-empty ⇒ allow only listed.\n */\n namespaces?: string[];\n}\n\n/**\n * Namespace value validation. Namespace identifiers are flexible (default,\n * team, self, principal-prefixed, project-prefixed) but must never contain\n * whitespace, path separators, traversal segments, or control characters —\n * such values are malformed at mint time and rejected, never silently\n * coerced.\n */\nconst NAMESPACE_VALUE_MAX_LENGTH = 128;\n// Non-empty, no whitespace, no path separators, no control chars. `.` and\n// `..` are rejected separately so legitimate dotted names (e.g. a domain)\n// remain allowed while traversal is not.\nconst NAMESPACE_VALUE_PATTERN = /^[^\\s\\/\\\\\\x00-\\x1F]+$/;\n\n/** True when `value` is an acceptable namespace allow-list entry. */\nexport function isValidNamespaceValue(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length === 0 || value.length > NAMESPACE_VALUE_MAX_LENGTH) {\n return false;\n }\n if (!NAMESPACE_VALUE_PATTERN.test(value)) return false;\n if (value === \".\" || value === \"..\") return false;\n return true;\n}\n\nfunction isStringArray(value: unknown): value is unknown[] {\n return Array.isArray(value) && value.every((v) => typeof v === \"string\");\n}\n\nfunction dedupeSort(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\n/**\n * Parse one axis (ops or namespaces) for PERSISTENCE/LOAD. Returns the\n * cleaned array (deduped, sorted; possibly empty to preserve \"present ⇒\n * fail-closed\") or `undefined` when the key is absent. Throws on a malformed\n * shape (non-array, non-string elements, malformed namespace values). Op\n * validation against the catalog happens only at mint time.\n */\nfunction parseAxis(\n obj: Record<string, unknown>,\n key: \"ops\" | \"namespaces\",\n validateValue: (v: unknown) => boolean,\n valueLabel: string,\n): string[] | undefined {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) return undefined;\n const value = obj[key];\n if (value === undefined || value === null) return undefined;\n if (!isStringArray(value)) {\n throw new Error(`capabilities ${key} must be an array of non-empty strings`);\n }\n const cleaned: string[] = [];\n for (const v of value) {\n if (typeof v !== \"string\" || v.length === 0) {\n throw new Error(`capabilities ${key} must be an array of non-empty strings`);\n }\n if (!validateValue(v)) {\n throw new Error(`capabilities ${key} contains a malformed ${valueLabel}: ${JSON.stringify(v)}`);\n }\n cleaned.push(v);\n }\n // Preserve presence: an explicitly empty array stays [] (fail-closed),\n // NOT coerced to undefined (which would mean unrestricted).\n return dedupeSort(cleaned);\n}\n\n/**\n * Normalize a capabilities record for PERSISTENCE/LOAD. Returns `undefined`\n * ONLY when the record is entirely absent (a pre-feature legacy entry ⇒\n * unrestricted). When present, an absent/`undefined` `version` is COERCED to\n * the current default (1) — mirroring {@link validateCapabilitiesForMint} — so\n * a record that mint-validated also load-normalizes without a schema throw.\n * An explicitly-present WRONG version (not 1) is still rejected. Throws on a\n * malformed record (non-object, explicitly-wrong version, malformed axes).\n */\nexport function normalizeCapabilities(raw: unknown): TokenCapabilities | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(\"capabilities must be an object with a version marker\");\n }\n const obj = raw as Record<string, unknown>;\n // Coerce absent/undefined version → 1, mirroring validateCapabilitiesForMint\n // (version 1 is the only schema version; coercing keeps mint-validated\n // records reloadable). Only an explicitly-present WRONG version throws.\n if (obj.version !== undefined && obj.version !== TOKEN_CAPABILITIES_VERSION) {\n throw new Error(`capabilities.version must be ${TOKEN_CAPABILITIES_VERSION}`);\n }\n const ops = parseAxis(obj, \"ops\", () => true, \"operation\");\n const namespaces = parseAxis(obj, \"namespaces\", isValidNamespaceValue, \"namespace\");\n const result: TokenCapabilities = { version: TOKEN_CAPABILITIES_VERSION };\n if (ops !== undefined) result.ops = ops;\n if (namespaces !== undefined) result.namespaces = namespaces;\n return result;\n}\n\n/**\n * Validate a capabilities record at MINT time. ALWAYS returns a versioned\n * record (never `undefined`) so every newly-minted token carries an explicit\n * capability decision — a new token can never gain full access by OMITTING\n * the field. When `raw` is absent/null, the result is an explicit\n * unrestricted record (`{ version: 1 }`), a deliberate/auditable choice. A\n * present-but-`undefined` (or absent) `version` is coerced to the current\n * default (1); an explicitly-wrong version is rejected. This version rule is\n * identical to {@link normalizeCapabilities} (mint/load symmetry). Rejects\n * unknown op names against the catalog and malformed namespace values;\n * throws a plain Error — the caller must NOT create a token when this throws.\n */\nexport function validateCapabilitiesForMint(\n raw: unknown,\n validOps: readonly string[],\n): TokenCapabilities {\n const result: TokenCapabilities = { version: TOKEN_CAPABILITIES_VERSION };\n if (raw === undefined || raw === null) {\n return result;\n }\n if (typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(\"capabilities must be an object with optional ops/namespaces arrays\");\n }\n const obj = raw as Record<string, unknown>;\n if (Object.prototype.hasOwnProperty.call(obj, \"version\") && obj.version !== undefined) {\n if (obj.version !== TOKEN_CAPABILITIES_VERSION) {\n throw new Error(`capabilities.version must be ${TOKEN_CAPABILITIES_VERSION}`);\n }\n }\n const validOpSet = new Set(validOps);\n\n if (Object.prototype.hasOwnProperty.call(obj, \"ops\") && obj.ops !== undefined && obj.ops !== null) {\n if (!isStringArray(obj.ops)) {\n throw new Error(\"capabilities ops must be an array of non-empty strings\");\n }\n const ops = obj.ops as unknown[];\n for (const v of ops) {\n if (typeof v !== \"string\" || v.length === 0) {\n throw new Error(\"capabilities ops must be an array of non-empty strings\");\n }\n }\n // Reject unknown op names against the catalog (unknown ⇒ reject, never drop).\n const unknown = ops.filter((op) => typeof op === \"string\" && !validOpSet.has(op));\n if (unknown.length > 0) {\n throw new Error(\n `capabilities ops contains unknown operation name(s): ${unknown.map((o) => JSON.stringify(o)).join(\", \")}`,\n );\n }\n // Preserve presence (empty stays [] ⇒ deny all ops).\n result.ops = dedupeSort(ops as string[]);\n }\n\n if (\n Object.prototype.hasOwnProperty.call(obj, \"namespaces\") &&\n obj.namespaces !== undefined &&\n obj.namespaces !== null\n ) {\n if (!isStringArray(obj.namespaces)) {\n throw new Error(\"capabilities namespaces must be an array of non-empty strings\");\n }\n const namespaces = obj.namespaces as unknown[];\n for (const v of namespaces) {\n if (typeof v !== \"string\" || v.length === 0) {\n throw new Error(\"capabilities namespaces must be an array of non-empty strings\");\n }\n if (!isValidNamespaceValue(v)) {\n throw new Error(`capabilities namespaces contains a malformed namespace: ${JSON.stringify(v)}`);\n }\n }\n result.namespaces = dedupeSort(namespaces as string[]);\n }\n\n return result;\n}\n\n/**\n * True when `caps` imposes any restriction (a present record with at least\n * one axis key). `undefined` (legacy / absent record) ⇒ unrestricted. A\n * present `{ version: 1 }` record with no axes ⇒ also unrestricted (but\n * auditable — it is a deliberate new-token decision, not omission).\n */\nexport function isCapabilityRestricted(caps: TokenCapabilities | undefined | null): boolean {\n if (!caps) return false;\n return caps.ops !== undefined || caps.namespaces !== undefined;\n}\n\n/**\n * True when `caps` permits `op`.\n * - record ABSENT (legacy) ⇒ unrestricted (true).\n * - ops axis ABSENT ⇒ unrestricted on this axis (true).\n * - ops axis PRESENT ⇒ `op` must be listed; `[]` ⇒ false (deny all).\n */\nexport function capabilityAllowsOp(caps: TokenCapabilities | undefined | null, op: string): boolean {\n if (caps?.ops === undefined) return true;\n return caps.ops.includes(op);\n}\n\n/**\n * True when `caps` permits `namespace`.\n * - record ABSENT / namespaces axis ABSENT ⇒ unrestricted (true).\n * - namespaces axis PRESENT ⇒ `namespace` must be listed; undefined\n * namespace ⇒ false; `[]` ⇒ false (deny all).\n */\nexport function capabilityAllowsNamespace(\n caps: TokenCapabilities | undefined | null,\n namespace: string | undefined,\n): boolean {\n if (caps?.namespaces === undefined) return true;\n if (namespace === undefined) return false;\n return caps.namespaces.includes(namespace);\n}\n\n/**\n * Throw {@link EngramAccessForbiddenError} when `caps` restricts ops and\n * `op` is not permitted. No-op for unrestricted tokens.\n */\nexport function assertOperationAllowed(\n caps: TokenCapabilities | undefined | null,\n op: string,\n): void {\n if (!capabilityAllowsOp(caps, op)) {\n throw new EngramAccessForbiddenError(\n `token is not permitted to call operation: ${op}`,\n );\n }\n}\n\n/**\n * Throw {@link EngramAccessForbiddenError} when `caps` restricts namespaces\n * and `namespace` is not permitted. No-op for unrestricted tokens.\n */\nexport function assertNamespaceAllowed(\n caps: TokenCapabilities | undefined | null,\n namespace: string | undefined,\n): void {\n if (!capabilityAllowsNamespace(caps, namespace)) {\n throw new EngramAccessForbiddenError(\n namespace === undefined\n ? \"token is scoped to specific namespaces and this operation requires an explicit namespace\"\n : `token is not permitted to access namespace: ${namespace}`,\n );\n }\n}\n\n/**\n * Resolve the EFFECTIVE namespace an operation runs against: a present,\n * non-empty request namespace wins, otherwise the server default — the same\n * resolution downstream storage applies\n * (`getWritableStorageForNamespace(undefined)` → `defaultNamespace`). Empty\n * strings are treated as absent. Centralized so every invocation surface\n * (HTTP query/body, MCP `tools/call`, id-loaded records, legacy pairs that\n * carry no namespace) applies ONE rule and none can dodge the check by\n * dropping the param. (issue #1850)\n */\nexport function resolveEffectiveNamespace(\n namespace: string | undefined,\n defaultNamespace: string | undefined,\n): string | undefined {\n const normalized = namespace !== undefined && namespace.length > 0 ? namespace : undefined;\n return normalized ?? defaultNamespace;\n}\n\n/**\n * The single effective-namespace allow-list chokepoint (issues #1837/#1850).\n * Throws {@link EngramAccessForbiddenError} when `caps` carries a namespaces\n * allow-list and the EFFECTIVE namespace (request value OR server default) is\n * not a member. FAIL CLOSED:\n * - a scoped token whose allow-list does not cover the effective namespace\n * (explicit OR defaulted) is rejected;\n * - an absent server default (unconfigured) is also rejected for scoped\n * tokens, so omitting `?namespace=` can never bypass the allow-list.\n * No-op for unrestricted tokens (no namespaces axis) so legacy/unrestricted\n * behavior is unchanged. Both the HTTP transport (`resolveNamespace`) and the\n * MCP dispatch route through this ONE function so no surface is missed.\n */\nexport function isNamespaceAllowed(\n caps: TokenCapabilities | undefined | null,\n namespace: string | undefined,\n defaultNamespace: string | undefined,\n): boolean {\n if (caps?.namespaces === undefined) return true; // unrestricted token\n const effective = resolveEffectiveNamespace(namespace, defaultNamespace);\n return effective !== undefined && caps.namespaces.includes(effective);\n}\n\nexport function enforceNamespaceAllowList(\n caps: TokenCapabilities | undefined | null,\n namespace: string | undefined,\n defaultNamespace: string | undefined,\n): void {\n if (isNamespaceAllowed(caps, namespace, defaultNamespace)) return;\n throw new EngramAccessForbiddenError(\n namespace === undefined\n ? \"token is scoped to specific namespaces; the server default namespace is not permitted — supply an allowed namespace\"\n : `token is not permitted to access namespace: ${namespace}`,\n );\n}\n\n/**\n * Fleet-wide / global maintenance operation guard (issue #1850 round 10).\n *\n * A distinct escalation class from the id-addressed routes (round 9) and the\n * param-namespace ops (round 4): some boundary operations inherently run\n * ACROSS ALL namespaces — or against a single global layer (compression\n * guidelines, shared context, compounding) that is not namespace-partitioned\n * — and carry NO `namespace` argument, so the MCP `tools/call` effective-\n * namespace chokepoint ({@link enforceNamespaceAllowList}, which only fires\n * when `toolAcceptsNamespace`) never applies. Without this guard a bearer\n * scoped to ONE tenant could trigger maintenance that mutates state in EVERY\n * namespace (privilege escalation).\n *\n * Fail CLOSED exactly like the other shared guards: a namespace-SCOPED token\n * (namespaces axis present) is rejected; unrestricted / legacy tokens (absent\n * record or no namespaces axis — i.e. cron and internal callers that never\n * bind a capability record) are unaffected. Reuses the EXISTING capability\n * model via {@link capabilityAllowsNamespace} — no new \"all\"/\"*\" scope concept.\n * Must run BEFORE any side effect so a denial never leaks a partial mutation.\n */\nexport function assertFleetWideOperationAllowed(\n caps: TokenCapabilities | undefined | null,\n): void {\n // capabilityAllowsNamespace returns false for ANY scoped token when the\n // namespace is undefined (a fleet-wide op has no single namespace), and\n // true for unrestricted/legacy tokens — exactly the desired policy.\n if (!capabilityAllowsNamespace(caps, undefined)) {\n throw new EngramAccessForbiddenError(\n \"token is scoped to specific namespaces; this maintenance operation runs across all namespaces and is not permitted for a namespace-scoped token\",\n );\n }\n}\n\n/**\n * Per-request AsyncLocalStorage carrying the presenting token's resolved\n * capabilities. The HTTP surface binds the resolved capabilities with\n * `.run(caps, handler)` for the WHOLE authorized request dispatch (NOT\n * `.enterWith()`, which mutates the current async resource and does not\n * reliably isolate the store across the handler's awaits / concurrent\n * requests — risking a fail-open read of undefined mid-handler); the\n * access boundary reads `.getStore()` to enforce the ops allow-list for\n * every boundary operation without each dispatch site threading the value\n * explicitly. Unset (CLI, direct boundary callers, tests) ⇒ undefined ⇒\n * unrestricted (issue #1850 round 7).\n */\nexport const tokenCapabilityStore = new AsyncLocalStorage<TokenCapabilities | undefined>();\n"],"mappings":";;;;;AAmCA,SAAS,yBAAyB;AAI3B,IAAM,6BAA6B;AA4B1C,IAAM,6BAA6B;AAInC,IAAM,0BAA0B;AAGzB,SAAS,sBAAsB,OAAiC;AACrE,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,SAAS,4BAA4B;AAChG,WAAO;AAAA,EACT;AACA,MAAI,CAAC,wBAAwB,KAAK,KAAK,EAAG,QAAO;AACjD,MAAI,UAAU,OAAO,UAAU,KAAM,QAAO;AAC5C,SAAO;AACT;AAEA,SAAS,cAAc,OAAoC;AACzD,SAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,CAAC,MAAM,OAAO,MAAM,QAAQ;AACzE;AAEA,SAAS,WAAW,QAA4B;AAC9C,SAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK;AACnC;AASA,SAAS,UACP,KACA,KACA,eACA,YACsB;AACtB,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,KAAK,GAAG,EAAG,QAAO;AAC5D,QAAM,QAAQ,IAAI,GAAG;AACrB,MAAI,UAAU,UAAa,UAAU,KA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