@kya-os/checkpoint-shared 1.10.0 → 1.11.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 (187) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/dist/base64url-BbVG8f-v.js +65 -0
  3. package/dist/base64url-D2MvsR20.mjs +49 -0
  4. package/dist/base64url-D2MvsR20.mjs.map +1 -0
  5. package/dist/beacon-forward-secret/index.d.mts +4 -0
  6. package/dist/beacon-forward-secret/index.d.mts.map +1 -0
  7. package/dist/beacon-forward-secret/index.d.ts +4 -0
  8. package/dist/beacon-forward-secret/index.d.ts.map +1 -0
  9. package/dist/beacon-forward-secret/index.js +15 -0
  10. package/dist/beacon-forward-secret/index.mjs +15 -0
  11. package/dist/beacon-forward-secret/index.mjs.map +1 -0
  12. package/dist/beacon-types/index.d.mts +53 -1
  13. package/dist/beacon-types/index.d.mts.map +1 -1
  14. package/dist/beacon-types/index.d.ts +53 -1
  15. package/dist/beacon-types/index.d.ts.map +1 -1
  16. package/dist/beacon-types/index.js +86 -1
  17. package/dist/beacon-types/index.mjs +77 -2
  18. package/dist/beacon-types/index.mjs.map +1 -1
  19. package/dist/{browser-posture-5fPrsxx7.d.mts → browser-posture-WPk0kl9u.d.mts} +18 -1
  20. package/dist/browser-posture-WPk0kl9u.d.mts.map +1 -0
  21. package/dist/{browser-posture-CCR1kh5e.d.ts → browser-posture-_y6BcdXw.d.ts} +18 -1
  22. package/dist/browser-posture-_y6BcdXw.d.ts.map +1 -0
  23. package/dist/browser-posture-cookie.mjs.map +1 -1
  24. package/dist/browser-posture-proof-verifier.js +136 -5
  25. package/dist/browser-posture-proof-verifier.mjs +134 -2
  26. package/dist/browser-posture-proof-verifier.mjs.map +1 -0
  27. package/dist/browser-posture-proof.d.mts +1 -1
  28. package/dist/browser-posture-proof.d.ts +1 -1
  29. package/dist/browser-posture-proof.js +1 -1
  30. package/dist/browser-posture-proof.mjs +1 -1
  31. package/dist/browser-posture-report.d.mts +17 -0
  32. package/dist/browser-posture-report.d.mts.map +1 -1
  33. package/dist/browser-posture-report.d.ts +17 -0
  34. package/dist/browser-posture-report.d.ts.map +1 -1
  35. package/dist/browser-posture.d.mts +1 -1
  36. package/dist/browser-posture.d.ts +1 -1
  37. package/dist/browser-posture.js +18 -1
  38. package/dist/browser-posture.mjs +18 -1
  39. package/dist/browser-posture.mjs.map +1 -1
  40. package/dist/browser.d.mts +10 -0
  41. package/dist/browser.d.mts.map +1 -1
  42. package/dist/browser.d.ts +10 -0
  43. package/dist/browser.d.ts.map +1 -1
  44. package/dist/browser.js +1 -1
  45. package/dist/browser.mjs +1 -1
  46. package/dist/browser.mjs.map +1 -1
  47. package/dist/canonical-signer/index.d.mts.map +1 -1
  48. package/dist/canonical-signer/index.d.ts.map +1 -1
  49. package/dist/canonical-signer/index.js +0 -4
  50. package/dist/canonical-signer/index.mjs +0 -4
  51. package/dist/canonical-signer/index.mjs.map +1 -1
  52. package/dist/{client-ip-B7w-uHfS.d.ts → client-ip-8KneiMK0.d.mts} +12 -2
  53. package/dist/{client-ip-B7w-uHfS.d.mts.map → client-ip-8KneiMK0.d.mts.map} +1 -1
  54. package/dist/{client-ip-B7w-uHfS.d.mts → client-ip-8KneiMK0.d.ts} +12 -2
  55. package/dist/{client-ip-B7w-uHfS.d.ts.map → client-ip-8KneiMK0.d.ts.map} +1 -1
  56. package/dist/{client-ip-B8wFzJ5f.js → client-ip-BEmLC4I4.js} +71 -0
  57. package/dist/{client-ip-DIJyr6px.mjs → client-ip-DlHx7GGh.mjs} +61 -2
  58. package/dist/client-ip-DlHx7GGh.mjs.map +1 -0
  59. package/dist/client-ip.d.mts +2 -2
  60. package/dist/client-ip.d.ts +2 -2
  61. package/dist/client-ip.js +3 -1
  62. package/dist/client-ip.mjs +2 -2
  63. package/dist/deploy/index.d.mts.map +1 -1
  64. package/dist/deploy/index.d.ts.map +1 -1
  65. package/dist/deploy/index.js +5 -1
  66. package/dist/deploy/index.mjs +5 -1
  67. package/dist/deploy/index.mjs.map +1 -1
  68. package/dist/{detection-reason-mapping-CQexNvR7.d.ts → detection-reason-mapping-BemDaDED.d.mts} +5 -2
  69. package/dist/detection-reason-mapping-BemDaDED.d.mts.map +1 -0
  70. package/dist/{detection-reason-mapping-CQexNvR7.d.mts → detection-reason-mapping-BemDaDED.d.ts} +5 -2
  71. package/dist/detection-reason-mapping-BemDaDED.d.ts.map +1 -0
  72. package/dist/{detection-reason-mapping-B9RSkOs8.js → detection-reason-mapping-BxYaQ8kb.js} +33 -8
  73. package/dist/{detection-reason-mapping-BGymWIPl.mjs → detection-reason-mapping-j-7bXsVb.mjs} +29 -10
  74. package/dist/detection-reason-mapping-j-7bXsVb.mjs.map +1 -0
  75. package/dist/errors/index.d.mts +4 -0
  76. package/dist/errors/index.d.mts.map +1 -1
  77. package/dist/errors/index.d.ts +4 -0
  78. package/dist/errors/index.d.ts.map +1 -1
  79. package/dist/errors/index.js +24 -8
  80. package/dist/errors/index.mjs +24 -8
  81. package/dist/errors/index.mjs.map +1 -1
  82. package/dist/{fetcher-CZfLcbRZ.d.mts → fetcher-CTKz07jg.d.mts} +12 -2
  83. package/dist/fetcher-CTKz07jg.d.mts.map +1 -0
  84. package/dist/{fetcher-CCw4Q95g.d.ts → fetcher-DCr920hx.d.ts} +12 -2
  85. package/dist/fetcher-DCr920hx.d.ts.map +1 -0
  86. package/dist/gateway-client-ip.js +1 -1
  87. package/dist/gateway-client-ip.mjs +1 -1
  88. package/dist/identity-cookie/index.d.mts +14 -0
  89. package/dist/identity-cookie/index.d.mts.map +1 -0
  90. package/dist/identity-cookie/index.d.ts +14 -0
  91. package/dist/identity-cookie/index.d.ts.map +1 -0
  92. package/dist/identity-cookie/index.js +45 -0
  93. package/dist/identity-cookie/index.mjs +43 -0
  94. package/dist/identity-cookie/index.mjs.map +1 -0
  95. package/dist/index.d.mts +598 -142
  96. package/dist/index.d.mts.map +1 -1
  97. package/dist/index.d.ts +598 -142
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +793 -198
  100. package/dist/index.mjs +743 -188
  101. package/dist/index.mjs.map +1 -1
  102. package/dist/kya-http.d.mts +2 -2
  103. package/dist/kya-http.d.ts +2 -2
  104. package/dist/kya-http.js +2 -1
  105. package/dist/kya-http.mjs +2 -2
  106. package/dist/mcpi/dashboard-config/index.mjs.map +1 -1
  107. package/dist/patterns-CdTh7LU2.d.mts +35 -0
  108. package/dist/patterns-CdTh7LU2.d.mts.map +1 -0
  109. package/dist/patterns-CdTh7LU2.d.ts +35 -0
  110. package/dist/patterns-CdTh7LU2.d.ts.map +1 -0
  111. package/dist/{patterns-CiMpbdAF.js → patterns-CnNxRnaK.js} +3 -130
  112. package/dist/{patterns-D4OAsNQY.mjs → patterns-CpRk9R3M.mjs} +5 -96
  113. package/dist/patterns-CpRk9R3M.mjs.map +1 -0
  114. package/dist/patterns.d.mts +2 -2
  115. package/dist/patterns.d.ts +2 -2
  116. package/dist/patterns.js +1 -7
  117. package/dist/patterns.mjs +2 -2
  118. package/dist/policy/fetcher.d.mts +2 -2
  119. package/dist/policy/fetcher.d.ts +2 -2
  120. package/dist/policy/fetcher.js +100 -8
  121. package/dist/policy/fetcher.mjs +99 -9
  122. package/dist/policy/fetcher.mjs.map +1 -1
  123. package/dist/proxy-assertion-mapping-BVwXVSMZ.mjs +81 -0
  124. package/dist/proxy-assertion-mapping-BVwXVSMZ.mjs.map +1 -0
  125. package/dist/proxy-assertion-mapping-BxhENrcY.d.mts +70 -0
  126. package/dist/proxy-assertion-mapping-BxhENrcY.d.mts.map +1 -0
  127. package/dist/proxy-assertion-mapping-D64AyZfG.js +85 -0
  128. package/dist/proxy-assertion-mapping-DhAynFqG.d.ts +70 -0
  129. package/dist/proxy-assertion-mapping-DhAynFqG.d.ts.map +1 -0
  130. package/dist/proxy-assertions.d.mts +2 -0
  131. package/dist/proxy-assertions.d.ts +2 -0
  132. package/dist/proxy-assertions.js +4 -0
  133. package/dist/proxy-assertions.mjs +3 -0
  134. package/dist/reason-codes.d.mts +2 -2
  135. package/dist/reason-codes.d.ts +2 -2
  136. package/dist/reason-codes.js +3 -2
  137. package/dist/reason-codes.mjs +2 -2
  138. package/dist/{registered-sid-CnWIU_l1.d.ts → registered-sid-BgDhdj2l.d.mts} +13 -2
  139. package/dist/registered-sid-BgDhdj2l.d.mts.map +1 -0
  140. package/dist/{registered-sid-CnWIU_l1.d.mts → registered-sid-BgDhdj2l.d.ts} +13 -2
  141. package/dist/registered-sid-BgDhdj2l.d.ts.map +1 -0
  142. package/dist/{registered-sid-BZfDOfXy.js → registered-sid-DG1tSSvl.js} +67 -12
  143. package/dist/{registered-sid-CS9V8nPr.mjs → registered-sid-D__xiDPu.mjs} +63 -14
  144. package/dist/registered-sid-D__xiDPu.mjs.map +1 -0
  145. package/dist/timezone-country-B6PkDyNP.d.mts +15 -0
  146. package/dist/timezone-country-B6PkDyNP.d.mts.map +1 -0
  147. package/dist/timezone-country-B6PkDyNP.d.ts +15 -0
  148. package/dist/timezone-country-B6PkDyNP.d.ts.map +1 -0
  149. package/dist/timezone-country-CROxU2Tl.js +505 -0
  150. package/dist/timezone-country-CrrnkOdy.mjs +489 -0
  151. package/dist/timezone-country-CrrnkOdy.mjs.map +1 -0
  152. package/dist/timezone-country.d.mts +2 -0
  153. package/dist/timezone-country.d.ts +2 -0
  154. package/dist/timezone-country.js +6 -0
  155. package/dist/timezone-country.mjs +3 -0
  156. package/dist/tool-protection/index.mjs.map +1 -1
  157. package/fixtures/detection/cloudflare-alias-parity.json +383 -0
  158. package/fixtures/detection/reason-codes.json +3 -1
  159. package/fixtures/detection/signal-exposure-example.json +1 -1
  160. package/fixtures/iana-tzdata/backward +375 -0
  161. package/fixtures/iana-tzdata/renamed-zones.json +21 -0
  162. package/fixtures/iana-tzdata/version +1 -0
  163. package/fixtures/iana-tzdata/zone.tab +448 -0
  164. package/fixtures/workbench/management-session.v1.json +20 -0
  165. package/fixtures/workbench/model-credentials.v1.json +8 -0
  166. package/fixtures/workbench/task-grant.v1.json +37 -0
  167. package/package.json +25 -3
  168. package/src/data/compiled/merged-rules.json +9 -7
  169. package/dist/browser-posture-5fPrsxx7.d.mts.map +0 -1
  170. package/dist/browser-posture-CCR1kh5e.d.ts.map +0 -1
  171. package/dist/browser-posture-proof-verifier-DvsOmFrM.js +0 -202
  172. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs +0 -180
  173. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs.map +0 -1
  174. package/dist/client-ip-DIJyr6px.mjs.map +0 -1
  175. package/dist/detection-reason-mapping-BGymWIPl.mjs.map +0 -1
  176. package/dist/detection-reason-mapping-CQexNvR7.d.mts.map +0 -1
  177. package/dist/detection-reason-mapping-CQexNvR7.d.ts.map +0 -1
  178. package/dist/fetcher-CCw4Q95g.d.ts.map +0 -1
  179. package/dist/fetcher-CZfLcbRZ.d.mts.map +0 -1
  180. package/dist/patterns-Bp40cwh2.d.mts +0 -110
  181. package/dist/patterns-Bp40cwh2.d.mts.map +0 -1
  182. package/dist/patterns-Bp40cwh2.d.ts +0 -110
  183. package/dist/patterns-Bp40cwh2.d.ts.map +0 -1
  184. package/dist/patterns-D4OAsNQY.mjs.map +0 -1
  185. package/dist/registered-sid-CS9V8nPr.mjs.map +0 -1
  186. package/dist/registered-sid-CnWIU_l1.d.mts.map +0 -1
  187. package/dist/registered-sid-CnWIU_l1.d.ts.map +0 -1
