@kya-os/checkpoint-shared 1.5.2 → 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 (135) hide show
  1. package/CHANGELOG.md +98 -1
  2. package/dist/beacon-types/index.d.mts +12 -1
  3. package/dist/beacon-types/index.d.mts.map +1 -1
  4. package/dist/beacon-types/index.d.ts +12 -1
  5. package/dist/beacon-types/index.d.ts.map +1 -1
  6. package/dist/beacon-types/index.js +18 -1
  7. package/dist/beacon-types/index.mjs +18 -2
  8. package/dist/beacon-types/index.mjs.map +1 -1
  9. package/dist/{browser-posture-D4j2a5gi.d.ts → browser-posture-B8YiPa5c.d.ts} +6 -6
  10. package/dist/{browser-posture-D4j2a5gi.d.ts.map → browser-posture-B8YiPa5c.d.ts.map} +1 -1
  11. package/dist/{browser-posture-DVoHMHjY.d.mts → browser-posture-BLhw-MON.d.mts} +6 -6
  12. package/dist/{browser-posture-DVoHMHjY.d.mts.map → browser-posture-BLhw-MON.d.mts.map} +1 -1
  13. package/dist/browser-posture-cookie.js +1 -1
  14. package/dist/browser-posture-cookie.mjs +1 -1
  15. package/dist/browser-posture-cookie.mjs.map +1 -1
  16. package/dist/browser-posture-proof.d.mts +2 -2
  17. package/dist/browser-posture-proof.d.mts.map +1 -1
  18. package/dist/browser-posture-proof.d.ts +2 -2
  19. package/dist/browser-posture-proof.d.ts.map +1 -1
  20. package/dist/browser-posture-proof.js +43 -2
  21. package/dist/browser-posture-proof.mjs +43 -2
  22. package/dist/browser-posture-proof.mjs.map +1 -1
  23. package/dist/browser-posture.d.mts +1 -1
  24. package/dist/browser-posture.d.ts +1 -1
  25. package/dist/browser-posture.js +3 -3
  26. package/dist/browser-posture.mjs +3 -3
  27. package/dist/browser-posture.mjs.map +1 -1
  28. package/dist/canonical-signer/index.d.mts.map +1 -1
  29. package/dist/canonical-signer/index.d.ts.map +1 -1
  30. package/dist/canonical-signer/index.js +86 -51
  31. package/dist/canonical-signer/index.mjs +86 -51
  32. package/dist/canonical-signer/index.mjs.map +1 -1
  33. package/dist/clearance.d.mts +1 -1
  34. package/dist/clearance.d.ts +1 -1
  35. package/dist/clearance.js +2 -2
  36. package/dist/clearance.mjs +2 -2
  37. package/dist/client-ip-DFamiNoz.d.mts +34 -0
  38. package/dist/client-ip-DFamiNoz.d.mts.map +1 -0
  39. package/dist/client-ip-DFamiNoz.d.ts +34 -0
  40. package/dist/client-ip-DFamiNoz.d.ts.map +1 -0
  41. package/dist/client-ip.d.mts +2 -0
  42. package/dist/client-ip.d.ts +2 -0
  43. package/dist/client-ip.js +7 -0
  44. package/dist/client-ip.mjs +3 -0
  45. package/dist/errors/index.d.mts +17 -0
  46. package/dist/errors/index.d.mts.map +1 -1
  47. package/dist/errors/index.d.ts +17 -0
  48. package/dist/errors/index.d.ts.map +1 -1
  49. package/dist/errors/index.js +75 -3
  50. package/dist/errors/index.mjs +75 -3
  51. package/dist/errors/index.mjs.map +1 -1
  52. package/dist/{external-Ct8j_hto.d.ts → external-B7WI9FyQ.d.mts} +2 -2
  53. package/dist/{external-Ct8j_hto.d.mts.map → external-B7WI9FyQ.d.mts.map} +1 -1
  54. package/dist/{external-Ct8j_hto.d.mts → external-B7WI9FyQ.d.ts} +2 -2
  55. package/dist/{external-Ct8j_hto.d.ts.map → external-B7WI9FyQ.d.ts.map} +1 -1
  56. package/dist/gateway-client-ip.d.mts +1 -1
  57. package/dist/gateway-client-ip.d.ts +1 -1
  58. package/dist/gateway-client-ip.js +1 -1
  59. package/dist/gateway-client-ip.mjs +1 -1
  60. package/dist/host-adapter/index.d.mts +2 -0
  61. package/dist/host-adapter/index.d.ts +2 -0
  62. package/dist/host-adapter/index.js +23 -0
  63. package/dist/host-adapter/index.mjs +3 -0
  64. package/dist/host-adapter-C-4IxmqM.mjs +540 -0
  65. package/dist/host-adapter-C-4IxmqM.mjs.map +1 -0
  66. package/dist/host-adapter-CwW9YB0U.js +694 -0
  67. package/dist/index-B7rTovHa.d.mts +707 -0
  68. package/dist/index-B7rTovHa.d.mts.map +1 -0
  69. package/dist/index-HaqfPtaL.d.ts +707 -0
  70. package/dist/index-HaqfPtaL.d.ts.map +1 -0
  71. package/dist/index.d.mts +742 -937
  72. package/dist/index.d.mts.map +1 -1
  73. package/dist/index.d.ts +742 -937
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +758 -1193
  76. package/dist/index.mjs +659 -1148
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/kya-http-error-codes-7ewV5RuK.d.mts +29 -0
  79. package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +1 -0
  80. package/dist/kya-http-error-codes-7ewV5RuK.d.ts +29 -0
  81. package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +1 -0
  82. package/dist/kya-http-error-codes-C2JiWPsi.mjs +73 -0
  83. package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +1 -0
  84. package/dist/kya-http-error-codes-UYb1zpGM.js +83 -0
  85. package/dist/kya-http.d.mts +3 -0
  86. package/dist/kya-http.d.ts +3 -0
  87. package/dist/kya-http.js +11 -0
  88. package/dist/kya-http.mjs +4 -0
  89. package/dist/mcpi/approval-grant/index.d.mts.map +1 -1
  90. package/dist/mcpi/approval-grant/index.d.ts.map +1 -1
  91. package/dist/mcpi/approval-grant/index.js +10 -1
  92. package/dist/mcpi/approval-grant/index.mjs +10 -1
  93. package/dist/mcpi/approval-grant/index.mjs.map +1 -1
  94. package/dist/mcpi/dashboard-config/index.d.mts +3 -2
  95. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
  96. package/dist/mcpi/dashboard-config/index.d.ts +3 -2
  97. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
  98. package/dist/policy/enforcement.d.mts +2 -0
  99. package/dist/policy/enforcement.d.ts +2 -0
  100. package/dist/policy/enforcement.js +15 -0
  101. package/dist/policy/enforcement.mjs +3 -0
  102. package/dist/{posture-origins-Dl7i8j93.mjs → posture-origins-Ba83O0cD.mjs} +3 -3
  103. package/dist/posture-origins-Ba83O0cD.mjs.map +1 -0
  104. package/dist/{posture-origins-CEm83u4D.js → posture-origins-CdVOdiMT.js} +7 -1
  105. package/dist/{project-verification-key-CgSVX9_m.mjs → project-verification-key-66N4edKn.mjs} +2 -2
  106. package/dist/{project-verification-key-CgSVX9_m.mjs.map → project-verification-key-66N4edKn.mjs.map} +1 -1
  107. package/dist/{project-verification-key-C3L5rd8a.js → project-verification-key-BccT12tQ.js} +1 -1
  108. package/dist/registered-sid-D3g-gZQF.d.mts +11 -0
  109. package/dist/registered-sid-D3g-gZQF.d.mts.map +1 -0
  110. package/dist/registered-sid-D3g-gZQF.d.ts +11 -0
  111. package/dist/registered-sid-D3g-gZQF.d.ts.map +1 -0
  112. package/dist/registered-sid-eLCNZvIF.js +170 -0
  113. package/dist/registered-sid-hUl-bvM5.mjs +142 -0
  114. package/dist/registered-sid-hUl-bvM5.mjs.map +1 -0
  115. package/dist/{schemas-DxY-dk9y.mjs → schemas-7qodsG-Z.mjs} +49 -2
  116. package/dist/schemas-7qodsG-Z.mjs.map +1 -0
  117. package/dist/{schemas-BmjNLAE7.js → schemas-YhagYDx_.js} +59 -0
  118. package/dist/step-up-BjP--hG-.d.mts +114 -0
  119. package/dist/step-up-BjP--hG-.d.mts.map +1 -0
  120. package/dist/step-up-BjP--hG-.d.ts +114 -0
  121. package/dist/step-up-BjP--hG-.d.ts.map +1 -0
  122. package/dist/step-up-C2d8C20x.js +1697 -0
  123. package/dist/step-up-COlmWJN8.mjs +1513 -0
  124. package/dist/step-up-COlmWJN8.mjs.map +1 -0
  125. package/fixtures/cli-registration.v2.json +115 -0
  126. package/fixtures/detection/reason-codes.json +1 -1
  127. package/fixtures/kya-http/README.md +34 -26
  128. package/fixtures/kya-http/protected-resource-metadata.full.json +14 -5
  129. package/fixtures/kya-http/protected-resource-metadata.invalid-issuer.json +51 -0
  130. package/fixtures/kya-http/protected-resource-metadata.no-issuer.json +32 -0
  131. package/fixtures/reviewer-grant-revocation.v1.json +285 -0
  132. package/package.json +26 -4
  133. package/dist/posture-origins-Dl7i8j93.mjs.map +0 -1
  134. package/dist/schemas-DxY-dk9y.mjs.map +0 -1
  135. package/fixtures/kya-http/protected-resource-metadata.global.json +0 -28
