sentinelayer-cli 0.6.2 → 0.8.1

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 (280) hide show
  1. package/README.md +1009 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/ai-governance/index.js +12 -0
  7. package/src/agents/ai-governance/tools/base.js +171 -0
  8. package/src/agents/ai-governance/tools/eval-regression.js +47 -0
  9. package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
  10. package/src/agents/ai-governance/tools/index.js +52 -0
  11. package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
  12. package/src/agents/ai-governance/tools/provenance-check.js +69 -0
  13. package/src/agents/backend/index.js +12 -0
  14. package/src/agents/backend/tools/base.js +189 -0
  15. package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
  16. package/src/agents/backend/tools/idempotency-audit.js +105 -0
  17. package/src/agents/backend/tools/index.js +87 -0
  18. package/src/agents/backend/tools/retry-audit.js +132 -0
  19. package/src/agents/backend/tools/timeout-audit.js +144 -0
  20. package/src/agents/code-quality/index.js +12 -0
  21. package/src/agents/code-quality/tools/base.js +159 -0
  22. package/src/agents/code-quality/tools/complexity-measure.js +197 -0
  23. package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
  24. package/src/agents/code-quality/tools/cycle-detect.js +49 -0
  25. package/src/agents/code-quality/tools/dep-graph.js +196 -0
  26. package/src/agents/code-quality/tools/index.js +89 -0
  27. package/src/agents/data-layer/index.js +12 -0
  28. package/src/agents/data-layer/tools/base.js +181 -0
  29. package/src/agents/data-layer/tools/index-audit.js +165 -0
  30. package/src/agents/data-layer/tools/index.js +83 -0
  31. package/src/agents/data-layer/tools/migration-scan.js +135 -0
  32. package/src/agents/data-layer/tools/query-explain.js +120 -0
  33. package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
  34. package/src/agents/documentation/index.js +12 -0
  35. package/src/agents/documentation/tools/api-diff.js +91 -0
  36. package/src/agents/documentation/tools/base.js +151 -0
  37. package/src/agents/documentation/tools/dead-link-check.js +58 -0
  38. package/src/agents/documentation/tools/docstring-coverage.js +78 -0
  39. package/src/agents/documentation/tools/index.js +52 -0
  40. package/src/agents/documentation/tools/readme-freshness.js +61 -0
  41. package/src/agents/envelope/fix-cycle.js +45 -0
  42. package/src/agents/envelope/index.js +31 -0
  43. package/src/agents/envelope/loop.js +150 -0
  44. package/src/agents/envelope/pulse.js +18 -0
  45. package/src/agents/envelope/stream.js +40 -0
  46. package/src/agents/infrastructure/index.js +12 -0
  47. package/src/agents/infrastructure/tools/base.js +171 -0
  48. package/src/agents/infrastructure/tools/checkov-run.js +32 -0
  49. package/src/agents/infrastructure/tools/drift-detect.js +59 -0
  50. package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
  51. package/src/agents/infrastructure/tools/index.js +52 -0
  52. package/src/agents/infrastructure/tools/tflint-run.js +31 -0
  53. package/src/agents/jules/config/definition.js +160 -160
  54. package/src/agents/jules/config/system-prompt.js +182 -182
  55. package/src/agents/jules/error-intake.js +51 -51
  56. package/src/agents/jules/fix-cycle.js +17 -17
  57. package/src/agents/jules/loop.js +460 -450
  58. package/src/agents/jules/pulse.js +10 -10
  59. package/src/agents/jules/stream.js +187 -186
  60. package/src/agents/jules/swarm/file-scanner.js +74 -74
  61. package/src/agents/jules/swarm/index.js +11 -11
  62. package/src/agents/jules/swarm/orchestrator.js +362 -362
  63. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  64. package/src/agents/jules/swarm/sub-agent.js +315 -309
  65. package/src/agents/jules/tools/aidenid-email.js +189 -189
  66. package/src/agents/jules/tools/auth-audit.js +1708 -1691
  67. package/src/agents/jules/tools/dispatch.js +340 -335
  68. package/src/agents/jules/tools/file-edit.js +2 -2
  69. package/src/agents/jules/tools/file-read.js +2 -2
  70. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  71. package/src/agents/jules/tools/glob.js +2 -2
  72. package/src/agents/jules/tools/grep.js +2 -2
  73. package/src/agents/jules/tools/index.js +29 -29
  74. package/src/agents/jules/tools/path-guards.js +2 -2
  75. package/src/agents/jules/tools/runtime-audit.js +507 -507
  76. package/src/agents/jules/tools/shell.js +2 -2
  77. package/src/agents/jules/tools/url-policy.js +100 -100
  78. package/src/agents/mode.js +113 -0
  79. package/src/agents/observability/index.js +12 -0
  80. package/src/agents/observability/tools/alert-audit.js +39 -0
  81. package/src/agents/observability/tools/base.js +181 -0
  82. package/src/agents/observability/tools/dashboard-gap.js +42 -0
  83. package/src/agents/observability/tools/index.js +54 -0
  84. package/src/agents/observability/tools/log-schema-check.js +74 -0
  85. package/src/agents/observability/tools/span-coverage.js +74 -0
  86. package/src/agents/persona-visuals.js +102 -61
  87. package/src/agents/release/index.js +12 -0
  88. package/src/agents/release/tools/base.js +181 -0
  89. package/src/agents/release/tools/changelog-diff.js +86 -0
  90. package/src/agents/release/tools/feature-flag-audit.js +126 -0
  91. package/src/agents/release/tools/index.js +61 -0
  92. package/src/agents/release/tools/rollback-verify.js +129 -0
  93. package/src/agents/release/tools/semver-check.js +109 -0
  94. package/src/agents/reliability/index.js +12 -0
  95. package/src/agents/reliability/tools/backpressure-check.js +129 -0
  96. package/src/agents/reliability/tools/base.js +181 -0
  97. package/src/agents/reliability/tools/chaos-probe.js +109 -0
  98. package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
  99. package/src/agents/reliability/tools/health-check-audit.js +111 -0
  100. package/src/agents/reliability/tools/index.js +87 -0
  101. package/src/agents/run-persona.js +109 -0
  102. package/src/agents/security/index.js +12 -0
  103. package/src/agents/security/tools/authz-audit.js +134 -0
  104. package/src/agents/security/tools/base.js +190 -0
  105. package/src/agents/security/tools/crypto-review.js +175 -0
  106. package/src/agents/security/tools/index.js +97 -0
  107. package/src/agents/security/tools/sast-scan.js +175 -0
  108. package/src/agents/security/tools/secrets-scan.js +216 -0
  109. package/src/agents/shared-tools/dispatch-core.js +320 -315
  110. package/src/agents/shared-tools/file-edit.js +180 -180
  111. package/src/agents/shared-tools/file-read.js +100 -100
  112. package/src/agents/shared-tools/glob.js +168 -168
  113. package/src/agents/shared-tools/grep.js +228 -228
  114. package/src/agents/shared-tools/index.js +46 -46
  115. package/src/agents/shared-tools/path-guards.js +161 -161
  116. package/src/agents/shared-tools/shell.js +383 -383
  117. package/src/agents/supply-chain/index.js +12 -0
  118. package/src/agents/supply-chain/tools/attestation-check.js +42 -0
  119. package/src/agents/supply-chain/tools/base.js +151 -0
  120. package/src/agents/supply-chain/tools/index.js +52 -0
  121. package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
  122. package/src/agents/supply-chain/tools/package-verify.js +56 -0
  123. package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
  124. package/src/agents/testing/index.js +12 -0
  125. package/src/agents/testing/tools/base.js +202 -0
  126. package/src/agents/testing/tools/coverage-gap.js +144 -0
  127. package/src/agents/testing/tools/flake-detect.js +125 -0
  128. package/src/agents/testing/tools/index.js +85 -0
  129. package/src/agents/testing/tools/mutation-test.js +143 -0
  130. package/src/agents/testing/tools/snapshot-diff.js +103 -0
  131. package/src/ai/aidenid.js +1021 -1009
  132. package/src/ai/client.js +553 -553
  133. package/src/ai/domain-target-store.js +268 -268
  134. package/src/ai/identity-store.js +270 -270
  135. package/src/ai/proxy.js +137 -137
  136. package/src/ai/site-store.js +145 -145
  137. package/src/audit/agents/architecture.js +180 -180
  138. package/src/audit/agents/compliance.js +179 -179
  139. package/src/audit/agents/documentation.js +165 -165
  140. package/src/audit/agents/performance.js +145 -145
  141. package/src/audit/agents/security.js +215 -215
  142. package/src/audit/agents/testing.js +172 -172
  143. package/src/audit/orchestrator.js +557 -557
  144. package/src/audit/package.js +204 -204
  145. package/src/audit/registry.js +284 -284
  146. package/src/audit/replay.js +103 -103
  147. package/src/auth/gate.js +428 -371
  148. package/src/auth/http.js +681 -611
  149. package/src/auth/service.js +1106 -1106
  150. package/src/auth/session-store.js +813 -813
  151. package/src/cli.js +257 -252
  152. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  153. package/src/commands/ai/provision-governance.js +1272 -1272
  154. package/src/commands/ai/shared.js +147 -147
  155. package/src/commands/ai.js +11 -11
  156. package/src/commands/apply.js +12 -12
  157. package/src/commands/audit.js +1171 -1166
  158. package/src/commands/auth.js +419 -419
  159. package/src/commands/chat.js +184 -191
  160. package/src/commands/config.js +184 -184
  161. package/src/commands/cost.js +311 -311
  162. package/src/commands/daemon/core.js +850 -850
  163. package/src/commands/daemon/extended.js +1048 -1048
  164. package/src/commands/daemon/shared.js +213 -213
  165. package/src/commands/daemon.js +11 -11
  166. package/src/commands/guide.js +174 -174
  167. package/src/commands/ingest.js +58 -58
  168. package/src/commands/init.js +55 -55
  169. package/src/commands/legacy-args.js +20 -10
  170. package/src/commands/mcp.js +461 -461
  171. package/src/commands/omargate.js +63 -29
  172. package/src/commands/persona.js +65 -20
  173. package/src/commands/plugin.js +260 -260
  174. package/src/commands/policy.js +132 -132
  175. package/src/commands/prompt.js +238 -238
  176. package/src/commands/review.js +704 -704
  177. package/src/commands/scan.js +865 -872
  178. package/src/commands/session.js +1238 -0
  179. package/src/commands/spec.js +771 -716
  180. package/src/commands/swarm.js +651 -651
  181. package/src/commands/telemetry.js +202 -202
  182. package/src/commands/watch.js +511 -511
  183. package/src/config/agent-dictionary.js +182 -182
  184. package/src/config/io.js +56 -56
  185. package/src/config/paths.js +18 -18
  186. package/src/config/schema.js +55 -55
  187. package/src/config/service.js +184 -184
  188. package/src/coord/events-log.js +141 -0
  189. package/src/coord/handshake.js +719 -0
  190. package/src/coord/index.js +35 -0
  191. package/src/coord/paths.js +84 -0
  192. package/src/coord/priority.js +62 -0
  193. package/src/coord/tarjan.js +157 -0
  194. package/src/cost/budget.js +235 -235
  195. package/src/cost/history.js +188 -188
  196. package/src/cost/tokenizer.js +160 -0
  197. package/src/cost/tracker.js +232 -171
  198. package/src/daemon/artifact-lineage.js +896 -534
  199. package/src/daemon/assignment-ledger.js +1083 -770
  200. package/src/daemon/ast-drift.js +496 -0
  201. package/src/daemon/ast-parser-layer.js +258 -258
  202. package/src/daemon/budget-governor.js +633 -633
  203. package/src/daemon/callgraph-overlay.js +646 -646
  204. package/src/daemon/error-worker.js +1209 -626
  205. package/src/daemon/fix-cycle.js +384 -377
  206. package/src/daemon/hybrid-mapper.js +929 -929
  207. package/src/daemon/ingest-refresh.js +79 -11
  208. package/src/daemon/jira-lifecycle.js +767 -632
  209. package/src/daemon/operator-control.js +657 -657
  210. package/src/daemon/pulse.js +327 -327
  211. package/src/daemon/reliability-lane.js +471 -471
  212. package/src/daemon/scope-engine.js +1068 -0
  213. package/src/daemon/watchdog.js +971 -971
  214. package/src/events/schema.js +190 -0
  215. package/src/guide/generator.js +316 -316
  216. package/src/ingest/engine.js +933 -918
  217. package/src/ingest/ownership.js +380 -0
  218. package/src/interactive/index.js +97 -97
  219. package/src/legacy-cli.js +3228 -2994
  220. package/src/mcp/registry.js +695 -695
  221. package/src/memory/blackboard.js +301 -301
  222. package/src/memory/retrieval.js +581 -581
  223. package/src/orchestrator/kai-chen.js +126 -0
  224. package/src/plugin/manifest.js +553 -553
  225. package/src/policy/packs.js +144 -144
  226. package/src/prompt/generator.js +136 -118
  227. package/src/review/ai-review.js +672 -679
  228. package/src/review/compliance-pack.js +389 -0
  229. package/src/review/investor-dd-config.js +54 -0
  230. package/src/review/investor-dd-file-loop.js +303 -0
  231. package/src/review/investor-dd-file-router.js +406 -0
  232. package/src/review/investor-dd-html-report.js +233 -0
  233. package/src/review/investor-dd-notification.js +120 -0
  234. package/src/review/investor-dd-orchestrator.js +405 -0
  235. package/src/review/investor-dd-persona-runner.js +275 -0
  236. package/src/review/live-validator.js +253 -0
  237. package/src/review/local-review.js +1351 -1305
  238. package/src/review/omargate-interactive.js +68 -68
  239. package/src/review/omargate-orchestrator.js +492 -300
  240. package/src/review/persona-prompts.js +484 -296
  241. package/src/review/reconciliation-rules.js +329 -0
  242. package/src/review/replay.js +235 -235
  243. package/src/review/report.js +664 -664
  244. package/src/review/reproducibility-chain.js +136 -0
  245. package/src/review/scan-modes.js +147 -42
  246. package/src/review/spec-binding.js +487 -487
  247. package/src/scaffold/generator.js +67 -67
  248. package/src/scaffold/templates.js +150 -150
  249. package/src/scan/generator.js +418 -418
  250. package/src/scan/gh-secrets.js +107 -107
  251. package/src/session/agent-registry.js +359 -0
  252. package/src/session/analytics.js +479 -0
  253. package/src/session/daemon.js +1396 -0
  254. package/src/session/file-locks.js +666 -0
  255. package/src/session/paths.js +37 -0
  256. package/src/session/recap.js +567 -0
  257. package/src/session/redact.js +82 -0
  258. package/src/session/runtime-bridge.js +762 -0
  259. package/src/session/scoring.js +406 -0
  260. package/src/session/setup-guides.js +304 -0
  261. package/src/session/store.js +704 -0
  262. package/src/session/stream.js +333 -0
  263. package/src/session/sync.js +753 -0
  264. package/src/session/tasks.js +1054 -0
  265. package/src/session/templates.js +188 -0
  266. package/src/spec/generator.js +619 -519
  267. package/src/spec/regenerate.js +237 -237
  268. package/src/spec/templates.js +91 -91
  269. package/src/swarm/dashboard.js +247 -247
  270. package/src/swarm/factory.js +363 -363
  271. package/src/swarm/pentest.js +934 -934
  272. package/src/swarm/registry.js +419 -419
  273. package/src/swarm/report.js +158 -158
  274. package/src/swarm/runtime.js +569 -576
  275. package/src/swarm/scenario-dsl.js +272 -272
  276. package/src/telemetry/ledger.js +302 -302
  277. package/src/telemetry/session-tracker.js +234 -234
  278. package/src/telemetry/sync.js +203 -203
  279. package/src/ui/command-hints.js +13 -13
  280. package/src/ui/markdown.js +220 -220
