@kya-os/checkpoint-shared 1.6.0 → 1.7.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 (83) hide show
  1. package/dist/{browser-posture-DIaVLuW3.d.ts → browser-posture-B8YiPa5c.d.ts} +5 -5
  2. package/dist/{browser-posture-DIaVLuW3.d.ts.map → browser-posture-B8YiPa5c.d.ts.map} +1 -1
  3. package/dist/{browser-posture-BuChqmH5.d.mts → browser-posture-BLhw-MON.d.mts} +5 -5
  4. package/dist/{browser-posture-BuChqmH5.d.mts.map → browser-posture-BLhw-MON.d.mts.map} +1 -1
  5. package/dist/browser-posture-cookie.js +1 -1
  6. package/dist/browser-posture-cookie.mjs +1 -1
  7. package/dist/browser-posture-cookie.mjs.map +1 -1
  8. package/dist/browser-posture-proof.d.mts +1 -1
  9. package/dist/browser-posture-proof.d.mts.map +1 -1
  10. package/dist/browser-posture-proof.d.ts +1 -1
  11. package/dist/browser-posture-proof.d.ts.map +1 -1
  12. package/dist/browser-posture-proof.js +42 -1
  13. package/dist/browser-posture-proof.mjs +42 -1
  14. package/dist/browser-posture-proof.mjs.map +1 -1
  15. package/dist/browser-posture.d.mts +1 -1
  16. package/dist/browser-posture.d.ts +1 -1
  17. package/dist/browser-posture.js +1 -1
  18. package/dist/browser-posture.mjs +1 -1
  19. package/dist/canonical-signer/index.d.mts.map +1 -1
  20. package/dist/canonical-signer/index.d.ts.map +1 -1
  21. package/dist/canonical-signer/index.js +86 -51
  22. package/dist/canonical-signer/index.mjs +86 -51
  23. package/dist/canonical-signer/index.mjs.map +1 -1
  24. package/dist/client-ip-DFamiNoz.d.mts +34 -0
  25. package/dist/client-ip-DFamiNoz.d.mts.map +1 -0
  26. package/dist/client-ip-DFamiNoz.d.ts +34 -0
  27. package/dist/client-ip-DFamiNoz.d.ts.map +1 -0
  28. package/dist/client-ip.d.mts +2 -0
  29. package/dist/client-ip.d.ts +2 -0
  30. package/dist/client-ip.js +7 -0
  31. package/dist/client-ip.mjs +3 -0
  32. package/dist/host-adapter/index.d.mts +2 -0
  33. package/dist/host-adapter/index.d.ts +2 -0
  34. package/dist/host-adapter/index.js +23 -0
  35. package/dist/host-adapter/index.mjs +3 -0
  36. package/dist/host-adapter-C-4IxmqM.mjs +540 -0
  37. package/dist/host-adapter-C-4IxmqM.mjs.map +1 -0
  38. package/dist/host-adapter-CwW9YB0U.js +694 -0
  39. package/dist/index-B7rTovHa.d.mts +707 -0
  40. package/dist/index-B7rTovHa.d.mts.map +1 -0
  41. package/dist/index-HaqfPtaL.d.ts +707 -0
  42. package/dist/index-HaqfPtaL.d.ts.map +1 -0
  43. package/dist/index.d.mts +107 -981
  44. package/dist/index.d.mts.map +1 -1
  45. package/dist/index.d.ts +107 -981
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +73 -2308
  48. package/dist/index.mjs +5 -2240
  49. package/dist/index.mjs.map +1 -1
  50. package/dist/kya-http-error-codes-7ewV5RuK.d.mts +29 -0
  51. package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +1 -0
  52. package/dist/kya-http-error-codes-7ewV5RuK.d.ts +29 -0
  53. package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +1 -0
  54. package/dist/kya-http-error-codes-C2JiWPsi.mjs +73 -0
  55. package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +1 -0
  56. package/dist/kya-http-error-codes-UYb1zpGM.js +83 -0
  57. package/dist/kya-http.d.mts +3 -0
  58. package/dist/kya-http.d.ts +3 -0
  59. package/dist/kya-http.js +11 -0
  60. package/dist/kya-http.mjs +4 -0
  61. package/dist/policy/enforcement.d.mts +2 -0
  62. package/dist/policy/enforcement.d.ts +2 -0
  63. package/dist/policy/enforcement.js +15 -0
  64. package/dist/policy/enforcement.mjs +3 -0
  65. package/dist/{posture-origins-Pn-ii-Pp.mjs → posture-origins-Ba83O0cD.mjs} +2 -2
  66. package/dist/posture-origins-Ba83O0cD.mjs.map +1 -0
  67. package/dist/{posture-origins-LFkX80oF.js → posture-origins-CdVOdiMT.js} +1 -1
  68. package/dist/registered-sid-D3g-gZQF.d.mts +11 -0
  69. package/dist/registered-sid-D3g-gZQF.d.mts.map +1 -0
  70. package/dist/registered-sid-D3g-gZQF.d.ts +11 -0
  71. package/dist/registered-sid-D3g-gZQF.d.ts.map +1 -0
  72. package/dist/registered-sid-eLCNZvIF.js +170 -0
  73. package/dist/registered-sid-hUl-bvM5.mjs +142 -0
  74. package/dist/registered-sid-hUl-bvM5.mjs.map +1 -0
  75. package/dist/step-up-BjP--hG-.d.mts +114 -0
  76. package/dist/step-up-BjP--hG-.d.mts.map +1 -0
  77. package/dist/step-up-BjP--hG-.d.ts +114 -0
  78. package/dist/step-up-BjP--hG-.d.ts.map +1 -0
  79. package/dist/step-up-C2d8C20x.js +1697 -0
  80. package/dist/step-up-COlmWJN8.mjs +1513 -0
  81. package/dist/step-up-COlmWJN8.mjs.map +1 -0
  82. package/package.json +23 -1
  83. package/dist/posture-origins-Pn-ii-Pp.mjs.map +0 -1
package/dist/index.js CHANGED
@@ -28,8 +28,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
 
29
29
  //#endregion
30
30
  const require_schemas = require('./schemas-YhagYDx_.js');
31
- const require_posture_origins = require('./posture-origins-LFkX80oF.js');
31
+ const require_posture_origins = require('./posture-origins-CdVOdiMT.js');
32
+ const require_host_adapter = require('./host-adapter-CwW9YB0U.js');
32
33
  const require_client_ip = require('./client-ip-CW6pRyLf.js');
34
+ const require_step_up = require('./step-up-C2d8C20x.js');
35
+ const require_kya_http_error_codes = require('./kya-http-error-codes-UYb1zpGM.js');
36
+ const require_registered_sid = require('./registered-sid-eLCNZvIF.js');
33
37
  let _noble_hashes_sha2_js = require("@noble/hashes/sha2.js");
34
38
  let _noble_hashes_utils_js = require("@noble/hashes/utils.js");
35
39
  let _kya_os_provider_registry = require("@kya-os/provider-registry");
@@ -11543,74 +11547,6 @@ function createValidationErrorResponse(message, details, meta) {
11543
11547
  };
11544
11548
  }
11545
11549
 
11546
- //#endregion
11547
- //#region src/utils/detection-class.ts
11548
- /**
11549
- * Convert DetectionClass discriminated union to database enum string
11550
- * Note: Automation and Unknown are legacy types, converted to Bot and IncompleteData respectively
11551
- */
11552
- function detectionClassToEnum(detectionClass) {
11553
- switch (detectionClass.type) {
11554
- case "Human": return "human";
11555
- case "AiAgent": return "ai_agent";
11556
- case "Automation": return "bot";
11557
- case "Bot": return "bot";
11558
- case "IncompleteData": return "incomplete_data";
11559
- default: return "incomplete_data";
11560
- }
11561
- }
11562
- /**
11563
- * Convert database enum string to DetectionClass discriminated union
11564
- * Handles both current and legacy enum values for backwards compatibility
11565
- */
11566
- function enumToDetectionClass(enumValue) {
11567
- switch (enumValue) {
11568
- case "human": return { type: "Human" };
11569
- case "ai_agent": return { type: "AiAgent" };
11570
- case "automation": return { type: "Bot" };
11571
- case "bot": return { type: "Bot" };
11572
- case "incomplete_data": return { type: "IncompleteData" };
11573
- case "unknown": return { type: "IncompleteData" };
11574
- default: return { type: "IncompleteData" };
11575
- }
11576
- }
11577
- /**
11578
- * Check if a value is a valid string-based detection class (current or legacy)
11579
- */
11580
- function isLegacyDetectionClass(value) {
11581
- return typeof value === "string" && [
11582
- "human",
11583
- "ai_agent",
11584
- "bot",
11585
- "incomplete_data",
11586
- "automation",
11587
- "unknown"
11588
- ].includes(value);
11589
- }
11590
- /**
11591
- * Migrate legacy string detection class to new discriminated union
11592
- * @deprecated Use enumToDetectionClass instead
11593
- */
11594
- function migrateLegacyDetectionClass(value) {
11595
- return enumToDetectionClass(value);
11596
- }
11597
- /**
11598
- * Safely convert any detection class value to the discriminated union format
11599
- */
11600
- function normalizeDetectionClass(value) {
11601
- if (value && typeof value === "object" && "type" in value) return value;
11602
- if (isLegacyDetectionClass(value)) return enumToDetectionClass(value);
11603
- return { type: "IncompleteData" };
11604
- }
11605
- /**
11606
- * Safely convert any detection class value to database enum format
11607
- */
11608
- function normalizeDetectionClassEnum(value) {
11609
- if (value && typeof value === "object" && "type" in value) return detectionClassToEnum(value);
11610
- if (isLegacyDetectionClass(value)) return detectionClassToEnum(enumToDetectionClass(value));
11611
- return "incomplete_data";
11612
- }
11613
-
11614
11550
  //#endregion
11615
11551
  //#region src/utils/agent-runtime-label.ts
11616
11552
  /**
@@ -14914,9 +14850,6 @@ const PolicyEvaluationResultSchema = require_schemas.object({
14914
14850
  /** What type of match triggered this decision */
14915
14851
  matchType: PolicyMatchTypeSchema
14916
14852
  });
14917
- function isEngineEnforcing(flags) {
14918
- return flags.engineEnforcementEnabled === true && flags.enabled !== false;
14919
- }
14920
14853
  /**
14921
14854
  * Validate and parse a policy configuration
14922
14855
  */
@@ -14937,20 +14870,6 @@ function parseEvaluationContext(data) {
14937
14870
  return PolicyEvaluationContextSchema.parse(data);
14938
14871
  }
14939
14872
 
14940
- //#endregion
14941
- //#region src/policy/fail-closed-response.ts
14942
- const FAIL_CLOSED_STATUS = 503;
14943
- const FAIL_CLOSED_RETRY_AFTER_SECONDS = 3;
14944
- const FAIL_CLOSED_BODY = {
14945
- error: "Service temporarily unavailable",
14946
- source: "checkpoint-middleware"
14947
- };
14948
- const FAIL_CLOSED_HEADERS = {
14949
- "Content-Type": "application/json",
14950
- "Cache-Control": "no-store",
14951
- "Retry-After": String(3)
14952
- };
14953
-
14954
14873
  //#endregion
14955
14874
  //#region src/policy/evaluator.ts