@@ -0,0 +1,1697 @@
1
+ //#region src/policy/engine-enforcing.ts
2
+ /**
3
+ * The act-gate for a composed policy: the engine acts on it only when engine
4
+ * enforcement is switched on and the policy is not disabled. Otherwise the
5
+ * composed policy is at most shadow-evaluated. Kept apart from `schemas.ts`,
6
+ * which builds Zod schemas when it loads, so request-time callers can use it
7
+ * without loading Zod.
8
+ */
9
+ function isEngineEnforcing(flags) {
10
+ return flags.engineEnforcementEnabled === true && flags.enabled !== false;
11
+ }
12
+
13
+ //#endregion
14
+ //#region src/policy/fail-closed-response.ts
15
+ const FAIL_CLOSED_STATUS = 503;
16
+ const FAIL_CLOSED_RETRY_AFTER_SECONDS = 3;
17
+ const FAIL_CLOSED_BODY = {
18
+ error: "Service temporarily unavailable",
19
+ source: "checkpoint-middleware"
20
+ };
21
+ const FAIL_CLOSED_HEADERS = {
22
+ "Content-Type": "application/json",
23
+ "Cache-Control": "no-store",
24
+ "Retry-After": String(3)
25
+ };
26
+
27
+ //#endregion
28
+ //#region src/policy/cedar-mask.ts
29
+ const blank = (char) => char === "\n" || char === "\r" ? char : " ";
30
+ function maskCedar(cedar) {
31
+ const visible = cedar.split("");
32
+ const code = cedar.split("");
33
+ const inString = new Array(cedar.length).fill(false);
34
+ let i = 0;
35
+ while (i < cedar.length) if (cedar[i] === "\"") {
36
+ let end = i + 1;
37
+ while (end < cedar.length && cedar[end] !== "\"") end += cedar[end] === "\\" ? 2 : 1;
38
+ const bodyEnd = Math.min(end, cedar.length);
39
+ for (let k = i + 1; k < bodyEnd; k++) {
40
+ inString[k] = true;
41
+ code[k] = blank(cedar[k]);
42
+ }
43
+ i = end + 1;
44
+ } else if (cedar[i] === "/" && cedar[i + 1] === "/") while (i < cedar.length && cedar[i] !== "\n" && cedar[i] !== "\r") {
45
+ visible[i] = " ";
46
+ code[i] = " ";
47
+ i++;
48
+ }
49
+ else i++;
50
+ return {
51
+ visible: visible.join(""),
52
+ code: code.join(""),
53
+ inString
54
+ };
55
+ }
56
+
57
+ //#endregion
58
+ //#region src/policy/cedar-space.ts
59
+ const CEDAR_SPACE_CLASS = "[\\t-\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]";
60
+ function isCedarSpace(char) {
61
+ const code = char.charCodeAt(0);
62
+ 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;
63
+ }
64
+
65
+ //#endregion
66
+ //#region src/policy/cedar-string.ts
67
+ /**
68
+ * The Cedar double-quoted string grammar shared by the compose engine's emitter/
69
+ * parser and every enforcement-path TEXT reader (required-scopes, cedar-rule-match).
70
+ * Keeping the escape codec AND the capture pattern in one place means a value the
71
+ * emitter escapes is decoded identically wherever a reader parses it back — they
72
+ * can never drift. (Rust/.NET parse Cedar with a real parser and are unaffected.)
73
+ */
74
+ /** Escape a value for embedding inside a Cedar double-quoted string literal. */
75
+ function escapeCedarString(value) {
76
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
77
+ }
78
+ /** Inverse of {@link escapeCedarString} — decode Cedar string escapes to raw text. */
79
+ function unescapeCedarString(value) {
80
+ return value.replace(/\\([\\"nrt])/g, (_m, ch) => ch === "n" ? "\n" : ch === "r" ? "\r" : ch === "t" ? " " : ch);
81
+ }
82
+ /**
83
+ * Build a RegExp matching `<prefixSource>"<body>"`, where <body> is an escape-aware
84
+ * Cedar string. Capture group 1 is the RAW (still-escaped) body — pass it through
85
+ * {@link unescapeCedarString} before use. `prefixSource` is a regex-source fragment
86
+ * (escape its own metacharacters). This is the single source of the quoted-string
87
+ * capture pattern.
88
+ */
89
+ function cedarQuotedValueRegExp(prefixSource, flags = "") {
90
+ return new RegExp(`${prefixSource}"((?:\\\\.|[^"\\\\])*)"`, flags);
91
+ }
92
+ const LIKE_ESCAPES = {
93
+ n: "\n",
94
+ r: "\r",
95
+ t: " ",
96
+ "0": "\0"
97
+ };
98
+ const NUMERIC_ESCAPE = /x([0-9a-fA-F]{2})|u\{([0-9a-fA-F][0-9a-fA-F_]*)\}/y;
99
+ const MAX_CODE_POINT = 1114111;
100
+ const MAX_UNICODE_DIGITS = 6;
101
+ function numericEscapeCode(raw, at) {
102
+ NUMERIC_ESCAPE.lastIndex = at;
103
+ const match = NUMERIC_ESCAPE.exec(raw);
104
+ if (match === null) return null;
105
+ if (match[1] !== void 0) return {
106
+ code: parseInt(match[1], 16),
107
+ length: match[0].length
108
+ };
109
+ const digits = match[2].replace(/_/g, "");
110
+ const code = parseInt(digits, 16);
111
+ return digits.length <= MAX_UNICODE_DIGITS && code <= MAX_CODE_POINT && (code < 55296 || code > 57343) ? {
112
+ code,
113
+ length: match[0].length
114
+ } : null;
115
+ }
116
+ function cedarLikeSegments(rawPattern) {
117
+ const segments = [""];
118
+ const append = (char) => {
119
+ if (char === "*") segments.push("");
120
+ else segments[segments.length - 1] += char;
121
+ };
122
+ for (let i = 0; i < rawPattern.length; i++) {
123
+ const char = rawPattern.charAt(i);
124
+ if (char !== "\\") {
125
+ append(char);
126
+ continue;
127
+ }
128
+ const numeric = numericEscapeCode(rawPattern, i + 1);
129
+ if (numeric !== null) {
130
+ append(String.fromCodePoint(numeric.code));
131
+ i += numeric.length;
132
+ } else {
133
+ const next = rawPattern.charAt(++i);
134
+ segments[segments.length - 1] += LIKE_ESCAPES[next] ?? next;
135
+ }
136
+ }
137
+ return segments;
138
+ }
139
+ function globMatches(segments, value) {
140
+ const first = segments[0];
141
+ if (segments.length === 1) return value === first;
142
+ const last = segments[segments.length - 1];
143
+ const end = value.length - last.length;
144
+ if (end < first.length || !value.startsWith(first) || !value.endsWith(last)) return false;
145
+ let position = first.length;
146
+ for (let i = 1; i < segments.length - 1; i++) {
147
+ const at = value.indexOf(segments[i], position);
148
+ if (at === -1 || at + segments[i].length > end) return false;
149
+ position = at + segments[i].length;
150
+ }
151
+ return true;
152
+ }
153
+
154
+ //#endregion
155
+ //#region src/policy/legacy-carve-out.ts
156
+ const NO_EVIDENCE_CATEGORY = "no_evidence";
157
+ const NO_EVIDENCE_EXCLUSION_TERM = `principal.category != "${NO_EVIDENCE_CATEGORY}"`;
158
+ const NO_EVIDENCE_EQUALITY_TERM = `principal.category == "${NO_EVIDENCE_CATEGORY}"`;
159
+ const WS = `${CEDAR_SPACE_CLASS}*`;
160
+ const SEGMENT_BOUNDARY = new RegExp(`\\b(?:forbid|permit)${WS}\\(|;`, "g");
161
+ const ACCESSOR = `(?:\\.${WS}category\\b|\\[${WS}"C[^"]*"${WS}\\])`;
162
+ const SUBJECT = `(?<![.\\w])principal${WS}${ACCESSOR}`;
163
+ const EXACT = "\"E[^\"]*\"";
164
+ const LIKEABLE = "\"[EL][^\"]*\"";
165
+ const ELEMENTS = `[^\\]\\[]*(?:\\[${WS}"[^"]*"${WS}\\][^\\]\\[]*){0,16}`;
166
+ const CATEGORY_READ = new RegExp(`(?<![.\\w])principal(?:${WS}\\))*${WS}${ACCESSOR}`, "g");
167
+ const GROUP_OR_PRINCIPAL = /[()[\]{}]|(?<![\w.])principal(?!\w)/g;
168
+ const CHAIN_LINK = new RegExp(`${WS}(?:\\.${WS}(category\\b)|\\.${WS}\\w+|\\[${WS}"(C)?[^"]*"${WS}\\])`, "y");
169
+ const PRINCIPAL_LENGTH = 9;
170
+ const BARE_GROUP = new RegExp(`^(?:\\(|${CEDAR_SPACE_CLASS})*$`);
171
+ const CATEGORY_COMPARED = new RegExp(`${SUBJECT}${WS}(?:(?:==|!=)${WS}${EXACT}|like${WS}${LIKEABLE})|${EXACT}${WS}(?:==|!=)${WS}${SUBJECT}`);
172
+ const LIST_CALL = new RegExp(`\\[(${ELEMENTS})\\]${WS}\\.${WS}contains(?:All|Any)?${WS}(?:(${SUBJECT})|(${EXACT})|\\[(${ELEMENTS})\\])`, "g");
173
+ const HAS_CATEGORY = new RegExp(SUBJECT);
174
+ const HAS_NO_EVIDENCE = new RegExp(EXACT);
175
+ 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");
176
+ function literalMarker(body) {
177
+ const segments = cedarLikeSegments(body);
178
+ if (segments.length === 1) {
179
+ if (segments[0] === "no_evidence") return "E";
180
+ return segments[0] === "category" ? "C" : " ";
181
+ }
182
+ return segments.some((segment) => segment.includes("no_evidence")) && globMatches(segments, "no_evidence") ? "L" : " ";
183
+ }
184
+ function scan(cedar) {
185
+ const { visible, code, inString } = maskCedar(cedar);
186
+ const marked = code.split("");
187
+ for (let start = 0; start < cedar.length;) {
188
+ if (!inString[start]) {
189
+ start++;
190
+ continue;
191
+ }
192
+ let end = start;
193
+ while (end < cedar.length && inString[end]) end++;
194
+ const marker = literalMarker(visible.slice(start, end));
195
+ if (marker !== " ") marked[start] = marker;
196
+ start = end;
197
+ }
198
+ const text = marked.join("");
199
+ return {
200
+ visible,
201
+ text,
202
+ flat: text.replace(/[()]/g, " "),
203
+ pairs: pairParentheses(text)
204
+ };
205
+ }
206
+ function pairParentheses(text) {
207
+ const pairs = new Int32Array(text.length).fill(-1);
208
+ const open = [];
209
+ for (let i = 0; i < text.length; i++) if (text[i] === "(") open.push(i);
210
+ else if (text[i] === ")") pairs[i] = open.pop() ?? -1;
211
+ return pairs;
212
+ }
213
+ function statementRanges(text) {
214
+ const ranges = [];
215
+ let open = -1;
216
+ for (const boundary of text.matchAll(SEGMENT_BOUNDARY)) if (boundary[0] === ";") {
217
+ if (open !== -1) ranges.push([open, boundary.index + 1]);
218
+ open = -1;
219
+ } else {
220
+ if (open !== -1) ranges.push([open, boundary.index]);
221
+ open = boundary.index;
222
+ }
223
+ if (open !== -1) ranges.push([open, text.length]);
224
+ return ranges;
225
+ }
226
+ function applyEdits(cedar, edits) {
227
+ if (edits.length === 0) return cedar;
228
+ const pieces = [];
229
+ let position = 0;
230
+ for (const edit of edits) {
231
+ pieces.push(cedar.slice(position, edit.start), edit.text);
232
+ position = edit.end;
233
+ }
234
+ pieces.push(cedar.slice(position));
235
+ return pieces.join("");
236
+ }
237
+ function namesNoEvidenceIn(flat) {
238
+ if (CATEGORY_COMPARED.test(flat)) return true;
239
+ for (const [, receiver, subject, exact, list = ""] of flat.matchAll(LIST_CALL)) {
240
+ const receiverReadsCategory = HAS_CATEGORY.test(receiver);
241
+ const receiverNamesNoEvidence = HAS_NO_EVIDENCE.test(receiver);
242
+ if (receiverReadsCategory && (exact !== void 0 || HAS_NO_EVIDENCE.test(list)) || receiverNamesNoEvidence && (subject !== void 0 || HAS_CATEGORY.test(list))) return true;
243
+ }
244
+ return false;
245
+ }
246
+ function namesNoEvidence(cedar) {
247
+ return namesNoEvidenceIn(scan(cedar).flat);
248
+ }
249
+ function groupStart({ text, pairs }, principal, read) {
250
+ const lastCloser = read.lastIndexOf(")");
251
+ if (lastCloser === -1) return principal;
252
+ const open = pairs[principal + lastCloser];
253
+ return open !== -1 && BARE_GROUP.test(text.slice(open, principal)) ? open : -1;
254
+ }
255
+ const isWordChar = (char) => char !== void 0 && /\w/.test(char);
256
+ function skipSpaceBack(text, from) {
257
+ let i = from;
258
+ while (i >= 0 && isCedarSpace(text[i])) i--;
259
+ return i;
260
+ }
261
+ function skipSpaceForward(text, from) {
262
+ let i = from;
263
+ while (i < text.length && isCedarSpace(text[i])) i++;
264
+ return i;
265
+ }
266
+ function wordEndingAt(text, end) {
267
+ let start = end;
268
+ while (start > 0 && isWordChar(text[start - 1])) start--;
269
+ return text.slice(start, end + 1);
270
+ }
271
+ function isPrincipalVariable(text, at) {
272
+ const before = skipSpaceBack(text, at - 1);
273
+ const char = text[before];
274
+ if (char === "." || char === "?") return false;
275
+ if (char === ":" && text[before - 1] === ":") return false;
276
+ if (isWordChar(char) && wordEndingAt(text, before) === "has") return false;
277
+ return text[skipSpaceForward(text, at + PRINCIPAL_LENGTH)] !== ":";
278
+ }
279
+ function isBranchValue(text, at) {
280
+ let before = skipSpaceBack(text, at - 1);
281
+ while (text[before] === "(") before = skipSpaceBack(text, before - 1);
282
+ const char = text[before];
283
+ const word = isWordChar(char) ? wordEndingAt(text, before) : "";
284
+ const introduced = word === "then" || word === "else" || char === ":" && text[before - 1] !== ":";
285
+ const after = skipSpaceForward(text, at + PRINCIPAL_LENGTH);
286
+ const next = text[after];
287
+ const ends = next === ")" || next === "}" || next === "]" || next === "," || text.startsWith("else", after) && !isWordChar(text[after + 4]);
288
+ return introduced && ends;
289
+ }
290
+ function headEnd(text, from, to) {
291
+ let depth = 0;
292
+ for (let i = text.indexOf("(", from); i < to; i++) if (text[i] === "(") depth++;
293
+ else if (text[i] === ")" && --depth === 0) return i + 1;
294
+ return from;
295
+ }
296
+ function directReads(scanned, from, to) {
297
+ const reads = [];
298
+ for (const read of scanned.text.slice(from, to).matchAll(CATEGORY_READ)) {
299
+ const principal = from + read.index;
300
+ if (!isPrincipalVariable(scanned.text, principal)) continue;
301
+ const start = groupStart(scanned, principal, read[0]);
302
+ if (start !== -1) reads.push({
303
+ principal,
304
+ start,
305
+ end: principal + read[0].length
306
+ });
307
+ }
308
+ return reads;
309
+ }
310
+ function readsCategoryAfter(text, from) {
311
+ CHAIN_LINK.lastIndex = from;
312
+ 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;
313
+ return false;
314
+ }
315
+ function readsCategoryOfCarriedPrincipal(text, from, to, reads) {
316
+ const direct = new Set(reads.map((read) => read.principal));
317
+ const holding = [false];
318
+ for (const token of text.slice(from, to).matchAll(GROUP_OR_PRINCIPAL)) {
319
+ const at = from + token.index;
320
+ if (token[0] === "principal") {
321
+ if (!direct.has(at) && isPrincipalVariable(text, at) && isBranchValue(text, at)) holding[holding.length - 1] = true;
322
+ } else if ("([{".includes(token[0])) holding.push(false);
323
+ else if (holding.length > 1 && holding.pop()) {
324
+ holding[holding.length - 1] = true;
325
+ if (readsCategoryAfter(text, at + 1)) return true;
326
+ }
327
+ }
328
+ return false;
329
+ }
330
+ function withNoEvidenceExclusion(cedar) {
331
+ const scanned = scan(cedar);
332
+ const { visible, text, flat } = scanned;
333
+ const edits = [];
334
+ for (const [from, to] of statementRanges(text)) {
335
+ if (namesNoEvidenceIn(flat.slice(from, to))) continue;
336
+ const reads = directReads(scanned, from, to);
337
+ if (reads.length === 0) continue;
338
+ if (readsCategoryOfCarriedPrincipal(text, headEnd(text, from, to), to, reads)) continue;
339
+ for (const { start, end } of reads) {
340
+ const accessor = visible.slice(start, end);
341
+ edits.push({
342
+ start,
343
+ end,
344
+ text: `(if ${accessor} == "${NO_EVIDENCE_CATEGORY}" then "human" else ${accessor})`
345
+ });
346
+ }
347
+ }
348
+ return applyEdits(cedar, edits);
349
+ }
350
+ function withoutNoEvidenceExclusion(cedar) {
351
+ const { visible, inString } = maskCedar(cedar);
352
+ const edits = [];
353
+ for (const read of visible.matchAll(SUBSTITUTED_READ)) {
354
+ const key = read[2];
355
+ if (!inString[read.index] && (key === void 0 || literalMarker(key.slice(1, -1)) === "C")) edits.push({
356
+ start: read.index,
357
+ end: read.index + read[0].length,
358
+ text: read[1]
359
+ });
360
+ }
361
+ return applyEdits(cedar, edits);
362
+ }
363
+
364
+ //#endregion
365
+ //#region src/policy/cedar-expression.ts
366
+ const MAX_NESTING = 48;
367
+ const MAX_HEX_ESCAPE = 127;
368
+ const UNNAMED_CATEGORY = "\ud800";
369
+ const LONE_SURROGATE = /\p{Surrogate}/u;
370
+ const HUMAN_NAMES = [
371
+ "",
372
+ "human",
373
+ "unknown",
374
+ "anonymous"
375
+ ];
376
+ const UNKNOWN = { k: "unknown" };
377
+ const PUNCTUATION = /* @__PURE__ */ new Set("<>!+-*()[]{}.,:");
378
+ const TWO_CHARACTER = /* @__PURE__ */ new Set([
379
+ "&&",
380
+ "||",
381
+ "==",
382
+ "!=",
383
+ "<=",
384
+ ">=",
385
+ "::"
386
+ ]);
387
+ const SIMPLE_ESCAPES = {
388
+ n: "\n",
389
+ r: "\r",
390
+ t: " ",
391
+ "\\": "\\",
392
+ "0": "\0",
393
+ "'": "'",
394
+ "\"": "\""
395
+ };
396
+ const IDENTIFIER_START = /[A-Za-z_]/;
397
+ const IDENTIFIER_PART = /[A-Za-z0-9_]/;
398
+ const DIGIT = /[0-9]/;
399
+ const UNSUPPORTED_PATTERN_ESCAPE = /\\[0u]/;
400
+ function tokenize(text) {
401
+ const tokens = [];
402
+ let i = 0;
403
+ while (i < text.length) {
404
+ const char = text[i];
405
+ if (isCedarSpace(char)) i += 1;
406
+ else if (char === "/" && text[i + 1] === "/") while (i < text.length && text[i] !== "\n" && text[i] !== "\r") i += 1;
407
+ else if (char === "\"") {
408
+ let end = i + 1;
409
+ while (end < text.length && text[end] !== "\"") end += text[end] === "\\" ? 2 : 1;
410
+ if (end >= text.length) throw new SyntaxError("unterminated string");
411
+ const body = text.slice(i + 1, end);
412
+ if (LONE_SURROGATE.test(body)) throw new SyntaxError("ill-formed string");
413
+ tokens.push({
414
+ t: "str",
415
+ v: body
416
+ });
417
+ i = end + 1;
418
+ } else if (IDENTIFIER_START.test(char)) {
419
+ let end = i + 1;
420
+ while (end < text.length && IDENTIFIER_PART.test(text[end])) end += 1;
421
+ tokens.push({
422
+ t: "id",
423
+ v: text.slice(i, end)
424
+ });
425
+ i = end;
426
+ } else if (DIGIT.test(char)) {
427
+ let end = i + 1;
428
+ while (end < text.length && DIGIT.test(text[end])) end += 1;
429
+ tokens.push({
430
+ t: "num",
431
+ v: text.slice(i, end)
432
+ });
433
+ i = end;
434
+ } else if (TWO_CHARACTER.has(text.slice(i, i + 2))) {
435
+ tokens.push({
436
+ t: "p",
437
+ v: text.slice(i, i + 2)
438
+ });
439
+ i += 2;
440
+ } else if (PUNCTUATION.has(char)) {
441
+ tokens.push({
442
+ t: "p",
443
+ v: char
444
+ });
445
+ i += 1;
446
+ } else throw new SyntaxError("unexpected character");
447
+ }
448
+ return tokens;
449
+ }
450
+ function decodeCedarString(raw) {
451
+ let out = "";
452
+ for (let i = 0; i < raw.length; i += 1) if (raw[i] !== "\\") out += raw[i];
453
+ else if (raw[i + 1] === "x" || raw[i + 1] === "u") {
454
+ const numeric = numericEscapeCode(raw, i + 1);
455
+ if (numeric === null || raw[i + 1] === "x" && numeric.code > MAX_HEX_ESCAPE) return null;
456
+ out += String.fromCodePoint(numeric.code);
457
+ i += numeric.length;
458
+ } else {
459
+ const mapped = SIMPLE_ESCAPES[raw[i + 1]];
460
+ if (mapped === void 0) return null;
461
+ out += mapped;
462
+ i += 1;
463
+ }
464
+ return out;
465
+ }
466
+ var Parser = class {
467
+ tokens;
468
+ position = 0;
469
+ readsTag = false;
470
+ constructor(tokens) {
471
+ this.tokens = tokens;
472
+ }
473
+ parseAll() {
474
+ const expression = this.expression(0);
475
+ if (this.position < this.tokens.length) throw new SyntaxError("trailing tokens");
476
+ return this.readsTag ? UNKNOWN : expression;
477
+ }
478
+ peek() {
479
+ return this.tokens[this.position];
480
+ }
481
+ is(type, value) {
482
+ const token = this.peek();
483
+ return token !== void 0 && token.t === type && token.v === value;
484
+ }
485
+ take(type, value) {
486
+ const found = this.is(type, value);
487
+ if (found) this.position += 1;
488
+ return found;
489
+ }
490
+ expect(type, value) {
491
+ if (!this.take(type, value)) throw new SyntaxError(`expected ${value}`);
492
+ }
493
+ next(type) {
494
+ const token = this.peek();
495
+ if (token === void 0 || token.t !== type) throw new SyntaxError(`expected ${type}`);
496
+ this.position += 1;
497
+ return token;
498
+ }
499
+ expression(depth) {
500
+ if (depth > MAX_NESTING) throw new SyntaxError("too deep");
501
+ if (this.take("id", "if")) {
502
+ const cond = this.expression(depth + 1);
503
+ this.expect("id", "then");
504
+ const then = this.expression(depth + 1);
505
+ this.expect("id", "else");
506
+ return {
507
+ k: "if",
508
+ cond,
509
+ then,
510
+ otherwise: this.expression(depth + 1)
511
+ };
512
+ }
513
+ return this.chain("||", () => this.chain("&&", () => this.relation(depth)));
514
+ }
515
+ chain(operator, operand) {
516
+ const terms = [operand()];
517
+ while (this.take("p", operator)) terms.push(operand());
518
+ return terms.length === 1 ? terms[0] : {
519
+ k: operator === "&&" ? "and" : "or",
520
+ terms
521
+ };
522
+ }
523
+ relation(depth) {
524
+ const left = this.additive(depth);
525
+ const token = this.peek();
526
+ if (token === void 0) return left;
527
+ if (token.t === "p" && (token.v === "==" || token.v === "!=")) {
528
+ this.position += 1;
529
+ return {
530
+ k: "cmp",
531
+ equals: token.v === "==",
532
+ left,
533
+ right: this.additive(depth)
534
+ };
535
+ }
536
+ if (token.t === "p" && [
537
+ "<",
538
+ "<=",
539
+ ">",
540
+ ">="
541
+ ].includes(token.v)) {
542
+ this.position += 1;
543
+ this.additive(depth);
544
+ return UNKNOWN;
545
+ }
546
+ if (token.t === "id" && token.v === "in") {
547
+ this.position += 1;
548
+ this.additive(depth);
549
+ return UNKNOWN;
550
+ }
551
+ if (token.t === "id" && token.v === "like") {
552
+ this.position += 1;
553
+ return {
554
+ k: "like",
555
+ operand: left,
556
+ pattern: this.next("str").v
557
+ };
558
+ }
559
+ if (token.t === "id" && token.v === "has") {
560
+ this.position += 1;
561
+ this.attributePath();
562
+ return UNKNOWN;
563
+ }
564
+ if (token.t === "id" && token.v === "is") {
565
+ this.position += 1;
566
+ this.namePath();
567
+ if (this.take("id", "in")) this.additive(depth);
568
+ return UNKNOWN;
569
+ }
570
+ return left;
571
+ }
572
+ attributePath() {
573
+ const first = this.peek();
574
+ if (first === void 0 || first.t !== "id" && first.t !== "str") throw new SyntaxError("expected attribute");
575
+ this.position += 1;
576
+ while (this.take("p", ".")) {
577
+ const part = this.peek();
578
+ if (part === void 0 || part.t !== "id" && part.t !== "str") throw new SyntaxError("expected attribute");
579
+ this.position += 1;
580
+ }
581
+ }
582
+ namePath() {
583
+ this.next("id");
584
+ while (this.take("p", "::")) this.next("id");
585
+ }
586
+ additive(depth) {
587
+ let result = this.multiplicative(depth);
588
+ while (this.is("p", "+") || this.is("p", "-")) {
589
+ this.position += 1;
590
+ this.multiplicative(depth);
591
+ result = UNKNOWN;
592
+ }
593
+ return result;
594
+ }
595
+ multiplicative(depth) {
596
+ let result = this.unary(depth);
597
+ while (this.take("p", "*")) {
598
+ this.unary(depth);
599
+ result = UNKNOWN;
600
+ }
601
+ return result;
602
+ }
603
+ unary(depth) {
604
+ const prefixes = [];
605
+ while (this.is("p", "!") || this.is("p", "-")) {
606
+ prefixes.push(this.peek().v);
607
+ this.position += 1;
608
+ if (prefixes.length > MAX_NESTING) throw new SyntaxError("too deep");
609
+ }
610
+ let result = this.member(depth);
611
+ for (let i = prefixes.length - 1; i >= 0; i -= 1) result = prefixes[i] === "!" ? {
612
+ k: "not",
613
+ operand: result
614
+ } : UNKNOWN;
615
+ return result;
616
+ }
617
+ member(depth) {
618
+ let result = this.primary(depth);
619
+ let links = 0;
620
+ for (;;) {
621
+ if (this.take("p", ".")) {
622
+ const method = this.next("id").v;
623
+ if (method === "getTag") this.readsTag = true;
624
+ result = this.is("p", "(") ? {
625
+ k: "call",
626
+ method,
627
+ receiver: result,
628
+ args: this.arguments(depth)
629
+ } : attribute(result, method);
630
+ } else if (this.take("p", "[")) {
631
+ const key = this.next("str").v;
632
+ this.expect("p", "]");
633
+ result = attribute(result, decodeCedarString(key));
634
+ } else return result;
635
+ links += 1;
636
+ if (links > MAX_NESTING) throw new SyntaxError("too deep");
637
+ }
638
+ }
639
+ arguments(depth) {
640
+ this.expect("p", "(");
641
+ return this.list(")", depth + 1);
642
+ }
643
+ list(close, depth) {
644
+ const items = [];
645
+ while (!this.take("p", close)) {
646
+ items.push(this.expression(depth));
647
+ if (!this.is("p", close)) this.expect("p", ",");
648
+ }
649
+ return items;
650
+ }
651
+ primary(depth) {
652
+ const token = this.peek();
653
+ if (token === void 0) throw new SyntaxError("unexpected end");
654
+ this.position += 1;
655
+ if (token.t === "str") return {
656
+ k: "str",
657
+ raw: token.v
658
+ };
659
+ if (token.t === "num") return UNKNOWN;
660
+ if (token.t === "id") {
661
+ if (token.v === "true" || token.v === "false") return {
662
+ k: "lit",
663
+ v: token.v === "true"
664
+ };
665
+ if ([
666
+ "principal",
667
+ "resource",
668
+ "action",
669
+ "context"
670
+ ].includes(token.v)) return {
671
+ k: "var",
672
+ name: token.v
673
+ };
674
+ while (this.take("p", "::")) {
675
+ if (this.peek()?.t === "str") {
676
+ this.position += 1;
677
+ return UNKNOWN;
678
+ }
679
+ this.next("id");
680
+ }
681
+ if (this.is("p", "(")) this.arguments(depth);
682
+ return UNKNOWN;
683
+ }
684
+ if (token.v === "(") {
685
+ const inner = this.expression(depth + 1);
686
+ this.expect("p", ")");
687
+ return inner;
688
+ }
689
+ if (token.v === "[") return {
690
+ k: "set",
691
+ items: this.list("]", depth + 1)
692
+ };
693
+ if (token.v === "{") {
694
+ while (!this.take("p", "}")) {
695
+ const key = this.peek();
696
+ if (key === void 0 || key.t !== "id" && key.t !== "str") throw new SyntaxError("expected key");
697
+ this.position += 1;
698
+ this.expect("p", ":");
699
+ this.expression(depth + 1);
700
+ if (!this.is("p", "}")) this.expect("p", ",");
701
+ }
702
+ return UNKNOWN;
703
+ }
704
+ throw new SyntaxError("unexpected token");
705
+ }
706
+ };
707
+ function attribute(target, name) {
708
+ if (target.k !== "var" || name === null) return UNKNOWN;
709
+ if (target.name === "principal" && (name === "category" || name === "name")) return { k: name };
710
+ return target.name === "resource" && name === "path" ? { k: "path" } : UNKNOWN;
711
+ }
712
+ const parseExpression = (text) => new Parser(tokenize(text)).parseAll();
713
+ const triOf = (value) => value ? "yes" : "no";
714
+ const invert = (value) => value === "maybe" ? "maybe" : value === "yes" ? "no" : "yes";
715
+ const constantSets = /* @__PURE__ */ new WeakMap();
716
+ function valueOf(expr, facts, read) {
717
+ switch (expr.k) {
718
+ case "str": {
719
+ const decoded = decodeCedarString(expr.raw);
720
+ return decoded === null ? { k: "unknown" } : {
721
+ k: "str",
722
+ v: decoded
723
+ };
724
+ }
725
+ case "category": return {
726
+ k: "str",
727
+ v: read
728
+ };
729
+ case "path": return facts.path === void 0 ? { k: "unknown" } : {
730
+ k: "str",
731
+ v: facts.path
732
+ };
733
+ case "name": return { k: "name" };
734
+ case "set": {
735
+ const known = constantSets.get(expr);
736
+ if (known !== void 0) return known;
737
+ const items = expr.items.map((item) => valueOf(item, facts, read));
738
+ const value = items.some((item) => item.k === "set") ? { k: "unknown" } : {
739
+ k: "set",
740
+ items
741
+ };
742
+ if (expr.items.every((item) => item.k === "str")) constantSets.set(expr, value);
743
+ return value;
744
+ }
745
+ case "if": {
746
+ const cond = evaluateExpression(expr.cond, facts);
747
+ if (cond === "maybe") return { k: "unknown" };
748
+ return valueOf(cond === "yes" ? expr.then : expr.otherwise, facts, read);
749
+ }
750
+ case "lit":
751
+ case "and":
752
+ case "or":
753
+ case "not":
754
+ case "cmp":
755
+ case "like":
756
+ case "call": return {
757
+ k: "tri",
758
+ v: evaluateExpression(expr, facts)
759
+ };
760
+ default: return { k: "unknown" };
761
+ }
762
+ }
763
+ function sameValue(left, right) {
764
+ if (left.k === "unknown" || right.k === "unknown") return "maybe";
765
+ if (left.k === "name" || right.k === "name") {
766
+ const other = left.k === "name" ? right : left;
767
+ if (other.k !== "str") return other.k === "name" ? "maybe" : "no";
768
+ return HUMAN_NAMES.includes(other.v.trim().toLowerCase()) ? "maybe" : "no";
769
+ }
770
+ if (left.k === "tri" && right.k === "tri") return left.v === "maybe" || right.v === "maybe" ? "maybe" : triOf(left.v === right.v);
771
+ if (left.k === "tri" || right.k === "tri") return "no";
772
+ if (left.k === "str" && right.k === "str") return triOf(left.v === right.v);
773
+ if (left.k === "set" && right.k === "set") {
774
+ const [leftIndex, rightIndex] = [indexItems(left.items), indexItems(right.items)];
775
+ if (leftIndex.pure && rightIndex.pure) return triOf(leftIndex.strings.size === rightIndex.strings.size && holdsAll(leftIndex, rightIndex));
776
+ const covers = (from, into) => {
777
+ const index = indexItems(into);
778
+ return combine(from.map((item) => member(item, index)), "and");
779
+ };
780
+ return combine([covers(left.items, right.items), covers(right.items, left.items)], "and");
781
+ }
782
+ return "no";
783
+ }
784
+ function holdsAll(index, other) {
785
+ for (const value of other.strings) if (!index.strings.has(value)) return false;
786
+ return true;
787
+ }
788
+ function shareAny(left, right) {
789
+ const [small, large] = left.strings.size <= right.strings.size ? [left, right] : [right, left];
790
+ for (const value of small.strings) if (large.strings.has(value)) return true;
791
+ return false;
792
+ }
793
+ const indexes = /* @__PURE__ */ new WeakMap();
794
+ function indexItems(items) {
795
+ const known = indexes.get(items);
796
+ if (known !== void 0) return known;
797
+ const index = buildIndex(items);
798
+ indexes.set(items, index);
799
+ return index;
800
+ }
801
+ function buildIndex(items) {
802
+ const strings = /* @__PURE__ */ new Set();
803
+ const representatives = /* @__PURE__ */ new Map();
804
+ for (const item of items) if (item.k === "str") {
805
+ strings.add(item.v);
806
+ representatives.set(HUMAN_NAMES.includes(item.v.trim().toLowerCase()) ? "human" : "str", item);
807
+ } else representatives.set(item.k === "tri" ? `tri:${item.v}` : item.k, item);
808
+ return {
809
+ strings,
810
+ representatives: [...representatives.values()],
811
+ pure: items.every((item) => item.k === "str")
812
+ };
813
+ }
814
+ function member(item, index) {
815
+ if (item.k === "str" && index.strings.has(item.v)) return "yes";
816
+ return combine(index.representatives.map((candidate) => sameValue(item, candidate)), "or");
817
+ }
818
+ function combine(results, op) {
819
+ const decisive = op === "and" ? "no" : "yes";
820
+ if (results.includes(decisive)) return decisive;
821
+ return results.includes("maybe") ? "maybe" : invert(decisive);
822
+ }
823
+ function setCall(method, receiver, args) {
824
+ if (receiver.k !== "set") return "maybe";
825
+ if (method === "isEmpty" && args.length === 0) return triOf(receiver.items.length === 0);
826
+ const [argument] = args;
827
+ if (args.length !== 1) return "maybe";
828
+ const index = indexItems(receiver.items);
829
+ if (method === "contains") return member(argument, index);
830
+ if (argument.k !== "set") return "maybe";
831
+ if (method === "containsAny" || method === "containsAll") {
832
+ const other = indexItems(argument.items);
833
+ if (index.pure && other.pure) return triOf(method === "containsAny" ? shareAny(index, other) : other.strings.size <= index.strings.size && holdsAll(index, other));
834
+ return combine(argument.items.map((item) => member(item, index)), method === "containsAny" ? "or" : "and");
835
+ }
836
+ return "maybe";
837
+ }
838
+ const leaves = (expr) => expr.k === "set" ? expr.items.flatMap(leaves) : expr.k === "if" ? [...leaves(expr.then), ...leaves(expr.otherwise)] : [expr];
839
+ function strings(exprs) {
840
+ const found = [];
841
+ for (const part of exprs.flatMap(leaves)) {
842
+ const decoded = part.k === "str" ? decodeCedarString(part.raw) : null;
843
+ if (decoded !== null) found.push(decoded);
844
+ }
845
+ return found;
846
+ }
847
+ const readsCategory = (exprs) => exprs.flatMap(leaves).some((part) => part.k === "category");
848
+ const spelledAtoms = /* @__PURE__ */ new WeakMap();
849
+ function spelledBy(expr) {
850
+ let spelled = spelledAtoms.get(expr);
851
+ if (spelled === void 0) {
852
+ const sides = expr.k === "cmp" ? [expr.left, expr.right] : [expr.receiver, ...expr.args];
853
+ spelled = {
854
+ reads: readsCategory(sides),
855
+ names: new Set(strings(sides))
856
+ };
857
+ spelledAtoms.set(expr, spelled);
858
+ }
859
+ return spelled;
860
+ }
861
+ function mentions(expr, name) {
862
+ if (name === void 0) return false;
863
+ if (expr.k === "like") {
864
+ const segments = cedarLikeSegments(expr.pattern);
865
+ return readsCategory([expr.operand]) && segments.some((segment) => segment.includes(name)) && globMatches(segments, name);
866
+ }
867
+ const { reads, names } = spelledBy(expr);
868
+ return reads && names.has(name);
869
+ }
870
+ const readOf = (expr, facts) => mentions(expr, facts.unnamed) ? UNNAMED_CATEGORY : facts.category;
871
+ function evaluateExpression(expr, facts) {
872
+ switch (expr.k) {
873
+ case "lit": return triOf(expr.v);
874
+ case "not": return invert(evaluateExpression(expr.operand, facts));
875
+ case "and":
876
+ case "or": return combine(expr.terms.map((term) => evaluateExpression(term, facts)), expr.k);
877
+ case "if": {
878
+ const cond = evaluateExpression(expr.cond, facts);
879
+ if (cond !== "maybe") return evaluateExpression(cond === "yes" ? expr.then : expr.otherwise, facts);
880
+ const [then, otherwise] = [expr.then, expr.otherwise].map((branch) => evaluateExpression(branch, facts));
881
+ return then === otherwise ? then : "maybe";
882
+ }
883
+ case "cmp": {
884
+ const read = readOf(expr, facts);
885
+ const same = sameValue(valueOf(expr.left, facts, read), valueOf(expr.right, facts, read));
886
+ return expr.equals ? same : invert(same);
887
+ }
888
+ case "like": {
889
+ const subject = valueOf(expr.operand, facts, readOf(expr, facts));
890
+ if (UNSUPPORTED_PATTERN_ESCAPE.test(expr.pattern)) return "maybe";
891
+ const segments = cedarLikeSegments(expr.pattern);
892
+ if (subject.k === "name") return HUMAN_NAMES.some((candidate) => globMatches(segments, candidate)) ? "maybe" : "no";
893
+ if (subject.k !== "str") return "maybe";
894
+ return triOf(globMatches(segments, subject.v));
895
+ }
896
+ case "call": {
897
+ const read = readOf(expr, facts);
898
+ return setCall(expr.method, valueOf(expr.receiver, facts, read), expr.args.map((arg) => valueOf(arg, facts, read)));
899
+ }
900
+ default: return "maybe";
901
+ }
902
+ }
903
+
904
+ //#endregion
905
+ //#region src/policy/cedar-principal-scope.ts
906
+ const PROBE_CLASSES = ["human", NO_EVIDENCE_CATEGORY];
907
+ const ANONYMOUS_PRINCIPAL_ID = "anonymous";
908
+ const S = CEDAR_SPACE_CLASS;
909
+ const HEAD = new RegExp(`\\b(forbid|permit)${S}*\\(`, "g");
910
+ const isAnnotationName = (code, index) => {
911
+ let position = index - 1;
912
+ while (position >= 0 && isCedarSpace(code[position])) position -= 1;
913
+ return code[position] === "@";
914
+ };
915
+ const skipSpace = (text, from) => {
916
+ let index = from;
917
+ while (index < text.length && isCedarSpace(text[index])) index += 1;
918
+ return index;
919
+ };
920
+ const conditionAt = (text, from) => {
921
+ const keywordStart = skipSpace(text, from);
922
+ const kind = text.startsWith("when", keywordStart) ? "when" : text.startsWith("unless", keywordStart) ? "unless" : null;
923
+ if (kind === null) return null;
924
+ const braceOpen = skipSpace(text, keywordStart + kind.length);
925
+ return text[braceOpen] === "{" ? {
926
+ kind,
927
+ braceOpen
928
+ } : null;
929
+ };
930
+ function matching(code, openIndex, open, close) {
931
+ let depth = 0;
932
+ for (let i = openIndex; i < code.length; i++) if (code[i] === open) depth++;
933
+ else if (code[i] === close) {
934
+ depth--;
935
+ if (depth === 0) return i;
936
+ }
937
+ return -1;
938
+ }
939
+ function parseCedarStatements(cedar) {
940
+ const { visible, code } = maskCedar(cedar);
941
+ const statements = [];
942
+ const heads = new RegExp(HEAD.source, "g");
943
+ let previousEnd = 0;
944
+ let match = heads.exec(code);
945
+ while (match !== null) {
946
+ if (isAnnotationName(code, match.index)) {
947
+ match = heads.exec(code);
948
+ continue;
949
+ }
950
+ const open = match.index + match[0].length - 1;
951
+ const scopeEnd = matching(code, open, "(", ")");
952
+ if (scopeEnd < 0) break;
953
+ const conditions = [];
954
+ let position = scopeEnd + 1;
955
+ for (;;) {
956
+ const condition = conditionAt(code, position);
957
+ if (condition === null) break;
958
+ const braceClose = matching(code, condition.braceOpen, "{", "}");
959
+ if (braceClose < 0) {
960
+ position = code.length;
961
+ break;
962
+ }
963
+ conditions.push({
964
+ kind: condition.kind,
965
+ body: visible.slice(condition.braceOpen + 1, braceClose)
966
+ });
967
+ position = braceClose + 1;
968
+ }
969
+ const terminatorAt = skipSpace(code, position);
970
+ const end = code[terminatorAt] === ";" ? terminatorAt + 1 : position;
971
+ statements.push({
972
+ effect: match[1],
973
+ blockStart: Math.min(skipSpace(cedar, previousEnd), match.index),
974
+ start: match.index,
975
+ end,
976
+ text: visible.slice(match.index, end),
977
+ scope: visible.slice(open + 1, scopeEnd),
978
+ conditions,
979
+ annotations: visible.slice(previousEnd, match.index)
980
+ });
981
+ previousEnd = end;
982
+ heads.lastIndex = end;
983
+ match = heads.exec(code);
984
+ }
985
+ return statements;
986
+ }
987
+ const TRUE_BODY = new RegExp(`^${S}*true${S}*$`);
988
+ const PRINCIPAL_EQUALS = new RegExp(`\\bprincipal${S}*==`);
989
+ const ENTITY_ID = new RegExp(`::${S}*"((?:\\\\.|[^"\\\\])*)"`, "g");
990
+ const IS_TYPE = new RegExp(`\\bis${S}+([\\w:]+)`);
991
+ const ID_ANNOTATION = new RegExp(`@id\\(${S}*"((?:\\\\.|[^"\\\\])*)"${S}*\\)`, "g");
992
+ function principalScope(scope) {
993
+ const { visible, code } = maskCedar(scope);
994
+ let depth = 0;
995
+ let end = code.length;
996
+ for (let i = 0; i < code.length; i++) {
997
+ const char = code[i];
998
+ if (char === "(" || char === "[" || char === "{") depth++;
999
+ else if (char === ")" || char === "]" || char === "}") depth--;
1000
+ else if (char === "," && depth === 0) {
1001
+ end = i;
1002
+ break;
1003
+ }
1004
+ }
1005
+ const text = visible.slice(0, end);
1006
+ const masked = code.slice(0, end);
1007
+ 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";
1008
+ const isType = IS_TYPE.exec(masked);
1009
+ if (isType) return isType[1].split("::").pop() === "Agent" ? "maybe" : "no";
1010
+ return "yes";
1011
+ }
1012
+ const prepared = /* @__PURE__ */ new WeakMap();
1013
+ function parsedCondition(body) {
1014
+ try {
1015
+ return parseExpression(body);
1016
+ } catch {
1017
+ return null;
1018
+ }
1019
+ }
1020
+ function evaluableOf(statement) {
1021
+ return {
1022
+ scope: principalScope(statement.scope),
1023
+ conditions: statement.conditions.map(({ kind, body }) => ({
1024
+ kind,
1025
+ node: parsedCondition(body)
1026
+ }))
1027
+ };
1028
+ }
1029
+ function preparedOf(statement) {
1030
+ let entry = prepared.get(statement);
1031
+ if (entry === void 0) {
1032
+ const named = namesNoEvidence(statement.text);
1033
+ entry = {
1034
+ namesNoEvidence: named,
1035
+ substituted: !named && withNoEvidenceExclusion(statement.text) !== statement.text,
1036
+ evaluable: evaluableOf(statement)
1037
+ };
1038
+ prepared.set(statement, entry);
1039
+ }
1040
+ return entry;
1041
+ }
1042
+ function statementApplies(statement, facts) {
1043
+ const { substituted, evaluable } = preparedOf(statement);
1044
+ const read = facts.category === "no_evidence" && substituted ? {
1045
+ ...facts,
1046
+ category: "human"
1047
+ } : facts;
1048
+ const effective = {
1049
+ category: read.category,
1050
+ path: read.path,
1051
+ unnamed: facts.discountNaming ? read.category : void 0
1052
+ };
1053
+ if (evaluable.scope === "no") return false;
1054
+ for (const { kind, node } of evaluable.conditions) {
1055
+ const result = node === null ? "maybe" : evaluateExpression(node, effective);
1056
+ if (kind === "when" && result === "no") return false;
1057
+ if (kind === "unless" && result === "yes") return false;
1058
+ }
1059
+ return true;
1060
+ }
1061
+ function reachesClassOnlyByNaming(statement, probe, path) {
1062
+ return statementApplies(statement, {
1063
+ category: probe,
1064
+ path
1065
+ }) && !statementApplies(statement, {
1066
+ category: probe,
1067
+ path,
1068
+ discountNaming: true
1069
+ });
1070
+ }
1071
+ function statementId(statement) {
1072
+ return Array.from(statement.annotations.matchAll(ID_ANNOTATION), (m) => unescapeCedarString(m[1])).at(-1);
1073
+ }
1074
+ let memoText;
1075
+ let memoParsed = {
1076
+ text: "",
1077
+ statements: []
1078
+ };
1079
+ function parsedOf(cedar) {
1080
+ if (memoText !== cedar) {
1081
+ const text = withoutNoEvidenceExclusion(cedar);
1082
+ memoParsed = {
1083
+ text,
1084
+ statements: parseCedarStatements(text)
1085
+ };
1086
+ memoText = cedar;
1087
+ }
1088
+ return memoParsed;
1089
+ }
1090
+ function analyzePolicyScope(cedar) {
1091
+ const { text, statements } = parsedOf(cedar);
1092
+ return {
1093
+ unnarrowedDeny(path) {
1094
+ const found = [];
1095
+ let line = 1;
1096
+ let counted = 0;
1097
+ for (const statement of statements) {
1098
+ if (statement.effect !== "forbid") continue;
1099
+ const classes = PROBE_CLASSES.filter((probe) => statementApplies(statement, {
1100
+ category: probe,
1101
+ path
1102
+ }) && !reachesClassOnlyByNaming(statement, probe, path));
1103
+ if (classes.length > 0) {
1104
+ for (; counted < statement.blockStart; counted++) if (text.charCodeAt(counted) === 10) line++;
1105
+ found.push({
1106
+ statement,
1107
+ classes,
1108
+ line
1109
+ });
1110
+ }
1111
+ }
1112
+ return found;
1113
+ },
1114
+ denyNamingClass(path, probe) {
1115
+ return statements.filter((statement) => statement.effect === "forbid" && (probe !== "no_evidence" || preparedOf(statement).namesNoEvidence) && reachesClassOnlyByNaming(statement, probe, path));
1116
+ },
1117
+ lacksBaselinePermit() {
1118
+ return statements.length > 0 && !statements.some(isBaselinePermit);
1119
+ }
1120
+ };
1121
+ }
1122
+ const unnarrowedDenyStatements = (cedar, path) => analyzePolicyScope(cedar).unnarrowedDeny(path);
1123
+ const lacksBaselinePermit = (cedar) => analyzePolicyScope(cedar).lacksBaselinePermit();
1124
+ function isBaselinePermit(statement) {
1125
+ return statement.effect === "permit" && principalScope(statement.scope) === "yes" && statement.conditions.every((condition) => condition.kind === "when" && TRUE_BODY.test(condition.body));
1126
+ }
1127
+
1128
+ //#endregion
1129
+ //#region src/policy/cedar-rule-match.ts
1130
+ /**
1131
+ * Shared best-effort matchers for reading a composed Cedar policy's per-rule
1132
+ * annotations (`@scopes`, `@approvers`, …) WITHOUT a Cedar AST. Both
1133
+ * `requiredScopesForRequest` (consent scopes) and `approvalQuorumForRequest`
1134
+ * (step-up quorum) narrow a rule's annotation to a request the same way the
1135
+ * compose engine's own `parseExistingCedar` does: blocks split on blank lines,
1136
+ * a rule contributes only when EVERY request fact it constrains matches.
1137
+ *
1138
+ * A fact is matched against the SAME projection the gateway/edge feeds the
1139
+ * engine (`name = agentName`, `category = scraper|detectionClass`), so the
1140
+ * narrowing mirrors the engine's own evaluation. An UNKNOWN fact never narrows.
1141
+ */
1142
+ const UNLESS_BRACE = new RegExp(`unless${CEDAR_SPACE_CLASS}*\\{`);
1143
+ const FORBID_HEAD = new RegExp(`\\bforbid${CEDAR_SPACE_CLASS}*\\(`, "g");
1144
+ /**
1145
+ * A block applies when its path AND principal conditions all match the KNOWN
1146
+ * request facts. An unknown fact never narrows (so the no-`request` case unions
1147
+ * every matching rule's annotation).
1148
+ */
1149
+ function blockApplies(block, request) {
1150
+ if (request?.path !== void 0 && !blockMatchesPath(block, request.path)) return false;
1151
+ if (request?.name !== void 0 && !blockMatchesEquality(block, "principal.name", request.name)) return false;
1152
+ if (request?.category !== void 0) {
1153
+ if (!blockMatchesEquality(block, "principal.category", categoryRead(block, request.category))) return false;
1154
+ }
1155
+ return true;
1156
+ }
1157
+ function categoryRead(block, category) {
1158
+ if (category !== "no_evidence") return category;
1159
+ const original = withoutNoEvidenceExclusion(block);
1160
+ return withNoEvidenceExclusion(original) !== original ? "human" : category;
1161
+ }
1162
+ /** The `resource.path` literals appearing anywhere in `text` (no `when`/
1163
+ * `unless` scoping — callers that care about scope use `splitWhenUnless`
1164
+ * first). Shared regex extraction for `pathLiteralsInBlock` and the
1165
+ * scope-aware helpers below. */
1166
+ function pathLiteralsInText(text) {
1167
+ return Array.from(text.matchAll(cedarQuotedValueRegExp("resource\\.path (?:like|==) ", "g")), (m) => unescapeCedarString(m[1]));
1168
+ }
1169
+ /**
1170
+ * The `resource.path` literals a block MENTIONS anywhere — `when` or
1171
+ * `unless` alike (empty = the block never mentions a path). Used for
1172
+ * enumeration (which concrete paths does this bundle reference at all),
1173
+ * NOT for "does this block's condition match path" — that's
1174
+ * `blockMatchesPath`, which is `unless`-aware. Mixing the two up is exactly
1175
+ * the bug Bugbot caught (2026-09-10): a literal that appears ONLY inside
1176
+ * `unless { … }` names a path this block does NOT apply to, not one it
1177
+ * targets.
1178
+ */
1179
+ function pathLiteralsInBlock(block) {
1180
+ return pathLiteralsInText(block);
1181
+ }
1182
+ /**
1183
+ * Split `block` into its `when`-scoped text and its `unless`-scoped inner
1184
+ * text, mirroring the compose engine's own excision order
1185
+ * (`apps/web/lib/compose/cedar.ts`'s `unless` handling): `unless { … }` is
1186
+ * located first and excised, so its own literals never leak into what
1187
+ * counts as the block's `when` (narrowing) scope.
1188
+ *
1189
+ * CodeQL js/polynomial-redos: a single `/unless\s*\{([\s\S]*?)\}\s*;?/`
1190
+ * regex is quadratic on a policy blob containing many "unless{"
1191
+ * substrings with no closing brace (composed policy text is untrusted,
1192
+ * customer-authored input evaluated on the request hot path) — an
1193
+ * unanchored match retries the unbounded `[\s\S]*?` scan-to-end at every
1194
+ * failed start position. `search()` for the fixed-length "unless\s*{"
1195
+ * prefix has no such ambiguity (each position fails fast), and the
1196
+ * closing brace is then found with a single linear `indexOf`, so the
1197
+ * whole split stays O(n) regardless of how many false "unless{" starts
1198
+ * the text contains.
1199
+ */
1200
+ function splitWhenUnless(block) {
1201
+ const unlessIndex = block.search(UNLESS_BRACE);
1202
+ if (unlessIndex === -1) return {
1203
+ whenText: block,
1204
+ unlessText: ""
1205
+ };
1206
+ const openBraceIndex = block.indexOf("{", unlessIndex);
1207
+ const closeBraceIndex = block.indexOf("}", openBraceIndex + 1);
1208
+ if (closeBraceIndex === -1) return {
1209
+ whenText: block,
1210
+ unlessText: ""
1211
+ };
1212
+ return {
1213
+ whenText: block.slice(0, unlessIndex),
1214
+ unlessText: block.slice(openBraceIndex + 1, closeBraceIndex)
1215
+ };
1216
+ }
1217
+ /**
1218
+ * A block applies to `path` when: no `unless` literal excludes it, AND
1219
+ * either the `when` scope has no path constraint at all (unconstrained →
1220
+ * matches every path except what `unless` just excluded), or one of the
1221
+ * `when` scope's path literals matches (exact, or a `*`-prefix glob).
1222
+ *
1223
+ * Bugbot (2026-09-10): the previous version read path literals from the
1224
+ * WHOLE block regardless of `when` vs `unless`, so a site-wide forbid whose
1225
+ * only path mention was an `unless { resource.path == "/checkout" }`
1226
+ * exemption got scored as "targets only /checkout" — backwards. It applies
1227
+ * to every path EXCEPT the excepted one, not ONLY the excepted one.
1228
+ */
1229
+ function blockMatchesPath(block, path) {
1230
+ const { whenText, unlessText } = splitWhenUnless(block);
1231
+ if (pathLiteralsInText(unlessText).some((literal) => pathLiteralMatches(literal, path))) return false;
1232
+ const whenLiterals = pathLiteralsInText(whenText);
1233
+ if (whenLiterals.length === 0) return true;
1234
+ return whenLiterals.some((literal) => pathLiteralMatches(literal, path));
1235
+ }
1236
+ /** Escape every regex metacharacter in `s` (so it matches literally). */
1237
+ function escapeRegExp(s) {
1238
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1239
+ }
1240
+ /**
1241
+ * Split a composed Cedar bundle into per-rule blocks (blank-line separated),
1242
+ * trimmed and with empties dropped. Mirrors the compose engine's own block
1243
+ * split (`apps/web/lib/compose/cedar.ts` `parseCedarBlocks`).
1244
+ */
1245
+ function splitCedarBlocks(cedar) {
1246
+ return cedar.split(/\n\s*\n/).map((b) => b.trim()).filter((b) => b.length > 0);
1247
+ }
1248
+ /**
1249
+ * The set of values a block positively constrains `attr` to via `== ` literals.
1250
+ * Empty = the block places no `==` constraint on `attr` (unconstrained).
1251
+ */
1252
+ function blockEqualityLiterals(block, attr) {
1253
+ const a = escapeRegExp(attr);
1254
+ return Array.from(block.matchAll(cedarQuotedValueRegExp(`${a} == `, "g")), (m) => unescapeCedarString(m[1]));
1255
+ }
1256
+ /**
1257
+ * The set of values a block EXCLUDES `attr` from via `!= ` literals.
1258
+ * Empty = the block places no `!=` constraint on `attr`.
1259
+ */
1260
+ function blockExclusionLiterals(block, attr) {
1261
+ const a = escapeRegExp(attr);
1262
+ return Array.from(block.matchAll(cedarQuotedValueRegExp(`${a} != `, "g")), (m) => unescapeCedarString(m[1]));
1263
+ }
1264
+ /** A block applies to `value` when it is NOT excluded by a `!=` literal AND
1265
+ * (it declares no `==` literal — unconstrained → applies to all — or `value` is
1266
+ * one of them; compose emits an OR-disjunction for a name set). Without the `!=`
1267
+ * arm a rule that challenges everyone EXCEPT X (`principal.name != "X"`) would
1268
+ * over-advertise its annotation to X — a broader grant than the rule meant. */
1269
+ function blockMatchesEquality(block, attr, value) {
1270
+ const eq = blockEqualityLiterals(block, attr);
1271
+ if (blockExclusionLiterals(block, attr).includes(value)) return false;
1272
+ if (eq.length > 0) return eq.includes(value);
1273
+ return true;
1274
+ }
1275
+ /**
1276
+ * Match a `resource.path` literal against the request path with CEDAR `like`
1277
+ * semantics — NOT the package's `matchPath`. Cedar `*` matches any sequence
1278
+ * INCLUDING `/` (regex `.*`), whereas `matchPath` treats a single `*` as
1279
+ * `[^/]*` (no slash); using it here would disagree with what the engine
1280
+ * actually matched. A `==`/non-wildcard literal is an exact match; a `like`
1281
+ * literal maps each `*` (and `**`) to `.*`, anchored.
1282
+ */
1283
+ function pathLiteralMatches(literal, path) {
1284
+ return globMatches(literal.split("*"), path);
1285
+ }
1286
+ /**
1287
+ * True when the block contains a Cedar `forbid` statement (a deny rule). A bare
1288
+ * `forbid` defaults to BLOCK; a `@verdict(...)` annotation refines the kind.
1289
+ */
1290
+ function isForbidBlock(block) {
1291
+ const { code } = maskCedar(block);
1292
+ return Array.from(code.matchAll(FORBID_HEAD)).some(({ index }) => !isAnnotationName(code, index));
1293
+ }
1294
+ function isUnnarrowedDenyBlock(block) {
1295
+ return unnarrowedDenyStatements(block).some(({ classes }) => classes.includes("human"));
1296
+ }
1297
+ function analyzePolicySource(cedar) {
1298
+ const scope = analyzePolicyScope(cedar);
1299
+ const analysis = {
1300
+ unnarrowedDenyFor: (path, probe) => scope.unnarrowedDeny(path).some(({ classes }) => classes.includes(probe)),
1301
+ explicitDenyFor: (path, probe) => scope.denyNamingClass(path, probe).length > 0,
1302
+ humanHazard: (path) => analysis.unnarrowedDenyFor(path, "human"),
1303
+ noEvidenceHazard: (path) => analysis.unnarrowedDenyFor(path, "no_evidence") && !analysis.noEvidenceNamed(path),
1304
+ noEvidenceNamed: (path) => analysis.explicitDenyFor(path, NO_EVIDENCE_CATEGORY)
1305
+ };
1306
+ return analysis;
1307
+ }
1308
+ function pathHasUnnarrowedDenyRuleFor(cedar, path, probe) {
1309
+ return analyzePolicySource(cedar).unnarrowedDenyFor(path, probe);
1310
+ }
1311
+ function pathHasExplicitDenyRuleFor(cedar, path, probe) {
1312
+ return analyzePolicySource(cedar).explicitDenyFor(path, probe);
1313
+ }
1314
+ function pathHasUnnarrowedDenyRule(cedar, path) {
1315
+ return analyzePolicySource(cedar).humanHazard(path);
1316
+ }
1317
+
1318
+ //#endregion
1319
+ //#region src/policy/byte-bounded-memo.ts
1320
+ var ByteBoundedMemo = class {
1321
+ budgetBytes;
1322
+ entries = /* @__PURE__ */ new Map();
1323
+ used = 0;
1324
+ constructor(budgetBytes) {
1325
+ this.budgetBytes = budgetBytes;
1326
+ }
1327
+ remember(key, bytes, make) {
1328
+ const hit = this.entries.get(key);
1329
+ if (hit !== void 0) {
1330
+ this.entries.delete(key);
1331
+ this.entries.set(key, hit);
1332
+ return hit.value;
1333
+ }
1334
+ const value = make();
1335
+ if (bytes > this.budgetBytes) return value;
1336
+ this.entries.set(key, {
1337
+ value,
1338
+ bytes
1339
+ });
1340
+ this.used += bytes;
1341
+ for (const [oldest, entry] of this.entries) {
1342
+ if (this.used <= this.budgetBytes) break;
1343
+ this.entries.delete(oldest);
1344
+ this.used -= entry.bytes;
1345
+ }
1346
+ return value;
1347
+ }
1348
+ };
1349
+
1350
+ //#endregion
1351
+ //#region src/policy/unsubstituted-source.ts
1352
+ const BUDGET_BYTES = 4194304;
1353
+ const BYTES_PER_CHARACTER = 4;
1354
+ const memo = new ByteBoundedMemo(BUDGET_BYTES);
1355
+ const unsubstitutedSource = (source) => memo.remember(source, source.length * BYTES_PER_CHARACTER, () => withoutNoEvidenceExclusion(source));
1356
+
1357
+ //#endregion
1358
+ //#region src/policy/required-scopes.ts
1359
+ /**
1360
+ * Consent scopes a composed Cedar policy REQUIRES for a request — the
1361
+ * `@scopes(...)` annotations the compose engine writes on CHALLENGE-verdict
1362
+ * rules (alongside `unless { context.granted_scopes.contains("S") }`).
1363
+ *
1364
+ * WHY: when a scope-gated rule challenges a request, the step-up must request
1365
+ * EXACTLY the scopes the policy demands, so the consent flow mints a delegation
1366
+ * carrying them (and the agent's retry then satisfies the carve-out). The
1367
+ * policy is the source of truth for "what this route requires", so reading its
1368
+ * `@scopes` is reading the SSOT — not re-deriving an engine-computed value.
1369
+ *
1370
+ * Best-effort TEXT parse (no Cedar AST), mirroring the compose engine's own
1371
+ * `parseExistingCedar`: blocks are split on blank lines. A CHALLENGE block
1372
+ * contributes its scopes only when EVERY request fact it constrains matches —
1373
+ * `resource.path`, `principal.name`, and `principal.category` — so on a shared
1374
+ * path the scopes of ANOTHER agent's CHALLENGE rule are not advertised (the
1375
+ * engine challenged on the rule whose `when` matched, not merely the path).
1376
+ *
1377
+ * A fact is matched against the SAME projection the gateway feeds the engine
1378
+ * (`name = detection.agentName`, `category = scraper|detectionClass`), so the
1379
+ * narrowing mirrors the engine's own evaluation. An UNKNOWN fact never narrows:
1380
+ * with no `request` (the consent allow-list case) this returns the union of
1381
+ * every CHALLENGE rule's scopes — exactly what consent must be able to grant.
1382
+ */
1383
+ function requiredScopesForRequest(policySource, request) {
1384
+ if (!policySource || !policySource.trim()) return [];
1385
+ const out = /* @__PURE__ */ new Set();
1386
+ for (const block of unsubstitutedSource(policySource).split(/\n\s*\n/)) {
1387
+ if (!/@verdict\("CHALLENGE"\)/.test(block)) continue;
1388
+ const scopesMatch = block.match(cedarQuotedValueRegExp("@scopes\\("));
1389
+ if (!scopesMatch) continue;
1390
+ const scopes = scopesMatch[1].split(/\s+/).filter(Boolean).map(unescapeCedarString);
1391
+ if (scopes.length === 0) continue;
1392
+ if (!blockApplies(block, request)) continue;
1393
+ for (const scope of scopes) out.add(scope);
1394
+ }
1395
+ return [...out];
1396
+ }
1397
+
1398
+ //#endregion
1399
+ //#region src/policy/decision-policy-id.ts
1400
+ function decisionPolicyId(decision) {
1401
+ switch (decision.kind) {
1402
+ case "Permit": return decision.policyId;
1403
+ case "Block": return decision.reason?.kind === "PolicyDenied" ? decision.reason.policyId : void 0;
1404
+ case "Challenge": return decision.params?.policyId;
1405
+ case "Redirect": return decision.target?.policyId;
1406
+ case "Instruct": return decision.payload?.policyId;
1407
+ default: return;
1408
+ }
1409
+ }
1410
+
1411
+ //#endregion
1412
+ //#region src/policy/approval-quorum.ts
1413
+ /**
1414
+ * The step-up APPROVAL QUORUM a composed Cedar policy requires for a request —
1415
+ * the `@approvers(...)` (+ optional `@quorum("N")`) annotations on a
1416
+ * CHALLENGE-verdict rule.
1417
+ *
1418
+ * WHY (ADR D7 — distinct verdict): the engine emits a single `Challenge` for
1419
+ * both consent (`@scopes`) and human-approval step-up (`@approvers`). They are
1420
+ * DIFFERENT security flows and must not collide — a consent challenge mints a
1421
+ * delegation; an approval-quorum challenge demands N-of-M humans cryptographically
1422
+ * sign. This classifier is the seam that tells them apart from the policy text:
1423
+ * - a CHALLENGE rule carrying `@approvers` → an approval quorum (this returns it)
1424
+ * - a CHALLENGE rule with only `@scopes` (or neither) → consent (returns null)
1425
+ *
1426
+ * It mirrors {@link requiredScopesForRequest}: the SAME best-effort block parse
1427
+ * and the SAME request narrowing (shared {@link blockApplies}), so the rule it
1428
+ * reads the quorum off is the rule the engine actually challenged on — not merely
1429
+ * one that shares a path. Reading the annotation is reading the SSOT (the policy
1430
+ * is the source of truth for "what this action requires"), not re-deriving it.
1431
+ *
1432
+ * The engine carries no rule id on its Challenge, so the classifier re-matches by
1433
+ * request facts and is FAIL-CLOSED on ambiguity:
1434
+ * - if a CONSENT-only CHALLENGE rule ALSO applies, it returns null — the engine
1435
+ * may have challenged on THAT, and reading approval off a different rule would
1436
+ * conflate the two flows (ADR D7)
1437
+ * - if two applying approval rules disagree on {n, approvers}, it returns null —
1438
+ * enforcing the wrong approver roster is a worse failure than a clean deny
1439
+ * Each caller feeds it the SAME facts its engine evaluated, so it narrows to the
1440
+ * rule the engine could have fired on. The EDGE worker sets resource.path +
1441
+ * principal.name and narrows on them; the Fly gateway sets NEITHER (it populates
1442
+ * category + the resource entity, leaving resource.path=="" and principal.name=""),
1443
+ * so it passes those as "" — path/name-scoped rules don't fire there, exactly as
1444
+ * the engine sees it, and a same-scope tie falls to the fail-closed guard above.
1445
+ */
1446
+ function approvalQuorumForRequest(policySource, request) {
1447
+ if (!policySource || !policySource.trim()) return null;
1448
+ let chosen = null;
1449
+ for (const block of unsubstitutedSource(policySource).split(/\n\s*\n/)) {
1450
+ if (!/@verdict\("CHALLENGE"\)/.test(block)) continue;
1451
+ if (!blockApplies(block, request)) continue;
1452
+ const approvers = parseApprovers(block);
1453
+ if (!approvers) return null;
1454
+ const candidate = {
1455
+ n: parseQuorumN(block),
1456
+ approvers
1457
+ };
1458
+ if (chosen && !sameQuorum(chosen, candidate)) return null;
1459
+ chosen = candidate;
1460
+ }
1461
+ return chosen;
1462
+ }
1463
+ /** The DIDs of an `@approvers("did … did")` annotation, or null when the rule
1464
+ * carries none (a consent challenge) or an empty/whitespace list (no real gate). */
1465
+ function parseApprovers(block) {
1466
+ const m = block.match(/@approvers\("([^"]*)"\)/);
1467
+ if (!m) return null;
1468
+ const approvers = m[1].split(/\s+/).filter(Boolean);
1469
+ return approvers.length > 0 ? approvers : null;
1470
+ }
1471
+ /** Two quorums match iff same n and same ordered approver list. */
1472
+ function sameQuorum(a, b) {
1473
+ return a.n === b.n && a.approvers.length === b.approvers.length && a.approvers.every((did, i) => did === b.approvers[i]);
1474
+ }
1475
+ /**
1476
+ * The `@quorum("N")` count, or 1 when absent/malformed. Fail-secure: an
1477
+ * unparseable or `< 1` value falls back to 1 (the smallest real quorum), never 0
1478
+ * — which would make the step-up gate a no-op. The route's own
1479
+ * `validateStepUpQuorum` is the second line of defence on a misconfigured n.
1480
+ */
1481
+ function parseQuorumN(block) {
1482
+ const m = block.match(/@quorum\("([^"]*)"\)/);
1483
+ if (!m) return 1;
1484
+ const n = Number(m[1]);
1485
+ return Number.isInteger(n) && n >= 1 ? n : 1;
1486
+ }
1487
+
1488
+ //#endregion
1489
+ //#region src/policy/step-up.ts
1490
+ /**
1491
+ * Validate a `step_up` decision's quorum before approval verification.
1492
+ * Fail-closed: returns a deny `reason` for any quorum that can never be
1493
+ * legitimately met; `{ ok: true }` only when the quorum is a real gate.
1494
+ *
1495
+ * Ordering is load-bearing: the `n` guard runs first, so an invalid quorum that
1496
+ * is both non-positive AND has no approvers reports `invalid_step_up_quorum`
1497
+ * (stable/deterministic reason).
1498
+ */
1499
+ function validateStepUpQuorum(quorum) {
1500
+ if (!Number.isInteger(quorum.n) || quorum.n < 1) return {
1501
+ ok: false,
1502
+ reason: "invalid_step_up_quorum"
1503
+ };
1504
+ if (!Array.isArray(quorum.approvers) || quorum.approvers.length === 0) return {
1505
+ ok: false,
1506
+ reason: "step_up_no_approvers"
1507
+ };
1508
+ return { ok: true };
1509
+ }
1510
+
1511
+ //#endregion
1512
+ Object.defineProperty(exports, 'ByteBoundedMemo', {
1513
+ enumerable: true,
1514
+ get: function () {
1515
+ return ByteBoundedMemo;
1516
+ }
1517
+ });
1518
+ Object.defineProperty(exports, 'FAIL_CLOSED_BODY', {
1519
+ enumerable: true,
1520
+ get: function () {
1521
+ return FAIL_CLOSED_BODY;
1522
+ }
1523
+ });
1524
+ Object.defineProperty(exports, 'FAIL_CLOSED_HEADERS', {
1525
+ enumerable: true,
1526
+ get: function () {
1527
+ return FAIL_CLOSED_HEADERS;
1528
+ }
1529
+ });
1530
+ Object.defineProperty(exports, 'FAIL_CLOSED_STATUS', {
1531
+ enumerable: true,
1532
+ get: function () {
1533
+ return FAIL_CLOSED_STATUS;
1534
+ }
1535
+ });
1536
+ Object.defineProperty(exports, 'NO_EVIDENCE_CATEGORY', {
1537
+ enumerable: true,
1538
+ get: function () {
1539
+ return NO_EVIDENCE_CATEGORY;
1540
+ }
1541
+ });
1542
+ Object.defineProperty(exports, 'NO_EVIDENCE_EQUALITY_TERM', {
1543
+ enumerable: true,
1544
+ get: function () {
1545
+ return NO_EVIDENCE_EQUALITY_TERM;
1546
+ }
1547
+ });
1548
+ Object.defineProperty(exports, 'NO_EVIDENCE_EXCLUSION_TERM', {
1549
+ enumerable: true,
1550
+ get: function () {
1551
+ return NO_EVIDENCE_EXCLUSION_TERM;
1552
+ }
1553
+ });
1554
+ Object.defineProperty(exports, 'PROBE_CLASSES', {
1555
+ enumerable: true,
1556
+ get: function () {
1557
+ return PROBE_CLASSES;
1558
+ }
1559
+ });
1560
+ Object.defineProperty(exports, 'analyzePolicySource', {
1561
+ enumerable: true,
1562
+ get: function () {
1563
+ return analyzePolicySource;
1564
+ }
1565
+ });
1566
+ Object.defineProperty(exports, 'approvalQuorumForRequest', {
1567
+ enumerable: true,
1568
+ get: function () {
1569
+ return approvalQuorumForRequest;
1570
+ }
1571
+ });
1572
+ Object.defineProperty(exports, 'blockEqualityLiterals', {
1573
+ enumerable: true,
1574
+ get: function () {
1575
+ return blockEqualityLiterals;
1576
+ }
1577
+ });
1578
+ Object.defineProperty(exports, 'cedarQuotedValueRegExp', {
1579
+ enumerable: true,
1580
+ get: function () {
1581
+ return cedarQuotedValueRegExp;
1582
+ }
1583
+ });
1584
+ Object.defineProperty(exports, 'decisionPolicyId', {
1585
+ enumerable: true,
1586
+ get: function () {
1587
+ return decisionPolicyId;
1588
+ }
1589
+ });
1590
+ Object.defineProperty(exports, 'escapeCedarString', {
1591
+ enumerable: true,
1592
+ get: function () {
1593
+ return escapeCedarString;
1594
+ }
1595
+ });
1596
+ Object.defineProperty(exports, 'isEngineEnforcing', {
1597
+ enumerable: true,
1598
+ get: function () {
1599
+ return isEngineEnforcing;
1600
+ }
1601
+ });
1602
+ Object.defineProperty(exports, 'isForbidBlock', {
1603
+ enumerable: true,
1604
+ get: function () {
1605
+ return isForbidBlock;
1606
+ }
1607
+ });
1608
+ Object.defineProperty(exports, 'isUnnarrowedDenyBlock', {
1609
+ enumerable: true,
1610
+ get: function () {
1611
+ return isUnnarrowedDenyBlock;
1612
+ }
1613
+ });
1614
+ Object.defineProperty(exports, 'lacksBaselinePermit', {
1615
+ enumerable: true,
1616
+ get: function () {
1617
+ return lacksBaselinePermit;
1618
+ }
1619
+ });
1620
+ Object.defineProperty(exports, 'parseCedarStatements', {
1621
+ enumerable: true,
1622
+ get: function () {
1623
+ return parseCedarStatements;
1624
+ }
1625
+ });
1626
+ Object.defineProperty(exports, 'pathHasExplicitDenyRuleFor', {
1627
+ enumerable: true,
1628
+ get: function () {
1629
+ return pathHasExplicitDenyRuleFor;
1630
+ }
1631
+ });
1632
+ Object.defineProperty(exports, 'pathHasUnnarrowedDenyRule', {
1633
+ enumerable: true,
1634
+ get: function () {
1635
+ return pathHasUnnarrowedDenyRule;
1636
+ }
1637
+ });
1638
+ Object.defineProperty(exports, 'pathHasUnnarrowedDenyRuleFor', {
1639
+ enumerable: true,
1640
+ get: function () {
1641
+ return pathHasUnnarrowedDenyRuleFor;
1642
+ }
1643
+ });
1644
+ Object.defineProperty(exports, 'pathLiteralsInBlock', {
1645
+ enumerable: true,
1646
+ get: function () {
1647
+ return pathLiteralsInBlock;
1648
+ }
1649
+ });
1650
+ Object.defineProperty(exports, 'requiredScopesForRequest', {
1651
+ enumerable: true,
1652
+ get: function () {
1653
+ return requiredScopesForRequest;
1654
+ }
1655
+ });
1656
+ Object.defineProperty(exports, 'splitCedarBlocks', {
1657
+ enumerable: true,
1658
+ get: function () {
1659
+ return splitCedarBlocks;
1660
+ }
1661
+ });
1662
+ Object.defineProperty(exports, 'statementApplies', {
1663
+ enumerable: true,
1664
+ get: function () {
1665
+ return statementApplies;
1666
+ }
1667
+ });
1668
+ Object.defineProperty(exports, 'statementId', {
1669
+ enumerable: true,
1670
+ get: function () {
1671
+ return statementId;
1672
+ }
1673
+ });
1674
+ Object.defineProperty(exports, 'unescapeCedarString', {
1675
+ enumerable: true,
1676
+ get: function () {
1677
+ return unescapeCedarString;
1678
+ }
1679
+ });
1680
+ Object.defineProperty(exports, 'unnarrowedDenyStatements', {
1681
+ enumerable: true,
1682
+ get: function () {
1683
+ return unnarrowedDenyStatements;
1684
+ }
1685
+ });
1686
+ Object.defineProperty(exports, 'validateStepUpQuorum', {
1687
+ enumerable: true,
1688
+ get: function () {
1689
+ return validateStepUpQuorum;
1690
+ }
1691
+ });
1692
+ Object.defineProperty(exports, 'withNoEvidenceExclusion', {
1693
+ enumerable: true,
1694
+ get: function () {
1695
+ return withNoEvidenceExclusion;
1696
+ }
1697
+ });