package/src/auth/http.js CHANGED
@@ -1,611 +1,681 @@
1
- import { setTimeout as sleep } from "node:timers/promises";
2
- import crypto from "node:crypto";
3
-
4
- /**
5
- * Default timeout applied to Sentinelayer API requests when no override is provided.
6
- * @type {number}
7
- */
8
- export const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
9
- export const DEFAULT_MAX_RETRIES = 2;
10
- export const DEFAULT_RETRY_DELAY_MS = 250;
11
- export const MAX_RETRY_DELAY_MS = 2_000;
12
- export const CIRCUIT_BREAKER_THRESHOLD = 5;
13
- export const CIRCUIT_BREAKER_COOLDOWN_MS = 30_000;
14
-
15
- const RETRYABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
16
- const CIRCUIT_TRACK_STATUS_CODES = new Set([401, 403, 408, 425, 429, 500, 502, 503, 504]);
17
- const circuitStateByScope = new Map();
18
- const REQUEST_ID_HEADERS = ["x-request-id", "request-id", "x-correlation-id"];
19
- const DEBUG_API_ERRORS_ENV = "SENTINELAYER_DEBUG_ERRORS";
20
- const MAX_API_ERROR_MESSAGE_LENGTH = 512;
21
- const IDEMPOTENCY_KEY_MIN_LENGTH = 32;
22
- const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
23
- const PREFIXED_UUID_V4_PATTERN = /^[a-z0-9][a-z0-9_-]{1,48}-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
24
-
25
- function resolveCircuitScope(url) {
26
- try {
27
- const parsed = new URL(String(url));
28
- return parsed.origin;
29
- } catch {
30
- return "unknown";
31
- }
32
- }
33
-
34
- function getCircuitState(scope) {
35
- const key = String(scope || "unknown");
36
- if (!circuitStateByScope.has(key)) {
37
- circuitStateByScope.set(key, { consecutiveFailures: 0, openedAtMs: 0 });
38
- }
39
- return circuitStateByScope.get(key);
40
- }
41
-
42
- function normalizeApiError(errorPayload = {}) {
43
- const fallbackMessage = "Unknown API error";
44
- if (!errorPayload || typeof errorPayload !== "object" || Array.isArray(errorPayload)) {
45
- return {
46
- code: "UNKNOWN",
47
- message: sanitizeApiErrorMessage(fallbackMessage, fallbackMessage),
48
- requestId: null,
49
- };
50
- }
51
- const rawMessage = String(errorPayload.message || fallbackMessage);
52
- const safeMessage = sanitizeApiErrorMessage(rawMessage, fallbackMessage);
53
- const message = appendDebugContext(safeMessage, {
54
- code: String(errorPayload.code || "UNKNOWN"),
55
- requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
56
- });
57
- return {
58
- code: String(errorPayload.code || "UNKNOWN"),
59
- message,
60
- requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
61
- };
62
- }
63
-
64
- function resolveRequestId(headers) {
65
- if (!headers || typeof headers.get !== "function") {
66
- return null;
67
- }
68
- for (const headerName of REQUEST_ID_HEADERS) {
69
- const value = headers.get(headerName);
70
- if (value) {
71
- return String(value);
72
- }
73
- }
74
- return null;
75
- }
76
-
77
- function resolveIdempotencyKey(headers) {
78
- if (!headers) {
79
- return null;
80
- }
81
- if (typeof headers.get === "function") {
82
- const value =
83
- headers.get("idempotency-key") ||
84
- headers.get("Idempotency-Key") ||
85
- headers.get("IDEMPOTENCY-KEY");
86
- return String(value || "").trim() || null;
87
- }
88
- if (typeof headers !== "object") {
89
- return null;
90
- }
91
- for (const [key, value] of Object.entries(headers)) {
92
- if (String(key || "").toLowerCase() === "idempotency-key") {
93
- const normalized = String(value || "").trim();
94
- return normalized || null;
95
- }
96
- }
97
- return null;
98
- }
99
-
100
- function isValidIdempotencyKey(value) {
101
- const normalized = String(value || "").trim();
102
- if (!normalized) {
103
- return false;
104
- }
105
- if (UUID_V4_PATTERN.test(normalized)) {
106
- return true;
107
- }
108
- if (PREFIXED_UUID_V4_PATTERN.test(normalized)) {
109
- return true;
110
- }
111
- if (normalized.length < IDEMPOTENCY_KEY_MIN_LENGTH) {
112
- return false;
113
- }
114
- return /^[A-Za-z0-9_-]+$/.test(normalized);
115
- }
116
-
117
- function validateIdempotencyKey(value) {
118
- if (!isValidIdempotencyKey(value)) {
119
- throw new SentinelayerApiError("Idempotency-Key must be a UUIDv4 or a prefixed UUID.", {
120
- status: 400,
121
- code: "IDEMPOTENCY_KEY_INVALID",
122
- });
123
- }
124
- }
125
-
126
- function sanitizeOperationName(value) {
127
- const normalized = String(value || "").toLowerCase();
128
- const cleaned = normalized.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
129
- return cleaned.slice(0, 32) || "mutation";
130
- }
131
-
132
- function createIdempotencyKeyForOperation(operationName) {
133
- const op = sanitizeOperationName(operationName);
134
- let suffix;
135
- try {
136
- suffix = crypto.randomUUID();
137
- } catch {
138
- suffix = crypto.randomBytes(16).toString("hex");
139
- }
140
- return `sl-cli-${op}-${suffix}`;
141
- }
142
-
143
- function normalizeHeaderObject(headers) {
144
- if (!headers) {
145
- return {};
146
- }
147
- if (typeof headers.get === "function") {
148
- const normalized = {};
149
- for (const [key, value] of headers.entries()) {
150
- normalized[key] = value;
151
- }
152
- return normalized;
153
- }
154
- if (typeof headers !== "object") {
155
- return {};
156
- }
157
- return { ...headers };
158
- }
159
-
160
- function isMutationVerb(method) {
161
- const normalized = String(method || "").trim().toUpperCase();
162
- return (
163
- normalized === "POST" ||
164
- normalized === "PUT" ||
165
- normalized === "PATCH" ||
166
- normalized === "DELETE"
167
- );
168
- }
169
-
170
- function applyIdempotencyKey(headers, idempotencyKey) {
171
- const normalized = normalizeHeaderObject(headers);
172
- if (idempotencyKey && !resolveIdempotencyKey(normalized)) {
173
- normalized["Idempotency-Key"] = idempotencyKey;
174
- }
175
- return normalized;
176
- }
177
-
178
- export class SentinelayerApiError extends Error {
179
- /**
180
- * @param {string} message
181
- * @param {{ status?: number, code?: string, requestId?: string | null }} [options]
182
- */
183
- constructor(message, { status = 500, code = "UNKNOWN", requestId = null } = {}) {
184
- const safeMessage = sanitizeApiErrorMessage(message, "Sentinelayer API error");
185
- super(appendDebugContext(safeMessage, { code, status, requestId }));
186
- this.name = "SentinelayerApiError";
187
- this.status = Number(status || 500);
188
- this.code = String(code || "UNKNOWN");
189
- this.requestId = requestId ? String(requestId) : null;
190
- }
191
- }
192
-
193
- function normalizePositiveNumber(value, fallback) {
194
- const parsed = Number(value);
195
- if (!Number.isFinite(parsed) || parsed <= 0) {
196
- return fallback;
197
- }
198
- return parsed;
199
- }
200
-
201
- function normalizeNonNegativeInteger(value, fallback) {
202
- const parsed = Number(value);
203
- if (!Number.isFinite(parsed) || parsed < 0) {
204
- return fallback;
205
- }
206
- return Math.floor(parsed);
207
- }
208
-
209
- function parseRetryAfterMs(value) {
210
- const raw = String(value || "").trim();
211
- if (!raw) {
212
- return null;
213
- }
214
- const seconds = Number(raw);
215
- if (Number.isFinite(seconds) && seconds >= 0) {
216
- return Math.round(seconds * 1000);
217
- }
218
- const parsedDate = Date.parse(raw);
219
- if (Number.isFinite(parsedDate)) {
220
- const delta = parsedDate - Date.now();
221
- if (delta > 0) {
222
- return delta;
223
- }
224
- }
225
- return null;
226
- }
227
-
228
- function computeBackoffMs({ attempt, retryDelayMs, retryAfterHeader }) {
229
- const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
230
- if (retryAfterMs !== null) {
231
- return Math.min(retryAfterMs, MAX_RETRY_DELAY_MS);
232
- }
233
- const exponent = Math.max(0, Number(attempt) - 1);
234
- const computed = Math.round(retryDelayMs * Math.pow(2, exponent));
235
- return Math.min(Math.max(1, computed), MAX_RETRY_DELAY_MS);
236
- }
237
-
238
- function isCircuitOpen(scope) {
239
- const circuitState = getCircuitState(scope);
240
- if (circuitState.openedAtMs <= 0) {
241
- return false;
242
- }
243
- if (Date.now() - circuitState.openedAtMs >= CIRCUIT_BREAKER_COOLDOWN_MS) {
244
- circuitState.openedAtMs = 0;
245
- circuitState.consecutiveFailures = 0;
246
- return false;
247
- }
248
- return true;
249
- }
250
-
251
- function recordFailureForCircuit(scope) {
252
- const circuitState = getCircuitState(scope);
253
- circuitState.consecutiveFailures += 1;
254
- if (circuitState.consecutiveFailures >= CIRCUIT_BREAKER_THRESHOLD) {
255
- circuitState.openedAtMs = Date.now();
256
- }
257
- }
258
-
259
- function shouldExposeApiErrorDetails() {
260
- const normalized = String(process.env[DEBUG_API_ERRORS_ENV] || "").trim().toLowerCase();
261
- return normalized === "true" || normalized === "1" || normalized === "yes";
262
- }
263
-
264
- function isTestNonIdempotentAllowed() {
265
- return (
266
- process.env.NODE_ENV === "test" &&
267
- process.env.SENTINELAYER_ALLOW_NON_IDEMPOTENT === "1" &&
268
- process.env.SENTINELAYER_CLI_TEST_MODE === "1" &&
269
- !process.env.CI
270
- );
271
- }
272
-
273
- function sanitizeApiErrorMessage(message, fallback = "Sentinelayer API error") {
274
- const fallbackMessage = String(fallback || "Sentinelayer API error");
275
- const normalized = String(message || "").trim();
276
- const candidate = normalized || fallbackMessage;
277
- const sanitized = candidate
278
- .replace(/\bbearer\s+[a-z0-9._~+/=-]+\b/gi, "bearer [REDACTED]")
279
- .replace(/\b(token|secret|password|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)\b\s*[:=]\s*["']?[^"'\s,;]+["']?/gi, "$1=[REDACTED]")
280
- .replace(/\b[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+\b/gi, "[REDACTED_JWT]")
281
- .replace(/\bhttps?:\/\/[^\s"'`]+/gi, () => "<redacted-url>")
282
- .replace(/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/gi, "<redacted-email>");
283
- if (sanitized.length <= MAX_API_ERROR_MESSAGE_LENGTH) {
284
- return sanitized;
285
- }
286
- return `${sanitized.slice(0, MAX_API_ERROR_MESSAGE_LENGTH - 3)}...`;
287
- }
288
-
289
- function anonymizeRequestIdForDebug(requestId) {
290
- const normalized = String(requestId || "").trim();
291
- if (!normalized) {
292
- return "";
293
- }
294
- return crypto.createHash("sha256").update(normalized).digest("hex").slice(0, 12);
295
- }
296
-
297
- function appendDebugContext(safeMessage, { code, status, requestId } = {}) {
298
- if (!shouldExposeApiErrorDetails()) {
299
- return safeMessage;
300
- }
301
- const parts = [];
302
- const normalizedCode = String(code || "").trim();
303
- const normalizedStatus = Number.isFinite(Number(status)) ? Number(status) : null;
304
- const requestIdHash = anonymizeRequestIdForDebug(requestId);
305
- if (normalizedCode) parts.push(`code=${normalizedCode}`);
306
- if (normalizedStatus) parts.push(`status=${normalizedStatus}`);
307
- if (requestIdHash) parts.push(`request_id_hash=${requestIdHash}`);
308
- if (parts.length === 0) return safeMessage;
309
- return `${safeMessage} (${parts.join(", ")})`;
310
- }
311
-
312
- function recordSuccessForCircuit(scope) {
313
- const circuitState = getCircuitState(scope);
314
- circuitState.consecutiveFailures = 0;
315
- circuitState.openedAtMs = 0;
316
- }
317
-
318
- function shouldRetryStatus(statusCode) {
319
- return RETRYABLE_STATUS_CODES.has(Number(statusCode || 0));
320
- }
321
-
322
- function shouldRecordFailureForStatus(statusCode) {
323
- return CIRCUIT_TRACK_STATUS_CODES.has(Number(statusCode || 0));
324
- }
325
-
326
- export function __resetRequestCircuitForTests(scope) {
327
- if (scope) {
328
- const circuitState = getCircuitState(scope);
329
- circuitState.consecutiveFailures = 0;
330
- circuitState.openedAtMs = 0;
331
- return;
332
- }
333
- circuitStateByScope.clear();
334
- }
335
-
336
- /**
337
- * Execute an HTTP request against the Sentinelayer API and parse a JSON response.
338
- * Throws `SentinelayerApiError` for transport errors, timeouts, API failures, and invalid JSON.
339
- *
340
- * @param {string} url
341
- * @param {{
342
- * method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
343
- * headers?: Record<string, string>,
344
- * body?: unknown,
345
- * idempotencyKey?: string | null,
346
- * allowNonIdempotent?: boolean,
347
- * timeoutMs?: number
348
- * maxRetries?: number,
349
- * retryDelayMs?: number
350
- * allowEmptyBody?: boolean
351
- * }} [options]
352
- * @returns {Promise<any>}
353
- */
354
- export async function requestJson(
355
- url,
356
- {
357
- method = "GET",
358
- headers = {},
359
- body,
360
- idempotencyKey = null,
361
- allowNonIdempotent = false,
362
- timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
363
- maxRetries = DEFAULT_MAX_RETRIES,
364
- retryDelayMs = DEFAULT_RETRY_DELAY_MS,
365
- allowEmptyBody = false,
366
- } = {}
367
- ) {
368
- const normalizedMethod = String(method || "GET").trim().toUpperCase();
369
- const explicitIdempotencyKey = String(idempotencyKey || "").trim() || null;
370
- const existingIdempotencyKey = explicitIdempotencyKey || resolveIdempotencyKey(headers);
371
- const isMutationMethod = isMutationVerb(normalizedMethod);
372
- const resolvedIdempotencyKey = existingIdempotencyKey;
373
- const requestHeaders = applyIdempotencyKey(headers, resolvedIdempotencyKey);
374
- const outgoingHeaders = { ...requestHeaders };
375
- if (body !== undefined) {
376
- outgoingHeaders["Content-Type"] = "application/json";
377
- }
378
- const isIdempotentMutation = Boolean(resolvedIdempotencyKey);
379
- const allowUnsafeMutation = Boolean(allowNonIdempotent) && isTestNonIdempotentAllowed();
380
- if (isMutationMethod && !isIdempotentMutation && !allowUnsafeMutation) {
381
- throw new SentinelayerApiError("Idempotency-Key is required for mutation requests.", {
382
- status: 400,
383
- code: "IDEMPOTENCY_KEY_REQUIRED",
384
- });
385
- }
386
- if (isMutationMethod && isIdempotentMutation) {
387
- validateIdempotencyKey(resolvedIdempotencyKey);
388
- }
389
- const retryableMethod =
390
- normalizedMethod === "GET" ||
391
- normalizedMethod === "HEAD" ||
392
- normalizedMethod === "OPTIONS" ||
393
- (isIdempotentMutation &&
394
- (normalizedMethod === "POST" ||
395
- normalizedMethod === "PUT" ||
396
- normalizedMethod === "PATCH" ||
397
- normalizedMethod === "DELETE"));
398
- const circuitScope = resolveCircuitScope(url);
399
- if (isCircuitOpen(circuitScope)) {
400
- throw new SentinelayerApiError("Request circuit breaker is open after consecutive API failures.", {
401
- status: 503,
402
- code: "CIRCUIT_OPEN",
403
- });
404
- }
405
-
406
- const normalizedTimeoutMs = normalizePositiveNumber(timeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
407
- const normalizedMaxRetries = normalizeNonNegativeInteger(maxRetries, DEFAULT_MAX_RETRIES);
408
- const normalizedRetryDelayMs = normalizePositiveNumber(retryDelayMs, DEFAULT_RETRY_DELAY_MS);
409
-
410
- let lastRetryableError = null;
411
- for (let attempt = 0; attempt <= normalizedMaxRetries; attempt += 1) {
412
- const controller = new AbortController();
413
- let timeoutTriggered = false;
414
- let timeoutHandle;
415
- timeoutHandle = setTimeout(() => {
416
- timeoutTriggered = true;
417
- controller.abort();
418
- }, normalizedTimeoutMs);
419
-
420
- try {
421
- const response = await fetch(String(url), {
422
- method: normalizedMethod,
423
- headers: outgoingHeaders,
424
- body: body === undefined ? undefined : JSON.stringify(body),
425
- redirect: "error",
426
- signal: controller.signal,
427
- });
428
-
429
- const rawBody = await response.text();
430
- const trimmedBody = rawBody.trim();
431
- const contentType = response.headers.get("content-type") || "";
432
- const isJson = /application\/json/i.test(contentType);
433
- let json = {};
434
- if (!trimmedBody) {
435
- const statusCode = Number(response.status || 0);
436
- const allowEmpty = Boolean(allowEmptyBody) || statusCode === 204 || statusCode === 205;
437
- if (response.ok && !allowEmpty) {
438
- const requestId = resolveRequestId(response.headers);
439
- throw new SentinelayerApiError("Empty response body returned by API.", {
440
- status: response.status,
441
- code: "EMPTY_BODY",
442
- requestId,
443
- });
444
- }
445
- } else {
446
- if (response.ok && !isJson) {
447
- const requestId = resolveRequestId(response.headers);
448
- throw new SentinelayerApiError("Invalid content-type returned by API.", {
449
- status: response.status,
450
- code: "INVALID_CONTENT_TYPE",
451
- requestId,
452
- });
453
- }
454
- if (isJson) {
455
- try {
456
- json = JSON.parse(rawBody);
457
- } catch {
458
- const requestId = resolveRequestId(response.headers);
459
- if (response.ok) {
460
- throw new SentinelayerApiError("Invalid JSON returned by API.", {
461
- status: response.status,
462
- code: "INVALID_JSON",
463
- requestId,
464
- });
465
- }
466
- }
467
- }
468
- }
469
-
470
- if (response.ok) {
471
- recordSuccessForCircuit(circuitScope);
472
- return json;
473
- }
474
-
475
- const apiError = normalizeApiError(json && typeof json === "object" ? json.error : {});
476
- const requestId = apiError.requestId || resolveRequestId(response.headers);
477
- const statusCode = Number(response.status || 500);
478
- const retryable = retryableMethod && shouldRetryStatus(statusCode);
479
- const shouldRecordCircuitFailure = shouldRecordFailureForStatus(statusCode);
480
- const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
481
- const error = new SentinelayerApiError(apiError.message, {
482
- status: statusCode,
483
- code: apiError.code,
484
- requestId,
485
- });
486
- error.retryAfterMs = retryAfterMs;
487
-
488
- if (!retryable || attempt >= normalizedMaxRetries) {
489
- if (shouldRecordCircuitFailure) {
490
- recordFailureForCircuit(circuitScope);
491
- }
492
- throw error;
493
- }
494
-
495
- lastRetryableError = error;
496
- const delayMs = computeBackoffMs({
497
- attempt: attempt + 1,
498
- retryDelayMs: normalizedRetryDelayMs,
499
- retryAfterHeader: response.headers.get("retry-after"),
500
- });
501
- await sleep(delayMs);
502
- continue;
503
- } catch (error) {
504
- if (error instanceof SentinelayerApiError) {
505
- throw error;
506
- }
507
-
508
- const isAbortError = Boolean(error && typeof error === "object" && error.name === "AbortError");
509
- const abortMessage = error instanceof Error ? error.message : String(error || "");
510
- const abortReason =
511
- isAbortError && !timeoutTriggered && /cancel/i.test(abortMessage) ? "CANCELLED" : "TIMEOUT";
512
- const abortCode = isAbortError ? abortReason : "NETWORK_ERROR";
513
- const abortStatus = isAbortError ? (abortReason === "CANCELLED" ? 499 : 408) : 503;
514
- const normalizedError = new SentinelayerApiError(
515
- isAbortError
516
- ? (abortReason === "CANCELLED" ? "Request cancelled." : "Request timed out.")
517
- : (error instanceof Error ? error.message : String(error || "Request failed")),
518
- {
519
- status: abortStatus,
520
- code: abortCode,
521
- }
522
- );
523
-
524
- if (!retryableMethod || attempt >= normalizedMaxRetries) {
525
- recordFailureForCircuit(circuitScope);
526
- throw normalizedError;
527
- }
528
-
529
- lastRetryableError = normalizedError;
530
- const delayMs = computeBackoffMs({
531
- attempt: attempt + 1,
532
- retryDelayMs: normalizedRetryDelayMs,
533
- retryAfterHeader: null,
534
- });
535
- await sleep(delayMs);
536
- continue;
537
- } finally {
538
- if (timeoutHandle) {
539
- clearTimeout(timeoutHandle);
540
- }
541
- await sleep(0);
542
- }
543
- }
544
-
545
- if (lastRetryableError instanceof SentinelayerApiError) {
546
- throw lastRetryableError;
547
- }
548
- throw new SentinelayerApiError("Request failed without a terminal response.", {
549
- status: 503,
550
- code: "NETWORK_ERROR",
551
- });
552
- }
553
-
554
- /**
555
- * Execute an HTTP mutation request and auto-derive an idempotency key when missing.
556
- *
557
- * @param {string} url
558
- * @param {{
559
- * method?: "POST" | "PUT" | "PATCH" | "DELETE",
560
- * headers?: Record<string, string>,
561
- * body?: unknown,
562
- * idempotencyKey?: string | null,
563
- * operationName: string,
564
- * timeoutMs?: number
565
- * maxRetries?: number,
566
- * retryDelayMs?: number
567
- * allowEmptyBody?: boolean
568
- * }} options
569
- * @returns {Promise<any>}
570
- */
571
- export async function requestJsonMutation(
572
- url,
573
- {
574
- method = "POST",
575
- headers = {},
576
- body,
577
- idempotencyKey = null,
578
- operationName,
579
- timeoutMs,
580
- maxRetries,
581
- retryDelayMs,
582
- allowEmptyBody = false,
583
- } = {}
584
- ) {
585
- const normalizedMethod = String(method || "POST").trim().toUpperCase();
586
- if (!isMutationVerb(normalizedMethod)) {
587
- throw new SentinelayerApiError("requestJsonMutation requires a mutation HTTP method.", {
588
- status: 400,
589
- code: "INVALID_MUTATION_METHOD",
590
- });
591
- }
592
- const resolvedOperation = String(operationName || "").trim();
593
- if (!resolvedOperation) {
594
- throw new SentinelayerApiError("requestJsonMutation requires an operationName.", {
595
- status: 400,
596
- code: "OPERATION_NAME_REQUIRED",
597
- });
598
- }
599
- const resolvedIdempotencyKey =
600
- String(idempotencyKey || "").trim() || createIdempotencyKeyForOperation(resolvedOperation);
601
- return requestJson(url, {
602
- method: normalizedMethod,
603
- headers,
604
- body,
605
- idempotencyKey: resolvedIdempotencyKey,
606
- timeoutMs,
607
- maxRetries,
608
- retryDelayMs,
609
- allowEmptyBody,
610
- });
611
- }
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ /**
8
+ * Default timeout applied to Sentinelayer API requests when no override is provided.
9
+ * @type {number}
10
+ */
11
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
12
+ export const DEFAULT_MAX_RETRIES = 2;
13
+ export const DEFAULT_RETRY_DELAY_MS = 250;
14
+ export const MAX_RETRY_DELAY_MS = 2_000;
15
+ export const CIRCUIT_BREAKER_THRESHOLD = 5;
16
+ export const CIRCUIT_BREAKER_COOLDOWN_MS = 30_000;
17
+
18
+ const RETRYABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
19
+ const CIRCUIT_TRACK_STATUS_CODES = new Set([401, 403, 408, 425, 429, 500, 502, 503, 504]);
20
+ const circuitStateByScope = new Map();
21
+
22
+ // File-backed cache. Lets cooldown + failure counts survive across CLI
23
+ // invocations without it, each new process hammers a degraded upstream
24
+ // until it hits the threshold again. Best-effort: if file ops fail, we
25
+ // silently fall back to in-memory behavior (no hard dependency).
26
+ const CIRCUIT_STATE_FILE = (() => {
27
+ const base = process.env.SENTINELAYER_CIRCUIT_STATE_DIR ||
28
+ path.join(os.homedir() || os.tmpdir(), ".sentinelayer");
29
+ try {
30
+ fs.mkdirSync(base, { recursive: true });
31
+ } catch {
32
+ /* noop */
33
+ }
34
+ return path.join(base, "circuit-state.json");
35
+ })();
36
+ let circuitStateLoaded = false;
37
+
38
+ function loadCircuitStateFromDisk() {
39
+ if (circuitStateLoaded) return;
40
+ circuitStateLoaded = true;
41
+ try {
42
+ const raw = fs.readFileSync(CIRCUIT_STATE_FILE, "utf-8");
43
+ const parsed = JSON.parse(raw);
44
+ if (!parsed || typeof parsed !== "object") return;
45
+ const now = Date.now();
46
+ for (const [key, value] of Object.entries(parsed)) {
47
+ if (!value || typeof value !== "object") continue;
48
+ const consecutiveFailures = Number(value.consecutiveFailures) || 0;
49
+ const openedAtMs = Number(value.openedAtMs) || 0;
50
+ // TTL: only carry over entries within the cooldown window — older
51
+ // entries are stale and should reset naturally on this process.
52
+ if (openedAtMs > 0 && now - openedAtMs < CIRCUIT_BREAKER_COOLDOWN_MS) {
53
+ circuitStateByScope.set(String(key), { consecutiveFailures, openedAtMs });
54
+ }
55
+ }
56
+ } catch {
57
+ /* noop: missing, corrupt, or unreadable — start fresh */
58
+ }
59
+ }
60
+
61
+ function persistCircuitState() {
62
+ try {
63
+ const snapshot = {};
64
+ for (const [key, value] of circuitStateByScope.entries()) {
65
+ snapshot[key] = {
66
+ consecutiveFailures: value.consecutiveFailures || 0,
67
+ openedAtMs: value.openedAtMs || 0,
68
+ };
69
+ }
70
+ const tmp = `${CIRCUIT_STATE_FILE}.${process.pid}.tmp`;
71
+ fs.writeFileSync(tmp, JSON.stringify(snapshot), "utf-8");
72
+ fs.renameSync(tmp, CIRCUIT_STATE_FILE);
73
+ } catch {
74
+ /* noop */
75
+ }
76
+ }
77
+ const REQUEST_ID_HEADERS = ["x-request-id", "request-id", "x-correlation-id"];
78
+ const DEBUG_API_ERRORS_ENV = "SENTINELAYER_DEBUG_ERRORS";
79
+ const MAX_API_ERROR_MESSAGE_LENGTH = 512;
80
+ const IDEMPOTENCY_KEY_MIN_LENGTH = 32;
81
+ const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
82
+ const PREFIXED_UUID_V4_PATTERN = /^[a-z0-9][a-z0-9_-]{1,48}-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
83
+
84
+ function resolveCircuitScope(url) {
85
+ try {
86
+ const parsed = new URL(String(url));
87
+ return parsed.origin;
88
+ } catch {
89
+ return "unknown";
90
+ }
91
+ }
92
+
93
+ function getCircuitState(scope) {
94
+ loadCircuitStateFromDisk();
95
+ const key = String(scope || "unknown");
96
+ if (!circuitStateByScope.has(key)) {
97
+ circuitStateByScope.set(key, { consecutiveFailures: 0, openedAtMs: 0 });
98
+ }
99
+ return circuitStateByScope.get(key);
100
+ }
101
+
102
+ function normalizeApiError(errorPayload = {}) {
103
+ const fallbackMessage = "Unknown API error";
104
+ if (!errorPayload || typeof errorPayload !== "object" || Array.isArray(errorPayload)) {
105
+ return {
106
+ code: "UNKNOWN",
107
+ message: sanitizeApiErrorMessage(fallbackMessage, fallbackMessage),
108
+ requestId: null,
109
+ };
110
+ }
111
+ const rawMessage = String(errorPayload.message || fallbackMessage);
112
+ const safeMessage = sanitizeApiErrorMessage(rawMessage, fallbackMessage);
113
+ const message = appendDebugContext(safeMessage, {
114
+ code: String(errorPayload.code || "UNKNOWN"),
115
+ requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
116
+ });
117
+ return {
118
+ code: String(errorPayload.code || "UNKNOWN"),
119
+ message,
120
+ requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
121
+ };
122
+ }
123
+
124
+ function resolveRequestId(headers) {
125
+ if (!headers || typeof headers.get !== "function") {
126
+ return null;
127
+ }
128
+ for (const headerName of REQUEST_ID_HEADERS) {
129
+ const value = headers.get(headerName);
130
+ if (value) {
131
+ return String(value);
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+
137
+ function resolveIdempotencyKey(headers) {
138
+ if (!headers) {
139
+ return null;
140
+ }
141
+ if (typeof headers.get === "function") {
142
+ const value =
143
+ headers.get("idempotency-key") ||
144
+ headers.get("Idempotency-Key") ||
145
+ headers.get("IDEMPOTENCY-KEY");
146
+ return String(value || "").trim() || null;
147
+ }
148
+ if (typeof headers !== "object") {
149
+ return null;
150
+ }
151
+ for (const [key, value] of Object.entries(headers)) {
152
+ if (String(key || "").toLowerCase() === "idempotency-key") {
153
+ const normalized = String(value || "").trim();
154
+ return normalized || null;
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+
160
+ function isValidIdempotencyKey(value) {
161
+ const normalized = String(value || "").trim();
162
+ if (!normalized) {
163
+ return false;
164
+ }
165
+ if (UUID_V4_PATTERN.test(normalized)) {
166
+ return true;
167
+ }
168
+ if (PREFIXED_UUID_V4_PATTERN.test(normalized)) {
169
+ return true;
170
+ }
171
+ if (normalized.length < IDEMPOTENCY_KEY_MIN_LENGTH) {
172
+ return false;
173
+ }
174
+ return /^[A-Za-z0-9_-]+$/.test(normalized);
175
+ }
176
+
177
+ function validateIdempotencyKey(value) {
178
+ if (!isValidIdempotencyKey(value)) {
179
+ throw new SentinelayerApiError("Idempotency-Key must be a UUIDv4 or a prefixed UUID.", {
180
+ status: 400,
181
+ code: "IDEMPOTENCY_KEY_INVALID",
182
+ });
183
+ }
184
+ }
185
+
186
+ function sanitizeOperationName(value) {
187
+ const normalized = String(value || "").toLowerCase();
188
+ const cleaned = normalized.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
189
+ return cleaned.slice(0, 32) || "mutation";
190
+ }
191
+
192
+ function createIdempotencyKeyForOperation(operationName) {
193
+ const op = sanitizeOperationName(operationName);
194
+ let suffix;
195
+ try {
196
+ suffix = crypto.randomUUID();
197
+ } catch {
198
+ suffix = crypto.randomBytes(16).toString("hex");
199
+ }
200
+ return `sl-cli-${op}-${suffix}`;
201
+ }
202
+
203
+ function normalizeHeaderObject(headers) {
204
+ if (!headers) {
205
+ return {};
206
+ }
207
+ if (typeof headers.get === "function") {
208
+ const normalized = {};
209
+ for (const [key, value] of headers.entries()) {
210
+ normalized[key] = value;
211
+ }
212
+ return normalized;
213
+ }
214
+ if (typeof headers !== "object") {
215
+ return {};
216
+ }
217
+ return { ...headers };
218
+ }
219
+
220
+ function isMutationVerb(method) {
221
+ const normalized = String(method || "").trim().toUpperCase();
222
+ return (
223
+ normalized === "POST" ||
224
+ normalized === "PUT" ||
225
+ normalized === "PATCH" ||
226
+ normalized === "DELETE"
227
+ );
228
+ }
229
+
230
+ function applyIdempotencyKey(headers, idempotencyKey) {
231
+ const normalized = normalizeHeaderObject(headers);
232
+ if (idempotencyKey && !resolveIdempotencyKey(normalized)) {
233
+ normalized["Idempotency-Key"] = idempotencyKey;
234
+ }
235
+ return normalized;
236
+ }
237
+
238
+ export class SentinelayerApiError extends Error {
239
+ /**
240
+ * @param {string} message
241
+ * @param {{ status?: number, code?: string, requestId?: string | null }} [options]
242
+ */
243
+ constructor(message, { status = 500, code = "UNKNOWN", requestId = null } = {}) {
244
+ const safeMessage = sanitizeApiErrorMessage(message, "Sentinelayer API error");
245
+ super(appendDebugContext(safeMessage, { code, status, requestId }));
246
+ this.name = "SentinelayerApiError";
247
+ this.status = Number(status || 500);
248
+ this.code = String(code || "UNKNOWN");
249
+ this.requestId = requestId ? String(requestId) : null;
250
+ }
251
+ }
252
+
253
+ function normalizePositiveNumber(value, fallback) {
254
+ const parsed = Number(value);
255
+ if (!Number.isFinite(parsed) || parsed <= 0) {
256
+ return fallback;
257
+ }
258
+ return parsed;
259
+ }
260
+
261
+ function normalizeNonNegativeInteger(value, fallback) {
262
+ const parsed = Number(value);
263
+ if (!Number.isFinite(parsed) || parsed < 0) {
264
+ return fallback;
265
+ }
266
+ return Math.floor(parsed);
267
+ }
268
+
269
+ function parseRetryAfterMs(value) {
270
+ const raw = String(value || "").trim();
271
+ if (!raw) {
272
+ return null;
273
+ }
274
+ const seconds = Number(raw);
275
+ if (Number.isFinite(seconds) && seconds >= 0) {
276
+ return Math.round(seconds * 1000);
277
+ }
278
+ const parsedDate = Date.parse(raw);
279
+ if (Number.isFinite(parsedDate)) {
280
+ const delta = parsedDate - Date.now();
281
+ if (delta > 0) {
282
+ return delta;
283
+ }
284
+ }
285
+ return null;
286
+ }
287
+
288
+ function computeBackoffMs({ attempt, retryDelayMs, retryAfterHeader }) {
289
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
290
+ if (retryAfterMs !== null) {
291
+ return Math.min(retryAfterMs, MAX_RETRY_DELAY_MS);
292
+ }
293
+ const exponent = Math.max(0, Number(attempt) - 1);
294
+ const computed = Math.round(retryDelayMs * Math.pow(2, exponent));
295
+ return Math.min(Math.max(1, computed), MAX_RETRY_DELAY_MS);
296
+ }
297
+
298
+ function isCircuitOpen(scope) {
299
+ const circuitState = getCircuitState(scope);
300
+ if (circuitState.openedAtMs <= 0) {
301
+ return false;
302
+ }
303
+ if (Date.now() - circuitState.openedAtMs >= CIRCUIT_BREAKER_COOLDOWN_MS) {
304
+ circuitState.openedAtMs = 0;
305
+ circuitState.consecutiveFailures = 0;
306
+ persistCircuitState();
307
+ return false;
308
+ }
309
+ return true;
310
+ }
311
+
312
+ function recordFailureForCircuit(scope) {
313
+ const circuitState = getCircuitState(scope);
314
+ circuitState.consecutiveFailures += 1;
315
+ if (circuitState.consecutiveFailures >= CIRCUIT_BREAKER_THRESHOLD) {
316
+ circuitState.openedAtMs = Date.now();
317
+ }
318
+ persistCircuitState();
319
+ }
320
+
321
+ function shouldExposeApiErrorDetails() {
322
+ const normalized = String(process.env[DEBUG_API_ERRORS_ENV] || "").trim().toLowerCase();
323
+ return normalized === "true" || normalized === "1" || normalized === "yes";
324
+ }
325
+
326
+ function isTestNonIdempotentAllowed() {
327
+ return (
328
+ process.env.NODE_ENV === "test" &&
329
+ process.env.SENTINELAYER_ALLOW_NON_IDEMPOTENT === "1" &&
330
+ process.env.SENTINELAYER_CLI_TEST_MODE === "1" &&
331
+ !process.env.CI
332
+ );
333
+ }
334
+
335
+ function sanitizeApiErrorMessage(message, fallback = "Sentinelayer API error") {
336
+ const fallbackMessage = String(fallback || "Sentinelayer API error");
337
+ const normalized = String(message || "").trim();
338
+ const candidate = normalized || fallbackMessage;
339
+ const sanitized = candidate
340
+ .replace(/\bbearer\s+[a-z0-9._~+/=-]+\b/gi, "bearer [REDACTED]")
341
+ .replace(/\b(token|secret|password|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)\b\s*[:=]\s*["']?[^"'\s,;]+["']?/gi, "$1=[REDACTED]")
342
+ .replace(/\b[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+\b/gi, "[REDACTED_JWT]")
343
+ .replace(/\bhttps?:\/\/[^\s"'`]+/gi, () => "<redacted-url>")
344
+ .replace(/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/gi, "<redacted-email>");
345
+ if (sanitized.length <= MAX_API_ERROR_MESSAGE_LENGTH) {
346
+ return sanitized;
347
+ }
348
+ return `${sanitized.slice(0, MAX_API_ERROR_MESSAGE_LENGTH - 3)}...`;
349
+ }
350
+
351
+ function anonymizeRequestIdForDebug(requestId) {
352
+ const normalized = String(requestId || "").trim();
353
+ if (!normalized) {
354
+ return "";
355
+ }
356
+ return crypto.createHash("sha256").update(normalized).digest("hex").slice(0, 12);
357
+ }
358
+
359
+ function appendDebugContext(safeMessage, { code, status, requestId } = {}) {
360
+ if (!shouldExposeApiErrorDetails()) {
361
+ return safeMessage;
362
+ }
363
+ const parts = [];
364
+ const normalizedCode = String(code || "").trim();
365
+ const normalizedStatus = Number.isFinite(Number(status)) ? Number(status) : null;
366
+ const requestIdHash = anonymizeRequestIdForDebug(requestId);
367
+ if (normalizedCode) parts.push(`code=${normalizedCode}`);
368
+ if (normalizedStatus) parts.push(`status=${normalizedStatus}`);
369
+ if (requestIdHash) parts.push(`request_id_hash=${requestIdHash}`);
370
+ if (parts.length === 0) return safeMessage;
371
+ return `${safeMessage} (${parts.join(", ")})`;
372
+ }
373
+
374
+ function recordSuccessForCircuit(scope) {
375
+ const circuitState = getCircuitState(scope);
376
+ circuitState.consecutiveFailures = 0;
377
+ circuitState.openedAtMs = 0;
378
+ persistCircuitState();
379
+ }
380
+
381
+ function shouldRetryStatus(statusCode) {
382
+ return RETRYABLE_STATUS_CODES.has(Number(statusCode || 0));
383
+ }
384
+
385
+ function shouldRecordFailureForStatus(statusCode) {
386
+ return CIRCUIT_TRACK_STATUS_CODES.has(Number(statusCode || 0));
387
+ }
388
+
389
+ export function __resetRequestCircuitForTests(scope) {
390
+ if (scope) {
391
+ const circuitState = getCircuitState(scope);
392
+ circuitState.consecutiveFailures = 0;
393
+ circuitState.openedAtMs = 0;
394
+ persistCircuitState();
395
+ return;
396
+ }
397
+ circuitStateByScope.clear();
398
+ circuitStateLoaded = true; // block disk reload after manual reset
399
+ try {
400
+ fs.rmSync(CIRCUIT_STATE_FILE, { force: true });
401
+ } catch {
402
+ /* noop */
403
+ }
404
+ }
405
+
406
+ /**
407
+ * Execute an HTTP request against the Sentinelayer API and parse a JSON response.
408
+ * Throws `SentinelayerApiError` for transport errors, timeouts, API failures, and invalid JSON.
409
+ *
410
+ * @param {string} url
411
+ * @param {{
412
+ * method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
413
+ * headers?: Record<string, string>,
414
+ * body?: unknown,
415
+ * idempotencyKey?: string | null,
416
+ * allowNonIdempotent?: boolean,
417
+ * timeoutMs?: number
418
+ * maxRetries?: number,
419
+ * retryDelayMs?: number
420
+ * allowEmptyBody?: boolean
421
+ * }} [options]
422
+ * @returns {Promise<any>}
423
+ */
424
+ export async function requestJson(
425
+ url,
426
+ {
427
+ method = "GET",
428
+ headers = {},
429
+ body,
430
+ idempotencyKey = null,
431
+ allowNonIdempotent = false,
432
+ timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
433
+ maxRetries = DEFAULT_MAX_RETRIES,
434
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS,
435
+ allowEmptyBody = false,
436
+ } = {}
437
+ ) {
438
+ const normalizedMethod = String(method || "GET").trim().toUpperCase();
439
+ const explicitIdempotencyKey = String(idempotencyKey || "").trim() || null;
440
+ const existingIdempotencyKey = explicitIdempotencyKey || resolveIdempotencyKey(headers);
441
+ const isMutationMethod = isMutationVerb(normalizedMethod);
442
+ const resolvedIdempotencyKey = existingIdempotencyKey;
443
+ const requestHeaders = applyIdempotencyKey(headers, resolvedIdempotencyKey);
444
+ const outgoingHeaders = { ...requestHeaders };
445
+ if (body !== undefined) {
446
+ outgoingHeaders["Content-Type"] = "application/json";
447
+ }
448
+ const isIdempotentMutation = Boolean(resolvedIdempotencyKey);
449
+ const allowUnsafeMutation = Boolean(allowNonIdempotent) && isTestNonIdempotentAllowed();
450
+ if (isMutationMethod && !isIdempotentMutation && !allowUnsafeMutation) {
451
+ throw new SentinelayerApiError("Idempotency-Key is required for mutation requests.", {
452
+ status: 400,
453
+ code: "IDEMPOTENCY_KEY_REQUIRED",
454
+ });
455
+ }
456
+ if (isMutationMethod && isIdempotentMutation) {
457
+ validateIdempotencyKey(resolvedIdempotencyKey);
458
+ }
459
+ const retryableMethod =
460
+ normalizedMethod === "GET" ||
461
+ normalizedMethod === "HEAD" ||
462
+ normalizedMethod === "OPTIONS" ||
463
+ (isIdempotentMutation &&
464
+ (normalizedMethod === "POST" ||
465
+ normalizedMethod === "PUT" ||
466
+ normalizedMethod === "PATCH" ||
467
+ normalizedMethod === "DELETE"));
468
+ const circuitScope = resolveCircuitScope(url);
469
+ if (isCircuitOpen(circuitScope)) {
470
+ throw new SentinelayerApiError("Request circuit breaker is open after consecutive API failures.", {
471
+ status: 503,
472
+ code: "CIRCUIT_OPEN",
473
+ });
474
+ }
475
+
476
+ const normalizedTimeoutMs = normalizePositiveNumber(timeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
477
+ const normalizedMaxRetries = normalizeNonNegativeInteger(maxRetries, DEFAULT_MAX_RETRIES);
478
+ const normalizedRetryDelayMs = normalizePositiveNumber(retryDelayMs, DEFAULT_RETRY_DELAY_MS);
479
+
480
+ let lastRetryableError = null;
481
+ for (let attempt = 0; attempt <= normalizedMaxRetries; attempt += 1) {
482
+ const controller = new AbortController();
483
+ let timeoutTriggered = false;
484
+ let timeoutHandle;
485
+ timeoutHandle = setTimeout(() => {
486
+ timeoutTriggered = true;
487
+ controller.abort();
488
+ }, normalizedTimeoutMs);
489
+
490
+ try {
491
+ const response = await fetch(String(url), {
492
+ method: normalizedMethod,
493
+ headers: outgoingHeaders,
494
+ body: body === undefined ? undefined : JSON.stringify(body),
495
+ redirect: "error",
496
+ signal: controller.signal,
497
+ });
498
+
499
+ const rawBody = await response.text();
500
+ const trimmedBody = rawBody.trim();
501
+ const contentType = response.headers.get("content-type") || "";
502
+ const isJson = /application\/json/i.test(contentType);
503
+ let json = {};
504
+ if (!trimmedBody) {
505
+ const statusCode = Number(response.status || 0);
506
+ const allowEmpty = Boolean(allowEmptyBody) || statusCode === 204 || statusCode === 205;
507
+ if (response.ok && !allowEmpty) {
508
+ const requestId = resolveRequestId(response.headers);
509
+ throw new SentinelayerApiError("Empty response body returned by API.", {
510
+ status: response.status,
511
+ code: "EMPTY_BODY",
512
+ requestId,
513
+ });
514
+ }
515
+ } else {
516
+ if (response.ok && !isJson) {
517
+ const requestId = resolveRequestId(response.headers);
518
+ throw new SentinelayerApiError("Invalid content-type returned by API.", {
519
+ status: response.status,
520
+ code: "INVALID_CONTENT_TYPE",
521
+ requestId,
522
+ });
523
+ }
524
+ if (isJson) {
525
+ try {
526
+ json = JSON.parse(rawBody);
527
+ } catch {
528
+ const requestId = resolveRequestId(response.headers);
529
+ if (response.ok) {
530
+ throw new SentinelayerApiError("Invalid JSON returned by API.", {
531
+ status: response.status,
532
+ code: "INVALID_JSON",
533
+ requestId,
534
+ });
535
+ }
536
+ }
537
+ }
538
+ }
539
+
540
+ if (response.ok) {
541
+ recordSuccessForCircuit(circuitScope);
542
+ return json;
543
+ }
544
+
545
+ const apiError = normalizeApiError(json && typeof json === "object" ? json.error : {});
546
+ const requestId = apiError.requestId || resolveRequestId(response.headers);
547
+ const statusCode = Number(response.status || 500);
548
+ const retryable = retryableMethod && shouldRetryStatus(statusCode);
549
+ const shouldRecordCircuitFailure = shouldRecordFailureForStatus(statusCode);
550
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
551
+ const error = new SentinelayerApiError(apiError.message, {
552
+ status: statusCode,
553
+ code: apiError.code,
554
+ requestId,
555
+ });
556
+ error.retryAfterMs = retryAfterMs;
557
+
558
+ if (!retryable || attempt >= normalizedMaxRetries) {
559
+ if (shouldRecordCircuitFailure) {
560
+ recordFailureForCircuit(circuitScope);
561
+ }
562
+ throw error;
563
+ }
564
+
565
+ lastRetryableError = error;
566
+ const delayMs = computeBackoffMs({
567
+ attempt: attempt + 1,
568
+ retryDelayMs: normalizedRetryDelayMs,
569
+ retryAfterHeader: response.headers.get("retry-after"),
570
+ });
571
+ await sleep(delayMs);
572
+ continue;
573
+ } catch (error) {
574
+ if (error instanceof SentinelayerApiError) {
575
+ throw error;
576
+ }
577
+
578
+ const isAbortError = Boolean(error && typeof error === "object" && error.name === "AbortError");
579
+ const abortMessage = error instanceof Error ? error.message : String(error || "");
580
+ const abortReason =
581
+ isAbortError && !timeoutTriggered && /cancel/i.test(abortMessage) ? "CANCELLED" : "TIMEOUT";
582
+ const abortCode = isAbortError ? abortReason : "NETWORK_ERROR";
583
+ const abortStatus = isAbortError ? (abortReason === "CANCELLED" ? 499 : 408) : 503;
584
+ const normalizedError = new SentinelayerApiError(
585
+ isAbortError
586
+ ? (abortReason === "CANCELLED" ? "Request cancelled." : "Request timed out.")
587
+ : (error instanceof Error ? error.message : String(error || "Request failed")),
588
+ {
589
+ status: abortStatus,
590
+ code: abortCode,
591
+ }
592
+ );
593
+
594
+ if (!retryableMethod || attempt >= normalizedMaxRetries) {
595
+ recordFailureForCircuit(circuitScope);
596
+ throw normalizedError;
597
+ }
598
+
599
+ lastRetryableError = normalizedError;
600
+ const delayMs = computeBackoffMs({
601
+ attempt: attempt + 1,
602
+ retryDelayMs: normalizedRetryDelayMs,
603
+ retryAfterHeader: null,
604
+ });
605
+ await sleep(delayMs);
606
+ continue;
607
+ } finally {
608
+ if (timeoutHandle) {
609
+ clearTimeout(timeoutHandle);
610
+ }
611
+ await sleep(0);
612
+ }
613
+ }
614
+
615
+ if (lastRetryableError instanceof SentinelayerApiError) {
616
+ throw lastRetryableError;
617
+ }
618
+ throw new SentinelayerApiError("Request failed without a terminal response.", {
619
+ status: 503,
620
+ code: "NETWORK_ERROR",
621
+ });
622
+ }
623
+
624
+ /**
625
+ * Execute an HTTP mutation request and auto-derive an idempotency key when missing.
626
+ *
627
+ * @param {string} url
628
+ * @param {{
629
+ * method?: "POST" | "PUT" | "PATCH" | "DELETE",
630
+ * headers?: Record<string, string>,
631
+ * body?: unknown,
632
+ * idempotencyKey?: string | null,
633
+ * operationName: string,
634
+ * timeoutMs?: number
635
+ * maxRetries?: number,
636
+ * retryDelayMs?: number
637
+ * allowEmptyBody?: boolean
638
+ * }} options
639
+ * @returns {Promise<any>}
640
+ */
641
+ export async function requestJsonMutation(
642
+ url,
643
+ {
644
+ method = "POST",
645
+ headers = {},
646
+ body,
647
+ idempotencyKey = null,
648
+ operationName,
649
+ timeoutMs,
650
+ maxRetries,
651
+ retryDelayMs,
652
+ allowEmptyBody = false,
653
+ } = {}
654
+ ) {
655
+ const normalizedMethod = String(method || "POST").trim().toUpperCase();
656
+ if (!isMutationVerb(normalizedMethod)) {
657
+ throw new SentinelayerApiError("requestJsonMutation requires a mutation HTTP method.", {
658
+ status: 400,
659
+ code: "INVALID_MUTATION_METHOD",
660
+ });
661
+ }
662
+ const resolvedOperation = String(operationName || "").trim();
663
+ if (!resolvedOperation) {
664
+ throw new SentinelayerApiError("requestJsonMutation requires an operationName.", {
665
+ status: 400,
666
+ code: "OPERATION_NAME_REQUIRED",
667
+ });
668
+ }
669
+ const resolvedIdempotencyKey =
670
+ String(idempotencyKey || "").trim() || createIdempotencyKeyForOperation(resolvedOperation);
671
+ return requestJson(url, {
672
+ method: normalizedMethod,
673
+ headers,
674
+ body,
675
+ idempotencyKey: resolvedIdempotencyKey,
676
+ timeoutMs,
677
+ maxRetries,
678
+ retryDelayMs,
679
+ allowEmptyBody,
680
+ });
681
+ }