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,493 +1,503 @@
1
- import { execFileSync } from "node:child_process";
2
- import path from "node:path";
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import { randomUUID } from "node:crypto";
6
-
7
- /**
8
- * Jules Tanaka — Runtime Audit Tool
9
- *
10
- * Lighthouse performance scan + Chrome DevTools Protocol inspection.
11
- * Requires: chrome/chromium available, lighthouse npm package.
12
- * All operations are optional gracefully degrade if deps unavailable.
13
- */
14
-
15
- const LIGHTHOUSE_TIMEOUT_MS = 120000;
16
-
17
- /**
18
- * @param {{ operation: string, url?: string, path?: string }} input
19
- * @returns {object} Structured result per operation
20
- */
21
- export async function runtimeAudit(input) {
22
- if (!RUNTIME_OPS.has(input.operation)) {
23
- throw new RuntimeAuditError(
24
- "Unknown operation: " + input.operation + ". Valid: " + [...RUNTIME_OPS].join(", "),
25
- );
26
- }
27
- return RUNTIME_DISPATCH[input.operation](input);
28
- }
29
-
30
- const RUNTIME_OPS = new Set([
31
- "lighthouse_scan",
32
- "check_response_headers",
33
- "detect_deployed_url",
34
- "check_console_errors",
35
- "check_network_waterfall",
36
- "check_dom_stats",
37
- ]);
38
-
39
- const RUNTIME_DISPATCH = {
40
- lighthouse_scan: lighthouseScan,
41
- check_response_headers: checkResponseHeaders,
42
- detect_deployed_url: detectDeployedUrl,
43
- check_console_errors: checkConsoleErrors,
44
- check_network_waterfall: checkNetworkWaterfall,
45
- check_dom_stats: checkDomStats,
46
- };
47
-
48
- /**
49
- * Run Lighthouse via npx (no install required).
50
- * Returns performance, accessibility, best-practices, SEO scores + key metrics.
51
- */
52
- async function lighthouseScan(input) {
53
- const url = input.url;
54
- if (!url) {
55
- throw new RuntimeAuditError("lighthouse_scan requires a url parameter");
56
- }
57
- if (!isValidUrl(url)) {
58
- throw new RuntimeAuditError("Invalid URL: " + url);
59
- }
60
-
61
- // Prefer SentinelLayer API scanner (authenticated, server-side Lighthouse).
62
- // Falls back to local npx lighthouse if API unavailable.
63
- try {
64
- const apiResult = await callScannerApi(url);
65
- if (apiResult.available) return apiResult;
66
- } catch { /* API unavailable — fall back to local */ }
67
-
68
- try {
69
- const outputPath = path.join(
70
- input.path || process.cwd(),
71
- ".sentinelayer",
72
- "reports",
73
- "lighthouse-" + Date.now() + ".json",
74
- );
75
- const outputDir = path.dirname(outputPath);
76
- if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
77
-
78
- execFileSync("npx", [
79
- "--yes", "lighthouse@12", url,
80
- "--output", "json", "--output-path", outputPath,
81
- "--chrome-flags=--headless --no-sandbox --disable-gpu", "--quiet",
82
- ], {
83
- encoding: "utf-8",
84
- timeout: LIGHTHOUSE_TIMEOUT_MS,
85
- stdio: ["pipe", "pipe", "pipe"],
86
- shell: true, // Windows: npx is npx.cmd, needs shell resolution
87
- });
88
-
89
- if (!fs.existsSync(outputPath)) {
90
- return { available: false, reason: "Lighthouse produced no output" };
91
- }
92
-
93
- const raw = JSON.parse(fs.readFileSync(outputPath, "utf-8"));
94
- const categories = raw.categories || {};
95
- const audits = raw.audits || {};
96
-
97
- return {
98
- available: true,
99
- reportPath: outputPath,
100
- scores: {
101
- performance: categories.performance?.score ?? null,
102
- accessibility: categories.accessibility?.score ?? null,
103
- bestPractices: categories["best-practices"]?.score ?? null,
104
- seo: categories.seo?.score ?? null,
105
- },
106
- metrics: {
107
- lcp_ms: audits["largest-contentful-paint"]?.numericValue ?? null,
108
- fcp_ms: audits["first-contentful-paint"]?.numericValue ?? null,
109
- cls: audits["cumulative-layout-shift"]?.numericValue ?? null,
110
- tbt_ms: audits["total-blocking-time"]?.numericValue ?? null,
111
- si_ms: audits["speed-index"]?.numericValue ?? null,
112
- tti_ms: audits["interactive"]?.numericValue ?? null,
113
- },
114
- opportunities: Object.values(audits)
115
- .filter(a => a.details?.type === "opportunity" && a.details?.overallSavingsMs > 100)
116
- .slice(0, 10)
117
- .map(a => ({
118
- id: a.id,
119
- title: a.title,
120
- savingsMs: a.details?.overallSavingsMs,
121
- savingsBytes: a.details?.overallSavingsBytes,
122
- })),
123
- };
124
- } catch (err) {
125
- return {
126
- available: false,
127
- reason: "Lighthouse failed: " + (err.message || "").slice(0, 200),
128
- };
129
- }
130
- }
131
-
132
- /**
133
- * Check HTTP response headers for security and performance headers.
134
- * Uses curl (available on all platforms).
135
- */
136
- function checkResponseHeaders(input) {
137
- const url = input.url;
138
- if (!url) throw new RuntimeAuditError("check_response_headers requires a url");
139
- if (!isValidUrl(url)) throw new RuntimeAuditError("Invalid URL: " + url);
140
-
141
- try {
142
- const safeUrl = sanitizeUrlForShell(url);
143
- if (!safeUrl) throw new Error("URL sanitization failed");
144
- const output = execFileSync("curl", ["-sI", "-L", "--max-time", "10", safeUrl], {
145
- encoding: "utf-8", timeout: 15000, stdio: ["pipe", "pipe", "pipe"],
146
- });
147
-
148
- const headers = parseHeaders(output);
149
- const securityHeaders = [
150
- "content-security-policy", "x-frame-options", "x-content-type-options",
151
- "strict-transport-security", "referrer-policy", "permissions-policy",
152
- ];
153
-
154
- const findings = [];
155
- for (const h of securityHeaders) {
156
- const present = headers[h] !== undefined;
157
- if (!present) {
158
- findings.push({
159
- header: h,
160
- present: false,
161
- severity: h === "content-security-policy" ? "P1" : "P2",
162
- });
163
- }
164
- }
165
-
166
- return {
167
- available: true,
168
- url,
169
- statusCode: parseInt(output.match(/HTTP\/[\d.]+ (\d+)/)?.[1] || "0"),
170
- headers,
171
- securityFindings: findings,
172
- cookieFlags: extractCookieFlags(headers),
173
- };
174
- } catch (err) {
175
- return { available: false, reason: "curl failed: " + err.message };
176
- }
177
- }
178
-
179
- /**
180
- * Try to detect a deployed URL from common config locations.
181
- */
182
- function detectDeployedUrl(input) {
183
- const rootPath = input.path || process.cwd();
184
- const candidates = [];
185
-
186
- // Check env vars
187
- for (const key of ["NEXT_PUBLIC_APP_URL", "VITE_APP_URL", "APP_URL", "BASE_URL", "DEPLOY_URL", "VERCEL_URL"]) {
188
- if (process.env[key]) {
189
- candidates.push({ source: "env:" + key, url: process.env[key] });
190
- }
191
- }
192
-
193
- // Check package.json homepage
194
- try {
195
- const pkg = JSON.parse(fs.readFileSync(path.join(rootPath, "package.json"), "utf-8"));
196
- if (pkg.homepage) candidates.push({ source: "package.json:homepage", url: pkg.homepage });
197
- } catch { /* skip */ }
198
-
199
- // Check vercel.json
200
- try {
201
- const vercel = JSON.parse(fs.readFileSync(path.join(rootPath, "vercel.json"), "utf-8"));
202
- if (vercel.alias) {
203
- const alias = Array.isArray(vercel.alias) ? vercel.alias[0] : vercel.alias;
204
- candidates.push({ source: "vercel.json:alias", url: "https://" + alias });
205
- }
206
- } catch { /* skip */ }
207
-
208
- // Check .env files for URLs
209
- for (const envFile of [".env", ".env.local", ".env.production"]) {
210
- try {
211
- const content = fs.readFileSync(path.join(rootPath, envFile), "utf-8");
212
- const urlMatch = content.match(/(?:APP_URL|BASE_URL|SITE_URL|DEPLOY_URL)\s*=\s*['"]?(https?:\/\/[^\s'"]+)/);
213
- if (urlMatch) candidates.push({ source: envFile, url: urlMatch[1] });
214
- } catch { /* skip */ }
215
- }
216
-
217
- return { candidates, found: candidates.length > 0, primary: candidates[0]?.url || null };
218
- }
219
-
220
- /**
221
- * Check for console errors by loading the page with Playwright (if available).
222
- * Falls back to a simple curl-based check.
223
- */
224
- function checkConsoleErrors(input) {
225
- const url = input.url;
226
- if (!url) throw new RuntimeAuditError("check_console_errors requires a url");
227
- if (!isValidUrl(url)) throw new RuntimeAuditError("Invalid URL: " + url);
228
-
229
- // Try playwright — URL passed via env var to prevent command injection
230
- try {
231
- const scriptPath = secureTempFile("sl-console-" + randomUUID().slice(0, 8) + ".cjs");
232
- fs.writeFileSync(scriptPath, `
233
- const { chromium } = require('playwright');
234
- (async () => {
235
- const targetUrl = process.env.SL_AUDIT_TARGET_URL;
236
- if (!targetUrl) { console.log(JSON.stringify({ errors: [], title: '' })); process.exit(0); }
237
- const browser = await chromium.launch({ headless: true });
238
- const page = await browser.newPage();
239
- const errors = [];
240
- page.on('console', msg => { if (msg.type() === 'error') errors.push({ text: msg.text(), url: msg.location()?.url }); });
241
- page.on('pageerror', err => errors.push({ text: err.message, type: 'uncaught' }));
242
- try {
243
- await page.goto(targetUrl, { waitUntil: 'networkidle', timeout: 30000 });
244
- console.log(JSON.stringify({ errors, title: await page.title() }));
245
- } finally {
246
- await browser.close();
247
- }
248
- })();
249
- `);
250
- const output = execFileSync("node", [scriptPath], {
251
- encoding: "utf-8", timeout: 45000,
252
- stdio: ["pipe", "pipe", "pipe"],
253
- env: { ...process.env, SL_AUDIT_TARGET_URL: url },
254
- });
255
- try { fs.unlinkSync(scriptPath); } catch { /* best effort */ }
256
- try { fs.rmdirSync(path.dirname(scriptPath)); } catch { /* best effort */ }
257
- const result = JSON.parse(output.trim());
258
- return { available: true, method: "playwright", ...result };
259
- } catch (playwrightErr) {
260
- // Playwright not available — return instruction
261
- return {
262
- available: false,
263
- reason: "Playwright not installed. Run: npx playwright install chromium",
264
- recommendation: "Install playwright for console error capture",
265
- };
266
- }
267
- }
268
-
269
- /**
270
- * Basic network waterfall check via curl timing.
271
- */
272
- function checkNetworkWaterfall(input) {
273
- const url = input.url;
274
- if (!url) throw new RuntimeAuditError("check_network_waterfall requires a url");
275
- if (!isValidUrl(url)) throw new RuntimeAuditError("Invalid URL: " + url);
276
-
277
- try {
278
- // Write curl format to temp file to avoid shell quoting issues across platforms
279
- const formatFile = secureTempFile("sl-curl-fmt-" + randomUUID().slice(0, 8) + ".txt");
280
- fs.writeFileSync(formatFile, '{"dns_ms":%{time_namelookup},"connect_ms":%{time_connect},"tls_ms":%{time_appconnect},"ttfb_ms":%{time_starttransfer},"total_ms":%{time_total},"size_bytes":%{size_download},"status":%{http_code}}');
281
- const safeUrl = sanitizeUrlForShell(url);
282
- if (!safeUrl) { try { fs.unlinkSync(formatFile); } catch {} throw new Error("URL sanitization failed"); }
283
- const output = execFileSync("curl", [
284
- "-sL", "-o", devNull(), "-w", "@" + formatFile, "--max-time", "15", safeUrl,
285
- ], { encoding: "utf-8", timeout: 20000, stdio: ["pipe", "pipe", "pipe"] });
286
- try { fs.unlinkSync(formatFile); } catch { /* best effort */ }
287
- try { fs.rmdirSync(path.dirname(formatFile)); } catch { /* best effort */ }
288
- const timing = JSON.parse(output.trim());
289
- // Convert seconds to milliseconds
290
- for (const key of ["dns_ms", "connect_ms", "tls_ms", "ttfb_ms", "total_ms"]) {
291
- timing[key] = Math.round(timing[key] * 1000);
292
- }
293
- return { available: true, url, timing };
294
- } catch (err) {
295
- return { available: false, reason: "curl timing failed: " + err.message };
296
- }
297
- }
298
-
299
- /**
300
- * Basic DOM stats (requires Playwright).
301
- */
302
- function checkDomStats(input) {
303
- const url = input.url;
304
- if (!url) throw new RuntimeAuditError("check_dom_stats requires a url");
305
- if (!isValidUrl(url)) throw new RuntimeAuditError("Invalid URL: " + url);
306
-
307
- // URL passed via env var to prevent command injection (CodeQL alert #51)
308
- try {
309
- const scriptPath = secureTempFile("sl-dom-" + randomUUID().slice(0, 8) + ".cjs");
310
- fs.writeFileSync(scriptPath, `
311
- const { chromium } = require('playwright');
312
- (async () => {
313
- const targetUrl = process.env.SL_AUDIT_TARGET_URL;
314
- if (!targetUrl) { console.log(JSON.stringify({})); process.exit(0); }
315
- const browser = await chromium.launch({ headless: true });
316
- try {
317
- const page = await browser.newPage();
318
- await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
319
- const stats = await page.evaluate(() => ({
320
- nodeCount: document.querySelectorAll('*').length,
321
- maxDepth: (function depth(el, d) { return Math.max(d, ...Array.from(el.children).map(c => depth(c, d+1))); })(document.body, 0),
322
- imgCount: document.querySelectorAll('img').length,
323
- imgWithoutAlt: document.querySelectorAll('img:not([alt])').length,
324
- formCount: document.querySelectorAll('form').length,
325
- inputWithoutLabel: document.querySelectorAll('input:not([aria-label]):not([id])').length,
326
- title: document.title,
327
- h1Count: document.querySelectorAll('h1').length,
328
- linkCount: document.querySelectorAll('a').length,
329
- }));
330
- console.log(JSON.stringify(stats));
331
- } finally {
332
- await browser.close();
333
- }
334
- })();
335
- `);
336
- const output = execFileSync("node", [scriptPath], {
337
- encoding: "utf-8", timeout: 45000,
338
- stdio: ["pipe", "pipe", "pipe"],
339
- env: { ...process.env, SL_AUDIT_TARGET_URL: url },
340
- });
341
- try { fs.unlinkSync(scriptPath); } catch { /* best effort */ }
342
- try { fs.rmdirSync(path.dirname(scriptPath)); } catch { /* best effort */ }
343
- return { available: true, method: "playwright", ...JSON.parse(output.trim()) };
344
- } catch {
345
- return { available: false, reason: "Playwright not installed" };
346
- }
347
- }
348
-
349
- // ── Helpers ──────────────────────────────────────────────��───────────
350
-
351
- function isValidUrl(url) {
352
- try {
353
- const parsed = new URL(url);
354
- return parsed.protocol === "http:" || parsed.protocol === "https:";
355
- } catch {
356
- return false;
357
- }
358
- }
359
-
360
- function parseHeaders(raw) {
361
- const headers = {};
362
- for (const line of raw.split("\n")) {
363
- const colonIdx = line.indexOf(":");
364
- if (colonIdx > 0) {
365
- const key = line.slice(0, colonIdx).trim().toLowerCase();
366
- const value = line.slice(colonIdx + 1).trim();
367
- headers[key] = value;
368
- }
369
- }
370
- return headers;
371
- }
372
-
373
- function extractCookieFlags(headers) {
374
- const cookies = [];
375
- const setCookies = Object.entries(headers).filter(([k]) => k === "set-cookie");
376
- for (const [, value] of setCookies) {
377
- cookies.push({
378
- raw: value.slice(0, 100),
379
- httpOnly: /httponly/i.test(value),
380
- secure: /secure/i.test(value),
381
- sameSite: value.match(/samesite=(\w+)/i)?.[1] || null,
382
- });
383
- }
384
- return cookies;
385
- }
386
-
387
- function devNull() {
388
- return process.platform === "win32" ? "NUL" : "/dev/null";
389
- }
390
-
391
- /**
392
- * Create a temp file path with secure random name.
393
- * Sets file permissions to 0o600 (owner read/write only) after creation.
394
- */
395
- function secureTempFile(name) {
396
- // CodeQL requires mkdtempSync for secure temp file creation (unique random dir)
397
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sl-rt-"));
398
- return path.join(dir, name);
399
- }
400
-
401
- function sanitizeUrlForShell(url) {
402
- // Only allow http/https URLs, strip any shell metacharacters
403
- try {
404
- const parsed = new URL(url);
405
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return "";
406
- return parsed.href;
407
- } catch {
408
- return "";
409
- }
410
- }
411
-
412
- /**
413
- * Call the SentinelLayer API scanner endpoint for server-side Lighthouse.
414
- * Requires authenticated session (token from sl auth login).
415
- * Returns structured result or throws if unavailable.
416
- */
417
- async function callScannerApi(url) {
418
- let session;
419
- try {
420
- const { readStoredSession } = await import("../../../auth/session-store.js");
421
- session = await readStoredSession();
422
- } catch { /* session read failed */ }
423
-
424
- if (!session || !session.token) {
425
- return { available: false, reason: "Not authenticated run sl auth login" };
426
- }
427
-
428
- const apiUrl = session.apiUrl || "https://api.sentinelayer.com";
429
- const scanEndpoint = apiUrl + "/api/v1/scan/url";
430
-
431
- // Submit scan
432
- const submitResponse = await fetch(scanEndpoint, {
433
- method: "POST",
434
- headers: {
435
- "Content-Type": "application/json",
436
- "Authorization": "Bearer " + session.token,
437
- },
438
- body: JSON.stringify({ url, scan_type: "lighthouse" }),
439
- signal: AbortSignal.timeout(15000),
440
- });
441
-
442
- if (!submitResponse.ok) {
443
- return { available: false, reason: "Scanner API returned " + submitResponse.status };
444
- }
445
-
446
- const submitData = await submitResponse.json();
447
- const scanId = submitData.scan_id || submitData.id;
448
- if (!scanId) {
449
- return { available: false, reason: "Scanner did not return scan_id" };
450
- }
451
-
452
- // Poll for completion (max 90s)
453
- const pollUrl = apiUrl + "/api/v1/scan/url/" + scanId;
454
- for (let attempt = 0; attempt < 30; attempt++) {
455
- await new Promise(r => setTimeout(r, 3000));
456
- try {
457
- const pollResponse = await fetch(pollUrl, {
458
- headers: { "Authorization": "Bearer " + session.token },
459
- signal: AbortSignal.timeout(10000),
460
- });
461
- if (!pollResponse.ok) continue;
462
- const pollData = await pollResponse.json();
463
- if (pollData.status === "completed" || pollData.status === "complete") {
464
- const scores = pollData.scores || pollData.lighthouse_scores || {};
465
- return {
466
- available: true,
467
- source: "sentinelayer-api",
468
- scanId,
469
- reportPath: null,
470
- scores: {
471
- performance: scores.performance ?? null,
472
- accessibility: scores.accessibility ?? null,
473
- bestPractices: scores.best_practices ?? scores.bestPractices ?? null,
474
- seo: scores.seo ?? null,
475
- },
476
- metrics: pollData.metrics || {},
477
- opportunities: pollData.opportunities || [],
478
- };
479
- }
480
- if (pollData.status === "failed" || pollData.status === "error") {
481
- return { available: false, reason: "Scanner reported failure: " + (pollData.error || pollData.status) };
482
- }
483
- } catch { /* poll failed, retry */ }
484
- }
485
- return { available: false, reason: "Scanner timed out after 90s" };
486
- }
487
-
488
- export class RuntimeAuditError extends Error {
489
- constructor(message) {
490
- super(message);
491
- this.name = "RuntimeAuditError";
492
- }
493
- }
1
+ import { execFileSync } from "node:child_process";
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import { randomUUID } from "node:crypto";
6
+ import { assertPermittedAuditTarget } from "./url-policy.js";
7
+
8
+ /**
9
+ * Jules Tanaka — Runtime Audit Tool
10
+ *
11
+ * Lighthouse performance scan + Chrome DevTools Protocol inspection.
12
+ * Requires: chrome/chromium available, lighthouse npm package.
13
+ * All operations are optional — gracefully degrade if deps unavailable.
14
+ */
15
+
16
+ const LIGHTHOUSE_TIMEOUT_MS = 120000;
17
+
18
+ /**
19
+ * @param {{ operation: string, url?: string, path?: string }} input
20
+ * @returns {object} Structured result per operation
21
+ */
22
+ export async function runtimeAudit(input) {
23
+ if (!RUNTIME_OPS.has(input.operation)) {
24
+ throw new RuntimeAuditError(
25
+ "Unknown operation: " + input.operation + ". Valid: " + [...RUNTIME_OPS].join(", "),
26
+ );
27
+ }
28
+ return RUNTIME_DISPATCH[input.operation](input);
29
+ }
30
+
31
+ const RUNTIME_OPS = new Set([
32
+ "lighthouse_scan",
33
+ "check_response_headers",
34
+ "detect_deployed_url",
35
+ "check_console_errors",
36
+ "check_network_waterfall",
37
+ "check_dom_stats",
38
+ ]);
39
+
40
+ const RUNTIME_DISPATCH = {
41
+ lighthouse_scan: lighthouseScan,
42
+ check_response_headers: checkResponseHeaders,
43
+ detect_deployed_url: detectDeployedUrl,
44
+ check_console_errors: checkConsoleErrors,
45
+ check_network_waterfall: checkNetworkWaterfall,
46
+ check_dom_stats: checkDomStats,
47
+ };
48
+
49
+ /**
50
+ * Run Lighthouse via npx (no install required).
51
+ * Returns performance, accessibility, best-practices, SEO scores + key metrics.
52
+ */
53
+ async function lighthouseScan(input) {
54
+ const url = input.url;
55
+ if (!url) {
56
+ throw new RuntimeAuditError("lighthouse_scan requires a url parameter");
57
+ }
58
+ const targetUrl = resolveRuntimeTargetUrl(url, input, "lighthouse_scan");
59
+
60
+ // Prefer SentinelLayer API scanner (authenticated, server-side Lighthouse).
61
+ // Falls back to local npx lighthouse if API unavailable.
62
+ try {
63
+ const apiResult = await callScannerApi(targetUrl);
64
+ if (apiResult.available) return apiResult;
65
+ } catch { /* API unavailable — fall back to local */ }
66
+
67
+ try {
68
+ const outputPath = path.join(
69
+ input.path || process.cwd(),
70
+ ".sentinelayer",
71
+ "reports",
72
+ "lighthouse-" + Date.now() + ".json",
73
+ );
74
+ const outputDir = path.dirname(outputPath);
75
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
76
+
77
+ execFileSync("npx", [
78
+ "--yes", "lighthouse@12", targetUrl,
79
+ "--output", "json", "--output-path", outputPath,
80
+ "--chrome-flags=--headless --no-sandbox --disable-gpu", "--quiet",
81
+ ], {
82
+ encoding: "utf-8",
83
+ timeout: LIGHTHOUSE_TIMEOUT_MS,
84
+ stdio: ["pipe", "pipe", "pipe"],
85
+ shell: true, // Windows: npx is npx.cmd, needs shell resolution
86
+ });
87
+
88
+ if (!fs.existsSync(outputPath)) {
89
+ return { available: false, reason: "Lighthouse produced no output" };
90
+ }
91
+
92
+ const raw = JSON.parse(fs.readFileSync(outputPath, "utf-8"));
93
+ const categories = raw.categories || {};
94
+ const audits = raw.audits || {};
95
+
96
+ return {
97
+ available: true,
98
+ reportPath: outputPath,
99
+ scores: {
100
+ performance: categories.performance?.score ?? null,
101
+ accessibility: categories.accessibility?.score ?? null,
102
+ bestPractices: categories["best-practices"]?.score ?? null,
103
+ seo: categories.seo?.score ?? null,
104
+ },
105
+ metrics: {
106
+ lcp_ms: audits["largest-contentful-paint"]?.numericValue ?? null,
107
+ fcp_ms: audits["first-contentful-paint"]?.numericValue ?? null,
108
+ cls: audits["cumulative-layout-shift"]?.numericValue ?? null,
109
+ tbt_ms: audits["total-blocking-time"]?.numericValue ?? null,
110
+ si_ms: audits["speed-index"]?.numericValue ?? null,
111
+ tti_ms: audits["interactive"]?.numericValue ?? null,
112
+ },
113
+ opportunities: Object.values(audits)
114
+ .filter(a => a.details?.type === "opportunity" && a.details?.overallSavingsMs > 100)
115
+ .slice(0, 10)
116
+ .map(a => ({
117
+ id: a.id,
118
+ title: a.title,
119
+ savingsMs: a.details?.overallSavingsMs,
120
+ savingsBytes: a.details?.overallSavingsBytes,
121
+ })),
122
+ };
123
+ } catch (err) {
124
+ return {
125
+ available: false,
126
+ reason: "Lighthouse failed: " + (err.message || "").slice(0, 200),
127
+ };
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Check HTTP response headers for security and performance headers.
133
+ * Uses curl (available on all platforms).
134
+ */
135
+ function checkResponseHeaders(input) {
136
+ const url = input.url;
137
+ if (!url) throw new RuntimeAuditError("check_response_headers requires a url");
138
+ const targetUrl = resolveRuntimeTargetUrl(url, input, "check_response_headers");
139
+
140
+ try {
141
+ const safeUrl = sanitizeUrlForShell(targetUrl);
142
+ if (!safeUrl) throw new Error("URL sanitization failed");
143
+ const output = execFileSync("curl", ["-sI", "-L", "--max-time", "10", safeUrl], {
144
+ encoding: "utf-8", timeout: 15000, stdio: ["pipe", "pipe", "pipe"],
145
+ });
146
+
147
+ const headers = parseHeaders(output);
148
+ const securityHeaders = [
149
+ "content-security-policy", "x-frame-options", "x-content-type-options",
150
+ "strict-transport-security", "referrer-policy", "permissions-policy",
151
+ ];
152
+
153
+ const findings = [];
154
+ for (const h of securityHeaders) {
155
+ const present = headers[h] !== undefined;
156
+ if (!present) {
157
+ findings.push({
158
+ header: h,
159
+ present: false,
160
+ severity: h === "content-security-policy" ? "P1" : "P2",
161
+ });
162
+ }
163
+ }
164
+
165
+ return {
166
+ available: true,
167
+ url: targetUrl,
168
+ statusCode: parseInt(output.match(/HTTP\/[\d.]+ (\d+)/)?.[1] || "0"),
169
+ headers,
170
+ securityFindings: findings,
171
+ cookieFlags: extractCookieFlags(headers),
172
+ };
173
+ } catch (err) {
174
+ return { available: false, reason: "curl failed: " + err.message };
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Try to detect a deployed URL from common config locations.
180
+ */
181
+ function detectDeployedUrl(input) {
182
+ const rootPath = input.path || process.cwd();
183
+ const candidates = [];
184
+
185
+ // Check env vars
186
+ for (const key of ["NEXT_PUBLIC_APP_URL", "VITE_APP_URL", "APP_URL", "BASE_URL", "DEPLOY_URL", "VERCEL_URL"]) {
187
+ if (process.env[key]) {
188
+ candidates.push({ source: "env:" + key, url: process.env[key] });
189
+ }
190
+ }
191
+
192
+ // Check package.json homepage
193
+ try {
194
+ const pkg = JSON.parse(fs.readFileSync(path.join(rootPath, "package.json"), "utf-8"));
195
+ if (pkg.homepage) candidates.push({ source: "package.json:homepage", url: pkg.homepage });
196
+ } catch { /* skip */ }
197
+
198
+ // Check vercel.json
199
+ try {
200
+ const vercel = JSON.parse(fs.readFileSync(path.join(rootPath, "vercel.json"), "utf-8"));
201
+ if (vercel.alias) {
202
+ const alias = Array.isArray(vercel.alias) ? vercel.alias[0] : vercel.alias;
203
+ candidates.push({ source: "vercel.json:alias", url: "https://" + alias });
204
+ }
205
+ } catch { /* skip */ }
206
+
207
+ // Check .env files for URLs
208
+ for (const envFile of [".env", ".env.local", ".env.production"]) {
209
+ try {
210
+ const content = fs.readFileSync(path.join(rootPath, envFile), "utf-8");
211
+ const urlMatch = content.match(/(?:APP_URL|BASE_URL|SITE_URL|DEPLOY_URL)\s*=\s*['"]?(https?:\/\/[^\s'"]+)/);
212
+ if (urlMatch) candidates.push({ source: envFile, url: urlMatch[1] });
213
+ } catch { /* skip */ }
214
+ }
215
+
216
+ return { candidates, found: candidates.length > 0, primary: candidates[0]?.url || null };
217
+ }
218
+
219
+ /**
220
+ * Check for console errors by loading the page with Playwright (if available).
221
+ * Falls back to a simple curl-based check.
222
+ */
223
+ function checkConsoleErrors(input) {
224
+ const url = input.url;
225
+ if (!url) throw new RuntimeAuditError("check_console_errors requires a url");
226
+ const targetUrl = resolveRuntimeTargetUrl(url, input, "check_console_errors");
227
+
228
+ // Try playwright — URL passed via env var to prevent command injection
229
+ try {
230
+ const scriptPath = secureTempFile("sl-console-" + randomUUID().slice(0, 8) + ".cjs");
231
+ fs.writeFileSync(scriptPath, `
232
+ const { chromium } = require('playwright');
233
+ (async () => {
234
+ const targetUrl = process.env.SL_AUDIT_TARGET_URL;
235
+ if (!targetUrl) { console.log(JSON.stringify({ errors: [], title: '' })); process.exit(0); }
236
+ const browser = await chromium.launch({ headless: true });
237
+ const page = await browser.newPage();
238
+ const errors = [];
239
+ page.on('console', msg => { if (msg.type() === 'error') errors.push({ text: msg.text(), url: msg.location()?.url }); });
240
+ page.on('pageerror', err => errors.push({ text: err.message, type: 'uncaught' }));
241
+ try {
242
+ await page.goto(targetUrl, { waitUntil: 'networkidle', timeout: 30000 });
243
+ console.log(JSON.stringify({ errors, title: await page.title() }));
244
+ } finally {
245
+ await browser.close();
246
+ }
247
+ })();
248
+ `);
249
+ const output = execFileSync("node", [scriptPath], {
250
+ encoding: "utf-8", timeout: 45000,
251
+ stdio: ["pipe", "pipe", "pipe"],
252
+ env: { ...process.env, SL_AUDIT_TARGET_URL: targetUrl },
253
+ });
254
+ try { fs.unlinkSync(scriptPath); } catch { /* best effort */ }
255
+ try { fs.rmdirSync(path.dirname(scriptPath)); } catch { /* best effort */ }
256
+ const result = JSON.parse(output.trim());
257
+ return { available: true, method: "playwright", ...result };
258
+ } catch (playwrightErr) {
259
+ // Playwright not available — return instruction
260
+ return {
261
+ available: false,
262
+ reason: "Playwright not installed. Run: npx playwright install chromium",
263
+ recommendation: "Install playwright for console error capture",
264
+ };
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Basic network waterfall check via curl timing.
270
+ */
271
+ function checkNetworkWaterfall(input) {
272
+ const url = input.url;
273
+ if (!url) throw new RuntimeAuditError("check_network_waterfall requires a url");
274
+ const targetUrl = resolveRuntimeTargetUrl(url, input, "check_network_waterfall");
275
+
276
+ try {
277
+ // Write curl format to temp file to avoid shell quoting issues across platforms
278
+ const formatFile = secureTempFile("sl-curl-fmt-" + randomUUID().slice(0, 8) + ".txt");
279
+ fs.writeFileSync(formatFile, '{"dns_ms":%{time_namelookup},"connect_ms":%{time_connect},"tls_ms":%{time_appconnect},"ttfb_ms":%{time_starttransfer},"total_ms":%{time_total},"size_bytes":%{size_download},"status":%{http_code}}');
280
+ const safeUrl = sanitizeUrlForShell(targetUrl);
281
+ if (!safeUrl) { try { fs.unlinkSync(formatFile); } catch {} throw new Error("URL sanitization failed"); }
282
+ const output = execFileSync("curl", [
283
+ "-sL", "-o", devNull(), "-w", "@" + formatFile, "--max-time", "15", safeUrl,
284
+ ], { encoding: "utf-8", timeout: 20000, stdio: ["pipe", "pipe", "pipe"] });
285
+ try { fs.unlinkSync(formatFile); } catch { /* best effort */ }
286
+ try { fs.rmdirSync(path.dirname(formatFile)); } catch { /* best effort */ }
287
+ const timing = JSON.parse(output.trim());
288
+ // Convert seconds to milliseconds
289
+ for (const key of ["dns_ms", "connect_ms", "tls_ms", "ttfb_ms", "total_ms"]) {
290
+ timing[key] = Math.round(timing[key] * 1000);
291
+ }
292
+ return { available: true, url: targetUrl, timing };
293
+ } catch (err) {
294
+ return { available: false, reason: "curl timing failed: " + err.message };
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Basic DOM stats (requires Playwright).
300
+ */
301
+ function checkDomStats(input) {
302
+ const url = input.url;
303
+ if (!url) throw new RuntimeAuditError("check_dom_stats requires a url");
304
+ const targetUrl = resolveRuntimeTargetUrl(url, input, "check_dom_stats");
305
+
306
+ // URL passed via env var to prevent command injection (CodeQL alert #51)
307
+ try {
308
+ const scriptPath = secureTempFile("sl-dom-" + randomUUID().slice(0, 8) + ".cjs");
309
+ fs.writeFileSync(scriptPath, `
310
+ const { chromium } = require('playwright');
311
+ (async () => {
312
+ const targetUrl = process.env.SL_AUDIT_TARGET_URL;
313
+ if (!targetUrl) { console.log(JSON.stringify({})); process.exit(0); }
314
+ const browser = await chromium.launch({ headless: true });
315
+ try {
316
+ const page = await browser.newPage();
317
+ await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
318
+ const stats = await page.evaluate(() => ({
319
+ nodeCount: document.querySelectorAll('*').length,
320
+ maxDepth: (function depth(el, d) { return Math.max(d, ...Array.from(el.children).map(c => depth(c, d+1))); })(document.body, 0),
321
+ imgCount: document.querySelectorAll('img').length,
322
+ imgWithoutAlt: document.querySelectorAll('img:not([alt])').length,
323
+ formCount: document.querySelectorAll('form').length,
324
+ inputWithoutLabel: document.querySelectorAll('input:not([aria-label]):not([id])').length,
325
+ title: document.title,
326
+ h1Count: document.querySelectorAll('h1').length,
327
+ linkCount: document.querySelectorAll('a').length,
328
+ }));
329
+ console.log(JSON.stringify(stats));
330
+ } finally {
331
+ await browser.close();
332
+ }
333
+ })();
334
+ `);
335
+ const output = execFileSync("node", [scriptPath], {
336
+ encoding: "utf-8", timeout: 45000,
337
+ stdio: ["pipe", "pipe", "pipe"],
338
+ env: { ...process.env, SL_AUDIT_TARGET_URL: targetUrl },
339
+ });
340
+ try { fs.unlinkSync(scriptPath); } catch { /* best effort */ }
341
+ try { fs.rmdirSync(path.dirname(scriptPath)); } catch { /* best effort */ }
342
+ return { available: true, method: "playwright", ...JSON.parse(output.trim()) };
343
+ } catch {
344
+ return { available: false, reason: "Playwright not installed" };
345
+ }
346
+ }
347
+
348
+ // ── Helpers ──────────────────────────────────────────────��───────────
349
+
350
+ function resolveRuntimeTargetUrl(url, input, operation) {
351
+ try {
352
+ const parsed = assertPermittedAuditTarget(url, {
353
+ operation,
354
+ allowPrivateTargets: input.allowPrivateTargets === true,
355
+ });
356
+ return parsed.toString();
357
+ } catch (error) {
358
+ throw new RuntimeAuditError(error.message);
359
+ }
360
+ }
361
+
362
+ function parseHeaders(raw) {
363
+ const headers = {};
364
+ for (const line of raw.split("\n")) {
365
+ const colonIdx = line.indexOf(":");
366
+ if (colonIdx > 0) {
367
+ const key = line.slice(0, colonIdx).trim().toLowerCase();
368
+ const value = line.slice(colonIdx + 1).trim();
369
+ headers[key] = value;
370
+ }
371
+ }
372
+ return headers;
373
+ }
374
+
375
+ function extractCookieFlags(headers) {
376
+ const cookies = [];
377
+ const setCookies = Object.entries(headers).filter(([k]) => k === "set-cookie");
378
+ for (const [, value] of setCookies) {
379
+ cookies.push({
380
+ raw: value.slice(0, 100),
381
+ httpOnly: /httponly/i.test(value),
382
+ secure: /secure/i.test(value),
383
+ sameSite: value.match(/samesite=(\w+)/i)?.[1] || null,
384
+ });
385
+ }
386
+ return cookies;
387
+ }
388
+
389
+ function devNull() {
390
+ return process.platform === "win32" ? "NUL" : "/dev/null";
391
+ }
392
+
393
+ /**
394
+ * Create a temp file path with secure random name.
395
+ * Sets file permissions to 0o600 (owner read/write only) after creation.
396
+ */
397
+ function secureTempFile(name) {
398
+ // CodeQL requires mkdtempSync for secure temp file creation (unique random dir)
399
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sl-rt-"));
400
+ return path.join(dir, name);
401
+ }
402
+
403
+ function sanitizeUrlForShell(url) {
404
+ // Only allow http/https URLs, strip any shell metacharacters
405
+ try {
406
+ const parsed = new URL(url);
407
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return "";
408
+ return parsed.href;
409
+ } catch {
410
+ return "";
411
+ }
412
+ }
413
+
414
+ async function fetchWithTimeout(url, options, timeoutMs) {
415
+ const controller = new AbortController();
416
+ const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);
417
+ try {
418
+ return await fetch(url, { ...options, signal: controller.signal });
419
+ } finally {
420
+ clearTimeout(timeoutHandle);
421
+ }
422
+ }
423
+
424
+ /**
425
+ * Call the SentinelLayer API scanner endpoint for server-side Lighthouse.
426
+ * Requires authenticated session (token from sl auth login).
427
+ * Returns structured result or throws if unavailable.
428
+ */
429
+ async function callScannerApi(url) {
430
+ let session;
431
+ try {
432
+ const { readStoredSession } = await import("../../../auth/session-store.js");
433
+ session = await readStoredSession();
434
+ } catch { /* session read failed */ }
435
+
436
+ if (!session || !session.token) {
437
+ return { available: false, reason: "Not authenticated — run sl auth login" };
438
+ }
439
+
440
+ const apiUrl = session.apiUrl || "https://api.sentinelayer.com";
441
+ const scanEndpoint = apiUrl + "/api/v1/scan/url";
442
+
443
+ // Submit scan
444
+ const submitResponse = await fetchWithTimeout(scanEndpoint, {
445
+ method: "POST",
446
+ headers: {
447
+ "Content-Type": "application/json",
448
+ "Authorization": "Bearer " + session.token,
449
+ },
450
+ body: JSON.stringify({ url, scan_type: "lighthouse" }),
451
+ }, 15000);
452
+
453
+ if (!submitResponse.ok) {
454
+ return { available: false, reason: "Scanner API returned " + submitResponse.status };
455
+ }
456
+
457
+ const submitData = await submitResponse.json();
458
+ const scanId = submitData.scan_id || submitData.id;
459
+ if (!scanId) {
460
+ return { available: false, reason: "Scanner did not return scan_id" };
461
+ }
462
+
463
+ // Poll for completion (max 90s)
464
+ const pollUrl = apiUrl + "/api/v1/scan/url/" + scanId;
465
+ for (let attempt = 0; attempt < 30; attempt++) {
466
+ await new Promise(r => setTimeout(r, 3000));
467
+ try {
468
+ const pollResponse = await fetchWithTimeout(pollUrl, {
469
+ headers: { "Authorization": "Bearer " + session.token },
470
+ }, 10000);
471
+ if (!pollResponse.ok) continue;
472
+ const pollData = await pollResponse.json();
473
+ if (pollData.status === "completed" || pollData.status === "complete") {
474
+ const scores = pollData.scores || pollData.lighthouse_scores || {};
475
+ return {
476
+ available: true,
477
+ source: "sentinelayer-api",
478
+ scanId,
479
+ reportPath: null,
480
+ scores: {
481
+ performance: scores.performance ?? null,
482
+ accessibility: scores.accessibility ?? null,
483
+ bestPractices: scores.best_practices ?? scores.bestPractices ?? null,
484
+ seo: scores.seo ?? null,
485
+ },
486
+ metrics: pollData.metrics || {},
487
+ opportunities: pollData.opportunities || [],
488
+ };
489
+ }
490
+ if (pollData.status === "failed" || pollData.status === "error") {
491
+ return { available: false, reason: "Scanner reported failure: " + (pollData.error || pollData.status) };
492
+ }
493
+ } catch { /* poll failed, retry */ }
494
+ }
495
+ return { available: false, reason: "Scanner timed out after 90s" };
496
+ }
497
+
498
+ export class RuntimeAuditError extends Error {
499
+ constructor(message) {
500
+ super(message);
501
+ this.name = "RuntimeAuditError";
502
+ }
503
+ }