sentinelayer-cli 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +996 -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 +62 -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 +319 -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 +226 -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 +493 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/ai/aidenid.js +972 -945
  30. package/src/ai/client.js +508 -508
  31. package/src/ai/domain-target-store.js +268 -268
  32. package/src/ai/identity-store.js +270 -270
  33. package/src/ai/site-store.js +145 -145
  34. package/src/audit/agents/architecture.js +180 -180
  35. package/src/audit/agents/compliance.js +179 -179
  36. package/src/audit/agents/documentation.js +165 -165
  37. package/src/audit/agents/performance.js +145 -145
  38. package/src/audit/agents/security.js +215 -215
  39. package/src/audit/agents/testing.js +172 -172
  40. package/src/audit/orchestrator.js +557 -557
  41. package/src/audit/package.js +204 -204
  42. package/src/audit/registry.js +284 -284
  43. package/src/audit/replay.js +103 -103
  44. package/src/auth/http.js +113 -113
  45. package/src/auth/service.js +891 -848
  46. package/src/auth/session-store.js +359 -345
  47. package/src/cli.js +252 -252
  48. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  49. package/src/commands/ai/provision-governance.js +1272 -1246
  50. package/src/commands/ai/shared.js +147 -147
  51. package/src/commands/ai.js +11 -11
  52. package/src/commands/apply.js +12 -12
  53. package/src/commands/audit.js +1166 -1147
  54. package/src/commands/auth.js +375 -366
  55. package/src/commands/chat.js +191 -191
  56. package/src/commands/config.js +184 -184
  57. package/src/commands/cost.js +311 -311
  58. package/src/commands/daemon/core.js +850 -850
  59. package/src/commands/daemon/extended.js +1048 -1048
  60. package/src/commands/daemon/shared.js +213 -213
  61. package/src/commands/daemon.js +11 -11
  62. package/src/commands/guide.js +174 -174
  63. package/src/commands/ingest.js +58 -58
  64. package/src/commands/init.js +55 -55
  65. package/src/commands/legacy-args.js +10 -10
  66. package/src/commands/mcp.js +461 -404
  67. package/src/commands/omargate.js +15 -15
  68. package/src/commands/persona.js +20 -20
  69. package/src/commands/plugin.js +260 -260
  70. package/src/commands/policy.js +132 -132
  71. package/src/commands/prompt.js +238 -238
  72. package/src/commands/review.js +704 -704
  73. package/src/commands/scan.js +866 -788
  74. package/src/commands/spec.js +716 -716
  75. package/src/commands/swarm.js +651 -651
  76. package/src/commands/telemetry.js +202 -202
  77. package/src/commands/watch.js +510 -510
  78. package/src/config/agent-dictionary.js +182 -182
  79. package/src/config/io.js +56 -56
  80. package/src/config/paths.js +18 -18
  81. package/src/config/schema.js +55 -55
  82. package/src/config/service.js +184 -184
  83. package/src/cost/budget.js +235 -235
  84. package/src/cost/history.js +188 -188
  85. package/src/cost/tracker.js +171 -171
  86. package/src/daemon/artifact-lineage.js +534 -534
  87. package/src/daemon/assignment-ledger.js +770 -770
  88. package/src/daemon/ast-parser-layer.js +258 -258
  89. package/src/daemon/budget-governor.js +633 -633
  90. package/src/daemon/callgraph-overlay.js +646 -646
  91. package/src/daemon/error-worker.js +626 -626
  92. package/src/daemon/hybrid-mapper.js +929 -929
  93. package/src/daemon/ingest-refresh.js +195 -0
  94. package/src/daemon/jira-lifecycle.js +632 -632
  95. package/src/daemon/operator-control.js +657 -657
  96. package/src/daemon/reliability-lane.js +471 -471
  97. package/src/daemon/watchdog.js +971 -971
  98. package/src/guide/generator.js +316 -316
  99. package/src/ingest/engine.js +918 -918
  100. package/src/interactive/action-menu.js +132 -0
  101. package/src/interactive/auto-ingest.js +111 -0
  102. package/src/interactive/index.js +95 -0
  103. package/src/interactive/workspace.js +92 -0
  104. package/src/legacy-cli.js +2548 -2435
  105. package/src/mcp/registry.js +695 -695
  106. package/src/memory/blackboard.js +301 -301
  107. package/src/memory/retrieval.js +581 -581
  108. package/src/plugin/manifest.js +553 -553
  109. package/src/policy/packs.js +144 -144
  110. package/src/prompt/generator.js +118 -106
  111. package/src/review/ai-review.js +669 -669
  112. package/src/review/local-review.js +1284 -1284
  113. package/src/review/replay.js +235 -235
  114. package/src/review/report.js +664 -664
  115. package/src/review/spec-binding.js +487 -487
  116. package/src/scaffold/generator.js +67 -0
  117. package/src/scaffold/templates.js +150 -0
  118. package/src/scan/generator.js +418 -351
  119. package/src/scan/gh-secrets.js +107 -0
  120. package/src/spec/generator.js +519 -519
  121. package/src/spec/regenerate.js +237 -237
  122. package/src/spec/templates.js +91 -91
  123. package/src/swarm/dashboard.js +247 -247
  124. package/src/swarm/factory.js +363 -363
  125. package/src/swarm/pentest.js +934 -934
  126. package/src/swarm/registry.js +419 -419
  127. package/src/swarm/report.js +158 -158
  128. package/src/swarm/runtime.js +576 -576
  129. package/src/swarm/scenario-dsl.js +272 -272
  130. package/src/telemetry/ledger.js +302 -302
  131. package/src/telemetry/session-tracker.js +118 -0
  132. package/src/telemetry/sync.js +190 -0
  133. package/src/ui/markdown.js +220 -220