14956
14875
  /**
@@ -15195,1390 +15114,6 @@ function createResult(action, reason, matchType, extras) {
15195
15114
  };
15196
15115
  }
15197
15116
 
15198
- //#endregion
15199
- //#region src/policy/cedar-mask.ts
15200
- const blank = (char) => char === "\n" || char === "\r" ? char : " ";
15201
- function maskCedar(cedar) {
15202
- const visible = cedar.split("");
15203
- const code = cedar.split("");
15204
- const inString = new Array(cedar.length).fill(false);
15205
- let i = 0;
15206
- while (i < cedar.length) if (cedar[i] === "\"") {
15207
- let end = i + 1;
15208
- while (end < cedar.length && cedar[end] !== "\"") end += cedar[end] === "\\" ? 2 : 1;
15209
- const bodyEnd = Math.min(end, cedar.length);
15210
- for (let k = i + 1; k < bodyEnd; k++) {
15211
- inString[k] = true;
15212
- code[k] = blank(cedar[k]);
15213
- }
15214
- i = end + 1;
15215
- } else if (cedar[i] === "/" && cedar[i + 1] === "/") while (i < cedar.length && cedar[i] !== "\n" && cedar[i] !== "\r") {
15216
- visible[i] = " ";
15217
- code[i] = " ";
15218
- i++;
15219
- }
15220
- else i++;
15221
- return {
15222
- visible: visible.join(""),
15223
- code: code.join(""),
15224
- inString
15225
- };
15226
- }
15227
-
15228
- //#endregion
15229
- //#region src/policy/cedar-space.ts
15230
- const CEDAR_SPACE_CLASS = "[\\t-\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]";
15231
- function isCedarSpace(char) {
15232
- const code = char.charCodeAt(0);
15233
- return code >= 9 && code <= 13 || code === 32 || code === 133 || code === 160 || code === 5760 || code >= 8192 && code <= 8202 || code === 8232 || code === 8233 || code === 8239 || code === 8287 || code === 12288;
15234
- }
15235
-
15236
- //#endregion
15237
- //#region src/policy/cedar-string.ts
15238
- /**
15239
- * The Cedar double-quoted string grammar shared by the compose engine's emitter/
15240
- * parser and every enforcement-path TEXT reader (required-scopes, cedar-rule-match).
15241
- * Keeping the escape codec AND the capture pattern in one place means a value the
15242
- * emitter escapes is decoded identically wherever a reader parses it back — they
15243
- * can never drift. (Rust/.NET parse Cedar with a real parser and are unaffected.)
15244
- */
15245
- /** Escape a value for embedding inside a Cedar double-quoted string literal. */
15246
- function escapeCedarString(value) {
15247
- return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
15248
- }
15249
- /** Inverse of {@link escapeCedarString} — decode Cedar string escapes to raw text. */
15250
- function unescapeCedarString(value) {
15251
- return value.replace(/\\([\\"nrt])/g, (_m, ch) => ch === "n" ? "\n" : ch === "r" ? "\r" : ch === "t" ? " " : ch);
15252
- }
15253
- /**
15254
- * Build a RegExp matching `<prefixSource>"<body>"`, where <body> is an escape-aware
15255
- * Cedar string. Capture group 1 is the RAW (still-escaped) body — pass it through
15256
- * {@link unescapeCedarString} before use. `prefixSource` is a regex-source fragment
15257
- * (escape its own metacharacters). This is the single source of the quoted-string
15258
- * capture pattern.
15259
- */
15260
- function cedarQuotedValueRegExp(prefixSource, flags = "") {
15261
- return new RegExp(`${prefixSource}"((?:\\\\.|[^"\\\\])*)"`, flags);
15262
- }
15263
- const LIKE_ESCAPES = {
15264
- n: "\n",
15265
- r: "\r",
15266
- t: " ",
15267
- "0": "\0"
15268
- };
15269
- const NUMERIC_ESCAPE = /x([0-9a-fA-F]{2})|u\{([0-9a-fA-F][0-9a-fA-F_]*)\}/y;
15270
- const MAX_CODE_POINT = 1114111;
15271
- const MAX_UNICODE_DIGITS = 6;
15272
- function numericEscapeCode(raw, at) {
15273
- NUMERIC_ESCAPE.lastIndex = at;
15274
- const match = NUMERIC_ESCAPE.exec(raw);
15275
- if (match === null) return null;
15276
- if (match[1] !== void 0) return {
15277
- code: parseInt(match[1], 16),
15278
- length: match[0].length
15279
- };
15280
- const digits = match[2].replace(/_/g, "");
15281
- const code = parseInt(digits, 16);
15282
- return digits.length <= MAX_UNICODE_DIGITS && code <= MAX_CODE_POINT && (code < 55296 || code > 57343) ? {
15283
- code,
15284
- length: match[0].length
15285
- } : null;
15286
- }
15287
- function cedarLikeSegments(rawPattern) {
15288
- const segments = [""];
15289
- const append = (char) => {
15290
- if (char === "*") segments.push("");
15291
- else segments[segments.length - 1] += char;
15292
- };
15293
- for (let i = 0; i < rawPattern.length; i++) {
15294
- const char = rawPattern.charAt(i);
15295
- if (char !== "\\") {
15296
- append(char);
15297
- continue;
15298
- }
15299
- const numeric = numericEscapeCode(rawPattern, i + 1);
15300
- if (numeric !== null) {
15301
- append(String.fromCodePoint(numeric.code));
15302
- i += numeric.length;
15303
- } else {
15304
- const next = rawPattern.charAt(++i);
15305
- segments[segments.length - 1] += LIKE_ESCAPES[next] ?? next;
15306
- }
15307
- }
15308
- return segments;
15309
- }
15310
- function globMatches(segments, value) {
15311
- const first = segments[0];
15312
- if (segments.length === 1) return value === first;
15313
- const last = segments[segments.length - 1];
15314
- const end = value.length - last.length;
15315
- if (end < first.length || !value.startsWith(first) || !value.endsWith(last)) return false;
15316
- let position = first.length;
15317
- for (let i = 1; i < segments.length - 1; i++) {
15318
- const at = value.indexOf(segments[i], position);
15319
- if (at === -1 || at + segments[i].length > end) return false;
15320
- position = at + segments[i].length;
15321
- }
15322
- return true;
15323
- }
15324
-
15325
- //#endregion
15326
- //#region src/policy/legacy-carve-out.ts
15327
- const NO_EVIDENCE_CATEGORY = "no_evidence";
15328
- const NO_EVIDENCE_EXCLUSION_TERM = `principal.category != "${NO_EVIDENCE_CATEGORY}"`;
15329
- const NO_EVIDENCE_EQUALITY_TERM = `principal.category == "${NO_EVIDENCE_CATEGORY}"`;
15330
- const WS = `${CEDAR_SPACE_CLASS}*`;
15331
- const SEGMENT_BOUNDARY = new RegExp(`\\b(?:forbid|permit)${WS}\\(|;`, "g");
15332
- const ACCESSOR = `(?:\\.${WS}category\\b|\\[${WS}"C[^"]*"${WS}\\])`;
15333
- const SUBJECT = `(?<![.\\w])principal${WS}${ACCESSOR}`;
15334
- const EXACT = "\"E[^\"]*\"";
15335
- const LIKEABLE = "\"[EL][^\"]*\"";
15336
- const ELEMENTS = `[^\\]\\[]*(?:\\[${WS}"[^"]*"${WS}\\][^\\]\\[]*){0,16}`;
15337
- const CATEGORY_READ = new RegExp(`(?<![.\\w])principal(?:${WS}\\))*${WS}${ACCESSOR}`, "g");
15338
- const GROUP_OR_PRINCIPAL = /[()[\]{}]|(?<![\w.])principal(?!\w)/g;
15339
- const CHAIN_LINK = new RegExp(`${WS}(?:\\.${WS}(category\\b)|\\.${WS}\\w+|\\[${WS}"(C)?[^"]*"${WS}\\])`, "y");
15340
- const PRINCIPAL_LENGTH = 9;
15341
- const BARE_GROUP = new RegExp(`^(?:\\(|${CEDAR_SPACE_CLASS})*$`);
15342
- const CATEGORY_COMPARED = new RegExp(`${SUBJECT}${WS}(?:(?:==|!=)${WS}${EXACT}|like${WS}${LIKEABLE})|${EXACT}${WS}(?:==|!=)${WS}${SUBJECT}`);
15343
- const LIST_CALL = new RegExp(`\\[(${ELEMENTS})\\]${WS}\\.${WS}contains(?:All|Any)?${WS}(?:(${SUBJECT})|(${EXACT})|\\[(${ELEMENTS})\\])`, "g");
15344
- const HAS_CATEGORY = new RegExp(SUBJECT);
15345
- const HAS_NO_EVIDENCE = new RegExp(EXACT);
15346
- const SUBSTITUTED_READ = new RegExp(`\\(if ((?:\\(|${CEDAR_SPACE_CLASS})*principal(?:\\)|${CEDAR_SPACE_CLASS})*(?:\\.${WS}category\\b|\\[${WS}("(?:\\\\.|[^"\\\\])*")${WS}\\])) == "${NO_EVIDENCE_CATEGORY}" then "human" else \\1\\)`, "g");
15347
- function literalMarker(body) {
15348
- const segments = cedarLikeSegments(body);
15349
- if (segments.length === 1) {
15350
- if (segments[0] === "no_evidence") return "E";
15351
- return segments[0] === "category" ? "C" : " ";
15352
- }
15353
- return segments.some((segment) => segment.includes("no_evidence")) && globMatches(segments, "no_evidence") ? "L" : " ";
15354
- }
15355
- function scan(cedar) {
15356
- const { visible, code, inString } = maskCedar(cedar);
15357
- const marked = code.split("");
15358
- for (let start = 0; start < cedar.length;) {
15359
- if (!inString[start]) {
15360
- start++;
15361
- continue;
15362
- }
15363
- let end = start;
15364
- while (end < cedar.length && inString[end]) end++;
15365
- const marker = literalMarker(visible.slice(start, end));
15366
- if (marker !== " ") marked[start] = marker;
15367
- start = end;
15368
- }
15369
- const text = marked.join("");
15370
- return {
15371
- visible,
15372
- text,
15373
- flat: text.replace(/[()]/g, " "),
15374
- pairs: pairParentheses(text)
15375
- };
15376
- }
15377
- function pairParentheses(text) {
15378
- const pairs = new Int32Array(text.length).fill(-1);
15379
- const open = [];
15380
- for (let i = 0; i < text.length; i++) if (text[i] === "(") open.push(i);
15381
- else if (text[i] === ")") pairs[i] = open.pop() ?? -1;
15382
- return pairs;
15383
- }
15384
- function statementRanges(text) {
15385
- const ranges = [];
15386
- let open = -1;
15387
- for (const boundary of text.matchAll(SEGMENT_BOUNDARY)) if (boundary[0] === ";") {
15388
- if (open !== -1) ranges.push([open, boundary.index + 1]);
15389
- open = -1;
15390
- } else {
15391
- if (open !== -1) ranges.push([open, boundary.index]);
15392
- open = boundary.index;
15393
- }
15394
- if (open !== -1) ranges.push([open, text.length]);
15395
- return ranges;
15396
- }
15397
- function applyEdits(cedar, edits) {
15398
- if (edits.length === 0) return cedar;
15399
- const pieces = [];
15400
- let position = 0;
15401
- for (const edit of edits) {
15402
- pieces.push(cedar.slice(position, edit.start), edit.text);
15403
- position = edit.end;
15404
- }
15405
- pieces.push(cedar.slice(position));
15406
- return pieces.join("");
15407
- }
15408
- function namesNoEvidenceIn(flat) {
15409
- if (CATEGORY_COMPARED.test(flat)) return true;
15410
- for (const [, receiver, subject, exact, list = ""] of flat.matchAll(LIST_CALL)) {
15411
- const receiverReadsCategory = HAS_CATEGORY.test(receiver);
15412
- const receiverNamesNoEvidence = HAS_NO_EVIDENCE.test(receiver);
15413
- if (receiverReadsCategory && (exact !== void 0 || HAS_NO_EVIDENCE.test(list)) || receiverNamesNoEvidence && (subject !== void 0 || HAS_CATEGORY.test(list))) return true;
15414
- }
15415
- return false;
15416
- }
15417
- function namesNoEvidence(cedar) {
15418
- return namesNoEvidenceIn(scan(cedar).flat);
15419
- }
15420
- function groupStart({ text, pairs }, principal, read) {
15421
- const lastCloser = read.lastIndexOf(")");
15422
- if (lastCloser === -1) return principal;
15423
- const open = pairs[principal + lastCloser];
15424
- return open !== -1 && BARE_GROUP.test(text.slice(open, principal)) ? open : -1;
15425
- }
15426
- const isWordChar = (char) => char !== void 0 && /\w/.test(char);
15427
- function skipSpaceBack(text, from) {
15428
- let i = from;
15429
- while (i >= 0 && isCedarSpace(text[i])) i--;
15430
- return i;
15431
- }
15432
- function skipSpaceForward(text, from) {
15433
- let i = from;
15434
- while (i < text.length && isCedarSpace(text[i])) i++;
15435
- return i;
15436
- }
15437
- function wordEndingAt(text, end) {
15438
- let start = end;
15439
- while (start > 0 && isWordChar(text[start - 1])) start--;
15440
- return text.slice(start, end + 1);
15441
- }
15442
- function isPrincipalVariable(text, at) {
15443
- const before = skipSpaceBack(text, at - 1);
15444
- const char = text[before];
15445
- if (char === "." || char === "?") return false;
15446
- if (char === ":" && text[before - 1] === ":") return false;
15447
- if (isWordChar(char) && wordEndingAt(text, before) === "has") return false;
15448
- return text[skipSpaceForward(text, at + PRINCIPAL_LENGTH)] !== ":";
15449
- }
15450
- function isBranchValue(text, at) {
15451
- let before = skipSpaceBack(text, at - 1);
15452
- while (text[before] === "(") before = skipSpaceBack(text, before - 1);
15453
- const char = text[before];
15454
- const word = isWordChar(char) ? wordEndingAt(text, before) : "";
15455
- const introduced = word === "then" || word === "else" || char === ":" && text[before - 1] !== ":";
15456
- const after = skipSpaceForward(text, at + PRINCIPAL_LENGTH);
15457
- const next = text[after];
15458
- const ends = next === ")" || next === "}" || next === "]" || next === "," || text.startsWith("else", after) && !isWordChar(text[after + 4]);
15459
- return introduced && ends;
15460
- }
15461
- function headEnd(text, from, to) {
15462
- let depth = 0;
15463
- for (let i = text.indexOf("(", from); i < to; i++) if (text[i] === "(") depth++;
15464
- else if (text[i] === ")" && --depth === 0) return i + 1;
15465
- return from;
15466
- }
15467
- function directReads(scanned, from, to) {
15468
- const reads = [];
15469
- for (const read of scanned.text.slice(from, to).matchAll(CATEGORY_READ)) {
15470
- const principal = from + read.index;
15471
- if (!isPrincipalVariable(scanned.text, principal)) continue;
15472
- const start = groupStart(scanned, principal, read[0]);
15473
- if (start !== -1) reads.push({
15474
- principal,
15475
- start,
15476
- end: principal + read[0].length
15477
- });
15478
- }
15479
- return reads;
15480
- }
15481
- function readsCategoryAfter(text, from) {
15482
- CHAIN_LINK.lastIndex = from;
15483
- for (let link = CHAIN_LINK.exec(text); link !== null; link = CHAIN_LINK.exec(text)) if (link[1] !== void 0 || link[2] !== void 0) return true;
15484
- return false;
15485
- }
15486
- function readsCategoryOfCarriedPrincipal(text, from, to, reads) {
15487
- const direct = new Set(reads.map((read) => read.principal));
15488
- const holding = [false];
15489
- for (const token of text.slice(from, to).matchAll(GROUP_OR_PRINCIPAL)) {
15490
- const at = from + token.index;
15491
- if (token[0] === "principal") {
15492
- if (!direct.has(at) && isPrincipalVariable(text, at) && isBranchValue(text, at)) holding[holding.length - 1] = true;
15493
- } else if ("([{".includes(token[0])) holding.push(false);
15494
- else if (holding.length > 1 && holding.pop()) {
15495
- holding[holding.length - 1] = true;
15496
- if (readsCategoryAfter(text, at + 1)) return true;
15497
- }
15498
- }
15499
- return false;
15500
- }
15501
- function withNoEvidenceExclusion(cedar) {
15502
- const scanned = scan(cedar);
15503
- const { visible, text, flat } = scanned;
15504
- const edits = [];
15505
- for (const [from, to] of statementRanges(text)) {
15506
- if (namesNoEvidenceIn(flat.slice(from, to))) continue;
15507
- const reads = directReads(scanned, from, to);
15508
- if (reads.length === 0) continue;
15509
- if (readsCategoryOfCarriedPrincipal(text, headEnd(text, from, to), to, reads)) continue;
15510
- for (const { start, end } of reads) {
15511
- const accessor = visible.slice(start, end);
15512
- edits.push({
15513
- start,
15514
- end,
15515
- text: `(if ${accessor} == "${NO_EVIDENCE_CATEGORY}" then "human" else ${accessor})`
15516
- });
15517
- }
15518
- }
15519
- return applyEdits(cedar, edits);
15520
- }
15521
- function withoutNoEvidenceExclusion(cedar) {
15522
- const { visible, inString } = maskCedar(cedar);
15523
- const edits = [];
15524
- for (const read of visible.matchAll(SUBSTITUTED_READ)) {
15525
- const key = read[2];
15526
- if (!inString[read.index] && (key === void 0 || literalMarker(key.slice(1, -1)) === "C")) edits.push({
15527
- start: read.index,
15528
- end: read.index + read[0].length,
15529
- text: read[1]
15530
- });
15531
- }
15532
- return applyEdits(cedar, edits);
15533
- }
15534
-
15535
- //#endregion
15536
- //#region src/policy/cedar-expression.ts
15537
- const MAX_NESTING = 48;
15538
- const MAX_HEX_ESCAPE = 127;
15539
- const UNNAMED_CATEGORY = "\ud800";
15540
- const LONE_SURROGATE = /\p{Surrogate}/u;
15541
- const HUMAN_NAMES = [
15542
- "",
15543
- "human",
15544
- "unknown",
15545
- "anonymous"
15546
- ];
15547
- const UNKNOWN = { k: "unknown" };
15548
- const PUNCTUATION = /* @__PURE__ */ new Set("<>!+-*()[]{}.,:");
15549
- const TWO_CHARACTER = /* @__PURE__ */ new Set([
15550
- "&&",
15551
- "||",
15552
- "==",
15553
- "!=",
15554
- "<=",
15555
- ">=",
15556
- "::"
15557
- ]);
15558
- const SIMPLE_ESCAPES = {
15559
- n: "\n",
15560
- r: "\r",
15561
- t: " ",
15562
- "\\": "\\",
15563
- "0": "\0",
15564
- "'": "'",
15565
- "\"": "\""
15566
- };
15567
- const IDENTIFIER_START = /[A-Za-z_]/;
15568
- const IDENTIFIER_PART = /[A-Za-z0-9_]/;
15569
- const DIGIT = /[0-9]/;
15570
- const UNSUPPORTED_PATTERN_ESCAPE = /\\[0u]/;
15571
- function tokenize(text) {
15572
- const tokens = [];
15573
- let i = 0;
15574
- while (i < text.length) {
15575
- const char = text[i];
15576
- if (isCedarSpace(char)) i += 1;
15577
- else if (char === "/" && text[i + 1] === "/") while (i < text.length && text[i] !== "\n" && text[i] !== "\r") i += 1;
15578
- else if (char === "\"") {
15579
- let end = i + 1;
15580
- while (end < text.length && text[end] !== "\"") end += text[end] === "\\" ? 2 : 1;
15581
- if (end >= text.length) throw new SyntaxError("unterminated string");
15582
- const body = text.slice(i + 1, end);
15583
- if (LONE_SURROGATE.test(body)) throw new SyntaxError("ill-formed string");
15584
- tokens.push({
15585
- t: "str",
15586
- v: body
15587
- });
15588
- i = end + 1;
15589
- } else if (IDENTIFIER_START.test(char)) {
15590
- let end = i + 1;
15591
- while (end < text.length && IDENTIFIER_PART.test(text[end])) end += 1;
15592
- tokens.push({
15593
- t: "id",
15594
- v: text.slice(i, end)
15595
- });
15596
- i = end;
15597
- } else if (DIGIT.test(char)) {
15598
- let end = i + 1;
15599
- while (end < text.length && DIGIT.test(text[end])) end += 1;
15600
- tokens.push({
15601
- t: "num",
15602
- v: text.slice(i, end)
15603
- });
15604
- i = end;
15605
- } else if (TWO_CHARACTER.has(text.slice(i, i + 2))) {
15606
- tokens.push({
15607
- t: "p",
15608
- v: text.slice(i, i + 2)
15609
- });
15610
- i += 2;
15611
- } else if (PUNCTUATION.has(char)) {
15612
- tokens.push({
15613
- t: "p",
15614
- v: char
15615
- });
15616
- i += 1;
15617
- } else throw new SyntaxError("unexpected character");
15618
- }
15619
- return tokens;
15620
- }
15621
- function decodeCedarString(raw) {
15622
- let out = "";
15623
- for (let i = 0; i < raw.length; i += 1) if (raw[i] !== "\\") out += raw[i];
15624
- else if (raw[i + 1] === "x" || raw[i + 1] === "u") {
15625
- const numeric = numericEscapeCode(raw, i + 1);
15626
- if (numeric === null || raw[i + 1] === "x" && numeric.code > MAX_HEX_ESCAPE) return null;
15627
- out += String.fromCodePoint(numeric.code);
15628
- i += numeric.length;
15629
- } else {
15630
- const mapped = SIMPLE_ESCAPES[raw[i + 1]];
15631
- if (mapped === void 0) return null;
15632
- out += mapped;
15633
- i += 1;
15634
- }
15635
- return out;
15636
- }
15637
- var Parser = class {
15638
- tokens;
15639
- position = 0;
15640
- readsTag = false;
15641
- constructor(tokens) {
15642
- this.tokens = tokens;
15643
- }
15644
- parseAll() {
15645
- const expression = this.expression(0);
15646
- if (this.position < this.tokens.length) throw new SyntaxError("trailing tokens");
15647
- return this.readsTag ? UNKNOWN : expression;
15648
- }
15649
- peek() {
15650
- return this.tokens[this.position];
15651
- }
15652
- is(type, value) {
15653
- const token = this.peek();
15654
- return token !== void 0 && token.t === type && token.v === value;
15655
- }
15656
- take(type, value) {
15657
- const found = this.is(type, value);
15658
- if (found) this.position += 1;
15659
- return found;
15660
- }
15661
- expect(type, value) {
15662
- if (!this.take(type, value)) throw new SyntaxError(`expected ${value}`);
15663
- }
15664
- next(type) {
15665
- const token = this.peek();
15666
- if (token === void 0 || token.t !== type) throw new SyntaxError(`expected ${type}`);
15667
- this.position += 1;
15668
- return token;
15669
- }
15670
- expression(depth) {
15671
- if (depth > MAX_NESTING) throw new SyntaxError("too deep");
15672
- if (this.take("id", "if")) {
15673
- const cond = this.expression(depth + 1);
15674
- this.expect("id", "then");
15675
- const then = this.expression(depth + 1);
15676
- this.expect("id", "else");
15677
- return {
15678
- k: "if",
15679
- cond,
15680
- then,
15681
- otherwise: this.expression(depth + 1)
15682
- };
15683
- }
15684
- return this.chain("||", () => this.chain("&&", () => this.relation(depth)));
15685
- }
15686
- chain(operator, operand) {
15687
- const terms = [operand()];
15688
- while (this.take("p", operator)) terms.push(operand());
15689
- return terms.length === 1 ? terms[0] : {
15690
- k: operator === "&&" ? "and" : "or",
15691
- terms
15692
- };
15693
- }
15694
- relation(depth) {
15695
- const left = this.additive(depth);
15696
- const token = this.peek();
15697
- if (token === void 0) return left;
15698
- if (token.t === "p" && (token.v === "==" || token.v === "!=")) {
15699
- this.position += 1;
15700
- return {
15701
- k: "cmp",
15702
- equals: token.v === "==",
15703
- left,
15704
- right: this.additive(depth)
15705
- };
15706
- }
15707
- if (token.t === "p" && [
15708
- "<",
15709
- "<=",
15710
- ">",
15711
- ">="
15712
- ].includes(token.v)) {
15713
- this.position += 1;
15714
- this.additive(depth);
15715
- return UNKNOWN;
15716
- }
15717
- if (token.t === "id" && token.v === "in") {
15718
- this.position += 1;
15719
- this.additive(depth);
15720
- return UNKNOWN;
15721
- }
15722
- if (token.t === "id" && token.v === "like") {
15723
- this.position += 1;
15724
- return {
15725
- k: "like",
15726
- operand: left,
15727
- pattern: this.next("str").v
15728
- };
15729
- }
15730
- if (token.t === "id" && token.v === "has") {
15731
- this.position += 1;
15732
- this.attributePath();
15733
- return UNKNOWN;
15734
- }
15735
- if (token.t === "id" && token.v === "is") {
15736
- this.position += 1;
15737
- this.namePath();
15738
- if (this.take("id", "in")) this.additive(depth);
15739
- return UNKNOWN;
15740
- }
15741
- return left;
15742
- }
15743
- attributePath() {
15744
- const first = this.peek();
15745
- if (first === void 0 || first.t !== "id" && first.t !== "str") throw new SyntaxError("expected attribute");
15746
- this.position += 1;
15747
- while (this.take("p", ".")) {
15748
- const part = this.peek();
15749
- if (part === void 0 || part.t !== "id" && part.t !== "str") throw new SyntaxError("expected attribute");
15750
- this.position += 1;
15751
- }
15752
- }
15753
- namePath() {
15754
- this.next("id");
15755
- while (this.take("p", "::")) this.next("id");
15756
- }
15757
- additive(depth) {
15758
- let result = this.multiplicative(depth);
15759
- while (this.is("p", "+") || this.is("p", "-")) {
15760
- this.position += 1;
15761
- this.multiplicative(depth);
15762
- result = UNKNOWN;
15763
- }
15764
- return result;
15765
- }
15766
- multiplicative(depth) {
15767
- let result = this.unary(depth);
15768
- while (this.take("p", "*")) {
15769
- this.unary(depth);
15770
- result = UNKNOWN;
15771
- }
15772
- return result;
15773
- }
15774
- unary(depth) {
15775
- const prefixes = [];
15776
- while (this.is("p", "!") || this.is("p", "-")) {
15777
- prefixes.push(this.peek().v);
15778
- this.position += 1;
15779
- if (prefixes.length > MAX_NESTING) throw new SyntaxError("too deep");
15780
- }
15781
- let result = this.member(depth);
15782
- for (let i = prefixes.length - 1; i >= 0; i -= 1) result = prefixes[i] === "!" ? {
15783
- k: "not",
15784
- operand: result
15785
- } : UNKNOWN;
15786
- return result;
15787
- }
15788
- member(depth) {
15789
- let result = this.primary(depth);
15790
- let links = 0;
15791
- for (;;) {
15792
- if (this.take("p", ".")) {
15793
- const method = this.next("id").v;
15794
- if (method === "getTag") this.readsTag = true;
15795
- result = this.is("p", "(") ? {
15796
- k: "call",
15797
- method,
15798
- receiver: result,
15799
- args: this.arguments(depth)
15800
- } : attribute(result, method);
15801
- } else if (this.take("p", "[")) {
15802
- const key = this.next("str").v;
15803
- this.expect("p", "]");
15804
- result = attribute(result, decodeCedarString(key));
15805
- } else return result;
15806
- links += 1;
15807
- if (links > MAX_NESTING) throw new SyntaxError("too deep");
15808
- }
15809
- }
15810
- arguments(depth) {
15811
- this.expect("p", "(");
15812
- return this.list(")", depth + 1);
15813
- }
15814
- list(close, depth) {
15815
- const items = [];
15816
- while (!this.take("p", close)) {
15817
- items.push(this.expression(depth));
15818
- if (!this.is("p", close)) this.expect("p", ",");
15819
- }
15820
- return items;
15821
- }
15822
- primary(depth) {
15823
- const token = this.peek();
15824
- if (token === void 0) throw new SyntaxError("unexpected end");
15825
- this.position += 1;
15826
- if (token.t === "str") return {
15827
- k: "str",
15828
- raw: token.v
15829
- };
15830
- if (token.t === "num") return UNKNOWN;
15831
- if (token.t === "id") {
15832
- if (token.v === "true" || token.v === "false") return {
15833
- k: "lit",
15834
- v: token.v === "true"
15835
- };
15836
- if ([
15837
- "principal",
15838
- "resource",
15839
- "action",
15840
- "context"
15841
- ].includes(token.v)) return {
15842
- k: "var",
15843
- name: token.v
15844
- };
15845
- while (this.take("p", "::")) {
15846
- if (this.peek()?.t === "str") {
15847
- this.position += 1;
15848
- return UNKNOWN;
15849
- }
15850
- this.next("id");
15851
- }
15852
- if (this.is("p", "(")) this.arguments(depth);
15853
- return UNKNOWN;
15854
- }
15855
- if (token.v === "(") {
15856
- const inner = this.expression(depth + 1);
15857
- this.expect("p", ")");
15858
- return inner;
15859
- }
15860
- if (token.v === "[") return {
15861
- k: "set",
15862
- items: this.list("]", depth + 1)
15863
- };
15864
- if (token.v === "{") {
15865
- while (!this.take("p", "}")) {
15866
- const key = this.peek();
15867
- if (key === void 0 || key.t !== "id" && key.t !== "str") throw new SyntaxError("expected key");
15868
- this.position += 1;
15869
- this.expect("p", ":");
15870
- this.expression(depth + 1);
15871
- if (!this.is("p", "}")) this.expect("p", ",");
15872
- }
15873
- return UNKNOWN;
15874
- }
15875
- throw new SyntaxError("unexpected token");
15876
- }
15877
- };
15878
- function attribute(target, name) {
15879
- if (target.k !== "var" || name === null) return UNKNOWN;
15880
- if (target.name === "principal" && (name === "category" || name === "name")) return { k: name };
15881
- return target.name === "resource" && name === "path" ? { k: "path" } : UNKNOWN;
15882
- }
15883
- const parseExpression = (text) => new Parser(tokenize(text)).parseAll();
15884
- const triOf = (value) => value ? "yes" : "no";
15885
- const invert = (value) => value === "maybe" ? "maybe" : value === "yes" ? "no" : "yes";
15886
- const constantSets = /* @__PURE__ */ new WeakMap();
15887
- function valueOf(expr, facts, read) {
15888
- switch (expr.k) {
15889
- case "str": {
15890
- const decoded = decodeCedarString(expr.raw);
15891
- return decoded === null ? { k: "unknown" } : {
15892
- k: "str",
15893
- v: decoded
15894
- };
15895
- }
15896
- case "category": return {
15897
- k: "str",
15898
- v: read
15899
- };
15900
- case "path": return facts.path === void 0 ? { k: "unknown" } : {
15901
- k: "str",
15902
- v: facts.path
15903
- };
15904
- case "name": return { k: "name" };
15905
- case "set": {
15906
- const known = constantSets.get(expr);
15907
- if (known !== void 0) return known;
15908
- const items = expr.items.map((item) => valueOf(item, facts, read));
15909
- const value = items.some((item) => item.k === "set") ? { k: "unknown" } : {
15910
- k: "set",
15911
- items
15912
- };
15913
- if (expr.items.every((item) => item.k === "str")) constantSets.set(expr, value);
15914
- return value;
15915
- }
15916
- case "if": {
15917
- const cond = evaluateExpression(expr.cond, facts);
15918
- if (cond === "maybe") return { k: "unknown" };
15919
- return valueOf(cond === "yes" ? expr.then : expr.otherwise, facts, read);
15920
- }
15921
- case "lit":
15922
- case "and":
15923
- case "or":
15924
- case "not":
15925
- case "cmp":
15926
- case "like":
15927
- case "call": return {
15928
- k: "tri",
15929
- v: evaluateExpression(expr, facts)
15930
- };
15931
- default: return { k: "unknown" };
15932
- }
15933
- }
15934
- function sameValue(left, right) {
15935
- if (left.k === "unknown" || right.k === "unknown") return "maybe";
15936
- if (left.k === "name" || right.k === "name") {
15937
- const other = left.k === "name" ? right : left;
15938
- if (other.k !== "str") return other.k === "name" ? "maybe" : "no";
15939
- return HUMAN_NAMES.includes(other.v.trim().toLowerCase()) ? "maybe" : "no";
15940
- }
15941
- if (left.k === "tri" && right.k === "tri") return left.v === "maybe" || right.v === "maybe" ? "maybe" : triOf(left.v === right.v);
15942
- if (left.k === "tri" || right.k === "tri") return "no";
15943
- if (left.k === "str" && right.k === "str") return triOf(left.v === right.v);
15944
- if (left.k === "set" && right.k === "set") {
15945
- const [leftIndex, rightIndex] = [indexItems(left.items), indexItems(right.items)];
15946
- if (leftIndex.pure && rightIndex.pure) return triOf(leftIndex.strings.size === rightIndex.strings.size && holdsAll(leftIndex, rightIndex));
15947
- const covers = (from, into) => {
15948
- const index = indexItems(into);
15949
- return combine(from.map((item) => member(item, index)), "and");
15950
- };
15951
- return combine([covers(left.items, right.items), covers(right.items, left.items)], "and");
15952
- }
15953
- return "no";
15954
- }
15955
- function holdsAll(index, other) {
15956
- for (const value of other.strings) if (!index.strings.has(value)) return false;
15957
- return true;
15958
- }
15959
- function shareAny(left, right) {
15960
- const [small, large] = left.strings.size <= right.strings.size ? [left, right] : [right, left];
15961
- for (const value of small.strings) if (large.strings.has(value)) return true;
15962
- return false;
15963
- }
15964
- const indexes = /* @__PURE__ */ new WeakMap();
15965
- function indexItems(items) {
15966
- const known = indexes.get(items);
15967
- if (known !== void 0) return known;
15968
- const index = buildIndex(items);
15969
- indexes.set(items, index);
15970
- return index;
15971
- }
15972
- function buildIndex(items) {
15973
- const strings = /* @__PURE__ */ new Set();
15974
- const representatives = /* @__PURE__ */ new Map();
15975
- for (const item of items) if (item.k === "str") {
15976
- strings.add(item.v);
15977
- representatives.set(HUMAN_NAMES.includes(item.v.trim().toLowerCase()) ? "human" : "str", item);
15978
- } else representatives.set(item.k === "tri" ? `tri:${item.v}` : item.k, item);
15979
- return {
15980
- strings,
15981
- representatives: [...representatives.values()],
15982
- pure: items.every((item) => item.k === "str")
15983
- };
15984
- }
15985
- function member(item, index) {
15986
- if (item.k === "str" && index.strings.has(item.v)) return "yes";
15987
- return combine(index.representatives.map((candidate) => sameValue(item, candidate)), "or");
15988
- }
15989
- function combine(results, op) {
15990
- const decisive = op === "and" ? "no" : "yes";
15991
- if (results.includes(decisive)) return decisive;
15992
- return results.includes("maybe") ? "maybe" : invert(decisive);
15993
- }
15994
- function setCall(method, receiver, args) {
15995
- if (receiver.k !== "set") return "maybe";
15996
- if (method === "isEmpty" && args.length === 0) return triOf(receiver.items.length === 0);
15997
- const [argument] = args;
15998
- if (args.length !== 1) return "maybe";
15999
- const index = indexItems(receiver.items);
16000
- if (method === "contains") return member(argument, index);
16001
- if (argument.k !== "set") return "maybe";
16002
- if (method === "containsAny" || method === "containsAll") {
16003
- const other = indexItems(argument.items);
16004
- if (index.pure && other.pure) return triOf(method === "containsAny" ? shareAny(index, other) : other.strings.size <= index.strings.size && holdsAll(index, other));
16005
- return combine(argument.items.map((item) => member(item, index)), method === "containsAny" ? "or" : "and");
16006
- }
16007
- return "maybe";
16008
- }
16009
- const leaves = (expr) => expr.k === "set" ? expr.items.flatMap(leaves) : expr.k === "if" ? [...leaves(expr.then), ...leaves(expr.otherwise)] : [expr];
16010
- function strings(exprs) {
16011
- const found = [];
16012
- for (const part of exprs.flatMap(leaves)) {
16013
- const decoded = part.k === "str" ? decodeCedarString(part.raw) : null;
16014
- if (decoded !== null) found.push(decoded);
16015
- }
16016
- return found;
16017
- }
16018
- const readsCategory = (exprs) => exprs.flatMap(leaves).some((part) => part.k === "category");
16019
- const spelledAtoms = /* @__PURE__ */ new WeakMap();
16020
- function spelledBy(expr) {
16021
- let spelled = spelledAtoms.get(expr);
16022
- if (spelled === void 0) {
16023
- const sides = expr.k === "cmp" ? [expr.left, expr.right] : [expr.receiver, ...expr.args];
16024
- spelled = {
16025
- reads: readsCategory(sides),
16026
- names: new Set(strings(sides))
16027
- };
16028
- spelledAtoms.set(expr, spelled);
16029
- }
16030
- return spelled;
16031
- }
16032
- function mentions(expr, name) {
16033
- if (name === void 0) return false;
16034
- if (expr.k === "like") {
16035
- const segments = cedarLikeSegments(expr.pattern);
16036
- return readsCategory([expr.operand]) && segments.some((segment) => segment.includes(name)) && globMatches(segments, name);
16037
- }
16038
- const { reads, names } = spelledBy(expr);
16039
- return reads && names.has(name);
16040
- }
16041
- const readOf = (expr, facts) => mentions(expr, facts.unnamed) ? UNNAMED_CATEGORY : facts.category;
16042
- function evaluateExpression(expr, facts) {
16043
- switch (expr.k) {
16044
- case "lit": return triOf(expr.v);
16045
- case "not": return invert(evaluateExpression(expr.operand, facts));
16046
- case "and":
16047
- case "or": return combine(expr.terms.map((term) => evaluateExpression(term, facts)), expr.k);
16048
- case "if": {
16049
- const cond = evaluateExpression(expr.cond, facts);
16050
- if (cond !== "maybe") return evaluateExpression(cond === "yes" ? expr.then : expr.otherwise, facts);
16051
- const [then, otherwise] = [expr.then, expr.otherwise].map((branch) => evaluateExpression(branch, facts));
16052
- return then === otherwise ? then : "maybe";
16053
- }
16054
- case "cmp": {
16055
- const read = readOf(expr, facts);
16056
- const same = sameValue(valueOf(expr.left, facts, read), valueOf(expr.right, facts, read));
16057
- return expr.equals ? same : invert(same);
16058
- }
16059
- case "like": {
16060
- const subject = valueOf(expr.operand, facts, readOf(expr, facts));
16061
- if (UNSUPPORTED_PATTERN_ESCAPE.test(expr.pattern)) return "maybe";
16062
- const segments = cedarLikeSegments(expr.pattern);
16063
- if (subject.k === "name") return HUMAN_NAMES.some((candidate) => globMatches(segments, candidate)) ? "maybe" : "no";
16064
- if (subject.k !== "str") return "maybe";
16065
- return triOf(globMatches(segments, subject.v));
16066
- }
16067
- case "call": {
16068
- const read = readOf(expr, facts);
16069
- return setCall(expr.method, valueOf(expr.receiver, facts, read), expr.args.map((arg) => valueOf(arg, facts, read)));
16070
- }
16071
- default: return "maybe";
16072
- }
16073
- }
16074
-
16075
- //#endregion
16076
- //#region src/policy/cedar-principal-scope.ts
16077
- const PROBE_CLASSES = ["human", NO_EVIDENCE_CATEGORY];
16078
- const ANONYMOUS_PRINCIPAL_ID = "anonymous";
16079
- const S = CEDAR_SPACE_CLASS;
16080
- const HEAD = new RegExp(`\\b(forbid|permit)${S}*\\(`, "g");
16081
- const isAnnotationName = (code, index) => {
16082
- let position = index - 1;
16083
- while (position >= 0 && isCedarSpace(code[position])) position -= 1;
16084
- return code[position] === "@";
16085
- };
16086
- const skipSpace = (text, from) => {
16087
- let index = from;
16088
- while (index < text.length && isCedarSpace(text[index])) index += 1;
16089
- return index;
16090
- };
16091
- const conditionAt = (text, from) => {
16092
- const keywordStart = skipSpace(text, from);
16093
- const kind = text.startsWith("when", keywordStart) ? "when" : text.startsWith("unless", keywordStart) ? "unless" : null;
16094
- if (kind === null) return null;
16095
- const braceOpen = skipSpace(text, keywordStart + kind.length);
16096
- return text[braceOpen] === "{" ? {
16097
- kind,
16098
- braceOpen
16099
- } : null;
16100
- };
16101
- function matching(code, openIndex, open, close) {
16102
- let depth = 0;
16103
- for (let i = openIndex; i < code.length; i++) if (code[i] === open) depth++;
16104
- else if (code[i] === close) {
16105
- depth--;
16106
- if (depth === 0) return i;
16107
- }
16108
- return -1;
16109
- }
16110
- function parseCedarStatements(cedar) {
16111
- const { visible, code } = maskCedar(cedar);
16112
- const statements = [];
16113
- const heads = new RegExp(HEAD.source, "g");
16114
- let previousEnd = 0;
16115
- let match = heads.exec(code);
16116
- while (match !== null) {
16117
- if (isAnnotationName(code, match.index)) {
16118
- match = heads.exec(code);
16119
- continue;
16120
- }
16121
- const open = match.index + match[0].length - 1;
16122
- const scopeEnd = matching(code, open, "(", ")");
16123
- if (scopeEnd < 0) break;
16124
- const conditions = [];
16125
- let position = scopeEnd + 1;
16126
- for (;;) {
16127
- const condition = conditionAt(code, position);
16128
- if (condition === null) break;
16129
- const braceClose = matching(code, condition.braceOpen, "{", "}");
16130
- if (braceClose < 0) {
16131
- position = code.length;
16132
- break;
16133
- }
16134
- conditions.push({
16135
- kind: condition.kind,
16136
- body: visible.slice(condition.braceOpen + 1, braceClose)
16137
- });
16138
- position = braceClose + 1;
16139
- }
16140
- const terminatorAt = skipSpace(code, position);
16141
- const end = code[terminatorAt] === ";" ? terminatorAt + 1 : position;
16142
- statements.push({
16143
- effect: match[1],
16144
- blockStart: Math.min(skipSpace(cedar, previousEnd), match.index),
16145
- start: match.index,
16146
- end,
16147
- text: visible.slice(match.index, end),
16148
- scope: visible.slice(open + 1, scopeEnd),
16149
- conditions,
16150
- annotations: visible.slice(previousEnd, match.index)
16151
- });
16152
- previousEnd = end;
16153
- heads.lastIndex = end;
16154
- match = heads.exec(code);
16155
- }
16156
- return statements;
16157
- }
16158
- const TRUE_BODY = new RegExp(`^${S}*true${S}*$`);
16159
- const PRINCIPAL_EQUALS = new RegExp(`\\bprincipal${S}*==`);
16160
- const ENTITY_ID = new RegExp(`::${S}*"((?:\\\\.|[^"\\\\])*)"`, "g");
16161
- const IS_TYPE = new RegExp(`\\bis${S}+([\\w:]+)`);
16162
- const ID_ANNOTATION = new RegExp(`@id\\(${S}*"((?:\\\\.|[^"\\\\])*)"${S}*\\)`, "g");
16163
- function principalScope(scope) {
16164
- const { visible, code } = maskCedar(scope);
16165
- let depth = 0;
16166
- let end = code.length;
16167
- for (let i = 0; i < code.length; i++) {
16168
- const char = code[i];
16169
- if (char === "(" || char === "[" || char === "{") depth++;
16170
- else if (char === ")" || char === "]" || char === "}") depth--;
16171
- else if (char === "," && depth === 0) {
16172
- end = i;
16173
- break;
16174
- }
16175
- }
16176
- const text = visible.slice(0, end);
16177
- const masked = code.slice(0, end);
16178
- if (PRINCIPAL_EQUALS.test(masked) || /\bin\b/.test(masked)) return Array.from(text.matchAll(ENTITY_ID), (m) => decodeCedarString(m[1])).some((id) => id === null || id === ANONYMOUS_PRINCIPAL_ID) ? "maybe" : "no";
16179
- const isType = IS_TYPE.exec(masked);
16180
- if (isType) return isType[1].split("::").pop() === "Agent" ? "maybe" : "no";
16181
- return "yes";
16182
- }
16183
- const prepared = /* @__PURE__ */ new WeakMap();
16184
- function parsedCondition(body) {
16185
- try {
16186
- return parseExpression(body);
16187
- } catch {
16188
- return null;
16189
- }
16190
- }
16191
- function evaluableOf(statement) {
16192
- return {
16193
- scope: principalScope(statement.scope),
16194
- conditions: statement.conditions.map(({ kind, body }) => ({
16195
- kind,
16196
- node: parsedCondition(body)
16197
- }))
16198
- };
16199
- }
16200
- function preparedOf(statement) {
16201
- let entry = prepared.get(statement);
16202
- if (entry === void 0) {
16203
- const named = namesNoEvidence(statement.text);
16204
- entry = {
16205
- namesNoEvidence: named,
16206
- substituted: !named && withNoEvidenceExclusion(statement.text) !== statement.text,
16207
- evaluable: evaluableOf(statement)
16208
- };
16209
- prepared.set(statement, entry);
16210
- }
16211
- return entry;
16212
- }
16213
- function statementApplies(statement, facts) {
16214
- const { substituted, evaluable } = preparedOf(statement);
16215
- const read = facts.category === "no_evidence" && substituted ? {
16216
- ...facts,
16217
- category: "human"
16218
- } : facts;
16219
- const effective = {
16220
- category: read.category,
16221
- path: read.path,
16222
- unnamed: facts.discountNaming ? read.category : void 0
16223
- };
16224
- if (evaluable.scope === "no") return false;
16225
- for (const { kind, node } of evaluable.conditions) {
16226
- const result = node === null ? "maybe" : evaluateExpression(node, effective);
16227
- if (kind === "when" && result === "no") return false;
16228
- if (kind === "unless" && result === "yes") return false;
16229
- }
16230
- return true;
16231
- }
16232
- function reachesClassOnlyByNaming(statement, probe, path) {
16233
- return statementApplies(statement, {
16234
- category: probe,
16235
- path
16236
- }) && !statementApplies(statement, {
16237
- category: probe,
16238
- path,
16239
- discountNaming: true
16240
- });
16241
- }
16242
- function statementId(statement) {
16243
- return Array.from(statement.annotations.matchAll(ID_ANNOTATION), (m) => unescapeCedarString(m[1])).at(-1);
16244
- }
16245
- let memoText;
16246
- let memoParsed = {
16247
- text: "",
16248
- statements: []
16249
- };
16250
- function parsedOf(cedar) {
16251
- if (memoText !== cedar) {
16252
- const text = withoutNoEvidenceExclusion(cedar);
16253
- memoParsed = {
16254
- text,
16255
- statements: parseCedarStatements(text)
16256
- };
16257
- memoText = cedar;
16258
- }
16259
- return memoParsed;
16260
- }
16261
- function analyzePolicyScope(cedar) {
16262
- const { text, statements } = parsedOf(cedar);
16263
- return {
16264
- unnarrowedDeny(path) {
16265
- const found = [];
16266
- let line = 1;
16267
- let counted = 0;
16268
- for (const statement of statements) {
16269
- if (statement.effect !== "forbid") continue;
16270
- const classes = PROBE_CLASSES.filter((probe) => statementApplies(statement, {
16271
- category: probe,
16272
- path
16273
- }) && !reachesClassOnlyByNaming(statement, probe, path));
16274
- if (classes.length > 0) {
16275
- for (; counted < statement.blockStart; counted++) if (text.charCodeAt(counted) === 10) line++;
16276
- found.push({
16277
- statement,
16278
- classes,
16279
- line
16280
- });
16281
- }
16282
- }
16283
- return found;
16284
- },
16285
- denyNamingClass(path, probe) {
16286
- return statements.filter((statement) => statement.effect === "forbid" && (probe !== "no_evidence" || preparedOf(statement).namesNoEvidence) && reachesClassOnlyByNaming(statement, probe, path));
16287
- },
16288
- lacksBaselinePermit() {
16289
- return statements.length > 0 && !statements.some(isBaselinePermit);
16290
- }
16291
- };
16292
- }
16293
- const unnarrowedDenyStatements = (cedar, path) => analyzePolicyScope(cedar).unnarrowedDeny(path);
16294
- const lacksBaselinePermit = (cedar) => analyzePolicyScope(cedar).lacksBaselinePermit();
16295
- function isBaselinePermit(statement) {
16296
- return statement.effect === "permit" && principalScope(statement.scope) === "yes" && statement.conditions.every((condition) => condition.kind === "when" && TRUE_BODY.test(condition.body));
16297
- }
16298
-
16299
- //#endregion
16300
- //#region src/policy/cedar-rule-match.ts
16301
- /**
16302
- * Shared best-effort matchers for reading a composed Cedar policy's per-rule
16303
- * annotations (`@scopes`, `@approvers`, …) WITHOUT a Cedar AST. Both
16304
- * `requiredScopesForRequest` (consent scopes) and `approvalQuorumForRequest`
16305
- * (step-up quorum) narrow a rule's annotation to a request the same way the
16306
- * compose engine's own `parseExistingCedar` does: blocks split on blank lines,
16307
- * a rule contributes only when EVERY request fact it constrains matches.
16308
- *
16309
- * A fact is matched against the SAME projection the gateway/edge feeds the
16310
- * engine (`name = agentName`, `category = scraper|detectionClass`), so the
16311
- * narrowing mirrors the engine's own evaluation. An UNKNOWN fact never narrows.
16312
- */
16313
- const UNLESS_BRACE = new RegExp(`unless${CEDAR_SPACE_CLASS}*\\{`);
16314
- const FORBID_HEAD = new RegExp(`\\bforbid${CEDAR_SPACE_CLASS}*\\(`, "g");
16315
- /**
16316
- * A block applies when its path AND principal conditions all match the KNOWN
16317
- * request facts. An unknown fact never narrows (so the no-`request` case unions
16318
- * every matching rule's annotation).
16319
- */
16320
- function blockApplies(block, request) {
16321
- if (request?.path !== void 0 && !blockMatchesPath(block, request.path)) return false;
16322
- if (request?.name !== void 0 && !blockMatchesEquality(block, "principal.name", request.name)) return false;
16323
- if (request?.category !== void 0) {
16324
- if (!blockMatchesEquality(block, "principal.category", categoryRead(block, request.category))) return false;
16325
- }
16326
- return true;
16327
- }
16328
- function categoryRead(block, category) {
16329
- if (category !== "no_evidence") return category;
16330
- const original = withoutNoEvidenceExclusion(block);
16331
- return withNoEvidenceExclusion(original) !== original ? "human" : category;
16332
- }
16333
- /** The `resource.path` literals appearing anywhere in `text` (no `when`/
16334
- * `unless` scoping — callers that care about scope use `splitWhenUnless`
16335
- * first). Shared regex extraction for `pathLiteralsInBlock` and the
16336
- * scope-aware helpers below. */
16337
- function pathLiteralsInText(text) {
16338
- return Array.from(text.matchAll(cedarQuotedValueRegExp("resource\\.path (?:like|==) ", "g")), (m) => unescapeCedarString(m[1]));
16339
- }
16340
- /**
16341
- * The `resource.path` literals a block MENTIONS anywhere — `when` or
16342
- * `unless` alike (empty = the block never mentions a path). Used for
16343
- * enumeration (which concrete paths does this bundle reference at all),
16344
- * NOT for "does this block's condition match path" — that's
16345
- * `blockMatchesPath`, which is `unless`-aware. Mixing the two up is exactly
16346
- * the bug Bugbot caught (2026-09-10): a literal that appears ONLY inside
16347
- * `unless { … }` names a path this block does NOT apply to, not one it
16348
- * targets.
16349
- */
16350
- function pathLiteralsInBlock(block) {
16351
- return pathLiteralsInText(block);
16352
- }
16353
- /**
16354
- * Split `block` into its `when`-scoped text and its `unless`-scoped inner
16355
- * text, mirroring the compose engine's own excision order
16356
- * (`apps/web/lib/compose/cedar.ts`'s `unless` handling): `unless { … }` is
16357
- * located first and excised, so its own literals never leak into what
16358
- * counts as the block's `when` (narrowing) scope.
16359
- *
16360
- * CodeQL js/polynomial-redos: a single `/unless\s*\{([\s\S]*?)\}\s*;?/`
16361
- * regex is quadratic on a policy blob containing many "unless{"
16362
- * substrings with no closing brace (composed policy text is untrusted,
16363
- * customer-authored input evaluated on the request hot path) — an
16364
- * unanchored match retries the unbounded `[\s\S]*?` scan-to-end at every
16365
- * failed start position. `search()` for the fixed-length "unless\s*{"
16366
- * prefix has no such ambiguity (each position fails fast), and the
16367
- * closing brace is then found with a single linear `indexOf`, so the
16368
- * whole split stays O(n) regardless of how many false "unless{" starts
16369
- * the text contains.
16370
- */
16371
- function splitWhenUnless(block) {
16372
- const unlessIndex = block.search(UNLESS_BRACE);
16373
- if (unlessIndex === -1) return {
16374
- whenText: block,
16375
- unlessText: ""
16376
- };
16377
- const openBraceIndex = block.indexOf("{", unlessIndex);
16378
- const closeBraceIndex = block.indexOf("}", openBraceIndex + 1);
16379
- if (closeBraceIndex === -1) return {
16380
- whenText: block,
16381
- unlessText: ""
16382
- };
16383
- return {
16384
- whenText: block.slice(0, unlessIndex),
16385
- unlessText: block.slice(openBraceIndex + 1, closeBraceIndex)
16386
- };
16387
- }
16388
- /**
16389
- * A block applies to `path` when: no `unless` literal excludes it, AND
16390
- * either the `when` scope has no path constraint at all (unconstrained →
16391
- * matches every path except what `unless` just excluded), or one of the
16392
- * `when` scope's path literals matches (exact, or a `*`-prefix glob).
16393
- *
16394
- * Bugbot (2026-09-10): the previous version read path literals from the
16395
- * WHOLE block regardless of `when` vs `unless`, so a site-wide forbid whose
16396
- * only path mention was an `unless { resource.path == "/checkout" }`
16397
- * exemption got scored as "targets only /checkout" — backwards. It applies
16398
- * to every path EXCEPT the excepted one, not ONLY the excepted one.
16399
- */
16400
- function blockMatchesPath(block, path) {
16401
- const { whenText, unlessText } = splitWhenUnless(block);
16402
- if (pathLiteralsInText(unlessText).some((literal) => pathLiteralMatches(literal, path))) return false;
16403
- const whenLiterals = pathLiteralsInText(whenText);
16404
- if (whenLiterals.length === 0) return true;
16405
- return whenLiterals.some((literal) => pathLiteralMatches(literal, path));
16406
- }
16407
- /** Escape every regex metacharacter in `s` (so it matches literally). */
16408
- function escapeRegExp(s) {
16409
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16410
- }
16411
- /**
16412
- * Split a composed Cedar bundle into per-rule blocks (blank-line separated),
16413
- * trimmed and with empties dropped. Mirrors the compose engine's own block
16414
- * split (`apps/web/lib/compose/cedar.ts` `parseCedarBlocks`).
16415
- */
16416
- function splitCedarBlocks(cedar) {
16417
- return cedar.split(/\n\s*\n/).map((b) => b.trim()).filter((b) => b.length > 0);
16418
- }
16419
- /**
16420
- * The set of values a block positively constrains `attr` to via `== ` literals.
16421
- * Empty = the block places no `==` constraint on `attr` (unconstrained).
16422
- */
16423
- function blockEqualityLiterals(block, attr) {
16424
- const a = escapeRegExp(attr);
16425
- return Array.from(block.matchAll(cedarQuotedValueRegExp(`${a} == `, "g")), (m) => unescapeCedarString(m[1]));
16426
- }
16427
- /**
16428
- * The set of values a block EXCLUDES `attr` from via `!= ` literals.
16429
- * Empty = the block places no `!=` constraint on `attr`.
16430
- */
16431
- function blockExclusionLiterals(block, attr) {
16432
- const a = escapeRegExp(attr);
16433
- return Array.from(block.matchAll(cedarQuotedValueRegExp(`${a} != `, "g")), (m) => unescapeCedarString(m[1]));
16434
- }
16435
- /** A block applies to `value` when it is NOT excluded by a `!=` literal AND
16436
- * (it declares no `==` literal — unconstrained → applies to all — or `value` is
16437
- * one of them; compose emits an OR-disjunction for a name set). Without the `!=`
16438
- * arm a rule that challenges everyone EXCEPT X (`principal.name != "X"`) would
16439
- * over-advertise its annotation to X — a broader grant than the rule meant. */
16440
- function blockMatchesEquality(block, attr, value) {
16441
- const eq = blockEqualityLiterals(block, attr);
16442
- if (blockExclusionLiterals(block, attr).includes(value)) return false;
16443
- if (eq.length > 0) return eq.includes(value);
16444
- return true;
16445
- }
16446
- /**
16447
- * Match a `resource.path` literal against the request path with CEDAR `like`
16448
- * semantics — NOT the package's `matchPath`. Cedar `*` matches any sequence
16449
- * INCLUDING `/` (regex `.*`), whereas `matchPath` treats a single `*` as
16450
- * `[^/]*` (no slash); using it here would disagree with what the engine
16451
- * actually matched. A `==`/non-wildcard literal is an exact match; a `like`
16452
- * literal maps each `*` (and `**`) to `.*`, anchored.
16453
- */
16454
- function pathLiteralMatches(literal, path) {
16455
- return globMatches(literal.split("*"), path);
16456
- }
16457
- /**
16458
- * True when the block contains a Cedar `forbid` statement (a deny rule). A bare
16459
- * `forbid` defaults to BLOCK; a `@verdict(...)` annotation refines the kind.
16460
- */
16461
- function isForbidBlock(block) {
16462
- const { code } = maskCedar(block);
16463
- return Array.from(code.matchAll(FORBID_HEAD)).some(({ index }) => !isAnnotationName(code, index));
16464
- }
16465
- function isUnnarrowedDenyBlock(block) {
16466
- return unnarrowedDenyStatements(block).some(({ classes }) => classes.includes("human"));
16467
- }
16468
- function analyzePolicySource(cedar) {
16469
- const scope = analyzePolicyScope(cedar);
16470
- const analysis = {
16471
- unnarrowedDenyFor: (path, probe) => scope.unnarrowedDeny(path).some(({ classes }) => classes.includes(probe)),
16472
- explicitDenyFor: (path, probe) => scope.denyNamingClass(path, probe).length > 0,
16473
- humanHazard: (path) => analysis.unnarrowedDenyFor(path, "human"),
16474
- noEvidenceHazard: (path) => analysis.unnarrowedDenyFor(path, "no_evidence") && !analysis.noEvidenceNamed(path),
16475
- noEvidenceNamed: (path) => analysis.explicitDenyFor(path, NO_EVIDENCE_CATEGORY)
16476
- };
16477
- return analysis;
16478
- }
16479
- function pathHasUnnarrowedDenyRuleFor(cedar, path, probe) {
16480
- return analyzePolicySource(cedar).unnarrowedDenyFor(path, probe);
16481
- }
16482
- function pathHasExplicitDenyRuleFor(cedar, path, probe) {
16483
- return analyzePolicySource(cedar).explicitDenyFor(path, probe);
16484
- }
16485
- function pathHasUnnarrowedDenyRule(cedar, path) {
16486
- return analyzePolicySource(cedar).humanHazard(path);
16487
- }
16488
-
16489
- //#endregion
16490
- //#region src/policy/byte-bounded-memo.ts
16491
- var ByteBoundedMemo = class {
16492
- budgetBytes;
16493
- entries = /* @__PURE__ */ new Map();
16494
- used = 0;
16495
- constructor(budgetBytes) {
16496
- this.budgetBytes = budgetBytes;
16497
- }
16498
- remember(key, bytes, make) {
16499
- const hit = this.entries.get(key);
16500
- if (hit !== void 0) {
16501
- this.entries.delete(key);
16502
- this.entries.set(key, hit);
16503
- return hit.value;
16504
- }
16505
- const value = make();
16506
- if (bytes > this.budgetBytes) return value;
16507
- this.entries.set(key, {
16508
- value,
16509
- bytes
16510
- });
16511
- this.used += bytes;
16512
- for (const [oldest, entry] of this.entries) {
16513
- if (this.used <= this.budgetBytes) break;
16514
- this.entries.delete(oldest);
16515
- this.used -= entry.bytes;
16516
- }
16517
- return value;
16518
- }
16519
- };
16520
-
16521
- //#endregion
16522
- //#region src/policy/unsubstituted-source.ts
16523
- const BUDGET_BYTES = 4194304;
16524
- const BYTES_PER_CHARACTER = 4;
16525
- const memo = new ByteBoundedMemo(BUDGET_BYTES);
16526
- const unsubstitutedSource = (source) => memo.remember(source, source.length * BYTES_PER_CHARACTER, () => withoutNoEvidenceExclusion(source));
16527
-
16528
- //#endregion
16529
- //#region src/policy/required-scopes.ts
16530
- /**
16531
- * Consent scopes a composed Cedar policy REQUIRES for a request — the
16532
- * `@scopes(...)` annotations the compose engine writes on CHALLENGE-verdict
16533
- * rules (alongside `unless { context.granted_scopes.contains("S") }`).
16534
- *
16535
- * WHY: when a scope-gated rule challenges a request, the step-up must request
16536
- * EXACTLY the scopes the policy demands, so the consent flow mints a delegation
16537
- * carrying them (and the agent's retry then satisfies the carve-out). The
16538
- * policy is the source of truth for "what this route requires", so reading its
16539
- * `@scopes` is reading the SSOT — not re-deriving an engine-computed value.
16540
- *
16541
- * Best-effort TEXT parse (no Cedar AST), mirroring the compose engine's own
16542
- * `parseExistingCedar`: blocks are split on blank lines. A CHALLENGE block
16543
- * contributes its scopes only when EVERY request fact it constrains matches —
16544
- * `resource.path`, `principal.name`, and `principal.category` — so on a shared
16545
- * path the scopes of ANOTHER agent's CHALLENGE rule are not advertised (the
16546
- * engine challenged on the rule whose `when` matched, not merely the path).
16547
- *
16548
- * A fact is matched against the SAME projection the gateway feeds the engine
16549
- * (`name = detection.agentName`, `category = scraper|detectionClass`), so the
16550
- * narrowing mirrors the engine's own evaluation. An UNKNOWN fact never narrows:
16551
- * with no `request` (the consent allow-list case) this returns the union of
16552
- * every CHALLENGE rule's scopes — exactly what consent must be able to grant.
16553
- */
16554
- function requiredScopesForRequest(policySource, request) {
16555
- if (!policySource || !policySource.trim()) return [];
16556
- const out = /* @__PURE__ */ new Set();
16557
- for (const block of unsubstitutedSource(policySource).split(/\n\s*\n/)) {
16558
- if (!/@verdict\("CHALLENGE"\)/.test(block)) continue;
16559
- const scopesMatch = block.match(cedarQuotedValueRegExp("@scopes\\("));
16560
- if (!scopesMatch) continue;
16561
- const scopes = scopesMatch[1].split(/\s+/).filter(Boolean).map(unescapeCedarString);
16562
- if (scopes.length === 0) continue;
16563
- if (!blockApplies(block, request)) continue;
16564
- for (const scope of scopes) out.add(scope);
16565
- }
16566
- return [...out];
16567
- }
16568
-
16569
- //#endregion
16570
- //#region src/policy/decision-policy-id.ts
16571
- function decisionPolicyId(decision) {
16572
- switch (decision.kind) {
16573
- case "Permit": return decision.policyId;
16574
- case "Block": return decision.reason?.kind === "PolicyDenied" ? decision.reason.policyId : void 0;
16575
- case "Challenge": return decision.params?.policyId;
16576
- case "Redirect": return decision.target?.policyId;
16577
- case "Instruct": return decision.payload?.policyId;
16578
- default: return;
16579
- }
16580
- }
16581
-
16582
15117
  //#endregion
16583
15118
  //#region src/policy/bespoke-policy.ts
16584
15119
  /** Stable synthetic `@id` per explicit bespoke mechanism. */
@@ -16638,125 +15173,25 @@ function nonNavigablePolicyLabel(policyId) {
16638
15173
  //#endregion
16639
15174
  //#region src/policy/policy-lint.ts
16640
15175
  const NARROW_ADVICE = "Add a `principal.category == \"ai_agent\"` (or `principal.name`) condition, or confirm you intend to affect them.";
16641
- const EVERYONE_MESSAGE = `This rule denies every visitor, including humans and ${NO_EVIDENCE_CATEGORY} visitors, because it does not narrow the principal. ${NARROW_ADVICE}`;
15176
+ const EVERYONE_MESSAGE = `This rule denies every visitor, including humans and ${require_step_up.NO_EVIDENCE_CATEGORY} visitors, because it does not narrow the principal. ${NARROW_ADVICE}`;
16642
15177
  const HUMAN_MESSAGE = `This rule denies human visitors because it does not narrow the principal. ${NARROW_ADVICE}`;
16643
- const NO_EVIDENCE_MESSAGE = `This rule also applies to ${NO_EVIDENCE_CATEGORY} visitors, who are real people whose browser sent no evidence to classify. Add a \`${NO_EVIDENCE_EXCLUSION_TERM}\` condition, or confirm you intend to affect them.`;
16644
- const messageFor = (classes) => classes.length === PROBE_CLASSES.length ? EVERYONE_MESSAGE : classes.includes("no_evidence") ? NO_EVIDENCE_MESSAGE : HUMAN_MESSAGE;
15178
+ const NO_EVIDENCE_MESSAGE = `This rule also applies to ${require_step_up.NO_EVIDENCE_CATEGORY} visitors, who are real people whose browser sent no evidence to classify. Add a \`${require_step_up.NO_EVIDENCE_EXCLUSION_TERM}\` condition, or confirm you intend to affect them.`;
15179
+ const messageFor = (classes) => classes.length === require_step_up.PROBE_CLASSES.length ? EVERYONE_MESSAGE : classes.includes("no_evidence") ? NO_EVIDENCE_MESSAGE : HUMAN_MESSAGE;
16645
15180
  function lintUnnarrowedDenyRules(cedar) {
16646
- return unnarrowedDenyStatements(cedar).map(({ statement, classes, line }) => ({
16647
- ruleId: statementId(statement),
15181
+ return require_step_up.unnarrowedDenyStatements(cedar).map(({ statement, classes, line }) => ({
15182
+ ruleId: require_step_up.statementId(statement),
16648
15183
  line,
16649
15184
  message: messageFor(classes)
16650
15185
  }));
16651
15186
  }
16652
- const MISSING_BASELINE_MESSAGE = `This policy has no baseline permit, so every visitor that no permit rule covers is denied, humans and ${NO_EVIDENCE_CATEGORY} visitors included. Add \`permit(principal, action, resource);\` if you want unmatched traffic allowed.`;
15187
+ const MISSING_BASELINE_MESSAGE = `This policy has no baseline permit, so every visitor that no permit rule covers is denied, humans and ${require_step_up.NO_EVIDENCE_CATEGORY} visitors included. Add \`permit(principal, action, resource);\` if you want unmatched traffic allowed.`;
16653
15188
  function lintMissingBaselinePermit(cedar) {
16654
- return lacksBaselinePermit(cedar) ? [{
15189
+ return require_step_up.lacksBaselinePermit(cedar) ? [{
16655
15190
  line: 1,
16656
15191
  message: MISSING_BASELINE_MESSAGE
16657
15192
  }] : [];
16658
15193
  }
16659
15194
 
16660
- //#endregion
16661
- //#region src/policy/approval-quorum.ts
16662
- /**
16663
- * The step-up APPROVAL QUORUM a composed Cedar policy requires for a request —
16664
- * the `@approvers(...)` (+ optional `@quorum("N")`) annotations on a
16665
- * CHALLENGE-verdict rule.
16666
- *
16667
- * WHY (ADR D7 — distinct verdict): the engine emits a single `Challenge` for
16668
- * both consent (`@scopes`) and human-approval step-up (`@approvers`). They are
16669
- * DIFFERENT security flows and must not collide — a consent challenge mints a
16670
- * delegation; an approval-quorum challenge demands N-of-M humans cryptographically
16671
- * sign. This classifier is the seam that tells them apart from the policy text:
16672
- * - a CHALLENGE rule carrying `@approvers` → an approval quorum (this returns it)
16673
- * - a CHALLENGE rule with only `@scopes` (or neither) → consent (returns null)
16674
- *
16675
- * It mirrors {@link requiredScopesForRequest}: the SAME best-effort block parse
16676
- * and the SAME request narrowing (shared {@link blockApplies}), so the rule it
16677
- * reads the quorum off is the rule the engine actually challenged on — not merely
16678
- * one that shares a path. Reading the annotation is reading the SSOT (the policy
16679
- * is the source of truth for "what this action requires"), not re-deriving it.
16680
- *
16681
- * The engine carries no rule id on its Challenge, so the classifier re-matches by
16682
- * request facts and is FAIL-CLOSED on ambiguity:
16683
- * - if a CONSENT-only CHALLENGE rule ALSO applies, it returns null — the engine
16684
- * may have challenged on THAT, and reading approval off a different rule would
16685
- * conflate the two flows (ADR D7)
16686
- * - if two applying approval rules disagree on {n, approvers}, it returns null —
16687
- * enforcing the wrong approver roster is a worse failure than a clean deny
16688
- * Each caller feeds it the SAME facts its engine evaluated, so it narrows to the
16689
- * rule the engine could have fired on. The EDGE worker sets resource.path +
16690
- * principal.name and narrows on them; the Fly gateway sets NEITHER (it populates
16691
- * category + the resource entity, leaving resource.path=="" and principal.name=""),
16692
- * so it passes those as "" — path/name-scoped rules don't fire there, exactly as
16693
- * the engine sees it, and a same-scope tie falls to the fail-closed guard above.
16694
- */
16695
- function approvalQuorumForRequest(policySource, request) {
16696
- if (!policySource || !policySource.trim()) return null;
16697
- let chosen = null;
16698
- for (const block of unsubstitutedSource(policySource).split(/\n\s*\n/)) {
16699
- if (!/@verdict\("CHALLENGE"\)/.test(block)) continue;
16700
- if (!blockApplies(block, request)) continue;
16701
- const approvers = parseApprovers(block);
16702
- if (!approvers) return null;
16703
- const candidate = {
16704
- n: parseQuorumN(block),
16705
- approvers
16706
- };
16707
- if (chosen && !sameQuorum(chosen, candidate)) return null;
16708
- chosen = candidate;
16709
- }
16710
- return chosen;
16711
- }
16712
- /** The DIDs of an `@approvers("did … did")` annotation, or null when the rule
16713
- * carries none (a consent challenge) or an empty/whitespace list (no real gate). */
16714
- function parseApprovers(block) {
16715
- const m = block.match(/@approvers\("([^"]*)"\)/);
16716
- if (!m) return null;
16717
- const approvers = m[1].split(/\s+/).filter(Boolean);
16718
- return approvers.length > 0 ? approvers : null;
16719
- }
16720
- /** Two quorums match iff same n and same ordered approver list. */
16721
- function sameQuorum(a, b) {
16722
- return a.n === b.n && a.approvers.length === b.approvers.length && a.approvers.every((did, i) => did === b.approvers[i]);
16723
- }
16724
- /**
16725
- * The `@quorum("N")` count, or 1 when absent/malformed. Fail-secure: an
16726
- * unparseable or `< 1` value falls back to 1 (the smallest real quorum), never 0
16727
- * — which would make the step-up gate a no-op. The route's own
16728
- * `validateStepUpQuorum` is the second line of defence on a misconfigured n.
16729
- */
16730
- function parseQuorumN(block) {
16731
- const m = block.match(/@quorum\("([^"]*)"\)/);
16732
- if (!m) return 1;
16733
- const n = Number(m[1]);
16734
- return Number.isInteger(n) && n >= 1 ? n : 1;
16735
- }
16736
-
16737
- //#endregion
16738
- //#region src/policy/step-up.ts
16739
- /**
16740
- * Validate a `step_up` decision's quorum before approval verification.
16741
- * Fail-closed: returns a deny `reason` for any quorum that can never be
16742
- * legitimately met; `{ ok: true }` only when the quorum is a real gate.
16743
- *
16744
- * Ordering is load-bearing: the `n` guard runs first, so an invalid quorum that
16745
- * is both non-positive AND has no approvers reports `invalid_step_up_quorum`
16746
- * (stable/deterministic reason).
16747
- */
16748
- function validateStepUpQuorum(quorum) {
16749
- if (!Number.isInteger(quorum.n) || quorum.n < 1) return {
16750
- ok: false,
16751
- reason: "invalid_step_up_quorum"
16752
- };
16753
- if (!Array.isArray(quorum.approvers) || quorum.approvers.length === 0) return {
16754
- ok: false,
16755
- reason: "step_up_no_approvers"
16756
- };
16757
- return { ok: true };
16758
- }
16759
-
16760
15195
  //#endregion
16761
15196
  //#region src/policy/fetcher.ts
16762
15197
  /**
@@ -17052,545 +15487,6 @@ function createEvaluationContext(options) {
17052
15487
  };
17053
15488
  }
17054
15489
 
17055
- //#endregion
17056
- //#region src/host-adapter/verdict-cookie.ts
17057
- /**
17058
- * Canonical cookie name. Sites-1's `/blocked` page reads from this
17059
- * exact key; do not rename without updating the dashboard route.
17060
- */
17061
- const VERDICT_COOKIE_NAME = "__checkpoint_verdict";
17062
- /**
17063
- * Compute the verdict label from a `RenderedResponse`.
17064
- */
17065
- function deriveVerdict(rendered) {
17066
- if (rendered.status === null) return "allowed";
17067
- if (rendered.status === 302) return "redirected";
17068
- return "denied";
17069
- }
17070
- /**
17071
- * Build the `__checkpoint_verdict` cookie value Sites-1's Sonner toast
17072
- * reads. Byte-format pinned by tests in both `checkpoint-nextjs` and
17073
- * `checkpoint-express`:
17074
- *
17075
- * - allowed: `{"verdict":"allowed"}`
17076
- * - denied: `{"verdict":"denied","reason":"<r>"}`
17077
- * - redirected: `{"verdict":"redirected"}`
17078
- *
17079
- * Returns raw JSON; the host's cookie-write call URL-encodes.
17080
- */
17081
- function encodeVerdictCookie(rendered) {
17082
- const verdict = deriveVerdict(rendered);
17083
- const reason = rendered.headers["X-Checkpoint-Reason"];
17084
- return JSON.stringify(reason ? {
17085
- verdict,
17086
- reason
17087
- } : { verdict });
17088
- }
17089
-
17090
- //#endregion
17091
- //#region src/host-adapter/content-negotiation.ts
17092
- /**
17093
- * Content negotiation — framework-agnostic Accept-header parsing for
17094
- * host adapters.
17095
- *
17096
- * The engine's `RenderedResponse` doesn't make HTML-vs-JSON branching
17097
- * decisions; the host wrapper does that based on what the client
17098
- * accepts. Both Next.js (NextRequest) and Express (Request) carry the
17099
- * Accept header in different shapes — `req.headers.get('accept')` vs
17100
- * `req.get('Accept')` vs `req.headers.accept` — so we accept any
17101
- * Headers-like input and do the parsing here.
17102
- */
17103
- /**
17104
- * `true` when the client signaled it accepts HTML or XHTML. Used by
17105
- * host adapters to choose between an HTML `/blocked` rewrite (browsers)
17106
- * and a JSON 4xx response (curl, fetch-from-a-tool, ChatGPT-User).
17107
- *
17108
- * Loose match — q-values, parameters, and additional MIME types are
17109
- * allowed. The spec's q-value precedence (RFC 9110 § 12.5.1) doesn't
17110
- * matter here; we only care whether HTML is present at all.
17111
- *
17112
- * Accepts:
17113
- * - a `Headers` instance (Web Fetch API; Next.js, Hono, Cloudflare)
17114
- * - a plain `Record<string, string>` (Express, Connect, Fastify)
17115
- * - a single string (caller already extracted the Accept value)
17116
- * - `undefined` (treated as no-HTML)
17117
- */
17118
- function acceptsHtml(input) {
17119
- const accept = extractAccept(input);
17120
- if (!accept) return false;
17121
- return accept.includes("text/html") || accept.includes("application/xhtml+xml");
17122
- }
17123
- function extractAccept(input) {
17124
- if (!input) return void 0;
17125
- if (typeof input === "string") return input;
17126
- if (typeof input.get === "function") return input.get("accept") ?? void 0;
17127
- const rec = input;
17128
- const value = rec.accept ?? rec.Accept;
17129
- if (Array.isArray(value)) return value.join(",");
17130
- return value;
17131
- }
17132
-
17133
- //#endregion
17134
- //#region src/host-adapter/decision-mapping.ts
17135
- /**
17136
- * Path the `/blocked` dashboard route lives at. HTML clients that hit
17137
- * a 4xx verdict get rewritten here at status 200 so the page renders
17138
- * with the verdict cookie set and Sonner can pick up the toast.
17139
- *
17140
- * Hard-coded by convention; if a customer ever needs a custom path,
17141
- * pass it through `CheckpointConfig.blockedPath` and override in the
17142
- * host adapter (not in this lookup).
17143
- */
17144
- const BLOCKED_PATH = "/blocked";
17145
- /**
17146
- * Classify a `RenderedResponse` into one of the four host-adapter
17147
- * branches. `clientAcceptsHtml` comes from `acceptsHtml()` in
17148
- * `content-negotiation.ts`.
17149
- */
17150
- function classifyResponseShape(rendered, clientAcceptsHtml) {
17151
- if (rendered.status === null) return "pass-through";
17152
- if (rendered.status === 302 && rendered.headers.Location) return "redirect";
17153
- if (clientAcceptsHtml && rendered.status >= 400 && rendered.status < 500) return "html-block";
17154
- return "json-block";
17155
- }
17156
-
17157
- //#endregion
17158
- //#region src/host-adapter/fetcher-envelope.ts
17159
- /**
17160
- * Dual-envelope selection predicate (draft-kya-http-02 §8.1 fetcher-200).
17161
- *
17162
- * AI-agent fetchers (Claude-User WebFetch, ChatGPT) collapse 4xx/5xx
17163
- * responses and never surface the body to the LLM, so the §8.1 step-up
17164
- * challenge served at 401 is invisible. The fix is a dual envelope: keep
17165
- * the spec 401 for capable/discovery clients, and serve a body-readable
17166
- * HTTP 200 (no `WWW-Authenticate`) for cooperative, self-identifying
17167
- * agents so they can read the body + relay the consent link.
17168
- *
17169
- * `serveBodyReadable200` is the shared selection predicate every TS PEP
17170
- * (checkpoint-nextjs, checkpoint-express / wasm-runtime) consults when its
17171
- * challenge-emission mode is `negotiated`. Centralising it here — rather
17172
- * than re-implementing per PEP — makes drift structurally impossible; the
17173
- * fetcher-200 fixture freezes envelope BYTES, this function freezes the
17174
- * SELECTION.
17175
- *
17176
- * **This is a cooperative-UX bridge, NOT an access control.** A spoofer
17177
- * that hides its identity and does not opt in simply receives the spec
17178
- * 401 (and the original body-drop). Access is still gated entirely by the
17179
- * unchanged detection + delegation verification — never by which envelope
17180
- * is selected.
17181
- */
17182
- /**
17183
- * Durable opt-in header — the primary, framework-agnostic signal that a
17184
- * caller is a cooperative agent able to handle the 200 fetcher envelope.
17185
- * Any non-empty value counts as opt-in (value semantics are reconciled
17186
- * with mcp-i-cloudflare's `KYA-Accept-Challenge: delegation` in the spec).
17187
- */
17188
- const ACCEPT_CHALLENGE_HEADER = "kya-accept-challenge";
17189
- function readHeader(input, name) {
17190
- if (!input) return void 0;
17191
- if (typeof input.get === "function") return input.get(name) ?? void 0;
17192
- const rec = input;
17193
- const lower = name.toLowerCase();
17194
- for (const key of Object.keys(rec)) if (key.toLowerCase() === lower) {
17195
- const v = rec[key];
17196
- return Array.isArray(v) ? v[0] : v ?? void 0;
17197
- }
17198
- }
17199
- /**
17200
- * Decide whether a `negotiated`-mode PEP should serve the body-readable
17201
- * HTTP 200 fetcher envelope (`true`) or the spec 401 (`false`).
17202
- *
17203
- * Serve 200 when EITHER:
17204
- * 1. the caller opts in via a non-empty `KYA-Accept-Challenge` header
17205
- * (the durable, primary signal), OR
17206
- * 2. detection classifies the caller as an AI agent — BOTH `isAgent` and
17207
- * `detectionClass === 'ai_agent'` must agree (a transitional UA heuristic,
17208
- * retired as frameworks adopt the header).
17209
- *
17210
- * Otherwise serve the 401 — spoofers, silent, discovery, and OAuth
17211
- * clients all land here, which is acceptable because this is UX, not a
17212
- * security boundary.
17213
- *
17214
- * Requiring both `isAgent` AND the `ai_agent` class to fire the heuristic
17215
- * mirrors .NET `IsInteractiveAiAgent` (`IsAgent && DetectionClass.Type ==
17216
- * AiAgent`) and the gateway worker, so the cross-PEP selection cannot drift on
17217
- * the pathological case where the two signals disagree (class says agent,
17218
- * `isAgent` says no): that caller is treated as non-cooperative (spec 401),
17219
- * never demoted past it. In normal engine output the two signals agree, so
17220
- * who-gets-200 is unchanged for real traffic.
17221
- *
17222
- * @param headers request headers (for the opt-in signal)
17223
- * @param detectionClass the caller's detection class in any representation
17224
- * the engine produces (a `DetectionClass` object, the
17225
- * `ai_agent` wire string, or absent)
17226
- * @param isAgent the engine's `isAgent` verdict — gates the `ai_agent`
17227
- * heuristic so a class/`isAgent` disagreement gets the 401
17228
- */
17229
- function serveBodyReadable200(headers, detectionClass, isAgent) {
17230
- const optIn = readHeader(headers, ACCEPT_CHALLENGE_HEADER);
17231
- if (optIn && optIn.trim().length > 0) return true;
17232
- if (isAgent && detectionClass !== void 0 && detectionClass !== null) {
17233
- if (normalizeDetectionClassEnum(detectionClass) === "ai_agent") return true;
17234
- }
17235
- return false;
17236
- }
17237
- /**
17238
- * Resolve the challenge-emission mode + request signals into the single
17239
- * boolean each PEP needs: serve the body-readable 200 (`true`) or the spec
17240
- * 401 (`false`). Centralising the mode gate here — not just the predicate —
17241
- * keeps the rollout switch identical across every TS PEP.
17242
- */
17243
- function selectBodyReadable200(mode, headers, detectionClass, isAgent) {
17244
- if (mode === "always-200") return true;
17245
- if (mode === "negotiated") return serveBodyReadable200(headers, detectionClass, isAgent);
17246
- return false;
17247
- }
17248
-
17249
- //#endregion
17250
- //#region src/mcpi/kya-http-error-codes.ts
17251
- /**
17252
- * KYA-HTTP error code registry — draft-kya-http-02 §9 / H1.2 (#3245).
17253
- *
17254
- * The `kyaos/*` strings are wire constants returned in the `error` field of a
17255
- * KYA-HTTP failure response (and mapped to an HTTP status). Emitters MUST use
17256
- * these EXACT bytes; consumers MAY additionally accept the legacy `kya/*`
17257
- * spellings for one transition cycle.
17258
- *
17259
- * The single source of truth is the golden fixture
17260
- * `packages/checkpoint-shared/fixtures/kya-http/error-codes.json`; the parity
17261
- * test in `__tests__/kya-http-error-codes.test.ts` reads that JSON via `fs` and
17262
- * asserts this map is byte-exact against it (no drift, no omissions).
17263
- *
17264
- * `as const satisfies Record<string, \`kyaos/${string}\`>` keeps the narrow
17265
- * literal value types (so consumers get autocomplete and a compile error on a
17266
- * typo'd code) while still proving every value is a well-formed `kyaos/…` string.
17267
- */
17268
- const KYA_HTTP_ERROR = {
17269
- MISSING_SIGNATURE: "kyaos/missing-signature",
17270
- INVALID_SIGNATURE: "kyaos/invalid-signature",
17271
- EXPIRED: "kyaos/expired",
17272
- REPLAY: "kyaos/replay",
17273
- DID_UNRESOLVABLE: "kyaos/did-unresolvable",
17274
- AUTHORIZATION_REQUIRED: "kyaos/authorization-required",
17275
- PROFILE_VIOLATION: "kyaos/profile-violation",
17276
- DELEGATION_REVOKED: "kyaos/delegation-revoked",
17277
- SCOPE_INSUFFICIENT: "kyaos/scope-insufficient",
17278
- CHAIN_BROKEN: "kyaos/chain-broken",
17279
- HOLDER_MISMATCH: "kyaos/holder-mismatch",
17280
- AUDIENCE_MISMATCH: "kyaos/audience-mismatch",
17281
- SESSION_MISMATCH: "kyaos/session-mismatch",
17282
- PICKUP_PINNED: "kyaos/pickup-pinned",
17283
- ASSURANCE_INSUFFICIENT: "kyaos/assurance-insufficient",
17284
- STATUS_PENDING: "kyaos/status-pending",
17285
- AUTHORIZATION_HOST_UNAVAILABLE: "kyaos/authorization-host-unavailable",
17286
- REPLAY_STATE_UNAVAILABLE: "kyaos/replay-state-unavailable",
17287
- REPLAY_CAPACITY: "kyaos/replay-capacity",
17288
- INVALID_SESSION: "kyaos/invalid-session",
17289
- PICKUP_EXPIRED: "kyaos/pickup-expired"
17290
- };
17291
- /**
17292
- * The HTTP status the registry assigns each code (draft-kya-http-02 §9).
17293
- * Mirrors `error-codes.json` exactly, pinned by `__tests__/kya-http-error-codes.test.ts`,
17294
- * and matches the engine's own table (`rust/crates/kya-os-engine/src/render/kya_error.rs`).
17295
- */
17296
- const KYA_HTTP_ERROR_STATUS = {
17297
- [KYA_HTTP_ERROR.MISSING_SIGNATURE]: 401,
17298
- [KYA_HTTP_ERROR.INVALID_SIGNATURE]: 401,
17299
- [KYA_HTTP_ERROR.EXPIRED]: 401,
17300
- [KYA_HTTP_ERROR.REPLAY]: 401,
17301
- [KYA_HTTP_ERROR.DID_UNRESOLVABLE]: 401,
17302
- [KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED]: 401,
17303
- [KYA_HTTP_ERROR.PROFILE_VIOLATION]: 403,
17304
- [KYA_HTTP_ERROR.DELEGATION_REVOKED]: 403,
17305
- [KYA_HTTP_ERROR.SCOPE_INSUFFICIENT]: 403,
17306
- [KYA_HTTP_ERROR.CHAIN_BROKEN]: 403,
17307
- [KYA_HTTP_ERROR.HOLDER_MISMATCH]: 403,
17308
- [KYA_HTTP_ERROR.AUDIENCE_MISMATCH]: 403,
17309
- [KYA_HTTP_ERROR.SESSION_MISMATCH]: 403,
17310
- [KYA_HTTP_ERROR.PICKUP_PINNED]: 403,
17311
- [KYA_HTTP_ERROR.ASSURANCE_INSUFFICIENT]: 403,
17312
- [KYA_HTTP_ERROR.STATUS_PENDING]: 503,
17313
- [KYA_HTTP_ERROR.AUTHORIZATION_HOST_UNAVAILABLE]: 503,
17314
- [KYA_HTTP_ERROR.REPLAY_STATE_UNAVAILABLE]: 503,
17315
- [KYA_HTTP_ERROR.REPLAY_CAPACITY]: 429,
17316
- [KYA_HTTP_ERROR.INVALID_SESSION]: 404,
17317
- [KYA_HTTP_ERROR.PICKUP_EXPIRED]: 410
17318
- };
17319
-
17320
- //#endregion
17321
- //#region src/host-adapter/challenge-wire.ts
17322
- /**
17323
- * Canonical fixture-pinned KYA HTTP challenge-wire builder.
17324
- *
17325
- * The builder is transport-neutral and Edge-safe. Hosts must register the
17326
- * challenge and resolve every URI before calling it; this module validates and
17327
- * serializes those trusted values without network, database, or request access.
17328
- */
17329
- const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
17330
- const DEFAULT_POLL_INTERVAL_S = 3;
17331
- const INVALID_QUOTED_VALUE = /[\u0000-\u001f\u007f"\\]/;
17332
- const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
17333
- const SID = /^kya-[0-9a-f]{16,}$/;
17334
- const ASSURANCE_TIERS = /* @__PURE__ */ new Set([
17335
- "anonymous",
17336
- "attested-bearer",
17337
- "key-bound",
17338
- "registered",
17339
- "delegated"
17340
- ]);
17341
- /** Typed validation failure raised before any response is materialized. */
17342
- var ChallengeWireError = class extends TypeError {
17343
- code;
17344
- constructor(code, message) {
17345
- super(message);
17346
- this.name = "ChallengeWireError";
17347
- this.code = code;
17348
- }
17349
- };
17350
- /** Generate a 128-bit, lower-case hexadecimal challenge id. */
17351
- function generateDelegationSid() {
17352
- const bytes = /* @__PURE__ */ new Uint8Array(16);
17353
- crypto.getRandomValues(bytes);
17354
- let hex = "";
17355
- for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
17356
- return `kya-${hex}`;
17357
- }
17358
- /** Derive pickup from the registered consent origin, never request Host. */
17359
- function deriveDelegationPickupUri(consentUri, sid) {
17360
- const consent = parseHttpsUrl("consentUri", consentUri);
17361
- assertQuotedValue("sid", sid, "invalid-sid");
17362
- return `${consent.origin}/api/delegation/pickup/${sid}`;
17363
- }
17364
- /** Build the byte-pinned Delegation authentication field value. */
17365
- function buildDelegationChallengeHeader(input) {
17366
- const normalized = validateInput(input);
17367
- const params = [
17368
- ["realm", normalized.realm],
17369
- ["sid", normalized.sid],
17370
- ["consent_uri", normalized.consentUri],
17371
- ["pickup_uri", normalized.pickupUri]
17372
- ];
17373
- if (normalized.requiredScopes.length > 0) params.push(["scope", normalized.requiredScopes.join(" ")]);
17374
- if (normalized.minAssurance) params.push(["min_assurance", normalized.minAssurance]);
17375
- if (input.pollIntervalS !== void 0) params.push(["interval", String(normalized.pollIntervalS)]);
17376
- params.push(["kind", normalized.kind]);
17377
- return `Delegation ${params.map(([name, value]) => `${name}="${value}"`).join(", ")}`;
17378
- }
17379
- /** Build RFC 9728 Bearer discovery for a protected-resource realm. */
17380
- function buildDelegationBearerHeader(realm) {
17381
- assertRealm(realm);
17382
- return `Bearer resource_metadata="https://${realm}${PROTECTED_RESOURCE_METADATA_PATH}"`;
17383
- }
17384
- /** Build the four required machine-followable delegation instruction elements. */
17385
- function buildDelegationInstructions(consentUri, pickupUri, pollIntervalS) {
17386
- return `This action requires human authorization. First establish your pickup binding at ${pickupUri}. If you can sign HTTP requests, sign each poll with an ephemeral did:key; otherwise generate one random 32-byte token encoded as unpadded base64url and send it as X-KYA-Pickup-Token on EVERY poll. After receiving 202 pending, show your user this link and ask them to approve: ${consentUri}. Continue polling ${pickupUri} every ${pollIntervalS} seconds with the same binding. When the response status is 200, take the 'delegation' value and retry your original request with header 'Authorization: Bearer <delegation>'.`;
17387
- }
17388
- /** Build the proof-bound body shared byte-for-byte by both HTTP envelopes. */
17389
- function buildDelegationChallengeBody(input) {
17390
- const normalized = validateInput(input);
17391
- const common = {
17392
- sid: normalized.sid,
17393
- consent_uri: normalized.consentUri,
17394
- pickup_uri: normalized.pickupUri,
17395
- ...normalized.requiredScopes.length > 0 ? { required_scopes: [...normalized.requiredScopes] } : {},
17396
- ...normalized.minAssurance ? { min_assurance: normalized.minAssurance } : {},
17397
- poll_interval_s: normalized.pollIntervalS,
17398
- challenge_proof: input.challengeProof
17399
- };
17400
- if (normalized.kind === "approval_quorum") return {
17401
- error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
17402
- kyaos: {
17403
- sid: common.sid,
17404
- kind: "approval_quorum",
17405
- quorum: normalized.quorum,
17406
- action_nonce: normalized.actionNonce,
17407
- consent_uri: common.consent_uri,
17408
- pickup_uri: common.pickup_uri,
17409
- ...common.required_scopes ? { required_scopes: common.required_scopes } : {},
17410
- ...common.min_assurance ? { min_assurance: common.min_assurance } : {},
17411
- poll_interval_s: common.poll_interval_s,
17412
- challenge_proof: common.challenge_proof
17413
- },
17414
- instructions: buildApprovalQuorumInstructions(normalized)
17415
- };
17416
- return {
17417
- error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
17418
- kyaos: {
17419
- ...common,
17420
- action: {
17421
- type: "delegation",
17422
- consent_uri: normalized.consentUri,
17423
- pickup_uri: normalized.pickupUri,
17424
- poll_interval_s: normalized.pollIntervalS,
17425
- pin: { header: "X-KYA-Pickup-Token" },
17426
- retry: {
17427
- header: "Authorization",
17428
- scheme: "Bearer",
17429
- value_from: "delegation"
17430
- }
17431
- }
17432
- },
17433
- instructions: buildDelegationInstructions(normalized.consentUri, normalized.pickupUri, normalized.pollIntervalS)
17434
- };
17435
- }
17436
- /** Build either the canonical 401 or its body-identical fetcher-200 envelope. */
17437
- function buildDelegationChallengeEnvelope(input, mode = "spec-401") {
17438
- const normalized = validateInput(input);
17439
- if (normalized.kind === "approval_quorum" && mode === "fetcher-200") throw new ChallengeWireError("unsupported-envelope", "fetcher-200 is not fixture-defined for approval_quorum");
17440
- const body = buildDelegationChallengeBody(input);
17441
- if (normalized.kind === "approval_quorum") return {
17442
- status: 401,
17443
- headers: [
17444
- ["WWW-Authenticate", buildDelegationChallengeHeader(input)],
17445
- ["Retry-After", String(normalized.pollIntervalS)],
17446
- ["Content-Type", "application/json"],
17447
- ["Cache-Control", "no-store"]
17448
- ],
17449
- body
17450
- };
17451
- const hintHeaders = [
17452
- ["Content-Type", "application/json"],
17453
- ["Cache-Control", "no-store"],
17454
- ["KYA-Auth-Required", "true"],
17455
- ["KYA-Auth-Url", normalized.consentUri],
17456
- ["Link", `<${normalized.consentUri}>; rel="kya-authorize"`],
17457
- ["KYA-Action", "challenge"]
17458
- ];
17459
- if (mode === "fetcher-200") return {
17460
- status: 200,
17461
- headers: hintHeaders,
17462
- body
17463
- };
17464
- return {
17465
- status: 401,
17466
- headers: [
17467
- ["WWW-Authenticate", buildDelegationChallengeHeader(input)],
17468
- ["WWW-Authenticate", `Bearer resource_metadata="${normalized.resourceMetadataUri}"`],
17469
- ["Retry-After", String(normalized.pollIntervalS)],
17470
- ...hintHeaders
17471
- ],
17472
- body
17473
- };
17474
- }
17475
- /** Preferred generic name; the legacy export remains for host compatibility. */
17476
- const buildChallengeWire = buildDelegationChallengeEnvelope;
17477
- function validateInput(input) {
17478
- assertRealm(input.realm);
17479
- assertQuotedValue("sid", input.sid, "invalid-sid");
17480
- if (!SID.test(input.sid)) throw new ChallengeWireError("invalid-sid", "sid must start with kya- and contain at least 64 bits of lower-case hexadecimal entropy");
17481
- const consent = parseHttpsUrl("consentUri", input.consentUri);
17482
- const pickup = parseHttpsUrl("pickupUri", input.pickupUri);
17483
- const expectedPickup = `${consent.origin}/api/delegation/pickup/${input.sid}`;
17484
- if (pickup.href !== expectedPickup) throw new ChallengeWireError("invalid-uri", "pickupUri must use the registered consent origin and sid");
17485
- const pollIntervalS = input.pollIntervalS ?? DEFAULT_POLL_INTERVAL_S;
17486
- if (!Number.isInteger(pollIntervalS) || pollIntervalS < 1 || pollIntervalS > 999) throw new ChallengeWireError("invalid-interval", "pollIntervalS must be an integer from 1 through 999");
17487
- if (input.challengeProof === void 0 || input.challengeProof === null) throw new ChallengeWireError("invalid-proof", "challengeProof is required");
17488
- const requiredScopes = input.requiredScopes ?? [];
17489
- for (const scope of requiredScopes) if (!SCOPE_TOKEN.test(scope)) throw new ChallengeWireError("invalid-scope", `invalid required scope: ${scope}`);
17490
- if (input.minAssurance && !ASSURANCE_TIERS.has(input.minAssurance)) throw new ChallengeWireError("invalid-assurance", `invalid minAssurance: ${input.minAssurance}`);
17491
- const kind = input.kind ?? "delegation";
17492
- if (kind !== "delegation" && kind !== "approval_quorum") throw new ChallengeWireError("invalid-kind", `unsupported challenge kind: ${String(kind)}`);
17493
- let resourceMetadataUri;
17494
- let quorum;
17495
- let actionNonce;
17496
- if (kind === "delegation") {
17497
- resourceMetadataUri = parseHttpsUrl("resourceMetadataUri", input.resourceMetadataUri).href;
17498
- const expectedMetadata = `https://${input.realm}${PROTECTED_RESOURCE_METADATA_PATH}`;
17499
- if (resourceMetadataUri !== expectedMetadata) throw new ChallengeWireError("invalid-uri", "resourceMetadataUri must be the protected resource RFC 9728 metadata URL");
17500
- } else {
17501
- const approval = input;
17502
- quorum = approval.quorum;
17503
- actionNonce = approval.actionNonce;
17504
- if (!Number.isInteger(quorum) || quorum < 1) throw new ChallengeWireError("invalid-quorum", "quorum must be a positive integer");
17505
- assertQuotedValue("actionNonce", actionNonce, "invalid-action-nonce");
17506
- }
17507
- return {
17508
- realm: input.realm,
17509
- sid: input.sid,
17510
- consentUri: consent.href,
17511
- pickupUri: pickup.href,
17512
- resourceMetadataUri,
17513
- requiredScopes,
17514
- pollIntervalS,
17515
- minAssurance: input.minAssurance,
17516
- kind,
17517
- quorum,
17518
- actionNonce
17519
- };
17520
- }
17521
- function buildApprovalQuorumInstructions(input) {
17522
- return `This action requires approval from ${input.quorum} human approvers. Show your user this link to begin the approval process: ${input.consentUri}. Then poll ${input.pickupUri} every ${input.pollIntervalS} seconds (sign polls with an ephemeral did:key, or send one random 32-byte X-KYA-Pickup-Token on EVERY poll). When the response status is 200, retry your original request presenting the returned grants in the KYA-Approvals header.`;
17523
- }
17524
- function assertRealm(realm) {
17525
- assertQuotedValue("realm", realm, "invalid-realm");
17526
- if (realm.includes("/") || realm.includes("@") || realm.includes("?") || realm.includes("#")) throw new ChallengeWireError("invalid-realm", "realm must be a host with an optional port");
17527
- try {
17528
- if (new URL(`https://${realm}`).host !== realm) throw new Error("invalid authority");
17529
- } catch {
17530
- throw new ChallengeWireError("invalid-realm", "realm must be a valid host with an optional port");
17531
- }
17532
- }
17533
- function assertQuotedValue(name, value, code) {
17534
- if (typeof value !== "string" || value.length === 0 || INVALID_QUOTED_VALUE.test(value)) throw new ChallengeWireError(code, `${name} contains characters unsafe for an HTTP quoted-string`);
17535
- }
17536
- function parseHttpsUrl(name, value) {
17537
- assertQuotedValue(name, value, "invalid-uri");
17538
- let parsed;
17539
- try {
17540
- parsed = new URL(value);
17541
- } catch {
17542
- throw new ChallengeWireError("invalid-uri", `${name} must be an absolute HTTPS URL`);
17543
- }
17544
- if (parsed.protocol !== "https:" || parsed.username || parsed.password) throw new ChallengeWireError("invalid-uri", `${name} must be an absolute HTTPS URL without credentials`);
17545
- return parsed;
17546
- }
17547
-
17548
- //#endregion
17549
- //#region src/host-adapter/challenge-context.ts
17550
- const DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = 3e3;
17551
- /**
17552
- * Resolve and validate registered challenge context at the async host boundary.
17553
- * Resolver failures become an absent context so the renderer can emit the
17554
- * canonical retryable status-pending response; secrets and proof values are
17555
- * never included in failure events.
17556
- */
17557
- async function resolveChallengeContext(resolver, context, options = {}) {
17558
- if (!resolver) return void 0;
17559
- const timeoutMs = options.timeoutMs ?? 3e3;
17560
- if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw new TypeError("challenge context timeout must be a positive integer");
17561
- let timeoutId;
17562
- try {
17563
- const value = await Promise.race([Promise.resolve(resolver(context)), new Promise((_resolve, reject) => {
17564
- timeoutId = setTimeout(() => reject(new ChallengeContextTimeoutError(timeoutMs)), timeoutMs);
17565
- })]);
17566
- if (timeoutId !== void 0) clearTimeout(timeoutId);
17567
- if (!value) return void 0;
17568
- try {
17569
- buildChallengeWire(value, "spec-401");
17570
- return value;
17571
- } catch (error) {
17572
- options.onFailure?.({
17573
- reason: "invalid-context",
17574
- message: error.message
17575
- });
17576
- return;
17577
- }
17578
- } catch (error) {
17579
- if (timeoutId !== void 0) clearTimeout(timeoutId);
17580
- options.onFailure?.({
17581
- reason: error instanceof ChallengeContextTimeoutError ? "timeout" : "resolver-error",
17582
- message: error instanceof ChallengeContextTimeoutError ? error.message : "challenge context resolver failed"
17583
- });
17584
- return;
17585
- }
17586
- }
17587
- var ChallengeContextTimeoutError = class extends Error {
17588
- constructor(timeoutMs) {
17589
- super(`challenge context resolution exceeded ${timeoutMs}ms`);
17590
- this.name = "ChallengeContextTimeoutError";
17591
- }
17592
- };
17593
-
17594
15490
  //#endregion
17595
15491
  //#region src/wire/vault.ts
17596
15492
  /**
@@ -17736,119 +15632,6 @@ function deriveMcpiUserDid(slug, userId) {
17736
15632
  return `${deriveMcpiOrgDid(slug)}:users:${userId}`;
17737
15633
  }
17738
15634
 
17739
- //#endregion
17740
- //#region src/mcpi/delegation-headers.ts
17741
- /**
17742
- * Delegation-proof request detection (P2 / DR-1).
17743
- *
17744
- * The engine's L2 delegation-root pinning (`ContextSpec.trustedDelegationRoots`)
17745
- * is consulted for every credential the engine verifies: the delegation-proof
17746
- * headers below AND an `Authorization: Bearer` VC-JWT. Consumers gate root
17747
- * resolution on `requestPresentedCredential`, so the human / no-credential hot
17748
- * path stays a precise no-op.
17749
- *
17750
- * Keeping the header set here (rather than re-listing the literals at each site)
17751
- * is the whole point: a new delegation transport header is added in one place
17752
- * and every verifier surface agrees.
17753
- */
17754
- /**
17755
- * Lowercased delegation-proof header names. `kya-os-delegation-credential` is the
17756
- * canonical KYA-OS transport; `kya-delegation` is the legacy envelope form still
17757
- * accepted via `legacyEnvelopeFallback`.
17758
- */
17759
- const DELEGATION_PROOF_HEADERS = ["kya-os-delegation-credential", "kya-delegation"];
17760
- /** A header value is "present" when it is a non-empty string (or non-empty list). */
17761
- function isPresent(value) {
17762
- if (Array.isArray(value)) return value.length > 0;
17763
- return typeof value === "string" && value.length > 0;
17764
- }
17765
- /**
17766
- * Does the request carry a KYA-OS delegation-proof header?
17767
- *
17768
- * Accepts either a `Headers` instance (Next.js / fetch — case-insensitive
17769
- * lookup) or a plain header record (raw Node/Express headers, gateway worker's
17770
- * lowercased map). Record keys are matched case-insensitively, so callers do not
17771
- * need to pre-normalize. Returns `false` for `null`/`undefined`.
17772
- */
17773
- function requestCarriesDelegationProof(headers) {
17774
- if (!headers) return false;
17775
- if (typeof headers.get === "function") {
17776
- const h = headers;
17777
- return DELEGATION_PROOF_HEADERS.some((name) => isPresent(h.get(name)));
17778
- }
17779
- const record = headers;
17780
- const lowerKeyed = /* @__PURE__ */ new Map();
17781
- for (const key of Object.keys(record)) lowerKeyed.set(key.toLowerCase(), record[key]);
17782
- return DELEGATION_PROOF_HEADERS.some((name) => isPresent(lowerKeyed.get(name)));
17783
- }
17784
- const MAX_VC_JWT_PAYLOAD_CHARS = 16384;
17785
- function headerText(headers, name) {
17786
- if (typeof headers.get === "function") return headers.get(name) ?? void 0;
17787
- for (const [key, value] of Object.entries(headers)) {
17788
- if (key.toLowerCase() !== name) continue;
17789
- if (Array.isArray(value)) return value.join(", ");
17790
- return typeof value === "string" ? value : void 0;
17791
- }
17792
- }
17793
- function isMemberDelimiter(c) {
17794
- return c === "=" || c === ";" || c === "," || c === " " || c === " ";
17795
- }
17796
- function hasKyaMember(value) {
17797
- let memberStart = true;
17798
- let quoted = false;
17799
- let escaped = false;
17800
- for (let i = 0; i < value.length; i++) {
17801
- const c = value[i];
17802
- if (quoted) {
17803
- if (escaped) escaped = false;
17804
- else if (c === "\\") escaped = true;
17805
- else if (c === "\"") quoted = false;
17806
- continue;
17807
- }
17808
- if (memberStart) {
17809
- if (c === " " || c === " ") continue;
17810
- if (value.startsWith("kya", i) && (i + 3 === value.length || isMemberDelimiter(value[i + 3]))) return true;
17811
- memberStart = false;
17812
- }
17813
- if (c === "\"") quoted = true;
17814
- else if (c === ",") memberStart = true;
17815
- }
17816
- return false;
17817
- }
17818
- function decodeBase64UrlJson(segment) {
17819
- const padded = segment.replace(/-/g, "+").replace(/_/g, "/");
17820
- const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
17821
- const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
17822
- return JSON.parse(new TextDecoder().decode(bytes));
17823
- }
17824
- function isDelegationCredentialPayload(payload) {
17825
- if (typeof payload !== "object" || payload === null) return false;
17826
- if ("vc" in payload) return true;
17827
- const type = payload.type;
17828
- return Array.isArray(type) && type.includes("DelegationCredential");
17829
- }
17830
- function looksLikeVcJwt(token) {
17831
- const parts = token.split(".");
17832
- if (parts.length !== 3 || parts.some((part) => part.length === 0)) return false;
17833
- if (parts[1].length > MAX_VC_JWT_PAYLOAD_CHARS) return true;
17834
- try {
17835
- return isDelegationCredentialPayload(decodeBase64UrlJson(parts[1]));
17836
- } catch {
17837
- return false;
17838
- }
17839
- }
17840
- /** Same definition as the .NET / Java `IsCredentialPresented`. */
17841
- function requestPresentedCredential(headers) {
17842
- if (!headers) return false;
17843
- for (const name of ["signature-input", "signature"]) {
17844
- const value = headerText(headers, name);
17845
- if (value && hasKyaMember(value)) return true;
17846
- }
17847
- if (requestCarriesDelegationProof(headers)) return true;
17848
- const bearer = headerText(headers, "authorization")?.match(/^bearer\s+(\S+)/i);
17849
- return bearer !== null && bearer !== void 0 && looksLikeVcJwt(bearer[1]);
17850
- }
17851
-
17852
15635
  //#endregion
17853
15636
  //#region src/mcpi/principal.ts
17854
15637
  /**
@@ -18086,24 +15869,6 @@ const DelegationVerifiedBySchema = require_schemas._enum([
18086
15869
  "checkpoint"
18087
15870
  ]);
18088
15871
  /**
18089
- * Max length of a registered session anchor (`sid`) accepted on the wire and
18090
- * enforced again at the customer route. The join partner
18091
- * `bouncer_sessions.id` is `varchar(100)`; `detections.registered_sid` stays
18092
- * `text` (converting a live column to `varchar` would take an ACCESS EXCLUSIVE
18093
- * rewrite of the hottest table), so this constant is the width contract
18094
- * instead of the column type.
18095
- */
18096
- const REGISTERED_SID_MAX_LENGTH = 100;
18097
- /**
18098
- * The one delegation result that may attribute a `sid` to a session timeline.
18099
- * A rejected presentation carries no engine-emitted sid, and a sid on a
18100
- * `failed` / `not_presented` report is attacker-shaped, so ingest stamps
18101
- * `registered_sid` only for this result and nulls it otherwise (D4 / D15).
18102
- * One member on purpose: Section 13 of the plan records how an explicitly
18103
- * unverified-labeled `failed` could join it later.
18104
- */
18105
- const SID_ATTRIBUTABLE_RESULT = "verified";
18106
- /**
18107
15872
  * The delegation the agent presented (a reference + outcome, not the proof).
18108
15873
  * `result` and `verifiedBy` are required; the JWT claims (`jti` / `iss` / `aud`
18109
15874
  * / `capabilities` / `exp`) are optional because `not_presented` carries none.
@@ -20079,7 +17844,7 @@ exports.A2ASignedRequestSchema = A2ASignedRequestSchema;
20079
17844
  exports.A2ATaskRequestSchema = A2ATaskRequestSchema;
20080
17845
  exports.A2ATaskSourceConfigSchema = A2ATaskSourceConfigSchema;
20081
17846
  exports.A2ATaskStateSchema = A2ATaskStateSchema;
20082
- exports.ACCEPT_CHALLENGE_HEADER = ACCEPT_CHALLENGE_HEADER;
17847
+ exports.ACCEPT_CHALLENGE_HEADER = require_host_adapter.ACCEPT_CHALLENGE_HEADER;
20083
17848
  exports.ADMIN_ACCOUNTS_STATUS_FILTERS = ADMIN_ACCOUNTS_STATUS_FILTERS;
20084
17849
  exports.ADMIN_ACCOUNT_STATUSES = ADMIN_ACCOUNT_STATUSES;
20085
17850
  exports.ADMIN_DELTA_BASES = ADMIN_DELTA_BASES;
@@ -20165,7 +17930,7 @@ exports.BARE_ERRORS = BARE_ERRORS;
20165
17930
  exports.BASELINE_ALLOW_POLICY_ID = BASELINE_ALLOW_POLICY_ID;
20166
17931
  exports.BESPOKE_POLICY_IDS = BESPOKE_POLICY_IDS;
20167
17932
  exports.BILLING_ERRORS = BILLING_ERRORS;
20168
- exports.BLOCKED_PATH = BLOCKED_PATH;
17933
+ exports.BLOCKED_PATH = require_host_adapter.BLOCKED_PATH;
20169
17934
  exports.BOT_USER_AGENT_PATTERNS = BOT_USER_AGENT_PATTERNS;
20170
17935
  exports.BOUNCER_LOWERCASE_ERRORS = BOUNCER_LOWERCASE_ERRORS;
20171
17936
  exports.BOUNCER_UPPERCASE_ERRORS = BOUNCER_UPPERCASE_ERRORS;
@@ -20202,7 +17967,7 @@ exports.BulkOperationResultSchema = BulkOperationResultSchema;
20202
17967
  exports.BulkOperationTypeSchema = BulkOperationTypeSchema;
20203
17968
  exports.BulkResponseSchema = BulkResponseSchema;
20204
17969
  exports.BulkResultItemSchema = BulkResultItemSchema;
20205
- exports.ByteBoundedMemo = ByteBoundedMemo;
17970
+ exports.ByteBoundedMemo = require_step_up.ByteBoundedMemo;
20206
17971
  exports.CACHE_LIMITS = CACHE_LIMITS;
20207
17972
  exports.CACHE_TTL = CACHE_TTL;
20208
17973
  exports.CLI_PAIRING_FRAMEWORKS = CLI_PAIRING_FRAMEWORKS;
@@ -20218,7 +17983,7 @@ exports.CURRENT_POLICY_VERSION = CURRENT_POLICY_VERSION;
20218
17983
  exports.CacheConfigSchema = CacheConfigSchema;
20219
17984
  exports.CachedDetectionDataSchema = CachedDetectionDataSchema;
20220
17985
  exports.ChallengeParamsSchema = ChallengeParamsSchema;
20221
- exports.ChallengeWireError = ChallengeWireError;
17986
+ exports.ChallengeWireError = require_host_adapter.ChallengeWireError;
20222
17987
  exports.CircuitBreakerConfigSchema = CircuitBreakerConfigSchema;
20223
17988
  exports.CircuitBreakerStateSchema = CircuitBreakerStateSchema;
20224
17989
  exports.ClaimVerificationSchema = ClaimVerificationSchema;
@@ -20289,7 +18054,7 @@ exports.DEFAULT_API_KEY_RATE_LIMITS = DEFAULT_API_KEY_RATE_LIMITS;
20289
18054
  exports.DEFAULT_AUTHORIZATION_HOST = DEFAULT_AUTHORIZATION_HOST;
20290
18055
  exports.DEFAULT_BEHAVIORAL_THRESHOLDS = DEFAULT_BEHAVIORAL_THRESHOLDS;
20291
18056
  exports.DEFAULT_CACHE_CONFIG = DEFAULT_CACHE_CONFIG;
20292
- exports.DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;
18057
+ exports.DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = require_host_adapter.DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;
20293
18058
  exports.DEFAULT_CONFIDENCE_THRESHOLDS = DEFAULT_CONFIDENCE_THRESHOLDS;
20294
18059
  exports.DEFAULT_CORS_CONFIG = DEFAULT_CORS_CONFIG;
20295
18060
  exports.DEFAULT_DETECTION_OPTIONS = DEFAULT_DETECTION_OPTIONS;
@@ -20307,7 +18072,7 @@ exports.DEFAULT_SESSION_CONFIG = DEFAULT_SESSION_CONFIG;
20307
18072
  exports.DEFAULT_THRESHOLDS = DEFAULT_THRESHOLDS;
20308
18073
  exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS;
20309
18074
  exports.DEFAULT_WEBHOOK_EVENTS = DEFAULT_WEBHOOK_EVENTS;
20310
- exports.DELEGATION_PROOF_HEADERS = DELEGATION_PROOF_HEADERS;
18075
+ exports.DELEGATION_PROOF_HEADERS = require_registered_sid.DELEGATION_PROOF_HEADERS;
20311
18076
  exports.DEPLOY_ERRORS = DEPLOY_ERRORS;
20312
18077
  exports.DEPLOY_STEPS = DEPLOY_STEPS;
20313
18078
  exports.DETECTION_ERRORS = DETECTION_ERRORS;
@@ -20391,9 +18156,9 @@ exports.EventTrackingRequestSchema = EventTrackingRequestSchema;
20391
18156
  exports.EventTrackingResponseSchema = EventTrackingResponseSchema;
20392
18157
  exports.ExportAnalyticsSchema = ExportAnalyticsSchema;
20393
18158
  exports.ExpressMiddlewareOptionsSchema = ExpressMiddlewareOptionsSchema;
20394
- exports.FAIL_CLOSED_BODY = FAIL_CLOSED_BODY;
20395
- exports.FAIL_CLOSED_HEADERS = FAIL_CLOSED_HEADERS;
20396
- exports.FAIL_CLOSED_STATUS = FAIL_CLOSED_STATUS;
18159
+ exports.FAIL_CLOSED_BODY = require_step_up.FAIL_CLOSED_BODY;
18160
+ exports.FAIL_CLOSED_HEADERS = require_step_up.FAIL_CLOSED_HEADERS;
18161
+ exports.FAIL_CLOSED_STATUS = require_step_up.FAIL_CLOSED_STATUS;
20397
18162
  exports.FallbackOptionsSchema = FallbackOptionsSchema;
20398
18163
  exports.FilterOperatorSchema = FilterOperatorSchema;
20399
18164
  exports.FingerprintAnalysisSchema = FingerprintAnalysisSchema;
@@ -20438,8 +18203,8 @@ exports.JafarParseError = JafarParseError;
20438
18203
  exports.KNOWN_AGENT_PATTERNS = KNOWN_AGENT_PATTERNS;
20439
18204
  exports.KYAOS_PROTOCOL_ERRORS = KYAOS_PROTOCOL_ERRORS;
20440
18205
  exports.KYA_A2A_EXTENSION = KYA_A2A_EXTENSION;
20441
- exports.KYA_HTTP_ERROR = KYA_HTTP_ERROR;
20442
- exports.KYA_HTTP_ERROR_STATUS = KYA_HTTP_ERROR_STATUS;
18206
+ exports.KYA_HTTP_ERROR = require_kya_http_error_codes.KYA_HTTP_ERROR;
18207
+ exports.KYA_HTTP_ERROR_STATUS = require_kya_http_error_codes.KYA_HTTP_ERROR_STATUS;
20443
18208
  exports.KYA_OS_HANDSHAKE_METHODS = KYA_OS_HANDSHAKE_METHODS;
20444
18209
  exports.KYA_OS_WIRE_METHODS = KYA_OS_WIRE_METHODS;
20445
18210
  exports.KeyboardEventSchema = KeyboardEventSchema;
@@ -20523,9 +18288,9 @@ exports.ModelCredentialRevocationSchema = ModelCredentialRevocationSchema;
20523
18288
  exports.ModelCredentialSchema = ModelCredentialSchema;
20524
18289
  exports.MouseEventSchema = MouseEventSchema;
20525
18290
  exports.NETWORK_ERRORS = NETWORK_ERRORS;
20526
- exports.NO_EVIDENCE_CATEGORY = NO_EVIDENCE_CATEGORY;
20527
- exports.NO_EVIDENCE_EQUALITY_TERM = NO_EVIDENCE_EQUALITY_TERM;
20528
- exports.NO_EVIDENCE_EXCLUSION_TERM = NO_EVIDENCE_EXCLUSION_TERM;
18291
+ exports.NO_EVIDENCE_CATEGORY = require_step_up.NO_EVIDENCE_CATEGORY;
18292
+ exports.NO_EVIDENCE_EQUALITY_TERM = require_step_up.NO_EVIDENCE_EQUALITY_TERM;
18293
+ exports.NO_EVIDENCE_EXCLUSION_TERM = require_step_up.NO_EVIDENCE_EXCLUSION_TERM;
20529
18294
  exports.NetworkConfigSchema = NetworkConfigSchema;
20530
18295
  exports.NetworkContextSchema = NetworkContextSchema;
20531
18296
  exports.NetworkInfoSchema = NetworkInfoSchema;
@@ -20661,7 +18426,7 @@ exports.QuerySchema = QuerySchema;
20661
18426
  exports.RATE_LIMIT_ERRORS = RATE_LIMIT_ERRORS;
20662
18427
  exports.READABLE_TEXT = READABLE_TEXT;
20663
18428
  exports.READABLE_TEXT_MESSAGE = READABLE_TEXT_MESSAGE;
20664
- exports.REGISTERED_SID_MAX_LENGTH = REGISTERED_SID_MAX_LENGTH;
18429
+ exports.REGISTERED_SID_MAX_LENGTH = require_registered_sid.REGISTERED_SID_MAX_LENGTH;
20665
18430
  exports.REPORT_AI_AGENT_NAMES = REPORT_AI_AGENT_NAMES;
20666
18431
  exports.REPORT_AI_CRAWLER_NAMES = REPORT_AI_CRAWLER_NAMES;
20667
18432
  exports.RESOURCE_ERRORS = RESOURCE_ERRORS;
@@ -20715,7 +18480,7 @@ exports.SERVICE_TRAFFIC_KEYS = SERVICE_TRAFFIC_KEYS;
20715
18480
  exports.SESSION_ERRORS = SESSION_ERRORS;
20716
18481
  exports.SESSION_LIMITS = SESSION_LIMITS;
20717
18482
  exports.SHADOW_NOISY_OR_CONFIDENCE_KEY = SHADOW_NOISY_OR_CONFIDENCE_KEY;
20718
- exports.SID_ATTRIBUTABLE_RESULT = SID_ATTRIBUTABLE_RESULT;
18483
+ exports.SID_ATTRIBUTABLE_RESULT = require_registered_sid.SID_ATTRIBUTABLE_RESULT;
20719
18484
  exports.SLUG_REGEX = SLUG_REGEX;
20720
18485
  exports.SUSPICIOUS_HEADERS = SUSPICIOUS_HEADERS;
20721
18486
  exports.SUSPICIOUS_PATTERNS = require_posture_origins.SUSPICIOUS_PATTERNS;
@@ -20847,7 +18612,7 @@ exports.VALIDATION_ERRORS = VALIDATION_ERRORS;
20847
18612
  exports.VALIDATION_MODES = VALIDATION_MODES;
20848
18613
  exports.VALIDATION_PATTERNS = require_posture_origins.VALIDATION_PATTERNS;
20849
18614
  exports.VAULT_ERRORS = VAULT_ERRORS;
20850
- exports.VERDICT_COOKIE_NAME = VERDICT_COOKIE_NAME;
18615
+ exports.VERDICT_COOKIE_NAME = require_host_adapter.VERDICT_COOKIE_NAME;
20851
18616
  exports.VERSION = VERSION;
20852
18617
  exports.VerdictEvidenceSchema = VerdictEvidenceSchema;
20853
18618
  exports.VerificationCacheEntrySchema = VerificationCacheEntrySchema;
@@ -20882,11 +18647,11 @@ exports.WorkloadEnrollmentResultSchema = WorkloadEnrollmentResultSchema;
20882
18647
  exports.WorkloadEnrollmentRevocationSchema = WorkloadEnrollmentRevocationSchema;
20883
18648
  exports.WorkloadEnrollmentSchema = WorkloadEnrollmentSchema;
20884
18649
  exports.WorkloadRotationProofPayloadSchema = WorkloadRotationProofPayloadSchema;
20885
- exports.acceptsHtml = acceptsHtml;
18650
+ exports.acceptsHtml = require_host_adapter.acceptsHtml;
20886
18651
  exports.adminAccountsQuerySchema = adminAccountsQuerySchema;
20887
18652
  exports.adminOverviewQuerySchema = adminOverviewQuerySchema;
20888
- exports.analyzePolicySource = analyzePolicySource;
20889
- exports.approvalQuorumForRequest = approvalQuorumForRequest;
18653
+ exports.analyzePolicySource = require_step_up.analyzePolicySource;
18654
+ exports.approvalQuorumForRequest = require_step_up.approvalQuorumForRequest;
20890
18655
  exports.assertVendorRangesFresh = assertVendorRangesFresh;
20891
18656
  exports.assignmentChangeRequestSchema = assignmentChangeRequestSchema;
20892
18657
  exports.auditLogQuerySchema = auditLogQuerySchema;
@@ -20895,22 +18660,22 @@ exports.base58btcEncode = base58btcEncode;
20895
18660
  exports.batchAssignmentRequestSchema = batchAssignmentRequestSchema;
20896
18661
  exports.bespokePolicyLabel = bespokePolicyLabel;
20897
18662
  exports.blockDelegationVerdict = blockDelegationVerdict;
20898
- exports.blockEqualityLiterals = blockEqualityLiterals;
20899
- exports.buildChallengeWire = buildChallengeWire;
20900
- exports.buildDelegationBearerHeader = buildDelegationBearerHeader;
20901
- exports.buildDelegationChallengeBody = buildDelegationChallengeBody;
20902
- exports.buildDelegationChallengeEnvelope = buildDelegationChallengeEnvelope;
20903
- exports.buildDelegationChallengeHeader = buildDelegationChallengeHeader;
20904
- exports.buildDelegationInstructions = buildDelegationInstructions;
18663
+ exports.blockEqualityLiterals = require_step_up.blockEqualityLiterals;
18664
+ exports.buildChallengeWire = require_host_adapter.buildChallengeWire;
18665
+ exports.buildDelegationBearerHeader = require_host_adapter.buildDelegationBearerHeader;
18666
+ exports.buildDelegationChallengeBody = require_host_adapter.buildDelegationChallengeBody;
18667
+ exports.buildDelegationChallengeEnvelope = require_host_adapter.buildDelegationChallengeEnvelope;
18668
+ exports.buildDelegationChallengeHeader = require_host_adapter.buildDelegationChallengeHeader;
18669
+ exports.buildDelegationInstructions = require_host_adapter.buildDelegationInstructions;
20905
18670
  exports.buildInitialStepsState = buildInitialStepsState;
20906
18671
  exports.buildKnownPatternLookup = buildKnownPatternLookup;
20907
18672
  exports.buildVerdictEvidence = buildVerdictEvidence;
20908
18673
  exports.calculateDeployProgress = calculateDeployProgress;
20909
18674
  exports.callbackSchema = callbackSchema;
20910
- exports.cedarQuotedValueRegExp = cedarQuotedValueRegExp;
18675
+ exports.cedarQuotedValueRegExp = require_step_up.cedarQuotedValueRegExp;
20911
18676
  exports.changePasswordSchema = changePasswordSchema;
20912
18677
  exports.classifyAgentTaxonomy = classifyAgentTaxonomy;
20913
- exports.classifyResponseShape = classifyResponseShape;
18678
+ exports.classifyResponseShape = require_host_adapter.classifyResponseShape;
20914
18679
  exports.claudeRuntimeLabel = claudeRuntimeLabel;
20915
18680
  exports.compressIpv6 = require_client_ip.compressIpv6;
20916
18681
  exports.computeEntropyConfidence = computeEntropyConfidence;
@@ -20924,27 +18689,27 @@ exports.createPaginatedResponseSchema = createPaginatedResponseSchema;
20924
18689
  exports.createPolicyFetcher = createPolicyFetcher;
20925
18690
  exports.createSuccessResponse = createSuccessResponse;
20926
18691
  exports.createValidationErrorResponse = createValidationErrorResponse;
20927
- exports.decisionPolicyId = decisionPolicyId;
18692
+ exports.decisionPolicyId = require_step_up.decisionPolicyId;
20928
18693
  exports.decodeDidKeyEd25519 = decodeDidKeyEd25519;
20929
18694
  exports.decodeDidKeyP256 = decodeDidKeyP256;
20930
18695
  exports.decodeEd25519PublicKeyMultibaseTolerant = decodeEd25519PublicKeyMultibaseTolerant;
20931
18696
  exports.defaultConfig = defaultConfig;
20932
18697
  exports.deriveConflictId = deriveConflictId;
20933
18698
  exports.deriveCorrelationId = deriveCorrelationId;
20934
- exports.deriveDelegationPickupUri = deriveDelegationPickupUri;
18699
+ exports.deriveDelegationPickupUri = require_host_adapter.deriveDelegationPickupUri;
20935
18700
  exports.deriveImportIssueId = deriveImportIssueId;
20936
18701
  exports.deriveMcpClientDid = deriveMcpClientDid;
20937
18702
  exports.deriveMcpiOrgDid = deriveMcpiOrgDid;
20938
18703
  exports.deriveMcpiOrgKid = deriveMcpiOrgKid;
20939
18704
  exports.deriveMcpiUserDid = deriveMcpiUserDid;
20940
- exports.deriveVerdict = deriveVerdict;
20941
- exports.detectionClassToEnum = detectionClassToEnum;
18705
+ exports.deriveVerdict = require_host_adapter.deriveVerdict;
18706
+ exports.detectionClassToEnum = require_host_adapter.detectionClassToEnum;
20942
18707
  exports.discoveredToolSchema = discoveredToolSchema;
20943
18708
  exports.encodeDidKeyEd25519 = encodeDidKeyEd25519;
20944
18709
  exports.encodeEd25519PublicKeyMultibase = encodeEd25519PublicKeyMultibase;
20945
- exports.encodeVerdictCookie = encodeVerdictCookie;
20946
- exports.enumToDetectionClass = enumToDetectionClass;
20947
- exports.escapeCedarString = escapeCedarString;
18710
+ exports.encodeVerdictCookie = require_host_adapter.encodeVerdictCookie;
18711
+ exports.enumToDetectionClass = require_host_adapter.enumToDetectionClass;
18712
+ exports.escapeCedarString = require_step_up.escapeCedarString;
20948
18713
  exports.evaluatePolicy = evaluatePolicy;
20949
18714
  exports.extractCorrelationIdFromHeaders = extractCorrelationIdFromHeaders;
20950
18715
  exports.extractMatch = require_posture_origins.extractMatch;
@@ -20966,7 +18731,7 @@ exports.gatewayInternalDiscoverErrorSchema = gatewayInternalDiscoverErrorSchema;
20966
18731
  exports.gatewayInternalDiscoverSuccessSchema = gatewayInternalDiscoverSuccessSchema;
20967
18732
  exports.gatewayInternalToolsListSchema = gatewayInternalToolsListSchema;
20968
18733
  exports.gatewayToolCallSchema = gatewayToolCallSchema;
20969
- exports.generateDelegationSid = generateDelegationSid;
18734
+ exports.generateDelegationSid = require_host_adapter.generateDelegationSid;
20970
18735
  exports.generateTestId = generateTestId;
20971
18736
  exports.getAgentDisplayName = getAgentDisplayName;
20972
18737
  exports.getBotType = getBotType;
@@ -20993,14 +18758,14 @@ exports.isAuthorizedLead = isAuthorizedLead;
20993
18758
  exports.isBespokePolicyId = isBespokePolicyId;
20994
18759
  exports.isBlockingAction = isBlockingAction;
20995
18760
  exports.isClaudeProductLabel = isClaudeProductLabel;
20996
- exports.isEngineEnforcing = isEngineEnforcing;
20997
- exports.isForbidBlock = isForbidBlock;
18761
+ exports.isEngineEnforcing = require_step_up.isEngineEnforcing;
18762
+ exports.isForbidBlock = require_step_up.isForbidBlock;
20998
18763
  exports.isHighConfidenceVerification = isHighConfidenceVerification;
20999
18764
  exports.isKnownAgentType = isKnownAgentType;
21000
18765
  exports.isKnownAiCrawler = isKnownAiCrawler;
21001
18766
  exports.isKyaOsHandshakeMethod = isKyaOsHandshakeMethod;
21002
18767
  exports.isKyaOsWireMethod = isKyaOsWireMethod;
21003
- exports.isLegacyDetectionClass = isLegacyDetectionClass;
18768
+ exports.isLegacyDetectionClass = require_host_adapter.isLegacyDetectionClass;
21004
18769
  exports.isLegitimateCategory = isLegitimateCategory;
21005
18770
  exports.isLimitExceeded = isLimitExceeded;
21006
18771
  exports.isNonNavigablePolicyId = isNonNavigablePolicyId;
@@ -21009,7 +18774,7 @@ exports.isPolicyUnavailableError = isPolicyUnavailableError;
21009
18774
  exports.isPrivateOrReservedHost = isPrivateOrReservedHost;
21010
18775
  exports.isSupportedAuthType = isSupportedAuthType;
21011
18776
  exports.isTraditionalBot = isTraditionalBot;
21012
- exports.isUnnarrowedDenyBlock = isUnnarrowedDenyBlock;
18777
+ exports.isUnnarrowedDenyBlock = require_step_up.isUnnarrowedDenyBlock;
21013
18778
  exports.isValidAuthorizationHost = isValidAuthorizationHost;
21014
18779
  exports.isValidFingerprintResponse = isValidFingerprintResponse;
21015
18780
  exports.isValidMcpiOrgSlug = isValidMcpiOrgSlug;
@@ -21024,7 +18789,7 @@ exports.mapProxyAssertions = mapProxyAssertions;
21024
18789
  exports.mapToLegacyAuthType = mapToLegacyAuthType;
21025
18790
  exports.matchPath = matchPath;
21026
18791
  exports.mergeWithDefaults = mergeWithDefaults;
21027
- exports.migrateLegacyDetectionClass = migrateLegacyDetectionClass;
18792
+ exports.migrateLegacyDetectionClass = require_host_adapter.migrateLegacyDetectionClass;
21028
18793
  exports.modelCredentialFingerprint = modelCredentialFingerprint;
21029
18794
  exports.nonNavigablePolicyLabel = nonNavigablePolicyLabel;
21030
18795
  exports.normalizeAgentName = normalizeAgentName;
@@ -21033,8 +18798,8 @@ exports.normalizeAllowedDomainList = normalizeAllowedDomainList;
21033
18798
  exports.normalizeChallengeType = normalizeChallengeType;
21034
18799
  exports.normalizeClientIp = require_client_ip.normalizeClientIp;
21035
18800
  exports.normalizeConfidence = normalizeConfidence;
21036
- exports.normalizeDetectionClass = normalizeDetectionClass;
21037
- exports.normalizeDetectionClassEnum = normalizeDetectionClassEnum;
18801
+ exports.normalizeDetectionClass = require_host_adapter.normalizeDetectionClass;
18802
+ exports.normalizeDetectionClassEnum = require_host_adapter.normalizeDetectionClassEnum;
21038
18803
  exports.normalizeHandshakeMethod = normalizeHandshakeMethod;
21039
18804
  exports.normalizeOrganizationName = normalizeOrganizationName;
21040
18805
  exports.normalizeStoredAllowedDomain = normalizeStoredAllowedDomain;
@@ -21042,7 +18807,7 @@ exports.normalizeWireMethod = normalizeWireMethod;
21042
18807
  exports.oauthClientSchema = oauthClientSchema;
21043
18808
  exports.parseAcceptedArtifactRevision = parseAcceptedArtifactRevision;
21044
18809
  exports.parseAgentName = parseAgentName;
21045
- exports.parseCedarStatements = parseCedarStatements;
18810
+ exports.parseCedarStatements = require_step_up.parseCedarStatements;
21046
18811
  exports.parseClaimVerification = parseClaimVerification;
21047
18812
  exports.parseDependencyBinding = parseDependencyBinding;
21048
18813
  exports.parseEvaluationContext = parseEvaluationContext;
@@ -21054,24 +18819,24 @@ exports.parsePolicyConfig = parsePolicyConfig;
21054
18819
  exports.parseRules = parseRules;
21055
18820
  exports.partial = partial;
21056
18821
  exports.passwordSchema = passwordSchema;
21057
- exports.pathHasExplicitDenyRuleFor = pathHasExplicitDenyRuleFor;
21058
- exports.pathHasUnnarrowedDenyRule = pathHasUnnarrowedDenyRule;
21059
- exports.pathHasUnnarrowedDenyRuleFor = pathHasUnnarrowedDenyRuleFor;
21060
- exports.pathLiteralsInBlock = pathLiteralsInBlock;
18822
+ exports.pathHasExplicitDenyRuleFor = require_step_up.pathHasExplicitDenyRuleFor;
18823
+ exports.pathHasUnnarrowedDenyRule = require_step_up.pathHasUnnarrowedDenyRule;
18824
+ exports.pathHasUnnarrowedDenyRuleFor = require_step_up.pathHasUnnarrowedDenyRuleFor;
18825
+ exports.pathLiteralsInBlock = require_step_up.pathLiteralsInBlock;
21061
18826
  exports.permitDelegationVerdict = permitDelegationVerdict;
21062
18827
  exports.projectResetRequestSchema = projectResetRequestSchema;
21063
18828
  exports.readableText = readableText;
21064
18829
  exports.reconstructConfidenceFromEvidence = reconstructConfidenceFromEvidence;
21065
18830
  exports.refineClaudeDisplayLabel = refineClaudeDisplayLabel;
21066
18831
  exports.refineSessionGrainClaudeLabel = refineSessionGrainClaudeLabel;
21067
- exports.requestCarriesDelegationProof = requestCarriesDelegationProof;
21068
- exports.requestPresentedCredential = requestPresentedCredential;
21069
- exports.requiredScopesForRequest = requiredScopesForRequest;
18832
+ exports.requestCarriesDelegationProof = require_registered_sid.requestCarriesDelegationProof;
18833
+ exports.requestPresentedCredential = require_registered_sid.requestPresentedCredential;
18834
+ exports.requiredScopesForRequest = require_step_up.requiredScopesForRequest;
21070
18835
  exports.resetPasswordSchema = resetPasswordSchema;
21071
18836
  exports.resetPolicyFetcher = resetPolicyFetcher;
21072
18837
  exports.resolveAuthorizationHost = resolveAuthorizationHost;
21073
18838
  exports.resolveBotSignals = resolveBotSignals;
21074
- exports.resolveChallengeContext = resolveChallengeContext;
18839
+ exports.resolveChallengeContext = require_host_adapter.resolveChallengeContext;
21075
18840
  exports.resolveClientIp = require_client_ip.resolveClientIp;
21076
18841
  exports.resolveTrustedDelegationRoots = resolveTrustedDelegationRoots;
21077
18842
  exports.riskScoreColumnValue = riskScoreColumnValue;
@@ -21079,13 +18844,13 @@ exports.riskScoreFromMetadata = riskScoreFromMetadata;
21079
18844
  exports.riskScoreSourceFromMetadata = riskScoreSourceFromMetadata;
21080
18845
  exports.safeParsePolicyConfig = safeParsePolicyConfig;
21081
18846
  exports.safeUrl = safeUrl;
21082
- exports.selectBodyReadable200 = selectBodyReadable200;
21083
- exports.serveBodyReadable200 = serveBodyReadable200;
18847
+ exports.selectBodyReadable200 = require_host_adapter.selectBodyReadable200;
18848
+ exports.serveBodyReadable200 = require_host_adapter.serveBodyReadable200;
21084
18849
  exports.signInSchema = signInSchema;
21085
18850
  exports.signUpSchema = signUpSchema;
21086
- exports.splitCedarBlocks = splitCedarBlocks;
21087
- exports.statementApplies = statementApplies;
21088
- exports.statementId = statementId;
18851
+ exports.splitCedarBlocks = require_step_up.splitCedarBlocks;
18852
+ exports.statementApplies = require_step_up.statementApplies;
18853
+ exports.statementId = require_step_up.statementId;
21089
18854
  exports.strict = strict;
21090
18855
  exports.supportsClientSide = supportsClientSide;
21091
18856
  exports.supportsHeaders = supportsHeaders;
@@ -21099,7 +18864,7 @@ exports.toPercent = toPercent;
21099
18864
  exports.toProviderRegistryFormat = toProviderRegistryFormat;
21100
18865
  exports.toStoredCorrelationId = toStoredCorrelationId;
21101
18866
  exports.toWasmRequestMetadata = toWasmRequestMetadata;
21102
- exports.unescapeCedarString = unescapeCedarString;
18867
+ exports.unescapeCedarString = require_step_up.unescapeCedarString;
21103
18868
  exports.updateStepsState = updateStepsState;
21104
18869
  exports.upstreamDiscoveryErrorSchema = upstreamDiscoveryErrorSchema;
21105
18870
  exports.upstreamServerInputSchema = upstreamServerInputSchema;
@@ -21124,7 +18889,7 @@ Object.defineProperty(exports, 'validateProviderDefinition', {
21124
18889
  });
21125
18890
  exports.validateRules = validateRules;
21126
18891
  exports.validateRulesLoose = validateRulesLoose;
21127
- exports.validateStepUpQuorum = validateStepUpQuorum;
18892
+ exports.validateStepUpQuorum = require_step_up.validateStepUpQuorum;
21128
18893
  exports.vaultResolveDataSchema = vaultResolveDataSchema;
21129
18894
  exports.vaultResolveErrorSchema = vaultResolveErrorSchema;
21130
18895
  exports.vaultResolveMetaSchema = vaultResolveMetaSchema;
@@ -21133,4 +18898,4 @@ exports.vaultResolveSuccessSchema = vaultResolveSuccessSchema;
21133
18898
  exports.verifyContractRecordIdentity = verifyContractRecordIdentity;
21134
18899
  exports.verifyEmailSchema = verifyEmailSchema;
21135
18900
  exports.wasmToDetectionResult = wasmToDetectionResult;
21136
- exports.withNoEvidenceExclusion = withNoEvidenceExclusion;
18901
+ exports.withNoEvidenceExclusion = require_step_up.withNoEvidenceExclusion;