@nexum-hub/browser 0.0.0-stage → 0.0.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.
- package/README.md +22 -2
- package/browser-extension/assets.js +654 -0
- package/browser-extension/build.mjs +111 -0
- package/browser-extension/clipboard.js +397 -0
- package/browser-extension/connection.js +880 -0
- package/browser-extension/dist/development/assets.js +654 -0
- package/browser-extension/dist/development/clipboard.js +397 -0
- package/browser-extension/dist/development/connection.js +880 -0
- package/browser-extension/dist/development/errors.js +106 -0
- package/browser-extension/dist/development/evaluate.js +160 -0
- package/browser-extension/dist/development/frames.js +256 -0
- package/browser-extension/dist/development/keyboard.js +167 -0
- package/browser-extension/dist/development/manifest.json +35 -0
- package/browser-extension/dist/development/native-node.js +85 -0
- package/browser-extension/dist/development/page-data.js +497 -0
- package/browser-extension/dist/development/page.js +772 -0
- package/browser-extension/dist/development/profile.js +2 -0
- package/browser-extension/dist/development/router.js +5961 -0
- package/browser-extension/dist/development/site-source.js +149 -0
- package/browser-extension/dist/development/transport.js +405 -0
- package/browser-extension/dist/development/visual.js +976 -0
- package/browser-extension/dist/development/worker.js +24 -0
- package/browser-extension/dist/production/assets.js +654 -0
- package/browser-extension/dist/production/clipboard.js +397 -0
- package/browser-extension/dist/production/connection.js +880 -0
- package/browser-extension/dist/production/errors.js +106 -0
- package/browser-extension/dist/production/evaluate.js +160 -0
- package/browser-extension/dist/production/frames.js +256 -0
- package/browser-extension/dist/production/keyboard.js +167 -0
- package/browser-extension/dist/production/manifest.json +35 -0
- package/browser-extension/dist/production/native-node.js +85 -0
- package/browser-extension/dist/production/page-data.js +497 -0
- package/browser-extension/dist/production/page.js +772 -0
- package/browser-extension/dist/production/profile.js +2 -0
- package/browser-extension/dist/production/router.js +5961 -0
- package/browser-extension/dist/production/site-source.js +149 -0
- package/browser-extension/dist/production/transport.js +405 -0
- package/browser-extension/dist/production/visual.js +976 -0
- package/browser-extension/dist/production/worker.js +24 -0
- package/browser-extension/errors.js +106 -0
- package/browser-extension/evaluate.js +160 -0
- package/browser-extension/frames.js +256 -0
- package/browser-extension/keyboard.js +167 -0
- package/browser-extension/native-node.js +85 -0
- package/browser-extension/page-data.js +497 -0
- package/browser-extension/page.js +772 -0
- package/browser-extension/release-info.json +21 -0
- package/browser-extension/route-manifest.json +807 -0
- package/browser-extension/router.js +5961 -0
- package/browser-extension/site-source.js +149 -0
- package/browser-extension/transport.js +405 -0
- package/browser-extension/visual.js +976 -0
- package/browser-extension/worker.js +24 -0
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.js +894 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/routes.d.ts +6 -0
- package/dist/client/routes.js +777 -0
- package/dist/client/routes.js.map +1 -0
- package/dist/client/serialize.d.ts +16 -0
- package/dist/client/serialize.js +355 -0
- package/dist/client/serialize.js.map +1 -0
- package/dist/client/types.d.ts +1342 -0
- package/dist/client/types.js +2 -0
- package/dist/client/types.js.map +1 -0
- package/dist/extension/artifacts.d.ts +60 -0
- package/dist/extension/artifacts.js +493 -0
- package/dist/extension/artifacts.js.map +1 -0
- package/dist/extension/assets.d.ts +10 -0
- package/dist/extension/assets.js +90 -0
- package/dist/extension/assets.js.map +1 -0
- package/dist/extension/batch.d.ts +6 -0
- package/dist/extension/batch.js +138 -0
- package/dist/extension/batch.js.map +1 -0
- package/dist/extension/files.d.ts +16 -0
- package/dist/extension/files.js +594 -0
- package/dist/extension/files.js.map +1 -0
- package/dist/extension/index.d.ts +3 -0
- package/dist/extension/index.js +623 -0
- package/dist/extension/index.js.map +1 -0
- package/dist/extension/protocol.d.ts +81 -0
- package/dist/extension/protocol.js +475 -0
- package/dist/extension/protocol.js.map +1 -0
- package/dist/extension/scope.d.ts +55 -0
- package/dist/extension/scope.js +563 -0
- package/dist/extension/scope.js.map +1 -0
- package/dist/extension/service.d.ts +113 -0
- package/dist/extension/service.js +905 -0
- package/dist/extension/service.js.map +1 -0
- package/docs/README.md +10 -0
- package/docs/api.md +1375 -0
- package/docs/connection.md +9 -0
- package/docs/lifecycle.md +17 -0
- package/docs/usage.md +75 -0
- package/implementation.json +2352 -0
- package/instructions/README.md +8 -0
- package/package.json +80 -4
- package/scripts/discover.js +12 -0
- package/scripts/screenshot.js +9 -0
- package/skills/browser-control/SKILL.md +12 -0
|
@@ -0,0 +1,880 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BrowserActionError,
|
|
3
|
+
requireValue,
|
|
4
|
+
record,
|
|
5
|
+
text,
|
|
6
|
+
publicError,
|
|
7
|
+
} from "./errors.js";
|
|
8
|
+
import {
|
|
9
|
+
BrowserBinaryInbox,
|
|
10
|
+
parseControl,
|
|
11
|
+
packBrowserValue,
|
|
12
|
+
unpackBrowserValue,
|
|
13
|
+
browserFrames,
|
|
14
|
+
transportLimits,
|
|
15
|
+
} from "./transport.js";
|
|
16
|
+
import { routeDefinitions } from "./router.js";
|
|
17
|
+
|
|
18
|
+
const encode = new TextEncoder();
|
|
19
|
+
const wait = (milliseconds) =>
|
|
20
|
+
new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
21
|
+
const sameBinding = (value, ready) =>
|
|
22
|
+
value.connectionId === ready.connectionId &&
|
|
23
|
+
value.generation === ready.generation;
|
|
24
|
+
/** Cold MV3 connection. Import and construction perform no storage, timer or socket I/O. */
|
|
25
|
+
export function createExtensionConnection({
|
|
26
|
+
chrome,
|
|
27
|
+
WebSocket: Socket = globalThis.WebSocket,
|
|
28
|
+
router,
|
|
29
|
+
profile,
|
|
30
|
+
extensionVersion,
|
|
31
|
+
url,
|
|
32
|
+
random = Math.random,
|
|
33
|
+
pingMs = 20000,
|
|
34
|
+
offlineMs = 60000,
|
|
35
|
+
}) {
|
|
36
|
+
requireValue(
|
|
37
|
+
["production", "development"].includes(profile),
|
|
38
|
+
"PROFILE_MISMATCH",
|
|
39
|
+
"Use a dedicated production or development extension build.",
|
|
40
|
+
);
|
|
41
|
+
const expectedUrl = `ws://127.0.0.1:${profile === "production" ? 43831 : 43832}/nexum-browser/v1`;
|
|
42
|
+
requireValue(
|
|
43
|
+
url === undefined || url === expectedUrl,
|
|
44
|
+
"PROFILE_MISMATCH",
|
|
45
|
+
"The extension cannot cross its fixed profile endpoint.",
|
|
46
|
+
);
|
|
47
|
+
let started = false,
|
|
48
|
+
stopped = false,
|
|
49
|
+
socket,
|
|
50
|
+
ready,
|
|
51
|
+
identity,
|
|
52
|
+
initialize,
|
|
53
|
+
reconnectTimer,
|
|
54
|
+
keepAlive,
|
|
55
|
+
reconnectAttempt = 0,
|
|
56
|
+
attemptSequence = 0,
|
|
57
|
+
lastMessage = 0,
|
|
58
|
+
sequence = 0,
|
|
59
|
+
snapshotPending = false,
|
|
60
|
+
snapshotDirty = false;
|
|
61
|
+
const clientInstanceId = crypto.randomUUID(),
|
|
62
|
+
inbox = new BrowserBinaryInbox(),
|
|
63
|
+
actions = new Map(),
|
|
64
|
+
receipts = new Map(),
|
|
65
|
+
leases = new Map(),
|
|
66
|
+
pendingLeaseReceipts = new Map();
|
|
67
|
+
let binaryTail = Promise.resolve(),
|
|
68
|
+
leaseReceiptPersistence = Promise.resolve(),
|
|
69
|
+
binaryProducers = 0;
|
|
70
|
+
const listeners = [];
|
|
71
|
+
const listen = (event, fn) => {
|
|
72
|
+
event?.addListener(fn);
|
|
73
|
+
if (event?.removeListener) listeners.push(() => event.removeListener(fn));
|
|
74
|
+
};
|
|
75
|
+
const state = () => ({
|
|
76
|
+
profile,
|
|
77
|
+
connected: !!ready && socket?.readyState === Socket.OPEN,
|
|
78
|
+
...(ready
|
|
79
|
+
? {
|
|
80
|
+
browserId: ready.browserId,
|
|
81
|
+
generation: ready.generation,
|
|
82
|
+
connectionId: ready.connectionId,
|
|
83
|
+
}
|
|
84
|
+
: {}),
|
|
85
|
+
});
|
|
86
|
+
const status = (online) => {
|
|
87
|
+
void Promise.resolve(
|
|
88
|
+
chrome.action?.setBadgeText?.({ text: online ? "" : "OFF" }),
|
|
89
|
+
).catch(() => {});
|
|
90
|
+
void Promise.resolve(
|
|
91
|
+
chrome.action?.setTitle?.({
|
|
92
|
+
title: online
|
|
93
|
+
? `Nexum browser (${profile})`
|
|
94
|
+
: `Nexum browser (${profile}) — offline`,
|
|
95
|
+
}),
|
|
96
|
+
).catch(() => {});
|
|
97
|
+
};
|
|
98
|
+
const bound = (extra) => ({
|
|
99
|
+
v: 1,
|
|
100
|
+
connectionId: ready.connectionId,
|
|
101
|
+
generation: ready.generation,
|
|
102
|
+
...extra,
|
|
103
|
+
});
|
|
104
|
+
const send = (value, expected = socket) => {
|
|
105
|
+
requireValue(
|
|
106
|
+
expected && expected === socket && expected.readyState === Socket.OPEN,
|
|
107
|
+
"EXTENSION_OFFLINE",
|
|
108
|
+
"The loopback connection is not open.",
|
|
109
|
+
);
|
|
110
|
+
const raw = JSON.stringify(value);
|
|
111
|
+
requireValue(
|
|
112
|
+
encode.encode(raw).byteLength <= transportLimits.controlBytes,
|
|
113
|
+
"OUTPUT_TOO_LARGE",
|
|
114
|
+
"The control frame exceeds its budget.",
|
|
115
|
+
);
|
|
116
|
+
expected.send(raw);
|
|
117
|
+
};
|
|
118
|
+
const sendBytes = async (frame, expected, controller) => {
|
|
119
|
+
while (expected.bufferedAmount > transportLimits.controlBytes) {
|
|
120
|
+
controller?.signal.throwIfAborted();
|
|
121
|
+
requireValue(
|
|
122
|
+
expected === socket && expected.readyState === Socket.OPEN,
|
|
123
|
+
"EXTENSION_OFFLINE",
|
|
124
|
+
);
|
|
125
|
+
await wait(5);
|
|
126
|
+
}
|
|
127
|
+
controller?.signal.throwIfAborted();
|
|
128
|
+
requireValue(
|
|
129
|
+
expected === socket && expected.readyState === Socket.OPEN,
|
|
130
|
+
"EXTENSION_OFFLINE",
|
|
131
|
+
);
|
|
132
|
+
expected.send(frame);
|
|
133
|
+
await wait(0);
|
|
134
|
+
};
|
|
135
|
+
const sendPacked = async (value, action, expected, controller) => {
|
|
136
|
+
requireValue(
|
|
137
|
+
binaryProducers < transportLimits.maxStreams,
|
|
138
|
+
"QUEUE_FULL",
|
|
139
|
+
"The browser byte producer queue is full.",
|
|
140
|
+
);
|
|
141
|
+
binaryProducers++;
|
|
142
|
+
const task = binaryTail.then(async () => {
|
|
143
|
+
controller.signal.throwIfAborted();
|
|
144
|
+
const binding = {
|
|
145
|
+
actionId: action.actionId,
|
|
146
|
+
operationId: action.operationId,
|
|
147
|
+
generation: action.generation,
|
|
148
|
+
};
|
|
149
|
+
const packed = await packBrowserValue(value, binding);
|
|
150
|
+
for (const stream of packed.streams) {
|
|
151
|
+
send(
|
|
152
|
+
{
|
|
153
|
+
v: 1,
|
|
154
|
+
type: "binary_start",
|
|
155
|
+
connectionId: action.connectionId,
|
|
156
|
+
...stream.meta,
|
|
157
|
+
},
|
|
158
|
+
expected,
|
|
159
|
+
);
|
|
160
|
+
for (const frame of browserFrames(stream.meta, stream.bytes))
|
|
161
|
+
await sendBytes(frame, expected, controller);
|
|
162
|
+
send(
|
|
163
|
+
{
|
|
164
|
+
v: 1,
|
|
165
|
+
type: "binary_end",
|
|
166
|
+
connectionId: action.connectionId,
|
|
167
|
+
...stream.meta,
|
|
168
|
+
},
|
|
169
|
+
expected,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
value: packed.value,
|
|
174
|
+
...(packed.valueStream ? { valueStream: packed.valueStream } : {}),
|
|
175
|
+
...(packed.attachments.length
|
|
176
|
+
? { attachments: packed.attachments }
|
|
177
|
+
: {}),
|
|
178
|
+
};
|
|
179
|
+
});
|
|
180
|
+
binaryTail = task.then(
|
|
181
|
+
() => {},
|
|
182
|
+
() => {},
|
|
183
|
+
);
|
|
184
|
+
try {
|
|
185
|
+
return await task;
|
|
186
|
+
} finally {
|
|
187
|
+
binaryProducers--;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
const trimReceipts = () => {
|
|
191
|
+
for (const [id, value] of receipts)
|
|
192
|
+
if (value.completedAt < Date.now() - 300000) receipts.delete(id);
|
|
193
|
+
while (receipts.size + actions.size >= 1024 && receipts.size > 0)
|
|
194
|
+
receipts.delete(receipts.keys().next().value);
|
|
195
|
+
};
|
|
196
|
+
const snapshots = async () => {
|
|
197
|
+
if (!ready || stopped) return;
|
|
198
|
+
if (snapshotPending) {
|
|
199
|
+
snapshotDirty = true;
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
snapshotPending = true;
|
|
203
|
+
const expected = socket,
|
|
204
|
+
generation = ready.generation;
|
|
205
|
+
try {
|
|
206
|
+
const tabs = await router.snapshot();
|
|
207
|
+
requireValue(
|
|
208
|
+
tabs.length <= 10000 &&
|
|
209
|
+
encode.encode(JSON.stringify(tabs)).byteLength <= 4 * 1024 * 1024,
|
|
210
|
+
"OUTPUT_TOO_LARGE",
|
|
211
|
+
"The complete tab snapshot exceeds its budget.",
|
|
212
|
+
);
|
|
213
|
+
const sendSnapshot = (type, items) => {
|
|
214
|
+
const parts = [];
|
|
215
|
+
let current = [],
|
|
216
|
+
bytes = 0;
|
|
217
|
+
for (const item of items) {
|
|
218
|
+
const size = encode.encode(JSON.stringify(item)).byteLength;
|
|
219
|
+
requireValue(size < 256 * 1024, "OUTPUT_TOO_LARGE");
|
|
220
|
+
if (bytes + size > 256 * 1024 && current.length) {
|
|
221
|
+
parts.push(current);
|
|
222
|
+
current = [];
|
|
223
|
+
bytes = 0;
|
|
224
|
+
}
|
|
225
|
+
current.push(item);
|
|
226
|
+
bytes += size;
|
|
227
|
+
}
|
|
228
|
+
parts.push(current);
|
|
229
|
+
const snapshotId = crypto.randomUUID();
|
|
230
|
+
for (let index = 0; index < parts.length; index++)
|
|
231
|
+
send(
|
|
232
|
+
bound({
|
|
233
|
+
type,
|
|
234
|
+
snapshotId,
|
|
235
|
+
index,
|
|
236
|
+
total: parts.length,
|
|
237
|
+
items: parts[index],
|
|
238
|
+
}),
|
|
239
|
+
expected,
|
|
240
|
+
);
|
|
241
|
+
};
|
|
242
|
+
if (expected !== socket || !ready || ready.generation !== generation)
|
|
243
|
+
return;
|
|
244
|
+
sendSnapshot(
|
|
245
|
+
"capabilities",
|
|
246
|
+
routeDefinitions.map((item) => ({ method: item.method })),
|
|
247
|
+
);
|
|
248
|
+
sendSnapshot("tabs", tabs);
|
|
249
|
+
} finally {
|
|
250
|
+
snapshotPending = false;
|
|
251
|
+
if (snapshotDirty) {
|
|
252
|
+
snapshotDirty = false;
|
|
253
|
+
queueMicrotask(
|
|
254
|
+
() =>
|
|
255
|
+
void snapshots().catch(() =>
|
|
256
|
+
socket?.close(4002, "snapshot failure"),
|
|
257
|
+
),
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
const rememberLeaseClosed = async (lease, value) => {
|
|
263
|
+
const receipt = {
|
|
264
|
+
v: 1,
|
|
265
|
+
type: "lease_closed",
|
|
266
|
+
...value,
|
|
267
|
+
leaseId: lease.leaseId,
|
|
268
|
+
runId: lease.runId,
|
|
269
|
+
operationId: lease.operationId,
|
|
270
|
+
originalGeneration: lease.generation,
|
|
271
|
+
connectionId: lease.connectionId,
|
|
272
|
+
generation: lease.generation,
|
|
273
|
+
};
|
|
274
|
+
pendingLeaseReceipts.set(lease.leaseId, receipt);
|
|
275
|
+
while (pendingLeaseReceipts.size > 256)
|
|
276
|
+
pendingLeaseReceipts.delete(pendingLeaseReceipts.keys().next().value);
|
|
277
|
+
const saved = [...pendingLeaseReceipts.values()];
|
|
278
|
+
const write = leaseReceiptPersistence
|
|
279
|
+
.catch(() => {})
|
|
280
|
+
.then(() => chrome.storage.session.set({ nexumClosedLeases: saved }));
|
|
281
|
+
leaseReceiptPersistence = write;
|
|
282
|
+
await write;
|
|
283
|
+
if (ready)
|
|
284
|
+
send(
|
|
285
|
+
bound({
|
|
286
|
+
...receipt,
|
|
287
|
+
connectionId: ready.connectionId,
|
|
288
|
+
generation: ready.generation,
|
|
289
|
+
}),
|
|
290
|
+
);
|
|
291
|
+
};
|
|
292
|
+
const closeLease = async (lease) => {
|
|
293
|
+
const value = await router.endLease(lease.leaseId);
|
|
294
|
+
leases.delete(lease.leaseId);
|
|
295
|
+
await rememberLeaseClosed(lease, value);
|
|
296
|
+
};
|
|
297
|
+
const disconnected = async (expected) => {
|
|
298
|
+
if (expected !== socket) return;
|
|
299
|
+
socket = undefined;
|
|
300
|
+
ready = undefined;
|
|
301
|
+
clearInterval(keepAlive);
|
|
302
|
+
keepAlive = undefined;
|
|
303
|
+
status(false);
|
|
304
|
+
for (const action of actions.values())
|
|
305
|
+
action.controller.abort(
|
|
306
|
+
new BrowserActionError(
|
|
307
|
+
"EXTENSION_OFFLINE",
|
|
308
|
+
"The connection closed after browser dispatch.",
|
|
309
|
+
{
|
|
310
|
+
dispatched: action.dispatched,
|
|
311
|
+
effect: action.dispatched ? "unknown" : "none",
|
|
312
|
+
},
|
|
313
|
+
),
|
|
314
|
+
);
|
|
315
|
+
inbox.discard();
|
|
316
|
+
for (const lease of leases.values()) void closeLease(lease).catch(() => {});
|
|
317
|
+
if (!stopped) schedule();
|
|
318
|
+
};
|
|
319
|
+
const schedule = () => {
|
|
320
|
+
if (stopped || reconnectTimer) return;
|
|
321
|
+
const steps = [1000, 2000, 4000, 8000, 16000, 30000],
|
|
322
|
+
delay =
|
|
323
|
+
steps[Math.min(reconnectAttempt++, steps.length - 1)] *
|
|
324
|
+
(0.8 + random() * 0.4);
|
|
325
|
+
reconnectTimer = setTimeout(() => {
|
|
326
|
+
reconnectTimer = undefined;
|
|
327
|
+
void connect().catch(() => schedule());
|
|
328
|
+
}, delay);
|
|
329
|
+
};
|
|
330
|
+
const completeArgs = (action) => {
|
|
331
|
+
const ids = [
|
|
332
|
+
...(action.message.attachments ?? []).map((item) => item.streamId),
|
|
333
|
+
...(action.message.argsStream ? [action.message.argsStream] : []),
|
|
334
|
+
];
|
|
335
|
+
return ids.every((id) => inbox.complete(id, action.message));
|
|
336
|
+
};
|
|
337
|
+
const ignoredBinary = (binding) => {
|
|
338
|
+
const action = actions.get(binding.actionId),
|
|
339
|
+
receipt = receipts.get(binding.actionId);
|
|
340
|
+
return !!(
|
|
341
|
+
(action?.controller.signal.aborted &&
|
|
342
|
+
action.operationId === binding.operationId &&
|
|
343
|
+
action.generation === binding.generation) ||
|
|
344
|
+
(receipt &&
|
|
345
|
+
receipt.operationId === binding.operationId &&
|
|
346
|
+
receipt.reply.generation === binding.generation)
|
|
347
|
+
);
|
|
348
|
+
};
|
|
349
|
+
const fingerprint = async (raw) =>
|
|
350
|
+
[
|
|
351
|
+
...new Uint8Array(
|
|
352
|
+
await crypto.subtle.digest("SHA-256", encode.encode(raw)),
|
|
353
|
+
),
|
|
354
|
+
]
|
|
355
|
+
.map((v) => v.toString(16).padStart(2, "0"))
|
|
356
|
+
.join("");
|
|
357
|
+
const execute = (action) => {
|
|
358
|
+
if (
|
|
359
|
+
action.executing ||
|
|
360
|
+
(!action.controller.signal.aborted && !completeArgs(action))
|
|
361
|
+
)
|
|
362
|
+
return;
|
|
363
|
+
action.executing = true;
|
|
364
|
+
const message = action.message,
|
|
365
|
+
expected = action.socket;
|
|
366
|
+
void (async () => {
|
|
367
|
+
let reply;
|
|
368
|
+
try {
|
|
369
|
+
await action.fingerprint;
|
|
370
|
+
action.controller.signal.throwIfAborted();
|
|
371
|
+
const args = unpackBrowserValue(
|
|
372
|
+
message.args,
|
|
373
|
+
message.attachments,
|
|
374
|
+
message.argsStream,
|
|
375
|
+
inbox,
|
|
376
|
+
message,
|
|
377
|
+
);
|
|
378
|
+
action.controller.signal.throwIfAborted();
|
|
379
|
+
requireValue(
|
|
380
|
+
ready && expected === socket && sameBinding(message, ready),
|
|
381
|
+
"EXTENSION_OFFLINE",
|
|
382
|
+
);
|
|
383
|
+
const value = await router.dispatch(
|
|
384
|
+
{ ...message, args },
|
|
385
|
+
action.controller.signal,
|
|
386
|
+
() => {
|
|
387
|
+
action.dispatched = true;
|
|
388
|
+
},
|
|
389
|
+
);
|
|
390
|
+
const packed = await sendPacked(
|
|
391
|
+
value,
|
|
392
|
+
message,
|
|
393
|
+
expected,
|
|
394
|
+
action.controller,
|
|
395
|
+
);
|
|
396
|
+
reply = {
|
|
397
|
+
v: 1,
|
|
398
|
+
type: "action_result",
|
|
399
|
+
actionId: message.actionId,
|
|
400
|
+
operationId: message.operationId,
|
|
401
|
+
runId: message.runId,
|
|
402
|
+
connectionId: message.connectionId,
|
|
403
|
+
generation: message.generation,
|
|
404
|
+
ok: true,
|
|
405
|
+
...packed,
|
|
406
|
+
};
|
|
407
|
+
} catch (cause) {
|
|
408
|
+
reply = {
|
|
409
|
+
v: 1,
|
|
410
|
+
type: "action_result",
|
|
411
|
+
actionId: message.actionId,
|
|
412
|
+
operationId: message.operationId,
|
|
413
|
+
runId: message.runId,
|
|
414
|
+
connectionId: message.connectionId,
|
|
415
|
+
generation: message.generation,
|
|
416
|
+
ok: false,
|
|
417
|
+
...publicError(cause, action.dispatched),
|
|
418
|
+
};
|
|
419
|
+
} finally {
|
|
420
|
+
clearTimeout(action.timer);
|
|
421
|
+
inbox.discard(message.actionId);
|
|
422
|
+
actions.delete(message.actionId);
|
|
423
|
+
}
|
|
424
|
+
// Receipts contain only control data. Binary results are not retained for replay.
|
|
425
|
+
const receipt = { ...reply };
|
|
426
|
+
if (receipt.ok && (receipt.attachments?.length || receipt.valueStream)) {
|
|
427
|
+
receipt.ok = false;
|
|
428
|
+
delete receipt.value;
|
|
429
|
+
delete receipt.valueStream;
|
|
430
|
+
delete receipt.attachments;
|
|
431
|
+
Object.assign(receipt, {
|
|
432
|
+
code: "UNKNOWN_RESULT",
|
|
433
|
+
message: "The original byte result cannot be replayed.",
|
|
434
|
+
dispatched: true,
|
|
435
|
+
effect: "unknown",
|
|
436
|
+
retryable: false,
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
receipts.set(message.actionId, {
|
|
440
|
+
reply: receipt,
|
|
441
|
+
completedAt: Date.now(),
|
|
442
|
+
operationId: message.operationId,
|
|
443
|
+
fingerprint: await action.fingerprint,
|
|
444
|
+
});
|
|
445
|
+
trimReceipts();
|
|
446
|
+
if (expected === socket && ready && sameBinding(message, ready))
|
|
447
|
+
send(reply, expected);
|
|
448
|
+
})().catch(() => {
|
|
449
|
+
if (expected === socket) expected.close(4002, "protocol failure");
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
const receive = async (event, expected) => {
|
|
453
|
+
if (expected !== socket || stopped) return;
|
|
454
|
+
if (typeof event.data !== "string") {
|
|
455
|
+
requireValue(
|
|
456
|
+
ready,
|
|
457
|
+
"PROTOCOL_MISMATCH",
|
|
458
|
+
"Binary data arrived before ready.",
|
|
459
|
+
);
|
|
460
|
+
inbox.push(event.data, ignoredBinary);
|
|
461
|
+
lastMessage = Date.now();
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
const message = parseControl(event.data);
|
|
465
|
+
lastMessage = Date.now();
|
|
466
|
+
if (message.type === "ready") {
|
|
467
|
+
requireValue(
|
|
468
|
+
!ready &&
|
|
469
|
+
message.profile === profile &&
|
|
470
|
+
message.browserSessionId === identity.browserSessionId &&
|
|
471
|
+
message.protocolVersion === 1 &&
|
|
472
|
+
Number.isSafeInteger(message.generation) &&
|
|
473
|
+
message.generation > 0,
|
|
474
|
+
"PROTOCOL_MISMATCH",
|
|
475
|
+
"The ready message belongs to another profile, session or protocol.",
|
|
476
|
+
);
|
|
477
|
+
for (const key of ["bootId", "connectionId", "browserId"])
|
|
478
|
+
text(message[key], 256);
|
|
479
|
+
record(message.limits);
|
|
480
|
+
for (const key of [
|
|
481
|
+
"controlBytes",
|
|
482
|
+
"headerBytes",
|
|
483
|
+
"chunkBytes",
|
|
484
|
+
"maxStreams",
|
|
485
|
+
"valueBytes",
|
|
486
|
+
"inFlight",
|
|
487
|
+
])
|
|
488
|
+
requireValue(
|
|
489
|
+
message.limits[key] === transportLimits[key],
|
|
490
|
+
"PROTOCOL_MISMATCH",
|
|
491
|
+
"The plugin and package use incompatible wire budgets.",
|
|
492
|
+
);
|
|
493
|
+
ready = Object.freeze(message);
|
|
494
|
+
router.bind(message);
|
|
495
|
+
reconnectAttempt = 0;
|
|
496
|
+
status(true);
|
|
497
|
+
await snapshots();
|
|
498
|
+
for (const receipt of pendingLeaseReceipts.values())
|
|
499
|
+
send(
|
|
500
|
+
bound({
|
|
501
|
+
...receipt,
|
|
502
|
+
connectionId: ready.connectionId,
|
|
503
|
+
generation: ready.generation,
|
|
504
|
+
}),
|
|
505
|
+
);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
if (message.type === "error" && !ready)
|
|
509
|
+
throw new BrowserActionError(
|
|
510
|
+
message.code ?? "PROTOCOL_MISMATCH",
|
|
511
|
+
"The local package rejected this plugin connection.",
|
|
512
|
+
);
|
|
513
|
+
requireValue(
|
|
514
|
+
ready && sameBinding(message, ready),
|
|
515
|
+
"PROTOCOL_MISMATCH",
|
|
516
|
+
"The message belongs to a stale browser connection.",
|
|
517
|
+
);
|
|
518
|
+
if (message.type === "ping") {
|
|
519
|
+
router.wake?.();
|
|
520
|
+
send(bound({ type: "pong" }));
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
if (message.type === "pong") return;
|
|
524
|
+
if (message.type === "binary_start") {
|
|
525
|
+
if (ignoredBinary(message)) return;
|
|
526
|
+
inbox.begin(message, (binding) => {
|
|
527
|
+
const action = actions.get(binding.actionId);
|
|
528
|
+
return (
|
|
529
|
+
action &&
|
|
530
|
+
!action.executing &&
|
|
531
|
+
action.operationId === binding.operationId &&
|
|
532
|
+
action.generation === binding.generation &&
|
|
533
|
+
[
|
|
534
|
+
...(action.message.attachments ?? []).map((a) => a.streamId),
|
|
535
|
+
action.message.argsStream,
|
|
536
|
+
].includes(binding.streamId)
|
|
537
|
+
);
|
|
538
|
+
});
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
if (message.type === "binary_end") {
|
|
542
|
+
if (ignoredBinary(message)) return;
|
|
543
|
+
try {
|
|
544
|
+
await inbox.end(message);
|
|
545
|
+
} catch (cause) {
|
|
546
|
+
if (ignoredBinary(message)) return;
|
|
547
|
+
throw cause;
|
|
548
|
+
}
|
|
549
|
+
const action = actions.get(message.actionId);
|
|
550
|
+
if (action) execute(action);
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
if (message.type === "action") {
|
|
554
|
+
for (const key of [
|
|
555
|
+
"actionId",
|
|
556
|
+
"operationId",
|
|
557
|
+
"runId",
|
|
558
|
+
"leaseId",
|
|
559
|
+
"method",
|
|
560
|
+
])
|
|
561
|
+
text(message[key], 256);
|
|
562
|
+
requireValue(
|
|
563
|
+
Number.isFinite(message.budgetMs) &&
|
|
564
|
+
message.budgetMs > 0 &&
|
|
565
|
+
message.budgetMs <= 2147483647 &&
|
|
566
|
+
message.args !== undefined,
|
|
567
|
+
"PROTOCOL_MISMATCH",
|
|
568
|
+
"The action declaration is invalid.",
|
|
569
|
+
);
|
|
570
|
+
trimReceipts();
|
|
571
|
+
if (actions.has(message.actionId)) {
|
|
572
|
+
const prior = actions.get(message.actionId);
|
|
573
|
+
requireValue(
|
|
574
|
+
prior.operationId === message.operationId &&
|
|
575
|
+
(await prior.fingerprint) === (await fingerprint(event.data)),
|
|
576
|
+
"PROTOCOL_MISMATCH",
|
|
577
|
+
"An action ID was rebound.",
|
|
578
|
+
);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
if (receipts.has(message.actionId)) {
|
|
582
|
+
const prior = receipts.get(message.actionId);
|
|
583
|
+
requireValue(
|
|
584
|
+
prior.operationId === message.operationId &&
|
|
585
|
+
prior.fingerprint === (await fingerprint(event.data)),
|
|
586
|
+
"PROTOCOL_MISMATCH",
|
|
587
|
+
"An action ID was rebound.",
|
|
588
|
+
);
|
|
589
|
+
send(prior.reply);
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
requireValue(
|
|
593
|
+
actions.size < transportLimits.inFlight &&
|
|
594
|
+
actions.size + receipts.size < 1024,
|
|
595
|
+
"QUEUE_FULL",
|
|
596
|
+
"The browser action receipt budget is full.",
|
|
597
|
+
);
|
|
598
|
+
const controller = new AbortController(),
|
|
599
|
+
action = {
|
|
600
|
+
actionId: message.actionId,
|
|
601
|
+
operationId: message.operationId,
|
|
602
|
+
generation: message.generation,
|
|
603
|
+
controller,
|
|
604
|
+
message,
|
|
605
|
+
socket: expected,
|
|
606
|
+
executing: false,
|
|
607
|
+
dispatched: false,
|
|
608
|
+
fingerprint: fingerprint(event.data),
|
|
609
|
+
};
|
|
610
|
+
action.timer = setTimeout(() => {
|
|
611
|
+
controller.abort(
|
|
612
|
+
new BrowserActionError(
|
|
613
|
+
"TIMEOUT",
|
|
614
|
+
"The action reached its browser-side deadline.",
|
|
615
|
+
{
|
|
616
|
+
dispatched: action.dispatched,
|
|
617
|
+
effect: action.dispatched ? "unknown" : "none",
|
|
618
|
+
},
|
|
619
|
+
),
|
|
620
|
+
);
|
|
621
|
+
execute(action);
|
|
622
|
+
}, message.budgetMs);
|
|
623
|
+
actions.set(message.actionId, action);
|
|
624
|
+
execute(action);
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
if (message.type === "cancel_action") {
|
|
628
|
+
const action = actions.get(message.actionId);
|
|
629
|
+
if (action) {
|
|
630
|
+
requireValue(
|
|
631
|
+
action.operationId === message.operationId,
|
|
632
|
+
"PROTOCOL_MISMATCH",
|
|
633
|
+
);
|
|
634
|
+
action.controller.abort(
|
|
635
|
+
new BrowserActionError(
|
|
636
|
+
"UNKNOWN_RESULT",
|
|
637
|
+
"The action was cancelled; dispatched website effects are not rolled back.",
|
|
638
|
+
{
|
|
639
|
+
dispatched: action.dispatched,
|
|
640
|
+
effect: action.dispatched ? "unknown" : "none",
|
|
641
|
+
},
|
|
642
|
+
),
|
|
643
|
+
);
|
|
644
|
+
if (!action.executing) execute(action);
|
|
645
|
+
}
|
|
646
|
+
inbox.discard(message.actionId);
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
if (message.type === "lease_open") {
|
|
650
|
+
for (const key of ["leaseId", "runId", "operationId"])
|
|
651
|
+
text(message[key], 256);
|
|
652
|
+
let value;
|
|
653
|
+
try {
|
|
654
|
+
value = await router.openLease(message);
|
|
655
|
+
} catch (cause) {
|
|
656
|
+
const rejected = router.rejectedLeaseOpen?.(cause);
|
|
657
|
+
if (
|
|
658
|
+
rejected?.rejected === true &&
|
|
659
|
+
rejected.leaseId === message.leaseId &&
|
|
660
|
+
rejected.runId === message.runId &&
|
|
661
|
+
rejected.operationId === message.operationId
|
|
662
|
+
) {
|
|
663
|
+
await rememberLeaseClosed(message, rejected);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
throw cause;
|
|
667
|
+
}
|
|
668
|
+
leases.set(message.leaseId, message);
|
|
669
|
+
send(
|
|
670
|
+
bound({
|
|
671
|
+
type: "lease_opened",
|
|
672
|
+
...value,
|
|
673
|
+
leaseId: message.leaseId,
|
|
674
|
+
runId: message.runId,
|
|
675
|
+
operationId: message.operationId,
|
|
676
|
+
}),
|
|
677
|
+
);
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
if (message.type === "lease_end") {
|
|
681
|
+
const lease = leases.get(message.leaseId);
|
|
682
|
+
if (!lease) {
|
|
683
|
+
const prior = pendingLeaseReceipts.get(message.leaseId);
|
|
684
|
+
requireValue(
|
|
685
|
+
prior && prior.runId === message.runId,
|
|
686
|
+
"INVALID_TARGET",
|
|
687
|
+
"Unknown lease cleanup identity.",
|
|
688
|
+
);
|
|
689
|
+
send(
|
|
690
|
+
bound({
|
|
691
|
+
...prior,
|
|
692
|
+
generation: ready.generation,
|
|
693
|
+
connectionId: ready.connectionId,
|
|
694
|
+
}),
|
|
695
|
+
);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
requireValue(
|
|
699
|
+
lease.runId === message.runId,
|
|
700
|
+
"INVALID_TARGET",
|
|
701
|
+
"A run cannot close another run's lease.",
|
|
702
|
+
);
|
|
703
|
+
await closeLease(lease);
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
throw new BrowserActionError(
|
|
707
|
+
"PROTOCOL_MISMATCH",
|
|
708
|
+
"The local endpoint sent an unsupported control message.",
|
|
709
|
+
);
|
|
710
|
+
};
|
|
711
|
+
const connect = async () => {
|
|
712
|
+
if (stopped || socket) return;
|
|
713
|
+
await initialize;
|
|
714
|
+
// Recheck after initialization. A socket, including one still closing,
|
|
715
|
+
// remains the current owner until its close handler starts cleanup.
|
|
716
|
+
if (stopped || socket) return;
|
|
717
|
+
const expected = new Socket(expectedUrl);
|
|
718
|
+
socket = expected;
|
|
719
|
+
expected.binaryType = "arraybuffer";
|
|
720
|
+
expected.addEventListener("open", () => {
|
|
721
|
+
if (expected !== socket || stopped) {
|
|
722
|
+
expected.close();
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
lastMessage = Date.now();
|
|
726
|
+
send(
|
|
727
|
+
{
|
|
728
|
+
v: 1,
|
|
729
|
+
type: "hello",
|
|
730
|
+
profile,
|
|
731
|
+
extensionId: chrome.runtime.id,
|
|
732
|
+
extensionVersion,
|
|
733
|
+
protocol: { min: 1, max: 1 },
|
|
734
|
+
...identity,
|
|
735
|
+
clientInstanceId,
|
|
736
|
+
attemptSequence: ++attemptSequence,
|
|
737
|
+
metadata: {
|
|
738
|
+
name: "Nexum browser",
|
|
739
|
+
extensionVersion,
|
|
740
|
+
versionSource: "unknown",
|
|
741
|
+
},
|
|
742
|
+
},
|
|
743
|
+
expected,
|
|
744
|
+
);
|
|
745
|
+
keepAlive = setInterval(() => {
|
|
746
|
+
if (expected !== socket || expected.readyState !== Socket.OPEN) return;
|
|
747
|
+
if (Date.now() - lastMessage >= offlineMs) {
|
|
748
|
+
expected.close(4001, "peer offline");
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
if (ready) send(bound({ type: "ping" }), expected);
|
|
752
|
+
}, pingMs);
|
|
753
|
+
});
|
|
754
|
+
expected.addEventListener("message", (event) => {
|
|
755
|
+
void receive(event, expected).catch(() => {
|
|
756
|
+
if (expected === socket) expected.close(4002, "protocol failure");
|
|
757
|
+
});
|
|
758
|
+
});
|
|
759
|
+
expected.addEventListener("close", () => {
|
|
760
|
+
void disconnected(expected).catch(() => schedule());
|
|
761
|
+
});
|
|
762
|
+
expected.addEventListener("error", () => {
|
|
763
|
+
if (expected === socket && expected.readyState !== Socket.CLOSED)
|
|
764
|
+
expected.close();
|
|
765
|
+
});
|
|
766
|
+
};
|
|
767
|
+
const api = {
|
|
768
|
+
start() {
|
|
769
|
+
requireValue(
|
|
770
|
+
!stopped,
|
|
771
|
+
"EXTENSION_OFFLINE",
|
|
772
|
+
"A disposed plugin connection cannot restart.",
|
|
773
|
+
);
|
|
774
|
+
if (started) return initialize;
|
|
775
|
+
started = true;
|
|
776
|
+
initialize = (async () => {
|
|
777
|
+
const local = await chrome.storage.local.get(["nexumBrowserProfileId"]),
|
|
778
|
+
session = await chrome.storage.session.get([
|
|
779
|
+
"nexumBrowserSessionId",
|
|
780
|
+
"nexumClosedLeases",
|
|
781
|
+
"nexumOwnedControls",
|
|
782
|
+
"nexumVisualMarkers",
|
|
783
|
+
]);
|
|
784
|
+
requireValue(
|
|
785
|
+
session.nexumBrowserSessionId || !session.nexumOwnedControls?.length,
|
|
786
|
+
"PROFILE_CONFLICT",
|
|
787
|
+
"Native attachment journal exists without its browser session identity.",
|
|
788
|
+
);
|
|
789
|
+
identity = {
|
|
790
|
+
browserProfileId: local.nexumBrowserProfileId ?? crypto.randomUUID(),
|
|
791
|
+
browserSessionId:
|
|
792
|
+
session.nexumBrowserSessionId ?? crypto.randomUUID(),
|
|
793
|
+
};
|
|
794
|
+
if (!local.nexumBrowserProfileId)
|
|
795
|
+
await chrome.storage.local.set({
|
|
796
|
+
nexumBrowserProfileId: identity.browserProfileId,
|
|
797
|
+
});
|
|
798
|
+
if (!session.nexumBrowserSessionId)
|
|
799
|
+
await chrome.storage.session.set({
|
|
800
|
+
nexumBrowserSessionId: identity.browserSessionId,
|
|
801
|
+
});
|
|
802
|
+
for (const receipt of session.nexumClosedLeases ?? [])
|
|
803
|
+
if (receipt && typeof receipt.leaseId === "string")
|
|
804
|
+
pendingLeaseReceipts.set(receipt.leaseId, receipt);
|
|
805
|
+
const owned = session.nexumOwnedControls ?? [];
|
|
806
|
+
requireValue(
|
|
807
|
+
owned.every(
|
|
808
|
+
(entry) =>
|
|
809
|
+
entry.target?.browserSessionId === identity.browserSessionId,
|
|
810
|
+
),
|
|
811
|
+
"PROFILE_CONFLICT",
|
|
812
|
+
"The saved native control belongs to another browser session.",
|
|
813
|
+
);
|
|
814
|
+
router.start();
|
|
815
|
+
if (router.recoverOwnedControls)
|
|
816
|
+
for (const recovered of await router.recoverOwnedControls(owned))
|
|
817
|
+
await rememberLeaseClosed(recovered.lease, recovered.receipt);
|
|
818
|
+
if (router.startVisual)
|
|
819
|
+
await router.startVisual(
|
|
820
|
+
identity.browserSessionId,
|
|
821
|
+
session.nexumVisualMarkers ?? [],
|
|
822
|
+
);
|
|
823
|
+
})();
|
|
824
|
+
void initialize.then(
|
|
825
|
+
() =>
|
|
826
|
+
connect().catch(() => {
|
|
827
|
+
status(false);
|
|
828
|
+
schedule();
|
|
829
|
+
}),
|
|
830
|
+
() => status(false),
|
|
831
|
+
);
|
|
832
|
+
listen(chrome.runtime.onStartup, () => void connect().catch(schedule));
|
|
833
|
+
listen(chrome.alarms?.onAlarm, (alarm) => {
|
|
834
|
+
if (alarm.name === "nexum-browser-connect")
|
|
835
|
+
void connect().catch(schedule);
|
|
836
|
+
});
|
|
837
|
+
void Promise.resolve(
|
|
838
|
+
chrome.alarms?.create?.("nexum-browser-connect", {
|
|
839
|
+
periodInMinutes: 0.5,
|
|
840
|
+
}),
|
|
841
|
+
).catch(() => {});
|
|
842
|
+
return initialize;
|
|
843
|
+
},
|
|
844
|
+
publish(event) {
|
|
845
|
+
if (!ready || !socket || stopped) return;
|
|
846
|
+
if (event.type === "tabs_changed") {
|
|
847
|
+
void snapshots().catch(() => socket?.close(4002, "snapshot failure"));
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
send(bound({ ...event, sequence: ++sequence }));
|
|
851
|
+
},
|
|
852
|
+
state,
|
|
853
|
+
async dispose() {
|
|
854
|
+
if (stopped) return;
|
|
855
|
+
stopped = true;
|
|
856
|
+
clearTimeout(reconnectTimer);
|
|
857
|
+
clearInterval(keepAlive);
|
|
858
|
+
for (const remove of listeners.splice(0)) remove();
|
|
859
|
+
for (const action of actions.values())
|
|
860
|
+
action.controller.abort(
|
|
861
|
+
new BrowserActionError(
|
|
862
|
+
"EXTENSION_OFFLINE",
|
|
863
|
+
"The plugin connection stopped.",
|
|
864
|
+
{
|
|
865
|
+
dispatched: action.dispatched,
|
|
866
|
+
effect: action.dispatched ? "unknown" : "none",
|
|
867
|
+
},
|
|
868
|
+
),
|
|
869
|
+
);
|
|
870
|
+
await Promise.allSettled([...leases.values()].map(closeLease));
|
|
871
|
+
await router.dispose();
|
|
872
|
+
if (socket && socket.readyState !== Socket.CLOSED)
|
|
873
|
+
socket.close(1000, "plugin stopped");
|
|
874
|
+
ready = undefined;
|
|
875
|
+
inbox.discard();
|
|
876
|
+
await chrome.alarms?.clear?.("nexum-browser-connect");
|
|
877
|
+
},
|
|
878
|
+
};
|
|
879
|
+
return Object.freeze(api);
|
|
880
|
+
}
|