| 1 | |
| 2 | |
| 3 | |
| 4 | import assert from 'node:assert/strict'; |
| 5 | import { execFile } from 'node:child_process'; |
| 6 | import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; |
| 7 | import { createRequire } from 'node:module'; |
| 8 | import { tmpdir } from 'node:os'; |
| 9 | import { isAbsolute, join } from 'node:path'; |
| 10 | import { request as httpRequest } from 'node:http'; |
| 11 | import { setTimeout } from 'node:timers/promises'; |
| 12 | |
| 13 | const binary = process.argv[2]; |
| 14 | assert.ok(binary && isAbsolute(binary), 'Pass an absolute newly built Cage CLI binary path.'); |
| 15 | const { chromium } = createRequire(import.meta.url)(process.env.CAGE_PLAYWRIGHT_MODULE || 'playwright'); |
| 16 | const profile = await mkdtemp(join(tmpdir(), 'cage-agent-native-browser-')); |
| 17 | const config = join(profile, 'profile', 'config.json'); |
| 18 | let pid, browser; |
| 19 | const errors = []; |
| 20 | const operations = []; |
| 21 | const claims = []; |
| 22 | const refreshTickets = new Set(); |
| 23 | let registrations = 0; |
| 24 | let prooflessClaims = 0; |
| 25 | |
| 26 | async function cli(args, input) { |
| 27 | const child = execFile(binary, ['agent', ...args, '--config', config], { timeout: 30000, encoding: 'utf8', maxBuffer: 4 << 20 }); |
| 28 | if (input !== undefined) child.stdin.end(JSON.stringify(input)); |
| 29 | const result = await new Promise((resolve, reject) => { |
| 30 | let stdout = '', stderr = ''; |
| 31 | child.stdout.on('data', chunk => { stdout += chunk; }); |
| 32 | child.stderr.on('data', chunk => { stderr += chunk; }); |
| 33 | child.on('error', reject); |
| 34 | child.on('close', code => { |
| 35 | if (code !== 0) reject(new Error(`Agent ${args[0]} failed (${code}): ${stdout} ${stderr}`)); |
| 36 | else resolve(JSON.parse(stdout)); |
| 37 | }); |
| 38 | }); |
| 39 | assert.equal(result.protocol, 1); |
| 40 | return result; |
| 41 | } |
| 42 | |
| 43 | async function entry() { |
| 44 | const record = JSON.parse(await readFile(join(profile, 'profile', 'control.json'), 'utf8')); |
| 45 | return new Promise((resolve, reject) => { |
| 46 | const body = JSON.stringify({ token: record.token }); |
| 47 | const request = httpRequest({ hostname: 'localhost', port: record.port, path: '/api/launch', method: 'POST', headers: { Origin: `http://localhost:${record.port}`, 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, response => { |
| 48 | let data = ''; |
| 49 | response.setEncoding('utf8'); |
| 50 | response.on('data', chunk => { data += chunk; }); |
| 51 | response.on('end', () => { |
| 52 | if (response.statusCode !== 200) { reject(new Error('Could not authenticate the isolated launch entry.')); return; } |
| 53 | resolve(JSON.parse(data).url); |
| 54 | }); |
| 55 | }); |
| 56 | request.on('error', reject); |
| 57 | request.setTimeout(10000, () => request.destroy(new Error('Isolated controller launch timed out.'))); |
| 58 | request.end(body); |
| 59 | }); |
| 60 | } |
| 61 | |
| 62 | async function submit(request) { |
| 63 | const reply = await cli(['request', 'POST', '/api/agent/native', '--input', '-'], { request, connection_id: 'local' }); |
| 64 | assert.equal(reply.status, 'accepted'); |
| 65 | assert.equal(reply.data.http_status, 202); |
| 66 | assert.equal(reply.data.body.status, 'pending'); |
| 67 | assert.ok(reply.data.body.id); |
| 68 | return reply.data.body.id; |
| 69 | } |
| 70 | |
| 71 | async function completed(id) { |
| 72 | const deadline = Date.now() + 20000; |
| 73 | while (Date.now() < deadline) { |
| 74 | const reply = await cli(['request', 'GET', `/api/agent/native/${id}`]); |
| 75 | const item = reply.data.body; |
| 76 | if (item.status === 'completed' || item.status === 'failed') return item; |
| 77 | assert.ok(['pending', 'running'].includes(item.status), 'Unknown native request status.'); |
| 78 | await setTimeout(150); |
| 79 | } |
| 80 | throw new Error('The compiled desktop consumer did not complete its original request.'); |
| 81 | } |
| 82 | |
| 83 | try { |
| 84 | await cli(['init']); |
| 85 | await writeFile(join(profile, 'profile', 'initialization.json'), JSON.stringify({ version: 1, completed: true }), { mode: 0o600 }); |
| 86 | await cli(['service.start']); |
| 87 | pid = JSON.parse(await readFile(join(profile, 'profile', 'control.json'), 'utf8')).pid; |
| 88 | await cli(['call', 'account.create', '--input', '-'], { username: 'Agent browser acceptance', password: 'Ephemeral-Browser-Password-123!', confirm_password: 'Ephemeral-Browser-Password-123!' }); |
| 89 | browser = await chromium.launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH }); |
| 90 | const context = await browser.newContext({ viewport: { width: 1280, height: 900 } }); |
| 91 | const page = await context.newPage(); |
| 92 | page.on('pageerror', error => errors.push(error.message)); |
| 93 | page.on('response', async response => { |
| 94 | if (new URL(response.url()).pathname === '/api/agent/native/window' && response.status() === 200) registrations++; |
| 95 | if (new URL(response.url()).pathname === '/api/agent/native' && response.request().method() === 'GET') { |
| 96 | if (!response.request().headers()['x-cage-agent-window']) prooflessClaims++; |
| 97 | try { |
| 98 | const value = await response.json(); if (value.id) claims.push(value.id); |
| 99 | } catch { } |
| 100 | } |
| 101 | }); |
| 102 | await page.exposeFunction('__cageNativeTest', async request => { |
| 103 | operations.push({ action: request.action, operation: request.operation, connection_id: request.connection_id }); |
| 104 | if (request.action === 'accountDevice') { |
| 105 | if (request.operation === 'status') return { supported: true, biometric_available: true, device_status: { automatic: 'disabled', biometric: 'disabled' } }; |
| 106 | throw new Error('请完成 Touch ID 用户验证(操作系统桥验收替身)。'); |
| 107 | } |
| 108 | if (request.action === 'refreshSession') { |
| 109 | const url = await entry(); |
| 110 | refreshTickets.add(new URL(url).hash.slice(1)); |
| 111 | return { url }; |
| 112 | } |
| 113 | if (request.action === 'appUpdate') return { phase: 'manual', currentVersion: 'acceptance-fixture', message: 'OS updater fixture; no app files are modified.' }; |
| 114 | if (request.action === 'appearance' || request.action === 'workbenchReady' || request.action === 'clipboardSyncCancel') return true; |
| 115 | throw new Error(`Unexpected OS bridge action in this smoke test: ${request.action}`); |
| 116 | }); |
| 117 | await page.addInitScript(() => { |
| 118 | window.cageNativeBridge = { postMessage: request => window.__cageNativeTest(request) }; |
| 119 | |
| 120 | sessionStorage.setItem('agent-native-browser-boots', String(Number(sessionStorage.getItem('agent-native-browser-boots') || 0) + 1)); |
| 121 | }); |
| 122 | await page.goto(await entry()); |
| 123 | await page.locator('.app').waitFor({ timeout: 20000 }); |
| 124 | await page.getByRole('complementary', { name: '项目与终端' }).waitFor(); |
| 125 | const boot = await page.evaluate(() => Number(sessionStorage.getItem('agent-native-browser-boots'))); |
| 126 | const origin = new URL(page.url()).origin; |
| 127 | const ordinaryClaim = await context.request.get(`${origin}/api/agent/native?consumer=window`, { headers: { 'X-Cage-Connection': 'local' } }); |
| 128 | assert.equal(ordinaryClaim.status(), 403, 'A browser session without native window proof could claim an OS action.'); |
| 129 | const initial = await cli(['call', 'status']); |
| 130 | assert.equal(initial.data.vm_running, false); |
| 131 | assert.equal(initial.data.ready, false); |
| 132 | |
| 133 | const preference = await submit({ action: 'clientPreferences', operation: 'set', values: { 'cage-sidebar-collapsed': 'true', 'cage-browser-tab-layout': '"vertical"', 'cage.audio': '{"muted":true,"volume":0.25}' } }); |
| 134 | const saved = await completed(preference); |
| 135 | assert.equal(saved.status, 'completed'); |
| 136 | assert.equal(saved.result.reload_required, true); |
| 137 | await page.waitForFunction(previous => Number(sessionStorage.getItem('agent-native-browser-boots')) > previous, boot); |
| 138 | await page.locator('.app.sidebar-collapsed').waitFor(); |
| 139 | assert.equal(await page.getByRole('complementary', { name: '项目与终端' }).count(), 0, 'The real workbench did not apply sidebar state after reload.'); |
| 140 | assert.deepEqual(await page.evaluate(() => ({ sidebar: localStorage.getItem('cage-sidebar-collapsed'), layout: localStorage.getItem('cage-browser-tab-layout'), audio: localStorage.getItem('cage.audio') })), { sidebar: 'true', layout: '"vertical"', audio: '{"muted":true,"volume":0.25}' }); |
| 141 | |
| 142 | const read = await completed(await submit({ action: 'clientPreferences', operation: 'get' })); |
| 143 | assert.equal(read.status, 'completed'); |
| 144 | assert.equal(read.result.values['cage-sidebar-collapsed'], 'true'); |
| 145 | assert.equal(read.result.values['cage-browser-tab-layout'], '"vertical"'); |
| 146 | |
| 147 | const biometric = await completed(await submit({ action: 'accountDevice', operation: 'enable', kind: 'biometric' })); |
| 148 | assert.equal(biometric.status, 'failed'); |
| 149 | assert.match(biometric.error, /请完成 Touch ID 用户验证/); |
| 150 | assert.equal(operations.filter(item => item.action === 'accountDevice' && item.operation === 'enable').length, 1, 'The failed biometric action was repeated.'); |
| 151 | |
| 152 | const refreshed = await completed(await submit({ action: 'refreshSession' })); |
| 153 | assert.equal(refreshed.status, 'completed'); |
| 154 | assert.deepEqual(refreshed.result, { refreshed: true }); |
| 155 | assert.ok(refreshTickets.size > 0); |
| 156 | for (const ticket of refreshTickets) assert.ok(!JSON.stringify(refreshed).includes(ticket), 'The native refresh ticket reached Agent output.'); |
| 157 | const forgedCompletion = await context.request.post(`${origin}/api/agent/native/${refreshed.id}/complete`, { headers: { Origin: origin, 'X-Cage-Connection': 'local' }, data: { result: { forged: true } } }); |
| 158 | assert.equal(forgedCompletion.status(), 403, 'A browser session without window proof could forge an OS completion.'); |
| 159 | |
| 160 | const restored = await completed(await submit({ action: 'clientPreferences', operation: 'set', values: { 'cage-sidebar-collapsed': 'false' } })); |
| 161 | assert.equal(restored.status, 'completed'); |
| 162 | await page.getByRole('complementary', { name: '项目与终端' }).waitFor(); |
| 163 | assert.equal(await page.locator('.app.sidebar-collapsed').count(), 0); |
| 164 | |
| 165 | |
| 166 | await page.getByRole('button', { name: '收起侧栏', exact: true }).click(); |
| 167 | await page.locator('.app.sidebar-collapsed').waitFor(); |
| 168 | const userChanged = await completed(await submit({ action: 'clientPreferences', operation: 'get' })); |
| 169 | assert.equal(userChanged.status, 'completed'); |
| 170 | assert.equal(userChanged.result.values['cage-sidebar-collapsed'], 'true'); |
| 171 | assert.ok(registrations >= 2, 'Document reload did not establish an independent native window proof.'); |
| 172 | assert.equal(prooflessClaims, 0, 'The real consumer omitted its window proof.'); |
| 173 | const persistedClientState = await page.evaluate(() => JSON.stringify({ local: { ...localStorage }, session: { ...sessionStorage } })); |
| 174 | for (const ticket of refreshTickets) assert.ok(!persistedClientState.includes(ticket), 'A native registration ticket was persisted by the UI.'); |
| 175 | assert.equal(claims.filter(id => id === preference).length, 1, 'A native request was claimed more than once.'); |
| 176 | assert.deepEqual(errors, []); |
| 177 | console.log('PASS: real Cage CLI + HTTP + compiled UI native queue, private window registration, ordinary-session claim/completion rejection, single claim, bidirectional sidebar preference, persistence/reload, OS verification failure, private refresh result and no VM startup. OS bridge was a fixture; no physical Touch ID or app installation was tested.'); |
| 178 | } finally { |
| 179 | await browser?.close(); |
| 180 | if (pid) { |
| 181 | try { process.kill(pid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; } |
| 182 | let retired = false; |
| 183 | for (let attempt = 0; attempt < 100; attempt++) { |
| 184 | try { await stat(join(profile, 'profile', 'control.json')); } catch (error) { if (error.code === 'ENOENT') { retired = true; break; } throw error; } |
| 185 | await setTimeout(100); |
| 186 | } |
| 187 | assert.ok(retired, 'Test controller did not retire; preserve its isolated directory.'); |
| 188 | } |
| 189 | await rm(profile, { recursive: true, force: true }); |
| 190 | } |