| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | import { mkdtemp, mkdir, readFile, rm, stat } from 'node:fs/promises'; |
| 4 | import { tmpdir } from 'node:os'; |
| 5 | import { dirname, isAbsolute, join, resolve } from 'node:path'; |
| 6 | import { randomBytes } from 'node:crypto'; |
| 7 | import { spawn } from 'node:child_process'; |
| 8 | |
| 9 | const [nativeArgument, outputArgument] = process.argv.slice(2); |
| 10 | if (!nativeArgument || !outputArgument || process.argv.length !== 4) { |
| 11 | console.error('Usage: test-smoke.mjs /path/to/cage-desktop /absolute/report.json'); |
| 12 | process.exit(2); |
| 13 | } |
| 14 | const native = resolve(nativeArgument); |
| 15 | const backend = join(dirname(native), 'cage'); |
| 16 | const output = resolve(outputArgument); |
| 17 | const root = await mkdtemp(join(tmpdir(), 'cage-linux-smoke-')); |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | const env = { ...process.env, CLAUDE_CAGE_CONFIG: join(root, 'profile', 'config.json'), CAGE_DESKTOP_OWNER_PID: String(process.pid) }; |
| 23 | let clean = false; |
| 24 | let result = 1; |
| 25 | |
| 26 | function execute(executable, args, timeout = 190000) { |
| 27 | return new Promise((resolvePromise, reject) => { |
| 28 | const child = spawn(executable, args, { env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] }); |
| 29 | let stdout = '', stderr = '', overflow = false; |
| 30 | const stopGroup = () => { |
| 31 | try { process.kill(-child.pid, 'SIGKILL'); } catch { } |
| 32 | }; |
| 33 | const timer = setTimeout(stopGroup, timeout); |
| 34 | child.stdout.on('data', data => { |
| 35 | stdout += data; |
| 36 | if (stdout.length > 65536) { overflow = true; stopGroup(); } |
| 37 | }); |
| 38 | child.stderr.on('data', data => { |
| 39 | stderr = (stderr + data).slice(-8192); |
| 40 | if (executable === native && args[0] === '--smoke-test') process.stderr.write(data); |
| 41 | }); |
| 42 | child.on('error', error => { clearTimeout(timer); reject(error); }); |
| 43 | |
| 44 | |
| 45 | |
| 46 | child.on('exit', (code, signal) => { if (code !== 0 || signal) stopGroup(); }); |
| 47 | child.on('close', (code, signal) => { |
| 48 | clearTimeout(timer); |
| 49 | if (overflow) reject(new Error('Backend response exceeded the output limit.')); |
| 50 | else resolvePromise({ code, signal, stdout, stderr }); |
| 51 | }); |
| 52 | }); |
| 53 | } |
| 54 | function parseBackend(run) { |
| 55 | |
| 56 | let data; |
| 57 | try { data = JSON.parse(run.stdout); } catch { throw new Error('Backend returned invalid JSON.'); } |
| 58 | if (run.code !== 0) throw new Error('Backend operation failed; inspect the isolated control.log.'); |
| 59 | return data; |
| 60 | } |
| 61 | |
| 62 | try { |
| 63 | if (!isAbsolute(output)) throw new Error('Report path must be absolute.'); |
| 64 | await mkdir(join(root, 'profile'), { mode: 0o700 }); |
| 65 | await mkdir(dirname(output), { recursive: true }); |
| 66 | await rm(output, { force: true }); |
| 67 | await rm(output + '.png', { force: true }); |
| 68 | const policy = await execute(native, ['--self-test'], 30000); |
| 69 | if (policy.code !== 0) throw new Error('Native origin policy tests failed.'); |
| 70 | const entry = parseBackend(await execute(backend, ['desktop', '--json'])); |
| 71 | if (entry.status !== 'ready') throw new Error('Isolated backend was not ready.'); |
| 72 | const url = new URL(entry.url); |
| 73 | if (url.protocol !== 'http:' || url.hostname !== 'localhost' || !url.hash || url.username || url.password) |
| 74 | throw new Error('Backend returned an invalid loopback entry.'); |
| 75 | const authenticate = await fetch(url.origin + '/api/session', { |
| 76 | method: 'POST', redirect: 'error', |
| 77 | headers: { 'Origin': url.origin, 'Content-Type': 'application/json' }, |
| 78 | body: JSON.stringify({ token: url.hash.slice(1) }), |
| 79 | }); |
| 80 | if (!authenticate.ok) throw new Error('Session authentication failed.'); |
| 81 | const cookie = authenticate.headers.get('set-cookie')?.split(';')[0]; |
| 82 | if (!cookie) throw new Error('Authenticated response did not create a session cookie.'); |
| 83 | async function api(path, body, generation) { |
| 84 | const headers = { Origin: url.origin, Cookie: cookie }; |
| 85 | if (body !== undefined) headers['Content-Type'] = 'application/json'; |
| 86 | if (generation) headers['X-Cage-Connection'] = generation; |
| 87 | const response = await fetch(url.origin + '/api/' + path, { |
| 88 | method: body === undefined ? 'GET' : 'POST', redirect: 'error', headers, |
| 89 | body: body === undefined ? undefined : JSON.stringify(body), |
| 90 | }); |
| 91 | if (!response.ok) throw new Error(`Isolated smoke API ${path} failed with ${response.status}.`); |
| 92 | return response.json(); |
| 93 | } |
| 94 | let current = await api('client/context'); |
| 95 | if (!current.desktop_gateway || current.mode !== 'none') throw new Error('A fresh full Cage must start at the environment picker.'); |
| 96 | const idle = await api('client/local-status'); |
| 97 | if (!idle.known || idle.service_running || idle.running) throw new Error('The desktop picker started a local workload.'); |
| 98 | const original = current.connection_id; |
| 99 | const pending = await api('client/candidate', { connection_id: original, mode: 'local' }); |
| 100 | const deadline = Date.now() + 30000; |
| 101 | while (true) { |
| 102 | current = await api('client/context'); |
| 103 | if (current.connection_id !== original || current.candidate?.id !== pending.id) throw new Error('The local candidate lost its original desktop view.'); |
| 104 | if (current.candidate.connection.state === 'connected') break; |
| 105 | if (current.candidate.connection.state === 'failed' || Date.now() > deadline) throw new Error('Could not open the local test workbench.'); |
| 106 | await new Promise((r) => setTimeout(r, 100)); |
| 107 | } |
| 108 | current = await api('client/commit', { connection_id: original, candidate_id: pending.id, local_action: 'auto' }); |
| 109 | if (current.mode !== 'local' || current.connection_id === original) throw new Error('Local workbench generation was not selected.'); |
| 110 | const password = randomBytes(24).toString('base64url'); |
| 111 | const account = await api('account/create', { username: 'Linux Smoke', password, confirm_password: password }, current.connection_id); |
| 112 | if (!account.unlocked) throw new Error('Could not prepare the isolated unlocked test account.'); |
| 113 | env.CAGE_SMOKE_STORAGE_MARKER = randomBytes(24).toString('hex'); |
| 114 | for (const phase of ['seed', 'verify']) { |
| 115 | env.CAGE_SMOKE_STORAGE_PHASE = phase; |
| 116 | await rm(output, { force: true }); |
| 117 | const nativeRun = await execute(native, ['--smoke-test', output], 150000); |
| 118 | if (nativeRun.code !== 0) throw new Error(`Native WebKit workbench ${phase} test failed.`); |
| 119 | const pass = JSON.parse(await readFile(output, 'utf8')); |
| 120 | if (pass.success !== true || pass.storageMarkerMatched !== true) throw new Error(`Native storage ${phase} evidence is incomplete.`); |
| 121 | } |
| 122 | const evidence = JSON.parse(await readFile(output, 'utf8')); |
| 123 | for (const key of ['success', 'nativeBridgeReady', 'authenticated', 'accountUnlocked', 'workbenchRendered', 'workbenchReadyAcknowledged', 'statusReceived', 'settingsReceived', 'unauthenticatedBridgeDenied', 'localStoragePersisted']) { |
| 124 | if (evidence[key] !== true) throw new Error(`Native smoke report lacks ${key}.`); |
| 125 | } |
| 126 | if ((await stat(output + '.png')).size < 1024) throw new Error('Native screenshot is missing or empty.'); |
| 127 | for (const directory of ['webkit', 'webkit/data', 'webkit/cache']) { |
| 128 | if ((await stat(join(root, 'profile', directory))).mode & 0o077) throw new Error('WebKit profile storage is not private.'); |
| 129 | } |
| 130 | result = 0; |
| 131 | console.log(JSON.stringify({ success: true, report: output, screenshot: output + '.png', version: evidence.version })); |
| 132 | } catch (error) { |
| 133 | console.error(error.message); |
| 134 | } finally { |
| 135 | try { |
| 136 | const cleanupRun = await execute(backend, ['prepare-update', '--json']); |
| 137 | if (cleanupRun.code !== 0) { |
| 138 | |
| 139 | |
| 140 | let message = ''; |
| 141 | try { |
| 142 | const response = JSON.parse(cleanupRun.stdout); |
| 143 | if (typeof response.message === 'string') message = response.message.slice(0, 500); |
| 144 | } catch { } |
| 145 | console.error(`Cleanup prepare-update failed (exit ${cleanupRun.code}, signal ${cleanupRun.signal || 'none'}): ${message}`); |
| 146 | } |
| 147 | const stopped = parseBackend(cleanupRun); |
| 148 | clean = stopped.status === 'prepared'; |
| 149 | if (!clean) console.error(`Cleanup prepare-update returned ${stopped.status || 'unknown status'}.`); |
| 150 | } catch (error) { |
| 151 | console.error(`Cleanup could not confirm controller exit: ${error.message}`); |
| 152 | |
| 153 | } |
| 154 | if (clean) await rm(root, { recursive: true, force: true }); |
| 155 | else { console.error(`Cleanup incomplete; isolated profile retained at ${root}`); result = 1; } |
| 156 | } |
| 157 | process.exitCode = result; |