@braedonsaunders/appkit-desk 0.6.0 → 0.8.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.
Files changed (53) hide show
  1. package/README.md +83 -1
  2. package/backend.d.ts +28 -7
  3. package/backend.d.ts.map +1 -1
  4. package/backend.js +18 -521
  5. package/backend.js.map +1 -1
  6. package/events.d.ts +3 -0
  7. package/events.d.ts.map +1 -1
  8. package/events.js.map +1 -1
  9. package/host.d.ts +32 -1
  10. package/host.d.ts.map +1 -1
  11. package/host.js +141 -23
  12. package/host.js.map +1 -1
  13. package/index.d.ts +3 -0
  14. package/index.d.ts.map +1 -1
  15. package/index.js +3 -0
  16. package/index.js.map +1 -1
  17. package/machine.d.ts +145 -0
  18. package/machine.d.ts.map +1 -0
  19. package/machine.js +518 -0
  20. package/machine.js.map +1 -0
  21. package/network.d.ts +37 -0
  22. package/network.d.ts.map +1 -0
  23. package/network.js +173 -0
  24. package/network.js.map +1 -0
  25. package/package.json +2 -2
  26. package/plan.d.ts +129 -31
  27. package/plan.d.ts.map +1 -1
  28. package/plan.js +165 -9
  29. package/plan.js.map +1 -1
  30. package/port-relay.d.ts +13 -0
  31. package/port-relay.d.ts.map +1 -0
  32. package/port-relay.js +56 -0
  33. package/port-relay.js.map +1 -0
  34. package/virtualization.d.ts +16 -0
  35. package/virtualization.d.ts.map +1 -0
  36. package/virtualization.js +148 -0
  37. package/virtualization.js.map +1 -0
  38. package/vz/Package.swift +23 -0
  39. package/vz/Sources/DeskNet/Addresses.swift +106 -0
  40. package/vz/Sources/DeskNet/DHCP.swift +111 -0
  41. package/vz/Sources/DeskNet/Fence.swift +57 -0
  42. package/vz/Sources/DeskNet/NetworkStack.swift +547 -0
  43. package/vz/Sources/DeskNet/Packets.swift +355 -0
  44. package/vz/Sources/DeskNet/Plumbing.swift +312 -0
  45. package/vz/Sources/DeskNet/Sockets.swift +221 -0
  46. package/vz/Sources/DeskNet/TCPFlow.swift +448 -0
  47. package/vz/Sources/appkit-desk-vz/Control.swift +152 -0
  48. package/vz/Sources/appkit-desk-vz/Helper.swift +505 -0
  49. package/vz/Sources/appkit-desk-vz/main.swift +38 -0
  50. package/vz/Tests/DeskNetTests/DeskNetTests.swift +426 -0
  51. package/vz/appkit-desk-vz.entitlements +8 -0
  52. package/vz/build.sh +23 -0
  53. package/vz/check/extract-boot.py +221 -0
