sentinelayer-cli 0.1.2 → 0.4.4

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 (129) hide show
  1. package/README.md +998 -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 +63 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +327 -319
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +557 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +503 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/agents/jules/tools/url-policy.js +100 -0
  30. package/src/ai/aidenid.js +972 -945
  31. package/src/ai/client.js +508 -508
  32. package/src/ai/domain-target-store.js +268 -268
  33. package/src/ai/identity-store.js +270 -270
  34. package/src/ai/site-store.js +145 -145
  35. package/src/audit/agents/architecture.js +180 -180
  36. package/src/audit/agents/compliance.js +179 -179
  37. package/src/audit/agents/documentation.js +165 -165
  38. package/src/audit/agents/performance.js +145 -145
  39. package/src/audit/agents/security.js +215 -215
  40. package/src/audit/agents/testing.js +172 -172
  41. package/src/audit/orchestrator.js +557 -557
  42. package/src/audit/package.js +204 -204
  43. package/src/audit/registry.js +284 -284
  44. package/src/audit/replay.js +103 -103
  45. package/src/auth/gate.js +45 -11
  46. package/src/auth/http.js +270 -113
  47. package/src/auth/service.js +891 -848
  48. package/src/auth/session-store.js +359 -345
  49. package/src/cli.js +252 -252
  50. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  51. package/src/commands/ai/provision-governance.js +1272 -1246
  52. package/src/commands/ai/shared.js +147 -147
  53. package/src/commands/ai.js +11 -11
  54. package/src/commands/apply.js +12 -12
  55. package/src/commands/audit.js +1166 -1166
  56. package/src/commands/auth.js +375 -366
  57. package/src/commands/chat.js +191 -191
  58. package/src/commands/config.js +184 -184
  59. package/src/commands/cost.js +311 -311
  60. package/src/commands/daemon/core.js +850 -850
  61. package/src/commands/daemon/extended.js +1048 -1048
  62. package/src/commands/daemon/shared.js +213 -213
  63. package/src/commands/daemon.js +11 -11
  64. package/src/commands/guide.js +174 -174
  65. package/src/commands/ingest.js +58 -58
  66. package/src/commands/init.js +55 -55
  67. package/src/commands/legacy-args.js +10 -10
  68. package/src/commands/mcp.js +461 -404
  69. package/src/commands/omargate.js +15 -15
  70. package/src/commands/persona.js +20 -20
  71. package/src/commands/plugin.js +260 -260
  72. package/src/commands/policy.js +132 -132
  73. package/src/commands/prompt.js +238 -238
  74. package/src/commands/review.js +704 -704
  75. package/src/commands/scan.js +866 -788
  76. package/src/commands/spec.js +716 -716
  77. package/src/commands/swarm.js +651 -651
  78. package/src/commands/telemetry.js +202 -202
  79. package/src/commands/watch.js +510 -510
  80. package/src/config/agent-dictionary.js +182 -182
  81. package/src/config/io.js +56 -56
  82. package/src/config/paths.js +18 -18
  83. package/src/config/schema.js +55 -55
  84. package/src/config/service.js +184 -184
  85. package/src/cost/budget.js +235 -235
  86. package/src/cost/history.js +188 -188
  87. package/src/cost/tracker.js +171 -171
  88. package/src/daemon/artifact-lineage.js +534 -534
  89. package/src/daemon/assignment-ledger.js +770 -770
  90. package/src/daemon/ast-parser-layer.js +258 -258
  91. package/src/daemon/budget-governor.js +633 -633
  92. package/src/daemon/callgraph-overlay.js +646 -646
  93. package/src/daemon/error-worker.js +626 -626
  94. package/src/daemon/hybrid-mapper.js +929 -929
  95. package/src/daemon/jira-lifecycle.js +632 -632
  96. package/src/daemon/operator-control.js +657 -657
  97. package/src/daemon/reliability-lane.js +471 -471
  98. package/src/daemon/watchdog.js +971 -971
  99. package/src/guide/generator.js +316 -316
  100. package/src/ingest/engine.js +918 -918
  101. package/src/legacy-cli.js +2592 -2435
  102. package/src/mcp/registry.js +695 -695
  103. package/src/memory/blackboard.js +301 -301
  104. package/src/memory/retrieval.js +581 -581
  105. package/src/plugin/manifest.js +553 -553
  106. package/src/policy/packs.js +144 -144
  107. package/src/prompt/generator.js +118 -106
  108. package/src/review/ai-review.js +669 -669
  109. package/src/review/local-review.js +1295 -1284
  110. package/src/review/replay.js +235 -235
  111. package/src/review/report.js +664 -664
  112. package/src/review/spec-binding.js +487 -487
  113. package/src/scaffold/generator.js +67 -0
  114. package/src/scaffold/templates.js +150 -0
  115. package/src/scan/generator.js +418 -351
  116. package/src/scan/gh-secrets.js +107 -0
  117. package/src/spec/generator.js +519 -519
  118. package/src/spec/regenerate.js +237 -237
  119. package/src/spec/templates.js +91 -91
  120. package/src/swarm/dashboard.js +247 -247
  121. package/src/swarm/factory.js +363 -363
  122. package/src/swarm/pentest.js +934 -934
  123. package/src/swarm/registry.js +419 -419
  124. package/src/swarm/report.js +158 -158
  125. package/src/swarm/runtime.js +576 -576
  126. package/src/swarm/scenario-dsl.js +272 -272
  127. package/src/telemetry/ledger.js +302 -302
  128. package/src/telemetry/sync.js +107 -61
  129. package/src/ui/markdown.js +220 -220
