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