@@ -2,7 +2,9 @@
2
2
  /**
3
3
  * Regular Expression Patterns
4
4
  *
5
- * Common regex patterns used for validation and detection
5
+ * Common regex patterns used for validation, and helpers that match bounded
6
+ * input against them. Request classification belongs to the detection
7
+ * engine, so no detection patterns live here.
6
8
  */
7
9
  /**
8
10
  * Validation Patterns
@@ -35,99 +37,6 @@ const VALIDATION_PATTERNS = {
35
37
  PIXEL_ID: /^px_[A-Za-z0-9]{16}$/
36
38
  };
37
39
  /**
38
- * User Agent Patterns for Agent Detection
39
- */
40
- const USER_AGENT_PATTERNS = {
41
- OPENAI: /(?:GPTBot|ChatGPT-User|OpenAI)/i,
42
- ANTHROPIC: /(?:Claude-Web|Claude-User|anthropic-ai|claude-web|claude-user|ClaudeBot)/i,
43
- PERPLEXITY: /(?:PerplexityBot|Perplexica)/i,
44
- GOOGLE_AI: /(?:Bard|Google-InspectionTool)/i,
45
- MICROSOFT_AI: /(?:BingPreview\/.*ChatGPT|Copilot)/i,
46
- GOOGLEBOT: /Googlebot/i,
47
- BINGBOT: /(?:bingbot|BingPreview|msnbot)/i,
48
- DUCKDUCKBOT: /DuckDuckBot/i,
49
- BAIDUBOT: /Baiduspider/i,
50
- YANDEXBOT: /YandexBot/i,
51
- FACEBOOK: /(?:facebookexternalhit|facebookcatalog)/i,
52
- TWITTER: /(?:Twitterbot|TwitterImageProxy)/i,
53
- LINKEDIN: /LinkedInBot/i,
54
- WHATSAPP: /WhatsApp/i,
55
- TELEGRAM: /TelegramBot/i,
56
- DISCORD: /Discordbot/i,
57
- SLACK: /Slackbot/i,
58
- GENERIC_BOT: /(?:bot|crawler|spider|scraper|agent)/i,
59
- SCRAPY: /Scrapy/i,
60
- PUPPETEER: /(?:HeadlessChrome|Puppeteer)/i,
61
- PLAYWRIGHT: /Playwright/i,
62
- SELENIUM: /(?:selenium|webdriver)/i,
63
- POSTMAN: /PostmanRuntime/i,
64
- INSOMNIA: /insomnia/i,
65
- CURL: /curl/i,
66
- WGET: /Wget/i,
67
- HTTPIE: /HTTPie/i,
68
- UPTIMEROBOT: /UptimeRobot/i,
69
- PINGDOM: /Pingdom/i,
70
- NEWRELIC: /NewRelicPinger/i,
71
- DATADOG: /Datadog/i
72
- };
73
- /**
74
- * Header Patterns for Agent Detection
75
- */
76
- const HEADER_PATTERNS = {
77
- AI_HEADERS: /^(?:X-(?:OpenAI|Anthropic|AI|Bot|Agent|LLM))/i,
78
- AUTOMATION_HEADERS: /^(?:X-(?:Automated|Robot|Crawler|Scraper))/i,
79
- MISSING_ACCEPT: /^$/,
80
- MISSING_ACCEPT_LANGUAGE: /^$/,
81
- MISSING_ACCEPT_ENCODING: /^$/,
82
- GENERIC_ACCEPT: /^\*\/\*$/,
83
- NO_COOKIES: /^$/,
84
- PROXY_HEADERS: /^(?:X-Forwarded-|X-Real-IP|X-Originating-IP|Via|Forwarded)/i,
85
- CLOUD_HEADERS: /^(?:X-(?:AWS|Azure|GCP|Cloudflare))/i
86
- };
87
- /**
88
- * Browser Patterns
89
- */
90
- const BROWSER_PATTERNS = {
91
- CHROME: /Chrome\/([0-9.]+)/,
92
- FIREFOX: /Firefox\/([0-9.]+)/,
93
- SAFARI: /Version\/([0-9.]+).*Safari/,
94
- EDGE: /Edg\/([0-9.]+)/,
95
- OPERA: /OPR\/([0-9.]+)/,
96
- IE: /MSIE ([0-9.]+)/
97
- };
98
- /**
99
- * Operating System Patterns
100
- */
101
- const OS_PATTERNS = {
102
- WINDOWS: /Windows NT ([0-9.]+)/,
103
- MACOS: /Mac OS X ([0-9_]+)/,
104
- LINUX: /Linux/,
105
- ANDROID: /Android ([0-9.]+)/,
106
- IOS: /OS ([0-9_]+) like Mac OS X/
107
- };
108
- /**
109
- * Mobile Device Patterns
110
- */
111
- const MOBILE_PATTERNS = {
112
- MOBILE: /(?:Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini)/i,
113
- TABLET: /(?:iPad|Android.*Tablet|Tablet.*Android|Kindle|Silk)/i,
114
- DESKTOP: /(?:Windows NT|Mac OS X|Linux|CrOS)/i
115
- };
116
- /**
117
- * Suspicious Behavior Patterns
118
- */
119
- const SUSPICIOUS_PATTERNS = {
120
- RAPID_REQUESTS: /^[0-9]{1,3}$/,
121
- SEQUENTIAL_URLS: /\?(?:page|offset|id)=[0-9]+/,
122
- API_ENDPOINTS: /\/api\/|\.json$|\.xml$/i,
123
- DIRECT_POST: /^POST$/,
124
- SQL_INJECTION: /(?:union|select|insert|update|delete|drop|create|alter|exec|script|javascript|onerror|onload|eval|src=)/i,
125
- XSS_ATTEMPT: /(?:<script|javascript:|onerror=|onclick=|<iframe|<embed|<object)/i,
126
- PATH_TRAVERSAL: /(?:\.\.\/|\.\.\\|%2e%2e%2f|%252e%252e%252f)/i,
127
- URL_ENCODED: /%[0-9a-f]{2}/i,
128
- BASE64_DATA: /data:[^;]+;base64,/i
129
- };
130
- /**
131
40
  * Maximum input length for pattern matching. UAs, header values, and
132
41
  * detection payloads are bounded in practice (<4KB even for the most
133
42
  * verbose Chrome/Firefox UAs). Caps worst-case complexity for any
@@ -169,5 +78,5 @@ function findMatchingPattern(patterns, value) {
169
78
  }
170
79
 
171
80
  //#endregion
172
- export { SUSPICIOUS_PATTERNS as a, VALIDATION_PATTERNS as c, testPattern as d, testPatterns as f, OS_PATTERNS as i, extractMatch as l, HEADER_PATTERNS as n, USER_AGENT_PATTERNS as o, MOBILE_PATTERNS as r, UUID_PATTERN as s, BROWSER_PATTERNS as t, findMatchingPattern as u };
173
- //# sourceMappingURL=patterns-D4OAsNQY.mjs.map
81
+ export { testPattern as a, findMatchingPattern as i, VALIDATION_PATTERNS as n, testPatterns as o, extractMatch as r, UUID_PATTERN as t };
82
+ //# sourceMappingURL=patterns-CpRk9R3M.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patterns-CpRk9R3M.mjs","names":[],"sources":["../src/constants/patterns.ts"],"sourcesContent":["/**\n * Regular Expression Patterns\n *\n * Common regex patterns used for validation, and helpers that match bounded\n * input against them. Request classification belongs to the detection\n * engine, so no detection patterns live here.\n */\n\n/**\n * Validation Patterns\n */\n// Hoisted out of the object literal below so bundle-size-critical leaves can\n// import JUST this one pattern. `VALIDATION_PATTERNS` re-exports it, so there\n// is still exactly one definition and no drift.\n//\n// Why it matters: rolldown (via tsdown) does not do property-level DCE on a\n// const object literal the way esbuild did. `browser-posture-cookie.ts` uses\n// only `.UUID`, but importing the whole object dragged every pattern —\n// ULID, SLUG, IPV4, IPV6 — into that leaf, taking it from 272 to 2,870 bytes.\nexport const UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport const VALIDATION_PATTERNS = {\n // Identifiers\n UUID: UUID_PATTERN,\n ULID: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n SLUG: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,\n\n // Network\n IPV4: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,\n IPV6: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,\n IP: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,\n // eslint-disable-next-line no-useless-escape\n // CIDR pattern: uses IPV4 pattern and restricts mask to 0-32\n CIDR: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\/(?:[0-9]|[12][0-9]|3[0-2])$/,\n // eslint-disable-next-line no-useless-escape\n DOMAIN: /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i,\n HOSTNAME:\n /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/,\n // eslint-disable-next-line no-useless-escape\n URL: /^https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/,\n\n // Contact\n // Email pattern: stricter validation (rejects consecutive dots, requires TLD)\n // Local part: alphanumeric start/end, dots allowed but not consecutive\n EMAIL:\n /^[a-zA-Z0-9](?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]|\\.(?!\\.))*[a-zA-Z0-9]?@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,\n PHONE: /^[+]?[(]?[0-9]{3}[)]?[-\\s.]?[0-9]{3}[-\\s.]?[0-9]{4,6}$/,\n\n // Security\n // JWT pattern: requires 3 parts (header.payload.signature) - signature cannot be empty\n JWT: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+$/,\n // eslint-disable-next-line no-useless-escape\n BASE64: /^[A-Za-z0-9+\\/]*={0,2}$/,\n HEX: /^[0-9a-fA-F]+$/,\n MD5: /^[a-f0-9]{32}$/i,\n SHA1: /^[a-f0-9]{40}$/i,\n SHA256: /^[a-f0-9]{64}$/i,\n\n // Versions\n SEMVER:\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/,\n\n // Files\n FILENAME: /^[a-zA-Z0-9](?:[a-zA-Z0-9 ._-]*[a-zA-Z0-9])?\\.[a-zA-Z0-9_-]+$/,\n PATH: /^(\\/[^/ ]*)+\\/?$/,\n\n // Keys\n API_KEY: /^[A-Za-z0-9_-]{32,}$/,\n SECRET_KEY: /^[A-Za-z0-9_-]{64,}$/,\n PIXEL_ID: /^px_[A-Za-z0-9]{16}$/,\n} as const;\n\n/**\n * Maximum input length for pattern matching. UAs, header values, and\n * detection payloads are bounded in practice (<4KB even for the most\n * verbose Chrome/Firefox UAs). Caps worst-case complexity for any\n * polynomial-shaped pattern an external caller might supply to\n * `testPattern` / `extractMatch`; CodeQL flagged the unbounded path\n * (js/polynomial-redos) on PR #2576.\n */\nconst MAX_PATTERN_INPUT_LENGTH = 4096;\n\n/**\n * Helper function to test a pattern. Returns `false` on inputs longer\n * than {@link MAX_PATTERN_INPUT_LENGTH} — an abuse signal we'd rather\n * reject than process.\n */\nexport function testPattern(pattern: RegExp, value: string): boolean {\n if (value.length > MAX_PATTERN_INPUT_LENGTH) return false;\n return pattern.test(value);\n}\n\n/**\n * Helper function to extract match from pattern. Returns `null` on\n * over-long inputs (same ReDoS defense as `testPattern`).\n */\nexport function extractMatch(pattern: RegExp, value: string): string | null {\n if (value.length > MAX_PATTERN_INPUT_LENGTH) return null;\n const match = value.match(pattern);\n return match ? match[1] || match[0] : null;\n}\n\n/**\n * Helper function to test multiple patterns\n */\nexport function testPatterns(patterns: RegExp[], value: string): boolean {\n return patterns.some((pattern) => testPattern(pattern, value));\n}\n\n/**\n * Helper function to find matching pattern\n */\nexport function findMatchingPattern(\n patterns: Record<string, RegExp>,\n value: string\n): string | null {\n for (const [name, pattern] of Object.entries(patterns)) {\n if (testPattern(pattern, value)) {\n return name;\n }\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,eACX;AAEF,MAAa,sBAAsB;CAEjC,MAAM;CACN,MAAM;CACN,MAAM;CAGN,MAAM;CACN,MAAM;CACN,IAAI;CAGJ,MAAM;CAEN,QAAQ;CACR,UACE;CAEF,KAAK;CAKL,OACE;CACF,OAAO;CAIP,KAAK;CAEL,QAAQ;CACR,KAAK;CACL,KAAK;CACL,MAAM;CACN,QAAQ;CAGR,QACE;CAGF,UAAU;CACV,MAAM;CAGN,SAAS;CACT,YAAY;CACZ,UAAU;AACZ;;;;;;;;;AAUA,MAAM,2BAA2B;;;;;;AAOjC,SAAgB,YAAY,SAAiB,OAAwB;CACnE,IAAI,MAAM,SAAS,0BAA0B,OAAO;CACpD,OAAO,QAAQ,KAAK,KAAK;AAC3B;;;;;AAMA,SAAgB,aAAa,SAAiB,OAA8B;CAC1E,IAAI,MAAM,SAAS,0BAA0B,OAAO;CACpD,MAAM,QAAQ,MAAM,MAAM,OAAO;CACjC,OAAO,QAAQ,MAAM,MAAM,MAAM,KAAK;AACxC;;;;AAKA,SAAgB,aAAa,UAAoB,OAAwB;CACvE,OAAO,SAAS,MAAM,YAAY,YAAY,SAAS,KAAK,CAAC;AAC/D;;;;AAKA,SAAgB,oBACd,UACA,OACe;CACf,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,QAAQ,GACnD,IAAI,YAAY,SAAS,KAAK,GAC5B,OAAO;CAGX,OAAO;AACT"}
@@ -1,2 +1,2 @@
1
- import { a as SUSPICIOUS_PATTERNS, c as VALIDATION_PATTERNS, d as testPattern, f as testPatterns, i as OS_PATTERNS, l as extractMatch, n as HEADER_PATTERNS, o as USER_AGENT_PATTERNS, r as MOBILE_PATTERNS, s as UUID_PATTERN, t as BROWSER_PATTERNS, u as findMatchingPattern } from "./patterns-Bp40cwh2.mjs";
2
- export { BROWSER_PATTERNS, HEADER_PATTERNS, MOBILE_PATTERNS, OS_PATTERNS, SUSPICIOUS_PATTERNS, USER_AGENT_PATTERNS, UUID_PATTERN, VALIDATION_PATTERNS, extractMatch, findMatchingPattern, testPattern, testPatterns };
1
+ import { a as testPattern, i as findMatchingPattern, n as VALIDATION_PATTERNS, o as testPatterns, r as extractMatch, t as UUID_PATTERN } from "./patterns-CdTh7LU2.mjs";
2
+ export { UUID_PATTERN, VALIDATION_PATTERNS, extractMatch, findMatchingPattern, testPattern, testPatterns };
@@ -1,2 +1,2 @@
1
- import { a as SUSPICIOUS_PATTERNS, c as VALIDATION_PATTERNS, d as testPattern, f as testPatterns, i as OS_PATTERNS, l as extractMatch, n as HEADER_PATTERNS, o as USER_AGENT_PATTERNS, r as MOBILE_PATTERNS, s as UUID_PATTERN, t as BROWSER_PATTERNS, u as findMatchingPattern } from "./patterns-Bp40cwh2.js";
2
- export { BROWSER_PATTERNS, HEADER_PATTERNS, MOBILE_PATTERNS, OS_PATTERNS, SUSPICIOUS_PATTERNS, USER_AGENT_PATTERNS, UUID_PATTERN, VALIDATION_PATTERNS, extractMatch, findMatchingPattern, testPattern, testPatterns };
1
+ import { a as testPattern, i as findMatchingPattern, n as VALIDATION_PATTERNS, o as testPatterns, r as extractMatch, t as UUID_PATTERN } from "./patterns-CdTh7LU2.js";
2
+ export { UUID_PATTERN, VALIDATION_PATTERNS, extractMatch, findMatchingPattern, testPattern, testPatterns };
package/dist/patterns.js CHANGED
@@ -1,12 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_patterns = require('./patterns-CiMpbdAF.js');
2
+ const require_patterns = require('./patterns-CnNxRnaK.js');
3
3
 
