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
@@ -1,1106 +1,1106 @@
1
- import crypto from "node:crypto";
2
- import process from "node:process";
3
- import { setTimeout as sleep } from "node:timers/promises";
4
-
5
- import open from "open";
6
-
7
- import { loadConfig } from "../config/service.js";
8
- import { SentinelayerApiError, requestJson, requestJsonMutation } from "./http.js";
9
- import {
10
- clearStoredSession,
11
- readStoredSession,
12
- readStoredSessionMetadata,
13
- writeStoredSession,
14
- } from "./session-store.js";
15
- import { authLoginHint } from "../ui/command-hints.js";
16
-
17
- const DEFAULT_API_URL = "https://api.sentinelayer.com";
18
- /** Default maximum wall-clock wait for browser-based CLI auth approval (ms). */
19
- export const DEFAULT_AUTH_TIMEOUT_MS = 10 * 60 * 1000;
20
- /** Default lifetime for issued API tokens used by CLI sessions (days). */
21
- export const DEFAULT_API_TOKEN_TTL_DAYS = 365;
22
- /** Default threshold at which stored tokens are rotated before expiry (days). */
23
- export const DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS = 7;
24
- const DEFAULT_IDE_NAME = "sl-cli";
25
- const MAX_AUTH_POLL_REQUESTS = 600;
26
- const MIN_TRANSIENT_POLL_DELAY_MS = 2_000;
27
- const TRANSIENT_DELAY_THRESHOLD = 3;
28
-
29
- function normalizeApiUrl(rawValue) {
30
- const candidate = String(rawValue || "").trim() || DEFAULT_API_URL;
31
- let parsed;
32
- try {
33
- parsed = new URL(candidate);
34
- } catch {
35
- throw new Error(`Invalid API URL '${candidate}'.`);
36
- }
37
- const hostname = String(parsed.hostname || "").toLowerCase();
38
- const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1";
39
- if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLocalhost)) {
40
- throw new Error(`API URL must use https (received '${candidate}').`);
41
- }
42
- parsed.pathname = "/";
43
- parsed.search = "";
44
- parsed.hash = "";
45
- return parsed.toString().replace(/\/$/, "");
46
- }
47
-
48
- function normalizePositiveNumber(rawValue, field, fallbackValue) {
49
- if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
50
- return fallbackValue;
51
- }
52
- const normalized = Number(rawValue);
53
- if (!Number.isFinite(normalized) || normalized <= 0) {
54
- throw new Error(`${field} must be a positive number.`);
55
- }
56
- return normalized;
57
- }
58
-
59
- function toAuthHeader(token) {
60
- return {
61
- Authorization: `Bearer ${String(token || "").trim()}`,
62
- };
63
- }
64
-
65
- function normalizeUser(user = {}) {
66
- return {
67
- id: String(user.id || "").trim(),
68
- githubUsername: String(user.githubUsername || user.github_username || "").trim(),
69
- email: String(user.email || "").trim(),
70
- avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
71
- isAdmin: Boolean(user.isAdmin || user.is_admin),
72
- };
73
- }
74
-
75
- function buildApiPath(apiUrl, pathSuffix) {
76
- return `${normalizeApiUrl(apiUrl)}${String(pathSuffix || "")}`;
77
- }
78
-
79
- function generateChallenge() {
80
- return crypto.randomBytes(48).toString("base64url");
81
- }
82
-
83
- function createFlowRequestId() {
84
- try {
85
- return crypto.randomUUID();
86
- } catch {
87
- return `flow-${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
88
- }
89
- }
90
-
91
- function withFlowRequestHeaders(headers, flowRequestId) {
92
- const merged = {
93
- ...(headers || {}),
94
- "X-Request-Id": createFlowRequestId(),
95
- };
96
- if (flowRequestId) {
97
- merged["X-Flow-Request-Id"] = flowRequestId;
98
- }
99
- return merged;
100
- }
101
-
102
- async function requestAuthJson(flowRequestId, ...args) {
103
- try {
104
- return await requestJson(...args);
105
- } catch (error) {
106
- if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
107
- error.requestId = flowRequestId;
108
- }
109
- throw error;
110
- }
111
- }
112
-
113
- async function requestAuthJsonMutation(flowRequestId, ...args) {
114
- try {
115
- return await requestJsonMutation(...args);
116
- } catch (error) {
117
- if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
118
- error.requestId = flowRequestId;
119
- }
120
- throw error;
121
- }
122
- }
123
-
124
- function defaultTokenLabel() {
125
- const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
126
- return `sl-cli-session-${stamp}`;
127
- }
128
-
129
- function createIdempotencyKey(prefix) {
130
- const normalizedPrefix = String(prefix || "sl-cli").trim() || "sl-cli";
131
- let suffix;
132
- try {
133
- suffix = crypto.randomUUID();
134
- } catch {
135
- suffix = `${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
136
- }
137
- return `${normalizedPrefix}-${suffix}`;
138
- }
139
-
140
- function computeDeterministicJitterFactor({ sessionId, attempt }) {
141
- const seed = `${String(sessionId || "").trim()}|${Number(attempt) || 0}`;
142
- const digest = crypto.createHash("sha256").update(seed).digest();
143
- const raw = digest.readUInt32BE(0);
144
- const ratio = raw / 0xffffffff;
145
- return 0.85 + ratio * 0.3;
146
- }
147
-
148
- function isNearExpiry(tokenExpiresAt, thresholdDays) {
149
- const normalized = String(tokenExpiresAt || "").trim();
150
- if (!normalized) {
151
- return false;
152
- }
153
- const expiryEpoch = Date.parse(normalized);
154
- if (!Number.isFinite(expiryEpoch)) {
155
- return false;
156
- }
157
- const thresholdMs = Number(thresholdDays || DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS) * 24 * 60 * 60 * 1000;
158
- return expiryEpoch - Date.now() <= thresholdMs;
159
- }
160
-
161
- /**
162
- * Resolve API URL precedence for auth operations: explicit -> env -> config -> default.
163
- *
164
- * @param {{
165
- * cwd?: string,
166
- * env?: NodeJS.ProcessEnv,
167
- * explicitApiUrl?: string,
168
- * homeDir?: string
169
- * }} [options]
170
- * @returns {Promise<string>}
171
- */
172
- export async function resolveApiUrl({
173
- cwd = process.cwd(),
174
- env = process.env,
175
- explicitApiUrl = "",
176
- homeDir,
177
- } = {}) {
178
- const overrideUrl = String(explicitApiUrl || "").trim();
179
- if (overrideUrl) {
180
- return normalizeApiUrl(overrideUrl);
181
- }
182
-
183
- const envUrl = String(env.SENTINELAYER_API_URL || "").trim();
184
- if (envUrl) {
185
- return normalizeApiUrl(envUrl);
186
- }
187
-
188
- const config = await loadConfig({ cwd, env, homeDir });
189
- const configuredApiUrl = String(config.resolved.apiUrl || "").trim();
190
- if (configuredApiUrl) {
191
- return normalizeApiUrl(configuredApiUrl);
192
- }
193
-
194
- return normalizeApiUrl(DEFAULT_API_URL);
195
- }
196
-
197
- async function startCliAuthSession({ apiUrl, challenge, ide, cliVersion, flowRequestId }) {
198
- return requestAuthJsonMutation(
199
- flowRequestId,
200
- buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/start"),
201
- {
202
- method: "POST",
203
- operationName: "auth-start",
204
- headers: withFlowRequestHeaders(null, flowRequestId),
205
- body: {
206
- challenge,
207
- ide: String(ide || DEFAULT_IDE_NAME),
208
- cli_version: String(cliVersion || "").trim() || null,
209
- },
210
- }
211
- );
212
- }
213
-
214
- async function pollCliAuthSession({
215
- apiUrl,
216
- sessionId,
217
- challenge,
218
- timeoutMs,
219
- pollIntervalSeconds,
220
- flowRequestId,
221
- }) {
222
- const timeout = normalizePositiveNumber(timeoutMs, "timeoutMs", DEFAULT_AUTH_TIMEOUT_MS);
223
- const pollIntervalMs = Math.max(250, Math.round(Number(pollIntervalSeconds || 2) * 1000));
224
- const maxPollIntervalMs = Math.max(pollIntervalMs, Math.min(5_000, Math.floor(timeout / 4)));
225
- const pollRequestTimeoutMs = Math.min(5_000, Math.max(1_000, pollIntervalMs));
226
- const pollRequestMaxRetries = 1;
227
- const pollRequestRetryDelayMs = 250;
228
- let pollAttempt = 0;
229
- const transientErrorBudget = Math.max(8, Math.ceil(timeout / maxPollIntervalMs) * 3);
230
- const maxSleepBudgetMs = Math.max(2_000, Math.floor(timeout * 0.8));
231
- const maxPollAttempts = Math.min(
232
- MAX_AUTH_POLL_REQUESTS,
233
- Math.max(1, Math.ceil(timeout / Math.max(250, pollIntervalMs)))
234
- );
235
- let rateLimitErrorCount = 0;
236
- let serverErrorCount = 0;
237
- let networkErrorCount = 0;
238
- let transientBudgetUsed = 0;
239
- let cumulativeSleepMs = 0;
240
- let pollIterations = 0;
241
- const deadline = Date.now() + timeout;
242
- const classifyPollError = (error) => {
243
- if (!(error instanceof SentinelayerApiError)) {
244
- return null;
245
- }
246
- if (error.status === 429) {
247
- return "rate_limit";
248
- }
249
- if (error.status >= 500) {
250
- return "server";
251
- }
252
- if (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT") {
253
- return "network";
254
- }
255
- return null;
256
- };
257
- const computePollDelayMs = (retryAfterMs = null) => {
258
- const transientErrorCount = rateLimitErrorCount + serverErrorCount + networkErrorCount;
259
- const minDelayMs =
260
- transientErrorCount >= TRANSIENT_DELAY_THRESHOLD ? MIN_TRANSIENT_POLL_DELAY_MS : 250;
261
- if (Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
262
- return Math.max(minDelayMs, Math.min(maxPollIntervalMs, Math.round(retryAfterMs)));
263
- }
264
- const exponent = Math.min(6, pollAttempt);
265
- const backoffMs = Math.min(maxPollIntervalMs, Math.round(pollIntervalMs * Math.pow(1.5, exponent)));
266
- const jitterFactor = computeDeterministicJitterFactor({ sessionId, attempt: pollAttempt });
267
- return Math.max(minDelayMs, Math.round(backoffMs * jitterFactor));
268
- };
269
-
270
- while (Date.now() < deadline) {
271
- const remainingBeforeRequestMs = deadline - Date.now();
272
- if (remainingBeforeRequestMs <= 250) {
273
- break;
274
- }
275
- pollIterations += 1;
276
- if (pollIterations > maxPollAttempts) {
277
- throw new SentinelayerApiError("CLI authentication polling exceeded attempt budget.", {
278
- status: 408,
279
- code: "CLI_AUTH_POLL_EXHAUSTED",
280
- requestId: flowRequestId || null,
281
- });
282
- }
283
- let payload;
284
- try {
285
- payload = await requestAuthJsonMutation(
286
- flowRequestId,
287
- buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/poll"),
288
- {
289
- method: "POST",
290
- operationName: "auth-poll",
291
- headers: withFlowRequestHeaders(null, flowRequestId),
292
- body: {
293
- session_id: sessionId,
294
- challenge,
295
- },
296
- timeoutMs: Math.max(250, Math.min(pollRequestTimeoutMs, remainingBeforeRequestMs)),
297
- maxRetries: pollRequestMaxRetries,
298
- retryDelayMs: pollRequestRetryDelayMs,
299
- }
300
- );
301
- } catch (error) {
302
- if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
303
- error.requestId = flowRequestId;
304
- }
305
- const classification = classifyPollError(error);
306
- if (classification) {
307
- const transientWeight = classification === "rate_limit" ? 3 : classification === "server" ? 2 : 1;
308
- if (transientBudgetUsed + transientWeight > transientErrorBudget) {
309
- throw new SentinelayerApiError("CLI authentication polling exhausted transient error budget.", {
310
- status: 503,
311
- code: "CLI_AUTH_TRANSIENT_BUDGET_EXHAUSTED",
312
- requestId: error.requestId || flowRequestId || null,
313
- });
314
- }
315
- transientBudgetUsed += transientWeight;
316
- if (classification === "rate_limit") {
317
- rateLimitErrorCount += 1;
318
- } else if (classification === "server") {
319
- serverErrorCount += 1;
320
- } else {
321
- networkErrorCount += 1;
322
- }
323
- const retryAfterMs = Number.isFinite(error.retryAfterMs) ? error.retryAfterMs : null;
324
- const delayMs = computePollDelayMs(retryAfterMs);
325
- const remainingBeforeSleepMs = deadline - Date.now();
326
- if (remainingBeforeSleepMs <= 250) {
327
- break;
328
- }
329
- const boundedDelayMs = Math.max(250, Math.min(delayMs, remainingBeforeSleepMs));
330
- if (cumulativeSleepMs + boundedDelayMs > maxSleepBudgetMs) {
331
- throw new SentinelayerApiError("CLI authentication polling exceeded retry sleep budget.", {
332
- status: 503,
333
- code: "CLI_AUTH_SLEEP_BUDGET_EXHAUSTED",
334
- requestId: error.requestId || flowRequestId || null,
335
- });
336
- }
337
- cumulativeSleepMs += boundedDelayMs;
338
- pollAttempt += 1;
339
- await sleep(boundedDelayMs);
340
- continue;
341
- }
342
- throw error;
343
- }
344
-
345
- const status = String(payload.status || "pending").trim().toLowerCase();
346
- if (status === "approved" && payload.auth_token) {
347
- return payload;
348
- }
349
- if (status === "rejected" || status === "denied" || status === "cancelled") {
350
- throw new SentinelayerApiError("CLI authentication was not approved.", {
351
- status: 401,
352
- code: "CLI_AUTH_REJECTED",
353
- requestId: flowRequestId || null,
354
- });
355
- }
356
- if (status === "expired") {
357
- throw new SentinelayerApiError("CLI authentication session expired.", {
358
- status: 401,
359
- code: "CLI_AUTH_EXPIRED",
360
- requestId: flowRequestId || null,
361
- });
362
- }
363
-
364
- const delayMs = computePollDelayMs();
365
- const remainingBeforeSleepMs = deadline - Date.now();
366
- if (remainingBeforeSleepMs <= 250) {
367
- break;
368
- }
369
- const boundedDelayMs = Math.max(250, Math.min(delayMs, remainingBeforeSleepMs));
370
- pollAttempt += 1;
371
- await sleep(boundedDelayMs);
372
- }
373
-
374
- throw new SentinelayerApiError("CLI authentication timed out. Restart and try again.", {
375
- status: 408,
376
- code: "CLI_AUTH_TIMEOUT",
377
- requestId: flowRequestId || null,
378
- });
379
- }
380
-
381
- async function fetchCurrentUser({ apiUrl, token, flowRequestId }) {
382
- return requestAuthJson(
383
- flowRequestId,
384
- buildApiPath(apiUrl, "/api/v1/auth/me"),
385
- {
386
- method: "GET",
387
- headers: withFlowRequestHeaders(toAuthHeader(token), flowRequestId),
388
- }
389
- );
390
- }
391
-
392
- async function issueApiToken({
393
- apiUrl,
394
- authToken,
395
- tokenLabel,
396
- tokenTtlDays,
397
- flowRequestId,
398
- }) {
399
- const expiresInDays = Math.round(
400
- normalizePositiveNumber(tokenTtlDays, "apiTokenTtlDays", DEFAULT_API_TOKEN_TTL_DAYS)
401
- );
402
- return requestAuthJsonMutation(
403
- flowRequestId,
404
- buildApiPath(apiUrl, "/api/v1/auth/api-tokens"),
405
- {
406
- method: "POST",
407
- operationName: "issue-token",
408
- headers: withFlowRequestHeaders(
409
- {
410
- ...toAuthHeader(authToken),
411
- },
412
- flowRequestId
413
- ),
414
- body: {
415
- label: String(tokenLabel || "").trim() || defaultTokenLabel(),
416
- scope: "cli",
417
- llm_credential_mode: "managed",
418
- expires_in_days: expiresInDays,
419
- },
420
- }
421
- );
422
- }
423
-
424
- async function revokeApiToken({ apiUrl, authToken, tokenId }) {
425
- const normalizedTokenId = String(tokenId || "").trim();
426
- if (!normalizedTokenId) {
427
- return false;
428
- }
429
- await requestJsonMutation(buildApiPath(apiUrl, `/api/v1/auth/api-tokens/${encodeURIComponent(normalizedTokenId)}`), {
430
- method: "DELETE",
431
- operationName: "revoke-token",
432
- headers: {
433
- ...toAuthHeader(authToken),
434
- },
435
- });
436
- return true;
437
- }
438
-
439
- async function rotateStoredApiTokenIfNeeded({
440
- session,
441
- thresholdDays,
442
- tokenLabel,
443
- tokenTtlDays,
444
- homeDir,
445
- }) {
446
- if (!session || !session.token || !session.tokenExpiresAt) {
447
- return { session, rotated: false };
448
- }
449
- if (!isNearExpiry(session.tokenExpiresAt, thresholdDays)) {
450
- return { session, rotated: false };
451
- }
452
-
453
- const issued = await issueApiToken({
454
- apiUrl: session.apiUrl,
455
- authToken: session.token,
456
- tokenLabel,
457
- tokenTtlDays,
458
- });
459
-
460
- const nextSession = await writeStoredSession(
461
- {
462
- apiUrl: session.apiUrl,
463
- token: String(issued.token || ""),
464
- tokenId: issued.id || null,
465
- tokenPrefix: issued.token_prefix || null,
466
- tokenExpiresAt: issued.expires_at || null,
467
- user: session.user,
468
- },
469
- { homeDir }
470
- );
471
-
472
- let revokeError = null;
473
- if (session.tokenId) {
474
- try {
475
- await revokeApiToken({
476
- apiUrl: session.apiUrl,
477
- authToken: nextSession.token,
478
- tokenId: session.tokenId,
479
- });
480
- } catch (error) {
481
- revokeError = error;
482
- }
483
- }
484
-
485
- return {
486
- session: nextSession,
487
- rotated: true,
488
- revokeError,
489
- };
490
- }
491
-
492
- /**
493
- * Perform browser-based CLI login flow and persist an API token session locally.
494
- *
495
- * @param {{
496
- * cwd?: string,
497
- * env?: NodeJS.ProcessEnv,
498
- * explicitApiUrl?: string,
499
- * skipBrowserOpen?: boolean,
500
- * timeoutMs?: number,
501
- * tokenLabel?: string,
502
- * tokenTtlDays?: number,
503
- * ide?: string,
504
- * cliVersion?: string,
505
- * homeDir?: string
506
- * }} [options]
507
- * @returns {Promise<{
508
- * apiUrl: string,
509
- * authorizeUrl: string,
510
- * browserOpened: boolean,
511
- * user: {
512
- * id: string,
513
- * githubUsername: string,
514
- * email: string,
515
- * avatarUrl: string,
516
- * isAdmin: boolean
517
- * },
518
- * tokenId: string | null,
519
- * tokenPrefix: string | null,
520
- * tokenExpiresAt: string | null,
521
- * storage: string,
522
- * filePath: string
523
- * }>}
524
- */
525
- export async function loginAndPersistSession({
526
- cwd = process.cwd(),
527
- env = process.env,
528
- explicitApiUrl = "",
529
- skipBrowserOpen = false,
530
- timeoutMs = DEFAULT_AUTH_TIMEOUT_MS,
531
- tokenLabel = "",
532
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
533
- ide = DEFAULT_IDE_NAME,
534
- cliVersion = "",
535
- homeDir,
536
- } = {}) {
537
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
538
- const challenge = generateChallenge();
539
- const flowRequestId = createFlowRequestId();
540
- const session = await startCliAuthSession({
541
- apiUrl,
542
- challenge,
543
- ide,
544
- cliVersion,
545
- flowRequestId,
546
- });
547
-
548
- const authorizeUrl = String(session.authorize_url || "").trim();
549
- let browserOpened = false;
550
- if (!skipBrowserOpen && authorizeUrl) {
551
- try {
552
- await open(authorizeUrl);
553
- browserOpened = true;
554
- } catch {
555
- browserOpened = false;
556
- }
557
- }
558
-
559
- const approval = await pollCliAuthSession({
560
- apiUrl,
561
- sessionId: String(session.session_id || "").trim(),
562
- challenge,
563
- timeoutMs,
564
- pollIntervalSeconds: Number(session.poll_interval_seconds || 2),
565
- flowRequestId,
566
- });
567
-
568
- const approvalToken = String(approval.auth_token || "").trim();
569
- if (!approvalToken) {
570
- throw new SentinelayerApiError("Authentication completed but no auth token was returned.", {
571
- status: 503,
572
- code: "CLI_AUTH_MISSING_TOKEN",
573
- requestId: flowRequestId || null,
574
- });
575
- }
576
-
577
- const user = normalizeUser(
578
- approval.user || (await fetchCurrentUser({ apiUrl, token: approvalToken, flowRequestId }))
579
- );
580
- const issuedApiToken = await issueApiToken({
581
- apiUrl,
582
- authToken: approvalToken,
583
- tokenLabel,
584
- tokenTtlDays,
585
- flowRequestId,
586
- });
587
-
588
- // Extract AIdenID metadata from approval (no secret stored locally)
589
- const rawAidenId = approval.aidenidCredentials || approval.aidenid_credentials || null;
590
- const aidenid =
591
- rawAidenId && rawAidenId.provisioned
592
- ? {
593
- orgId: String(rawAidenId.orgId || rawAidenId.org_id || "").trim() || null,
594
- projectId: String(rawAidenId.projectId || rawAidenId.project_id || "").trim() || null,
595
- apiKeyPrefix: String(rawAidenId.apiKeyPrefix || rawAidenId.api_key_prefix || "").trim() || null,
596
- provisionedAt: new Date().toISOString(),
597
- }
598
- : null;
599
-
600
- const stored = await writeStoredSession(
601
- {
602
- apiUrl,
603
- token: String(issuedApiToken.token || ""),
604
- tokenId: issuedApiToken.id || null,
605
- tokenPrefix: issuedApiToken.token_prefix || null,
606
- tokenExpiresAt: issuedApiToken.expires_at || null,
607
- user,
608
- aidenid,
609
- },
610
- { homeDir }
611
- );
612
-
613
- return {
614
- apiUrl,
615
- authorizeUrl,
616
- browserOpened,
617
- user,
618
- tokenId: stored.tokenId,
619
- tokenPrefix: stored.tokenPrefix,
620
- tokenExpiresAt: stored.tokenExpiresAt,
621
- storage: stored.storage,
622
- filePath: stored.filePath,
623
- aidenid: stored.aidenid || null,
624
- flowRequestId,
625
- };
626
- }
627
-
628
- /**
629
- * Resolve active auth credentials used by CLI commands, optionally rotating near-expiry session tokens.
630
- *
631
- * @param {{
632
- * cwd?: string,
633
- * env?: NodeJS.ProcessEnv,
634
- * explicitApiUrl?: string,
635
- * autoRotate?: boolean,
636
- * rotateThresholdDays?: number,
637
- * tokenLabel?: string,
638
- * tokenTtlDays?: number,
639
- * homeDir?: string
640
- * }} [options]
641
- * @returns {Promise<null | {
642
- * apiUrl: string,
643
- * token: string,
644
- * source: "env" | "config" | "session",
645
- * user: {
646
- * id: string,
647
- * githubUsername: string,
648
- * email: string,
649
- * avatarUrl: string,
650
- * isAdmin: boolean
651
- * } | null,
652
- * storage: string,
653
- * tokenId: string | null,
654
- * tokenPrefix: string | null,
655
- * tokenExpiresAt: string | null,
656
- * rotated: boolean,
657
- * filePath: string | null
658
- * }>}
659
- */
660
- export async function resolveActiveAuthSession({
661
- cwd = process.cwd(),
662
- env = process.env,
663
- explicitApiUrl = "",
664
- autoRotate = true,
665
- rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
666
- tokenLabel = "",
667
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
668
- homeDir,
669
- } = {}) {
670
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
671
-
672
- const envToken = String(env.SENTINELAYER_TOKEN || "").trim();
673
- if (envToken) {
674
- return {
675
- apiUrl,
676
- token: envToken,
677
- source: "env",
678
- user: null,
679
- aidenid: null,
680
- storage: "env",
681
- tokenId: null,
682
- tokenPrefix: null,
683
- tokenExpiresAt: null,
684
- rotated: false,
685
- filePath: null,
686
- };
687
- }
688
-
689
- const config = await loadConfig({ cwd, env, homeDir });
690
- const configuredToken = String(config.resolved.sentinelayerToken || "").trim();
691
- if (configuredToken) {
692
- return {
693
- apiUrl,
694
- token: configuredToken,
695
- source: "config",
696
- user: null,
697
- aidenid: null,
698
- storage: "config",
699
- tokenId: null,
700
- tokenPrefix: null,
701
- tokenExpiresAt: null,
702
- rotated: false,
703
- filePath: null,
704
- };
705
- }
706
-
707
- const stored = await readStoredSession({ homeDir });
708
- if (!stored) {
709
- return null;
710
- }
711
-
712
- let active = stored;
713
- let rotated = false;
714
- if (autoRotate) {
715
- try {
716
- const rotateResult = await rotateStoredApiTokenIfNeeded({
717
- session: stored,
718
- thresholdDays: rotateThresholdDays,
719
- tokenLabel,
720
- tokenTtlDays,
721
- homeDir,
722
- });
723
- active = rotateResult.session;
724
- rotated = rotateResult.rotated;
725
- if (rotateResult.revokeError) {
726
- console.warn(
727
- "Sentinelayer token rotation succeeded but previous token revocation failed. " +
728
- "Revoke the old token manually in the dashboard if needed."
729
- );
730
- }
731
- } catch {
732
- // Keep existing token if rotation fails.
733
- active = stored;
734
- rotated = false;
735
- }
736
- }
737
-
738
- return {
739
- apiUrl,
740
- token: active.token,
741
- source: "session",
742
- user: normalizeUser(active.user || {}),
743
- aidenid: active.aidenid || null,
744
- storage: active.storage,
745
- tokenId: active.tokenId || null,
746
- tokenPrefix: active.tokenPrefix || null,
747
- tokenExpiresAt: active.tokenExpiresAt || null,
748
- rotated,
749
- filePath: active.filePath,
750
- };
751
- }
752
-
753
- /**
754
- * Return current authentication state, with optional remote `/auth/me` verification.
755
- *
756
- * @param {{
757
- * cwd?: string,
758
- * env?: NodeJS.ProcessEnv,
759
- * explicitApiUrl?: string,
760
- * checkRemote?: boolean,
761
- * autoRotate?: boolean,
762
- * rotateThresholdDays?: number,
763
- * tokenLabel?: string,
764
- * tokenTtlDays?: number,
765
- * homeDir?: string
766
- * }} [options]
767
- * @returns {Promise<{
768
- * authenticated: boolean,
769
- * apiUrl: string,
770
- * source: string | null,
771
- * storage: string | null,
772
- * user: any,
773
- * remoteUser: any,
774
- * remoteError: null | { code: string, message: string, status: number, requestId: string | null },
775
- * rotated: boolean,
776
- * tokenExpiresAt: string | null,
777
- * tokenPrefix: string | null,
778
- * tokenId: string | null,
779
- * filePath: string | null
780
- * }>}
781
- */
782
- export async function getAuthStatus({
783
- cwd = process.cwd(),
784
- env = process.env,
785
- explicitApiUrl = "",
786
- checkRemote = true,
787
- autoRotate = true,
788
- rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
789
- tokenLabel = "",
790
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
791
- homeDir,
792
- } = {}) {
793
- const session = await resolveActiveAuthSession({
794
- cwd,
795
- env,
796
- explicitApiUrl,
797
- autoRotate,
798
- rotateThresholdDays,
799
- tokenLabel,
800
- tokenTtlDays,
801
- homeDir,
802
- });
803
-
804
- if (!session) {
805
- return {
806
- authenticated: false,
807
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
808
- source: null,
809
- storage: null,
810
- user: null,
811
- aidenid: null,
812
- remoteUser: null,
813
- remoteError: null,
814
- rotated: false,
815
- tokenExpiresAt: null,
816
- tokenPrefix: null,
817
- tokenId: null,
818
- filePath: null,
819
- };
820
- }
821
-
822
- let remoteUser = null;
823
- let remoteError = null;
824
- if (checkRemote) {
825
- try {
826
- remoteUser = normalizeUser(await fetchCurrentUser({ apiUrl: session.apiUrl, token: session.token }));
827
- } catch (error) {
828
- remoteError =
829
- error instanceof SentinelayerApiError
830
- ? {
831
- code: error.code,
832
- message: error.message,
833
- status: error.status,
834
- requestId: error.requestId,
835
- }
836
- : {
837
- code: "UNKNOWN",
838
- message: error instanceof Error ? error.message : String(error || "Unknown error"),
839
- status: 500,
840
- requestId: null,
841
- };
842
- }
843
- }
844
-
845
- return {
846
- authenticated: !remoteError,
847
- apiUrl: session.apiUrl,
848
- source: session.source,
849
- storage: session.storage,
850
- user: session.user,
851
- aidenid: session.aidenid || null,
852
- remoteUser,
853
- remoteError,
854
- rotated: session.rotated,
855
- tokenExpiresAt: session.tokenExpiresAt,
856
- tokenPrefix: session.tokenPrefix,
857
- tokenId: session.tokenId,
858
- filePath: session.filePath,
859
- };
860
- }
861
-
862
- /**
863
- * List persisted local session metadata for CLI operators/HITL dashboards.
864
- *
865
- * @param {{ cwd?: string, env?: NodeJS.ProcessEnv, explicitApiUrl?: string, homeDir?: string }} [options]
866
- * @returns {Promise<{ apiUrl: string, sessions: Array<any> }>}
867
- */
868
- export async function listStoredAuthSessions({
869
- cwd = process.cwd(),
870
- env = process.env,
871
- explicitApiUrl = "",
872
- homeDir,
873
- } = {}) {
874
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
875
- const stored = await readStoredSessionMetadata({ homeDir });
876
- if (!stored) {
877
- return {
878
- apiUrl,
879
- sessions: [],
880
- };
881
- }
882
-
883
- return {
884
- apiUrl,
885
- sessions: [
886
- {
887
- source: "session",
888
- storage: stored.storage || null,
889
- tokenId: stored.tokenId || null,
890
- tokenPrefix: stored.tokenPrefix || null,
891
- tokenExpiresAt: stored.tokenExpiresAt || null,
892
- createdAt: stored.createdAt || null,
893
- updatedAt: stored.updatedAt || null,
894
- user: normalizeUser(stored.user || {}),
895
- filePath: stored.filePath || null,
896
- },
897
- ],
898
- };
899
- }
900
-
901
- /**
902
- * Revoke an API token remotely and clear matching local stored session metadata when applicable.
903
- *
904
- * @param {{
905
- * cwd?: string,
906
- * env?: NodeJS.ProcessEnv,
907
- * explicitApiUrl?: string,
908
- * tokenId?: string,
909
- * homeDir?: string
910
- * }} [options]
911
- * @returns {Promise<{
912
- * apiUrl: string,
913
- * source: string,
914
- * tokenId: string,
915
- * revokedRemote: boolean,
916
- * matchedStoredSession: boolean,
917
- * clearedLocal: boolean,
918
- * filePath: string | null
919
- * }>}
920
- */
921
- export async function revokeAuthToken({
922
- cwd = process.cwd(),
923
- env = process.env,
924
- explicitApiUrl = "",
925
- tokenId = "",
926
- homeDir,
927
- } = {}) {
928
- const active = await resolveActiveAuthSession({
929
- cwd,
930
- env,
931
- explicitApiUrl,
932
- autoRotate: false,
933
- homeDir,
934
- });
935
- if (!active || !active.token) {
936
- throw new SentinelayerApiError(`No active auth token found. Run \`${authLoginHint()}\` first.`, {
937
- status: 401,
938
- code: "AUTH_REQUIRED",
939
- });
940
- }
941
-
942
- const targetTokenId = String(tokenId || "").trim() || String(active.tokenId || "").trim();
943
- if (!targetTokenId) {
944
- throw new Error(
945
- "tokenId is required. Provide --token-id or use a stored session that includes token metadata."
946
- );
947
- }
948
-
949
- await revokeApiToken({
950
- apiUrl: active.apiUrl,
951
- authToken: active.token,
952
- tokenId: targetTokenId,
953
- });
954
-
955
- let matchedStoredSession = false;
956
- let clearedLocal = false;
957
- let filePath = null;
958
- const stored = await readStoredSession({ homeDir });
959
- if (stored && String(stored.tokenId || "").trim() === targetTokenId) {
960
- matchedStoredSession = true;
961
- const cleared = await clearStoredSession({ homeDir });
962
- clearedLocal = Boolean(cleared.hadSession);
963
- filePath = cleared.filePath || null;
964
- }
965
-
966
- return {
967
- apiUrl: active.apiUrl,
968
- source: active.source,
969
- tokenId: targetTokenId,
970
- revokedRemote: true,
971
- matchedStoredSession,
972
- clearedLocal,
973
- filePath,
974
- };
975
- }
976
-
977
- /**
978
- * Clear local CLI session state and optionally revoke the remote token first.
979
- *
980
- * @param {{
981
- * homeDir?: string,
982
- * cwd?: string,
983
- * env?: NodeJS.ProcessEnv,
984
- * explicitApiUrl?: string,
985
- * revokeRemote?: boolean
986
- * }} [options]
987
- * @returns {Promise<{
988
- * hadStoredSession: boolean,
989
- * revokedRemote: boolean,
990
- * clearedLocal: boolean,
991
- * apiUrl?: string,
992
- * filePath?: string
993
- * }>}
994
- */
995
- export async function logoutSession({
996
- homeDir,
997
- cwd = process.cwd(),
998
- env = process.env,
999
- explicitApiUrl = "",
1000
- revokeRemote = true,
1001
- } = {}) {
1002
- const stored = await readStoredSession({ homeDir });
1003
- if (!stored) {
1004
- return {
1005
- hadStoredSession: false,
1006
- revokedRemote: false,
1007
- clearedLocal: false,
1008
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
1009
- };
1010
- }
1011
-
1012
- let revokedRemote = false;
1013
- if (revokeRemote && stored.tokenId && stored.token) {
1014
- try {
1015
- await revokeApiToken({
1016
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
1017
- authToken: stored.token,
1018
- tokenId: stored.tokenId,
1019
- });
1020
- revokedRemote = true;
1021
- } catch {
1022
- revokedRemote = false;
1023
- }
1024
- }
1025
-
1026
- const cleared = await clearStoredSession({ homeDir });
1027
- return {
1028
- hadStoredSession: true,
1029
- revokedRemote,
1030
- clearedLocal: cleared.hadSession,
1031
- filePath: cleared.filePath,
1032
- };
1033
- }
1034
-
1035
- /**
1036
- * Fetch runtime run event stream slices used by `sl watch` and reproducibility artifacts.
1037
- *
1038
- * @param {{
1039
- * apiUrl: string,
1040
- * authToken: string,
1041
- * runId: string,
1042
- * afterEventId?: string | null
1043
- * }} [options]
1044
- * @returns {Promise<any>}
1045
- */
1046
- export async function listRuntimeRunEvents({
1047
- apiUrl,
1048
- authToken,
1049
- runId,
1050
- afterEventId = null,
1051
- } = {}) {
1052
- const query = afterEventId
1053
- ? `?after_event_id=${encodeURIComponent(String(afterEventId))}`
1054
- : "";
1055
- return requestJson(
1056
- buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/events/list${query}`),
1057
- {
1058
- method: "GET",
1059
- headers: toAuthHeader(authToken),
1060
- }
1061
- );
1062
- }
1063
-
1064
- /**
1065
- * Fetch runtime run status snapshot from the Sentinelayer API.
1066
- *
1067
- * @param {{ apiUrl: string, authToken: string, runId: string }} [options]
1068
- * @returns {Promise<any>}
1069
- */
1070
- /**
1071
- * Fetch AIdenID credentials from the SentinelLayer API (lazy-provisioning).
1072
- * The secret is returned in-memory only, never persisted to disk.
1073
- */
1074
- export async function fetchAidenIdCredentials({
1075
- apiUrl = DEFAULT_API_URL,
1076
- token = "",
1077
- } = {}) {
1078
- const response = await requestJson(
1079
- buildApiPath(apiUrl, "/api/v1/aidenid/credentials"),
1080
- {
1081
- method: "GET",
1082
- headers: toAuthHeader(token),
1083
- }
1084
- );
1085
- return {
1086
- orgId: String(response.orgId || response.org_id || "").trim(),
1087
- projectId: String(response.projectId || response.project_id || "").trim(),
1088
- apiKeyPrefix: String(response.apiKeyPrefix || response.api_key_prefix || "").trim(),
1089
- apiKey: String(response.apiKey || response.api_key || "").trim(),
1090
- provisioned: Boolean(response.provisioned),
1091
- };
1092
- }
1093
-
1094
- export async function getRuntimeRunStatus({
1095
- apiUrl,
1096
- authToken,
1097
- runId,
1098
- } = {}) {
1099
- return requestJson(
1100
- buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/status`),
1101
- {
1102
- method: "GET",
1103
- headers: toAuthHeader(authToken),
1104
- }
1105
- );
1106
- }
1
+ import crypto from "node:crypto";
2
+ import process from "node:process";
3
+ import { setTimeout as sleep } from "node:timers/promises";
4
+
5
+ import open from "open";
6
+
7
+ import { loadConfig } from "../config/service.js";
8
+ import { SentinelayerApiError, requestJson, requestJsonMutation } from "./http.js";
9
+ import {
10
+ clearStoredSession,
11
+ readStoredSession,
12
+ readStoredSessionMetadata,
13
+ writeStoredSession,
14
+ } from "./session-store.js";
15
+ import { authLoginHint } from "../ui/command-hints.js";
16
+
17
+ const DEFAULT_API_URL = "https://api.sentinelayer.com";
18
+ /** Default maximum wall-clock wait for browser-based CLI auth approval (ms). */
19
+ export const DEFAULT_AUTH_TIMEOUT_MS = 10 * 60 * 1000;
20
+ /** Default lifetime for issued API tokens used by CLI sessions (days). */
21
+ export const DEFAULT_API_TOKEN_TTL_DAYS = 365;
22
+ /** Default threshold at which stored tokens are rotated before expiry (days). */
23
+ export const DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS = 7;
24
+ const DEFAULT_IDE_NAME = "sl-cli";
25
+ const MAX_AUTH_POLL_REQUESTS = 600;
26
+ const MIN_TRANSIENT_POLL_DELAY_MS = 2_000;
27
+ const TRANSIENT_DELAY_THRESHOLD = 3;
28
+
29
+ function normalizeApiUrl(rawValue) {
30
+ const candidate = String(rawValue || "").trim() || DEFAULT_API_URL;
31
+ let parsed;
32
+ try {
33
+ parsed = new URL(candidate);
34
+ } catch {
35
+ throw new Error(`Invalid API URL '${candidate}'.`);
36
+ }
37
+ const hostname = String(parsed.hostname || "").toLowerCase();
38
+ const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1";
39
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLocalhost)) {
40
+ throw new Error(`API URL must use https (received '${candidate}').`);
41
+ }
42
+ parsed.pathname = "/";
43
+ parsed.search = "";
44
+ parsed.hash = "";
45
+ return parsed.toString().replace(/\/$/, "");
46
+ }
47
+
48
+ function normalizePositiveNumber(rawValue, field, fallbackValue) {
49
+ if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
50
+ return fallbackValue;
51
+ }
52
+ const normalized = Number(rawValue);
53
+ if (!Number.isFinite(normalized) || normalized <= 0) {
54
+ throw new Error(`${field} must be a positive number.`);
55
+ }
56
+ return normalized;
57
+ }
58
+
59
+ function toAuthHeader(token) {
60
+ return {
61
+ Authorization: `Bearer ${String(token || "").trim()}`,
62
+ };
63
+ }
64
+
65
+ function normalizeUser(user = {}) {
66
+ return {
67
+ id: String(user.id || "").trim(),
68
+ githubUsername: String(user.githubUsername || user.github_username || "").trim(),
69
+ email: String(user.email || "").trim(),
70
+ avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
71
+ isAdmin: Boolean(user.isAdmin || user.is_admin),
72
+ };
73
+ }
74
+
75
+ function buildApiPath(apiUrl, pathSuffix) {
76
+ return `${normalizeApiUrl(apiUrl)}${String(pathSuffix || "")}`;
77
+ }
78
+
79
+ function generateChallenge() {
80
+ return crypto.randomBytes(48).toString("base64url");
81
+ }
82
+
83
+ function createFlowRequestId() {
84
+ try {
85
+ return crypto.randomUUID();
86
+ } catch {
87
+ return `flow-${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
88
+ }
89
+ }
90
+
91
+ function withFlowRequestHeaders(headers, flowRequestId) {
92
+ const merged = {
93
+ ...(headers || {}),
94
+ "X-Request-Id": createFlowRequestId(),
95
+ };
96
+ if (flowRequestId) {
97
+ merged["X-Flow-Request-Id"] = flowRequestId;
98
+ }
99
+ return merged;
100
+ }
101
+
102
+ async function requestAuthJson(flowRequestId, ...args) {
103
+ try {
104
+ return await requestJson(...args);
105
+ } catch (error) {
106
+ if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
107
+ error.requestId = flowRequestId;
108
+ }
109
+ throw error;
110
+ }
111
+ }
112
+
113
+ async function requestAuthJsonMutation(flowRequestId, ...args) {
114
+ try {
115
+ return await requestJsonMutation(...args);
116
+ } catch (error) {
117
+ if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
118
+ error.requestId = flowRequestId;
119
+ }
120
+ throw error;
121
+ }
122
+ }
123
+
124
+ function defaultTokenLabel() {
125
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
126
+ return `sl-cli-session-${stamp}`;
127
+ }
128
+
129
+ function createIdempotencyKey(prefix) {
130
+ const normalizedPrefix = String(prefix || "sl-cli").trim() || "sl-cli";
131
+ let suffix;
132
+ try {
133
+ suffix = crypto.randomUUID();
134
+ } catch {
135
+ suffix = `${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
136
+ }
137
+ return `${normalizedPrefix}-${suffix}`;
138
+ }
139
+
140
+ function computeDeterministicJitterFactor({ sessionId, attempt }) {
141
+ const seed = `${String(sessionId || "").trim()}|${Number(attempt) || 0}`;
142
+ const digest = crypto.createHash("sha256").update(seed).digest();
143
+ const raw = digest.readUInt32BE(0);
144
+ const ratio = raw / 0xffffffff;
145
+ return 0.85 + ratio * 0.3;
146
+ }
147
+
148
+ function isNearExpiry(tokenExpiresAt, thresholdDays) {
149
+ const normalized = String(tokenExpiresAt || "").trim();
150
+ if (!normalized) {
151
+ return false;
152
+ }
153
+ const expiryEpoch = Date.parse(normalized);
154
+ if (!Number.isFinite(expiryEpoch)) {
155
+ return false;
156
+ }
157
+ const thresholdMs = Number(thresholdDays || DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS) * 24 * 60 * 60 * 1000;
158
+ return expiryEpoch - Date.now() <= thresholdMs;
159
+ }
160
+
161
+ /**
162
+ * Resolve API URL precedence for auth operations: explicit -> env -> config -> default.
163
+ *
164
+ * @param {{
165
+ * cwd?: string,
166
+ * env?: NodeJS.ProcessEnv,
167
+ * explicitApiUrl?: string,
168
+ * homeDir?: string
169
+ * }} [options]
170
+ * @returns {Promise<string>}
171
+ */
172
+ export async function resolveApiUrl({
173
+ cwd = process.cwd(),
174
+ env = process.env,
175
+ explicitApiUrl = "",
176
+ homeDir,
177
+ } = {}) {
178
+ const overrideUrl = String(explicitApiUrl || "").trim();
179
+ if (overrideUrl) {
180
+ return normalizeApiUrl(overrideUrl);
181
+ }
182
+
183
+ const envUrl = String(env.SENTINELAYER_API_URL || "").trim();
184
+ if (envUrl) {
185
+ return normalizeApiUrl(envUrl);
186
+ }
187
+
188
+ const config = await loadConfig({ cwd, env, homeDir });
189
+ const configuredApiUrl = String(config.resolved.apiUrl || "").trim();
190
+ if (configuredApiUrl) {
191
+ return normalizeApiUrl(configuredApiUrl);
192
+ }
193
+
194
+ return normalizeApiUrl(DEFAULT_API_URL);
195
+ }
196
+
197
+ async function startCliAuthSession({ apiUrl, challenge, ide, cliVersion, flowRequestId }) {
198
+ return requestAuthJsonMutation(
199
+ flowRequestId,
200
+ buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/start"),
201
+ {
202
+ method: "POST",
203
+ operationName: "auth-start",
204
+ headers: withFlowRequestHeaders(null, flowRequestId),
205
+ body: {
206
+ challenge,
207
+ ide: String(ide || DEFAULT_IDE_NAME),
208
+ cli_version: String(cliVersion || "").trim() || null,
209
+ },
210
+ }
211
+ );
212
+ }
213
+
214
+ async function pollCliAuthSession({
215
+ apiUrl,
216
+ sessionId,
217
+ challenge,
218
+ timeoutMs,
219
+ pollIntervalSeconds,
220
+ flowRequestId,
221
+ }) {
222
+ const timeout = normalizePositiveNumber(timeoutMs, "timeoutMs", DEFAULT_AUTH_TIMEOUT_MS);
223
+ const pollIntervalMs = Math.max(250, Math.round(Number(pollIntervalSeconds || 2) * 1000));
224
+ const maxPollIntervalMs = Math.max(pollIntervalMs, Math.min(5_000, Math.floor(timeout / 4)));
225
+ const pollRequestTimeoutMs = Math.min(5_000, Math.max(1_000, pollIntervalMs));
226
+ const pollRequestMaxRetries = 1;
227
+ const pollRequestRetryDelayMs = 250;
228
+ let pollAttempt = 0;
229
+ const transientErrorBudget = Math.max(8, Math.ceil(timeout / maxPollIntervalMs) * 3);
230
+ const maxSleepBudgetMs = Math.max(2_000, Math.floor(timeout * 0.8));
231
+ const maxPollAttempts = Math.min(
232
+ MAX_AUTH_POLL_REQUESTS,
233
+ Math.max(1, Math.ceil(timeout / Math.max(250, pollIntervalMs)))
234
+ );
235
+ let rateLimitErrorCount = 0;
236
+ let serverErrorCount = 0;
237
+ let networkErrorCount = 0;
238
+ let transientBudgetUsed = 0;
239
+ let cumulativeSleepMs = 0;
240
+ let pollIterations = 0;
241
+ const deadline = Date.now() + timeout;
242
+ const classifyPollError = (error) => {
243
+ if (!(error instanceof SentinelayerApiError)) {
244
+ return null;
245
+ }
246
+ if (error.status === 429) {
247
+ return "rate_limit";
248
+ }
249
+ if (error.status >= 500) {
250
+ return "server";
251
+ }
252
+ if (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT") {
253
+ return "network";
254
+ }
255
+ return null;
256
+ };
257
+ const computePollDelayMs = (retryAfterMs = null) => {
258
+ const transientErrorCount = rateLimitErrorCount + serverErrorCount + networkErrorCount;
259
+ const minDelayMs =
260
+ transientErrorCount >= TRANSIENT_DELAY_THRESHOLD ? MIN_TRANSIENT_POLL_DELAY_MS : 250;
261
+ if (Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
262
+ return Math.max(minDelayMs, Math.min(maxPollIntervalMs, Math.round(retryAfterMs)));
263
+ }
264
+ const exponent = Math.min(6, pollAttempt);
265
+ const backoffMs = Math.min(maxPollIntervalMs, Math.round(pollIntervalMs * Math.pow(1.5, exponent)));
266
+ const jitterFactor = computeDeterministicJitterFactor({ sessionId, attempt: pollAttempt });
267
+ return Math.max(minDelayMs, Math.round(backoffMs * jitterFactor));
268
+ };
269
+
270
+ while (Date.now() < deadline) {
271
+ const remainingBeforeRequestMs = deadline - Date.now();
272
+ if (remainingBeforeRequestMs <= 250) {
273
+ break;
274
+ }
275
+ pollIterations += 1;
276
+ if (pollIterations > maxPollAttempts) {
277
+ throw new SentinelayerApiError("CLI authentication polling exceeded attempt budget.", {
278
+ status: 408,
279
+ code: "CLI_AUTH_POLL_EXHAUSTED",
280
+ requestId: flowRequestId || null,
281
+ });
282
+ }
283
+ let payload;
284
+ try {
285
+ payload = await requestAuthJsonMutation(
286
+ flowRequestId,
287
+ buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/poll"),
288
+ {
289
+ method: "POST",
290
+ operationName: "auth-poll",
291
+ headers: withFlowRequestHeaders(null, flowRequestId),
292
+ body: {
293
+ session_id: sessionId,
294
+ challenge,
295
+ },
296
+ timeoutMs: Math.max(250, Math.min(pollRequestTimeoutMs, remainingBeforeRequestMs)),
297
+ maxRetries: pollRequestMaxRetries,
298
+ retryDelayMs: pollRequestRetryDelayMs,
299
+ }
300
+ );
301
+ } catch (error) {
302
+ if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
303
+ error.requestId = flowRequestId;
304
+ }
305
+ const classification = classifyPollError(error);
306
+ if (classification) {
307
+ const transientWeight = classification === "rate_limit" ? 3 : classification === "server" ? 2 : 1;
308
+ if (transientBudgetUsed + transientWeight > transientErrorBudget) {
309
+ throw new SentinelayerApiError("CLI authentication polling exhausted transient error budget.", {
310
+ status: 503,
311
+ code: "CLI_AUTH_TRANSIENT_BUDGET_EXHAUSTED",
312
+ requestId: error.requestId || flowRequestId || null,
313
+ });
314
+ }
315
+ transientBudgetUsed += transientWeight;
316
+ if (classification === "rate_limit") {
317
+ rateLimitErrorCount += 1;
318
+ } else if (classification === "server") {
319
+ serverErrorCount += 1;
320
+ } else {
321
+ networkErrorCount += 1;
322
+ }
323
+ const retryAfterMs = Number.isFinite(error.retryAfterMs) ? error.retryAfterMs : null;
324
+ const delayMs = computePollDelayMs(retryAfterMs);
325
+ const remainingBeforeSleepMs = deadline - Date.now();
326
+ if (remainingBeforeSleepMs <= 250) {
327
+ break;
328
+ }
329
+ const boundedDelayMs = Math.max(250, Math.min(delayMs, remainingBeforeSleepMs));
330
+ if (cumulativeSleepMs + boundedDelayMs > maxSleepBudgetMs) {
331
+ throw new SentinelayerApiError("CLI authentication polling exceeded retry sleep budget.", {
332
+ status: 503,
333
+ code: "CLI_AUTH_SLEEP_BUDGET_EXHAUSTED",
334
+ requestId: error.requestId || flowRequestId || null,
335
+ });
336
+ }
337
+ cumulativeSleepMs += boundedDelayMs;
338
+ pollAttempt += 1;
339
+ await sleep(boundedDelayMs);
340
+ continue;
341
+ }
342
+ throw error;
343
+ }
344
+
345
+ const status = String(payload.status || "pending").trim().toLowerCase();
346
+ if (status === "approved" && payload.auth_token) {
347
+ return payload;
348
+ }
349
+ if (status === "rejected" || status === "denied" || status === "cancelled") {
350
+ throw new SentinelayerApiError("CLI authentication was not approved.", {
351
+ status: 401,
352
+ code: "CLI_AUTH_REJECTED",
353
+ requestId: flowRequestId || null,
354
+ });
355
+ }
356
+ if (status === "expired") {
357
+ throw new SentinelayerApiError("CLI authentication session expired.", {
358
+ status: 401,
359
+ code: "CLI_AUTH_EXPIRED",
360
+ requestId: flowRequestId || null,
361
+ });
362
+ }
363
+
364
+ const delayMs = computePollDelayMs();
365
+ const remainingBeforeSleepMs = deadline - Date.now();
366
+ if (remainingBeforeSleepMs <= 250) {
367
+ break;
368
+ }
369
+ const boundedDelayMs = Math.max(250, Math.min(delayMs, remainingBeforeSleepMs));
370
+ pollAttempt += 1;
371
+ await sleep(boundedDelayMs);
372
+ }
373
+
374
+ throw new SentinelayerApiError("CLI authentication timed out. Restart and try again.", {
375
+ status: 408,
376
+ code: "CLI_AUTH_TIMEOUT",
377
+ requestId: flowRequestId || null,
378
+ });
379
+ }
380
+
381
+ async function fetchCurrentUser({ apiUrl, token, flowRequestId }) {
382
+ return requestAuthJson(
383
+ flowRequestId,
384
+ buildApiPath(apiUrl, "/api/v1/auth/me"),
385
+ {
386
+ method: "GET",
387
+ headers: withFlowRequestHeaders(toAuthHeader(token), flowRequestId),
388
+ }
389
+ );
390
+ }
391
+
392
+ async function issueApiToken({
393
+ apiUrl,
394
+ authToken,
395
+ tokenLabel,
396
+ tokenTtlDays,
397
+ flowRequestId,
398
+ }) {
399
+ const expiresInDays = Math.round(
400
+ normalizePositiveNumber(tokenTtlDays, "apiTokenTtlDays", DEFAULT_API_TOKEN_TTL_DAYS)
401
+ );
402
+ return requestAuthJsonMutation(
403
+ flowRequestId,
404
+ buildApiPath(apiUrl, "/api/v1/auth/api-tokens"),
405
+ {
406
+ method: "POST",
407
+ operationName: "issue-token",
408
+ headers: withFlowRequestHeaders(
409
+ {
410
+ ...toAuthHeader(authToken),
411
+ },
412
+ flowRequestId
413
+ ),
414
+ body: {
415
+ label: String(tokenLabel || "").trim() || defaultTokenLabel(),
416
+ scope: "cli",
417
+ llm_credential_mode: "managed",
418
+ expires_in_days: expiresInDays,
419
+ },
420
+ }
421
+ );
422
+ }
423
+
424
+ async function revokeApiToken({ apiUrl, authToken, tokenId }) {
425
+ const normalizedTokenId = String(tokenId || "").trim();
426
+ if (!normalizedTokenId) {
427
+ return false;
428
+ }
429
+ await requestJsonMutation(buildApiPath(apiUrl, `/api/v1/auth/api-tokens/${encodeURIComponent(normalizedTokenId)}`), {
430
+ method: "DELETE",
431
+ operationName: "revoke-token",
432
+ headers: {
433
+ ...toAuthHeader(authToken),
434
+ },
435
+ });
436
+ return true;
437
+ }
438
+
439
+ async function rotateStoredApiTokenIfNeeded({
440
+ session,
441
+ thresholdDays,
442
+ tokenLabel,
443
+ tokenTtlDays,
444
+ homeDir,
445
+ }) {
446
+ if (!session || !session.token || !session.tokenExpiresAt) {
447
+ return { session, rotated: false };
448
+ }
449
+ if (!isNearExpiry(session.tokenExpiresAt, thresholdDays)) {
450
+ return { session, rotated: false };
451
+ }
452
+
453
+ const issued = await issueApiToken({
454
+ apiUrl: session.apiUrl,
455
+ authToken: session.token,
456
+ tokenLabel,
457
+ tokenTtlDays,
458
+ });
459
+
460
+ const nextSession = await writeStoredSession(
461
+ {
462
+ apiUrl: session.apiUrl,
463
+ token: String(issued.token || ""),
464
+ tokenId: issued.id || null,
465
+ tokenPrefix: issued.token_prefix || null,
466
+ tokenExpiresAt: issued.expires_at || null,
467
+ user: session.user,
468
+ },
469
+ { homeDir }
470
+ );
471
+
472
+ let revokeError = null;
473
+ if (session.tokenId) {
474
+ try {
475
+ await revokeApiToken({
476
+ apiUrl: session.apiUrl,
477
+ authToken: nextSession.token,
478
+ tokenId: session.tokenId,
479
+ });
480
+ } catch (error) {
481
+ revokeError = error;
482
+ }
483
+ }
484
+
485
+ return {
486
+ session: nextSession,
487
+ rotated: true,
488
+ revokeError,
489
+ };
490
+ }
491
+
492
+ /**
493
+ * Perform browser-based CLI login flow and persist an API token session locally.
494
+ *
495
+ * @param {{
496
+ * cwd?: string,
497
+ * env?: NodeJS.ProcessEnv,
498
+ * explicitApiUrl?: string,
499
+ * skipBrowserOpen?: boolean,
500
+ * timeoutMs?: number,
501
+ * tokenLabel?: string,
502
+ * tokenTtlDays?: number,
503
+ * ide?: string,
504
+ * cliVersion?: string,
505
+ * homeDir?: string
506
+ * }} [options]
507
+ * @returns {Promise<{
508
+ * apiUrl: string,
509
+ * authorizeUrl: string,
510
+ * browserOpened: boolean,
511
+ * user: {
512
+ * id: string,
513
+ * githubUsername: string,
514
+ * email: string,
515
+ * avatarUrl: string,
516
+ * isAdmin: boolean
517
+ * },
518
+ * tokenId: string | null,
519
+ * tokenPrefix: string | null,
520
+ * tokenExpiresAt: string | null,
521
+ * storage: string,
522
+ * filePath: string
523
+ * }>}
524
+ */
525
+ export async function loginAndPersistSession({
526
+ cwd = process.cwd(),
527
+ env = process.env,
528
+ explicitApiUrl = "",
529
+ skipBrowserOpen = false,
530
+ timeoutMs = DEFAULT_AUTH_TIMEOUT_MS,
531
+ tokenLabel = "",
532
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
533
+ ide = DEFAULT_IDE_NAME,
534
+ cliVersion = "",
535
+ homeDir,
536
+ } = {}) {
537
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
538
+ const challenge = generateChallenge();
539
+ const flowRequestId = createFlowRequestId();
540
+ const session = await startCliAuthSession({
541
+ apiUrl,
542
+ challenge,
543
+ ide,
544
+ cliVersion,
545
+ flowRequestId,
546
+ });
547
+
548
+ const authorizeUrl = String(session.authorize_url || "").trim();
549
+ let browserOpened = false;
550
+ if (!skipBrowserOpen && authorizeUrl) {
551
+ try {
552
+ await open(authorizeUrl);
553
+ browserOpened = true;
554
+ } catch {
555
+ browserOpened = false;
556
+ }
557
+ }
558
+
559
+ const approval = await pollCliAuthSession({
560
+ apiUrl,
561
+ sessionId: String(session.session_id || "").trim(),
562
+ challenge,
563
+ timeoutMs,
564
+ pollIntervalSeconds: Number(session.poll_interval_seconds || 2),
565
+ flowRequestId,
566
+ });
567
+
568
+ const approvalToken = String(approval.auth_token || "").trim();
569
+ if (!approvalToken) {
570
+ throw new SentinelayerApiError("Authentication completed but no auth token was returned.", {
571
+ status: 503,
572
+ code: "CLI_AUTH_MISSING_TOKEN",
573
+ requestId: flowRequestId || null,
574
+ });
575
+ }
576
+
577
+ const user = normalizeUser(
578
+ approval.user || (await fetchCurrentUser({ apiUrl, token: approvalToken, flowRequestId }))
579
+ );
580
+ const issuedApiToken = await issueApiToken({
581
+ apiUrl,
582
+ authToken: approvalToken,
583
+ tokenLabel,
584
+ tokenTtlDays,
585
+ flowRequestId,
586
+ });
587
+
588
+ // Extract AIdenID metadata from approval (no secret stored locally)
589
+ const rawAidenId = approval.aidenidCredentials || approval.aidenid_credentials || null;
590
+ const aidenid =
591
+ rawAidenId && rawAidenId.provisioned
592
+ ? {
593
+ orgId: String(rawAidenId.orgId || rawAidenId.org_id || "").trim() || null,
594
+ projectId: String(rawAidenId.projectId || rawAidenId.project_id || "").trim() || null,
595
+ apiKeyPrefix: String(rawAidenId.apiKeyPrefix || rawAidenId.api_key_prefix || "").trim() || null,
596
+ provisionedAt: new Date().toISOString(),
597
+ }
598
+ : null;
599
+
600
+ const stored = await writeStoredSession(
601
+ {
602
+ apiUrl,
603
+ token: String(issuedApiToken.token || ""),
604
+ tokenId: issuedApiToken.id || null,
605
+ tokenPrefix: issuedApiToken.token_prefix || null,
606
+ tokenExpiresAt: issuedApiToken.expires_at || null,
607
+ user,
608
+ aidenid,
609
+ },
610
+ { homeDir }
611
+ );
612
+
613
+ return {
614
+ apiUrl,
615
+ authorizeUrl,
616
+ browserOpened,
617
+ user,
618
+ tokenId: stored.tokenId,
619
+ tokenPrefix: stored.tokenPrefix,
620
+ tokenExpiresAt: stored.tokenExpiresAt,
621
+ storage: stored.storage,
622
+ filePath: stored.filePath,
623
+ aidenid: stored.aidenid || null,
624
+ flowRequestId,
625
+ };
626
+ }
627
+
628
+ /**
629
+ * Resolve active auth credentials used by CLI commands, optionally rotating near-expiry session tokens.
630
+ *
631
+ * @param {{
632
+ * cwd?: string,
633
+ * env?: NodeJS.ProcessEnv,
634
+ * explicitApiUrl?: string,
635
+ * autoRotate?: boolean,
636
+ * rotateThresholdDays?: number,
637
+ * tokenLabel?: string,
638
+ * tokenTtlDays?: number,
639
+ * homeDir?: string
640
+ * }} [options]
641
+ * @returns {Promise<null | {
642
+ * apiUrl: string,
643
+ * token: string,
644
+ * source: "env" | "config" | "session",
645
+ * user: {
646
+ * id: string,
647
+ * githubUsername: string,
648
+ * email: string,
649
+ * avatarUrl: string,
650
+ * isAdmin: boolean
651
+ * } | null,
652
+ * storage: string,
653
+ * tokenId: string | null,
654
+ * tokenPrefix: string | null,
655
+ * tokenExpiresAt: string | null,
656
+ * rotated: boolean,
657
+ * filePath: string | null
658
+ * }>}
659
+ */
660
+ export async function resolveActiveAuthSession({
661
+ cwd = process.cwd(),
662
+ env = process.env,
663
+ explicitApiUrl = "",
664
+ autoRotate = true,
665
+ rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
666
+ tokenLabel = "",
667
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
668
+ homeDir,
669
+ } = {}) {
670
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
671
+
672
+ const envToken = String(env.SENTINELAYER_TOKEN || "").trim();
673
+ if (envToken) {
674
+ return {
675
+ apiUrl,
676
+ token: envToken,
677
+ source: "env",
678
+ user: null,
679
+ aidenid: null,
680
+ storage: "env",
681
+ tokenId: null,
682
+ tokenPrefix: null,
683
+ tokenExpiresAt: null,
684
+ rotated: false,
685
+ filePath: null,
686
+ };
687
+ }
688
+
689
+ const config = await loadConfig({ cwd, env, homeDir });
690
+ const configuredToken = String(config.resolved.sentinelayerToken || "").trim();
691
+ if (configuredToken) {
692
+ return {
693
+ apiUrl,
694
+ token: configuredToken,
695
+ source: "config",
696
+ user: null,
697
+ aidenid: null,
698
+ storage: "config",
699
+ tokenId: null,
700
+ tokenPrefix: null,
701
+ tokenExpiresAt: null,
702
+ rotated: false,
703
+ filePath: null,
704
+ };
705
+ }
706
+
707
+ const stored = await readStoredSession({ homeDir });
708
+ if (!stored) {
709
+ return null;
710
+ }
711
+
712
+ let active = stored;
713
+ let rotated = false;
714
+ if (autoRotate) {
715
+ try {
716
+ const rotateResult = await rotateStoredApiTokenIfNeeded({
717
+ session: stored,
718
+ thresholdDays: rotateThresholdDays,
719
+ tokenLabel,
720
+ tokenTtlDays,
721
+ homeDir,
722
+ });
723
+ active = rotateResult.session;
724
+ rotated = rotateResult.rotated;
725
+ if (rotateResult.revokeError) {
726
+ console.warn(
727
+ "Sentinelayer token rotation succeeded but previous token revocation failed. " +
728
+ "Revoke the old token manually in the dashboard if needed."
729
+ );
730
+ }
731
+ } catch {
732
+ // Keep existing token if rotation fails.
733
+ active = stored;
734
+ rotated = false;
735
+ }
736
+ }
737
+
738
+ return {
739
+ apiUrl,
740
+ token: active.token,
741
+ source: "session",
742
+ user: normalizeUser(active.user || {}),
743
+ aidenid: active.aidenid || null,
744
+ storage: active.storage,
745
+ tokenId: active.tokenId || null,
746
+ tokenPrefix: active.tokenPrefix || null,
747
+ tokenExpiresAt: active.tokenExpiresAt || null,
748
+ rotated,
749
+ filePath: active.filePath,
750
+ };
751
+ }
752
+
753
+ /**
754
+ * Return current authentication state, with optional remote `/auth/me` verification.
755
+ *
756
+ * @param {{
757
+ * cwd?: string,
758
+ * env?: NodeJS.ProcessEnv,
759
+ * explicitApiUrl?: string,
760
+ * checkRemote?: boolean,
761
+ * autoRotate?: boolean,
762
+ * rotateThresholdDays?: number,
763
+ * tokenLabel?: string,
764
+ * tokenTtlDays?: number,
765
+ * homeDir?: string
766
+ * }} [options]
767
+ * @returns {Promise<{
768
+ * authenticated: boolean,
769
+ * apiUrl: string,
770
+ * source: string | null,
771
+ * storage: string | null,
772
+ * user: any,
773
+ * remoteUser: any,
774
+ * remoteError: null | { code: string, message: string, status: number, requestId: string | null },
775
+ * rotated: boolean,
776
+ * tokenExpiresAt: string | null,
777
+ * tokenPrefix: string | null,
778
+ * tokenId: string | null,
779
+ * filePath: string | null
780
+ * }>}
781
+ */
782
+ export async function getAuthStatus({
783
+ cwd = process.cwd(),
784
+ env = process.env,
785
+ explicitApiUrl = "",
786
+ checkRemote = true,
787
+ autoRotate = true,
788
+ rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
789
+ tokenLabel = "",
790
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
791
+ homeDir,
792
+ } = {}) {
793
+ const session = await resolveActiveAuthSession({
794
+ cwd,
795
+ env,
796
+ explicitApiUrl,
797
+ autoRotate,
798
+ rotateThresholdDays,
799
+ tokenLabel,
800
+ tokenTtlDays,
801
+ homeDir,
802
+ });
803
+
804
+ if (!session) {
805
+ return {
806
+ authenticated: false,
807
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
808
+ source: null,
809
+ storage: null,
810
+ user: null,
811
+ aidenid: null,
812
+ remoteUser: null,
813
+ remoteError: null,
814
+ rotated: false,
815
+ tokenExpiresAt: null,
816
+ tokenPrefix: null,
817
+ tokenId: null,
818
+ filePath: null,
819
+ };
820
+ }
821
+
822
+ let remoteUser = null;
823
+ let remoteError = null;
824
+ if (checkRemote) {
825
+ try {
826
+ remoteUser = normalizeUser(await fetchCurrentUser({ apiUrl: session.apiUrl, token: session.token }));
827
+ } catch (error) {
828
+ remoteError =
829
+ error instanceof SentinelayerApiError
830
+ ? {
831
+ code: error.code,
832
+ message: error.message,
833
+ status: error.status,
834
+ requestId: error.requestId,
835
+ }
836
+ : {
837
+ code: "UNKNOWN",
838
+ message: error instanceof Error ? error.message : String(error || "Unknown error"),
839
+ status: 500,
840
+ requestId: null,
841
+ };
842
+ }
843
+ }
844
+
845
+ return {
846
+ authenticated: !remoteError,
847
+ apiUrl: session.apiUrl,
848
+ source: session.source,
849
+ storage: session.storage,
850
+ user: session.user,
851
+ aidenid: session.aidenid || null,
852
+ remoteUser,
853
+ remoteError,
854
+ rotated: session.rotated,
855
+ tokenExpiresAt: session.tokenExpiresAt,
856
+ tokenPrefix: session.tokenPrefix,
857
+ tokenId: session.tokenId,
858
+ filePath: session.filePath,
859
+ };
860
+ }
861
+
862
+ /**
863
+ * List persisted local session metadata for CLI operators/HITL dashboards.
864
+ *
865
+ * @param {{ cwd?: string, env?: NodeJS.ProcessEnv, explicitApiUrl?: string, homeDir?: string }} [options]
866
+ * @returns {Promise<{ apiUrl: string, sessions: Array<any> }>}
867
+ */
868
+ export async function listStoredAuthSessions({
869
+ cwd = process.cwd(),
870
+ env = process.env,
871
+ explicitApiUrl = "",
872
+ homeDir,
873
+ } = {}) {
874
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
875
+ const stored = await readStoredSessionMetadata({ homeDir });
876
+ if (!stored) {
877
+ return {
878
+ apiUrl,
879
+ sessions: [],
880
+ };
881
+ }
882
+
883
+ return {
884
+ apiUrl,
885
+ sessions: [
886
+ {
887
+ source: "session",
888
+ storage: stored.storage || null,
889
+ tokenId: stored.tokenId || null,
890
+ tokenPrefix: stored.tokenPrefix || null,
891
+ tokenExpiresAt: stored.tokenExpiresAt || null,
892
+ createdAt: stored.createdAt || null,
893
+ updatedAt: stored.updatedAt || null,
894
+ user: normalizeUser(stored.user || {}),
895
+ filePath: stored.filePath || null,
896
+ },
897
+ ],
898
+ };
899
+ }
900
+
901
+ /**
902
+ * Revoke an API token remotely and clear matching local stored session metadata when applicable.
903
+ *
904
+ * @param {{
905
+ * cwd?: string,
906
+ * env?: NodeJS.ProcessEnv,
907
+ * explicitApiUrl?: string,
908
+ * tokenId?: string,
909
+ * homeDir?: string
910
+ * }} [options]
911
+ * @returns {Promise<{
912
+ * apiUrl: string,
913
+ * source: string,
914
+ * tokenId: string,
915
+ * revokedRemote: boolean,
916
+ * matchedStoredSession: boolean,
917
+ * clearedLocal: boolean,
918
+ * filePath: string | null
919
+ * }>}
920
+ */
921
+ export async function revokeAuthToken({
922
+ cwd = process.cwd(),
923
+ env = process.env,
924
+ explicitApiUrl = "",
925
+ tokenId = "",
926
+ homeDir,
927
+ } = {}) {
928
+ const active = await resolveActiveAuthSession({
929
+ cwd,
930
+ env,
931
+ explicitApiUrl,
932
+ autoRotate: false,
933
+ homeDir,
934
+ });
935
+ if (!active || !active.token) {
936
+ throw new SentinelayerApiError(`No active auth token found. Run \`${authLoginHint()}\` first.`, {
937
+ status: 401,
938
+ code: "AUTH_REQUIRED",
939
+ });
940
+ }
941
+
942
+ const targetTokenId = String(tokenId || "").trim() || String(active.tokenId || "").trim();
943
+ if (!targetTokenId) {
944
+ throw new Error(
945
+ "tokenId is required. Provide --token-id or use a stored session that includes token metadata."
946
+ );
947
+ }
948
+
949
+ await revokeApiToken({
950
+ apiUrl: active.apiUrl,
951
+ authToken: active.token,
952
+ tokenId: targetTokenId,
953
+ });
954
+
955
+ let matchedStoredSession = false;
956
+ let clearedLocal = false;
957
+ let filePath = null;
958
+ const stored = await readStoredSession({ homeDir });
959
+ if (stored && String(stored.tokenId || "").trim() === targetTokenId) {
960
+ matchedStoredSession = true;
961
+ const cleared = await clearStoredSession({ homeDir });
962
+ clearedLocal = Boolean(cleared.hadSession);
963
+ filePath = cleared.filePath || null;
964
+ }
965
+
966
+ return {
967
+ apiUrl: active.apiUrl,
968
+ source: active.source,
969
+ tokenId: targetTokenId,
970
+ revokedRemote: true,
971
+ matchedStoredSession,
972
+ clearedLocal,
973
+ filePath,
974
+ };
975
+ }
976
+
977
+ /**
978
+ * Clear local CLI session state and optionally revoke the remote token first.
979
+ *
980
+ * @param {{
981
+ * homeDir?: string,
982
+ * cwd?: string,
983
+ * env?: NodeJS.ProcessEnv,
984
+ * explicitApiUrl?: string,
985
+ * revokeRemote?: boolean
986
+ * }} [options]
987
+ * @returns {Promise<{
988
+ * hadStoredSession: boolean,
989
+ * revokedRemote: boolean,
990
+ * clearedLocal: boolean,
991
+ * apiUrl?: string,
992
+ * filePath?: string
993
+ * }>}
994
+ */
995
+ export async function logoutSession({
996
+ homeDir,
997
+ cwd = process.cwd(),
998
+ env = process.env,
999
+ explicitApiUrl = "",
1000
+ revokeRemote = true,
1001
+ } = {}) {
1002
+ const stored = await readStoredSession({ homeDir });
1003
+ if (!stored) {
1004
+ return {
1005
+ hadStoredSession: false,
1006
+ revokedRemote: false,
1007
+ clearedLocal: false,
1008
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
1009
+ };
1010
+ }
1011
+
1012
+ let revokedRemote = false;
1013
+ if (revokeRemote && stored.tokenId && stored.token) {
1014
+ try {
1015
+ await revokeApiToken({
1016
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
1017
+ authToken: stored.token,
1018
+ tokenId: stored.tokenId,
1019
+ });
1020
+ revokedRemote = true;
1021
+ } catch {
1022
+ revokedRemote = false;
1023
+ }
1024
+ }
1025
+
1026
+ const cleared = await clearStoredSession({ homeDir });
1027
+ return {
1028
+ hadStoredSession: true,
1029
+ revokedRemote,
1030
+ clearedLocal: cleared.hadSession,
1031
+ filePath: cleared.filePath,
1032
+ };
1033
+ }
1034
+
1035
+ /**
1036
+ * Fetch runtime run event stream slices used by `sl watch` and reproducibility artifacts.
1037
+ *
1038
+ * @param {{
1039
+ * apiUrl: string,
1040
+ * authToken: string,
1041
+ * runId: string,
1042
+ * afterEventId?: string | null
1043
+ * }} [options]
1044
+ * @returns {Promise<any>}
1045
+ */
1046
+ export async function listRuntimeRunEvents({
1047
+ apiUrl,
1048
+ authToken,
1049
+ runId,
1050
+ afterEventId = null,
1051
+ } = {}) {
1052
+ const query = afterEventId
1053
+ ? `?after_event_id=${encodeURIComponent(String(afterEventId))}`
1054
+ : "";
1055
+ return requestJson(
1056
+ buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/events/list${query}`),
1057
+ {
1058
+ method: "GET",
1059
+ headers: toAuthHeader(authToken),
1060
+ }
1061
+ );
1062
+ }
1063
+
1064
+ /**
1065
+ * Fetch runtime run status snapshot from the Sentinelayer API.
1066
+ *
1067
+ * @param {{ apiUrl: string, authToken: string, runId: string }} [options]
1068
+ * @returns {Promise<any>}
1069
+ */
1070
+ /**
1071
+ * Fetch AIdenID credentials from the SentinelLayer API (lazy-provisioning).
1072
+ * The secret is returned in-memory only, never persisted to disk.
1073
+ */
1074
+ export async function fetchAidenIdCredentials({
1075
+ apiUrl = DEFAULT_API_URL,
1076
+ token = "",
1077
+ } = {}) {
1078
+ const response = await requestJson(
1079
+ buildApiPath(apiUrl, "/api/v1/aidenid/credentials"),
1080
+ {
1081
+ method: "GET",
1082
+ headers: toAuthHeader(token),
1083
+ }
1084
+ );
1085
+ return {
1086
+ orgId: String(response.orgId || response.org_id || "").trim(),
1087
+ projectId: String(response.projectId || response.project_id || "").trim(),
1088
+ apiKeyPrefix: String(response.apiKeyPrefix || response.api_key_prefix || "").trim(),
1089
+ apiKey: String(response.apiKey || response.api_key || "").trim(),
1090
+ provisioned: Boolean(response.provisioned),
1091
+ };
1092
+ }
1093
+
1094
+ export async function getRuntimeRunStatus({
1095
+ apiUrl,
1096
+ authToken,
1097
+ runId,
1098
+ } = {}) {
1099
+ return requestJson(
1100
+ buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/status`),
1101
+ {
1102
+ method: "GET",
1103
+ headers: toAuthHeader(authToken),
1104
+ }
1105
+ );
1106
+ }