@raytrace-cli/cli 0.5.0 → 0.6.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.
- package/README.md +27 -1
- package/bin/raytrace.mjs +69 -2
- package/dist/dashboard/assets/{index-jyV5iYHJ.js → index-Dc3LTk8b.js} +4 -4
- package/dist/dashboard/index.html +1 -1
- package/package.json +2 -1
- package/proxy/agent-intent-schema.test.mjs +142 -0
- package/proxy/call-assessment.test.mjs +167 -0
- package/proxy/capture.mjs +11 -4
- package/proxy/capture.test.mjs +49 -0
- package/proxy/claude-code-adapter.mjs +19 -0
- package/proxy/claude-code-hook.mjs +3 -1
- package/proxy/codex-config.mjs +5 -0
- package/proxy/codex.mjs +3 -2
- package/proxy/evidence-schema.test.mjs +233 -0
- package/proxy/evidence-store.mjs +91 -22
- package/proxy/evidence-store.test.mjs +304 -0
- package/proxy/exec-narrative.test.mjs +262 -0
- package/proxy/execution-correlation.test.mjs +146 -0
- package/proxy/execution-runner.test.mjs +38 -0
- package/proxy/experiment-engine.test.mjs +93 -0
- package/proxy/explanations.test.mjs +20 -0
- package/proxy/gvisor-forwarder.test.mjs +368 -0
- package/proxy/init-evidence-db.mjs +30 -0
- package/proxy/local-token.mjs +30 -0
- package/proxy/playground-recovery.test.mjs +130 -0
- package/proxy/playground.mjs +31 -3
- package/proxy/prompt-traces.test.mjs +32 -0
- package/proxy/providers.test.mjs +76 -0
- package/proxy/proxy.integration.test.mjs +135 -0
- package/proxy/raytace-proxy.mjs +58 -18
- package/proxy/request-metrics.test.mjs +19 -0
- package/proxy/request-policy.mjs +45 -0
- package/proxy/request-policy.test.mjs +47 -0
- package/proxy/sandbox-bridge.mjs +3 -0
- package/proxy/search.test.mjs +161 -0
- package/proxy/smoke.test.mjs +93 -0
- package/proxy/step-lab.test.mjs +38 -0
- package/proxy/summaries.test.mjs +69 -0
- package/proxy/tool-metadata.test.mjs +38 -0
- package/proxy/trace-view.mjs +50 -18
- package/proxy/trace-view.test.mjs +72 -0
- package/proxy/typesafe.test.mjs +39 -0
- package/src/claude-code.mjs +38 -1
- package/src/commands.mjs +69 -25
- package/src/config.mjs +16 -7
- package/src/export.mjs +200 -0
- package/src/lima.mjs +42 -1
- package/src/local-sandbox.mjs +19 -4
- package/src/paths.mjs +8 -8
- package/src/proxy-process.mjs +26 -3
- package/src/sandbox.mjs +13 -3
- package/src/upload.mjs +198 -0
- package/worker/sandbox/claude-hook.mjs +50 -17
- package/worker/sandbox/projects.py +3 -2
- package/worker/sandbox/transcript-delivery.test.mjs +153 -0
- package/worker/sandbox/viewer.py +21 -2
package/src/proxy-process.mjs
CHANGED
|
@@ -9,10 +9,11 @@ import { createConnection } from 'node:net';
|
|
|
9
9
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
10
10
|
import { paths } from './paths.mjs';
|
|
11
11
|
import { portOf, proxyEnv, readConfig } from './config.mjs';
|
|
12
|
+
import { readToken } from '../proxy/local-token.mjs';
|
|
12
13
|
|
|
13
14
|
// The proxy API this CLI's dashboard needs (proxy/raytace-proxy.mjs PROXY_API).
|
|
14
15
|
// A proxy from an older install answers without it, or with less.
|
|
15
|
-
export const PROXY_API =
|
|
16
|
+
export const PROXY_API = 4;
|
|
16
17
|
|
|
17
18
|
/** The running proxy's API version: 0 for one from before it said. */
|
|
18
19
|
export async function proxyApi(port) {
|
|
@@ -22,13 +23,25 @@ export async function proxyApi(port) {
|
|
|
22
23
|
} catch { return 0; }
|
|
23
24
|
}
|
|
24
25
|
|
|
26
|
+
const signedIn = () => ({ authorization: `Bearer ${readToken(paths.home)}` });
|
|
27
|
+
|
|
25
28
|
export async function healthy(port) {
|
|
26
29
|
try {
|
|
27
|
-
const response = await fetch(`http://127.0.0.1:${port}/raytace/models`, { signal: AbortSignal.timeout(2000) });
|
|
30
|
+
const response = await fetch(`http://127.0.0.1:${port}/raytace/models`, { headers: signedIn(), signal: AbortSignal.timeout(2000) });
|
|
28
31
|
return response.ok;
|
|
29
32
|
} catch { return false; }
|
|
30
33
|
}
|
|
31
34
|
|
|
35
|
+
/** The dashboard's address, carrying a one-time ticket that signs this browser
|
|
36
|
+
* in. A proxy from before tickets just gets its plain address. */
|
|
37
|
+
export async function dashboardLink(port) {
|
|
38
|
+
const url = `http://127.0.0.1:${port}`;
|
|
39
|
+
try {
|
|
40
|
+
const response = await fetch(`${url}/raytace/session`, { method: 'POST', headers: signedIn(), signal: AbortSignal.timeout(2000) });
|
|
41
|
+
return response.ok ? `${url}/raytace/session?ticket=${(await response.json()).ticket}` : url;
|
|
42
|
+
} catch { return url; }
|
|
43
|
+
}
|
|
44
|
+
|
|
32
45
|
/** True when anything at all is listening on the port. */
|
|
33
46
|
export function portInUse(port) {
|
|
34
47
|
return new Promise((done) => {
|
|
@@ -42,6 +55,16 @@ function alive(pid) {
|
|
|
42
55
|
try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
|
|
43
56
|
}
|
|
44
57
|
|
|
58
|
+
/** Read-only check for running proxy pid; does not remove stale PID file. */
|
|
59
|
+
export function checkRunningPid() {
|
|
60
|
+
if (!existsSync(paths.proxyPid)) return null;
|
|
61
|
+
try {
|
|
62
|
+
const pid = Number(readFileSync(paths.proxyPid, 'utf8').trim());
|
|
63
|
+
if (Number.isInteger(pid) && pid > 0 && alive(pid)) return pid;
|
|
64
|
+
} catch { /* unreadable */ }
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
45
68
|
/** The pid this CLI started, if that process is still running. */
|
|
46
69
|
export function runningPid() {
|
|
47
70
|
if (!existsSync(paths.proxyPid)) return null;
|
|
@@ -79,7 +102,7 @@ export async function start() {
|
|
|
79
102
|
return { ...(await start()), replaced: true };
|
|
80
103
|
}
|
|
81
104
|
if (await portInUse(port)) throw new Error(`Port ${port} is in use by something that is not answering as RayTrace. Free it, or set RAYTACE_PORT in ${paths.config}.`);
|
|
82
|
-
if (!existsSync(paths.dashboard)) throw new Error(`The dashboard is missing from ${paths.dashboard}. Reinstall @raytrace/cli.`);
|
|
105
|
+
if (!existsSync(paths.dashboard)) throw new Error(`The dashboard is missing from ${paths.dashboard}. Reinstall @raytrace-cli/cli.`);
|
|
83
106
|
|
|
84
107
|
mkdirSync(paths.logs, { recursive: true });
|
|
85
108
|
mkdirSync(paths.run, { recursive: true });
|
package/src/sandbox.mjs
CHANGED
|
@@ -173,13 +173,23 @@ export async function stop(id, flags = {}) {
|
|
|
173
173
|
export async function destroy(id, flags) {
|
|
174
174
|
if (flags.local || local.isLocal(id)) return local.destroy(id, flags, { ask, interactive });
|
|
175
175
|
id = await pickId(id);
|
|
176
|
+
const me = await call('GET', '/v1/me').catch(() => ({}));
|
|
177
|
+
const plan = me.plan ?? {};
|
|
178
|
+
const paid = plan.plan && plan.plan !== 'beta';
|
|
179
|
+
let keep = Boolean(flags['keep-traces']);
|
|
176
180
|
if (!flags.yes) {
|
|
177
|
-
if (!interactive()) throw new Error('Pass --yes to destroy without a prompt.');
|
|
178
|
-
say(`This deletes ${id}: its files, and any sign-in made inside it
|
|
181
|
+
if (!interactive()) throw new Error('Pass --yes to destroy without a prompt (with --yes, traces are deleted unless --keep-traces is passed).');
|
|
182
|
+
say(`This deletes ${id}: its files, and any sign-in made inside it.`);
|
|
183
|
+
if (!paid) say('Free does not keep traces after destroy: its recorded traces are deleted too.\nTo keep them, upgrade to Pro first: https://raytracer.si/pricing');
|
|
179
184
|
if ((await ask('Type the sandbox id to confirm: ')) !== id) { say('Not destroyed.'); return; }
|
|
185
|
+
if (paid && !keep) {
|
|
186
|
+
keep = /^y(es)?$/i.test((await ask('Keep its traces until your retention date? They stay readable and count against your evidences storage. [y/N] ')).trim());
|
|
187
|
+
}
|
|
180
188
|
}
|
|
181
|
-
await call('DELETE', `/v1/sandboxes/${id}`);
|
|
189
|
+
const result = await call('DELETE', `/v1/sandboxes/${id}${keep ? '?keep_traces=1' : ''}`);
|
|
182
190
|
say(`${id} destroyed.`);
|
|
191
|
+
if (result.traces_kept) say(`Its traces are kept until ${new Date(result.traces_kept_until * 1000).toLocaleDateString()}.`);
|
|
192
|
+
else if (result.traces_deleted === false) say('Note: its traces could not be deleted; they may still show on the dashboard.');
|
|
183
193
|
}
|
|
184
194
|
|
|
185
195
|
/** An interactive terminal in the sandbox, carried over one upgraded HTTP request.
|
package/src/upload.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// `raytrace upload logs`: send a local sandbox's recorded evidences (the
|
|
2
|
+
// gzipped ~/.raytrace/evidence.db snapshot) to RayTrace cloud, where they
|
|
3
|
+
// render on app.raytracer.si like a cloud sandbox's. Uploading is always
|
|
4
|
+
// explicit: what will go is printed and confirmed first, and nothing is
|
|
5
|
+
// sent signed-out — the account flow runs first, like `sandbox create`.
|
|
6
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { createReadStream, createWriteStream, existsSync, mkdtempSync, rmSync } from 'node:fs';
|
|
9
|
+
import { open, stat } from 'node:fs/promises';
|
|
10
|
+
import { tmpdir } from 'node:os';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { createGzip } from 'node:zlib';
|
|
13
|
+
import { pipeline } from 'node:stream/promises';
|
|
14
|
+
import { accessToken, login } from './auth.mjs';
|
|
15
|
+
import { readConfig } from './config.mjs';
|
|
16
|
+
import { ask, interactive } from './prompt.mjs';
|
|
17
|
+
import { registry } from './local-sandbox.mjs';
|
|
18
|
+
import { paths } from './paths.mjs';
|
|
19
|
+
import { openEvidenceStore } from '../proxy/evidence-store.mjs';
|
|
20
|
+
|
|
21
|
+
const say = (line = '') => console.log(line);
|
|
22
|
+
const API = 'https://api.raytracer.si';
|
|
23
|
+
const CHUNK = 8 * 1024 * 1024;
|
|
24
|
+
const RETRIES = 5;
|
|
25
|
+
const mb = (bytes) => bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(2)} GB` : `${(bytes / 1024 ** 2).toFixed(1)} MB`;
|
|
26
|
+
|
|
27
|
+
/** The local sandbox an upload names: by id or name, else the only one. */
|
|
28
|
+
export function pickSandbox(ref, boxes = registry()) {
|
|
29
|
+
const ids = Object.keys(boxes);
|
|
30
|
+
if (!ids.length) throw new Error('No local sandboxes yet. Create one: raytrace sandbox create --local');
|
|
31
|
+
if (!ref) {
|
|
32
|
+
if (ids.length > 1) throw new Error(`More than one local sandbox; say which: raytrace upload logs --sandbox <name>\n${ids.map((id) => ` ${boxes[id].name} ${id}`).join('\n')}`);
|
|
33
|
+
return { id: ids[0], ...boxes[ids[0]] };
|
|
34
|
+
}
|
|
35
|
+
const byId = boxes[ref];
|
|
36
|
+
if (byId) return { id: ref, ...byId };
|
|
37
|
+
const byName = ids.find((id) => boxes[id].name === ref);
|
|
38
|
+
if (byName) return { id: byName, ...boxes[byName] };
|
|
39
|
+
throw new Error(`No local sandbox named ${ref}. Local sandboxes:\n${ids.map((id) => ` ${boxes[id].name} ${id}`).join('\n')}`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A consistent gzipped snapshot of the evidences database (never the live
|
|
43
|
+
* WAL file itself), plus what one sandbox holds in it. */
|
|
44
|
+
export function snapshotEvidences(database = paths.database) {
|
|
45
|
+
if (!existsSync(database)) throw new Error(`No evidences recorded yet (${database} does not exist). Run an agent in a local sandbox first.`);
|
|
46
|
+
const dir = mkdtempSync(join(tmpdir(), 'raytrace-upload-'));
|
|
47
|
+
const plain = join(dir, 'evidence.db');
|
|
48
|
+
const source = new DatabaseSync(database, { readOnly: true });
|
|
49
|
+
try { source.exec(`VACUUM INTO '${plain.replaceAll("'", "''")}'`); } finally { source.close(); }
|
|
50
|
+
return { dir, plain };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Trims the snapshot to one sandbox, so nothing of any other sandbox or
|
|
54
|
+
* session leaves this machine. Only ever run on the temporary copy. */
|
|
55
|
+
export function keepOnlySandbox(plain, keep) {
|
|
56
|
+
const scratch = 'upload-unattributed';
|
|
57
|
+
const db = new DatabaseSync(plain);
|
|
58
|
+
let others;
|
|
59
|
+
try {
|
|
60
|
+
others = db.prepare('SELECT external_session_id AS id FROM agent_sessions WHERE external_session_id IS NOT NULL').all()
|
|
61
|
+
.map((row) => row.id).filter((id) => !keep.includes(id));
|
|
62
|
+
// Captures no sandbox claimed: forgetSessions finds a sandbox's by project id.
|
|
63
|
+
db.prepare('UPDATE runtime_sandboxes SET project_id = ? WHERE project_id IS NULL').run(scratch);
|
|
64
|
+
others.push(...db.prepare('SELECT DISTINCT project_id AS id FROM runtime_sandboxes WHERE project_id IS NOT NULL').all()
|
|
65
|
+
.map((row) => row.id).filter((id) => !keep.includes(id) && !others.includes(id)));
|
|
66
|
+
} finally { db.close(); }
|
|
67
|
+
const store = openEvidenceStore(plain);
|
|
68
|
+
try { store.forgetSessions(others); } finally { store.close(); }
|
|
69
|
+
const compact = new DatabaseSync(plain);
|
|
70
|
+
try { compact.exec('VACUUM'); } finally { compact.close(); }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function sandboxStats(plain, sandboxId) {
|
|
74
|
+
const db = new DatabaseSync(plain, { readOnly: true });
|
|
75
|
+
try {
|
|
76
|
+
const row = db.prepare(`
|
|
77
|
+
SELECT COUNT(DISTINCT e.id) AS exchanges, COUNT(DISTINCT e.turn_id) AS turns,
|
|
78
|
+
MIN(e.started_at_ms) AS first, MAX(e.started_at_ms) AS last
|
|
79
|
+
FROM agent_sessions s LEFT JOIN agent_exchanges e ON e.session_id = s.id
|
|
80
|
+
WHERE s.external_session_id = ?`).get(sandboxId);
|
|
81
|
+
return { exchanges: row.exchanges ?? 0, turns: row.turns ?? 0, first: row.first ?? null, last: row.last ?? null };
|
|
82
|
+
} finally { db.close(); }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Sends the file in chunks. The server says where its copy ends, so an
|
|
86
|
+
* interrupted upload (this run's or an earlier one's) carries on from there. */
|
|
87
|
+
export async function sendChunks({ url, key, sandbox, name, file, size, sha256, onProgress = () => {}, send = fetch }) {
|
|
88
|
+
const handle = await open(file, 'r');
|
|
89
|
+
const buffer = Buffer.alloc(CHUNK);
|
|
90
|
+
let offset = 0;
|
|
91
|
+
let failures = 0;
|
|
92
|
+
try {
|
|
93
|
+
for (;;) {
|
|
94
|
+
const { bytesRead } = await handle.read(buffer, 0, Math.min(CHUNK, size - offset), offset);
|
|
95
|
+
const query = new URLSearchParams({ sandbox, name, sha256, size: String(size), offset: String(offset) });
|
|
96
|
+
let response;
|
|
97
|
+
try {
|
|
98
|
+
response = await send(new URL(`/v1/evidence/import?${query}`, url), {
|
|
99
|
+
method: 'POST', body: buffer.subarray(0, bytesRead),
|
|
100
|
+
headers: { authorization: `Bearer ${key}`, 'content-type': 'application/gzip' },
|
|
101
|
+
});
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (++failures > RETRIES) throw new Error(`Upload interrupted: ${error.message}. Run it again to continue where it stopped.`);
|
|
104
|
+
await new Promise((resolve) => { setTimeout(resolve, 500 * 2 ** failures); });
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const data = await response.json().catch(() => ({}));
|
|
108
|
+
if (response.status === 409 && data.code === 'upload_offset') { offset = data.offset; onProgress(offset); continue; }
|
|
109
|
+
if (response.status >= 500 && ++failures <= RETRIES) {
|
|
110
|
+
await new Promise((resolve) => { setTimeout(resolve, 500 * 2 ** failures); });
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (!response.ok) {
|
|
114
|
+
const hint = data.upgrade ? '\nUpgrade: https://raytracer.si/pricing' : '';
|
|
115
|
+
throw new Error(`${data.error || `HTTP ${response.status}`}${hint}`);
|
|
116
|
+
}
|
|
117
|
+
failures = 0;
|
|
118
|
+
if (data.complete) return data;
|
|
119
|
+
offset = data.offset;
|
|
120
|
+
onProgress(offset);
|
|
121
|
+
}
|
|
122
|
+
} finally {
|
|
123
|
+
await handle.close();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function api() {
|
|
128
|
+
const config = readConfig();
|
|
129
|
+
const url = process.env.RAYTRACE_API_URL || config.RAYTRACE_API_URL || API;
|
|
130
|
+
let key = process.env.RAYTRACE_API_KEY || config.RAYTRACE_API_KEY || await accessToken();
|
|
131
|
+
if (!key) {
|
|
132
|
+
if (!interactive()) throw new Error('Uploading evidences needs a RayTrace account. Sign in first: raytrace auth login');
|
|
133
|
+
say('Uploading evidences needs a RayTrace account — let us sign you in (or create your account) first.');
|
|
134
|
+
await login();
|
|
135
|
+
key = await accessToken();
|
|
136
|
+
if (!key) throw new Error('Not signed in. Run: raytrace auth login');
|
|
137
|
+
say();
|
|
138
|
+
}
|
|
139
|
+
return { url: new URL(url), key };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function callJson(method, path) {
|
|
143
|
+
const { url, key } = await api();
|
|
144
|
+
const response = await fetch(new URL(path, url), { method, headers: { authorization: `Bearer ${key}` } });
|
|
145
|
+
const data = await response.json().catch(() => ({}));
|
|
146
|
+
if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
|
|
147
|
+
return data;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function uploadStatus() {
|
|
151
|
+
const me = await callJson('GET', '/v1/me');
|
|
152
|
+
const plan = me.plan ?? {};
|
|
153
|
+
say(`Plan: ${plan.label ?? plan.plan ?? 'Free'}`);
|
|
154
|
+
say(`Evidences storage: ${mb(plan.storage_used_bytes ?? 0)} of ${mb(plan.storage_bytes ?? 0)} used`);
|
|
155
|
+
say(`Retention: ${plan.retention_days ? `${plan.retention_days} days` : 'kept only while a sandbox lives (Free)'}`);
|
|
156
|
+
say(`Sandboxes: up to ${plan.max_live ?? 1} live`);
|
|
157
|
+
const boxes = await callJson('GET', '/v1/sandboxes');
|
|
158
|
+
for (const box of Array.isArray(boxes) ? boxes : []) {
|
|
159
|
+
if (!box.traces_kept_until) continue;
|
|
160
|
+
const days = Math.max(0, Math.ceil((box.traces_kept_until * 1000 - Date.now()) / 86_400_000));
|
|
161
|
+
say(` ${box.name}: traces kept ${days} more day${days === 1 ? '' : 's'}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function uploadLogs({ sandbox: ref = null, yes = false, dryRun = false } = {}) {
|
|
166
|
+
const box = pickSandbox(ref);
|
|
167
|
+
const { dir, plain } = snapshotEvidences();
|
|
168
|
+
try {
|
|
169
|
+
keepOnlySandbox(plain, [box.id]);
|
|
170
|
+
const gz = `${plain}.gz`;
|
|
171
|
+
await pipeline(createReadStream(plain), createGzip({ level: 6 }), createWriteStream(gz, { mode: 0o600 }));
|
|
172
|
+
const size = (await stat(gz)).size;
|
|
173
|
+
const stats = sandboxStats(plain, box.id);
|
|
174
|
+
const day = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
175
|
+
say(`Sandbox ${box.name} (${box.id}): ${stats.turns} prompt${stats.turns === 1 ? '' : 's'}, ${stats.exchanges} model exchanges${stats.first ? `, ${day(stats.first)} to ${day(stats.last)}` : ''}.`);
|
|
176
|
+
say(`Evidences to upload: ${mb(size)} gzipped, this sandbox only. They will be readable at https://app.raytracer.si/?view=sandboxes`);
|
|
177
|
+
say('Credential-shaped fields are withheld when recorded. That covers named fields only: prompts and tool output can still contain secrets, with no guarantee.');
|
|
178
|
+
if (dryRun) { say('Dry run: nothing uploaded.'); return; }
|
|
179
|
+
if (!yes) {
|
|
180
|
+
if (!interactive()) throw new Error('Pass --yes to upload without a prompt.');
|
|
181
|
+
if (!/^y(es)?$/i.test((await ask('We are uploading evidences. Continue? [y/N] ')).trim())) { say('Not uploaded.'); return; }
|
|
182
|
+
}
|
|
183
|
+
const { url, key } = await api();
|
|
184
|
+
const sha256 = createHash('sha256');
|
|
185
|
+
await pipeline(createReadStream(gz), sha256);
|
|
186
|
+
const data = await sendChunks({
|
|
187
|
+
url, key, sandbox: box.id, name: box.name, file: gz, size, sha256: sha256.digest('hex'),
|
|
188
|
+
onProgress: (sent) => { if (process.stdout.isTTY) process.stdout.write(`\rUploading: ${mb(sent)} of ${mb(size)}`); },
|
|
189
|
+
});
|
|
190
|
+
if (process.stdout.isTTY) say();
|
|
191
|
+
say(`Uploaded: ${data.exchanges} exchanges for ${box.name}. Storage: ${mb(data.storage.used_bytes)} of ${mb(data.storage.limit_bytes)}.`);
|
|
192
|
+
if (data.kept_until) say(`Kept until ${new Date(data.kept_until * 1000).toLocaleDateString()}.`);
|
|
193
|
+
if (data.runtime?.error) say(`Note: ${data.runtime.error}; its prompts and tool calls did upload.`);
|
|
194
|
+
say('See it at https://app.raytracer.si/?view=sandboxes');
|
|
195
|
+
} finally {
|
|
196
|
+
rmSync(dir, { recursive: true, force: true });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -40,7 +40,7 @@ import { join, resolve } from 'node:path';
|
|
|
40
40
|
// The RayTrace CLI's sandbox bridge on the host, as projects.py set it on this
|
|
41
41
|
// sandbox (Lima's address for the host when unset).
|
|
42
42
|
const BROKER = `${process.env.RAYTRACE_BROKER || 'http://192.168.5.2:8799'}/raytace/ingest/claude-code`;
|
|
43
|
-
const CHUNK =
|
|
43
|
+
const CHUNK = 512 * 1024; // even worst-case JSON escaping stays under 4 MiB
|
|
44
44
|
const home = process.env.HOME || '/home/node';
|
|
45
45
|
|
|
46
46
|
let input;
|
|
@@ -100,8 +100,13 @@ if (input.hook_event_name === 'PreToolUse') {
|
|
|
100
100
|
}
|
|
101
101
|
if (input.tool_name === 'Bash' && /^[A-Za-z0-9_-]{1,128}$/.test(id ?? '') && typeof command === 'string') {
|
|
102
102
|
// An input change needs a decision with it. Only a session that already
|
|
103
|
-
// skips permission prompts gets "allow"; any other still asks as usual
|
|
104
|
-
|
|
103
|
+
// skips permission prompts gets "allow"; any other still asks as usual,
|
|
104
|
+
// unless running in headless/CI agent mode (CI, GitHub Actions, or RAYTRACE_ALLOW_ALL/RAYTRACE_HEADLESS=1).
|
|
105
|
+
const isCI = process.env.CI === 'true' || process.env.CI === '1' || Boolean(process.env.GITHUB_ACTIONS);
|
|
106
|
+
const allowAll = isCI || process.env.RAYTRACE_ALLOW_ALL === '1' || process.env.RAYTRACE_ALLOW_ALL === 'true'
|
|
107
|
+
|| process.env.RAYTRACE_HEADLESS === '1' || process.env.HEADLESS === '1';
|
|
108
|
+
const isBypass = input.permission_mode === 'bypassPermissions' || input.permission_mode === 'dontAsk';
|
|
109
|
+
const decision = (isBypass || allowAll) ? 'allow' : 'ask';
|
|
105
110
|
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision,
|
|
106
111
|
updatedInput: { ...input.tool_input, command: `export RAYTRACE_CALL_ID=${id}\n${command}` } } }));
|
|
107
112
|
}
|
|
@@ -289,7 +294,11 @@ try {
|
|
|
289
294
|
.map((line) => { try { return JSON.parse(line); } catch { return null; } }).filter(Boolean);
|
|
290
295
|
let delivered = events.length === 0;
|
|
291
296
|
|
|
292
|
-
|
|
297
|
+
// Drain the bytes present at entry, not an endlessly growing transcript.
|
|
298
|
+
// Successful fragments do not consume the bounded conflict retry budget.
|
|
299
|
+
let endOffset = null;
|
|
300
|
+
let conflicts = 0;
|
|
301
|
+
while (conflicts < 8) {
|
|
293
302
|
// A new session's first prompt fires before Claude Code has written its
|
|
294
303
|
// transcript: send the snapshot anyway, with no lines yet.
|
|
295
304
|
let fd = null;
|
|
@@ -297,28 +306,52 @@ try {
|
|
|
297
306
|
let text = '';
|
|
298
307
|
let more = false;
|
|
299
308
|
if (fd !== null) try {
|
|
300
|
-
|
|
309
|
+
if (endOffset === null) endOffset = fstatSync(fd).size;
|
|
310
|
+
const available = endOffset - offset;
|
|
301
311
|
if (available > 0) {
|
|
302
312
|
const buffer = Buffer.alloc(Math.min(available, CHUNK));
|
|
303
|
-
readSync(fd, buffer, 0, buffer.length, offset);
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
313
|
+
let end = readSync(fd, buffer, 0, buffer.length, offset);
|
|
314
|
+
// A fragment can split a JSON line, but never a UTF-8 codepoint:
|
|
315
|
+
// decoding half a character would change its bytes and the offset.
|
|
316
|
+
let lead = end - 1;
|
|
317
|
+
while (lead >= 0 && (buffer[lead] & 0xc0) === 0x80) lead -= 1;
|
|
318
|
+
if (lead >= 0) {
|
|
319
|
+
const byte = buffer[lead];
|
|
320
|
+
const width = byte < 0x80 ? 1 : byte < 0xe0 ? 2 : byte < 0xf0 ? 3 : 4;
|
|
321
|
+
if (end - lead < width) end = lead;
|
|
322
|
+
}
|
|
323
|
+
text = buffer.subarray(0, end).toString('utf8');
|
|
324
|
+
more = offset + end < endOffset;
|
|
307
325
|
}
|
|
308
326
|
} finally { closeSync(fd); }
|
|
309
|
-
const
|
|
310
|
-
method: 'POST',
|
|
311
|
-
headers: { 'content-type': 'application/json', 'x-raytace-sandbox-token': token },
|
|
312
|
-
body: JSON.stringify({ session_id: session, hook_event_name: input.hook_event_name, offset, text, ...(snap ? { snapshot: snap } : {}),
|
|
327
|
+
const envelope = () => JSON.stringify({ session_id: session, hook_event_name: input.hook_event_name, offset, text, more, ...(snap ? { snapshot: snap } : {}),
|
|
313
328
|
...(delivered ? {} : { events }),
|
|
314
329
|
// A Playground fork's sandbox carries its own id (projects.py): RayTrace
|
|
315
330
|
// files the fork's steps under it, not under the project it forks.
|
|
316
|
-
...(/^rtf-[a-f0-9]{32}$/.test(process.env.RAYTRACE_SESSION ?? '') ? { fork: process.env.RAYTRACE_SESSION } : {}) })
|
|
331
|
+
...(/^rtf-[a-f0-9]{32}$/.test(process.env.RAYTRACE_SESSION ?? '') ? { fork: process.env.RAYTRACE_SESSION } : {}) });
|
|
332
|
+
let requestBody = envelope();
|
|
333
|
+
while (Buffer.byteLength(requestBody) > 4 * 1024 * 1024 && text) {
|
|
334
|
+
const bytes = Buffer.from(text);
|
|
335
|
+
let end = Math.floor(bytes.length / 2);
|
|
336
|
+
// Cut before any incomplete codepoint at the new boundary.
|
|
337
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80) end -= 1;
|
|
338
|
+
text = bytes.subarray(0, end).toString('utf8');
|
|
339
|
+
more = true;
|
|
340
|
+
requestBody = envelope();
|
|
341
|
+
}
|
|
342
|
+
if (Buffer.byteLength(requestBody) > 4 * 1024 * 1024) {
|
|
343
|
+
console.error('RayTrace: transcript metadata exceeds the request limit; pending data was retained.');
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
const response = await fetch(BROKER, {
|
|
347
|
+
method: 'POST',
|
|
348
|
+
headers: { 'content-type': 'application/json', 'x-raytace-sandbox-token': token },
|
|
349
|
+
body: requestBody,
|
|
317
350
|
signal: AbortSignal.timeout(4000),
|
|
318
351
|
});
|
|
319
352
|
const body = await response.json().catch(() => ({}));
|
|
320
|
-
if (response.status === 409 && Number.isInteger(body.size)) { offset = body.size; continue; }
|
|
321
|
-
if (!response.ok ||
|
|
353
|
+
if (response.status === 409 && Number.isInteger(body.size) && body.size >= 0) { offset = body.size; conflicts += 1; continue; }
|
|
354
|
+
if (!response.ok || body.size !== offset + Buffer.byteLength(text)) break;
|
|
322
355
|
if (!delivered) {
|
|
323
356
|
delivered = true;
|
|
324
357
|
try { writeFileSync(queuedFile, readFileSync(queuedFile).subarray(queued.length)); } catch { /* already gone */ }
|
|
@@ -326,6 +359,6 @@ try {
|
|
|
326
359
|
offset = body.size;
|
|
327
360
|
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
328
361
|
writeFileSync(stateFile, String(offset));
|
|
329
|
-
if (!more) break;
|
|
362
|
+
if (!more || !text) break; // an incomplete UTF-8 tail waits for the next hook
|
|
330
363
|
}
|
|
331
364
|
} catch { /* RayTrace or the manager not running: stay silent */ }
|
|
@@ -645,8 +645,9 @@ def main():
|
|
|
645
645
|
if opts.action == 'start':
|
|
646
646
|
return
|
|
647
647
|
# Exiting this shell or Codex never stops/removes the persistent container.
|
|
648
|
-
run('docker', 'exec', '-it', opts.id, '/bin/bash', '-c',
|
|
649
|
-
'if [ -f /home/node/.raytace-codex/config.toml ]; then export CODEX_HOME=/home/node/.raytace-codex; fi; exec /bin/bash')
|
|
648
|
+
proc = subprocess.run(['docker', 'exec', '-it', opts.id, '/bin/bash', '-c',
|
|
649
|
+
'if [ -f /home/node/.raytace-codex/config.toml ]; then export CODEX_HOME=/home/node/.raytace-codex; fi; exec /bin/bash'], check=False)
|
|
650
|
+
sys.exit(proc.returncode)
|
|
650
651
|
elif opts.action == 'stop':
|
|
651
652
|
run('docker', 'stop', '-t', '10', opts.id)
|
|
652
653
|
elif opts.action == 'delete':
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from 'node:fs';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
|
+
import * as fsPromises from 'node:fs/promises';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
|
|
10
|
+
const root = resolve(fileURLToPath(new URL('../../', import.meta.url)));
|
|
11
|
+
const session = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
|
|
12
|
+
const setup = (repo) => {
|
|
13
|
+
const dir = mkdtempSync(join(tmpdir(), 'raytrace-delivery-'));
|
|
14
|
+
const home = join(dir, 'isolated-home');
|
|
15
|
+
const state = join(dir, 'offsets');
|
|
16
|
+
const transcript = join(home, '.claude', 'projects', 'test', `${session}.jsonl`);
|
|
17
|
+
mkdirSync(resolve(transcript, '..'), {recursive:true});
|
|
18
|
+
mkdirSync(join(home,'.raytace'), {recursive:true});
|
|
19
|
+
mkdirSync(join(home,'.raytace-codex'), {recursive:true});
|
|
20
|
+
writeFileSync(join(home,'.raytace','sandbox-token'), 'synthetic-token');
|
|
21
|
+
writeFileSync(join(home,'.raytace-codex','config.toml'), '"x-raytace-sandbox-token" = "synthetic-token"');
|
|
22
|
+
const hookPath = fileURLToPath(new URL('./claude-hook.mjs', import.meta.url));
|
|
23
|
+
const source = readFileSync(hookPath,'utf8')
|
|
24
|
+
.replace("const home = process.env.HOME || '/home/node';", `const home = ${JSON.stringify(home)};`)
|
|
25
|
+
.replace("const STATE_DIR = '/tmp/raytace-claude';", `const STATE_DIR = ${JSON.stringify(state)};`);
|
|
26
|
+
const hook = join(dir,'hook.mjs'); writeFileSync(hook,source);
|
|
27
|
+
const preloader = join(dir,'fake-transport.mjs');
|
|
28
|
+
const adapter = pathToFileURL(resolve(root,'proxy/claude-code-adapter.mjs')).href;
|
|
29
|
+
writeFileSync(preloader, `
|
|
30
|
+
import {existsSync,readFileSync,writeFileSync,appendFileSync} from 'node:fs';
|
|
31
|
+
import {join} from 'node:path';
|
|
32
|
+
import {parseTranscript,exchangesFromTranscript} from ${JSON.stringify(adapter)};
|
|
33
|
+
const dir=${JSON.stringify(dir)};
|
|
34
|
+
globalThis.fetch=async (url,init)=>{
|
|
35
|
+
const note=JSON.parse(init.body), calls=join(dir,'calls.jsonl'), server=join(dir,'received.txt');
|
|
36
|
+
appendFileSync(calls, JSON.stringify({note,bytes:Buffer.byteLength(init.body)})+'\\n');
|
|
37
|
+
const mode=JSON.parse(readFileSync(join(dir,'mode.json'),'utf8'));
|
|
38
|
+
if(mode.grow){appendFileSync(${JSON.stringify(transcript)},mode.grow);writeFileSync(join(dir,'mode.json'),'{}');}
|
|
39
|
+
let bytes=existsSync(server)?readFileSync(server):Buffer.alloc(0);
|
|
40
|
+
const answer=(status,body)=>({status,ok:status===200,json:async()=>body});
|
|
41
|
+
if(mode.fail) return answer(503,{});
|
|
42
|
+
if(mode.conflict) return answer(409,{size:bytes.length});
|
|
43
|
+
if(note.offset!==bytes.length) return answer(409,{size:bytes.length});
|
|
44
|
+
bytes=Buffer.concat([bytes,Buffer.from(note.text)]);writeFileSync(server,bytes);
|
|
45
|
+
if(mode.loseAck){writeFileSync(join(dir,'mode.json'),'{}');throw new Error('synthetic lost acknowledgement');}
|
|
46
|
+
const lines=parseTranscript(bytes.toString('utf8'));
|
|
47
|
+
const rows=exchangesFromTranscript(lines,{final:note.hook_event_name==='Stop'&¬e.more!==true});
|
|
48
|
+
for(const row of rows) appendFileSync(join(dir,'rows.jsonl'),JSON.stringify(row)+'\\n');
|
|
49
|
+
return answer(200,{size:bytes.length});
|
|
50
|
+
};`);
|
|
51
|
+
writeFileSync(join(dir,'mode.json'),'{}');
|
|
52
|
+
return {dir,state,transcript,run() {
|
|
53
|
+
const result=spawnSync(process.execPath,['--import',preloader,hook],{
|
|
54
|
+
input:JSON.stringify({session_id:session,transcript_path:transcript,hook_event_name:'Stop'}),
|
|
55
|
+
encoding:'utf8',timeout:15000,maxBuffer:1024*1024,
|
|
56
|
+
});
|
|
57
|
+
assert.equal(result.error,undefined);assert.equal(result.status,0,result.stderr);
|
|
58
|
+
}, calls(){return readFileSync(join(dir,'calls.jsonl'),'utf8').trim().split('\n').map(JSON.parse);},
|
|
59
|
+
mode(value){writeFileSync(join(dir,'mode.json'),JSON.stringify(value));},
|
|
60
|
+
offset(){return existsSync(join(state,`${session}.offset`))?Number(readFileSync(join(state,`${session}.offset`),'utf8')):0;},
|
|
61
|
+
received(){return existsSync(join(dir,'received.txt'))?readFileSync(join(dir,'received.txt'),'utf8'):'';},
|
|
62
|
+
close(){rmSync(dir,{recursive:true,force:true});}};
|
|
63
|
+
};
|
|
64
|
+
for (const repo of ['local']) {
|
|
65
|
+
test(`${repo}: actual hook drains escaped oversized lines across UTF-8 boundaries and finalizes only once`,()=>{
|
|
66
|
+
const fixture=setup(repo);
|
|
67
|
+
try {
|
|
68
|
+
const line=(type,message,extra={})=>JSON.stringify({type,sessionId:session,timestamp:'2026-10-28T00:00:00Z',message,...extra})+'\n';
|
|
69
|
+
const raw=line('user',{content:'synthetic prompt'})
|
|
70
|
+
+line('assistant',{id:'message',content:[{type:'text',text:'first part'}]},{requestId:'request'})
|
|
71
|
+
+line('user',{content:[{type:'tool_result',tool_use_id:'call',content:'\\'.repeat(2_500_000)+'😀'.repeat(300_000)}]})
|
|
72
|
+
+line('assistant',{id:'message',content:[{type:'text',text:'last part'}]},{requestId:'request'});
|
|
73
|
+
writeFileSync(fixture.transcript,raw);fixture.run();
|
|
74
|
+
assert.equal(fixture.received(),raw);assert.equal(fixture.offset(),Buffer.byteLength(raw));
|
|
75
|
+
const calls=fixture.calls();assert.ok(calls.length>8);
|
|
76
|
+
assert.ok(calls.every(c=>c.bytes<=4*1024*1024));
|
|
77
|
+
assert.ok(calls.slice(0,-1).every(c=>c.note.more===true));assert.equal(calls.at(-1).note.more,false);
|
|
78
|
+
const rows=readFileSync(join(fixture.dir,'rows.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
|
|
79
|
+
assert.equal(rows.length,1);assert.equal(rows[0].response.payload.output.length,2);
|
|
80
|
+
} finally {fixture.close();}
|
|
81
|
+
});
|
|
82
|
+
test(`${repo}: failed send retains offset and retry delivers exact bytes`,()=>{
|
|
83
|
+
const fixture=setup(repo);try {
|
|
84
|
+
const raw=JSON.stringify({type:'user',message:{content:'hello 😀'}})+'\n';
|
|
85
|
+
writeFileSync(fixture.transcript,raw);fixture.mode({fail:true});fixture.run();
|
|
86
|
+
assert.equal(fixture.offset(),0);assert.equal(fixture.received(),'');
|
|
87
|
+
fixture.mode({});fixture.run();assert.equal(fixture.received(),raw);assert.equal(fixture.offset(),Buffer.byteLength(raw));
|
|
88
|
+
} finally {fixture.close();}
|
|
89
|
+
});
|
|
90
|
+
test(`${repo}: lost acknowledgement resumes with 409 without duplicating bytes`,()=>{
|
|
91
|
+
const fixture=setup(repo);try {
|
|
92
|
+
const raw=JSON.stringify({type:'user',message:{content:'hello'}})+'\n';
|
|
93
|
+
writeFileSync(fixture.transcript,raw);fixture.mode({loseAck:true});fixture.run();
|
|
94
|
+
assert.equal(fixture.offset(),0);assert.equal(fixture.received(),raw);
|
|
95
|
+
fixture.run();assert.equal(fixture.received(),raw);assert.equal(fixture.offset(),Buffer.byteLength(raw));
|
|
96
|
+
} finally {fixture.close();}
|
|
97
|
+
});
|
|
98
|
+
test(`${repo}: drain stops at entry size and a later hook sends concurrently appended bytes`,()=>{
|
|
99
|
+
const fixture=setup(repo);try {
|
|
100
|
+
const raw=JSON.stringify({type:'user',message:{content:'initial'}})+'\n';
|
|
101
|
+
const added=JSON.stringify({type:'user',message:{content:'appended during send'}})+'\n';
|
|
102
|
+
writeFileSync(fixture.transcript,raw);fixture.mode({grow:added});fixture.run();
|
|
103
|
+
assert.equal(fixture.received(),raw);assert.equal(fixture.offset(),Buffer.byteLength(raw));
|
|
104
|
+
fixture.run();assert.equal(fixture.received(),raw+added);
|
|
105
|
+
} finally {fixture.close();}
|
|
106
|
+
});
|
|
107
|
+
test(`${repo}: repeated conflicts have a bounded retry budget`,()=>{
|
|
108
|
+
const fixture=setup(repo);try {
|
|
109
|
+
writeFileSync(fixture.transcript,'{}\n');fixture.mode({conflict:true});fixture.run();
|
|
110
|
+
assert.equal(fixture.calls().length,8);assert.equal(fixture.offset(),0);
|
|
111
|
+
} finally {fixture.close();}
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const sessionPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
116
|
+
for (const repo of ['local']) {
|
|
117
|
+
test(`${repo}: real receiver accepts partial lines, enforces byte offsets and validates fragment flags`,async()=>{
|
|
118
|
+
const dir=mkdtempSync(join(tmpdir(), 'raytrace-receiver-'));
|
|
119
|
+
try {
|
|
120
|
+
const source=readFileSync(resolve(root,'proxy/raytace-proxy.mjs'),'utf8');
|
|
121
|
+
const start=source.indexOf('async function appendSandboxTranscript(');
|
|
122
|
+
const end=source.indexOf('\n/**',start);
|
|
123
|
+
const fn=new Function('join','sandboxTranscripts','CLAUDE_SESSION_ID','serially','mkdir','stat','appendFile',
|
|
124
|
+
`${source.slice(start,end)};return appendSandboxTranscript;`)(join,dir,sessionPattern,(_path,job)=>job(),fsPromises.mkdir,fsPromises.stat,fsPromises.appendFile);
|
|
125
|
+
const initial={session_id:session,offset:0,text:'{"value":"😀',more:true};
|
|
126
|
+
const first=await fn('rtp-synthetic',initial);assert.equal(first.status,200);
|
|
127
|
+
assert.equal(first.body.size,Buffer.byteLength(initial.text));
|
|
128
|
+
const duplicate=await fn('rtp-synthetic',initial);assert.equal(duplicate.status,409);assert.equal(duplicate.body.size,first.body.size);
|
|
129
|
+
const tail={session_id:session,offset:first.body.size,text:'"}\n',more:false};
|
|
130
|
+
const final=await fn('rtp-synthetic',tail);assert.equal(final.status,200);
|
|
131
|
+
assert.equal(readFileSync(join(dir,'rtp-synthetic',`${session}.jsonl`),'utf8'),initial.text+tail.text);
|
|
132
|
+
assert.equal((await fn('rtp-synthetic',{...tail,offset:final.body.size,more:'false'})).status,400);
|
|
133
|
+
assert.equal((await fn('rtp-synthetic',{...tail,offset:-1})).status,400);
|
|
134
|
+
assert.equal((await fn('rtp-synthetic',{...tail,session_id:'../../bad'})).status,400);
|
|
135
|
+
// Existing whole-line senders remain accepted without the new flag.
|
|
136
|
+
assert.equal((await fn('rtp-synthetic',{session_id:session,offset:final.body.size,text:'{}\n'})).status,200);
|
|
137
|
+
} finally {rmSync(dir,{recursive:true,force:true});}
|
|
138
|
+
});
|
|
139
|
+
test(`${repo}: actual serialized envelope is bounded and queued metadata is retained`,()=>{
|
|
140
|
+
const fixture=setup(repo);try {
|
|
141
|
+
mkdirSync(fixture.state,{recursive:true});
|
|
142
|
+
const event={id:'synthetic-large-event',detail:'x'.repeat(3_700_000)};
|
|
143
|
+
const queue=join(fixture.state,`${session}.events.jsonl`);
|
|
144
|
+
writeFileSync(queue,JSON.stringify(event)+'\n');
|
|
145
|
+
const raw=JSON.stringify({type:'user',message:{content:'\\'.repeat(400_000)}})+'\n';
|
|
146
|
+
writeFileSync(fixture.transcript,raw);fixture.run();
|
|
147
|
+
assert.equal(fixture.received(),raw);
|
|
148
|
+
const calls=fixture.calls();assert.ok(calls.length>1);assert.ok(calls.every(c=>c.bytes<=4*1024*1024));
|
|
149
|
+
assert.deepEqual(calls[0].note.events,[event]);assert.equal(readFileSync(queue,'utf8'),'');
|
|
150
|
+
} finally {fixture.close();}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
package/worker/sandbox/viewer.py
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
"""Loopback-only, read-only evidence viewer, forwarded by Lima to the Mac.
|
|
1
|
+
"""Loopback-only, read-only evidence viewer, forwarded by Lima to the Mac.
|
|
2
|
+
|
|
3
|
+
A forwarded port is open to every account on the Mac, so each request carries
|
|
4
|
+
the token the CLI writes here (src/local-sandbox.mjs). No token, no evidence.
|
|
5
|
+
"""
|
|
6
|
+
import hmac
|
|
2
7
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
3
8
|
import json
|
|
4
9
|
from pathlib import Path
|
|
@@ -6,6 +11,17 @@ import sqlite3
|
|
|
6
11
|
import time
|
|
7
12
|
from urllib.parse import urlparse, parse_qs
|
|
8
13
|
|
|
14
|
+
TOKEN = Path('/etc/raytace/viewer-token')
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def allowed(header):
|
|
18
|
+
try:
|
|
19
|
+
token = TOKEN.read_text().strip()
|
|
20
|
+
except OSError:
|
|
21
|
+
return False
|
|
22
|
+
return bool(token) and hmac.compare_digest(header.encode(), f'Bearer {token}'.encode())
|
|
23
|
+
|
|
24
|
+
|
|
9
25
|
def event_page(db, query):
|
|
10
26
|
container = query.get('container', [''])[0]
|
|
11
27
|
before = int(query.get('before', ['0'])[0])
|
|
@@ -74,7 +90,7 @@ PAGE = '''<!doctype html><meta charset="utf-8"><title>RayTrace runtime evidence<
|
|
|
74
90
|
<table><thead><tr><th>Event</th><th>PID / parent</th><th>Executable / arguments / result</th></tr></thead><tbody id="events"></tbody></table>
|
|
75
91
|
<script>
|
|
76
92
|
const select=document.getElementById('jobs');
|
|
77
|
-
async function refresh(){try{const response=await fetch('
|
|
93
|
+
async function refresh(){try{const response=await fetch('events');if(!response.ok)throw Error('Collector unavailable');const data=await response.json();
|
|
78
94
|
const chosen=select.value;select.replaceChildren(new Option('All sandboxes and collector health',''));for(const id of data.containers)select.add(new Option(id.slice(0,16),id));select.value=chosen;
|
|
79
95
|
const rows=data.events.filter(e=>!select.value||e.container_id===select.value);
|
|
80
96
|
document.getElementById('status').textContent='Latest '+rows.length+' events (up to 500). '+data.gaps+' recorded collection errors/gaps.';
|
|
@@ -89,6 +105,9 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
89
105
|
if self.headers.get('Host', '').split(':')[0] not in ('localhost', '127.0.0.1'):
|
|
90
106
|
self.send_error(403)
|
|
91
107
|
return
|
|
108
|
+
if not allowed(self.headers.get('Authorization', '')):
|
|
109
|
+
self.send_error(401)
|
|
110
|
+
return
|
|
92
111
|
if self.path == '/':
|
|
93
112
|
body, mime = PAGE.encode(), 'text/html; charset=utf-8'
|
|
94
113
|
elif urlparse(self.path).path == '/time':
|