4
- exports.BROWSER_PATTERNS = require_patterns.BROWSER_PATTERNS;
5
- exports.HEADER_PATTERNS = require_patterns.HEADER_PATTERNS;
6
- exports.MOBILE_PATTERNS = require_patterns.MOBILE_PATTERNS;
7
- exports.OS_PATTERNS = require_patterns.OS_PATTERNS;
8
- exports.SUSPICIOUS_PATTERNS = require_patterns.SUSPICIOUS_PATTERNS;
9
- exports.USER_AGENT_PATTERNS = require_patterns.USER_AGENT_PATTERNS;
10
4
  exports.UUID_PATTERN = require_patterns.UUID_PATTERN;
11
5
  exports.VALIDATION_PATTERNS = require_patterns.VALIDATION_PATTERNS;
12
6
  exports.extractMatch = require_patterns.extractMatch;
package/dist/patterns.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { a as SUSPICIOUS_PATTERNS, c as VALIDATION_PATTERNS, d as testPattern, f as testPatterns, i as OS_PATTERNS, l as extractMatch, n as HEADER_PATTERNS, o as USER_AGENT_PATTERNS, r as MOBILE_PATTERNS, s as UUID_PATTERN, t as BROWSER_PATTERNS, u as findMatchingPattern } from "./patterns-D4OAsNQY.mjs";
1
+ import { a as testPattern, i as findMatchingPattern, n as VALIDATION_PATTERNS, o as testPatterns, r as extractMatch, t as UUID_PATTERN } from "./patterns-CpRk9R3M.mjs";
2
2
 
