| 1 | import assert from "node:assert/strict"; |
| 2 | import test from "node:test"; |
| 3 | import { agentClientPreferences, clientPreferences, createAgentNativeConsumer, executeAgentNative } from "./agent-native.js"; |
| 4 | |
| 5 | const context = { mode: "remote", connection_id: "generation-a", instance_id: "server-one" }; |
| 6 | function storage() { |
| 7 | const values = new Map(); |
| 8 | return { values, getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key) }; |
| 9 | } |
| 10 | const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); }; |
| 11 | function clock() { |
| 12 | const scheduled = []; |
| 13 | return { scheduled, schedule: callback => { scheduled.push(callback); return callback; }, cancel: callback => { const index = scheduled.indexOf(callback); if (index >= 0) scheduled.splice(index, 1); }, tick: async () => { scheduled.shift()?.(); await flush(); } }; |
| 14 | } |
| 15 | function consumerForTest(dependencies) { |
| 16 | return createAgentNativeConsumer({ |
| 17 | ...dependencies, |
| 18 | getOrigin: () => "http://localhost:17777", |
| 19 | native: async (action, extra) => action === "refreshSession" ? { url: "http://localhost:17777/#fresh-native-ticket" } : dependencies.native(action, extra), |
| 20 | api: async (path, body, method, headers) => { |
| 21 | if (path === "/agent/native/window") { |
| 22 | assert.deepEqual(body, { ticket: "fresh-native-ticket" }); |
| 23 | return { window_proof: "private-window-proof" }; |
| 24 | } |
| 25 | assert.equal(headers?.["X-Cage-Agent-Window"], "private-window-proof"); |
| 26 | return dependencies.api(path, body, method, headers); |
| 27 | }, |
| 28 | }); |
| 29 | } |
| 30 | |
| 31 | test("client preference writes use the window's remote instance and preserve original string encodings", () => { |
| 32 | const state = storage(); |
| 33 | state.setItem("unrelated-token", "keep-private"); |
| 34 | state.setItem("cage-sidebar-collapsed:remote:server-two", "false"); |
| 35 | const values = { |
| 36 | "cage-sidebar-collapsed": "true", |
| 37 | "cage-browser-tab-layout": '"vertical"', |
| 38 | "cage-keyboard": "native", |
| 39 | "cage.audio": '{"muted":false,"volume":0.25}', |
| 40 | "cage-desktop-zoom": "1.25", |
| 41 | "cage-tab-layout": '{"/workspace":{"order":["browser-1"],"sessionOrder":{"/project":["session-1"]},"browser-1":{"title":"Saved title","pinned":true}}}', |
| 42 | }; |
| 43 | const result = clientPreferences({ operation: "set", values }, context, state); |
| 44 | assert.equal(result.reload_required, true); |
| 45 | assert.equal(state.getItem("cage-sidebar-collapsed:remote:server-one"), "true"); |
| 46 | assert.equal(state.getItem("cage-sidebar-collapsed:remote:server-two"), "false"); |
| 47 | assert.equal(state.getItem("cage-browser-tab-layout:remote:server-one"), '"vertical"'); |
| 48 | assert.equal(state.getItem("cage.audio"), values["cage.audio"]); |
| 49 | assert.deepEqual(result.values["cage-keyboard"], "native"); |
| 50 | assert.ok(!JSON.stringify(result).includes("keep-private")); |
| 51 | assert.ok(!JSON.stringify(result).includes("unrelated-token")); |
| 52 | assert.equal(result.storage_keys["cage-keyboard"], "cage-keyboard:remote:server-one"); |
| 53 | assert.ok(agentClientPreferences.length >= 8); |
| 54 | }); |
| 55 | |
| 56 | test("invalid or server-owned preference patches do not change any earlier field", () => { |
| 57 | const state = storage(); |
| 58 | for (const values of [ |
| 59 | { "cage-sidebar-collapsed": "true", "unknown": "secret" }, |
| 60 | { "cage-sidebar-collapsed": "true", "cage.audio": '{"volume":5,"muted":false}' }, |
| 61 | { "cage-appearance": "{}" }, |
| 62 | { "cage-tab-layout": '{"project":{"order":{}}}' }, |
| 63 | { "cage-browser-tab-layout": "vertical" }, |
| 64 | ]) assert.throws(() => clientPreferences({ operation: "set", values }, context, state)); |
| 65 | assert.equal(state.values.size, 0); |
| 66 | assert.throws(() => clientPreferences({ operation: "set", values: { "cage-keyboard": "mac" } }, { mode: "local" }, state), /settings.keyboard/); |
| 67 | }); |
| 68 | |
| 69 | test("partial storage failure restores entries already changed in the patch", () => { |
| 70 | const state = storage(); |
| 71 | state.setItem("cage.audio", '{"volume":1,"muted":false}'); |
| 72 | const original = state.setItem; |
| 73 | state.setItem = (key, value) => { if (key === "cage-desktop-zoom") throw new Error("full"); original(key, value); }; |
| 74 | assert.throws(() => clientPreferences({ operation: "set", values: { "cage.audio": '{"volume":0,"muted":true}', "cage-desktop-zoom": "1.5" } }, context, state), /full/); |
| 75 | assert.equal(state.getItem("cage.audio"), '{"volume":1,"muted":false}'); |
| 76 | }); |
| 77 | |
| 78 | test("a late native result is rejected and a request for an old generation never invokes the bridge", async () => { |
| 79 | let current = context, release, calls = 0; |
| 80 | const dependencies = { storage: storage(), getContext: () => current, native: () => { calls++; return new Promise(resolve => { release = resolve; }); } }; |
| 81 | await assert.rejects(executeAgentNative({ connection_id: "old", request: { action: "chooseFolder" } }, dependencies), { code: "connection_changed" }); |
| 82 | assert.equal(calls, 0); |
| 83 | const pending = executeAgentNative({ connection_id: context.connection_id, request: { action: "accountDevice", operation: "unlock", kind: "biometric", connection_id: "malicious-override" } }, dependencies); |
| 84 | current = { ...context, connection_id: "generation-b" }; |
| 85 | release({ unlocked: true }); |
| 86 | await assert.rejects(pending, { code: "connection_changed" }); |
| 87 | assert.equal(calls, 1); |
| 88 | }); |
| 89 | |
| 90 | test("native operations retain their production checks and never return the refresh ticket", async () => { |
| 91 | let received; |
| 92 | const deps = { storage: storage(), getContext: () => context, native: async (action, input) => { received = { action, input }; return { url: "http://localhost:17777/#private-ticket" }; } }; |
| 93 | const result = await executeAgentNative({ connection_id: context.connection_id, request: { action: "refreshSession", connection_id: "override" } }, deps); |
| 94 | assert.deepEqual(result, { refreshed: true }); |
| 95 | assert.deepEqual(received, { action: "refreshSession", input: {} }); |
| 96 | deps.native = async () => { throw new Error("macOS 要求 Touch ID"); }; |
| 97 | await assert.rejects(executeAgentNative({ connection_id: context.connection_id, request: { action: "accountDevice", operation: "unlock" } }, deps), /Touch ID/); |
| 98 | }); |
| 99 | |
| 100 | test("lost completion response retries the receipt without repeating a native action", async () => { |
| 101 | const timers = clock(); let actions = 0, claims = 0, completes = 0; |
| 102 | const consumer = consumerForTest({ |
| 103 | ...timers, getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, |
| 104 | native: async () => { actions++; return { ok: true }; }, |
| 105 | api: async path => { |
| 106 | if (path.includes("consumer=window")) { claims++; return claims === 1 ? { id: "request-1", connection_id: context.connection_id, request: { action: "clipboardRead" } } : {}; } |
| 107 | completes++; if (completes === 1) throw new Error("lost acknowledgement"); return { ok: true }; |
| 108 | }, |
| 109 | }); |
| 110 | consumer.start(); await flush(); |
| 111 | assert.equal(actions, 1); assert.equal(completes, 1); |
| 112 | await timers.tick(); |
| 113 | assert.equal(actions, 1); assert.equal(completes, 2); assert.equal(claims, 1); |
| 114 | consumer.stop(); assert.equal(timers.scheduled.length, 0); |
| 115 | }); |
| 116 | |
| 117 | test("preference reload follows a successful receipt and never a lost one", async () => { |
| 118 | const timers = clock(); let completes = 0, reloads = 0; |
| 119 | const consumer = consumerForTest({ |
| 120 | ...timers, getContext: () => context, storage: storage(), reload: () => { reloads++; }, nativeAvailable: () => true, |
| 121 | native: async () => { throw new Error("must use client preference handler"); }, |
| 122 | api: async path => { |
| 123 | if (path.includes("consumer=window")) return { id: "request-1", connection_id: context.connection_id, request: { action: "clientPreferences", operation: "set", values: { "cage-sidebar-collapsed": "true" } } }; |
| 124 | completes++; if (completes === 1) throw new Error("lost"); return {}; |
| 125 | }, |
| 126 | }); |
| 127 | consumer.start(); await flush(); assert.equal(reloads, 0); |
| 128 | await timers.tick(); assert.equal(reloads, 1); assert.equal(timers.scheduled.length, 0); |
| 129 | }); |
| 130 | |
| 131 | test("two desktop consumers execute a claimed operation once and stopping cancels future polling", async () => { |
| 132 | const pending = [{ id: "request-1", connection_id: context.connection_id, request: { action: "chooseFolder" } }]; |
| 133 | let actions = 0, polls = 0; |
| 134 | const consumers = []; |
| 135 | const clocks = []; |
| 136 | for (let i = 0; i < 2; i++) { |
| 137 | const timers = clock(); clocks.push(timers); |
| 138 | consumers.push(consumerForTest({ ...timers, getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, |
| 139 | native: async () => { actions++; return "/chosen/project"; }, |
| 140 | api: async path => { if (path.includes("consumer=window")) { polls++; return pending.shift() || {}; } return {}; }, |
| 141 | })); |
| 142 | } |
| 143 | consumers.forEach(consumer => consumer.start()); await flush(); |
| 144 | assert.equal(actions, 1); assert.equal(polls, 2); |
| 145 | consumers.forEach(consumer => consumer.stop()); |
| 146 | for (const timers of clocks) { await timers.tick(); assert.equal(timers.scheduled.length, 0); } |
| 147 | assert.equal(polls, 2); |
| 148 | }); |
| 149 | |
| 150 | test("a window stopped while waiting for a claim reports non-execution", async () => { |
| 151 | const timers = clock(); let release, actions = 0, body; |
| 152 | const consumer = consumerForTest({ ...timers, getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, |
| 153 | native: async () => { actions++; }, |
| 154 | api: async (path, value) => { if (path.includes("consumer=window")) return new Promise(resolve => { release = resolve; }); body = value; return {}; }, |
| 155 | }); |
| 156 | consumer.start(); await flush(); consumer.stop(); release({ id: "request-1", connection_id: context.connection_id, request: { action: "chooseFolder" } }); await flush(); |
| 157 | assert.equal(actions, 0); assert.match(body.error, /未执行/); assert.equal(timers.scheduled.length, 0); |
| 158 | }); |
| 159 | |
| 160 | test("a native registration ticket never goes to a changed origin or starts an action", async () => { |
| 161 | const timers = clock(); let requests = 0, actions = 0; |
| 162 | const consumer = createAgentNativeConsumer({ ...timers, getOrigin: () => "http://localhost:17777", getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, |
| 163 | native: async action => { if (action === "refreshSession") return { url: "http://attacker.invalid/#secret-ticket" }; actions++; }, |
| 164 | api: async () => { requests++; }, |
| 165 | }); |
| 166 | consumer.start(); await flush(); consumer.stop(); |
| 167 | assert.equal(requests, 0); assert.equal(actions, 0); |
| 168 | }); |
| 169 | |
| 170 | test("expired window proof registers anew and retries only the original completion", async () => { |
| 171 | const timers = clock(); let registrations = 0, actions = 0, claims = 0, completes = 0; |
| 172 | const receipts = []; |
| 173 | const consumer = createAgentNativeConsumer({ ...timers, getOrigin: () => "http://localhost:17777", getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, |
| 174 | native: async action => action === "refreshSession" ? { url: `http://localhost:17777/#ticket-${registrations + 1}` } : (actions++, { ok: true }), |
| 175 | api: async (path, body, method, headers) => { |
| 176 | if (path === "/agent/native/window") { registrations++; assert.equal(body.ticket, `ticket-${registrations}`); return { window_proof: `proof-${registrations}` }; } |
| 177 | assert.equal(headers["X-Cage-Agent-Window"], `proof-${registrations}`); |
| 178 | if (path.includes("consumer=window")) { claims++; return { id: "original", connection_id: context.connection_id, request: { action: "chooseFolder" } }; } |
| 179 | completes++; receipts.push(body); |
| 180 | if (completes === 1) { const error = new Error("expired"); error.status = 403; throw error; } |
| 181 | return {}; |
| 182 | }, |
| 183 | }); |
| 184 | consumer.start(); await flush(); |
| 185 | assert.equal(actions, 1); assert.equal(completes, 1); assert.equal(registrations, 1); |
| 186 | await timers.tick(); consumer.stop(); |
| 187 | assert.equal(registrations, 2); assert.equal(claims, 1); assert.equal(actions, 1); assert.equal(completes, 2); |
| 188 | assert.deepEqual(receipts[0], receipts[1]); |
| 189 | assert.ok(!JSON.stringify(receipts).includes("proof-")); |
| 190 | assert.ok(!JSON.stringify(receipts).includes("ticket-")); |
| 191 | }); |
| 192 | |
| 193 | test("independent desktop consumers retain distinct private window proofs", async () => { |
| 194 | const proofs = new Set(); const consumers = []; let registrations = 0; |
| 195 | for (let i = 0; i < 2; i++) { |
| 196 | const timers = clock(); |
| 197 | const consumer = createAgentNativeConsumer({ ...timers, getOrigin: () => "http://localhost:17777", getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, |
| 198 | native: async () => ({ url: `http://localhost:17777/#window-${i}` }), |
| 199 | api: async (path, body, method, headers) => { |
| 200 | if (path === "/agent/native/window") { registrations++; return { window_proof: body.ticket + "-proof" }; } |
| 201 | proofs.add(headers["X-Cage-Agent-Window"]); return {}; |
| 202 | }, |
| 203 | }); |
| 204 | consumers.push(consumer); consumer.start(); |
| 205 | } |
| 206 | await flush(); consumers.forEach(consumer => consumer.stop()); |
| 207 | assert.equal(registrations, 2); assert.equal(proofs.size, 2); |
| 208 | }); |