@@ -1,848 +1,891 @@
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 } from "./http.js";
9
- import {
10
- clearStoredSession,
11
- readStoredSession,
12
- readStoredSessionMetadata,
13
- writeStoredSession,
14
- } from "./session-store.js";
15
-
16
- const DEFAULT_API_URL = "https://api.sentinelayer.com";
17
- /** Default maximum wall-clock wait for browser-based CLI auth approval (ms). */
18
- export const DEFAULT_AUTH_TIMEOUT_MS = 10 * 60 * 1000;
19
- /** Default lifetime for issued API tokens used by CLI sessions (days). */
20
- export const DEFAULT_API_TOKEN_TTL_DAYS = 365;
21
- /** Default threshold at which stored tokens are rotated before expiry (days). */
22
- export const DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS = 7;
23
- const DEFAULT_IDE_NAME = "sl-cli";
24
-
25
- function normalizeApiUrl(rawValue) {
26
- const candidate = String(rawValue || "").trim() || DEFAULT_API_URL;
27
- let parsed;
28
- try {
29
- parsed = new URL(candidate);
30
- } catch {
31
- throw new Error(`Invalid API URL '${candidate}'.`);
32
- }
33
- parsed.pathname = "/";
34
- parsed.search = "";
35
- parsed.hash = "";
36
- return parsed.toString().replace(/\/$/, "");
37
- }
38
-
39
- function normalizePositiveNumber(rawValue, field, fallbackValue) {
40
- if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
41
- return fallbackValue;
42
- }
43
- const normalized = Number(rawValue);
44
- if (!Number.isFinite(normalized) || normalized <= 0) {
45
- throw new Error(`${field} must be a positive number.`);
46
- }
47
- return normalized;
48
- }
49
-
50
- function toAuthHeader(token) {
51
- return {
52
- Authorization: `Bearer ${String(token || "").trim()}`,
53
- };
54
- }
55
-
56
- function normalizeUser(user = {}) {
57
- return {
58
- id: String(user.id || "").trim(),
59
- githubUsername: String(user.githubUsername || user.github_username || "").trim(),
60
- email: String(user.email || "").trim(),
61
- avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
62
- isAdmin: Boolean(user.isAdmin || user.is_admin),
63
- };
64
- }
65
-
66
- function buildApiPath(apiUrl, pathSuffix) {
67
- return `${normalizeApiUrl(apiUrl)}${String(pathSuffix || "")}`;
68
- }
69
-
70
- function generateChallenge() {
71
- return crypto.randomBytes(48).toString("base64url");
72
- }
73
-
74
- function defaultTokenLabel() {
75
- const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
76
- return `sl-cli-session-${stamp}`;
77
- }
78
-
79
- function isNearExpiry(tokenExpiresAt, thresholdDays) {
80
- const normalized = String(tokenExpiresAt || "").trim();
81
- if (!normalized) {
82
- return false;
83
- }
84
- const expiryEpoch = Date.parse(normalized);
85
- if (!Number.isFinite(expiryEpoch)) {
86
- return false;
87
- }
88
- const thresholdMs = Number(thresholdDays || DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS) * 24 * 60 * 60 * 1000;
89
- return expiryEpoch - Date.now() <= thresholdMs;
90
- }
91
-
92
- /**
93
- * Resolve API URL precedence for auth operations: explicit -> env -> config -> default.
94
- *
95
- * @param {{
96
- * cwd?: string,
97
- * env?: NodeJS.ProcessEnv,
98
- * explicitApiUrl?: string,
99
- * homeDir?: string
100
- * }} [options]
101
- * @returns {Promise<string>}
102
- */
103
- export async function resolveApiUrl({
104
- cwd = process.cwd(),
105
- env = process.env,
106
- explicitApiUrl = "",
107
- homeDir,
108
- } = {}) {
109
- const overrideUrl = String(explicitApiUrl || "").trim();
110
- if (overrideUrl) {
111
- return normalizeApiUrl(overrideUrl);
112
- }
113
-
114
- const envUrl = String(env.SENTINELAYER_API_URL || "").trim();
115
- if (envUrl) {
116
- return normalizeApiUrl(envUrl);
117
- }
118
-
119
- const config = await loadConfig({ cwd, env, homeDir });
120
- const configuredApiUrl = String(config.resolved.apiUrl || "").trim();
121
- if (configuredApiUrl) {
122
- return normalizeApiUrl(configuredApiUrl);
123
- }
124
-
125
- return normalizeApiUrl(DEFAULT_API_URL);
126
- }
127
-
128
- async function startCliAuthSession({ apiUrl, challenge, ide, cliVersion }) {
129
- return requestJson(buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/start"), {
130
- method: "POST",
131
- body: {
132
- challenge,
133
- ide: String(ide || DEFAULT_IDE_NAME),
134
- cli_version: String(cliVersion || "").trim() || null,
135
- },
136
- });
137
- }
138
-
139
- async function pollCliAuthSession({
140
- apiUrl,
141
- sessionId,
142
- challenge,
143
- timeoutMs,
144
- pollIntervalSeconds,
145
- }) {
146
- const timeout = normalizePositiveNumber(timeoutMs, "timeoutMs", DEFAULT_AUTH_TIMEOUT_MS);
147
- const pollIntervalMs = Math.max(250, Math.round(Number(pollIntervalSeconds || 2) * 1000));
148
- const deadline = Date.now() + timeout;
149
- const isTransientPollError = (error) =>
150
- error instanceof SentinelayerApiError &&
151
- (error.code === "NETWORK_ERROR" ||
152
- error.code === "TIMEOUT" ||
153
- error.status === 429 ||
154
- error.status >= 500);
155
-
156
- while (Date.now() < deadline) {
157
- let payload;
158
- try {
159
- payload = await requestJson(buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/poll"), {
160
- method: "POST",
161
- body: {
162
- session_id: sessionId,
163
- challenge,
164
- },
165
- });
166
- } catch (error) {
167
- if (isTransientPollError(error)) {
168
- await sleep(pollIntervalMs);
169
- continue;
170
- }
171
- throw error;
172
- }
173
-
174
- const status = String(payload.status || "pending").trim().toLowerCase();
175
- if (status === "approved" && payload.auth_token) {
176
- return payload;
177
- }
178
- if (status === "rejected" || status === "denied" || status === "cancelled") {
179
- throw new SentinelayerApiError("CLI authentication was not approved.", {
180
- status: 401,
181
- code: "CLI_AUTH_REJECTED",
182
- });
183
- }
184
- if (status === "expired") {
185
- throw new SentinelayerApiError("CLI authentication session expired.", {
186
- status: 401,
187
- code: "CLI_AUTH_EXPIRED",
188
- });
189
- }
190
-
191
- await sleep(pollIntervalMs);
192
- }
193
-
194
- throw new SentinelayerApiError("CLI authentication timed out. Restart and try again.", {
195
- status: 408,
196
- code: "CLI_AUTH_TIMEOUT",
197
- });
198
- }
199
-
200
- async function fetchCurrentUser({ apiUrl, token }) {
201
- return requestJson(buildApiPath(apiUrl, "/api/v1/auth/me"), {
202
- method: "GET",
203
- headers: toAuthHeader(token),
204
- });
205
- }
206
-
207
- async function issueApiToken({
208
- apiUrl,
209
- authToken,
210
- tokenLabel,
211
- tokenTtlDays,
212
- }) {
213
- const expiresInDays = Math.round(
214
- normalizePositiveNumber(tokenTtlDays, "apiTokenTtlDays", DEFAULT_API_TOKEN_TTL_DAYS)
215
- );
216
- return requestJson(buildApiPath(apiUrl, "/api/v1/auth/api-tokens"), {
217
- method: "POST",
218
- headers: toAuthHeader(authToken),
219
- body: {
220
- label: String(tokenLabel || "").trim() || defaultTokenLabel(),
221
- scope: "github_app_bridge",
222
- llm_credential_mode: "managed",
223
- expires_in_days: expiresInDays,
224
- },
225
- });
226
- }
227
-
228
- async function revokeApiToken({ apiUrl, authToken, tokenId }) {
229
- const normalizedTokenId = String(tokenId || "").trim();
230
- if (!normalizedTokenId) {
231
- return false;
232
- }
233
- await requestJson(buildApiPath(apiUrl, `/api/v1/auth/api-tokens/${encodeURIComponent(normalizedTokenId)}`), {
234
- method: "DELETE",
235
- headers: toAuthHeader(authToken),
236
- });
237
- return true;
238
- }
239
-
240
- async function rotateStoredApiTokenIfNeeded({
241
- session,
242
- thresholdDays,
243
- tokenLabel,
244
- tokenTtlDays,
245
- homeDir,
246
- }) {
247
- if (!session || !session.token || !session.tokenExpiresAt) {
248
- return { session, rotated: false };
249
- }
250
- if (!isNearExpiry(session.tokenExpiresAt, thresholdDays)) {
251
- return { session, rotated: false };
252
- }
253
-
254
- const issued = await issueApiToken({
255
- apiUrl: session.apiUrl,
256
- authToken: session.token,
257
- tokenLabel,
258
- tokenTtlDays,
259
- });
260
-
261
- const nextSession = await writeStoredSession(
262
- {
263
- apiUrl: session.apiUrl,
264
- token: String(issued.token || ""),
265
- tokenId: issued.id || null,
266
- tokenPrefix: issued.token_prefix || null,
267
- tokenExpiresAt: issued.expires_at || null,
268
- user: session.user,
269
- },
270
- { homeDir }
271
- );
272
-
273
- if (session.tokenId) {
274
- try {
275
- await revokeApiToken({
276
- apiUrl: session.apiUrl,
277
- authToken: nextSession.token,
278
- tokenId: session.tokenId,
279
- });
280
- } catch {
281
- // Ignore revoke failures; new token is already active.
282
- }
283
- }
284
-
285
- return {
286
- session: nextSession,
287
- rotated: true,
288
- };
289
- }
290
-
291
- /**
292
- * Perform browser-based CLI login flow and persist an API token session locally.
293
- *
294
- * @param {{
295
- * cwd?: string,
296
- * env?: NodeJS.ProcessEnv,
297
- * explicitApiUrl?: string,
298
- * skipBrowserOpen?: boolean,
299
- * timeoutMs?: number,
300
- * tokenLabel?: string,
301
- * tokenTtlDays?: number,
302
- * ide?: string,
303
- * cliVersion?: string,
304
- * homeDir?: string
305
- * }} [options]
306
- * @returns {Promise<{
307
- * apiUrl: string,
308
- * authorizeUrl: string,
309
- * browserOpened: boolean,
310
- * user: {
311
- * id: string,
312
- * githubUsername: string,
313
- * email: string,
314
- * avatarUrl: string,
315
- * isAdmin: boolean
316
- * },
317
- * tokenId: string | null,
318
- * tokenPrefix: string | null,
319
- * tokenExpiresAt: string | null,
320
- * storage: string,
321
- * filePath: string
322
- * }>}
323
- */
324
- export async function loginAndPersistSession({
325
- cwd = process.cwd(),
326
- env = process.env,
327
- explicitApiUrl = "",
328
- skipBrowserOpen = false,
329
- timeoutMs = DEFAULT_AUTH_TIMEOUT_MS,
330
- tokenLabel = "",
331
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
332
- ide = DEFAULT_IDE_NAME,
333
- cliVersion = "",
334
- homeDir,
335
- } = {}) {
336
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
337
- const challenge = generateChallenge();
338
- const session = await startCliAuthSession({
339
- apiUrl,
340
- challenge,
341
- ide,
342
- cliVersion,
343
- });
344
-
345
- const authorizeUrl = String(session.authorize_url || "").trim();
346
- let browserOpened = false;
347
- if (!skipBrowserOpen && authorizeUrl) {
348
- try {
349
- await open(authorizeUrl);
350
- browserOpened = true;
351
- } catch {
352
- browserOpened = false;
353
- }
354
- }
355
-
356
- const approval = await pollCliAuthSession({
357
- apiUrl,
358
- sessionId: String(session.session_id || "").trim(),
359
- challenge,
360
- timeoutMs,
361
- pollIntervalSeconds: Number(session.poll_interval_seconds || 2),
362
- });
363
-
364
- const approvalToken = String(approval.auth_token || "").trim();
365
- if (!approvalToken) {
366
- throw new SentinelayerApiError("Authentication completed but no auth token was returned.", {
367
- status: 503,
368
- code: "CLI_AUTH_MISSING_TOKEN",
369
- });
370
- }
371
-
372
- const user = normalizeUser(approval.user || (await fetchCurrentUser({ apiUrl, token: approvalToken })));
373
- const issuedApiToken = await issueApiToken({
374
- apiUrl,
375
- authToken: approvalToken,
376
- tokenLabel,
377
- tokenTtlDays,
378
- });
379
-
380
- const stored = await writeStoredSession(
381
- {
382
- apiUrl,
383
- token: String(issuedApiToken.token || ""),
384
- tokenId: issuedApiToken.id || null,
385
- tokenPrefix: issuedApiToken.token_prefix || null,
386
- tokenExpiresAt: issuedApiToken.expires_at || null,
387
- user,
388
- },
389
- { homeDir }
390
- );
391
-
392
- return {
393
- apiUrl,
394
- authorizeUrl,
395
- browserOpened,
396
- user,
397
- tokenId: stored.tokenId,
398
- tokenPrefix: stored.tokenPrefix,
399
- tokenExpiresAt: stored.tokenExpiresAt,
400
- storage: stored.storage,
401
- filePath: stored.filePath,
402
- };
403
- }
404
-
405
- /**
406
- * Resolve active auth credentials used by CLI commands, optionally rotating near-expiry session tokens.
407
- *
408
- * @param {{
409
- * cwd?: string,
410
- * env?: NodeJS.ProcessEnv,
411
- * explicitApiUrl?: string,
412
- * autoRotate?: boolean,
413
- * rotateThresholdDays?: number,
414
- * tokenLabel?: string,
415
- * tokenTtlDays?: number,
416
- * homeDir?: string
417
- * }} [options]
418
- * @returns {Promise<null | {
419
- * apiUrl: string,
420
- * token: string,
421
- * source: "env" | "config" | "session",
422
- * user: {
423
- * id: string,
424
- * githubUsername: string,
425
- * email: string,
426
- * avatarUrl: string,
427
- * isAdmin: boolean
428
- * } | null,
429
- * storage: string,
430
- * tokenId: string | null,
431
- * tokenPrefix: string | null,
432
- * tokenExpiresAt: string | null,
433
- * rotated: boolean,
434
- * filePath: string | null
435
- * }>}
436
- */
437
- export async function resolveActiveAuthSession({
438
- cwd = process.cwd(),
439
- env = process.env,
440
- explicitApiUrl = "",
441
- autoRotate = true,
442
- rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
443
- tokenLabel = "",
444
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
445
- homeDir,
446
- } = {}) {
447
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
448
-
449
- const envToken = String(env.SENTINELAYER_TOKEN || "").trim();
450
- if (envToken) {
451
- return {
452
- apiUrl,
453
- token: envToken,
454
- source: "env",
455
- user: null,
456
- storage: "env",
457
- tokenId: null,
458
- tokenPrefix: null,
459
- tokenExpiresAt: null,
460
- rotated: false,
461
- filePath: null,
462
- };
463
- }
464
-
465
- const config = await loadConfig({ cwd, env, homeDir });
466
- const configuredToken = String(config.resolved.sentinelayerToken || "").trim();
467
- if (configuredToken) {
468
- return {
469
- apiUrl,
470
- token: configuredToken,
471
- source: "config",
472
- user: null,
473
- storage: "config",
474
- tokenId: null,
475
- tokenPrefix: null,
476
- tokenExpiresAt: null,
477
- rotated: false,
478
- filePath: null,
479
- };
480
- }
481
-
482
- const stored = await readStoredSession({ homeDir });
483
- if (!stored) {
484
- return null;
485
- }
486
-
487
- let active = stored;
488
- let rotated = false;
489
- if (autoRotate) {
490
- try {
491
- const rotateResult = await rotateStoredApiTokenIfNeeded({
492
- session: stored,
493
- thresholdDays: rotateThresholdDays,
494
- tokenLabel,
495
- tokenTtlDays,
496
- homeDir,
497
- });
498
- active = rotateResult.session;
499
- rotated = rotateResult.rotated;
500
- } catch {
501
- // Keep existing token if rotation fails.
502
- active = stored;
503
- rotated = false;
504
- }
505
- }
506
-
507
- return {
508
- apiUrl,
509
- token: active.token,
510
- source: "session",
511
- user: normalizeUser(active.user || {}),
512
- storage: active.storage,
513
- tokenId: active.tokenId || null,
514
- tokenPrefix: active.tokenPrefix || null,
515
- tokenExpiresAt: active.tokenExpiresAt || null,
516
- rotated,
517
- filePath: active.filePath,
518
- };
519
- }
520
-
521
- /**
522
- * Return current authentication state, with optional remote `/auth/me` verification.
523
- *
524
- * @param {{
525
- * cwd?: string,
526
- * env?: NodeJS.ProcessEnv,
527
- * explicitApiUrl?: string,
528
- * checkRemote?: boolean,
529
- * autoRotate?: boolean,
530
- * rotateThresholdDays?: number,
531
- * tokenLabel?: string,
532
- * tokenTtlDays?: number,
533
- * homeDir?: string
534
- * }} [options]
535
- * @returns {Promise<{
536
- * authenticated: boolean,
537
- * apiUrl: string,
538
- * source: string | null,
539
- * storage: string | null,
540
- * user: any,
541
- * remoteUser: any,
542
- * remoteError: null | { code: string, message: string, status: number, requestId: string | null },
543
- * rotated: boolean,
544
- * tokenExpiresAt: string | null,
545
- * tokenPrefix: string | null,
546
- * tokenId: string | null,
547
- * filePath: string | null
548
- * }>}
549
- */
550
- export async function getAuthStatus({
551
- cwd = process.cwd(),
552
- env = process.env,
553
- explicitApiUrl = "",
554
- checkRemote = true,
555
- autoRotate = true,
556
- rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
557
- tokenLabel = "",
558
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
559
- homeDir,
560
- } = {}) {
561
- const session = await resolveActiveAuthSession({
562
- cwd,
563
- env,
564
- explicitApiUrl,
565
- autoRotate,
566
- rotateThresholdDays,
567
- tokenLabel,
568
- tokenTtlDays,
569
- homeDir,
570
- });
571
-
572
- if (!session) {
573
- return {
574
- authenticated: false,
575
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
576
- source: null,
577
- storage: null,
578
- user: null,
579
- remoteUser: null,
580
- remoteError: null,
581
- rotated: false,
582
- tokenExpiresAt: null,
583
- tokenPrefix: null,
584
- tokenId: null,
585
- filePath: null,
586
- };
587
- }
588
-
589
- let remoteUser = null;
590
- let remoteError = null;
591
- if (checkRemote) {
592
- try {
593
- remoteUser = normalizeUser(await fetchCurrentUser({ apiUrl: session.apiUrl, token: session.token }));
594
- } catch (error) {
595
- remoteError =
596
- error instanceof SentinelayerApiError
597
- ? {
598
- code: error.code,
599
- message: error.message,
600
- status: error.status,
601
- requestId: error.requestId,
602
- }
603
- : {
604
- code: "UNKNOWN",
605
- message: error instanceof Error ? error.message : String(error || "Unknown error"),
606
- status: 500,
607
- requestId: null,
608
- };
609
- }
610
- }
611
-
612
- return {
613
- authenticated: !remoteError,
614
- apiUrl: session.apiUrl,
615
- source: session.source,
616
- storage: session.storage,
617
- user: session.user,
618
- remoteUser,
619
- remoteError,
620
- rotated: session.rotated,
621
- tokenExpiresAt: session.tokenExpiresAt,
622
- tokenPrefix: session.tokenPrefix,
623
- tokenId: session.tokenId,
624
- filePath: session.filePath,
625
- };
626
- }
627
-
628
- /**
629
- * List persisted local session metadata for CLI operators/HITL dashboards.
630
- *
631
- * @param {{ cwd?: string, env?: NodeJS.ProcessEnv, explicitApiUrl?: string, homeDir?: string }} [options]
632
- * @returns {Promise<{ apiUrl: string, sessions: Array<any> }>}
633
- */
634
- export async function listStoredAuthSessions({
635
- cwd = process.cwd(),
636
- env = process.env,
637
- explicitApiUrl = "",
638
- homeDir,
639
- } = {}) {
640
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
641
- const stored = await readStoredSessionMetadata({ homeDir });
642
- if (!stored) {
643
- return {
644
- apiUrl,
645
- sessions: [],
646
- };
647
- }
648
-
649
- return {
650
- apiUrl,
651
- sessions: [
652
- {
653
- source: "session",
654
- storage: stored.storage || null,
655
- tokenId: stored.tokenId || null,
656
- tokenPrefix: stored.tokenPrefix || null,
657
- tokenExpiresAt: stored.tokenExpiresAt || null,
658
- createdAt: stored.createdAt || null,
659
- updatedAt: stored.updatedAt || null,
660
- user: normalizeUser(stored.user || {}),
661
- filePath: stored.filePath || null,
662
- },
663
- ],
664
- };
665
- }
666
-
667
- /**
668
- * Revoke an API token remotely and clear matching local stored session metadata when applicable.
669
- *
670
- * @param {{
671
- * cwd?: string,
672
- * env?: NodeJS.ProcessEnv,
673
- * explicitApiUrl?: string,
674
- * tokenId?: string,
675
- * homeDir?: string
676
- * }} [options]
677
- * @returns {Promise<{
678
- * apiUrl: string,
679
- * source: string,
680
- * tokenId: string,
681
- * revokedRemote: boolean,
682
- * matchedStoredSession: boolean,
683
- * clearedLocal: boolean,
684
- * filePath: string | null
685
- * }>}
686
- */
687
- export async function revokeAuthToken({
688
- cwd = process.cwd(),
689
- env = process.env,
690
- explicitApiUrl = "",
691
- tokenId = "",
692
- homeDir,
693
- } = {}) {
694
- const active = await resolveActiveAuthSession({
695
- cwd,
696
- env,
697
- explicitApiUrl,
698
- autoRotate: false,
699
- homeDir,
700
- });
701
- if (!active || !active.token) {
702
- throw new SentinelayerApiError("No active auth token found. Run `sl auth login` first.", {
703
- status: 401,
704
- code: "AUTH_REQUIRED",
705
- });
706
- }
707
-
708
- const targetTokenId = String(tokenId || "").trim() || String(active.tokenId || "").trim();
709
- if (!targetTokenId) {
710
- throw new Error(
711
- "tokenId is required. Provide --token-id or use a stored session that includes token metadata."
712
- );
713
- }
714
-
715
- await revokeApiToken({
716
- apiUrl: active.apiUrl,
717
- authToken: active.token,
718
- tokenId: targetTokenId,
719
- });
720
-
721
- let matchedStoredSession = false;
722
- let clearedLocal = false;
723
- let filePath = null;
724
- const stored = await readStoredSession({ homeDir });
725
- if (stored && String(stored.tokenId || "").trim() === targetTokenId) {
726
- matchedStoredSession = true;
727
- const cleared = await clearStoredSession({ homeDir });
728
- clearedLocal = Boolean(cleared.hadSession);
729
- filePath = cleared.filePath || null;
730
- }
731
-
732
- return {
733
- apiUrl: active.apiUrl,
734
- source: active.source,
735
- tokenId: targetTokenId,
736
- revokedRemote: true,
737
- matchedStoredSession,
738
- clearedLocal,
739
- filePath,
740
- };
741
- }
742
-
743
- /**
744
- * Clear local CLI session state and optionally revoke the remote token first.
745
- *
746
- * @param {{
747
- * homeDir?: string,
748
- * cwd?: string,
749
- * env?: NodeJS.ProcessEnv,
750
- * explicitApiUrl?: string,
751
- * revokeRemote?: boolean
752
- * }} [options]
753
- * @returns {Promise<{
754
- * hadStoredSession: boolean,
755
- * revokedRemote: boolean,
756
- * clearedLocal: boolean,
757
- * apiUrl?: string,
758
- * filePath?: string
759
- * }>}
760
- */
761
- export async function logoutSession({
762
- homeDir,
763
- cwd = process.cwd(),
764
- env = process.env,
765
- explicitApiUrl = "",
766
- revokeRemote = true,
767
- } = {}) {
768
- const stored = await readStoredSession({ homeDir });
769
- if (!stored) {
770
- return {
771
- hadStoredSession: false,
772
- revokedRemote: false,
773
- clearedLocal: false,
774
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
775
- };
776
- }
777
-
778
- let revokedRemote = false;
779
- if (revokeRemote && stored.tokenId && stored.token) {
780
- try {
781
- await revokeApiToken({
782
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
783
- authToken: stored.token,
784
- tokenId: stored.tokenId,
785
- });
786
- revokedRemote = true;
787
- } catch {
788
- revokedRemote = false;
789
- }
790
- }
791
-
792
- const cleared = await clearStoredSession({ homeDir });
793
- return {
794
- hadStoredSession: true,
795
- revokedRemote,
796
- clearedLocal: cleared.hadSession,
797
- filePath: cleared.filePath,
798
- };
799
- }
800
-
801
- /**
802
- * Fetch runtime run event stream slices used by `sl watch` and reproducibility artifacts.
803
- *
804
- * @param {{
805
- * apiUrl: string,
806
- * authToken: string,
807
- * runId: string,
808
- * afterEventId?: string | null
809
- * }} [options]
810
- * @returns {Promise<any>}
811
- */
812
- export async function listRuntimeRunEvents({
813
- apiUrl,
814
- authToken,
815
- runId,
816
- afterEventId = null,
817
- } = {}) {
818
- const query = afterEventId
819
- ? `?after_event_id=${encodeURIComponent(String(afterEventId))}`
820
- : "";
821
- return requestJson(
822
- buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/events/list${query}`),
823
- {
824
- method: "GET",
825
- headers: toAuthHeader(authToken),
826
- }
827
- );
828
- }
829
-
830
- /**
831
- * Fetch runtime run status snapshot from the Sentinelayer API.
832
- *
833
- * @param {{ apiUrl: string, authToken: string, runId: string }} [options]
834
- * @returns {Promise<any>}
835
- */
836
- export async function getRuntimeRunStatus({
837
- apiUrl,
838
- authToken,
839
- runId,
840
- } = {}) {
841
- return requestJson(
842
- buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/status`),
843
- {
844
- method: "GET",
845
- headers: toAuthHeader(authToken),
846
- }
847
- );
848
- }
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 } from "./http.js";
9
+ import {
10
+ clearStoredSession,
11
+ readStoredSession,
12
+ readStoredSessionMetadata,
13
+ writeStoredSession,
14
+ } from "./session-store.js";
15
+
16
+ const DEFAULT_API_URL = "https://api.sentinelayer.com";
17
+ /** Default maximum wall-clock wait for browser-based CLI auth approval (ms). */
18
+ export const DEFAULT_AUTH_TIMEOUT_MS = 10 * 60 * 1000;
19
+ /** Default lifetime for issued API tokens used by CLI sessions (days). */
20
+ export const DEFAULT_API_TOKEN_TTL_DAYS = 365;
21
+ /** Default threshold at which stored tokens are rotated before expiry (days). */
22
+ export const DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS = 7;
23
+ const DEFAULT_IDE_NAME = "sl-cli";
24
+
25
+ function normalizeApiUrl(rawValue) {
26
+ const candidate = String(rawValue || "").trim() || DEFAULT_API_URL;
27
+ let parsed;
28
+ try {
29
+ parsed = new URL(candidate);
30
+ } catch {
31
+ throw new Error(`Invalid API URL '${candidate}'.`);
32
+ }
33
+ parsed.pathname = "/";
34
+ parsed.search = "";
35
+ parsed.hash = "";
36
+ return parsed.toString().replace(/\/$/, "");
37
+ }
38
+
39
+ function normalizePositiveNumber(rawValue, field, fallbackValue) {
40
+ if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
41
+ return fallbackValue;
42
+ }
43
+ const normalized = Number(rawValue);
44
+ if (!Number.isFinite(normalized) || normalized <= 0) {
45
+ throw new Error(`${field} must be a positive number.`);
46
+ }
47
+ return normalized;
48
+ }
49
+
50
+ function toAuthHeader(token) {
51
+ return {
52
+ Authorization: `Bearer ${String(token || "").trim()}`,
53
+ };
54
+ }
55
+
56
+ function normalizeUser(user = {}) {
57
+ return {
58
+ id: String(user.id || "").trim(),
59
+ githubUsername: String(user.githubUsername || user.github_username || "").trim(),
60
+ email: String(user.email || "").trim(),
61
+ avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
62
+ isAdmin: Boolean(user.isAdmin || user.is_admin),
63
+ };
64
+ }
65
+
66
+ function buildApiPath(apiUrl, pathSuffix) {
67
+ return `${normalizeApiUrl(apiUrl)}${String(pathSuffix || "")}`;
68
+ }
69
+
70
+ function generateChallenge() {
71
+ return crypto.randomBytes(48).toString("base64url");
72
+ }
73
+
74
+ function defaultTokenLabel() {
75
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
76
+ return `sl-cli-session-${stamp}`;
77
+ }
78
+
79
+ function isNearExpiry(tokenExpiresAt, thresholdDays) {
80
+ const normalized = String(tokenExpiresAt || "").trim();
81
+ if (!normalized) {
82
+ return false;
83
+ }
84
+ const expiryEpoch = Date.parse(normalized);
85
+ if (!Number.isFinite(expiryEpoch)) {
86
+ return false;
87
+ }
88
+ const thresholdMs = Number(thresholdDays || DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS) * 24 * 60 * 60 * 1000;
89
+ return expiryEpoch - Date.now() <= thresholdMs;
90
+ }
91
+
92
+ /**
93
+ * Resolve API URL precedence for auth operations: explicit -> env -> config -> default.
94
+ *
95
+ * @param {{
96
+ * cwd?: string,
97
+ * env?: NodeJS.ProcessEnv,
98
+ * explicitApiUrl?: string,
99
+ * homeDir?: string
100
+ * }} [options]
101
+ * @returns {Promise<string>}
102
+ */
103
+ export async function resolveApiUrl({
104
+ cwd = process.cwd(),
105
+ env = process.env,
106
+ explicitApiUrl = "",
107
+ homeDir,
108
+ } = {}) {
109
+ const overrideUrl = String(explicitApiUrl || "").trim();
110
+ if (overrideUrl) {
111
+ return normalizeApiUrl(overrideUrl);
112
+ }
113
+
114
+ const envUrl = String(env.SENTINELAYER_API_URL || "").trim();
115
+ if (envUrl) {
116
+ return normalizeApiUrl(envUrl);
117
+ }
118
+
119
+ const config = await loadConfig({ cwd, env, homeDir });
120
+ const configuredApiUrl = String(config.resolved.apiUrl || "").trim();
121
+ if (configuredApiUrl) {
122
+ return normalizeApiUrl(configuredApiUrl);
123
+ }
124
+
125
+ return normalizeApiUrl(DEFAULT_API_URL);
126
+ }
127
+
128
+ async function startCliAuthSession({ apiUrl, challenge, ide, cliVersion }) {
129
+ return requestJson(buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/start"), {
130
+ method: "POST",
131
+ body: {
132
+ challenge,
133
+ ide: String(ide || DEFAULT_IDE_NAME),
134
+ cli_version: String(cliVersion || "").trim() || null,
135
+ },
136
+ });
137
+ }
138
+
139
+ async function pollCliAuthSession({
140
+ apiUrl,
141
+ sessionId,
142
+ challenge,
143
+ timeoutMs,
144
+ pollIntervalSeconds,
145
+ }) {
146
+ const timeout = normalizePositiveNumber(timeoutMs, "timeoutMs", DEFAULT_AUTH_TIMEOUT_MS);
147
+ const pollIntervalMs = Math.max(250, Math.round(Number(pollIntervalSeconds || 2) * 1000));
148
+ const deadline = Date.now() + timeout;
149
+ const isTransientPollError = (error) =>
150
+ error instanceof SentinelayerApiError &&
151
+ (error.code === "NETWORK_ERROR" ||
152
+ error.code === "TIMEOUT" ||
153
+ error.status === 429 ||
154
+ error.status >= 500);
155
+
156
+ while (Date.now() < deadline) {
157
+ let payload;
158
+ try {
159
+ payload = await requestJson(buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/poll"), {
160
+ method: "POST",
161
+ body: {
162
+ session_id: sessionId,
163
+ challenge,
164
+ },
165
+ });
166
+ } catch (error) {
167
+ if (isTransientPollError(error)) {
168
+ await sleep(pollIntervalMs);
169
+ continue;
170
+ }
171
+ throw error;
172
+ }
173
+
174
+ const status = String(payload.status || "pending").trim().toLowerCase();
175
+ if (status === "approved" && payload.auth_token) {
176
+ return payload;
177
+ }
178
+ if (status === "rejected" || status === "denied" || status === "cancelled") {
179
+ throw new SentinelayerApiError("CLI authentication was not approved.", {
180
+ status: 401,
181
+ code: "CLI_AUTH_REJECTED",
182
+ });
183
+ }
184
+ if (status === "expired") {
185
+ throw new SentinelayerApiError("CLI authentication session expired.", {
186
+ status: 401,
187
+ code: "CLI_AUTH_EXPIRED",
188
+ });
189
+ }
190
+
191
+ await sleep(pollIntervalMs);
192
+ }
193
+
194
+ throw new SentinelayerApiError("CLI authentication timed out. Restart and try again.", {
195
+ status: 408,
196
+ code: "CLI_AUTH_TIMEOUT",
197
+ });
198
+ }
199
+
200
+ async function fetchCurrentUser({ apiUrl, token }) {
201
+ return requestJson(buildApiPath(apiUrl, "/api/v1/auth/me"), {
202
+ method: "GET",
203
+ headers: toAuthHeader(token),
204
+ });
205
+ }
206
+
207
+ async function issueApiToken({
208
+ apiUrl,
209
+ authToken,
210
+ tokenLabel,
211
+ tokenTtlDays,
212
+ }) {
213
+ const expiresInDays = Math.round(
214
+ normalizePositiveNumber(tokenTtlDays, "apiTokenTtlDays", DEFAULT_API_TOKEN_TTL_DAYS)
215
+ );
216
+ return requestJson(buildApiPath(apiUrl, "/api/v1/auth/api-tokens"), {
217
+ method: "POST",
218
+ headers: toAuthHeader(authToken),
219
+ body: {
220
+ label: String(tokenLabel || "").trim() || defaultTokenLabel(),
221
+ scope: "github_app_bridge",
222
+ llm_credential_mode: "managed",
223
+ expires_in_days: expiresInDays,
224
+ },
225
+ });
226
+ }
227
+
228
+ async function revokeApiToken({ apiUrl, authToken, tokenId }) {
229
+ const normalizedTokenId = String(tokenId || "").trim();
230
+ if (!normalizedTokenId) {
231
+ return false;
232
+ }
233
+ await requestJson(buildApiPath(apiUrl, `/api/v1/auth/api-tokens/${encodeURIComponent(normalizedTokenId)}`), {
234
+ method: "DELETE",
235
+ headers: toAuthHeader(authToken),
236
+ });
237
+ return true;
238
+ }
239
+
240
+ async function rotateStoredApiTokenIfNeeded({
241
+ session,
242
+ thresholdDays,
243
+ tokenLabel,
244
+ tokenTtlDays,
245
+ homeDir,
246
+ }) {
247
+ if (!session || !session.token || !session.tokenExpiresAt) {
248
+ return { session, rotated: false };
249
+ }
250
+ if (!isNearExpiry(session.tokenExpiresAt, thresholdDays)) {
251
+ return { session, rotated: false };
252
+ }
253
+
254
+ const issued = await issueApiToken({
255
+ apiUrl: session.apiUrl,
256
+ authToken: session.token,
257
+ tokenLabel,
258
+ tokenTtlDays,
259
+ });
260
+
261
+ const nextSession = await writeStoredSession(
262
+ {
263
+ apiUrl: session.apiUrl,
264
+ token: String(issued.token || ""),
265
+ tokenId: issued.id || null,
266
+ tokenPrefix: issued.token_prefix || null,
267
+ tokenExpiresAt: issued.expires_at || null,
268
+ user: session.user,
269
+ },
270
+ { homeDir }
271
+ );
272
+
273
+ if (session.tokenId) {
274
+ try {
275
+ await revokeApiToken({
276
+ apiUrl: session.apiUrl,
277
+ authToken: nextSession.token,
278
+ tokenId: session.tokenId,
279
+ });
280
+ } catch {
281
+ // Ignore revoke failures; new token is already active.
282
+ }
283
+ }
284
+
285
+ return {
286
+ session: nextSession,
287
+ rotated: true,
288
+ };
289
+ }
290
+
291
+ /**
292
+ * Perform browser-based CLI login flow and persist an API token session locally.
293
+ *
294
+ * @param {{
295
+ * cwd?: string,
296
+ * env?: NodeJS.ProcessEnv,
297
+ * explicitApiUrl?: string,
298
+ * skipBrowserOpen?: boolean,
299
+ * timeoutMs?: number,
300
+ * tokenLabel?: string,
301
+ * tokenTtlDays?: number,
302
+ * ide?: string,
303
+ * cliVersion?: string,
304
+ * homeDir?: string
305
+ * }} [options]
306
+ * @returns {Promise<{
307
+ * apiUrl: string,
308
+ * authorizeUrl: string,
309
+ * browserOpened: boolean,
310
+ * user: {
311
+ * id: string,
312
+ * githubUsername: string,
313
+ * email: string,
314
+ * avatarUrl: string,
315
+ * isAdmin: boolean
316
+ * },
317
+ * tokenId: string | null,
318
+ * tokenPrefix: string | null,
319
+ * tokenExpiresAt: string | null,
320
+ * storage: string,
321
+ * filePath: string
322
+ * }>}
323
+ */
324
+ export async function loginAndPersistSession({
325
+ cwd = process.cwd(),
326
+ env = process.env,
327
+ explicitApiUrl = "",
328
+ skipBrowserOpen = false,
329
+ timeoutMs = DEFAULT_AUTH_TIMEOUT_MS,
330
+ tokenLabel = "",
331
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
332
+ ide = DEFAULT_IDE_NAME,
333
+ cliVersion = "",
334
+ homeDir,
335
+ } = {}) {
336
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
337
+ const challenge = generateChallenge();
338
+ const session = await startCliAuthSession({
339
+ apiUrl,
340
+ challenge,
341
+ ide,
342
+ cliVersion,
343
+ });
344
+
345
+ const authorizeUrl = String(session.authorize_url || "").trim();
346
+ let browserOpened = false;
347
+ if (!skipBrowserOpen && authorizeUrl) {
348
+ try {
349
+ await open(authorizeUrl);
350
+ browserOpened = true;
351
+ } catch {
352
+ browserOpened = false;
353
+ }
354
+ }
355
+
356
+ const approval = await pollCliAuthSession({
357
+ apiUrl,
358
+ sessionId: String(session.session_id || "").trim(),
359
+ challenge,
360
+ timeoutMs,
361
+ pollIntervalSeconds: Number(session.poll_interval_seconds || 2),
362
+ });
363
+
364
+ const approvalToken = String(approval.auth_token || "").trim();
365
+ if (!approvalToken) {
366
+ throw new SentinelayerApiError("Authentication completed but no auth token was returned.", {
367
+ status: 503,
368
+ code: "CLI_AUTH_MISSING_TOKEN",
369
+ });
370
+ }
371
+
372
+ const user = normalizeUser(approval.user || (await fetchCurrentUser({ apiUrl, token: approvalToken })));
373
+ const issuedApiToken = await issueApiToken({
374
+ apiUrl,
375
+ authToken: approvalToken,
376
+ tokenLabel,
377
+ tokenTtlDays,
378
+ });
379
+
380
+ // Extract AIdenID metadata from approval (no secret stored locally)
381
+ const rawAidenId = approval.aidenidCredentials || approval.aidenid_credentials || null;
382
+ const aidenid =
383
+ rawAidenId && rawAidenId.provisioned
384
+ ? {
385
+ orgId: String(rawAidenId.orgId || rawAidenId.org_id || "").trim() || null,
386
+ projectId: String(rawAidenId.projectId || rawAidenId.project_id || "").trim() || null,
387
+ apiKeyPrefix: String(rawAidenId.apiKeyPrefix || rawAidenId.api_key_prefix || "").trim() || null,
388
+ provisionedAt: new Date().toISOString(),
389
+ }
390
+ : null;
391
+
392
+ const stored = await writeStoredSession(
393
+ {
394
+ apiUrl,
395
+ token: String(issuedApiToken.token || ""),
396
+ tokenId: issuedApiToken.id || null,
397
+ tokenPrefix: issuedApiToken.token_prefix || null,
398
+ tokenExpiresAt: issuedApiToken.expires_at || null,
399
+ user,
400
+ aidenid,
401
+ },
402
+ { homeDir }
403
+ );
404
+
405
+ return {
406
+ apiUrl,
407
+ authorizeUrl,
408
+ browserOpened,
409
+ user,
410
+ tokenId: stored.tokenId,
411
+ tokenPrefix: stored.tokenPrefix,
412
+ tokenExpiresAt: stored.tokenExpiresAt,
413
+ storage: stored.storage,
414
+ filePath: stored.filePath,
415
+ aidenid: stored.aidenid || null,
416
+ };
417
+ }
418
+
419
+ /**
420
+ * Resolve active auth credentials used by CLI commands, optionally rotating near-expiry session tokens.
421
+ *
422
+ * @param {{
423
+ * cwd?: string,
424
+ * env?: NodeJS.ProcessEnv,
425
+ * explicitApiUrl?: string,
426
+ * autoRotate?: boolean,
427
+ * rotateThresholdDays?: number,
428
+ * tokenLabel?: string,
429
+ * tokenTtlDays?: number,
430
+ * homeDir?: string
431
+ * }} [options]
432
+ * @returns {Promise<null | {
433
+ * apiUrl: string,
434
+ * token: string,
435
+ * source: "env" | "config" | "session",
436
+ * user: {
437
+ * id: string,
438
+ * githubUsername: string,
439
+ * email: string,
440
+ * avatarUrl: string,
441
+ * isAdmin: boolean
442
+ * } | null,
443
+ * storage: string,
444
+ * tokenId: string | null,
445
+ * tokenPrefix: string | null,
446
+ * tokenExpiresAt: string | null,
447
+ * rotated: boolean,
448
+ * filePath: string | null
449
+ * }>}
450
+ */
451
+ export async function resolveActiveAuthSession({
452
+ cwd = process.cwd(),
453
+ env = process.env,
454
+ explicitApiUrl = "",
455
+ autoRotate = true,
456
+ rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
457
+ tokenLabel = "",
458
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
459
+ homeDir,
460
+ } = {}) {
461
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
462
+
463
+ const envToken = String(env.SENTINELAYER_TOKEN || "").trim();
464
+ if (envToken) {
465
+ return {
466
+ apiUrl,
467
+ token: envToken,
468
+ source: "env",
469
+ user: null,
470
+ aidenid: null,
471
+ storage: "env",
472
+ tokenId: null,
473
+ tokenPrefix: null,
474
+ tokenExpiresAt: null,
475
+ rotated: false,
476
+ filePath: null,
477
+ };
478
+ }
479
+
480
+ const config = await loadConfig({ cwd, env, homeDir });
481
+ const configuredToken = String(config.resolved.sentinelayerToken || "").trim();
482
+ if (configuredToken) {
483
+ return {
484
+ apiUrl,
485
+ token: configuredToken,
486
+ source: "config",
487
+ user: null,
488
+ aidenid: null,
489
+ storage: "config",
490
+ tokenId: null,
491
+ tokenPrefix: null,
492
+ tokenExpiresAt: null,
493
+ rotated: false,
494
+ filePath: null,
495
+ };
496
+ }
497
+
498
+ const stored = await readStoredSession({ homeDir });
499
+ if (!stored) {
500
+ return null;
501
+ }
502
+
503
+ let active = stored;
504
+ let rotated = false;
505
+ if (autoRotate) {
506
+ try {
507
+ const rotateResult = await rotateStoredApiTokenIfNeeded({
508
+ session: stored,
509
+ thresholdDays: rotateThresholdDays,
510
+ tokenLabel,
511
+ tokenTtlDays,
512
+ homeDir,
513
+ });
514
+ active = rotateResult.session;
515
+ rotated = rotateResult.rotated;
516
+ } catch {
517
+ // Keep existing token if rotation fails.
518
+ active = stored;
519
+ rotated = false;
520
+ }
521
+ }
522
+
523
+ return {
524
+ apiUrl,
525
+ token: active.token,
526
+ source: "session",
527
+ user: normalizeUser(active.user || {}),
528
+ aidenid: active.aidenid || null,
529
+ storage: active.storage,
530
+ tokenId: active.tokenId || null,
531
+ tokenPrefix: active.tokenPrefix || null,
532
+ tokenExpiresAt: active.tokenExpiresAt || null,
533
+ rotated,
534
+ filePath: active.filePath,
535
+ };
536
+ }
537
+
538
+ /**
539
+ * Return current authentication state, with optional remote `/auth/me` verification.
540
+ *
541
+ * @param {{
542
+ * cwd?: string,
543
+ * env?: NodeJS.ProcessEnv,
544
+ * explicitApiUrl?: string,
545
+ * checkRemote?: boolean,
546
+ * autoRotate?: boolean,
547
+ * rotateThresholdDays?: number,
548
+ * tokenLabel?: string,
549
+ * tokenTtlDays?: number,
550
+ * homeDir?: string
551
+ * }} [options]
552
+ * @returns {Promise<{
553
+ * authenticated: boolean,
554
+ * apiUrl: string,
555
+ * source: string | null,
556
+ * storage: string | null,
557
+ * user: any,
558
+ * remoteUser: any,
559
+ * remoteError: null | { code: string, message: string, status: number, requestId: string | null },
560
+ * rotated: boolean,
561
+ * tokenExpiresAt: string | null,
562
+ * tokenPrefix: string | null,
563
+ * tokenId: string | null,
564
+ * filePath: string | null
565
+ * }>}
566
+ */
567
+ export async function getAuthStatus({
568
+ cwd = process.cwd(),
569
+ env = process.env,
570
+ explicitApiUrl = "",
571
+ checkRemote = true,
572
+ autoRotate = true,
573
+ rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
574
+ tokenLabel = "",
575
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
576
+ homeDir,
577
+ } = {}) {
578
+ const session = await resolveActiveAuthSession({
579
+ cwd,
580
+ env,
581
+ explicitApiUrl,
582
+ autoRotate,
583
+ rotateThresholdDays,
584
+ tokenLabel,
585
+ tokenTtlDays,
586
+ homeDir,
587
+ });
588
+
589
+ if (!session) {
590
+ return {
591
+ authenticated: false,
592
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
593
+ source: null,
594
+ storage: null,
595
+ user: null,
596
+ aidenid: null,
597
+ remoteUser: null,
598
+ remoteError: null,
599
+ rotated: false,
600
+ tokenExpiresAt: null,
601
+ tokenPrefix: null,
602
+ tokenId: null,
603
+ filePath: null,
604
+ };
605
+ }
606
+
607
+ let remoteUser = null;
608
+ let remoteError = null;
609
+ if (checkRemote) {
610
+ try {
611
+ remoteUser = normalizeUser(await fetchCurrentUser({ apiUrl: session.apiUrl, token: session.token }));
612
+ } catch (error) {
613
+ remoteError =
614
+ error instanceof SentinelayerApiError
615
+ ? {
616
+ code: error.code,
617
+ message: error.message,
618
+ status: error.status,
619
+ requestId: error.requestId,
620
+ }
621
+ : {
622
+ code: "UNKNOWN",
623
+ message: error instanceof Error ? error.message : String(error || "Unknown error"),
624
+ status: 500,
625
+ requestId: null,
626
+ };
627
+ }
628
+ }
629
+
630
+ return {
631
+ authenticated: !remoteError,
632
+ apiUrl: session.apiUrl,
633
+ source: session.source,
634
+ storage: session.storage,
635
+ user: session.user,
636
+ aidenid: session.aidenid || null,
637
+ remoteUser,
638
+ remoteError,
639
+ rotated: session.rotated,
640
+ tokenExpiresAt: session.tokenExpiresAt,
641
+ tokenPrefix: session.tokenPrefix,
642
+ tokenId: session.tokenId,
643
+ filePath: session.filePath,
644
+ };
645
+ }
646
+
647
+ /**
648
+ * List persisted local session metadata for CLI operators/HITL dashboards.
649
+ *
650
+ * @param {{ cwd?: string, env?: NodeJS.ProcessEnv, explicitApiUrl?: string, homeDir?: string }} [options]
651
+ * @returns {Promise<{ apiUrl: string, sessions: Array<any> }>}
652
+ */
653
+ export async function listStoredAuthSessions({
654
+ cwd = process.cwd(),
655
+ env = process.env,
656
+ explicitApiUrl = "",
657
+ homeDir,
658
+ } = {}) {
659
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
660
+ const stored = await readStoredSessionMetadata({ homeDir });
661
+ if (!stored) {
662
+ return {
663
+ apiUrl,
664
+ sessions: [],
665
+ };
666
+ }
667
+
668
+ return {
669
+ apiUrl,
670
+ sessions: [
671
+ {
672
+ source: "session",
673
+ storage: stored.storage || null,
674
+ tokenId: stored.tokenId || null,
675
+ tokenPrefix: stored.tokenPrefix || null,
676
+ tokenExpiresAt: stored.tokenExpiresAt || null,
677
+ createdAt: stored.createdAt || null,
678
+ updatedAt: stored.updatedAt || null,
679
+ user: normalizeUser(stored.user || {}),
680
+ filePath: stored.filePath || null,
681
+ },
682
+ ],
683
+ };
684
+ }
685
+
686
+ /**
687
+ * Revoke an API token remotely and clear matching local stored session metadata when applicable.
688
+ *
689
+ * @param {{
690
+ * cwd?: string,
691
+ * env?: NodeJS.ProcessEnv,
692
+ * explicitApiUrl?: string,
693
+ * tokenId?: string,
694
+ * homeDir?: string
695
+ * }} [options]
696
+ * @returns {Promise<{
697
+ * apiUrl: string,
698
+ * source: string,
699
+ * tokenId: string,
700
+ * revokedRemote: boolean,
701
+ * matchedStoredSession: boolean,
702
+ * clearedLocal: boolean,
703
+ * filePath: string | null
704
+ * }>}
705
+ */
706
+ export async function revokeAuthToken({
707
+ cwd = process.cwd(),
708
+ env = process.env,
709
+ explicitApiUrl = "",
710
+ tokenId = "",
711
+ homeDir,
712
+ } = {}) {
713
+ const active = await resolveActiveAuthSession({
714
+ cwd,
715
+ env,
716
+ explicitApiUrl,
717
+ autoRotate: false,
718
+ homeDir,
719
+ });
720
+ if (!active || !active.token) {
721
+ throw new SentinelayerApiError("No active auth token found. Run `sl auth login` first.", {
722
+ status: 401,
723
+ code: "AUTH_REQUIRED",
724
+ });
725
+ }
726
+
727
+ const targetTokenId = String(tokenId || "").trim() || String(active.tokenId || "").trim();
728
+ if (!targetTokenId) {
729
+ throw new Error(
730
+ "tokenId is required. Provide --token-id or use a stored session that includes token metadata."
731
+ );
732
+ }
733
+
734
+ await revokeApiToken({
735
+ apiUrl: active.apiUrl,
736
+ authToken: active.token,
737
+ tokenId: targetTokenId,
738
+ });
739
+
740
+ let matchedStoredSession = false;
741
+ let clearedLocal = false;
742
+ let filePath = null;
743
+ const stored = await readStoredSession({ homeDir });
744
+ if (stored && String(stored.tokenId || "").trim() === targetTokenId) {
745
+ matchedStoredSession = true;
746
+ const cleared = await clearStoredSession({ homeDir });
747
+ clearedLocal = Boolean(cleared.hadSession);
748
+ filePath = cleared.filePath || null;
749
+ }
750
+
751
+ return {
752
+ apiUrl: active.apiUrl,
753
+ source: active.source,
754
+ tokenId: targetTokenId,
755
+ revokedRemote: true,
756
+ matchedStoredSession,
757
+ clearedLocal,
758
+ filePath,
759
+ };
760
+ }
761
+
762
+ /**
763
+ * Clear local CLI session state and optionally revoke the remote token first.
764
+ *
765
+ * @param {{
766
+ * homeDir?: string,
767
+ * cwd?: string,
768
+ * env?: NodeJS.ProcessEnv,
769
+ * explicitApiUrl?: string,
770
+ * revokeRemote?: boolean
771
+ * }} [options]
772
+ * @returns {Promise<{
773
+ * hadStoredSession: boolean,
774
+ * revokedRemote: boolean,
775
+ * clearedLocal: boolean,
776
+ * apiUrl?: string,
777
+ * filePath?: string
778
+ * }>}
779
+ */
780
+ export async function logoutSession({
781
+ homeDir,
782
+ cwd = process.cwd(),
783
+ env = process.env,
784
+ explicitApiUrl = "",
785
+ revokeRemote = true,
786
+ } = {}) {
787
+ const stored = await readStoredSession({ homeDir });
788
+ if (!stored) {
789
+ return {
790
+ hadStoredSession: false,
791
+ revokedRemote: false,
792
+ clearedLocal: false,
793
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
794
+ };
795
+ }
796
+
797
+ let revokedRemote = false;
798
+ if (revokeRemote && stored.tokenId && stored.token) {
799
+ try {
800
+ await revokeApiToken({
801
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
802
+ authToken: stored.token,
803
+ tokenId: stored.tokenId,
804
+ });
805
+ revokedRemote = true;
806
+ } catch {
807
+ revokedRemote = false;
808
+ }
809
+ }
810
+
811
+ const cleared = await clearStoredSession({ homeDir });
812
+ return {
813
+ hadStoredSession: true,
814
+ revokedRemote,
815
+ clearedLocal: cleared.hadSession,
816
+ filePath: cleared.filePath,
817
+ };
818
+ }
819
+
820
+ /**
821
+ * Fetch runtime run event stream slices used by `sl watch` and reproducibility artifacts.
822
+ *
823
+ * @param {{
824
+ * apiUrl: string,
825
+ * authToken: string,
826
+ * runId: string,
827
+ * afterEventId?: string | null
828
+ * }} [options]
829
+ * @returns {Promise<any>}
830
+ */
831
+ export async function listRuntimeRunEvents({
832
+ apiUrl,
833
+ authToken,
834
+ runId,
835
+ afterEventId = null,
836
+ } = {}) {
837
+ const query = afterEventId
838
+ ? `?after_event_id=${encodeURIComponent(String(afterEventId))}`
839
+ : "";
840
+ return requestJson(
841
+ buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/events/list${query}`),
842
+ {
843
+ method: "GET",
844
+ headers: toAuthHeader(authToken),
845
+ }
846
+ );
847
+ }
848
+
849
+ /**
850
+ * Fetch runtime run status snapshot from the Sentinelayer API.
851
+ *
852
+ * @param {{ apiUrl: string, authToken: string, runId: string }} [options]
853
+ * @returns {Promise<any>}
854
+ */
855
+ /**
856
+ * Fetch AIdenID credentials from the SentinelLayer API (lazy-provisioning).
857
+ * The secret is returned in-memory only, never persisted to disk.
858
+ */
859
+ export async function fetchAidenIdCredentials({
860
+ apiUrl = DEFAULT_API_URL,
861
+ token = "",
862
+ } = {}) {
863
+ const response = await requestJson(
864
+ buildApiPath(apiUrl, "/api/v1/aidenid/credentials"),
865
+ {
866
+ method: "GET",
867
+ headers: toAuthHeader(token),
868
+ }
869
+ );
870
+ return {
871
+ orgId: String(response.orgId || response.org_id || "").trim(),
872
+ projectId: String(response.projectId || response.project_id || "").trim(),
873
+ apiKeyPrefix: String(response.apiKeyPrefix || response.api_key_prefix || "").trim(),
874
+ apiKey: String(response.apiKey || response.api_key || "").trim(),
875
+ provisioned: Boolean(response.provisioned),
876
+ };
877
+ }
878
+
879
+ export async function getRuntimeRunStatus({
880
+ apiUrl,
881
+ authToken,
882
+ runId,
883
+ } = {}) {
884
+ return requestJson(
885
+ buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/status`),
886
+ {
887
+ method: "GET",
888
+ headers: toAuthHeader(authToken),
889
+ }
890
+ );
891
+ }