architecture-harness 0.22.0 → 0.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/package.json +23 -3
- package/src/cli/bash-command-guard.mjs +44 -5
- package/src/cli/bash-command-guard.test.mjs +35 -1
- package/src/cli/check-commands.mjs +82 -0
- package/src/cli/check-commands.test.mjs +190 -0
- package/src/cli/check.mjs +34 -13
- package/src/cli/ci-template.test.mjs +12 -0
- package/src/cli/cli.test.mjs +17 -1
- package/src/cli/codex-implement.mjs +7 -2
- package/src/cli/codex-implement.test.mjs +29 -0
- package/src/cli/commit-msg.mjs +5 -2
- package/src/cli/commit-msg.test.mjs +12 -0
- package/src/cli/dispatch-reminder.mjs +4 -1
- package/src/cli/dispatch-reminder.test.mjs +5 -1
- package/src/cli/generated-file-guard.mjs +10 -1
- package/src/cli/generated-file-guard.test.mjs +10 -0
- package/src/cli/git-hooks.test.mjs +5 -0
- package/src/cli/post-edit-gate.test.mjs +9 -2
- package/src/cli/pr-check.mjs +15 -2
- package/src/cli/pr-check.test.mjs +19 -9
- package/src/cli/qc.mjs +27 -3
- package/src/cli/screens-discovery.mjs +60 -0
- package/src/cli/screens.mjs +84 -0
- package/src/cli/shell-command.mjs +3 -1
- package/src/cli/stack.mjs +14 -0
- package/src/cli/stop-gate.test.mjs +17 -0
- package/src/cli/work-order-guard.mjs +2 -2
- package/src/config.mjs +15 -0
- package/src/config.test.mjs +33 -1
- package/src/eslint/rules/no-raw-fetch.mjs +42 -2
- package/src/eslint/rules.test.mjs +15 -0
- package/src/gates/audit-append-only.mjs +18 -4
- package/src/gates/audit-append-only.test.mjs +19 -0
- package/src/gates/tenant-predicate.mjs +147 -7
- package/src/gates/tenant-predicate.test.mjs +55 -0
- package/src/gates/tenant-tables.mjs +5 -2
- package/src/gates/tenant-tables.test.mjs +8 -0
- package/src/gates/threshold-ratchet.mjs +12 -9
- package/src/gates/threshold-ratchet.test.mjs +16 -0
- package/src/plugin.test.mjs +28 -0
- package/src/screens/auth-context.test.mjs +41 -0
- package/src/screens/auth-run.test.mjs +147 -0
- package/src/screens/auth.mjs +223 -0
- package/src/screens/auth.test.mjs +76 -0
- package/src/screens/capture-idle.test.mjs +27 -0
- package/src/screens/capture.browser-test.mjs +73 -0
- package/src/screens/capture.mjs +175 -0
- package/src/screens/capture.test.mjs +28 -0
- package/src/screens/catalog.browser-test.mjs +32 -0
- package/src/screens/catalog.mjs +72 -0
- package/src/screens/catalog.test.mjs +36 -0
- package/src/screens/chrome.mjs +21 -0
- package/src/screens/compare.mjs +40 -0
- package/src/screens/compare.test.mjs +30 -0
- package/src/screens/discovery.browser-test.mjs +29 -0
- package/src/screens/discovery.mjs +158 -0
- package/src/screens/discovery.test.mjs +27 -0
- package/src/screens/inventory.mjs +69 -0
- package/src/screens/inventory.test.mjs +10 -0
- package/src/screens/map.mjs +63 -0
- package/src/screens/map.test.mjs +35 -0
- package/src/screens/open.browser-test.mjs +50 -0
- package/src/screens/regions.mjs +137 -0
- package/src/screens/regions.test.mjs +38 -0
- package/src/screens/session-files.mjs +39 -0
- package/src/screens/session-files.test.mjs +39 -0
- package/src/screens/setup.browser-test.mjs +49 -0
- package/src/screens/setup.mjs +78 -0
- package/src/screens/stack-auth.browser-test.mjs +30 -0
- package/src/screens/stack-auth.mjs +106 -0
- package/src/screens/stack-auth.test.mjs +65 -0
- package/src/screens/write-guard.mjs +26 -0
- package/src/stack/stack.mjs +131 -0
- package/src/stack/stack.test.mjs +40 -0
- package/src/stack/supervisor.mjs +30 -0
- package/templates/github/workflows/ci.yml +13 -5
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { chromium } from "playwright";
|
|
9
|
+
import { browserSession, seedSession } from "./auth.mjs";
|
|
10
|
+
import { runScreens } from "../cli/screens.mjs";
|
|
11
|
+
import { captureScreens } from "./capture.mjs";
|
|
12
|
+
import { chromeMissing } from "./chrome.mjs";
|
|
13
|
+
|
|
14
|
+
const noChrome = await chromeMissing(chromium);
|
|
15
|
+
|
|
16
|
+
async function fixture(t) {
|
|
17
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-auth-run-"));
|
|
18
|
+
t.mock.method(os, "homedir", () => root);
|
|
19
|
+
const requests = [];
|
|
20
|
+
const server = http.createServer((req, res) => {
|
|
21
|
+
requests.push(req.url);
|
|
22
|
+
res.setHeader("content-type", "text/html");
|
|
23
|
+
if (req.url.startsWith("/bff/login") && req.headers.cookie?.includes("sso=yes")) {
|
|
24
|
+
res.writeHead(302, { "set-cookie": "app=yes; Path=/; HttpOnly", location: "/projects" }).end();
|
|
25
|
+
} else if (req.url === "/projects" && req.headers.cookie?.includes("app=yes")) res.end('<main id="signed">Projects</main>');
|
|
26
|
+
else res.end('<input id="user"><input id="pass" type="password"><button id="submit">Login</button>');
|
|
27
|
+
});
|
|
28
|
+
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
|
29
|
+
t.after(async () => { await new Promise(resolve => server.close(resolve)); rmSync(root, { recursive: true, force: true }); });
|
|
30
|
+
const baseUrl = `http://127.0.0.1:${server.address().port}`;
|
|
31
|
+
const target = { baseUrl, auth: { mode: "browser-session", domain: "fixture.auth0.test", path: "/projects", signedIn: "#signed" } };
|
|
32
|
+
const state = path.join(root, ".qc/screens/state/fixture.auth0.test.json");
|
|
33
|
+
mkdirSync(path.dirname(state), { recursive: true });
|
|
34
|
+
const save = cookies => writeFileSync(state, JSON.stringify({ cookies: cookies.map(name => ({ name, value: "yes", domain: "127.0.0.1", path: "/", expires: -1, httpOnly: true, secure: false, sameSite: "Lax" })), origins: [] }));
|
|
35
|
+
return { root, requests, target, state, save };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test("expired application state refreshes once through the login path and persists the renewed cookie", { skip: noChrome }, async t => {
|
|
39
|
+
const f = await fixture(t);
|
|
40
|
+
f.save(["sso"]);
|
|
41
|
+
const session = await browserSession(chromium, f.target, { targetName: "new-local", timeout: 3000, allowInteractive: false });
|
|
42
|
+
await session.close();
|
|
43
|
+
assert.equal(f.requests.filter(p => p.startsWith("/bff/login")).length, 1);
|
|
44
|
+
assert.ok(JSON.parse(readFileSync(f.state)).cookies.some(c => c.name === "app"));
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("seed errors name the target and failing field without exposing browser diagnostics or credentials", { skip: noChrome }, async t => {
|
|
48
|
+
const f = await fixture(t);
|
|
49
|
+
const target = { ...f.target, auth: { ...f.target.auth, mode: "seed-login", path: "/login", userSelector: "#user", passwordSelector: "#missing", submitSelector: "#submit" } };
|
|
50
|
+
await assert.rejects(seedSession(chromium, target, { targetName: "old-local", credentials: { user: "test", password: randomUUID() }, timeout: 3000 }), error => {
|
|
51
|
+
assert.equal(error.message, "old-local: seed sign-in failed at the password field");
|
|
52
|
+
return true;
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("run stops with code four and one human instruction without capturing or retrying", { skip: noChrome }, async t => {
|
|
57
|
+
const f = await fixture(t);
|
|
58
|
+
f.save([]);
|
|
59
|
+
const map = path.join(f.root, "map.json");
|
|
60
|
+
writeFileSync(map, JSON.stringify({ widths: [200], targets: { "new-local": f.target, other: f.target }, screens: [{ name: "projects", targets: { "new-local": { path: "/projects" }, other: { path: "/projects" } } }] }));
|
|
61
|
+
const lines = [];
|
|
62
|
+
const code = await runScreens(["run", "projects", "--map", map, "--targets", "new-local,other", "--out", path.join(f.root, "out"), "--timeout", "3000", "--sign-in-timeout", "100"], { say: line => lines.push(line) });
|
|
63
|
+
assert.equal(code, 4);
|
|
64
|
+
assert.deepEqual(lines, ["new-local: needs a person to sign in (run qc screens auth new-local --headed)"]);
|
|
65
|
+
assert.equal(f.requests.filter(p => p.startsWith("/bff/login")).length, 1);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("capture checks each target once before navigating any screen and closes earlier sessions on failure", async t => {
|
|
69
|
+
const f = await fixture(t);
|
|
70
|
+
const events = [];
|
|
71
|
+
await assert.rejects(captureScreens({ widths: [200], targets: { first: f.target, second: f.target }, screens: [{ name: "projects", targets: { first: { path: "/projects" }, second: { path: "/projects" } } }] }, { targets: ["first", "second"], out: path.join(f.root, "out") }, {
|
|
72
|
+
sessionFactory: async (_chromium, _target, options) => {
|
|
73
|
+
events.push(options.targetName);
|
|
74
|
+
assert.equal(options.allowInteractive, false);
|
|
75
|
+
if (options.targetName === "second") throw new Error("second failed");
|
|
76
|
+
return { context: { route: async () => {} }, page: { setViewportSize: async () => { throw new Error("capture before preflight"); } }, close: async () => events.push("closed") };
|
|
77
|
+
},
|
|
78
|
+
}), /second failed/);
|
|
79
|
+
assert.deepEqual(events, ["first", "second", "closed"]);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
// A headed browser needs a display, which a Linux CI runner lacks.
|
|
84
|
+
test("headed auth accepts the named target and saves a valid session", { skip: noChrome || (process.platform === "linux" && !process.env.DISPLAY) }, async t => {
|
|
85
|
+
const f = await fixture(t);
|
|
86
|
+
f.save(["app"]);
|
|
87
|
+
const map = path.join(f.root, "map.json");
|
|
88
|
+
writeFileSync(map, JSON.stringify({ widths: [200], targets: { "new-local": f.target, other: f.target }, screens: [{ name: "projects", targets: { "new-local": { path: "/projects" }, other: { path: "/projects" } } }] }));
|
|
89
|
+
const lines = [];
|
|
90
|
+
assert.equal(await runScreens(["auth", "new-local", "--headed", "--map", map, "--timeout", "3000"], { say: line => lines.push(line) }), 0);
|
|
91
|
+
assert.deepEqual(lines, ["new-local: signed in"]);
|
|
92
|
+
assert.ok(JSON.parse(readFileSync(f.state)).cookies.some(c => c.name === "app"));
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test("parallel sessions preserve the shared saved state and write a complete refresh ledger", { skip: noChrome }, async t => {
|
|
96
|
+
const f = await fixture(t);
|
|
97
|
+
f.save(["sso"]);
|
|
98
|
+
const { targetSession } = await import("./stack-auth.mjs");
|
|
99
|
+
const sessions = await Promise.all(Array.from({ length: 3 }, () => targetSession(chromium, f.target, { targetName: "new-local", timeout: 3000, allowInteractive: false })));
|
|
100
|
+
await Promise.all(sessions.map(s => s.close()));
|
|
101
|
+
assert.equal(f.requests.filter(p => p.startsWith("/bff/login")).length, 1);
|
|
102
|
+
assert.ok(JSON.parse(readFileSync(f.state)).cookies.some(c => c.name === "app"));
|
|
103
|
+
const files = readdirSync(path.join(f.root, ".qc/screens"));
|
|
104
|
+
const ledger = files.filter(name => /^session-.*\.json$/.test(name));
|
|
105
|
+
assert.equal(ledger.length, 1);
|
|
106
|
+
const record = JSON.parse(readFileSync(path.join(f.root, ".qc/screens", ledger[0])));
|
|
107
|
+
assert.equal(record.target.baseUrl, f.target.baseUrl);
|
|
108
|
+
assert.ok(Number.isFinite(Date.parse(record.lastRefreshed)));
|
|
109
|
+
assert.equal(files.some(name => name.endsWith(".lock") || name.endsWith(".tmp")), false);
|
|
110
|
+
assert.deepEqual(readdirSync(path.dirname(f.state)), ["fixture.auth0.test.json"]);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("a browser launch failure names the target and method without asking for human sign-in", async t => {
|
|
114
|
+
const f = await fixture(t);
|
|
115
|
+
f.save([]);
|
|
116
|
+
await assert.rejects(browserSession({ launch: async () => { throw new Error("private browser diagnostics"); } }, f.target, { targetName: "new-local", allowInteractive: false }), error => {
|
|
117
|
+
assert.equal(error.message, "new-local: browser-session sign-in failed at the browser");
|
|
118
|
+
assert.equal(error.exitCode, undefined);
|
|
119
|
+
return true;
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("--allow-writes reaches the capture write guard as well as the session", async t => {
|
|
124
|
+
const f = await fixture(t);
|
|
125
|
+
const verdicts = [];
|
|
126
|
+
const report = await captureScreens({ widths: [200], targets: { first: f.target, second: f.target }, screens: [{ name: "projects", targets: { first: { path: "/projects" }, second: { path: "/projects" } } }] }, { targets: ["first", "second"], out: path.join(f.root, "out"), allowWrites: true }, {
|
|
127
|
+
say: () => {},
|
|
128
|
+
sessionFactory: async (_chromium, _target, options) => {
|
|
129
|
+
assert.equal(options.allowWrites, true);
|
|
130
|
+
const context = { route: async (_pattern, handler) => {
|
|
131
|
+
await handler({ request: () => ({ method: () => "POST", url: () => `${f.target.baseUrl}/api/items` }), fallback: async () => verdicts.push("allowed"), abort: async () => verdicts.push("blocked") });
|
|
132
|
+
} };
|
|
133
|
+
return { context, page: { setViewportSize: async () => { throw new Error("stop after the guard"); } }, close: async () => {} };
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
assert.equal(report[0].error.message, "stop after the guard");
|
|
137
|
+
assert.deepEqual(verdicts, ["allowed", "allowed"]);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("a cached target also passes preflight before a changed-target capture", async t => {
|
|
141
|
+
const f = await fixture(t);
|
|
142
|
+
const names = [];
|
|
143
|
+
await assert.rejects(captureScreens({ widths: [200], targets: { first: f.target, second: f.target }, screens: [{ name: "projects", targets: { first: { path: "/projects" }, second: { path: "/projects" } } }] }, { targets: ["first", "second"], changed: "second", out: path.join(f.root, "out") }, {
|
|
144
|
+
sessionFactory: async (_chromium, _target, options) => { names.push(options.targetName); throw new Error("preflight failed"); },
|
|
145
|
+
}), /preflight failed/);
|
|
146
|
+
assert.deepEqual(names, ["first"]);
|
|
147
|
+
});
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { atomicJson, withFileLock } from "./session-files.mjs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { requireLocalhost } from "./map.mjs";
|
|
6
|
+
import { installWriteGuard } from "./write-guard.mjs";
|
|
7
|
+
|
|
8
|
+
/** Branch: a failed session advances to the next method. */
|
|
9
|
+
export async function firstSignedIn(methods) {
|
|
10
|
+
for (const method of methods) {
|
|
11
|
+
const session = await method();
|
|
12
|
+
if (session) return session;
|
|
13
|
+
}
|
|
14
|
+
throw new Error("No signed-in page reached; complete sign-in in the headed Chrome window and rerun");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Resource: authentication files stay outside every repository. */
|
|
18
|
+
export function privateRoot() {
|
|
19
|
+
const root = path.join(os.homedir(), ".qc", "screens");
|
|
20
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
21
|
+
for (let current = realpathSync(root); ; current = path.dirname(current)) {
|
|
22
|
+
if (existsSync(path.join(current, ".git"))) throw new Error("The screens state directory must stay outside every repository");
|
|
23
|
+
if (current === path.dirname(current)) break;
|
|
24
|
+
}
|
|
25
|
+
return root;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Resource: copy session files without opening the password store. */
|
|
29
|
+
export function copyChromeProfile(root, source) {
|
|
30
|
+
const chrome = source ?? (process.platform === "win32" ? path.join(process.env.LOCALAPPDATA, "Google", "Chrome", "User Data") : process.platform === "darwin" ? path.join(os.homedir(), "Library", "Application Support", "Google", "Chrome") : path.join(os.homedir(), ".config", "google-chrome"));
|
|
31
|
+
const localState = path.join(chrome, "Local State");
|
|
32
|
+
const profileName = JSON.parse(readFileSync(localState, "utf8")).profile?.last_used ?? "Default";
|
|
33
|
+
if (!/^(Default|Profile \d+)$/.test(profileName)) throw new Error("Chrome profile name is unsupported");
|
|
34
|
+
const destination = path.join(root, "profile");
|
|
35
|
+
mkdirSync(destination, { recursive: true, mode: 0o700 });
|
|
36
|
+
cpSync(localState, path.join(destination, "Local State"));
|
|
37
|
+
const output = path.join(destination, profileName);
|
|
38
|
+
mkdirSync(output, { recursive: true, mode: 0o700 });
|
|
39
|
+
for (const name of ["Cookies", "Cookies-journal", "Network/Cookies", "Network/Cookies-journal", "Local Storage", "IndexedDB", "Preferences", "Secure Preferences"]) {
|
|
40
|
+
const file = path.join(chrome, profileName, name);
|
|
41
|
+
if (existsSync(file)) cpSync(file, path.join(output, name), { recursive: true });
|
|
42
|
+
}
|
|
43
|
+
return { directory: destination, profileName };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function reachesSignedIn(context, target, timeout) {
|
|
47
|
+
const page = await context.newPage();
|
|
48
|
+
await page.goto(new URL(target.auth.path ?? "/projects", target.baseUrl).href, { waitUntil: "domcontentloaded", timeout });
|
|
49
|
+
await page.locator(target.auth.signedIn).first().waitFor({ state: "visible", timeout });
|
|
50
|
+
if (new URL(page.url()).origin !== new URL(target.baseUrl).origin) throw new Error("Sign-in finished on another origin");
|
|
51
|
+
return { context, page };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function saveState(context, file, target) {
|
|
55
|
+
// A parent-domain cookie, such as .auth0.com, reaches every tenant on that domain, so only exact hosts are kept.
|
|
56
|
+
const hosts = [new URL(target.baseUrl).hostname, target.auth.domain].filter(Boolean).map(host => host.toLowerCase());
|
|
57
|
+
const origins = [new URL(target.baseUrl).origin, ...(target.auth.domain ? [`https://${target.auth.domain.toLowerCase()}`] : [])];
|
|
58
|
+
const state = await context.storageState();
|
|
59
|
+
state.cookies = state.cookies.filter(cookie => hosts.includes(cookie.domain.replace(/^\./, "").toLowerCase()));
|
|
60
|
+
state.origins = state.origins.filter(origin => origins.includes(new URL(origin.origin).origin));
|
|
61
|
+
await atomicJson(file, state);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Record: interactive sign-in is a terminal result for unattended commands. */
|
|
65
|
+
export class PersonSignInRequired extends Error {
|
|
66
|
+
constructor(targetName) {
|
|
67
|
+
super(`${targetName}: needs a person to sign in (run qc screens auth ${targetName} --headed)`);
|
|
68
|
+
this.exitCode = 4;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Pipeline: reuse saved cookies and refresh through the real login page without typing. */
|
|
73
|
+
export async function browserSession(chromium, target, options = {}) {
|
|
74
|
+
const { targetName = target.name ?? target.baseUrl } = options;
|
|
75
|
+
try {
|
|
76
|
+
const file = path.join(privateRoot(), "state", `${target.auth.domain}.json`);
|
|
77
|
+
return await withFileLock(file, () => lockedBrowserSession(chromium, target, file, { ...options, targetName }));
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error instanceof PersonSignInRequired || error.authFailure) throw error;
|
|
80
|
+
throw authFailure(targetName, "browser-session", "the session files");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function authFailure(targetName, method, stage) {
|
|
85
|
+
const error = new Error(`${targetName}: ${method} sign-in failed at ${stage}`);
|
|
86
|
+
error.authFailure = true;
|
|
87
|
+
return error;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function lockedBrowserSession(chromium, target, file, { timeout = 15000, signInTimeout = 180000, say = console.error, chromeProfile, allowInteractive = false, headed = false, allowWrites = false, targetName }) {
|
|
91
|
+
const launch = async method => {
|
|
92
|
+
let context, browser, profileRoot;
|
|
93
|
+
let stage = "the copied Chrome profile";
|
|
94
|
+
const close = async () => {
|
|
95
|
+
try { if (context) await context.close(); }
|
|
96
|
+
finally {
|
|
97
|
+
try { if (browser) await browser.close(); }
|
|
98
|
+
finally { if (profileRoot) rmSync(profileRoot, { recursive: true, force: true }); }
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
try {
|
|
102
|
+
if (method === "profile") {
|
|
103
|
+
profileRoot = path.join(privateRoot(), `profile-${process.pid}-${Date.now()}`);
|
|
104
|
+
const profile = copyChromeProfile(profileRoot, chromeProfile);
|
|
105
|
+
stage = "the browser";
|
|
106
|
+
context = await chromium.launchPersistentContext(profile.directory, { channel: "chrome", headless: !headed, deviceScaleFactor: 1, reducedMotion: "reduce", serviceWorkers: "block", args: [`--profile-directory=${profile.profileName}`] });
|
|
107
|
+
} else {
|
|
108
|
+
if (method === "state" && !existsSync(file)) return null;
|
|
109
|
+
stage = "the browser";
|
|
110
|
+
browser = await chromium.launch({ channel: "chrome", headless: !headed && method !== "headed" });
|
|
111
|
+
stage = "the session file";
|
|
112
|
+
const storageState = method === "state" ? JSON.parse(readFileSync(file, "utf8")) : undefined;
|
|
113
|
+
stage = "the browser";
|
|
114
|
+
context = await browser.newContext({ deviceScaleFactor: 1, reducedMotion: "reduce", serviceWorkers: "block", ...(storageState ? { storageState } : {}) });
|
|
115
|
+
}
|
|
116
|
+
await installWriteGuard(context, target, { allowWrites });
|
|
117
|
+
if (method === "headed") say(`${targetName}: sign in once in the Chrome window.`);
|
|
118
|
+
stage = "the login page";
|
|
119
|
+
let session;
|
|
120
|
+
if (method === "state") {
|
|
121
|
+
try {
|
|
122
|
+
session = await reachesSignedIn(context, { ...target, auth: { ...target.auth, path: target.auth.checkPath ?? "/projects" } }, timeout);
|
|
123
|
+
} catch {
|
|
124
|
+
for (const page of context.pages()) await page.close();
|
|
125
|
+
const loginPath = target.auth.loginPath ?? (target.auth.path && target.auth.path !== "/projects" ? target.auth.path : "/bff/login?returnTo=%2Fprojects");
|
|
126
|
+
session = await reachesSignedIn(context, { ...target, auth: { ...target.auth, path: loginPath } }, timeout);
|
|
127
|
+
}
|
|
128
|
+
} else session = await reachesSignedIn(context, target, method === "headed" ? signInTimeout : timeout);
|
|
129
|
+
stage = "the session file";
|
|
130
|
+
await saveState(context, file, target);
|
|
131
|
+
return { ...session, close };
|
|
132
|
+
} catch {
|
|
133
|
+
await close().catch(() => {});
|
|
134
|
+
if (stage === "the browser" || stage === "the session file") throw authFailure(targetName, "browser-session", stage);
|
|
135
|
+
if (allowInteractive) say(`${targetName}: browser-session sign-in failed at the ${method === "state" ? "saved session and silent refresh" : method === "profile" ? "copied Chrome profile" : "headed login page"}.`);
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const methods = allowInteractive ? ["state", "profile", "headed"] : ["state"];
|
|
140
|
+
for (const method of methods) {
|
|
141
|
+
const session = await launch(method);
|
|
142
|
+
if (session) return session;
|
|
143
|
+
}
|
|
144
|
+
throw new PersonSignInRequired(targetName);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Resource: read only named fields, without evaluating seed code. */
|
|
148
|
+
export function seedFields(auth) {
|
|
149
|
+
try {
|
|
150
|
+
const source = readFileSync(auth.seedFile, "utf8");
|
|
151
|
+
let json;
|
|
152
|
+
try { json = JSON.parse(source); } catch { json = null; }
|
|
153
|
+
const field = name => {
|
|
154
|
+
if (json) return name.split(".").reduce((value, key) => value?.[key], json);
|
|
155
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name)) throw new Error("Invalid seed field");
|
|
156
|
+
const match = source.match(new RegExp(`(?:\\b${name}\\s*[:=]\\s*)(["'\x60])([^"'\x60\\r\\n]+)\\1`));
|
|
157
|
+
return match?.[2];
|
|
158
|
+
};
|
|
159
|
+
const user = field(auth.userField);
|
|
160
|
+
const password = field(auth.passwordField);
|
|
161
|
+
if (typeof user !== "string" || typeof password !== "string" || !user || !password) throw new Error("Missing seed fields");
|
|
162
|
+
return { user, password };
|
|
163
|
+
} catch {
|
|
164
|
+
throw new Error("Cannot read the named seed fields");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Pipeline: fill credentials only while every request stays on loopback. */
|
|
169
|
+
export async function seedSession(chromium, target, options = {}) {
|
|
170
|
+
const { targetName = target.name ?? target.baseUrl } = options;
|
|
171
|
+
const method = target.auth.mode === "form" ? "form" : "seed";
|
|
172
|
+
try {
|
|
173
|
+
requireLocalhost(target.baseUrl);
|
|
174
|
+
const file = path.join(privateRoot(), `local-${new URL(target.baseUrl).port || "80"}.json`);
|
|
175
|
+
return await withFileLock(file, () => lockedSeedSession(chromium, target, file, { ...options, targetName, method }));
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (error.authFailure) throw error;
|
|
178
|
+
throw authFailure(targetName, method, "the localhost guard or session files");
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function lockedSeedSession(chromium, target, file, { timeout = 15000, credentials, savedOnly = false, headed = false, targetName, method }) {
|
|
183
|
+
let browser;
|
|
184
|
+
let stage = "the saved session";
|
|
185
|
+
try {
|
|
186
|
+
if (savedOnly && !existsSync(file)) throw new Error("No saved local session");
|
|
187
|
+
stage = "the browser";
|
|
188
|
+
browser = await chromium.launch({ channel: "chrome", headless: !headed });
|
|
189
|
+
const context = await browser.newContext({ deviceScaleFactor: 1, reducedMotion: "reduce", serviceWorkers: "block", ...(existsSync(file) ? { storageState: JSON.parse(readFileSync(file, "utf8")) } : {}) });
|
|
190
|
+
await context.route("**/*", async route => {
|
|
191
|
+
try { requireLocalhost(route.request().url()); } catch { await route.abort(); return; }
|
|
192
|
+
await route.continue();
|
|
193
|
+
});
|
|
194
|
+
if (savedOnly) {
|
|
195
|
+
stage = "the saved session";
|
|
196
|
+
const session = await reachesSignedIn(context, { ...target, auth: { ...target.auth, path: target.auth.checkPath ?? "/projects" } }, timeout);
|
|
197
|
+
await saveState(context, file, target);
|
|
198
|
+
return { ...session, close: () => browser.close() };
|
|
199
|
+
}
|
|
200
|
+
stage = "the login page";
|
|
201
|
+
const page = await context.newPage();
|
|
202
|
+
await page.goto(new URL(target.auth.path ?? "/login", target.baseUrl).href, { waitUntil: "domcontentloaded", timeout });
|
|
203
|
+
requireLocalhost(page.url());
|
|
204
|
+
stage = "the credential fields";
|
|
205
|
+
const { user, password } = credentials ?? seedFields(target.auth);
|
|
206
|
+
stage = "the username field";
|
|
207
|
+
await page.locator(target.auth.userSelector).fill(user, { timeout });
|
|
208
|
+
requireLocalhost(page.url());
|
|
209
|
+
stage = "the password field";
|
|
210
|
+
await page.locator(target.auth.passwordSelector).fill(password, { timeout });
|
|
211
|
+
requireLocalhost(page.url());
|
|
212
|
+
stage = "the submit control";
|
|
213
|
+
await page.locator(target.auth.submitSelector).click({ timeout });
|
|
214
|
+
stage = "the signed-in page";
|
|
215
|
+
await page.locator(target.auth.signedIn).first().waitFor({ state: "visible", timeout });
|
|
216
|
+
stage = "the session file";
|
|
217
|
+
await saveState(context, file, target);
|
|
218
|
+
return { context, page, close: () => browser.close() };
|
|
219
|
+
} catch {
|
|
220
|
+
if (browser) await browser.close().catch(() => {});
|
|
221
|
+
throw authFailure(targetName, method, stage);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { firstSignedIn, seedFields, copyChromeProfile, browserSession } from "./auth.mjs";
|
|
7
|
+
|
|
8
|
+
test("profile sign-in saves only target and authentication hosts", async t => {
|
|
9
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-auth-filter-"));
|
|
10
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
11
|
+
t.mock.method(os, "homedir", () => root);
|
|
12
|
+
const source = path.join(root, "chrome");
|
|
13
|
+
mkdirSync(source);
|
|
14
|
+
writeFileSync(path.join(source, "Local State"), JSON.stringify({ profile: { last_used: "Default" } }));
|
|
15
|
+
const target = { baseUrl: "https://app.example.test", auth: { domain: "tenant.auth0.test", signedIn: "main" } };
|
|
16
|
+
const context = {
|
|
17
|
+
route: async () => {}, close: async () => {},
|
|
18
|
+
newPage: async () => ({ goto: async () => {}, url: () => target.baseUrl, locator: () => ({ first: () => ({ waitFor: async () => {} }) }) }),
|
|
19
|
+
storageState: async () => ({
|
|
20
|
+
cookies: ["app.example.test", ".example.test", ".tenant.auth0.test", ".auth0.test", "foreign.test", "evilapp.example.test", "example.test.evil"].map(domain => ({ name: "session", domain, path: "/" })),
|
|
21
|
+
origins: [target.baseUrl, "https://tenant.auth0.test", "https://app.example.test:8443", "http://app.example.test", "https://foreign.test", "https://evilapp.example.test"].map(origin => ({ origin, localStorage: [] })),
|
|
22
|
+
}),
|
|
23
|
+
};
|
|
24
|
+
const session = await browserSession({ launchPersistentContext: async () => context }, target, { chromeProfile: source, allowInteractive: true, say: () => {} });
|
|
25
|
+
t.after(() => session.close());
|
|
26
|
+
const saved = JSON.parse(readFileSync(path.join(root, ".qc", "screens", "state", "tenant.auth0.test.json"), "utf8"));
|
|
27
|
+
assert.deepEqual(saved.cookies.map(cookie => cookie.domain), ["app.example.test", ".tenant.auth0.test"]);
|
|
28
|
+
assert.deepEqual(saved.origins.map(origin => origin.origin), [target.baseUrl, "https://tenant.auth0.test"]);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("auth falls back in order and stops at the first signed-in context", async () => {
|
|
32
|
+
const calls = [];
|
|
33
|
+
const session = { signedIn: true };
|
|
34
|
+
const result = await firstSignedIn([
|
|
35
|
+
async () => { calls.push("state"); return null; },
|
|
36
|
+
async () => { calls.push("profile"); return session; },
|
|
37
|
+
async () => { calls.push("headed"); throw new Error("must not run"); },
|
|
38
|
+
]);
|
|
39
|
+
assert.equal(result, session);
|
|
40
|
+
assert.deepEqual(calls, ["state", "profile"]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("auth reaches headed fallback after both reusable sessions fail", async () => {
|
|
44
|
+
const calls = [];
|
|
45
|
+
const session = {};
|
|
46
|
+
assert.equal(await firstSignedIn([async () => { calls.push(1); return null; }, async () => { calls.push(2); return null; }, async () => { calls.push(3); return session; }]), session);
|
|
47
|
+
assert.deepEqual(calls, [1, 2, 3]);
|
|
48
|
+
await assert.rejects(firstSignedIn([async () => null]), /signed-in/);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("profile copy includes cookies and excludes Chrome's password store", () => {
|
|
52
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-screen-profile-"));
|
|
53
|
+
try {
|
|
54
|
+
const source = path.join(root, "source");
|
|
55
|
+
mkdirSync(path.join(source, "Default", "Network"), { recursive: true });
|
|
56
|
+
writeFileSync(path.join(source, "Local State"), JSON.stringify({ profile: { last_used: "Default" } }));
|
|
57
|
+
writeFileSync(path.join(source, "Default", "Network", "Cookies"), "encrypted cookie fixture");
|
|
58
|
+
writeFileSync(path.join(source, "Default", "Login Data"), "password store fixture");
|
|
59
|
+
const copy = copyChromeProfile(root, source);
|
|
60
|
+
assert.equal(existsSync(path.join(copy.directory, "Default", "Network", "Cookies")), true);
|
|
61
|
+
assert.equal(existsSync(path.join(copy.directory, "Default", "Login Data")), false);
|
|
62
|
+
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("seed fields support JSON paths and literal source fields without evaluating code", () => {
|
|
66
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-screen-seed-"));
|
|
67
|
+
try {
|
|
68
|
+
const seedFile = path.join(root, "seed.json");
|
|
69
|
+
writeFileSync(seedFile, JSON.stringify({ account: { name: "a", pass: "b" } }));
|
|
70
|
+
assert.deepEqual(seedFields({ seedFile, userField: "account.name", passwordField: "account.pass" }), { user: "a", password: "b" });
|
|
71
|
+
writeFileSync(seedFile, 'const account = { username: "a", password: "b" }; throw new Error("must not evaluate");');
|
|
72
|
+
assert.deepEqual(seedFields({ seedFile, userField: "username", passwordField: "password" }), { user: "a", password: "b" });
|
|
73
|
+
writeFileSync(seedFile, 'const password = getSecret();');
|
|
74
|
+
assert.throws(() => seedFields({ seedFile, userField: "username", passwordField: "password" }), /^Error: Cannot read the named seed fields$/);
|
|
75
|
+
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
76
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import { mkdtempSync, existsSync, rmSync } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { chromium } from "playwright";
|
|
8
|
+
import { capturePage } from "./capture.mjs";
|
|
9
|
+
import { chromeMissing } from "./chrome.mjs";
|
|
10
|
+
|
|
11
|
+
test("an entry with idle false captures a page that polls forever", { skip: await chromeMissing(chromium) }, async t => {
|
|
12
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-capture-idle-"));
|
|
13
|
+
const server = http.createServer((req, res) => {
|
|
14
|
+
if (req.url === "/poll") return res.end("ok");
|
|
15
|
+
res.setHeader("content-type", "text/html");
|
|
16
|
+
res.end('<main id="ready">Pins</main><script>setInterval(() => fetch("/poll"), 100)</script>');
|
|
17
|
+
});
|
|
18
|
+
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
|
19
|
+
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); rmSync(root, { recursive: true, force: true }); });
|
|
20
|
+
const browser = await chromium.launch({ channel: "chrome" });
|
|
21
|
+
t.after(() => browser.close());
|
|
22
|
+
const page = await browser.newPage();
|
|
23
|
+
const target = { baseUrl: `http://127.0.0.1:${server.address().port}`, auth: { signedIn: "#ready" } };
|
|
24
|
+
await assert.rejects(capturePage({ page }, target, { path: "/", ready: "#ready" }, 200, 200, path.join(root, "busy.png"), 1500), /networkidle|Timeout/);
|
|
25
|
+
await capturePage({ page }, target, { path: "/", ready: "#ready", idle: false }, 200, 200, path.join(root, "polling.png"), 1500);
|
|
26
|
+
assert.ok(existsSync(path.join(root, "polling.png")));
|
|
27
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { setTimeout } from "node:timers/promises";
|
|
7
|
+
import { chromium } from "playwright";
|
|
8
|
+
import { PNG } from "pngjs";
|
|
9
|
+
import { capturePage } from "./capture.mjs";
|
|
10
|
+
import { findRegions } from "./regions.mjs";
|
|
11
|
+
import { collectInventory, diffInventory } from "./inventory.mjs";
|
|
12
|
+
|
|
13
|
+
test("accessibility inventory excludes table data and masked controls", async () => {
|
|
14
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
15
|
+
try {
|
|
16
|
+
const page = await browser.newPage();
|
|
17
|
+
const content = value => `<label>Email<input placeholder="Your email"></label><button aria-label="Next">Go</button><table><tr><th>Title</th></tr><tr><td>${value}</td></tr></table><section id="masked"><button>Hidden</button></section>`;
|
|
18
|
+
await page.setContent(content("First row"));
|
|
19
|
+
const first = await collectInventory(page, ["#masked"]);
|
|
20
|
+
await page.setContent(content("Other data"));
|
|
21
|
+
const second = await collectInventory(page, ["#masked"]);
|
|
22
|
+
assert.deepEqual(first.map(item => item.role), ["textbox", "button", "columnheader"]);
|
|
23
|
+
assert.equal(first[0].name, "Email");
|
|
24
|
+
assert.equal(first[0].placeholder, "Your email");
|
|
25
|
+
assert.deepEqual(diffInventory(first, second), []);
|
|
26
|
+
} finally { await browser.close(); }
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("different text in the same box produces identical layout images", async () => {
|
|
30
|
+
const directory = mkdtempSync(path.join(os.tmpdir(), "qc-screens-layout-"));
|
|
31
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
32
|
+
try {
|
|
33
|
+
const context = await browser.newContext({ deviceScaleFactor: 1, serviceWorkers: "block" });
|
|
34
|
+
let text = "First";
|
|
35
|
+
await context.route("https://screens.example/**", route => route.fulfill({ contentType: "text/html", body: `<main id="ready"><button style="width:100px;height:40px">${text}</button></main>` }));
|
|
36
|
+
const page = await context.newPage();
|
|
37
|
+
const target = { baseUrl: "https://screens.example", auth: { signedIn: "#ready" } };
|
|
38
|
+
await capturePage({ page }, target, { path: "/", ready: "#ready" }, 200, 100, path.join(directory, "a.png"), 5000);
|
|
39
|
+
text = "Other text";
|
|
40
|
+
await capturePage({ page }, target, { path: "/", ready: "#ready" }, 200, 100, path.join(directory, "b.png"), 5000);
|
|
41
|
+
const images = ["a", "b"].map(name => PNG.sync.read(readFileSync(path.join(directory, `${name}.layout.png`))));
|
|
42
|
+
assert.deepEqual(findRegions(...images), []);
|
|
43
|
+
} finally {
|
|
44
|
+
await browser.close();
|
|
45
|
+
rmSync(directory, { recursive: true, force: true });
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("capture includes a thumbnail whose response follows the ready selector", async () => {
|
|
50
|
+
const directory = mkdtempSync(path.join(os.tmpdir(), "qc-screens-image-"));
|
|
51
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
52
|
+
try {
|
|
53
|
+
const context = await browser.newContext({ serviceWorkers: "block" });
|
|
54
|
+
const image = new PNG({ width: 20, height: 20 });
|
|
55
|
+
for (let offset = 0; offset < image.data.length; offset += 4) image.data.set([255, 0, 0, 255], offset);
|
|
56
|
+
await context.route("https://screens.example/**", async route => {
|
|
57
|
+
if (route.request().url().endsWith("/photo.png")) {
|
|
58
|
+
await setTimeout(800);
|
|
59
|
+
await route.fulfill({ contentType: "image/png", body: PNG.sync.write(image) });
|
|
60
|
+
} else {
|
|
61
|
+
await route.fulfill({ contentType: "text/html", body: '<body style="margin:0"><main id="ready"><img src="/photo.png" width="20" height="20"></main></body>' });
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
const page = await context.newPage();
|
|
65
|
+
const file = path.join(directory, "capture.png");
|
|
66
|
+
await capturePage({ page }, { baseUrl: "https://screens.example", auth: { signedIn: "#ready" } }, { path: "/", ready: "#ready" }, 100, 100, file, 5000);
|
|
67
|
+
const capture = PNG.sync.read(readFileSync(file));
|
|
68
|
+
assert.deepEqual([...capture.data.subarray(0, 4)], [255, 0, 0, 255]);
|
|
69
|
+
} finally {
|
|
70
|
+
await browser.close();
|
|
71
|
+
rmSync(directory, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
});
|