3
- export { BROWSER_PATTERNS, HEADER_PATTERNS, MOBILE_PATTERNS, OS_PATTERNS, SUSPICIOUS_PATTERNS, USER_AGENT_PATTERNS, UUID_PATTERN, VALIDATION_PATTERNS, extractMatch, findMatchingPattern, testPattern, testPatterns };
3
+ export { UUID_PATTERN, VALIDATION_PATTERNS, extractMatch, findMatchingPattern, testPattern, testPatterns };
@@ -1,2 +1,2 @@
1
- import { a as PolicyUnavailableError, i as PolicyFetcherConfig, n as PolicyCacheAdapter, o as isPolicyUnavailableError, r as PolicyFetcher, t as CachedPolicy } from "../fetcher-CZfLcbRZ.mjs";
2
- export { CachedPolicy, PolicyCacheAdapter, PolicyFetcher, PolicyFetcherConfig, PolicyUnavailableError, isPolicyUnavailableError };
1
+ import { a as PolicyFetcherConfig, c as isPolicyUnavailableError, i as PolicyFetcher, n as PolicyAuthError, o as PolicyUnavailableError, r as PolicyCacheAdapter, s as isPolicyAuthError, t as CachedPolicy } from "../fetcher-CTKz07jg.mjs";
2
+ export { CachedPolicy, PolicyAuthError, PolicyCacheAdapter, PolicyFetcher, PolicyFetcherConfig, PolicyUnavailableError, isPolicyAuthError, isPolicyUnavailableError };
@@ -1,2 +1,2 @@
1
- import { a as PolicyUnavailableError, i as PolicyFetcherConfig, n as PolicyCacheAdapter, o as isPolicyUnavailableError, r as PolicyFetcher, t as CachedPolicy } from "../fetcher-CCw4Q95g.js";
2
- export { CachedPolicy, PolicyCacheAdapter, PolicyFetcher, PolicyFetcherConfig, PolicyUnavailableError, isPolicyUnavailableError };
1
+ import { a as PolicyFetcherConfig, c as isPolicyUnavailableError, i as PolicyFetcher, n as PolicyAuthError, o as PolicyUnavailableError, r as PolicyCacheAdapter, s as isPolicyAuthError, t as CachedPolicy } from "../fetcher-DCr920hx.js";
2
+ export { CachedPolicy, PolicyAuthError, PolicyCacheAdapter, PolicyFetcher, PolicyFetcherConfig, PolicyUnavailableError, isPolicyAuthError, isPolicyUnavailableError };
@@ -12,6 +12,9 @@ const require_schemas = require('../schemas-Cm4C4Z5G.js');
12
12
  * - In-memory caching with TTL