package/machine.js ADDED
@@ -0,0 +1,518 @@
1
+ /**
2
+ * The guest channel every backend shares: the hybrid-vsock handshake, the
3
+ * proof that a guest is really behind it, the reconnecting machine, and the
4
+ * child-process plumbing around a VMM. Cloud Hypervisor and the
5
+ * Virtualization.framework helper both expose the guest agent through a host
6
+ * Unix socket with the same `CONNECT <port>` preamble, so everything from the
7
+ * socket inwards is one implementation. Internal to the package.
8
+ */
9
+ import { spawn } from 'node:child_process';
10
+ import { createConnection } from 'node:net';
11
+ import { Buffer } from 'node:buffer';
12
+ import { DeskRequestFateUnknownError } from './backend.js';
13
+ import { DeskError } from './plan.js';
14
+ import { encodeFrame, FrameDecoder, parseHostBoundMessage, } from './protocol.js';
15
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
16
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 20_000;
17
+ export const DEFAULT_CONNECT_RETRY_DELAY_MS = 100;
18
+ export const DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000;
19
+ export const DEFAULT_RECONNECT_WINDOW_MS = 30_000;
20
+ export const DEFAULT_RECONNECT_RETRY_DELAY_MS = 250;
21
+ /**
22
+ * How far the reconnect delay is allowed to double. A guest agent that systemd
23
+ * is restarting is not helped by being hammered four times a second for the
24
+ * whole window, and an unbounded doubling would spend most of the window
25
+ * asleep after two failures.
26
+ */
27
+ export const RECONNECT_BACKOFF_CEILING = 8;
28
+ export const DEFAULT_KILL_GRACE_MS = 2_000;
29
+ const HANDSHAKE_LINE_LIMIT = 128;
30
+ /**
31
+ * The machine, and the small state machine that keeps it connected.
32
+ *
33
+ * A vsock channel is not a fact the host learns once at boot — the transport
34
+ * can lie about being connected, and it can go away mid-lease for reasons that
35
+ * have nothing to do with the desk being unusable: the guest agent restarts,
36
+ * the socat bridge drops, a transient vsock error, the guest wedges for a
37
+ * moment. Treating any of those as terminal stranded the desk for the rest of
38
+ * its lease with a perfectly healthy guest behind it, answering every call
39
+ * with "no longer connected". So a live connection is something this machine
40
+ * RE-ESTABLISHES:
41
+ *
42
+ * live ──unexpected drop──▶ reconnecting ──confirmed guest──▶ live
43
+ * │ │
44
+ * │ └──window exhausted / VMM exited──▶ closed
45
+ * └──shutdown(), VMM already exited, protocol violation───────────▶ closed
46
+ *
47
+ * `closed` is terminal. Nothing reconnects out of it, which is what makes
48
+ * `shutdown()` and a dead VMM final rather than the start of a retry loop.
49
+ *
50
+ * What differs between hypervisors is only how the VM stops, parks, and
51
+ * reaches guest ports, and those arrive as functions.
52
+ */
53
+ export function createGuestMachine(options) {
54
+ const { deskId, exit, now, idFactory, requestTimeoutMs, reconnectWindowMs } = options;
55
+ const pending = new Map();
56
+ // Listeners live on the machine rather than on the socket, so a reconnect
57
+ // re-points the data path at the new stream and every subscriber keeps
58
+ // working without re-registering.
59
+ const listeners = new Set();
60
+ const watchers = new Set();
61
+ let stream = options.stream;
62
+ let state = 'live';
63
+ let reconnects = 0;
64
+ let reconnecting = null;
65
+ function failAll(error) {
66
+ for (const entry of pending.values()) {
67
+ clearTimeout(entry.timer);
68
+ entry.reject(error);
69
+ }
70
+ pending.clear();
71
+ }
72
+ function announce(change) {
73
+ for (const watcher of [...watchers])
74
+ watcher(change);
75
+ }
76
+ function close(error, intentional) {
77
+ if (state === 'closed')
78
+ return;
79
+ state = 'closed';
80
+ failAll(error);
81
+ stream.destroy();
82
+ // A desk the consumer asked to stop is not news; one that stopped on its
83
+ // own is the thing an operator needs to be told about.
84
+ if (!intentional)
85
+ announce({ state: 'lost', deskId, reason: error.message });
86
+ }
87
+ function attach(next) {
88
+ stream = next;
89
+ // Each connection decodes with its OWN decoder: a frame the drop cut in
90
+ // half must never be completed by the first bytes of its replacement.
91
+ const decoder = new FrameDecoder();
92
+ const current = () => stream === next && state !== 'closed';
93
+ const onData = (chunk) => {
94
+ if (!current())
95
+ return;
96
+ let values;
97
+ try {
98
+ values = decoder.push(chunk);
99
+ }
100
+ catch (error) {
101
+ close(new DeskError(`Guest agent protocol violation on desk ${deskId}: ${errorMessage(error)}`), false);
102
+ return;
103
+ }
104
+ for (const value of values) {
105
+ let message;
106
+ try {
107
+ message = parseHostBoundMessage(value);
108
+ }
109
+ catch (error) {
110
+ close(new DeskError(`Guest agent sent a malformed message on desk ${deskId}: ${errorMessage(error)}`), false);
111
+ return;
112
+ }
113
+ if ('id' in message) {
114
+ const entry = pending.get(message.id);
115
+ if (!entry)
116
+ continue;
117
+ pending.delete(message.id);
118
+ clearTimeout(entry.timer);
119
+ if (message.ok)
120
+ entry.resolve(message.result);
121
+ else
122
+ entry.reject(new DeskError(`Guest agent error on desk ${deskId}: ${message.error}`));
123
+ }
124
+ else {
125
+ for (const listener of [...listeners])
126
+ listener(message);
127
+ }
128
+ }
129
+ };
130
+ next.on('data', onData);
131
+ next.once('close', () => {
132
+ drop(next, `the guest agent connection closed on desk ${deskId}`);
133
+ });
134
+ next.once('error', (error) => {
135
+ drop(next, `the guest agent connection failed on desk ${deskId}: ${error.message}`);
136
+ });
137
+ }
138
+ function drop(from, reason) {
139
+ if (state !== 'live' || from !== stream)
140
+ return;
141
+ from.destroy();
142
+ if (exit.done) {
143
+ // A dead VMM is not a connection problem. There is no guest to get back
144
+ // to, and retrying against it forever only delays the fresh boot the
145
+ // desk actually needs.
146
+ close(new DeskError(`Desk ${deskId} is no longer connected: the VMM exited (${reason}).`), false);
147
+ return;
148
+ }
149
+ state = 'reconnecting';
150
+ const lostAt = now();
151
+ // In-flight requests CANNOT be silently retried. Each of their frames
152
+ // already reached the guest, and whether the guest ran it before the
153
+ // channel went away is not knowable from here: an `exec` may have sent
154
+ // mail, a `click` may have landed. Replaying a side-effecting operation to
155
+ // paper over a blip is the wrong kind of resilience, so every one of them
156
+ // is told its fate is unknown and the caller decides.
157
+ failAll(new DeskRequestFateUnknownError(`Desk ${deskId} lost its guest agent connection while this request was in flight `
158
+ + `(${reason}); the guest may or may not have run it.`));
159
+ reconnecting = restore(reason, lostAt);
160
+ }
161
+ /** Always resolves: callers await it to learn the outcome, not to be thrown at. */
162
+ async function restore(reason, lostAt) {
163
+ let next;
164
+ try {
165
+ next = await options.reconnect(() => state !== 'reconnecting');
166
+ }
167
+ catch (error) {
168
+ close(new DeskError(`Desk ${deskId} lost its guest agent connection and could not get it back: ${errorMessage(error)}`), false);
169
+ return;
170
+ }
171
+ if (state !== 'reconnecting') {
172
+ // shutdown() won the race while the replacement socket was coming up.
173
+ next.destroy();
174
+ return;
175
+ }
176
+ attach(next);
177
+ state = 'live';
178
+ reconnects += 1;
179
+ announce({ state: 'reconnected', deskId, reason, downtimeMs: now() - lostAt, reconnects });
180
+ }
181
+ attach(options.stream);
182
+ const machine = {
183
+ deskId,
184
+ async request(command, requestOptions = {}) {
185
+ // A call that lands mid-reconnect waits for it rather than failing on
186
+ // the spot: the guest is usually back within seconds, and telling a
187
+ // caller a desk is gone when it is about to be fine is the bug this
188
+ // machine exists to end. The wait is bounded by the same window the
189
+ // reconnect itself is.
190
+ const waitUntil = now() + reconnectWindowMs;
191
+ while (state === 'reconnecting') {
192
+ const attempt = reconnecting;
193
+ if (!attempt || now() >= waitUntil)
194
+ break;
195
+ await attempt;
196
+ }
197
+ if (state !== 'live') {
198
+ // This one never left the host, so — unlike a request that was in
199
+ // flight when the channel dropped — repeating it is safe.
200
+ throw new DeskError(`Desk ${deskId} is no longer connected.`);
201
+ }
202
+ const id = idFactory();
203
+ const timeoutMs = requestOptions.timeoutMs ?? requestTimeoutMs;
204
+ const target = stream;
205
+ return await new Promise((resolvePromise, rejectPromise) => {
206
+ const timer = setTimeout(() => {
207
+ pending.delete(id);
208
+ rejectPromise(new DeskError(`Guest request ${command.op} timed out on desk ${deskId}.`));
209
+ }, timeoutMs);
210
+ timer.unref();
211
+ pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
212
+ target.write(encodeFrame({ ...command, id }));
213
+ });
214
+ },
215
+ subscribe(listener) {
216
+ listeners.add(listener);
217
+ return () => {
218
+ listeners.delete(listener);
219
+ };
220
+ },
221
+ onConnectionChange(listener) {
222
+ watchers.add(listener);
223
+ return () => {
224
+ watchers.delete(listener);
225
+ };
226
+ },
227
+ async shutdown() {
228
+ // Terminal by construction: `closed` is the state the reconnect loop
229
+ // checks, so an explicit shutdown can never be followed by a reconnect.
230
+ close(new DeskError(`Desk ${deskId} is shutting down.`), true);
231
+ await options.stop();
232
+ },
233
+ };
234
+ if (options.park) {
235
+ const park = options.park;
236
+ machine.park = async (snapshotDir) => {
237
+ // Close the guest channel FIRST. Pausing a VM strands whatever was in
238
+ // flight on the vsock, and a reconnect attempt against a paused guest
239
+ // would burn the whole reconnect window before giving up — so the channel
240
+ // is made terminal before the VM stops answering, exactly as shutdown
241
+ // does it.
242
+ close(new DeskError(`Desk ${deskId} is being parked.`), true);
243
+ await park(snapshotDir);
244
+ };
245
+ }
246
+ if (options.connect) {
247
+ const connect = options.connect;
248
+ machine.connect = async (port) => {
249
+ if (state === 'closed')
250
+ throw new DeskError(`Desk ${deskId} is no longer connected.`);
251
+ return await connect(port);
252
+ };
253
+ }
254
+ return machine;
255
+ }
256
+ /**
257
+ * Read a child's output and keep only the last few kilobytes.
258
+ *
259
+ * This is not for logging — it is load-bearing. A child spawned with its
260
+ * streams as PIPES blocks once a pipe nobody reads fills, after about 64KB.
261
+ * Cloud Hypervisor logs while it runs, so an unread pipe freezes the guest
262
+ * partway through boot: the process is alive, the disk is untouched, and the
263
+ * guest agent never reaches vsock. Every symptom points at the image and none
264
+ * of them are its fault.
265
+ *
266
+ * Draining costs nothing and buys the tail of what the process said, which is
267
+ * the difference between "the VMM exited" and knowing why. `streams` names the
268
+ * pipes to drain: a helper that speaks a protocol on stdout drains only stderr.
269
+ */
270
+ export function drainOutput(child, limit = 8 * 1024, streams = ['stdout', 'stderr']) {
271
+ let buffered = '';
272
+ const absorb = (chunk) => {
273
+ buffered += String(chunk);
274
+ if (buffered.length > limit)
275
+ buffered = buffered.slice(buffered.length - limit);
276
+ };
277
+ for (const name of streams) {
278
+ const pipe = child[name];
279
+ pipe?.on('data', absorb);
280
+ // A pipe that errors must not take the process down with it.
281
+ pipe?.on('error', () => undefined);
282
+ }
283
+ return { tail: () => buffered.trim() };
284
+ }
285
+ export function watchExit(child) {
286
+ const watcher = { done: false, promise: Promise.resolve() };
287
+ watcher.promise = new Promise((resolvePromise) => {
288
+ const settle = () => {
289
+ watcher.done = true;
290
+ resolvePromise();
291
+ };
292
+ child.once('exit', settle);
293
+ child.once('error', settle);
294
+ });
295
+ return watcher;
296
+ }
297
+ export async function terminate(child, exit, killGraceMs) {
298
+ if (exit.done)
299
+ return;
300
+ child.kill('SIGTERM');
301
+ const forceKill = setTimeout(() => {
302
+ if (!exit.done)
303
+ child.kill('SIGKILL');
304
+ }, killGraceMs);
305
+ forceKill.unref();
306
+ await exit.promise;
307
+ clearTimeout(forceKill);
308
+ }
309
+ export function runToCompletion(child, label) {
310
+ return new Promise((resolvePromise, rejectPromise) => {
311
+ let stderr = '';
312
+ child.stderr?.on('data', (chunk) => {
313
+ stderr += String(chunk);
314
+ });
315
+ child.once('error', (error) => {
316
+ rejectPromise(new DeskError(`${label} failed to start: ${error.message}`));
317
+ });
318
+ child.once('exit', (code, signal) => {
319
+ if (code === 0) {
320
+ resolvePromise();
321
+ return;
322
+ }
323
+ const detail = stderr.trim();
324
+ rejectPromise(new DeskError(`${label} exited with code ${code ?? 'unknown'}`
325
+ + `${signal ? ` (${signal})` : ''}${detail ? `: ${detail}` : '.'}`));
326
+ });
327
+ });
328
+ }
329
+ /**
330
+ * Cloud Hypervisor exposes guest vsock ports through a host Unix socket with
331
+ * a line-oriented preamble: the client writes `CONNECT <port>\n` and the VMM
332
+ * answers `OK <assigned>\n` before the byte stream becomes the guest
333
+ * connection. The VMM creates the socket during boot, so connection attempts
334
+ * retry until the deadline. The Virtualization.framework helper speaks the
335
+ * same preamble on its own socket.
336
+ *
337
+ * The same loop serves the first connection and every later reconnect, so a
338
+ * reconnect gets `confirmGuest` too — a mid-lease reconnect that trusted the
339
+ * banner would re-adopt exactly the hollow stream the boot path learned not to.
340
+ */
341
+ export async function connectWithRetry(options) {
342
+ const deadline = options.now() + options.timeoutMs;
343
+ let lastFailure = 'the guest agent never answered';
344
+ let retryDelayMs = options.retryDelayMs;
345
+ while (options.now() <= deadline) {
346
+ if (options.exited.done) {
347
+ throw new DeskError(options.exitedMessage ?? 'The VMM exited before the guest agent came up.');
348
+ }
349
+ if (options.abandoned?.() === true) {
350
+ throw new DeskError('the connection attempt was abandoned.');
351
+ }
352
+ try {
353
+ const stream = await attemptHandshake(options.connect, options.socketPath, options.port, options.attemptTimeoutMs);
354
+ try {
355
+ await confirmGuest(stream, options.attemptTimeoutMs);
356
+ }
357
+ catch (error) {
358
+ stream.destroy();
359
+ throw error;
360
+ }
361
+ return stream;
362
+ }
363
+ catch (error) {
364
+ lastFailure = errorMessage(error);
365
+ }
366
+ await delay(retryDelayMs);
367
+ if (options.maxRetryDelayMs !== undefined) {
368
+ retryDelayMs = Math.min(retryDelayMs * 2, options.maxRetryDelayMs);
369
+ }
370
+ }
371
+ throw new DeskError(`Timed out connecting to the guest agent at ${options.socketPath}: ${lastFailure}`);
372
+ }
373
+ /**
374
+ * Prove a guest is behind the handshake by asking it something.
375
+ *
376
+ * Cloud Hypervisor answers `CONNECT <port>` with `OK` whether or not anything
377
+ * in the guest is listening on that port, and only closes the socket a moment
378
+ * later when it finds nobody there. A caller that trusts the banner therefore
379
+ * "connects" to a guest that is still booting, gets a closed stream seconds
380
+ * later, and — because a closed machine is not retried — leaves the desk dead
381
+ * for as long as it is leased, with a healthy guest sitting behind it. So the
382
+ * handshake is not the test; a reply is.
383
+ */
384
+ async function confirmGuest(stream, timeoutMs) {
385
+ const decoder = new FrameDecoder();
386
+ await new Promise((resolvePromise, rejectPromise) => {
387
+ let settled = false;
388
+ const finish = (error) => {
389
+ if (settled)
390
+ return;
391
+ settled = true;
392
+ clearTimeout(timer);
393
+ stream.off('data', onData);
394
+ stream.off('close', onClose);
395
+ stream.off('error', finish);
396
+ if (error)
397
+ rejectPromise(error);
398
+ else
399
+ resolvePromise();
400
+ };
401
+ const timer = setTimeout(() => finish(new DeskError('the guest agent did not answer the first request.')), timeoutMs);
402
+ timer.unref?.();
403
+ const onClose = () => finish(new DeskError('the connection closed before the guest agent answered.'));
404
+ const onData = (chunk) => {
405
+ let values;
406
+ try {
407
+ values = decoder.push(chunk);
408
+ }
409
+ catch (error) {
410
+ finish(error instanceof Error ? error : new Error(String(error)));
411
+ return;
412
+ }
413
+ for (const value of values) {
414
+ // Anything at all proves a guest is there; the reply is parsed for
415
+ // real by the machine once it owns the stream.
416
+ if (value && typeof value === 'object') {
417
+ finish();
418
+ return;
419
+ }
420
+ }
421
+ };
422
+ stream.on('data', onData);
423
+ stream.once('close', onClose);
424
+ stream.once('error', finish);
425
+ stream.write(encodeFrame({ id: 'hello', op: 'ping' }));
426
+ });
427
+ }
428
+ /**
429
+ * One handshake attempt, which MUST settle.
430
+ *
431
+ * Cloud Hypervisor accepts a connection on the vsock socket whether or not
432
+ * anything in the guest is listening on the port, and when nothing is it may
433
+ * answer nothing at all: no reply, no error, no close. Without a deadline of
434
+ * its own this promise then never settles — and because the caller awaits it
435
+ * inside the retry loop, the loop stops iterating, the overall deadline is
436
+ * never re-checked, and the boot hangs forever rather than failing. That is
437
+ * indistinguishable from a wedged host and it is why every attempt is bounded
438
+ * here as well as in aggregate.
439
+ *
440
+ * A close before the reply line is a refusal: that is how a port with nothing
441
+ * listening presents through Cloud Hypervisor, and the Virtualization.framework
442
+ * helper presents a refused vsock or TCP port the same way.
443
+ */
444
+ export function attemptHandshake(connect, socketPath, port, attemptTimeoutMs) {
445
+ return new Promise((resolvePromise, rejectPromise) => {
446
+ let stream;
447
+ try {
448
+ stream = connect(socketPath);
449
+ }
450
+ catch (error) {
451
+ rejectPromise(error instanceof Error ? error : new Error(String(error)));
452
+ return;
453
+ }
454
+ let banner = '';
455
+ let settled = false;
456
+ const timer = setTimeout(() => {
457
+ fail(new DeskError('vsock handshake went unanswered.'));
458
+ }, attemptTimeoutMs);
459
+ // An unref'd timer must not hold the process open on its own.
460
+ timer.unref?.();
461
+ const fail = (error) => {
462
+ if (settled)
463
+ return;
464
+ settled = true;
465
+ clearTimeout(timer);
466
+ stream.destroy();
467
+ rejectPromise(error);
468
+ };
469
+ const onData = (chunk) => {
470
+ banner += chunk.toString('latin1');
471
+ const newline = banner.indexOf('\n');
472
+ if (newline === -1) {
473
+ if (banner.length > HANDSHAKE_LINE_LIMIT) {
474
+ fail(new DeskError('vsock handshake reply exceeded the line limit.'));
475
+ }
476
+ return;
477
+ }
478
+ const line = banner.slice(0, newline);
479
+ const rest = banner.slice(newline + 1);
480
+ stream.off('data', onData);
481
+ stream.off('error', fail);
482
+ if (!line.startsWith('OK ')) {
483
+ fail(new DeskError(`vsock handshake was refused: ${line}`));
484
+ return;
485
+ }
486
+ settled = true;
487
+ clearTimeout(timer);
488
+ if (rest.length > 0)
489
+ stream.unshift(Buffer.from(rest, 'latin1'));
490
+ resolvePromise(stream);
491
+ };
492
+ stream.on('data', onData);
493
+ stream.once('error', fail);
494
+ // A close before the banner is a refusal, not a hang.
495
+ stream.once('close', () => fail(new DeskError('vsock handshake closed before a reply.')));
496
+ stream.write(`CONNECT ${port}\n`);
497
+ });
498
+ }
499
+ export function defaultLauncher(command, args, options) {
500
+ return spawn(command, [...args], {
501
+ stdio: ['ignore', 'pipe', 'pipe'],
502
+ uid: options.identity?.uid,
503
+ gid: options.identity?.gid,
504
+ });
505
+ }
506
+ export function defaultConnect(socketPath) {
507
+ return createConnection(socketPath);
508
+ }
509
+ export function delay(ms) {
510
+ return new Promise((resolvePromise) => {
511
+ const timer = setTimeout(resolvePromise, ms);
512
+ timer.unref();
513
+ });
514
+ }
515
+ export function errorMessage(error) {
516
+ return error instanceof Error ? error.message : String(error);
517
+ }
518
+ //# sourceMappingURL=machine.js.map
package/machine.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machine.js","sourceRoot":"","sources":["../src/machine.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEpC,OAAO,EAAE,2BAA2B,EAA+C,MAAM,WAAW,CAAA;AACpG,OAAO,EAAE,SAAS,EAA6B,MAAM,QAAQ,CAAA;AAC7D,OAAO,EACL,WAAW,EACX,YAAY,EACZ,qBAAqB,GAGtB,MAAM,YAAY,CAAA;AAEnB,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAA;AAChD,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAA;AAChD,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,CAAA;AACjD,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAA;AACjD,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAA;AACjD,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAG,CAAA;AACnD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAA;AAC1C,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAA;AAC1C,MAAM,oBAAoB,GAAG,GAAG,CAAA;AAEhC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAmBlC;IACC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,GAAG,OAAO,CAAA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AAI,OAAO,CAAO,CAAC,cAAc,EAAE,EAAE;QAC1C,MAAM,KAAK,GAAG,UAAU,CAAC,cAAc,EAAE,EAAE,CAAC,CAAA;QAC5C,KAAK,CAAC,KAAK,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC/D,CAAC","sourcesContent":["/**\n * The guest channel every backend shares: the hybrid-vsock handshake, the\n * proof that a guest is really behind it, the reconnecting machine, and the\n * child-process plumbing around a VMM. Cloud Hypervisor and the\n * Virtualization.framework helper both expose the guest agent through a host\n * Unix socket with the same `CONNECT <port>` preamble, so everything from the\n * socket inwards is one implementation. Internal to the package.\n */\nimport { spawn, type ChildProcess } from 'node:child_process'\nimport { createConnection } from 'node:net'\nimport { Buffer } from 'node:buffer'\nimport type { Duplex } from 'node:stream'\nimport { DeskRequestFateUnknownError, type DeskConnectionChange, type DeskMachine } from './backend'\nimport { DeskError, type DeskLauncherIdentity } from './plan'\nimport {\n encodeFrame,\n FrameDecoder,\n parseHostBoundMessage,\n type GuestEventMessage,\n type HostBoundMessage,\n} from './protocol'\n\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 20_000\nexport const DEFAULT_CONNECT_RETRY_DELAY_MS = 100\nexport const DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000\nexport const DEFAULT_RECONNECT_WINDOW_MS = 30_000\nexport const DEFAULT_RECONNECT_RETRY_DELAY_MS = 250\n/**\n * How far the reconnect delay is allowed to double. A guest agent that systemd\n * is restarting is not helped by being hammered four times a second for the\n * whole window, and an unbounded doubling would spend most of the window\n * asleep after two failures.\n */\nexport const RECONNECT_BACKOFF_CEILING = 8\nexport const DEFAULT_KILL_GRACE_MS = 2_000\nconst HANDSHAKE_LINE_LIMIT = 128\n\n/**\n * The machine, and the small state machine that keeps it connected.\n *\n * A vsock channel is not a fact the host learns once at boot — the transport\n * can lie about being connected, and it can go away mid-lease for reasons that\n * have nothing to do with the desk being unusable: the guest agent restarts,\n * the socat bridge drops, a transient vsock error, the guest wedges for a\n * moment. Treating any of those as terminal stranded the desk for the rest of\n * its lease with a perfectly healthy guest behind it, answering every call\n * with \"no longer connected\". So a live connection is something this machine\n * RE-ESTABLISHES:\n *\n * live ──unexpected drop──▶ reconnecting ──confirmed guest──▶ live\n * │ │\n * │ └──window exhausted / VMM exited──▶ closed\n * └──shutdown(), VMM already exited, protocol violation───────────▶ closed\n *\n * `closed` is terminal. Nothing reconnects out of it, which is what makes\n * `shutdown()` and a dead VMM final rather than the start of a retry loop.\n *\n * What differs between hypervisors is only how the VM stops, parks, and\n * reaches guest ports, and those arrive as functions.\n */\nexport function createGuestMachine(options: {\n deskId: string\n exit: ExitWatcher\n stream: Duplex\n /** Re-establishes the channel; resolves only once a guest has answered. */\n reconnect: (abandoned: () => boolean) => Promise<Duplex>\n reconnectWindowMs: number\n now: () => number\n idFactory: () => string\n requestTimeoutMs: number\n /** Stop the VMM; resolves once its process has exited. */\n stop: () => Promise<void>\n /**\n * Pause, snapshot into `snapshotDir`, and stop the VMM. Called after the\n * guest channel has been closed. Must leave the VMM stopped on failure too.\n */\n park?: (snapshotDir: string) => Promise<void>\n /** Open a host-to-guest TCP stream, for backends with no routable guest. */\n connect?: (port: number) => Promise<Duplex>\n}): DeskMachine {\n const { deskId, exit, now, idFactory, requestTimeoutMs, reconnectWindowMs } = options\n const pending = new Map<\n string,\n { resolve: (result: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }\n >()\n // Listeners live on the machine rather than on the socket, so a reconnect\n // re-points the data path at the new stream and every subscriber keeps\n // working without re-registering.\n const listeners = new Set<(event: GuestEventMessage) => void>()\n const watchers = new Set<(change: DeskConnectionChange) => void>()\n let stream = options.stream\n let state: 'live' | 'reconnecting' | 'closed' = 'live'\n let reconnects = 0\n let reconnecting: Promise<void> | null = null\n\n function failAll(error: Error): void {\n for (const entry of pending.values()) {\n clearTimeout(entry.timer)\n entry.reject(error)\n }\n pending.clear()\n }\n\n function announce(change: DeskConnectionChange): void {\n for (const watcher of [...watchers]) watcher(change)\n }\n\n function close(error: DeskError, intentional: boolean): void {\n if (state === 'closed') return\n state = 'closed'\n failAll(error)\n stream.destroy()\n // A desk the consumer asked to stop is not news; one that stopped on its\n // own is the thing an operator needs to be told about.\n if (!intentional) announce({ state: 'lost', deskId, reason: error.message })\n }\n\n function attach(next: Duplex): void {\n stream = next\n // Each connection decodes with its OWN decoder: a frame the drop cut in\n // half must never be completed by the first bytes of its replacement.\n const decoder = new FrameDecoder()\n const current = () => stream === next && state !== 'closed'\n const onData = (chunk: Buffer): void => {\n if (!current()) return\n let values: unknown[]\n try {\n values = decoder.push(chunk)\n } catch (error) {\n close(\n new DeskError(`Guest agent protocol violation on desk ${deskId}: ${errorMessage(error)}`),\n false,\n )\n return\n }\n for (const value of values) {\n let message: HostBoundMessage\n try {\n message = parseHostBoundMessage(value)\n } catch (error) {\n close(\n new DeskError(`Guest agent sent a malformed message on desk ${deskId}: ${errorMessage(error)}`),\n false,\n )\n return\n }\n if ('id' in message) {\n const entry = pending.get(message.id)\n if (!entry) continue\n pending.delete(message.id)\n clearTimeout(entry.timer)\n if (message.ok) entry.resolve(message.result)\n else entry.reject(new DeskError(`Guest agent error on desk ${deskId}: ${message.error}`))\n } else {\n for (const listener of [...listeners]) listener(message)\n }\n }\n }\n next.on('data', onData)\n next.once('close', () => {\n drop(next, `the guest agent connection closed on desk ${deskId}`)\n })\n next.once('error', (error: Error) => {\n drop(next, `the guest agent connection failed on desk ${deskId}: ${error.message}`)\n })\n }\n\n function drop(from: Duplex, reason: string): void {\n if (state !== 'live' || from !== stream) return\n from.destroy()\n if (exit.done) {\n // A dead VMM is not a connection problem. There is no guest to get back\n // to, and retrying against it forever only delays the fresh boot the\n // desk actually needs.\n close(new DeskError(`Desk ${deskId} is no longer connected: the VMM exited (${reason}).`), false)\n return\n }\n state = 'reconnecting'\n const lostAt = now()\n // In-flight requests CANNOT be silently retried. Each of their frames\n // already reached the guest, and whether the guest ran it before the\n // channel went away is not knowable from here: an `exec` may have sent\n // mail, a `click` may have landed. Replaying a side-effecting operation to\n // paper over a blip is the wrong kind of resilience, so every one of them\n // is told its fate is unknown and the caller decides.\n failAll(\n new DeskRequestFateUnknownError(\n `Desk ${deskId} lost its guest agent connection while this request was in flight `\n + `(${reason}); the guest may or may not have run it.`,\n ),\n )\n reconnecting = restore(reason, lostAt)\n }\n\n /** Always resolves: callers await it to learn the outcome, not to be thrown at. */\n async function restore(reason: string, lostAt: number): Promise<void> {\n let next: Duplex\n try {\n next = await options.reconnect(() => state !== 'reconnecting')\n } catch (error) {\n close(\n new DeskError(\n `Desk ${deskId} lost its guest agent connection and could not get it back: ${errorMessage(error)}`,\n ),\n false,\n )\n return\n }\n if (state !== 'reconnecting') {\n // shutdown() won the race while the replacement socket was coming up.\n next.destroy()\n return\n }\n attach(next)\n state = 'live'\n reconnects += 1\n announce({ state: 'reconnected', deskId, reason, downtimeMs: now() - lostAt, reconnects })\n }\n\n attach(options.stream)\n\n const machine: DeskMachine = {\n deskId,\n async request(command, requestOptions = {}) {\n // A call that lands mid-reconnect waits for it rather than failing on\n // the spot: the guest is usually back within seconds, and telling a\n // caller a desk is gone when it is about to be fine is the bug this\n // machine exists to end. The wait is bounded by the same window the\n // reconnect itself is.\n const waitUntil = now() + reconnectWindowMs\n while (state === 'reconnecting') {\n const attempt = reconnecting\n if (!attempt || now() >= waitUntil) break\n await attempt\n }\n if (state !== 'live') {\n // This one never left the host, so — unlike a request that was in\n // flight when the channel dropped — repeating it is safe.\n throw new DeskError(`Desk ${deskId} is no longer connected.`)\n }\n const id = idFactory()\n const timeoutMs = requestOptions.timeoutMs ?? requestTimeoutMs\n const target = stream\n return await new Promise<unknown>((resolvePromise, rejectPromise) => {\n const timer = setTimeout(() => {\n pending.delete(id)\n rejectPromise(new DeskError(`Guest request ${command.op} timed out on desk ${deskId}.`))\n }, timeoutMs)\n timer.unref()\n pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer })\n target.write(encodeFrame({ ...command, id }))\n })\n },\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n onConnectionChange(listener) {\n watchers.add(listener)\n return () => {\n watchers.delete(listener)\n }\n },\n async shutdown() {\n // Terminal by construction: `closed` is the state the reconnect loop\n // checks, so an explicit shutdown can never be followed by a reconnect.\n close(new DeskError(`Desk ${deskId} is shutting down.`), true)\n await options.stop()\n },\n }\n if (options.park) {\n const park = options.park\n machine.park = async (snapshotDir: string) => {\n // Close the guest channel FIRST. Pausing a VM strands whatever was in\n // flight on the vsock, and a reconnect attempt against a paused guest\n // would burn the whole reconnect window before giving up — so the channel\n // is made terminal before the VM stops answering, exactly as shutdown\n // does it.\n close(new DeskError(`Desk ${deskId} is being parked.`), true)\n await park(snapshotDir)\n }\n }\n if (options.connect) {\n const connect = options.connect\n machine.connect = async (port: number) => {\n if (state === 'closed') throw new DeskError(`Desk ${deskId} is no longer connected.`)\n return await connect(port)\n }\n }\n return machine\n}\n\nexport interface ExitWatcher {\n done: boolean\n promise: Promise<void>\n}\n\n/**\n * Read a child's output and keep only the last few kilobytes.\n *\n * This is not for logging — it is load-bearing. A child spawned with its\n * streams as PIPES blocks once a pipe nobody reads fills, after about 64KB.\n * Cloud Hypervisor logs while it runs, so an unread pipe freezes the guest\n * partway through boot: the process is alive, the disk is untouched, and the\n * guest agent never reaches vsock. Every symptom points at the image and none\n * of them are its fault.\n *\n * Draining costs nothing and buys the tail of what the process said, which is\n * the difference between \"the VMM exited\" and knowing why. `streams` names the\n * pipes to drain: a helper that speaks a protocol on stdout drains only stderr.\n */\nexport function drainOutput(\n child: ChildProcess,\n limit = 8 * 1024,\n streams: readonly ('stdout' | 'stderr')[] = ['stdout', 'stderr'],\n): { tail: () => string } {\n let buffered = ''\n const absorb = (chunk: unknown) => {\n buffered += String(chunk)\n if (buffered.length > limit) buffered = buffered.slice(buffered.length - limit)\n }\n for (const name of streams) {\n const pipe = child[name]\n pipe?.on('data', absorb)\n // A pipe that errors must not take the process down with it.\n pipe?.on('error', () => undefined)\n }\n return { tail: () => buffered.trim() }\n}\n\nexport function watchExit(child: ChildProcess): ExitWatcher {\n const watcher: ExitWatcher = { done: false, promise: Promise.resolve() }\n watcher.promise = new Promise<void>((resolvePromise) => {\n const settle = () => {\n watcher.done = true\n resolvePromise()\n }\n child.once('exit', settle)\n child.once('error', settle)\n })\n return watcher\n}\n\nexport async function terminate(child: ChildProcess, exit: ExitWatcher, killGraceMs: number): Promise<void> {\n if (exit.done) return\n child.kill('SIGTERM')\n const forceKill = setTimeout(() => {\n if (!exit.done) child.kill('SIGKILL')\n }, killGraceMs)\n forceKill.unref()\n await exit.promise\n clearTimeout(forceKill)\n}\n\nexport function runToCompletion(child: ChildProcess, label: string): Promise<void> {\n return new Promise<void>((resolvePromise, rejectPromise) => {\n let stderr = ''\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n child.once('error', (error) => {\n rejectPromise(new DeskError(`${label} failed to start: ${error.message}`))\n })\n child.once('exit', (code, signal) => {\n if (code === 0) {\n resolvePromise()\n return\n }\n const detail = stderr.trim()\n rejectPromise(\n new DeskError(\n `${label} exited with code ${code ?? 'unknown'}`\n + `${signal ? ` (${signal})` : ''}${detail ? `: ${detail}` : '.'}`,\n ),\n )\n })\n })\n}\n\n/**\n * Cloud Hypervisor exposes guest vsock ports through a host Unix socket with\n * a line-oriented preamble: the client writes `CONNECT <port>\\n` and the VMM\n * answers `OK <assigned>\\n` before the byte stream becomes the guest\n * connection. The VMM creates the socket during boot, so connection attempts\n * retry until the deadline. The Virtualization.framework helper speaks the\n * same preamble on its own socket.\n *\n * The same loop serves the first connection and every later reconnect, so a\n * reconnect gets `confirmGuest` too — a mid-lease reconnect that trusted the\n * banner would re-adopt exactly the hollow stream the boot path learned not to.\n */\nexport async function connectWithRetry(options: {\n connect: (socketPath: string) => Duplex\n now: () => number\n socketPath: string\n port: number\n timeoutMs: number\n retryDelayMs: number\n /** Ceiling the delay doubles toward; omitted keeps the delay constant. */\n maxRetryDelayMs?: number\n attemptTimeoutMs: number\n exited: ExitWatcher\n /** A dead VMM means something different at boot than it does mid-lease. */\n exitedMessage?: string\n /** Stops the loop early when the caller no longer wants the connection. */\n abandoned?: () => boolean\n}): Promise<Duplex> {\n const deadline = options.now() + options.timeoutMs\n let lastFailure = 'the guest agent never answered'\n let retryDelayMs = options.retryDelayMs\n while (options.now() <= deadline) {\n if (options.exited.done) {\n throw new DeskError(options.exitedMessage ?? 'The VMM exited before the guest agent came up.')\n }\n if (options.abandoned?.() === true) {\n throw new DeskError('the connection attempt was abandoned.')\n }\n try {\n const stream = await attemptHandshake(\n options.connect,\n options.socketPath,\n options.port,\n options.attemptTimeoutMs,\n )\n try {\n await confirmGuest(stream, options.attemptTimeoutMs)\n } catch (error) {\n stream.destroy()\n throw error\n }\n return stream\n } catch (error) {\n lastFailure = errorMessage(error)\n }\n await delay(retryDelayMs)\n if (options.maxRetryDelayMs !== undefined) {\n retryDelayMs = Math.min(retryDelayMs * 2, options.maxRetryDelayMs)\n }\n }\n throw new DeskError(\n `Timed out connecting to the guest agent at ${options.socketPath}: ${lastFailure}`,\n )\n}\n\n/**\n * Prove a guest is behind the handshake by asking it something.\n *\n * Cloud Hypervisor answers `CONNECT <port>` with `OK` whether or not anything\n * in the guest is listening on that port, and only closes the socket a moment\n * later when it finds nobody there. A caller that trusts the banner therefore\n * \"connects\" to a guest that is still booting, gets a closed stream seconds\n * later, and — because a closed machine is not retried — leaves the desk dead\n * for as long as it is leased, with a healthy guest sitting behind it. So the\n * handshake is not the test; a reply is.\n */\nasync function confirmGuest(stream: Duplex, timeoutMs: number): Promise<void> {\n const decoder = new FrameDecoder()\n await new Promise<void>((resolvePromise, rejectPromise) => {\n let settled = false\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n stream.off('data', onData)\n stream.off('close', onClose)\n stream.off('error', finish)\n if (error) rejectPromise(error)\n else resolvePromise()\n }\n const timer = setTimeout(\n () => finish(new DeskError('the guest agent did not answer the first request.')),\n timeoutMs,\n )\n timer.unref?.()\n const onClose = () =>\n finish(new DeskError('the connection closed before the guest agent answered.'))\n const onData = (chunk: Buffer) => {\n let values: unknown[]\n try {\n values = decoder.push(chunk)\n } catch (error) {\n finish(error instanceof Error ? error : new Error(String(error)))\n return\n }\n for (const value of values) {\n // Anything at all proves a guest is there; the reply is parsed for\n // real by the machine once it owns the stream.\n if (value && typeof value === 'object') {\n finish()\n return\n }\n }\n }\n stream.on('data', onData)\n stream.once('close', onClose)\n stream.once('error', finish)\n stream.write(encodeFrame({ id: 'hello', op: 'ping' }))\n })\n}\n\n/**\n * One handshake attempt, which MUST settle.\n *\n * Cloud Hypervisor accepts a connection on the vsock socket whether or not\n * anything in the guest is listening on the port, and when nothing is it may\n * answer nothing at all: no reply, no error, no close. Without a deadline of\n * its own this promise then never settles — and because the caller awaits it\n * inside the retry loop, the loop stops iterating, the overall deadline is\n * never re-checked, and the boot hangs forever rather than failing. That is\n * indistinguishable from a wedged host and it is why every attempt is bounded\n * here as well as in aggregate.\n *\n * A close before the reply line is a refusal: that is how a port with nothing\n * listening presents through Cloud Hypervisor, and the Virtualization.framework\n * helper presents a refused vsock or TCP port the same way.\n */\nexport function attemptHandshake(\n connect: (socketPath: string) => Duplex,\n socketPath: string,\n port: number,\n attemptTimeoutMs: number,\n): Promise<Duplex> {\n return new Promise<Duplex>((resolvePromise, rejectPromise) => {\n let stream: Duplex\n try {\n stream = connect(socketPath)\n } catch (error) {\n rejectPromise(error instanceof Error ? error : new Error(String(error)))\n return\n }\n let banner = ''\n let settled = false\n const timer = setTimeout(() => {\n fail(new DeskError('vsock handshake went unanswered.'))\n }, attemptTimeoutMs)\n // An unref'd timer must not hold the process open on its own.\n timer.unref?.()\n const fail = (error: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n stream.destroy()\n rejectPromise(error)\n }\n const onData = (chunk: Buffer) => {\n banner += chunk.toString('latin1')\n const newline = banner.indexOf('\\n')\n if (newline === -1) {\n if (banner.length > HANDSHAKE_LINE_LIMIT) {\n fail(new DeskError('vsock handshake reply exceeded the line limit.'))\n }\n return\n }\n const line = banner.slice(0, newline)\n const rest = banner.slice(newline + 1)\n stream.off('data', onData)\n stream.off('error', fail)\n if (!line.startsWith('OK ')) {\n fail(new DeskError(`vsock handshake was refused: ${line}`))\n return\n }\n settled = true\n clearTimeout(timer)\n if (rest.length > 0) stream.unshift(Buffer.from(rest, 'latin1'))\n resolvePromise(stream)\n }\n stream.on('data', onData)\n stream.once('error', fail)\n // A close before the banner is a refusal, not a hang.\n stream.once('close', () => fail(new DeskError('vsock handshake closed before a reply.')))\n stream.write(`CONNECT ${port}\\n`)\n })\n}\n\nexport function defaultLauncher(\n command: string,\n args: readonly string[],\n options: { identity?: DeskLauncherIdentity },\n): ChildProcess {\n return spawn(command, [...args], {\n stdio: ['ignore', 'pipe', 'pipe'],\n uid: options.identity?.uid,\n gid: options.identity?.gid,\n })\n}\n\nexport function defaultConnect(socketPath: string): Duplex {\n return createConnection(socketPath)\n}\n\nexport function delay(ms: number): Promise<void> {\n return new Promise<void>((resolvePromise) => {\n const timer = setTimeout(resolvePromise, ms)\n timer.unref()\n })\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n"]}
package/network.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { DeskHandle } from './host.js';
2
+ export interface DeskNetworkCommandRunner {
3
+ run(command: string, args: readonly string[]): Promise<string>;
4
+ }
5
+ export interface DeskNetworkOptions {
6
+ gateway: string;
7
+ dns: string;
8
+ egress: {
9
+ mode: 'proxied';
10
+ httpProxyPort: number;
11
+ httpsProxyPort: number;
12
+ } | {
13
+ mode: 'open';
14
+ };
15
+ chainPrefix?: string;
16
+ allowHostPorts?: readonly number[];
17
+ prefixLength?: number;
18
+ runner?: DeskNetworkCommandRunner;
19
+ enableForwarding?: () => Promise<void>;
20
+ }
21
+ export interface DeskNetworkAddress {
22
+ tap: string;
23
+ guest: string;
24
+ }
25
+ /** Deterministic TAP and locally administered MAC for an unsigned desk index. */
26
+ export declare function deskNetworkIdentity(index: number): {
27
+ tap: string;
28
+ macAddress: string;
29
+ };
30
+ /** Point-to-point TAP with either open or transparent-proxy egress. */
31
+ export declare function createDeskNetwork(options: DeskNetworkOptions): {
32
+ ensure(value: DeskNetworkAddress): Promise<void>;
33
+ teardown(value: DeskNetworkAddress): Promise<void>;
34
+ configureGuest(desk: Pick<DeskHandle, "exec">, value: DeskNetworkAddress): Promise<void>;
35
+ };
36
+ export declare function syncDeskGuestClock(desk: Pick<DeskHandle, 'exec'>, now?: number): Promise<void>;
37
+ //# sourceMappingURL=network.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network.d.ts","sourceRoot":"","sources":["../src/network.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAA;AAExC,MAAM,WAAW,wBAAwB;IACvC,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;CAC/D;AACD,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAA;IACf,GAAG,EAAE,MAAM,CAAA;IACX,MAAM,EAAE;QAAE,IAAI,EAAE,SAAS,CAAC;QAAC,aAAa,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAA;IAC7F,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;IAClC,YAAY,CAAC,EAAE,MAAM,CAA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