@@ -1,222 +1,226 @@
1
- import { execFileSync } from "node:child_process";
2
- import fs from "node:fs";
3
- import path from "node:path";
4
- import os from "node:os";
5
- import { randomUUID } from "node:crypto";
6
-
7
- /**
8
- * Jules Tanaka — Authenticated Page Audit
9
- *
10
- * Provisions an AIdenID ephemeral identity, uses Playwright to log in,
11
- * then inspects authenticated pages (DevTools console, DOM, headers).
12
- * Falls back gracefully when AIdenID or Playwright unavailable.
13
- */
14
-
15
- export function authAudit(input) {
16
- if (!AUTH_OPS.has(input.operation)) {
17
- throw new AuthAuditError("Unknown operation: " + input.operation + ". Valid: " + [...AUTH_OPS].join(", "));
18
- }
19
- return AUTH_DISPATCH[input.operation](input);
20
- }
21
-
22
- const AUTH_OPS = new Set([
23
- "provision_test_identity",
24
- "authenticated_page_check",
25
- "check_auth_flow_security",
26
- ]);
27
-
28
- const AUTH_DISPATCH = {
29
- provision_test_identity: provisionTestIdentity,
30
- authenticated_page_check: authenticatedPageCheck,
31
- check_auth_flow_security: checkAuthFlowSecurity,
32
- };
33
-
34
- async function provisionTestIdentity(input) {
35
- try {
36
- const { provisionEmailIdentity, resolveAidenIdCredentials } = await import("../../../ai/aidenid.js");
37
- const creds = resolveAidenIdCredentials();
38
- if (!creds.apiKey) {
39
- return { available: false, reason: "AIdenID API key not configured (set AIDENID_API_KEY)" };
40
- }
41
- const result = await provisionEmailIdentity({
42
- apiUrl: creds.apiUrl, apiKey: creds.apiKey,
43
- tags: ["jules-audit", "frontend-test"],
44
- ttlSeconds: 3600, dryRun: input.execute !== true,
45
- });
46
- return { available: true, dryRun: input.execute !== true, identity: result.identity || result };
47
- } catch (err) {
48
- return { available: false, reason: "AIdenID provisioning failed: " + err.message };
49
- }
50
- }
51
-
52
- /**
53
- * Run Playwright to authenticate and inspect the page.
54
- * - URLs and credentials passed ONLY via env vars (no string interpolation)
55
- * - Auth verification checks URL change + cookie presence (not just click success)
56
- * - Console errors redacted to prevent sensitive data leakage
57
- * - Cookie values never captured (names + flags only)
58
- * - Temp script cleanup in finally block (not just success path)
59
- */
60
- function authenticatedPageCheck(input) {
61
- const url = input.url;
62
- if (!url) throw new AuthAuditError("authenticated_page_check requires url");
63
- if (!isValidUrl(url)) throw new AuthAuditError("Invalid URL: " + url);
64
-
65
- const loginUrl = input.loginUrl || url + "/login";
66
- let scriptPath = null;
67
-
68
- try {
69
- scriptPath = secureTempFile("sl-auth-audit-" + randomUUID().slice(0, 8) + ".cjs");
70
- fs.writeFileSync(scriptPath, PLAYWRIGHT_AUTH_SCRIPT);
71
-
72
- const env = {
73
- ...process.env,
74
- SL_AUDIT_TARGET_URL: url,
75
- SL_AUDIT_LOGIN_URL: loginUrl,
76
- SL_AUDIT_TEST_EMAIL: input.email || "",
77
- SL_AUDIT_TEST_PASSWORD: input.password || "",
78
- SL_AUDIT_EMAIL_FIELD: input.emailField || "",
79
- SL_AUDIT_PASSWORD_FIELD: input.passwordField || "",
80
- SL_AUDIT_SUBMIT_SELECTOR: input.submitSelector || "",
81
- };
82
-
83
- const output = execFileSync("node", [scriptPath], {
84
- encoding: "utf-8", timeout: 60000,
85
- stdio: ["pipe", "pipe", "pipe"],
86
- env,
87
- });
88
-
89
- const result = JSON.parse(output.trim());
90
- const findings = [];
91
- for (const cookie of (result.cookies || [])) {
92
- if (cookie.sensitive && !cookie.httpOnly) {
93
- findings.push({ severity: "P1", title: "Sensitive cookie '" + cookie.name + "' missing httpOnly flag", file: url });
94
- }
95
- if (cookie.sensitive && !cookie.secure) {
96
- findings.push({ severity: "P1", title: "Sensitive cookie '" + cookie.name + "' missing Secure flag", file: url });
97
- }
98
- if (cookie.sensitive && cookie.sameSite === "None") {
99
- findings.push({ severity: "P2", title: "Sensitive cookie '" + cookie.name + "' has SameSite=None", file: url });
100
- }
101
- }
102
- return { available: true, method: "playwright", findings, ...result };
103
- } catch (err) {
104
- return { available: false, reason: "Playwright auth audit failed: " + err.message };
105
- } finally {
106
- // Clean up temp script AND its mkdtemp parent directory
107
- if (scriptPath) {
108
- try { fs.unlinkSync(scriptPath); } catch { /* best effort */ }
109
- try { fs.rmdirSync(path.dirname(scriptPath)); } catch { /* best effort — dir may not be empty */ }
110
- }
111
- }
112
- }
113
-
114
- // Playwright script as a constant — no string interpolation of URLs/credentials.
115
- // All dynamic values come from environment variables at runtime.
116
- const PLAYWRIGHT_AUTH_SCRIPT = `
117
- const { chromium } = require('playwright');
118
- (async () => {
119
- const targetUrl = process.env.SL_AUDIT_TARGET_URL;
120
- const loginUrl = process.env.SL_AUDIT_LOGIN_URL;
121
- const email = process.env.SL_AUDIT_TEST_EMAIL;
122
- const password = process.env.SL_AUDIT_TEST_PASSWORD;
123
- const emailSelector = process.env.SL_AUDIT_EMAIL_FIELD || 'input[type="email"]';
124
- const passwordSelector = process.env.SL_AUDIT_PASSWORD_FIELD || 'input[type="password"]';
125
- const submitSelector = process.env.SL_AUDIT_SUBMIT_SELECTOR || 'button[type="submit"]';
126
-
127
- const browser = await chromium.launch({ headless: true });
128
- const page = await browser.newPage();
129
- const results = { authenticated: false, errors: [], cookies: [], headers: {}, domStats: {} };
130
-
131
- try {
132
- if (email && password && loginUrl) {
133
- await page.goto(loginUrl, { waitUntil: 'networkidle', timeout: 30000 });
134
- await page.fill(emailSelector, email);
135
- await page.fill(passwordSelector, password);
136
- await page.click(submitSelector);
137
- await page.waitForNavigation({ waitUntil: 'networkidle', timeout: 15000 }).catch(() => {});
138
- // P2 fix: verify auth by checking URL change + session cookie presence
139
- const currentUrl = page.url();
140
- const postCookies = await page.context().cookies();
141
- results.authenticated = currentUrl !== loginUrl || postCookies.some(c => /session|token|auth/i.test(c.name));
142
- }
143
-
144
- await page.goto(targetUrl, { waitUntil: 'networkidle', timeout: 30000 });
145
-
146
- // P2 fix: redact sensitive content from console errors
147
- page.on('console', msg => {
148
- if (msg.type() === 'error') {
149
- const text = (msg.text() || '').slice(0, 200).replace(/Bearer\\s+\\S+/gi, 'Bearer [REDACTED]').replace(/token[=:]\\S+/gi, 'token=[REDACTED]');
150
- results.errors.push({ text });
151
- }
152
- });
153
-
154
- // P2 fix: capture cookie names + flags only, never values
155
- const cookies = await page.context().cookies();
156
- results.cookies = cookies.map(c => ({
157
- name: c.name, domain: c.domain,
158
- httpOnly: c.httpOnly, secure: c.secure,
159
- sameSite: c.sameSite,
160
- sensitive: /session|token|auth|jwt/i.test(c.name),
161
- }));
162
-
163
- results.domStats = await page.evaluate(() => ({
164
- title: document.title,
165
- nodeCount: document.querySelectorAll('*').length,
166
- formCount: document.querySelectorAll('form').length,
167
- inputCount: document.querySelectorAll('input').length,
168
- }));
169
-
170
- const response = await page.goto(targetUrl, { waitUntil: 'commit', timeout: 10000 }).catch(() => null);
171
- if (response) {
172
- const h = response.headers();
173
- results.headers = {
174
- 'content-security-policy': h['content-security-policy'] || null,
175
- 'x-frame-options': h['x-frame-options'] || null,
176
- 'strict-transport-security': h['strict-transport-security'] || null,
177
- 'cache-control': h['cache-control'] || null,
178
- };
179
- }
180
- } catch (err) {
181
- results.errors.push({ text: 'Navigation error: ' + (err.message || '').slice(0, 100) });
182
- } finally {
183
- try { console.log(JSON.stringify(results)); } catch { /* output failure non-blocking */ }
184
- await browser.close();
185
- }
186
- })();
187
- `;
188
-
189
- function checkAuthFlowSecurity(input) {
190
- const loginUrl = input.loginUrl || input.url;
191
- if (!loginUrl) throw new AuthAuditError("check_auth_flow_security requires loginUrl or url");
192
- if (!isValidUrl(loginUrl)) throw new AuthAuditError("Invalid URL: " + loginUrl);
193
-
194
- const findings = [];
195
- try {
196
- const output = execFileSync("curl", ["-sI", "-L", "--max-time", "10", loginUrl], {
197
- encoding: "utf-8", timeout: 15000, stdio: ["pipe", "pipe", "pipe"],
198
- });
199
- const headers = {};
200
- for (const line of output.split("\n")) {
201
- const idx = line.indexOf(":");
202
- if (idx > 0) headers[line.slice(0, idx).trim().toLowerCase()] = line.slice(idx + 1).trim();
203
- }
204
- if (!headers["strict-transport-security"]) findings.push({ severity: "P1", title: "Login page missing HSTS header", file: loginUrl });
205
- if (!headers["content-security-policy"]) findings.push({ severity: "P2", title: "Login page missing CSP header", file: loginUrl });
206
- if (headers["x-powered-by"]) findings.push({ severity: "P2", title: "Login page exposes X-Powered-By: " + headers["x-powered-by"], file: loginUrl });
207
- } catch { /* curl failed, non-blocking */ }
208
- return { available: true, loginUrl, findings };
209
- }
210
-
211
- function isValidUrl(url) {
212
- try { const p = new URL(url); return p.protocol === "http:" || p.protocol === "https:"; } catch { return false; }
213
- }
214
-
215
- function secureTempFile(name) {
216
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sl-auth-"));
217
- return path.join(dir, name);
218
- }
219
-
220
- export class AuthAuditError extends Error {
221
- constructor(message) { super(message); this.name = "AuthAuditError"; }
222
- }
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ import { randomUUID } from "node:crypto";
6
+
7
+ /**
8
+ * Jules Tanaka — Authenticated Page Audit
9
+ *
10
+ * Provisions an AIdenID ephemeral identity, uses Playwright to log in,
11
+ * then inspects authenticated pages (DevTools console, DOM, headers).
12
+ * Falls back gracefully when AIdenID or Playwright unavailable.
13
+ */
14
+
15
+ export function authAudit(input) {
16
+ if (!AUTH_OPS.has(input.operation)) {
17
+ throw new AuthAuditError("Unknown operation: " + input.operation + ". Valid: " + [...AUTH_OPS].join(", "));
18
+ }
19
+ return AUTH_DISPATCH[input.operation](input);
20
+ }
21
+
22
+ const AUTH_OPS = new Set([
23
+ "provision_test_identity",
24
+ "authenticated_page_check",
25
+ "check_auth_flow_security",
26
+ ]);
27
+
28
+ const AUTH_DISPATCH = {
29
+ provision_test_identity: provisionTestIdentity,
30
+ authenticated_page_check: authenticatedPageCheck,
31
+ check_auth_flow_security: checkAuthFlowSecurity,
32
+ };
33
+
34
+ async function provisionTestIdentity(input) {
35
+ try {
36
+ const { provisionEmailIdentity, resolveAidenIdCredentials } = await import("../../../ai/aidenid.js");
37
+ const creds = await resolveAidenIdCredentials();
38
+ if (!creds.apiKey) {
39
+ return { available: false, reason: "AIdenID API key not configured (set AIDENID_API_KEY)" };
40
+ }
41
+ const result = await provisionEmailIdentity({
42
+ apiUrl: creds.apiUrl, apiKey: creds.apiKey,
43
+ tags: ["jules-audit", "frontend-test"],
44
+ ttlSeconds: 3600, dryRun: input.execute !== true,
45
+ });
46
+ return { available: true, dryRun: input.execute !== true, identity: result.identity || result };
47
+ } catch (err) {
48
+ return { available: false, reason: "AIdenID provisioning failed: " + err.message };
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Run Playwright to authenticate and inspect the page.
54
+ * - URLs and credentials passed ONLY via env vars (no string interpolation)
55
+ * - Auth verification checks URL change + cookie presence (not just click success)
56
+ * - Console errors redacted to prevent sensitive data leakage
57
+ * - Cookie values never captured (names + flags only)
58
+ * - Temp script cleanup in finally block (not just success path)
59
+ */
60
+ async function authenticatedPageCheck(input) {
61
+ const url = input.url;
62
+ if (!url) throw new AuthAuditError("authenticated_page_check requires url");
63
+ if (!isValidUrl(url)) throw new AuthAuditError("Invalid URL: " + url);
64
+
65
+ const loginUrl = input.loginUrl || url + "/login";
66
+ let scriptPath = null;
67
+
68
+ try {
69
+ scriptPath = secureTempFile("sl-auth-audit-" + randomUUID().slice(0, 8) + ".cjs");
70
+ fs.writeFileSync(scriptPath, PLAYWRIGHT_AUTH_SCRIPT);
71
+
72
+ // Use scrubbed env strip API keys/tokens from child process
73
+ const { buildScrubbedEnv } = await import("./shell.js");
74
+ const env = {
75
+ ...buildScrubbedEnv(),
76
+ SL_AUDIT_TARGET_URL: url,
77
+ SL_AUDIT_LOGIN_URL: loginUrl,
78
+ SL_AUDIT_TEST_EMAIL: input.email || "",
79
+ SL_AUDIT_TEST_PASSWORD: input.password || "",
80
+ SL_AUDIT_EMAIL_FIELD: input.emailField || "",
81
+ SL_AUDIT_PASSWORD_FIELD: input.passwordField || "",
82
+ SL_AUDIT_SUBMIT_SELECTOR: input.submitSelector || "",
83
+ };
84
+
85
+ const output = execFileSync("node", [scriptPath], {
86
+ encoding: "utf-8", timeout: 60000,
87
+ stdio: ["pipe", "pipe", "pipe"],
88
+ env,
89
+ });
90
+
91
+ const result = JSON.parse(output.trim());
92
+ const findings = [];
93
+ for (const cookie of (result.cookies || [])) {
94
+ if (cookie.sensitive && !cookie.httpOnly) {
95
+ findings.push({ severity: "P1", title: "Sensitive cookie '" + cookie.name + "' missing httpOnly flag", file: url });
96
+ }
97
+ if (cookie.sensitive && !cookie.secure) {
98
+ findings.push({ severity: "P1", title: "Sensitive cookie '" + cookie.name + "' missing Secure flag", file: url });
99
+ }
100
+ if (cookie.sensitive && cookie.sameSite === "None") {
101
+ findings.push({ severity: "P2", title: "Sensitive cookie '" + cookie.name + "' has SameSite=None", file: url });
102
+ }
103
+ }
104
+ return { available: true, method: "playwright", findings, ...result };
105
+ } catch (err) {
106
+ return { available: false, reason: "Playwright auth audit failed: " + err.message };
107
+ } finally {
108
+ // Clean up temp script AND its mkdtemp parent directory
109
+ if (scriptPath) {
110
+ try { fs.unlinkSync(scriptPath); } catch { /* best effort */ }
111
+ try { fs.rmdirSync(path.dirname(scriptPath)); } catch { /* best effort — dir may not be empty */ }
112
+ }
113
+ }
114
+ }
115
+
116
+ // Playwright script as a constant — no string interpolation of URLs/credentials.
117
+ // All dynamic values come from environment variables at runtime.
118
+ const PLAYWRIGHT_AUTH_SCRIPT = `
119
+ const { chromium } = require('playwright');
120
+ (async () => {
121
+ const targetUrl = process.env.SL_AUDIT_TARGET_URL;
122
+ const loginUrl = process.env.SL_AUDIT_LOGIN_URL;
123
+ const email = process.env.SL_AUDIT_TEST_EMAIL;
124
+ const password = process.env.SL_AUDIT_TEST_PASSWORD;
125
+ const emailSelector = process.env.SL_AUDIT_EMAIL_FIELD || 'input[type="email"]';
126
+ const passwordSelector = process.env.SL_AUDIT_PASSWORD_FIELD || 'input[type="password"]';
127
+ const submitSelector = process.env.SL_AUDIT_SUBMIT_SELECTOR || 'button[type="submit"]';
128
+
129
+ const browser = await chromium.launch({ headless: true });
130
+ const page = await browser.newPage();
131
+ const results = { authenticated: false, errors: [], cookies: [], headers: {}, domStats: {} };
132
+
133
+ try {
134
+ if (email && password && loginUrl) {
135
+ await page.goto(loginUrl, { waitUntil: 'networkidle', timeout: 30000 });
136
+ await page.fill(emailSelector, email);
137
+ await page.fill(passwordSelector, password);
138
+ await page.click(submitSelector);
139
+ await page.waitForNavigation({ waitUntil: 'networkidle', timeout: 15000 }).catch(() => {});
140
+ // P2 fix: verify auth by checking URL change + session cookie presence
141
+ const currentUrl = page.url();
142
+ const postCookies = await page.context().cookies();
143
+ results.authenticated = currentUrl !== loginUrl || postCookies.some(c => /session|token|auth/i.test(c.name));
144
+ }
145
+
146
+ await page.goto(targetUrl, { waitUntil: 'networkidle', timeout: 30000 });
147
+
148
+ // P2 fix: redact sensitive content from console errors
149
+ page.on('console', msg => {
150
+ if (msg.type() === 'error') {
151
+ const text = (msg.text() || '').slice(0, 200).replace(/Bearer\\s+\\S+/gi, 'Bearer [REDACTED]').replace(/token[=:]\\S+/gi, 'token=[REDACTED]');
152
+ results.errors.push({ text });
153
+ }
154
+ });
155
+
156
+ // P2 fix: capture cookie names + flags only, never values
157
+ const cookies = await page.context().cookies();
158
+ results.cookies = cookies.map(c => ({
159
+ name: c.name, domain: c.domain,
160
+ httpOnly: c.httpOnly, secure: c.secure,
161
+ sameSite: c.sameSite,
162
+ sensitive: /session|token|auth|jwt/i.test(c.name),
163
+ }));
164
+
165
+ results.domStats = await page.evaluate(() => ({
166
+ title: document.title,
167
+ nodeCount: document.querySelectorAll('*').length,
168
+ formCount: document.querySelectorAll('form').length,
169
+ inputCount: document.querySelectorAll('input').length,
170
+ }));
171
+
172
+ const response = await page.goto(targetUrl, { waitUntil: 'commit', timeout: 10000 }).catch(() => null);
173
+ if (response) {
174
+ const h = response.headers();
175
+ results.headers = {
176
+ 'content-security-policy': h['content-security-policy'] || null,
177
+ 'x-frame-options': h['x-frame-options'] || null,
178
+ 'strict-transport-security': h['strict-transport-security'] || null,
179
+ 'cache-control': h['cache-control'] || null,
180
+ };
181
+ }
182
+ } catch (err) {
183
+ results.errors.push({ text: 'Navigation error: ' + (err.message || '').slice(0, 100) });
184
+ } finally {
185
+ try { console.log(JSON.stringify(results)); } catch { /* output failure non-blocking */ }
186
+ await browser.close();
187
+ }
188
+ })();
189
+ `;
190
+
191
+ function checkAuthFlowSecurity(input) {
192
+ const loginUrl = input.loginUrl || input.url;
193
+ if (!loginUrl) throw new AuthAuditError("check_auth_flow_security requires loginUrl or url");
194
+ if (!isValidUrl(loginUrl)) throw new AuthAuditError("Invalid URL: " + loginUrl);
195
+
196
+ const findings = [];
197
+ try {
198
+ const output = execFileSync("curl", ["-sI", "-L", "--max-time", "10", loginUrl], {
199
+ encoding: "utf-8", timeout: 15000, stdio: ["pipe", "pipe", "pipe"],
200
+ });
201
+ const headers = {};
202
+ for (const line of output.split("\n")) {
203
+ const idx = line.indexOf(":");
204
+ if (idx > 0) headers[line.slice(0, idx).trim().toLowerCase()] = line.slice(idx + 1).trim();
205
+ }
206
+ if (!headers["strict-transport-security"]) findings.push({ severity: "P1", title: "Login page missing HSTS header", file: loginUrl });
207
+ if (!headers["content-security-policy"]) findings.push({ severity: "P2", title: "Login page missing CSP header", file: loginUrl });
208
+ if (headers["x-powered-by"]) findings.push({ severity: "P2", title: "Login page exposes X-Powered-By: " + headers["x-powered-by"], file: loginUrl });
209
+ } catch (err) {
210
+ return { available: false, loginUrl, findings, reason: "curl failed: " + err.message };
211
+ }
212
+ return { available: true, loginUrl, findings };
213
+ }
214
+
215
+ function isValidUrl(url) {
216
+ try { const p = new URL(url); return p.protocol === "http:" || p.protocol === "https:"; } catch { return false; }
217
+ }
218
+
219
+ function secureTempFile(name) {
220
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sl-auth-"));
221
+ return path.join(dir, name);
222
+ }
223
+
224
+ export class AuthAuditError extends Error {
225
+ constructor(message) { super(message); this.name = "AuthAuditError"; }
226
+ }