13
13
  * - Origin reads for legacy adapters that cannot coordinate shared invalidation
14
14
  * - Fallback to default policy on errors
15
+ * - A short, jittered memory of failed loads: a refused key or a timeout costs
16
+ * one origin call and one log line per window, and any other failure is
17
+ * retried on the next load but logged once per window
15
18
  * - Configurable API endpoints
16
19
  */
17
20
  function looksLikePolicyApiBody(data) {
@@ -45,6 +48,39 @@ function isPolicyUnavailableError(error) {
45
48
  return error instanceof Error && error.name === "PolicyUnavailableError" && "code" in error && error.code === "POLICY_UNAVAILABLE";
46
49
  }
47
50
  /**
51
+ * The policy API refused the request's credentials (HTTP 401 or 403). This is a
52
+ * configuration fault, not an outage, so the message names the key to check.
53
+ */
54
+ var PolicyAuthError = class extends Error {
55
+ code = "POLICY_AUTH_FAILED";
56
+ status;
57
+ constructor(status, apiKeySent) {
58
+ super(apiKeySent ? `The policy API refused the API key (HTTP ${status}); check that CHECKPOINT_API_KEY is this project's API key` : `The policy API requires an API key (HTTP ${status}); set apiKey (CHECKPOINT_API_KEY)`);
59
+ this.name = "PolicyAuthError";
60
+ this.status = status;
61
+ }
62
+ };
63
+ /** Recognize the same failure across independently loaded SDK package copies. */
64
+ function isPolicyAuthError(error) {
65
+ return error instanceof Error && error.name === "PolicyAuthError" && "code" in error && error.code === "POLICY_AUTH_FAILED";
66
+ }
67
+ /**
68
+ * How long a failed load is remembered. After a refused key or a timeout, a
69
+ * load within the window gets the same outcome without a fetch or a log line,
70
+ * so a wrong key or a hung origin costs one origin call and one log line per
71
+ * window rather than one per request (and no request waits out another
72
+ * timeout). A refused key waits longer, since it does not recover until the
73
+ * host is reconfigured. Any other failure (a 5xx, a network error, a body
74
+ * that is not a policy) is often transient, so the next load reads the origin
75
+ * again; only its repeat log lines are suppressed for the window.
76
+ */
77
+ const FAILURE_RETRY_MS = {
78
+ unavailable: 5e3,
79
+ auth: 6e4
80
+ };
81
+ /** Each window is stretched or shortened by up to this fraction, so instances spread their retries. */
82
+ const FAILURE_RETRY_JITTER = .2;
83
+ /**
48
84
  * Simple in-memory cache with TTL support
49
85
  */
50
86
  var MemoryCache = class {
@@ -52,7 +88,7 @@ var MemoryCache = class {
52
88
  get(key) {
53
89
  const entry = this.cache.get(key);
54
90
  if (!entry) return null;
55
- if (Date.now() > entry.expiresAt) {
91
+ if (Date.now() >= entry.expiresAt) {
56
92
  this.cache.delete(key);
57
93
  return null;
58
94
  }
@@ -84,6 +120,8 @@ function nextCacheRevision() {
84
120
  var PolicyFetcher = class {
85
121
  config;
86
122
  memoryCache;
123
+ /** Recent failed loads by cache key; see {@link FAILURE_RETRY_MS}. */
124
+ failures = /* @__PURE__ */ new Map();
87
125
  constructor(config) {
88
126
  this.config = {
89
127
  apiBaseUrl: config.apiBaseUrl,
@@ -139,10 +177,13 @@ var PolicyFetcher = class {
139
177
  if (!this.isExpired(cached.expiresAt)) return cached.policy;
140
178
  }
141
179
  }
180
+ const recent = this.recentFailure(cacheKey);
181
+ if (recent && recent.kind !== "failed") return this.failedLoad(recent);
142
182
  try {
143
183
  const policy = await Promise.race([this.fetchPolicyFromApi(projectId, controller.signal), expired]);
144
184
  requireActiveLoad();
145
185
  if (cacheKey !== this.getCacheKey(projectId)) continue;
186
+ if (this.failures.has(cacheKey)) this.failures.delete(cacheKey);
146
187
  if (useMemoryCache) {
147
188
  const now = /* @__PURE__ */ new Date();
148
189
  const cached = {
@@ -158,12 +199,16 @@ var PolicyFetcher = class {
158
199
  requireActiveLoad();
159
200
  return policy;
160
201
  } catch (error) {
161
- requireActiveLoad();
162
- if (isPolicyUnavailableError(error)) throw error;
163
- if (cacheKey !== this.getCacheKey(projectId)) continue;
164
- console.error(`[PolicyFetcher] Failed to fetch policy for ${projectId}:`, error);
165
- if (this.config.throwOnUnavailable) throw new PolicyUnavailableError();
166
- return this.getDefaultPolicy();
202
+ const timedOut = controller.signal.aborted || Date.now() >= deadline || isPolicyUnavailableError(error);
203
+ const current = cacheKey === this.getCacheKey(projectId);
204
+ if (!timedOut && !current) continue;
205
+ const failure = timedOut ? { kind: "timeout" } : isPolicyAuthError(error) ? {
206
+ kind: "auth",
207
+ status: error.status,
208
+ apiKeySent: Boolean(this.config.apiKey)
209
+ } : { kind: "failed" };
210
+ if (current) this.rememberFailure(cacheKey, projectId, failure, error);
211
+ return this.failedLoad(failure);
167
212
  }
168
213
  }
169
214
  throw new PolicyUnavailableError();
@@ -187,6 +232,7 @@ var PolicyFetcher = class {
187
232
  signal,
188
233
  cache: "no-store"
189
234
  });
235
+ if (response.status === 401 || response.status === 403) throw new PolicyAuthError(response.status, Boolean(this.config.apiKey));
190
236
  if (!response.ok) throw new Error(`API returned ${response.status}: ${response.statusText}`);
191
237
  const data = await response.json();
192
238
  if (!looksLikePolicyApiBody(data)) throw new Error("Policy response is not from the policy API");
@@ -200,6 +246,49 @@ var PolicyFetcher = class {
200
246
  getDefaultPolicy() {
201
247
  return require_schemas.PolicyConfigSchema.parse(require_schemas.DEFAULT_POLICY);
202
248
  }
249
+ /** The failure remembered for this key, while its window lasts. */
250
+ recentFailure(cacheKey) {
251
+ const entry = this.failures.get(cacheKey);
252
+ if (!entry) return void 0;
253
+ if (Date.now() < entry.retryAt) return entry.failure;
254
+ this.failures.delete(cacheKey);
255
+ }
256
+ /**
257
+ * Remember a failed load and log it, once per window: a load that fails the
258
+ * same way while the window is open neither extends it nor logs again, and
259
+ * neither does a fast failure during a refused-key or timeout window. A
260
+ * different failure replaces a fast failure's window and is logged.
261
+ */
262
+ rememberFailure(cacheKey, projectId, failure, error) {
263
+ const recent = this.recentFailure(cacheKey);
264
+ if (recent && (recent.kind === failure.kind || failure.kind === "failed")) return;
265
+ const now = Date.now();
266
+ for (const [key, entry] of this.failures) if (now >= entry.retryAt) this.failures.delete(key);
267
+ const windowMs = FAILURE_RETRY_MS[failure.kind === "auth" ? "auth" : "unavailable"];
268
+ const jitter = 1 + FAILURE_RETRY_JITTER * (2 * Math.random() - 1);
269
+ this.failures.set(cacheKey, {
270
+ failure,
271
+ retryAt: now + Math.round(windowMs * jitter)
272
+ });
273
+ const retry = `retrying after about ${windowMs / 1e3} s`;
274
+ if (failure.kind === "auth") {
275
+ const refused = new PolicyAuthError(failure.status, failure.apiKeySent);
276
+ console.error(`[PolicyFetcher] Policy for ${projectId} not loaded: ${refused.message}; ${retry}`);
277
+ } else if (failure.kind === "timeout") console.error(`[PolicyFetcher] Policy for ${projectId} did not load within ${this.config.timeoutMs} ms; ${retry}`);
278
+ else console.error(`[PolicyFetcher] Failed to fetch policy for ${projectId}; further failures in the next ${windowMs / 1e3} s are not logged:`, error);
279
+ }
280
+ /**
281
+ * The outcome of a failed load. A timeout always rejects. A refused key
282
+ * rejects with {@link PolicyAuthError} and any other failure with
283
+ * {@link PolicyUnavailableError} when `throwOnUnavailable` is set; otherwise
284
+ * both return the default policy.
285
+ */
286
+ failedLoad(failure) {
287
+ if (failure.kind === "timeout") throw new PolicyUnavailableError();
288
+ if (!this.config.throwOnUnavailable) return this.getDefaultPolicy();
289
+ if (failure.kind === "auth") throw new PolicyAuthError(failure.status, failure.apiKeySent);
290
+ throw new PolicyUnavailableError();
291
+ }
203
292
  /**
204
293
  * Retire this runtime's cached policy key before any asynchronous cleanup.
205
294
  * Older reads and writes cannot restore the retired entry for these fetchers.
@@ -225,16 +314,19 @@ var PolicyFetcher = class {
225
314
  */
226
315
  clearCache() {
227
316
  if (!this.config.disableMemoryCache) this.memoryCache.clear();
317
+ this.failures.clear();
228
318
  }
229
319
  /**
230
320
  * Check if a date string is expired
231
321
  */
232
322
  isExpired(dateString) {
233
- return new Date(dateString).getTime() < Date.now();
323
+ return new Date(dateString).getTime() <= Date.now();
234
324
  }
235
325
  };
236
326
 
237
327
  //#endregion
328
+ exports.PolicyAuthError = PolicyAuthError;
238
329
  exports.PolicyFetcher = PolicyFetcher;
239
330
  exports.PolicyUnavailableError = PolicyUnavailableError;
331
+ exports.isPolicyAuthError = isPolicyAuthError;
240
332
  exports.isPolicyUnavailableError = isPolicyUnavailableError;
@@ -11,6 +11,9 @@ import { E as DEFAULT_POLICY, S as CACHE_TTL, m as PolicyConfigSchema, x as safe
11
11
  * - In-memory caching with TTL
12
12
  * - Origin reads for legacy adapters that cannot coordinate shared invalidation
13
13
  * - Fallback to default policy on errors
14
+ * - A short, jittered memory of failed loads: a refused key or a timeout costs
15
+ * one origin call and one log line per window, and any other failure is
16
+ * retried on the next load but logged once per window
14
17
  * - Configurable API endpoints
15
18
  */
16
19
  function looksLikePolicyApiBody(data) {
@@ -44,6 +47,39 @@ function isPolicyUnavailableError(error) {
44
47
  return error instanceof Error && error.name === "PolicyUnavailableError" && "code" in error && error.code === "POLICY_UNAVAILABLE";
45
48
  }
46
49
  /**
50
+ * The policy API refused the request's credentials (HTTP 401 or 403). This is a
51
+ * configuration fault, not an outage, so the message names the key to check.
52
+ */
53
+ var PolicyAuthError = class extends Error {
54
+ code = "POLICY_AUTH_FAILED";
55
+ status;
56
+ constructor(status, apiKeySent) {
57
+ super(apiKeySent ? `The policy API refused the API key (HTTP ${status}); check that CHECKPOINT_API_KEY is this project's API key` : `The policy API requires an API key (HTTP ${status}); set apiKey (CHECKPOINT_API_KEY)`);
58
+ this.name = "PolicyAuthError";
59
+ this.status = status;
60
+ }
61
+ };
62
+ /** Recognize the same failure across independently loaded SDK package copies. */
63
+ function isPolicyAuthError(error) {
64
+ return error instanceof Error && error.name === "PolicyAuthError" && "code" in error && error.code === "POLICY_AUTH_FAILED";
65
+ }
66
+ /**
67
+ * How long a failed load is remembered. After a refused key or a timeout, a
68
+ * load within the window gets the same outcome without a fetch or a log line,
69
+ * so a wrong key or a hung origin costs one origin call and one log line per
70
+ * window rather than one per request (and no request waits out another
71
+ * timeout). A refused key waits longer, since it does not recover until the
72
+ * host is reconfigured. Any other failure (a 5xx, a network error, a body
73
+ * that is not a policy) is often transient, so the next load reads the origin
74
+ * again; only its repeat log lines are suppressed for the window.
75
+ */
76
+ const FAILURE_RETRY_MS = {
77
+ unavailable: 5e3,
78
+ auth: 6e4
79
+ };
80
+ /** Each window is stretched or shortened by up to this fraction, so instances spread their retries. */
81
+ const FAILURE_RETRY_JITTER = .2;
82
+ /**
47
83
  * Simple in-memory cache with TTL support
48
84
  */
49
85
  var MemoryCache = class {
@@ -51,7 +87,7 @@ var MemoryCache = class {
51
87
  get(key) {
52
88
  const entry = this.cache.get(key);
53
89
  if (!entry) return null;
54
- if (Date.now() > entry.expiresAt) {
90
+ if (Date.now() >= entry.expiresAt) {
55
91
  this.cache.delete(key);
56
92
  return null;
57
93
  }
@@ -83,6 +119,8 @@ function nextCacheRevision() {
83
119
  var PolicyFetcher = class {
84
120
  config;
85
121
  memoryCache;
122
+ /** Recent failed loads by cache key; see {@link FAILURE_RETRY_MS}. */
123
+ failures = /* @__PURE__ */ new Map();
86
124
  constructor(config) {
87
125
  this.config = {
88
126
  apiBaseUrl: config.apiBaseUrl,
@@ -138,10 +176,13 @@ var PolicyFetcher = class {
138
176
  if (!this.isExpired(cached.expiresAt)) return cached.policy;
139
177
  }
140
178
  }
179
+ const recent = this.recentFailure(cacheKey);
180
+ if (recent && recent.kind !== "failed") return this.failedLoad(recent);
141
181
  try {
142
182
  const policy = await Promise.race([this.fetchPolicyFromApi(projectId, controller.signal), expired]);
143
183
  requireActiveLoad();
144
184
  if (cacheKey !== this.getCacheKey(projectId)) continue;
185
+ if (this.failures.has(cacheKey)) this.failures.delete(cacheKey);
145
186
  if (useMemoryCache) {
146
187
  const now = /* @__PURE__ */ new Date();
147
188
  const cached = {
@@ -157,12 +198,16 @@ var PolicyFetcher = class {
157
198
  requireActiveLoad();
158
199
  return policy;
159
200
  } catch (error) {
160
- requireActiveLoad();
161
- if (isPolicyUnavailableError(error)) throw error;
162
- if (cacheKey !== this.getCacheKey(projectId)) continue;
163
- console.error(`[PolicyFetcher] Failed to fetch policy for ${projectId}:`, error);
164
- if (this.config.throwOnUnavailable) throw new PolicyUnavailableError();
165
- return this.getDefaultPolicy();
201
+ const timedOut = controller.signal.aborted || Date.now() >= deadline || isPolicyUnavailableError(error);
202
+ const current = cacheKey === this.getCacheKey(projectId);
203
+ if (!timedOut && !current) continue;
204
+ const failure = timedOut ? { kind: "timeout" } : isPolicyAuthError(error) ? {
205
+ kind: "auth",
206
+ status: error.status,
207
+ apiKeySent: Boolean(this.config.apiKey)
208
+ } : { kind: "failed" };
209
+ if (current) this.rememberFailure(cacheKey, projectId, failure, error);
210
+ return this.failedLoad(failure);
166
211
  }
167
212
  }
168
213
  throw new PolicyUnavailableError();
@@ -186,6 +231,7 @@ var PolicyFetcher = class {
186
231
  signal,
187
232
  cache: "no-store"
188
233
  });
234
+ if (response.status === 401 || response.status === 403) throw new PolicyAuthError(response.status, Boolean(this.config.apiKey));
189
235
  if (!response.ok) throw new Error(`API returned ${response.status}: ${response.statusText}`);
190
236
  const data = await response.json();
191
237
  if (!looksLikePolicyApiBody(data)) throw new Error("Policy response is not from the policy API");
@@ -199,6 +245,49 @@ var PolicyFetcher = class {
199
245
  getDefaultPolicy() {
200
246
  return PolicyConfigSchema.parse(DEFAULT_POLICY);
201
247
  }
248
+ /** The failure remembered for this key, while its window lasts. */
249
+ recentFailure(cacheKey) {
250
+ const entry = this.failures.get(cacheKey);
251
+ if (!entry) return void 0;
252
+ if (Date.now() < entry.retryAt) return entry.failure;
253
+ this.failures.delete(cacheKey);
254
+ }
255
+ /**
256
+ * Remember a failed load and log it, once per window: a load that fails the
257
+ * same way while the window is open neither extends it nor logs again, and
258
+ * neither does a fast failure during a refused-key or timeout window. A
259
+ * different failure replaces a fast failure's window and is logged.
260
+ */
261
+ rememberFailure(cacheKey, projectId, failure, error) {
262
+ const recent = this.recentFailure(cacheKey);
263
+ if (recent && (recent.kind === failure.kind || failure.kind === "failed")) return;
264
+ const now = Date.now();
265
+ for (const [key, entry] of this.failures) if (now >= entry.retryAt) this.failures.delete(key);
266
+ const windowMs = FAILURE_RETRY_MS[failure.kind === "auth" ? "auth" : "unavailable"];
267
+ const jitter = 1 + FAILURE_RETRY_JITTER * (2 * Math.random() - 1);
268
+ this.failures.set(cacheKey, {
269
+ failure,
270
+ retryAt: now + Math.round(windowMs * jitter)
271
+ });
272
+ const retry = `retrying after about ${windowMs / 1e3} s`;
273
+ if (failure.kind === "auth") {
274
+ const refused = new PolicyAuthError(failure.status, failure.apiKeySent);
275
+ console.error(`[PolicyFetcher] Policy for ${projectId} not loaded: ${refused.message}; ${retry}`);
276
+ } else if (failure.kind === "timeout") console.error(`[PolicyFetcher] Policy for ${projectId} did not load within ${this.config.timeoutMs} ms; ${retry}`);
277
+ else console.error(`[PolicyFetcher] Failed to fetch policy for ${projectId}; further failures in the next ${windowMs / 1e3} s are not logged:`, error);
278
+ }
279
+ /**
280
+ * The outcome of a failed load. A timeout always rejects. A refused key
281
+ * rejects with {@link PolicyAuthError} and any other failure with
282
+ * {@link PolicyUnavailableError} when `throwOnUnavailable` is set; otherwise
283
+ * both return the default policy.
284
+ */
285
+ failedLoad(failure) {
286
+ if (failure.kind === "timeout") throw new PolicyUnavailableError();
287
+ if (!this.config.throwOnUnavailable) return this.getDefaultPolicy();
288
+ if (failure.kind === "auth") throw new PolicyAuthError(failure.status, failure.apiKeySent);
289
+ throw new PolicyUnavailableError();
290
+ }
202
291
  /**
203
292
  * Retire this runtime's cached policy key before any asynchronous cleanup.
204
293
  * Older reads and writes cannot restore the retired entry for these fetchers.
@@ -224,15 +313,16 @@ var PolicyFetcher = class {
224
313
  */
225
314
  clearCache() {
226
315
  if (!this.config.disableMemoryCache) this.memoryCache.clear();
316
+ this.failures.clear();
227
317
  }
228
318
  /**
229
319
  * Check if a date string is expired
230
320
  */
231
321
  isExpired(dateString) {
232
- return new Date(dateString).getTime() < Date.now();
322
+ return new Date(dateString).getTime() <= Date.now();
233
323
  }
234
324
  };
235
325
 
236
326
  //#endregion
237
- export { PolicyFetcher, PolicyUnavailableError, isPolicyUnavailableError };
327
+ export { PolicyAuthError, PolicyFetcher, PolicyUnavailableError, isPolicyAuthError, isPolicyUnavailableError };
238
328
  //# sourceMappingURL=fetcher.mjs.map