@braedonsaunders/appkit-desk 0.8.0 → 0.10.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.
package/plan.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { Buffer } from 'node:buffer';
2
2
  import { createHash } from 'node:crypto';
3
- import { existsSync } from 'node:fs';
3
+ import { existsSync, statSync } from 'node:fs';
4
4
  import { isIP } from 'node:net';
5
5
  import { arch as hostArch, release as hostRelease, tmpdir } from 'node:os';
6
- import { dirname, isAbsolute, join, resolve } from 'node:path';
6
+ import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
7
7
  export const DEFAULT_VMM_PATH = '/usr/bin/cloud-hypervisor';
8
8
  export const DEFAULT_KVM_PATH = '/dev/kvm';
9
9
  export const DEFAULT_QEMU_IMG_PATH = '/usr/bin/qemu-img';
@@ -11,6 +11,12 @@ export const DEFAULT_RUNTIME_DIR = '/run/appkit-desk';
11
11
  export const DEFAULT_MEMORY_MB = 384;
12
12
  export const DEFAULT_VCPUS = 2;
13
13
  export const DEFAULT_KERNEL_CMDLINE = 'root=/dev/vda rw quiet';
14
+ /**
15
+ * Where a Cloud Hypervisor desk looks for `virtiofsd` when `virtiofsdPath` is
16
+ * not set and it is not on `PATH`: Debian's and Fedora's package location.
17
+ */
18
+ export const DEFAULT_VIRTIOFSD_PATH = '/usr/libexec/virtiofsd';
19
+ export const DEFAULT_VIRTIOFSD_SANDBOX = 'namespace';
14
20
  /**
15
21
  * The guest network Virtualization.framework desks get from the helper's NAT:
16
22
  * the same addresses QEMU's user networking uses, so they are unsurprising in
@@ -26,6 +32,10 @@ export const VZ_GUEST_CID = 3;
26
32
  const MIN_DARWIN_MAJOR = 23;
27
33
  /** `sun_path` holds 104 bytes on Darwin, including the terminator. */
28
34
  const DARWIN_SOCKET_PATH_LIMIT = 103;
35
+ /** `sun_path` holds 108 bytes on Linux, including the terminator. */
36
+ const LINUX_SOCKET_PATH_LIMIT = 107;
37
+ /** Linux's virtio-fs tag field is 36 bytes; Virtualization.framework enforces the same. */
38
+ const SHARE_TAG_PATTERN = /^[a-z0-9][a-z0-9-]{0,35}$/;
29
39
  const DESK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
30
40
  const TAP_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,14}$/;
31
41
  const MAC_ADDRESS_PATTERN = /^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$/i;
@@ -75,6 +85,9 @@ export function cleanDeskId(value) {
75
85
  }
76
86
  export function buildDeskLaunchPlan(options, dependencies = {}) {
77
87
  const hypervisor = options.hypervisor ?? 'cloud-hypervisor';
88
+ if (options.memoryRestoreMode !== undefined && (options.memoryRestoreMode !== 'copyonwrite' || hypervisor !== 'cloud-hypervisor')) {
89
+ throw new DeskError('Copy-on-write restore requires Cloud Hypervisor.');
90
+ }
78
91
  if (hypervisor === 'virtualization')
79
92
  return buildVirtualizationPlan(options, dependencies);
80
93
  if (hypervisor !== 'cloud-hypervisor') {
@@ -88,6 +101,7 @@ export function buildDeskLaunchPlan(options, dependencies = {}) {
88
101
  function buildCloudHypervisorPlan(options, dependencies) {
89
102
  const pathExists = dependencies.pathExists ?? existsSync;
90
103
  const deviceExists = dependencies.deviceExists ?? existsSync;
104
+ const isDirectory = dependencies.isDirectory ?? directoryExists;
91
105
  const deskId = cleanDeskId(options.deskId);
92
106
  const kvmPath = absolutePath(options.kvmPath ?? DEFAULT_KVM_PATH, 'kvmPath');
93
107
  if (!deviceExists(kvmPath)) {
@@ -140,6 +154,15 @@ function buildCloudHypervisorPlan(options, dependencies) {
140
154
  // guest instead of a missing snapshot out here.
141
155
  throw new DeskError(`Desk ${deskId} has no snapshot to restore at ${snapshotDir}`);
142
156
  }
157
+ const attachments = cleanAttachments(options.readOnlyAttachments, pathExists);
158
+ const shares = cloudHypervisorShares(cleanShares(options.shares, isDirectory), {
159
+ deskId,
160
+ runtimeDir,
161
+ virtiofsdPath: options.virtiofsdPath,
162
+ sandbox: options.virtiofsdSandbox ?? DEFAULT_VIRTIOFSD_SANDBOX,
163
+ pathExists,
164
+ searchPath: dependencies.searchPath ?? process.env.PATH ?? '',
165
+ });
143
166
  const create = pathExists(overlayPath)
144
167
  ? null
145
168
  : {
@@ -166,18 +189,24 @@ function buildCloudHypervisorPlan(options, dependencies) {
166
189
  // that died in that window would, on the next start, replay this memory
167
190
  // against a disk that had moved on. That is corruption, not a stale cache.
168
191
  //
169
- // So the guest comes back PAUSED, the caller destroys the snapshot while
170
- // nothing can write, and only then is the VM resumed.
192
+ // The guest comes back PAUSED; before it runs, the caller must make the
193
+ // snapshot unavailable for replay. File-backed restores keep their retired
194
+ // source unchanged until the VMM exits.
171
195
  //
172
196
  // The tap is reopened BY NAME from the snapshotted config. That is the detail
173
197
  // that makes this possible at all: Cloud Hypervisor's `net_fds` restore
174
198
  // parameter exists for VMs whose tap was passed as a file descriptor, and
175
199
  // producing one from Node would mean an ioctl(TUNSETIFF) it cannot make.
176
200
  // Because `deskPlan` configures `--net tap=<name>`, there is nothing to pass.
201
+ //
202
+ // Shares are in the snapshotted config too, by socket path, with each
203
+ // daemon's state. What the snapshot cannot hold is a running `virtiofsd`, so
204
+ // the backend starts the same daemons on the same sockets before this VMM
205
+ // either way, and the VMM loads their state back into them.
177
206
  const args = restoring
178
207
  ? [
179
208
  '--api-socket', apiSocketPath,
180
- '--restore', `source_url=file://${snapshotDir},resume=false`,
209
+ '--restore', `source_url=file://${snapshotDir},resume=false${options.memoryRestoreMode === 'copyonwrite' ? ',memory_restore_mode=copyonwrite' : ''}`,
181
210
  ]
182
211
  : [
183
212
  '--api-socket', apiSocketPath,
@@ -188,11 +217,18 @@ function buildCloudHypervisorPlan(options, dependencies) {
188
217
  '--cmdline', kernelCmdline,
189
218
  // Be explicit that the disk is raw: CH deprecated image-format auto-detection
190
219
  // and warns without image_type; there is never a qcow2 overlay here.
191
- '--disk', `path=${overlayPath},image_type=raw`,
192
- '--memory', `size=${memoryMb}M`,
220
+ '--disk', `path=${overlayPath},image_type=raw`, ...attachments.filter(a => a.kind === 'block').map(a => `path=${a.path},readonly=on,image_type=raw`),
221
+ ...attachments.filter(a => a.kind === 'pmem').flatMap(a => ['--pmem', `file=${a.path},discard_writes=on`]),
222
+ // vhost-user devices map guest RAM into their daemon, so it must be
223
+ // shared memory; a desk without shares keeps private memory.
224
+ '--memory', `size=${memoryMb}M${shares.length === 0 ? '' : ',shared=on'}`,
225
+ ...(options.freePageReporting ? ['--balloon', 'size=0,free_page_reporting=on'] : []),
193
226
  '--cpus', `boot=${vcpus}`,
194
227
  '--vsock', `cid=${vsockCid},socket=${vsockSocketPath}`,
195
228
  '--net', `tap=${tapDevice},mac=${macAddress}`,
229
+ ...(shares.length === 0
230
+ ? []
231
+ : ['--fs', ...shares.map((share) => `tag=${share.tag},socket=${share.socketPath}`)]),
196
232
  '--serial', 'off',
197
233
  '--console', 'off',
198
234
  ];
@@ -205,6 +241,7 @@ function buildCloudHypervisorPlan(options, dependencies) {
205
241
  api: { socketPath: apiSocketPath },
206
242
  tap: { device: tapDevice, mac: macAddress },
207
243
  snapshot: { dir: snapshotDir, restoring },
244
+ shares,
208
245
  memoryMb,
209
246
  vcpus,
210
247
  kernelPath,
@@ -222,10 +259,17 @@ function buildCloudHypervisorPlan(options, dependencies) {
222
259
  */
223
260
  function buildVirtualizationPlan(options, dependencies) {
224
261
  const pathExists = dependencies.pathExists ?? existsSync;
262
+ if (options.readOnlyAttachments?.length)
263
+ throw new DeskError('Read-only attachments require Cloud Hypervisor.');
264
+ if (options.freePageReporting)
265
+ throw new DeskError('Free-page reporting requires Cloud Hypervisor.');
225
266
  const deskId = cleanDeskId(options.deskId);
226
267
  if (options.tapDevice !== undefined) {
227
268
  throw new DeskError('tapDevice applies to Cloud Hypervisor desks; a Virtualization.framework desk has no TAP.');
228
269
  }
270
+ if (options.virtiofsdPath !== undefined || options.virtiofsdSandbox !== undefined) {
271
+ throw new DeskError('virtiofsdPath and virtiofsdSandbox apply to Cloud Hypervisor desks; Virtualization.framework serves shares itself.');
272
+ }
229
273
  const kernelPath = absolutePath(options.kernelPath, 'kernelPath');
230
274
  if (!pathExists(kernelPath)) {
231
275
  throw new DeskError(`Guest kernel does not exist: ${kernelPath}`);
@@ -258,6 +302,7 @@ function buildVirtualizationPlan(options, dependencies) {
258
302
  throw new DeskError(`Desk ${deskId} has no snapshot to restore at ${snapshotDir}`);
259
303
  }
260
304
  const network = cleanGuestNetwork(options.guestNetwork ?? {});
305
+ const shares = cleanShares(options.shares, dependencies.isDirectory ?? directoryExists);
261
306
  return {
262
307
  hypervisor: 'virtualization',
263
308
  deskId,
@@ -273,6 +318,7 @@ function buildVirtualizationPlan(options, dependencies) {
273
318
  ...network,
274
319
  },
275
320
  snapshot: { dir: snapshotDir, restoring },
321
+ shares,
276
322
  memoryMb,
277
323
  vcpus,
278
324
  kernelPath,
@@ -281,6 +327,116 @@ function buildVirtualizationPlan(options, dependencies) {
281
327
  launcherIdentity: cleanLauncherIdentity(options.launcherIdentity),
282
328
  };
283
329
  }
330
+ /** Reject ambiguous Cloud Hypervisor key-value arguments and unpinned images. */
331
+ export function cleanAttachments(attachments, pathExists) {
332
+ if (attachments === undefined)
333
+ return [];
334
+ if (!Array.isArray(attachments))
335
+ throw new DeskError('readOnlyAttachments must be an array.');
336
+ return attachments.map((attachment, index) => {
337
+ if (!attachment || !['block', 'pmem'].includes(attachment.kind) || !/^[a-f0-9]{64}$/.test(attachment.sha256))
338
+ throw new DeskError(`Invalid readOnlyAttachments[${index}].`);
339
+ const path = absolutePath(attachment.path, `readOnlyAttachments[${index}].path`);
340
+ if (path.includes(',') || !pathExists(path))
341
+ throw new DeskError(`Invalid attachment path: ${path}`);
342
+ return { path, kind: attachment.kind, sha256: attachment.sha256 };
343
+ });
344
+ }
345
+ /** Validate shares as given: tags, absolute existing directories, explicit access. */
346
+ function cleanShares(shares, isDirectory) {
347
+ if (shares === undefined)
348
+ return [];
349
+ if (!Array.isArray(shares))
350
+ throw new DeskError('shares must be an array.');
351
+ const tags = new Set();
352
+ return shares.map((share, index) => {
353
+ const field = `shares[${index}]`;
354
+ if (typeof share !== 'object' || share === null)
355
+ throw new DeskError(`${field} must be an object.`);
356
+ if (typeof share.tag !== 'string' || !SHARE_TAG_PATTERN.test(share.tag)) {
357
+ throw new DeskError(`${field}.tag must be 1–36 lowercase letters, digits, or hyphens, starting with a letter or digit.`);
358
+ }
359
+ if (tags.has(share.tag))
360
+ throw new DeskError(`${field}.tag ${share.tag} is already used by another share.`);
361
+ tags.add(share.tag);
362
+ if (typeof share.path !== 'string')
363
+ throw new DeskError(`${field}.path must be an absolute path.`);
364
+ const path = absolutePath(share.path, `${field}.path`);
365
+ if (!isDirectory(path))
366
+ throw new DeskError(`${field}.path is not an existing directory: ${path}`);
367
+ if (typeof share.readOnly !== 'boolean')
368
+ throw new DeskError(`${field}.readOnly must be a boolean.`);
369
+ return { tag: share.tag, path, readOnly: share.readOnly };
370
+ });
371
+ }
372
+ /**
373
+ * One `virtiofsd` per share. `--cache=auto` lets the guest cache for a second
374
+ * at a time, so changes the host makes under a share reach running guests;
375
+ * `always` would let a guest keep serving a file the host has replaced.
376
+ * `--readonly` is the enforcement for a read-only share — the guest is never
377
+ * trusted to honour a read-only mount.
378
+ *
379
+ * The migration flags are for parking. Cloud Hypervisor carries the daemon's
380
+ * state — the files and directories the guest holds — inside a snapshot, and
381
+ * hands it to the fresh daemon on restore, which reopens each by path. A file
382
+ * that has no path by then (unlinked on the host, or by the guest while held
383
+ * open) becomes an error for the guest to see on that file alone, rather than
384
+ * a restore that fails and costs the whole desk its memory.
385
+ */
386
+ function cloudHypervisorShares(shares, context) {
387
+ if (shares.length === 0)
388
+ return [];
389
+ if (context.sandbox !== 'namespace' && context.sandbox !== 'chroot') {
390
+ throw new DeskError("virtiofsdSandbox must be 'namespace' or 'chroot'.");
391
+ }
392
+ const command = resolveVirtiofsd(context.virtiofsdPath, context.pathExists, context.searchPath);
393
+ return shares.map((share) => {
394
+ // A dot cannot appear in a tag, so `<desk>.<tag>` names one socket for
395
+ // exactly one desk and share even though desk IDs may contain hyphens.
396
+ const socketPath = join(context.runtimeDir, `desk-${context.deskId}.${share.tag}.fs.sock`);
397
+ if (Buffer.byteLength(socketPath) > LINUX_SOCKET_PATH_LIMIT) {
398
+ throw new DeskError(`Socket path ${socketPath} is longer than the ${LINUX_SOCKET_PATH_LIMIT} bytes Linux allows; `
399
+ + 'use a shorter runtimeDir, deskId, or share tag.');
400
+ }
401
+ return {
402
+ ...share,
403
+ socketPath,
404
+ daemon: {
405
+ command,
406
+ args: [
407
+ `--socket-path=${socketPath}`,
408
+ `--shared-dir=${share.path}`,
409
+ `--sandbox=${context.sandbox}`,
410
+ '--cache=auto',
411
+ '--migration-mode=find-paths',
412
+ '--migration-on-error=guest-error',
413
+ ...(share.readOnly ? ['--readonly'] : []),
414
+ ],
415
+ },
416
+ };
417
+ });
418
+ }
419
+ function resolveVirtiofsd(configured, pathExists, searchPath) {
420
+ if (configured !== undefined) {
421
+ const path = absolutePath(configured, 'virtiofsdPath');
422
+ if (!pathExists(path)) {
423
+ throw new DeskError(`virtiofsd was not found at ${path}. Install virtiofsd or configure virtiofsdPath.`);
424
+ }
425
+ return path;
426
+ }
427
+ const candidates = [
428
+ ...searchPath.split(delimiter).filter((entry) => isAbsolute(entry)).map((entry) => join(entry, 'virtiofsd')),
429
+ DEFAULT_VIRTIOFSD_PATH,
430
+ ];
431
+ const found = candidates.find((candidate) => pathExists(candidate));
432
+ if (found === undefined) {
433
+ throw new DeskError(`virtiofsd was not found on PATH or at ${DEFAULT_VIRTIOFSD_PATH}. Install virtiofsd 1.13 or later, or configure virtiofsdPath.`);
434
+ }
435
+ return found;
436
+ }
437
+ function directoryExists(path) {
438
+ return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
439
+ }
284
440
  function cleanGuestNetwork(options) {
285
441
  if (options.allowLan !== undefined && typeof options.allowLan !== 'boolean') {
286
442
  throw new DeskError('guestNetwork.allowLan must be a boolean.');
package/plan.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plan.js","sourceRoot":"","sources":["../src/plan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAA;AAC/B,OAAO,EAAE,IAAI,IAAI,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAC1E,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAE9D,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAA;AAC3D,MAAM,CAAC,MAAM,gBAAgB,GAAG,UAAU,CAAA;AAC1C,MAAM,CAAC,MAAM,qBAAqB,GAAG,mBAAmB,CAAA;AACxD,MAAM,CAAC,MAAM,mBAAmB,GAAG,kBAAkB,CAAA;AACrD,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAA;AACpC,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAA;AAC9B,MAAM,CAAC,MAAM,sBAAsB,GAAG,wBAAwB,CAAA;AAC9D;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,WAAW,CAAA;AACnD,MAAM,CAAC,MAAM,0BAA0B,GAAG,UAAU,CAAA;AACpD,MAAM,CAAC,MAAM,wBAAwB,GAAG,EAAE,CAAA;AAC1C,MAAM,CAAC,MAAM,cAAc,GAAsB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;AACvE,0EAA0E;AAC1E,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAA;AAC7B,0FAA0F;AAC1F,MAAM,gBAAgB,GAAG,EAAE,CAAA;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K,CAAC,EAAE,CAAC;QACjC,MAAM,IAAI,SAAS,CAAC,GAAG,KAAK,4BAA4B,CAAC,CAAA;IAC3D,CAAC;IACD,OAAO,OAAO,CAAC,KAAK,CAAC,CAAA;AACvB,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,KAAa;IACnD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,SAAS,CAAC,GAAG,KAAK,8BAA8B,CAAC,CAAA;IAC7D,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import { Buffer } from 'node:buffer'\nimport { createHash } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport { isIP } from 'node:net'\nimport { arch as hostArch, release as hostRelease, tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\n\nexport const DEFAULT_VMM_PATH = '/usr/bin/cloud-hypervisor'\nexport const DEFAULT_KVM_PATH = '/dev/kvm'\nexport const DEFAULT_QEMU_IMG_PATH = '/usr/bin/qemu-img'\nexport const DEFAULT_RUNTIME_DIR = '/run/appkit-desk'\nexport const DEFAULT_MEMORY_MB = 384\nexport const DEFAULT_VCPUS = 2\nexport const DEFAULT_KERNEL_CMDLINE = 'root=/dev/vda rw quiet'\n/**\n * The guest network Virtualization.framework desks get from the helper's NAT:\n * the same addresses QEMU's user networking uses, so they are unsurprising in\n * a guest. Nothing outside the helper ever sees them.\n */\nexport const DEFAULT_VZ_GUEST_ADDRESS = '10.0.2.15'\nexport const DEFAULT_VZ_GATEWAY_ADDRESS = '10.0.2.2'\nexport const DEFAULT_VZ_PREFIX_LENGTH = 24\nexport const DEFAULT_VZ_DNS: readonly string[] = ['1.1.1.1', '9.9.9.9']\n/** Virtualization.framework always gives the guest vsock context ID 3. */\nexport const VZ_GUEST_CID = 3\n/** The first Darwin release with Virtualization.framework save and restore (macOS 14). */\nconst MIN_DARWIN_MAJOR = 23\n/** `sun_path` holds 104 bytes on Darwin, including the terminator. */\nconst DARWIN_SOCKET_PATH_LIMIT = 103\n\nconst DESK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/\nconst TAP_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,14}$/\nconst MAC_ADDRESS_PATTERN = /^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$/i\n/** vsock CIDs 0–2 are reserved (hypervisor, loopback, host). */\nconst MIN_GUEST_CID = 3\nconst MAX_GUEST_CID = 0xffff_fffe\n\n/**\n * Every failure this package raises. The `name` is annotated as `string`\n * rather than left to infer its literal so a subclass can narrow the meaning\n * of a failure — see `DeskRequestFateUnknownError` — without callers losing\n * the one `instanceof DeskError` they already check.\n */\nexport class DeskError extends Error {\n override readonly name: string = 'DeskError'\n}\n\nexport interface DeskLauncherIdentity {\n /** Host/container UID used to invoke the VMM and image tooling. */\n uid: number\n /** Host/container GID used to invoke the VMM and image tooling. */\n gid: number\n}\n\n/**\n * Which hypervisor a plan is for: Cloud Hypervisor over KVM on Linux, or\n * Apple's Virtualization.framework through the `appkit-desk-vz` helper on an\n * Apple silicon Mac.\n */\nexport type DeskHypervisor = 'cloud-hypervisor' | 'virtualization'\n\n/**\n * The guest network of a Virtualization.framework desk. The helper runs a\n * userspace NAT: the guest reaches the public internet and nothing else unless\n * `allowLan` is set — no RFC 1918 space, link-local, CGNAT, or the Mac itself.\n */\nexport interface DeskGuestNetworkOptions {\n /** Let the guest reach the Mac's LAN, link-local and CGNAT space, and the Mac. */\n allowLan?: boolean\n /** The address the helper's DHCP server leases the guest. */\n guestAddress?: string\n /** The helper's own address on the link: the guest's router. */\n gatewayAddress?: string\n prefixLength?: number\n /** Resolvers the guest is handed; the first also answers DNS sent to the gateway. */\n dns?: readonly string[]\n}\n\nexport interface DeskLaunchPlanOptions {\n deskId: string\n /** Defaults to `cloud-hypervisor`. */\n hypervisor?: DeskHypervisor\n /** Cloud Hypervisor only: the VMM binary. */\n vmmPath?: string\n /** Cloud Hypervisor only: the KVM device. */\n kvmPath?: string\n qemuImgPath?: string\n /** Absolute path of the kernel image the microVM boots. */\n kernelPath: string\n /**\n * Absolute path of an initramfs. Required whenever the kernel loads its\n * root-filesystem or virtio drivers as modules — a stock distro cloud kernel\n * panics with \"VFS: Unable to mount root fs\" if it boots without one. Omit\n * only for a kernel with virtio_blk/ext4 built in.\n */\n initramfsPath?: string\n /** Absolute path of the golden raw base image every desk clones. */\n baseImagePath: string\n /** Absolute path of this desk's copy-on-write overlay (a raw reflink clone). */\n overlayPath: string\n memoryMb?: number\n vcpus?: number\n /**\n * Guest vsock context ID; must be unique among resident desks. Cloud\n * Hypervisor only — a Virtualization.framework guest is always CID 3, and\n * its vsock is private to its helper.\n */\n vsockCid: number\n /**\n * Directory holding the desk's control sockets. Defaults to\n * `/run/appkit-desk` for Cloud Hypervisor and `<os tmpdir>/appkit-desk` for\n * Virtualization.framework.\n */\n runtimeDir?: string\n /** Cloud Hypervisor only: host TAP device name; derived from the CID when omitted. */\n tapDevice?: string\n /**\n * Guest MAC address. Derived from the CID for Cloud Hypervisor, and from the\n * desk ID for Virtualization.framework, whose restore needs the same NIC.\n */\n macAddress?: string\n /** Virtualization.framework only: the helper's NAT network and fence. */\n guestNetwork?: DeskGuestNetworkOptions\n kernelCmdline?: string\n launcherIdentity?: DeskLauncherIdentity\n /**\n * Where this desk's memory snapshot lives. Defaults beside the overlay, which\n * is the volume sized for desk state — a snapshot is roughly `memoryMb` of\n * guest RAM, so it does not belong on a runtime tmpfs.\n */\n snapshotDir?: string\n /**\n * Resume from that snapshot instead of booting the kernel.\n *\n * A restored VM continues with its process tree intact, which is the whole\n * point of parking with memory rather than shutting down: an agent's in-guest\n * daemon survives. Refused when the snapshot is not there, rather than falling\n * back to a cold boot — a silent cold boot is how a desk loses the state it\n * was promised to have kept.\n */\n restore?: boolean\n}\n\n/** What every plan carries, whichever hypervisor runs it. */\nexport interface DeskLaunchPlanBase {\n deskId: string\n overlay: {\n path: string\n basePath: string\n /** The overlay-creation step, or `null` when the overlay already exists. */\n create: { command: string; args: string[] } | null\n }\n /**\n * The host Unix socket the guest's vsock is reached through, with Cloud\n * Hypervisor's hybrid-vsock preamble: write `CONNECT <port>\\n`, read\n * `OK <n>\\n`, then the stream is the guest connection.\n */\n vsock: { cid: number; socketPath: string }\n /** Where a memory snapshot of this desk is written, and read back from. */\n snapshot: { dir: string; restoring: boolean }\n memoryMb: number\n vcpus: number\n kernelPath: string\n /** Resolved initramfs path, or `null` when the kernel needs none. */\n initramfsPath: string | null\n kernelCmdline: string\n launcherIdentity?: DeskLauncherIdentity\n}\n\n/**\n * The complete Cloud Hypervisor invocation as inspectable data. Nothing here\n * has been spawned: tests, audit logs, and readiness screens can assert on the\n * exact argv a desk would boot with.\n */\nexport interface CloudHypervisorLaunchPlan extends DeskLaunchPlanBase {\n hypervisor: 'cloud-hypervisor'\n vmm: { command: string; args: string[] }\n api: { socketPath: string }\n tap: { device: string; mac: string }\n}\n\n/**\n * A Virtualization.framework desk as inspectable data: what the helper is\n * asked to boot. The helper path belongs to the backend, not the plan.\n */\nexport interface VirtualizationLaunchPlan extends DeskLaunchPlanBase {\n hypervisor: 'virtualization'\n /**\n * The host Unix socket guest TCP ports are reached through, with the same\n * preamble as `vsock`: `CONNECT <tcp port>\\n` answered by `OK <n>\\n` once\n * the guest accepts, or a close with nothing written when it refuses.\n */\n ports: { socketPath: string }\n network: {\n mac: string\n allowLan: boolean\n guestAddress: string\n gatewayAddress: string\n prefixLength: number\n dns: string[]\n }\n}\n\nexport type DeskLaunchPlan = CloudHypervisorLaunchPlan | VirtualizationLaunchPlan\n\n/**\n * Whether this host can run desks at all. On Linux: a usable `/dev/kvm` and\n * the Cloud Hypervisor binary. On macOS: Apple silicon, macOS 14 or later (the\n * first with Virtualization.framework save and restore), and an existing\n * `appkit-desk-vz` helper at `helperPath`. Signature and entitlement are checked\n * by macOS on execution, not by this probe. Every check is injectable and the\n * answer is fail-closed — a host missing any of them gets no desk capability\n * rather than a degraded one.\n */\nexport function isDeskSupported(options: {\n platform?: NodeJS.Platform\n kvmPath?: string\n vmmPath?: string\n /** macOS: the signed `appkit-desk-vz` helper. Required there. */\n helperPath?: string\n arch?: string\n /** The kernel release, as `os.release()` reports it. */\n osRelease?: string\n pathExists?: (path: string) => boolean\n} = {}): boolean {\n const platform = options.platform ?? process.platform\n const pathExists = options.pathExists ?? existsSync\n if (platform === 'darwin') {\n const major = Number.parseInt((options.osRelease ?? hostRelease()).split('.')[0] ?? '', 10)\n return (\n (options.arch ?? hostArch()) === 'arm64'\n && Number.isInteger(major)\n && major >= MIN_DARWIN_MAJOR\n && options.helperPath !== undefined\n && isAbsolute(options.helperPath)\n && pathExists(options.helperPath)\n )\n }\n return (\n platform === 'linux'\n && pathExists(options.kvmPath ?? DEFAULT_KVM_PATH)\n && pathExists(options.vmmPath ?? DEFAULT_VMM_PATH)\n )\n}\n\n/** Validate a desk identifier, which is used in socket paths and device names. */\nexport function cleanDeskId(value: string): string {\n if (!DESK_ID_PATTERN.test(value)) {\n throw new DeskError(\n 'deskId must be 1–64 letters, numbers, dots, underscores, or hyphens.',\n )\n }\n return value\n}\n\nexport interface DeskLaunchPlanDependencies {\n pathExists?: (path: string) => boolean\n deviceExists?: (path: string) => boolean\n}\n\n/**\n * Build the deterministic launch plan without spawning anything. Fail closed:\n * a missing `/dev/kvm` or VMM binary (Cloud Hypervisor), kernel, base image,\n * or overlay directory throws instead of producing a plan that cannot boot.\n */\nexport function buildDeskLaunchPlan(\n options: DeskLaunchPlanOptions & { hypervisor: 'virtualization' },\n dependencies?: DeskLaunchPlanDependencies,\n): VirtualizationLaunchPlan\nexport function buildDeskLaunchPlan(\n options: DeskLaunchPlanOptions & { hypervisor?: 'cloud-hypervisor' },\n dependencies?: DeskLaunchPlanDependencies,\n): CloudHypervisorLaunchPlan\nexport function buildDeskLaunchPlan(\n options: DeskLaunchPlanOptions,\n dependencies?: DeskLaunchPlanDependencies,\n): DeskLaunchPlan\nexport function buildDeskLaunchPlan(\n options: DeskLaunchPlanOptions,\n dependencies: DeskLaunchPlanDependencies = {},\n): DeskLaunchPlan {\n const hypervisor = options.hypervisor ?? 'cloud-hypervisor'\n if (hypervisor === 'virtualization') return buildVirtualizationPlan(options, dependencies)\n if (hypervisor !== 'cloud-hypervisor') {\n throw new DeskError(`Unknown hypervisor: ${String(hypervisor)}`)\n }\n if (options.guestNetwork !== undefined) {\n throw new DeskError(\n 'guestNetwork applies to Virtualization.framework desks; a Cloud Hypervisor desk is networked with createDeskNetwork.',\n )\n }\n return buildCloudHypervisorPlan(options, dependencies)\n}\n\nfunction buildCloudHypervisorPlan(\n options: DeskLaunchPlanOptions,\n dependencies: DeskLaunchPlanDependencies,\n): CloudHypervisorLaunchPlan {\n const pathExists = dependencies.pathExists ?? existsSync\n const deviceExists = dependencies.deviceExists ?? existsSync\n const deskId = cleanDeskId(options.deskId)\n const kvmPath = absolutePath(options.kvmPath ?? DEFAULT_KVM_PATH, 'kvmPath')\n if (!deviceExists(kvmPath)) {\n throw new DeskError(\n `KVM is not available at ${kvmPath}. Desks require hardware virtualization; `\n + 'there is no software-emulation fallback.',\n )\n }\n const vmmPath = absolutePath(options.vmmPath ?? DEFAULT_VMM_PATH, 'vmmPath')\n if (!pathExists(vmmPath)) {\n throw new DeskError(\n `Cloud Hypervisor was not found at ${vmmPath}. Install cloud-hypervisor or configure vmmPath.`,\n )\n }\n const kernelPath = absolutePath(options.kernelPath, 'kernelPath')\n if (!pathExists(kernelPath)) {\n throw new DeskError(`Guest kernel does not exist: ${kernelPath}`)\n }\n const initramfsPath =\n options.initramfsPath === undefined\n ? null\n : absolutePath(options.initramfsPath, 'initramfsPath')\n if (initramfsPath !== null && !pathExists(initramfsPath)) {\n throw new DeskError(`Initramfs does not exist: ${initramfsPath}`)\n }\n const baseImagePath = absolutePath(options.baseImagePath, 'baseImagePath')\n if (!pathExists(baseImagePath)) {\n throw new DeskError(`Base image does not exist: ${baseImagePath}`)\n }\n const overlayPath = absolutePath(options.overlayPath, 'overlayPath')\n const overlayDirectory = dirname(overlayPath)\n if (!pathExists(overlayDirectory)) {\n throw new DeskError(`Overlay directory does not exist: ${overlayDirectory}`)\n }\n const memoryMb = positiveInteger(options.memoryMb ?? DEFAULT_MEMORY_MB, 'memoryMb')\n const vcpus = positiveInteger(options.vcpus ?? DEFAULT_VCPUS, 'vcpus')\n const vsockCid = cleanCid(options.vsockCid)\n const runtimeDir = absolutePath(options.runtimeDir ?? DEFAULT_RUNTIME_DIR, 'runtimeDir')\n const tapDevice = cleanTapDevice(options.tapDevice ?? defaultTapDevice(vsockCid))\n const macAddress = cleanMacAddress(options.macAddress ?? defaultMacAddress(vsockCid))\n const kernelCmdline = options.kernelCmdline ?? DEFAULT_KERNEL_CMDLINE\n const launcherIdentity = cleanLauncherIdentity(options.launcherIdentity)\n const vsockSocketPath = join(runtimeDir, `desk-${deskId}.vsock`)\n const apiSocketPath = join(runtimeDir, `desk-${deskId}.api.sock`)\n // Beside the overlay by default: a snapshot is the guest's RAM, so it belongs\n // on the volume provisioned for desk state rather than on a runtime tmpfs.\n const snapshotDir = options.snapshotDir\n ? absolutePath(options.snapshotDir, 'snapshotDir')\n : join(overlayDirectory, `${deskId}.snapshot`)\n const restoring = options.restore === true\n if (restoring && !pathExists(snapshotDir)) {\n // Refused rather than silently cold-booted. A caller asking to restore has\n // been told this desk kept its memory; quietly booting a fresh kernel would\n // lose the process tree it was relying on and look like a crash inside the\n // guest instead of a missing snapshot out here.\n throw new DeskError(`Desk ${deskId} has no snapshot to restore at ${snapshotDir}`)\n }\n\n const create = pathExists(overlayPath)\n ? null\n : {\n // Cloud Hypervisor cannot follow disk backing chains: a qcow2 overlay\n // over a qcow2/raw base is rejected with UnsupportedFeature /\n // MaxNestingDepthExceeded. So the overlay is a plain raw file, cloned\n // from the raw base with `cp --reflink=auto` — an instant, block-sharing\n // copy-on-write clone on XFS/Btrfs and a graceful full-copy fallback on\n // ext4. Either way CH boots the resulting raw file with no backing chain.\n command: 'cp',\n args: ['--reflink=auto', baseImagePath, overlayPath],\n }\n\n // A restoring VMM is handed the snapshot and nothing else.\n //\n // The snapshot carries the whole machine config — memory size, cpus, disk,\n // vsock, net — so passing `--kernel`/`--disk` alongside `--restore` is not\n // redundant, it is rejected.\n //\n // `resume=false` is deliberate, and it is the difference between this being\n // safe and being a data-loss bug. A memory snapshot is only valid against the\n // disk as it stood when the snapshot was taken. Resume the guest in this same\n // spawn and it starts writing immediately, so for as long as the snapshot\n // still exists there are two valid-looking pasts for one desk — and a host\n // that died in that window would, on the next start, replay this memory\n // against a disk that had moved on. That is corruption, not a stale cache.\n //\n // So the guest comes back PAUSED, the caller destroys the snapshot while\n // nothing can write, and only then is the VM resumed.\n //\n // The tap is reopened BY NAME from the snapshotted config. That is the detail\n // that makes this possible at all: Cloud Hypervisor's `net_fds` restore\n // parameter exists for VMs whose tap was passed as a file descriptor, and\n // producing one from Node would mean an ioctl(TUNSETIFF) it cannot make.\n // Because `deskPlan` configures `--net tap=<name>`, there is nothing to pass.\n const args = restoring\n ? [\n '--api-socket', apiSocketPath,\n '--restore', `source_url=file://${snapshotDir},resume=false`,\n ]\n : [\n '--api-socket', apiSocketPath,\n '--kernel', kernelPath,\n // A modular distro kernel needs its initramfs to bring up virtio_blk and\n // mount root; omitted only for a kernel with those drivers built in.\n ...(initramfsPath === null ? [] : ['--initramfs', initramfsPath]),\n '--cmdline', kernelCmdline,\n // Be explicit that the disk is raw: CH deprecated image-format auto-detection\n // and warns without image_type; there is never a qcow2 overlay here.\n '--disk', `path=${overlayPath},image_type=raw`,\n '--memory', `size=${memoryMb}M`,\n '--cpus', `boot=${vcpus}`,\n '--vsock', `cid=${vsockCid},socket=${vsockSocketPath}`,\n '--net', `tap=${tapDevice},mac=${macAddress}`,\n '--serial', 'off',\n '--console', 'off',\n ]\n\n return {\n hypervisor: 'cloud-hypervisor',\n deskId,\n vmm: { command: vmmPath, args },\n overlay: { path: overlayPath, basePath: baseImagePath, create },\n vsock: { cid: vsockCid, socketPath: vsockSocketPath },\n api: { socketPath: apiSocketPath },\n tap: { device: tapDevice, mac: macAddress },\n snapshot: { dir: snapshotDir, restoring },\n memoryMb,\n vcpus,\n kernelPath,\n initramfsPath,\n kernelCmdline,\n launcherIdentity,\n }\n}\n\n/**\n * The Virtualization.framework plan. The same fail-closed checks on the guest\n * assets; no KVM or VMM binary, because the backend owns the helper; and the\n * overlay is an APFS clone (`cp -c`), which is to APFS what `--reflink=auto`\n * is to XFS: instant and block-sharing. A volume that cannot clone must be\n * replaced with one that supports it.\n */\nfunction buildVirtualizationPlan(\n options: DeskLaunchPlanOptions,\n dependencies: DeskLaunchPlanDependencies,\n): VirtualizationLaunchPlan {\n const pathExists = dependencies.pathExists ?? existsSync\n const deskId = cleanDeskId(options.deskId)\n if (options.tapDevice !== undefined) {\n throw new DeskError('tapDevice applies to Cloud Hypervisor desks; a Virtualization.framework desk has no TAP.')\n }\n const kernelPath = absolutePath(options.kernelPath, 'kernelPath')\n if (!pathExists(kernelPath)) {\n throw new DeskError(`Guest kernel does not exist: ${kernelPath}`)\n }\n const initramfsPath =\n options.initramfsPath === undefined ? null : absolutePath(options.initramfsPath, 'initramfsPath')\n if (initramfsPath !== null && !pathExists(initramfsPath)) {\n throw new DeskError(`Initramfs does not exist: ${initramfsPath}`)\n }\n const baseImagePath = absolutePath(options.baseImagePath, 'baseImagePath')\n if (!pathExists(baseImagePath)) {\n throw new DeskError(`Base image does not exist: ${baseImagePath}`)\n }\n const overlayPath = absolutePath(options.overlayPath, 'overlayPath')\n const overlayDirectory = dirname(overlayPath)\n if (!pathExists(overlayDirectory)) {\n throw new DeskError(`Overlay directory does not exist: ${overlayDirectory}`)\n }\n const memoryMb = positiveInteger(options.memoryMb ?? DEFAULT_MEMORY_MB, 'memoryMb')\n const vcpus = positiveInteger(options.vcpus ?? DEFAULT_VCPUS, 'vcpus')\n const runtimeDir = absolutePath(options.runtimeDir ?? join(tmpdir(), 'appkit-desk'), 'runtimeDir')\n // Keep Darwin's small sockaddr_un limit even for a maximum-length desk ID.\n const socketId = createHash('sha256').update(deskId).digest('hex').slice(0, 20)\n const vsockSocketPath = socketPath(join(runtimeDir, `d-${socketId}.vsock`))\n const portsSocketPath = socketPath(join(runtimeDir, `d-${socketId}.ports`))\n const snapshotDir = options.snapshotDir\n ? absolutePath(options.snapshotDir, 'snapshotDir')\n : join(overlayDirectory, `${deskId}.snapshot`)\n const restoring = options.restore === true\n if (restoring && !pathExists(snapshotDir)) {\n throw new DeskError(`Desk ${deskId} has no snapshot to restore at ${snapshotDir}`)\n }\n const network = cleanGuestNetwork(options.guestNetwork ?? {})\n return {\n hypervisor: 'virtualization',\n deskId,\n overlay: {\n path: overlayPath,\n basePath: baseImagePath,\n create: pathExists(overlayPath) ? null : { command: 'cp', args: ['-c', baseImagePath, overlayPath] },\n },\n vsock: { cid: VZ_GUEST_CID, socketPath: vsockSocketPath },\n ports: { socketPath: portsSocketPath },\n network: {\n mac: cleanMacAddress(options.macAddress ?? deskMacAddress(deskId)),\n ...network,\n },\n snapshot: { dir: snapshotDir, restoring },\n memoryMb,\n vcpus,\n kernelPath,\n initramfsPath,\n kernelCmdline: options.kernelCmdline ?? DEFAULT_KERNEL_CMDLINE,\n launcherIdentity: cleanLauncherIdentity(options.launcherIdentity),\n }\n}\n\nfunction cleanGuestNetwork(\n options: DeskGuestNetworkOptions,\n): Omit<VirtualizationLaunchPlan['network'], 'mac'> {\n if (options.allowLan !== undefined && typeof options.allowLan !== 'boolean') {\n throw new DeskError('guestNetwork.allowLan must be a boolean.')\n }\n const guestAddress = ipv4(options.guestAddress ?? DEFAULT_VZ_GUEST_ADDRESS, 'guestNetwork.guestAddress')\n const gatewayAddress = ipv4(options.gatewayAddress ?? DEFAULT_VZ_GATEWAY_ADDRESS, 'guestNetwork.gatewayAddress')\n const prefixLength = options.prefixLength ?? DEFAULT_VZ_PREFIX_LENGTH\n if (!Number.isInteger(prefixLength) || prefixLength < 8 || prefixLength > 30) {\n throw new DeskError('guestNetwork.prefixLength must be an integer between 8 and 30.')\n }\n const mask = (0xffff_ffff << (32 - prefixLength)) >>> 0\n if (\n guestAddress === gatewayAddress\n || ((ipv4Number(guestAddress) & mask) >>> 0) !== ((ipv4Number(gatewayAddress) & mask) >>> 0)\n ) {\n throw new DeskError(\"guestNetwork.guestAddress must be a different address in the gateway's subnet.\")\n }\n const dns = [...(options.dns ?? DEFAULT_VZ_DNS)]\n if (dns.length < 1 || dns.length > 3) {\n throw new DeskError('guestNetwork.dns must list one to three IPv4 resolvers.')\n }\n return {\n allowLan: options.allowLan ?? false,\n guestAddress,\n gatewayAddress,\n prefixLength,\n dns: dns.map((entry) => ipv4(entry, 'guestNetwork.dns')),\n }\n}\n\n/** Stable per desk, so a restored guest finds the NIC it was saved with. */\nfunction deskMacAddress(deskId: string): string {\n const digest = createHash('sha256').update(`appkit-desk:${deskId}`).digest()\n const octets = [0x06, ...digest.subarray(0, 5)]\n return octets.map((octet) => octet.toString(16).padStart(2, '0')).join(':')\n}\n\nfunction socketPath(path: string): string {\n if (Buffer.byteLength(path) > DARWIN_SOCKET_PATH_LIMIT) {\n throw new DeskError(\n `Socket path ${path} is longer than the ${DARWIN_SOCKET_PATH_LIMIT} bytes macOS allows; `\n + 'use a shorter runtimeDir or deskId.',\n )\n }\n return path\n}\n\nfunction ipv4(value: string, field: string): string {\n if (typeof value !== 'string' || isIP(value) !== 4) {\n throw new DeskError(`${field} must be an IPv4 address.`)\n }\n return value\n}\n\nfunction ipv4Number(address: string): number {\n return address.split('.').reduce((value, octet) => ((value << 8) | Number(octet)) >>> 0, 0)\n}\n\nfunction defaultTapDevice(cid: number): string {\n return `dsk${cid}`\n}\n\nfunction defaultMacAddress(cid: number): string {\n // Locally administered, unicast prefix; the low four octets carry the CID so\n // the address is stable per desk and never collides across resident desks.\n const octets = [0x06, 0x00, (cid >>> 24) & 0xff, (cid >>> 16) & 0xff, (cid >>> 8) & 0xff, cid & 0xff]\n return octets.map((octet) => octet.toString(16).padStart(2, '0')).join(':')\n}\n\nfunction cleanCid(value: number): number {\n if (!Number.isInteger(value) || value < MIN_GUEST_CID || value > MAX_GUEST_CID) {\n throw new DeskError(\n `vsockCid must be an integer between ${MIN_GUEST_CID} and ${MAX_GUEST_CID}.`,\n )\n }\n return value\n}\n\nfunction cleanTapDevice(value: string): string {\n if (!TAP_DEVICE_PATTERN.test(value)) {\n throw new DeskError('tapDevice must be 1–15 characters of letters, numbers, underscores, or hyphens.')\n }\n return value\n}\n\nfunction cleanMacAddress(value: string): string {\n if (!MAC_ADDRESS_PATTERN.test(value)) {\n throw new DeskError(`macAddress is not a valid MAC address: ${value}`)\n }\n return value.toLowerCase()\n}\n\nexport function cleanLauncherIdentity(\n identity: DeskLauncherIdentity | undefined,\n): DeskLauncherIdentity | undefined {\n if (!identity) return undefined\n const max = 2_147_483_647\n if (!Number.isInteger(identity.uid) || identity.uid < 1 || identity.uid > max) {\n throw new DeskError(`launcherIdentity.uid must be an integer between 1 and ${max}.`)\n }\n if (!Number.isInteger(identity.gid) || identity.gid < 0 || identity.gid > max) {\n throw new DeskError(`launcherIdentity.gid must be an integer between 0 and ${max}.`)\n }\n return { uid: identity.uid, gid: identity.gid }\n}\n\nfunction absolutePath(value: string, field: string): string {\n if (!value || !isAbsolute(value)) {\n throw new DeskError(`${field} must be an absolute path.`)\n }\n return resolve(value)\n}\n\nfunction positiveInteger(value: number, field: string): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new DeskError(`${field} must be a positive integer.`)\n }\n return value\n}\n"]}
1
+ {"version":3,"file":"plan.js","sourceRoot":"","sources":["../src/plan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU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,GAAG,GAAG,CAAC,IAAI,QAAQ,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC;QAC9E,MAAM,IAAI,SAAS,CAAC,yDAAyD,GAAG,GAAG,CAAC,CAAA;IACtF,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC,GAAG,GAAG,CAAC,IAAI,QAAQ,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC;QAC9E,MAAM,IAAI,SAAS,CAAC,yDAAyD,GAAG,GAAG,CAAC,CAAA;IACtF,CAAC;IACD,OAAO,EAAE,GAAG,EAAE,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,CAAC,GAAG,EAAE,CAAA;AACjD,CAAC;AAED,SAAS,YAAY,CAAC,KAAa,EAAE,KAAa;IAChD,IAAI,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QACjC,MAAM,IAAI,SAAS,CAAC,GAAG,KAAK,4BAA4B,CAAC,CAAA;IAC3D,CAAC;IACD,OAAO,OAAO,CAAC,KAAK,CAAC,CAAA;AACvB,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,KAAa;IACnD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,SAAS,CAAC,GAAG,KAAK,8BAA8B,CAAC,CAAA;IAC7D,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import { Buffer } from 'node:buffer'\nimport { createHash } from 'node:crypto'\nimport { existsSync, statSync } from 'node:fs'\nimport { isIP } from 'node:net'\nimport { arch as hostArch, release as hostRelease, tmpdir } from 'node:os'\nimport { delimiter, dirname, isAbsolute, join, resolve } from 'node:path'\n\nexport const DEFAULT_VMM_PATH = '/usr/bin/cloud-hypervisor'\nexport const DEFAULT_KVM_PATH = '/dev/kvm'\nexport const DEFAULT_QEMU_IMG_PATH = '/usr/bin/qemu-img'\nexport const DEFAULT_RUNTIME_DIR = '/run/appkit-desk'\nexport const DEFAULT_MEMORY_MB = 384\nexport const DEFAULT_VCPUS = 2\nexport const DEFAULT_KERNEL_CMDLINE = 'root=/dev/vda rw quiet'\n/**\n * Where a Cloud Hypervisor desk looks for `virtiofsd` when `virtiofsdPath` is\n * not set and it is not on `PATH`: Debian's and Fedora's package location.\n */\nexport const DEFAULT_VIRTIOFSD_PATH = '/usr/libexec/virtiofsd'\nexport const DEFAULT_VIRTIOFSD_SANDBOX: DeskVirtiofsdSandbox = 'namespace'\n/**\n * The guest network Virtualization.framework desks get from the helper's NAT:\n * the same addresses QEMU's user networking uses, so they are unsurprising in\n * a guest. Nothing outside the helper ever sees them.\n */\nexport const DEFAULT_VZ_GUEST_ADDRESS = '10.0.2.15'\nexport const DEFAULT_VZ_GATEWAY_ADDRESS = '10.0.2.2'\nexport const DEFAULT_VZ_PREFIX_LENGTH = 24\nexport const DEFAULT_VZ_DNS: readonly string[] = ['1.1.1.1', '9.9.9.9']\n/** Virtualization.framework always gives the guest vsock context ID 3. */\nexport const VZ_GUEST_CID = 3\n/** The first Darwin release with Virtualization.framework save and restore (macOS 14). */\nconst MIN_DARWIN_MAJOR = 23\n/** `sun_path` holds 104 bytes on Darwin, including the terminator. */\nconst DARWIN_SOCKET_PATH_LIMIT = 103\n/** `sun_path` holds 108 bytes on Linux, including the terminator. */\nconst LINUX_SOCKET_PATH_LIMIT = 107\n/** Linux's virtio-fs tag field is 36 bytes; Virtualization.framework enforces the same. */\nconst SHARE_TAG_PATTERN = /^[a-z0-9][a-z0-9-]{0,35}$/\n\nconst DESK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/\nconst TAP_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,14}$/\nconst MAC_ADDRESS_PATTERN = /^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$/i\n/** vsock CIDs 0–2 are reserved (hypervisor, loopback, host). */\nconst MIN_GUEST_CID = 3\nconst MAX_GUEST_CID = 0xffff_fffe\n\n/**\n * Every failure this package raises. The `name` is annotated as `string`\n * rather than left to infer its literal so a subclass can narrow the meaning\n * of a failure — see `DeskRequestFateUnknownError` — without callers losing\n * the one `instanceof DeskError` they already check.\n */\nexport class DeskError extends Error {\n override readonly name: string = 'DeskError'\n}\n\nexport interface DeskLauncherIdentity {\n /** Host/container UID used to invoke the VMM and image tooling. */\n uid: number\n /** Host/container GID used to invoke the VMM and image tooling. */\n gid: number\n}\n\n/**\n * Which hypervisor a plan is for: Cloud Hypervisor over KVM on Linux, or\n * Apple's Virtualization.framework through the `appkit-desk-vz` helper on an\n * Apple silicon Mac.\n */\nexport type DeskHypervisor = 'cloud-hypervisor' | 'virtualization'\n\n/**\n * The guest network of a Virtualization.framework desk. The helper runs a\n * userspace NAT: the guest reaches the public internet and nothing else unless\n * `allowLan` is set — no RFC 1918 space, link-local, CGNAT, or the Mac itself.\n */\nexport interface DeskGuestNetworkOptions {\n /** Let the guest reach the Mac's LAN, link-local and CGNAT space, and the Mac. */\n allowLan?: boolean\n /** The address the helper's DHCP server leases the guest. */\n guestAddress?: string\n /** The helper's own address on the link: the guest's router. */\n gatewayAddress?: string\n prefixLength?: number\n /** Resolvers the guest is handed; the first also answers DNS sent to the gateway. */\n dns?: readonly string[]\n}\n\n/**\n * A host directory shared into the guest over virtio-fs. The guest mounts it\n * with `mount -t virtiofs <tag> <dir>`.\n */\nexport interface DeskShare {\n /** 1–36 lowercase letters, digits, or hyphens, starting with a letter or digit; unique per desk. */\n tag: string\n /** Absolute path of an existing host directory. */\n path: string\n /**\n * Refuse every write from the guest. Enforced by the host's file server, so\n * a guest cannot lift it by remounting the share read-write.\n */\n readOnly: boolean\n}\n\n/**\n * How `virtiofsd` confines itself to the shared directory. `namespace` (its\n * own default) pivots into the directory inside new mount, PID and network\n * namespaces, which needs CAP_SYS_ADMIN when run as root and unprivileged user\n * namespaces otherwise. `chroot` only chroots, which needs root and suits a\n * container that may not create namespaces. Both stop symlinks from escaping\n * the share; running unconfined is not offered.\n */\nexport type DeskVirtiofsdSandbox = 'namespace' | 'chroot'\n\n/** An immutable host image. The caller must retain its bytes and path for every snapshot. */\nexport interface DeskReadOnlyAttachment {\n path: string\n /** SHA-256 of the immutable image, used as snapshot identity. */\n sha256: string\n kind: 'block' | 'pmem'\n}\n\nexport interface DeskLaunchPlanOptions {\n deskId: string\n /** Defaults to `cloud-hypervisor`. */\n hypervisor?: DeskHypervisor\n /** Cloud Hypervisor only: the VMM binary. */\n vmmPath?: string\n /** Cloud Hypervisor only: the KVM device. */\n kvmPath?: string\n qemuImgPath?: string\n /** Absolute path of the kernel image the microVM boots. */\n kernelPath: string\n /**\n * Absolute path of an initramfs. Required whenever the kernel loads its\n * root-filesystem or virtio drivers as modules — a stock distro cloud kernel\n * panics with \"VFS: Unable to mount root fs\" if it boots without one. Omit\n * only for a kernel with virtio_blk/ext4 built in.\n */\n initramfsPath?: string\n /** Absolute path of the golden raw base image every desk clones. */\n baseImagePath: string\n /** Absolute path of this desk's copy-on-write overlay (a raw reflink clone). */\n overlayPath: string\n memoryMb?: number\n /** Cloud Hypervisor virtio-balloon with free-page reporting, size zero. */\n freePageReporting?: boolean\n vcpus?: number\n /**\n * Guest vsock context ID; must be unique among resident desks. Cloud\n * Hypervisor only — a Virtualization.framework guest is always CID 3, and\n * its vsock is private to its helper.\n */\n vsockCid: number\n /**\n * Directory holding the desk's control sockets. Defaults to\n * `/run/appkit-desk` for Cloud Hypervisor and `<os tmpdir>/appkit-desk` for\n * Virtualization.framework.\n */\n runtimeDir?: string\n /** Cloud Hypervisor only: host TAP device name; derived from the CID when omitted. */\n tapDevice?: string\n /**\n * Guest MAC address. Derived from the CID for Cloud Hypervisor, and from the\n * desk ID for Virtualization.framework, whose restore needs the same NIC.\n */\n macAddress?: string\n /** Virtualization.framework only: the helper's NAT network and fence. */\n guestNetwork?: DeskGuestNetworkOptions\n /**\n * Host directories shared into the guest. Restoring a snapshot requires the\n * same shares the desk was parked with; see the backends.\n */\n shares?: readonly DeskShare[]\n /** Additional immutable Cloud Hypervisor devices, in guest enumeration order. */\n readOnlyAttachments?: readonly DeskReadOnlyAttachment[]\n /**\n * Cloud Hypervisor only: the `virtiofsd` binary (1.13 or later) that serves\n * each share. Defaults to the first `virtiofsd` on `PATH`, then\n * `/usr/libexec/virtiofsd`. Not needed, and not looked for, without shares.\n */\n virtiofsdPath?: string\n /** Cloud Hypervisor only: defaults to `namespace`. */\n virtiofsdSandbox?: DeskVirtiofsdSandbox\n kernelCmdline?: string\n launcherIdentity?: DeskLauncherIdentity\n /**\n * Where this desk's memory snapshot lives. Defaults beside the overlay, which\n * is the volume sized for desk state — a snapshot is roughly `memoryMb` of\n * guest RAM, so it does not belong on a runtime tmpfs.\n */\n snapshotDir?: string\n /**\n * Resume from that snapshot instead of booting the kernel.\n *\n * A restored VM continues with its process tree intact, which is the whole\n * point of parking with memory rather than shutting down: an agent's in-guest\n * daemon survives. Refused when the snapshot is not there, rather than falling\n * back to a cold boot — a silent cold boot is how a desk loses the state it\n * was promised to have kept.\n */\n restore?: boolean\n /** Cloud Hypervisor copy-on-write restore; the source must remain unchanged while resident. */\n memoryRestoreMode?: 'copyonwrite'\n}\n\n/** What every plan carries, whichever hypervisor runs it. */\nexport interface DeskLaunchPlanBase {\n deskId: string\n overlay: {\n path: string\n basePath: string\n /** The overlay-creation step, or `null` when the overlay already exists. */\n create: { command: string; args: string[] } | null\n }\n /**\n * The host Unix socket the guest's vsock is reached through, with Cloud\n * Hypervisor's hybrid-vsock preamble: write `CONNECT <port>\\n`, read\n * `OK <n>\\n`, then the stream is the guest connection.\n */\n vsock: { cid: number; socketPath: string }\n /** Where a memory snapshot of this desk is written, and read back from. */\n snapshot: { dir: string; restoring: boolean }\n /** Host directories shared into the guest, in the order they were given. */\n shares: readonly DeskShare[]\n memoryMb: number\n vcpus: number\n kernelPath: string\n /** Resolved initramfs path, or `null` when the kernel needs none. */\n initramfsPath: string | null\n kernelCmdline: string\n launcherIdentity?: DeskLauncherIdentity\n}\n\n/**\n * The complete Cloud Hypervisor invocation as inspectable data. Nothing here\n * has been spawned: tests, audit logs, and readiness screens can assert on the\n * exact argv a desk would boot with.\n */\nexport interface CloudHypervisorLaunchPlan extends DeskLaunchPlanBase {\n hypervisor: 'cloud-hypervisor'\n vmm: { command: string; args: string[] }\n api: { socketPath: string }\n tap: { device: string; mac: string }\n /**\n * Each share with the `virtiofsd` that serves it. Every daemon must be\n * listening on its socket before the VMM starts, for a boot and for a\n * restore alike.\n */\n shares: readonly CloudHypervisorShare[]\n}\n\nexport interface CloudHypervisorShare extends DeskShare {\n /** The vhost-user socket the daemon listens on and the VMM connects to. */\n socketPath: string\n daemon: { command: string; args: string[] }\n}\n\n/**\n * A Virtualization.framework desk as inspectable data: what the helper is\n * asked to boot. The helper path belongs to the backend, not the plan.\n */\nexport interface VirtualizationLaunchPlan extends DeskLaunchPlanBase {\n hypervisor: 'virtualization'\n /**\n * The host Unix socket guest TCP ports are reached through, with the same\n * preamble as `vsock`: `CONNECT <tcp port>\\n` answered by `OK <n>\\n` once\n * the guest accepts, or a close with nothing written when it refuses.\n */\n ports: { socketPath: string }\n network: {\n mac: string\n allowLan: boolean\n guestAddress: string\n gatewayAddress: string\n prefixLength: number\n dns: string[]\n }\n}\n\nexport type DeskLaunchPlan = CloudHypervisorLaunchPlan | VirtualizationLaunchPlan\n\n/**\n * Whether this host can run desks at all. On Linux: a usable `/dev/kvm` and\n * the Cloud Hypervisor binary. On macOS: Apple silicon, macOS 14 or later (the\n * first with Virtualization.framework save and restore), and an existing\n * `appkit-desk-vz` helper at `helperPath`. Signature and entitlement are checked\n * by macOS on execution, not by this probe. Every check is injectable and the\n * answer is fail-closed — a host missing any of them gets no desk capability\n * rather than a degraded one.\n */\nexport function isDeskSupported(options: {\n platform?: NodeJS.Platform\n kvmPath?: string\n vmmPath?: string\n /** macOS: the signed `appkit-desk-vz` helper. Required there. */\n helperPath?: string\n arch?: string\n /** The kernel release, as `os.release()` reports it. */\n osRelease?: string\n pathExists?: (path: string) => boolean\n} = {}): boolean {\n const platform = options.platform ?? process.platform\n const pathExists = options.pathExists ?? existsSync\n if (platform === 'darwin') {\n const major = Number.parseInt((options.osRelease ?? hostRelease()).split('.')[0] ?? '', 10)\n return (\n (options.arch ?? hostArch()) === 'arm64'\n && Number.isInteger(major)\n && major >= MIN_DARWIN_MAJOR\n && options.helperPath !== undefined\n && isAbsolute(options.helperPath)\n && pathExists(options.helperPath)\n )\n }\n return (\n platform === 'linux'\n && pathExists(options.kvmPath ?? DEFAULT_KVM_PATH)\n && pathExists(options.vmmPath ?? DEFAULT_VMM_PATH)\n )\n}\n\n/** Validate a desk identifier, which is used in socket paths and device names. */\nexport function cleanDeskId(value: string): string {\n if (!DESK_ID_PATTERN.test(value)) {\n throw new DeskError(\n 'deskId must be 1–64 letters, numbers, dots, underscores, or hyphens.',\n )\n }\n return value\n}\n\nexport interface DeskLaunchPlanDependencies {\n pathExists?: (path: string) => boolean\n deviceExists?: (path: string) => boolean\n /** Whether a path is an existing directory; checked for every share. */\n isDirectory?: (path: string) => boolean\n /** Searched for `virtiofsd` when `virtiofsdPath` is not set; defaults to `process.env.PATH`. */\n searchPath?: string\n}\n\n/**\n * Build the deterministic launch plan without spawning anything. Fail closed:\n * a missing `/dev/kvm` or VMM binary (Cloud Hypervisor), kernel, base image,\n * or overlay directory throws instead of producing a plan that cannot boot.\n */\nexport function buildDeskLaunchPlan(\n options: DeskLaunchPlanOptions & { hypervisor: 'virtualization' },\n dependencies?: DeskLaunchPlanDependencies,\n): VirtualizationLaunchPlan\nexport function buildDeskLaunchPlan(\n options: DeskLaunchPlanOptions & { hypervisor?: 'cloud-hypervisor' },\n dependencies?: DeskLaunchPlanDependencies,\n): CloudHypervisorLaunchPlan\nexport function buildDeskLaunchPlan(\n options: DeskLaunchPlanOptions,\n dependencies?: DeskLaunchPlanDependencies,\n): DeskLaunchPlan\nexport function buildDeskLaunchPlan(\n options: DeskLaunchPlanOptions,\n dependencies: DeskLaunchPlanDependencies = {},\n): DeskLaunchPlan {\n const hypervisor = options.hypervisor ?? 'cloud-hypervisor'\n if (options.memoryRestoreMode !== undefined && (options.memoryRestoreMode !== 'copyonwrite' || hypervisor !== 'cloud-hypervisor')) {\n throw new DeskError('Copy-on-write restore requires Cloud Hypervisor.')\n }\n if (hypervisor === 'virtualization') return buildVirtualizationPlan(options, dependencies)\n if (hypervisor !== 'cloud-hypervisor') {\n throw new DeskError(`Unknown hypervisor: ${String(hypervisor)}`)\n }\n if (options.guestNetwork !== undefined) {\n throw new DeskError(\n 'guestNetwork applies to Virtualization.framework desks; a Cloud Hypervisor desk is networked with createDeskNetwork.',\n )\n }\n return buildCloudHypervisorPlan(options, dependencies)\n}\n\nfunction buildCloudHypervisorPlan(\n options: DeskLaunchPlanOptions,\n dependencies: DeskLaunchPlanDependencies,\n): CloudHypervisorLaunchPlan {\n const pathExists = dependencies.pathExists ?? existsSync\n const deviceExists = dependencies.deviceExists ?? existsSync\n const isDirectory = dependencies.isDirectory ?? directoryExists\n const deskId = cleanDeskId(options.deskId)\n const kvmPath = absolutePath(options.kvmPath ?? DEFAULT_KVM_PATH, 'kvmPath')\n if (!deviceExists(kvmPath)) {\n throw new DeskError(\n `KVM is not available at ${kvmPath}. Desks require hardware virtualization; `\n + 'there is no software-emulation fallback.',\n )\n }\n const vmmPath = absolutePath(options.vmmPath ?? DEFAULT_VMM_PATH, 'vmmPath')\n if (!pathExists(vmmPath)) {\n throw new DeskError(\n `Cloud Hypervisor was not found at ${vmmPath}. Install cloud-hypervisor or configure vmmPath.`,\n )\n }\n const kernelPath = absolutePath(options.kernelPath, 'kernelPath')\n if (!pathExists(kernelPath)) {\n throw new DeskError(`Guest kernel does not exist: ${kernelPath}`)\n }\n const initramfsPath =\n options.initramfsPath === undefined\n ? null\n : absolutePath(options.initramfsPath, 'initramfsPath')\n if (initramfsPath !== null && !pathExists(initramfsPath)) {\n throw new DeskError(`Initramfs does not exist: ${initramfsPath}`)\n }\n const baseImagePath = absolutePath(options.baseImagePath, 'baseImagePath')\n if (!pathExists(baseImagePath)) {\n throw new DeskError(`Base image does not exist: ${baseImagePath}`)\n }\n const overlayPath = absolutePath(options.overlayPath, 'overlayPath')\n const overlayDirectory = dirname(overlayPath)\n if (!pathExists(overlayDirectory)) {\n throw new DeskError(`Overlay directory does not exist: ${overlayDirectory}`)\n }\n const memoryMb = positiveInteger(options.memoryMb ?? DEFAULT_MEMORY_MB, 'memoryMb')\n const vcpus = positiveInteger(options.vcpus ?? DEFAULT_VCPUS, 'vcpus')\n const vsockCid = cleanCid(options.vsockCid)\n const runtimeDir = absolutePath(options.runtimeDir ?? DEFAULT_RUNTIME_DIR, 'runtimeDir')\n const tapDevice = cleanTapDevice(options.tapDevice ?? defaultTapDevice(vsockCid))\n const macAddress = cleanMacAddress(options.macAddress ?? defaultMacAddress(vsockCid))\n const kernelCmdline = options.kernelCmdline ?? DEFAULT_KERNEL_CMDLINE\n const launcherIdentity = cleanLauncherIdentity(options.launcherIdentity)\n const vsockSocketPath = join(runtimeDir, `desk-${deskId}.vsock`)\n const apiSocketPath = join(runtimeDir, `desk-${deskId}.api.sock`)\n // Beside the overlay by default: a snapshot is the guest's RAM, so it belongs\n // on the volume provisioned for desk state rather than on a runtime tmpfs.\n const snapshotDir = options.snapshotDir\n ? absolutePath(options.snapshotDir, 'snapshotDir')\n : join(overlayDirectory, `${deskId}.snapshot`)\n const restoring = options.restore === true\n if (restoring && !pathExists(snapshotDir)) {\n // Refused rather than silently cold-booted. A caller asking to restore has\n // been told this desk kept its memory; quietly booting a fresh kernel would\n // lose the process tree it was relying on and look like a crash inside the\n // guest instead of a missing snapshot out here.\n throw new DeskError(`Desk ${deskId} has no snapshot to restore at ${snapshotDir}`)\n }\n const attachments = cleanAttachments(options.readOnlyAttachments, pathExists)\n const shares = cloudHypervisorShares(cleanShares(options.shares, isDirectory), {\n deskId,\n runtimeDir,\n virtiofsdPath: options.virtiofsdPath,\n sandbox: options.virtiofsdSandbox ?? DEFAULT_VIRTIOFSD_SANDBOX,\n pathExists,\n searchPath: dependencies.searchPath ?? process.env.PATH ?? '',\n })\n\n const create = pathExists(overlayPath)\n ? null\n : {\n // Cloud Hypervisor cannot follow disk backing chains: a qcow2 overlay\n // over a qcow2/raw base is rejected with UnsupportedFeature /\n // MaxNestingDepthExceeded. So the overlay is a plain raw file, cloned\n // from the raw base with `cp --reflink=auto` — an instant, block-sharing\n // copy-on-write clone on XFS/Btrfs and a graceful full-copy fallback on\n // ext4. Either way CH boots the resulting raw file with no backing chain.\n command: 'cp',\n args: ['--reflink=auto', baseImagePath, overlayPath],\n }\n\n // A restoring VMM is handed the snapshot and nothing else.\n //\n // The snapshot carries the whole machine config — memory size, cpus, disk,\n // vsock, net — so passing `--kernel`/`--disk` alongside `--restore` is not\n // redundant, it is rejected.\n //\n // `resume=false` is deliberate, and it is the difference between this being\n // safe and being a data-loss bug. A memory snapshot is only valid against the\n // disk as it stood when the snapshot was taken. Resume the guest in this same\n // spawn and it starts writing immediately, so for as long as the snapshot\n // still exists there are two valid-looking pasts for one desk — and a host\n // that died in that window would, on the next start, replay this memory\n // against a disk that had moved on. That is corruption, not a stale cache.\n //\n // The guest comes back PAUSED; before it runs, the caller must make the\n // snapshot unavailable for replay. File-backed restores keep their retired\n // source unchanged until the VMM exits.\n //\n // The tap is reopened BY NAME from the snapshotted config. That is the detail\n // that makes this possible at all: Cloud Hypervisor's `net_fds` restore\n // parameter exists for VMs whose tap was passed as a file descriptor, and\n // producing one from Node would mean an ioctl(TUNSETIFF) it cannot make.\n // Because `deskPlan` configures `--net tap=<name>`, there is nothing to pass.\n //\n // Shares are in the snapshotted config too, by socket path, with each\n // daemon's state. What the snapshot cannot hold is a running `virtiofsd`, so\n // the backend starts the same daemons on the same sockets before this VMM\n // either way, and the VMM loads their state back into them.\n const args = restoring\n ? [\n '--api-socket', apiSocketPath,\n '--restore', `source_url=file://${snapshotDir},resume=false${options.memoryRestoreMode === 'copyonwrite' ? ',memory_restore_mode=copyonwrite' : ''}`,\n ]\n : [\n '--api-socket', apiSocketPath,\n '--kernel', kernelPath,\n // A modular distro kernel needs its initramfs to bring up virtio_blk and\n // mount root; omitted only for a kernel with those drivers built in.\n ...(initramfsPath === null ? [] : ['--initramfs', initramfsPath]),\n '--cmdline', kernelCmdline,\n // Be explicit that the disk is raw: CH deprecated image-format auto-detection\n // and warns without image_type; there is never a qcow2 overlay here.\n '--disk', `path=${overlayPath},image_type=raw`, ...attachments.filter(a => a.kind === 'block').map(a => `path=${a.path},readonly=on,image_type=raw`),\n ...attachments.filter(a => a.kind === 'pmem').flatMap(a => ['--pmem', `file=${a.path},discard_writes=on`]),\n // vhost-user devices map guest RAM into their daemon, so it must be\n // shared memory; a desk without shares keeps private memory.\n '--memory', `size=${memoryMb}M${shares.length === 0 ? '' : ',shared=on'}`,\n ...(options.freePageReporting ? ['--balloon', 'size=0,free_page_reporting=on'] : []),\n '--cpus', `boot=${vcpus}`,\n '--vsock', `cid=${vsockCid},socket=${vsockSocketPath}`,\n '--net', `tap=${tapDevice},mac=${macAddress}`,\n ...(shares.length === 0\n ? []\n : ['--fs', ...shares.map((share) => `tag=${share.tag},socket=${share.socketPath}`)]),\n '--serial', 'off',\n '--console', 'off',\n ]\n\n return {\n hypervisor: 'cloud-hypervisor',\n deskId,\n vmm: { command: vmmPath, args },\n overlay: { path: overlayPath, basePath: baseImagePath, create },\n vsock: { cid: vsockCid, socketPath: vsockSocketPath },\n api: { socketPath: apiSocketPath },\n tap: { device: tapDevice, mac: macAddress },\n snapshot: { dir: snapshotDir, restoring },\n shares,\n memoryMb,\n vcpus,\n kernelPath,\n initramfsPath,\n kernelCmdline,\n launcherIdentity,\n }\n}\n\n/**\n * The Virtualization.framework plan. The same fail-closed checks on the guest\n * assets; no KVM or VMM binary, because the backend owns the helper; and the\n * overlay is an APFS clone (`cp -c`), which is to APFS what `--reflink=auto`\n * is to XFS: instant and block-sharing. A volume that cannot clone must be\n * replaced with one that supports it.\n */\nfunction buildVirtualizationPlan(\n options: DeskLaunchPlanOptions,\n dependencies: DeskLaunchPlanDependencies,\n): VirtualizationLaunchPlan {\n const pathExists = dependencies.pathExists ?? existsSync\n if (options.readOnlyAttachments?.length) throw new DeskError('Read-only attachments require Cloud Hypervisor.')\n if (options.freePageReporting) throw new DeskError('Free-page reporting requires Cloud Hypervisor.')\n const deskId = cleanDeskId(options.deskId)\n if (options.tapDevice !== undefined) {\n throw new DeskError('tapDevice applies to Cloud Hypervisor desks; a Virtualization.framework desk has no TAP.')\n }\n if (options.virtiofsdPath !== undefined || options.virtiofsdSandbox !== undefined) {\n throw new DeskError(\n 'virtiofsdPath and virtiofsdSandbox apply to Cloud Hypervisor desks; Virtualization.framework serves shares itself.',\n )\n }\n const kernelPath = absolutePath(options.kernelPath, 'kernelPath')\n if (!pathExists(kernelPath)) {\n throw new DeskError(`Guest kernel does not exist: ${kernelPath}`)\n }\n const initramfsPath =\n options.initramfsPath === undefined ? null : absolutePath(options.initramfsPath, 'initramfsPath')\n if (initramfsPath !== null && !pathExists(initramfsPath)) {\n throw new DeskError(`Initramfs does not exist: ${initramfsPath}`)\n }\n const baseImagePath = absolutePath(options.baseImagePath, 'baseImagePath')\n if (!pathExists(baseImagePath)) {\n throw new DeskError(`Base image does not exist: ${baseImagePath}`)\n }\n const overlayPath = absolutePath(options.overlayPath, 'overlayPath')\n const overlayDirectory = dirname(overlayPath)\n if (!pathExists(overlayDirectory)) {\n throw new DeskError(`Overlay directory does not exist: ${overlayDirectory}`)\n }\n const memoryMb = positiveInteger(options.memoryMb ?? DEFAULT_MEMORY_MB, 'memoryMb')\n const vcpus = positiveInteger(options.vcpus ?? DEFAULT_VCPUS, 'vcpus')\n const runtimeDir = absolutePath(options.runtimeDir ?? join(tmpdir(), 'appkit-desk'), 'runtimeDir')\n // Keep Darwin's small sockaddr_un limit even for a maximum-length desk ID.\n const socketId = createHash('sha256').update(deskId).digest('hex').slice(0, 20)\n const vsockSocketPath = socketPath(join(runtimeDir, `d-${socketId}.vsock`))\n const portsSocketPath = socketPath(join(runtimeDir, `d-${socketId}.ports`))\n const snapshotDir = options.snapshotDir\n ? absolutePath(options.snapshotDir, 'snapshotDir')\n : join(overlayDirectory, `${deskId}.snapshot`)\n const restoring = options.restore === true\n if (restoring && !pathExists(snapshotDir)) {\n throw new DeskError(`Desk ${deskId} has no snapshot to restore at ${snapshotDir}`)\n }\n const network = cleanGuestNetwork(options.guestNetwork ?? {})\n const shares = cleanShares(options.shares, dependencies.isDirectory ?? directoryExists)\n return {\n hypervisor: 'virtualization',\n deskId,\n overlay: {\n path: overlayPath,\n basePath: baseImagePath,\n create: pathExists(overlayPath) ? null : { command: 'cp', args: ['-c', baseImagePath, overlayPath] },\n },\n vsock: { cid: VZ_GUEST_CID, socketPath: vsockSocketPath },\n ports: { socketPath: portsSocketPath },\n network: {\n mac: cleanMacAddress(options.macAddress ?? deskMacAddress(deskId)),\n ...network,\n },\n snapshot: { dir: snapshotDir, restoring },\n shares,\n memoryMb,\n vcpus,\n kernelPath,\n initramfsPath,\n kernelCmdline: options.kernelCmdline ?? DEFAULT_KERNEL_CMDLINE,\n launcherIdentity: cleanLauncherIdentity(options.launcherIdentity),\n }\n}\n\n/** Reject ambiguous Cloud Hypervisor key-value arguments and unpinned images. */\nexport function cleanAttachments(attachments: readonly DeskReadOnlyAttachment[] | undefined, pathExists: (path: string) => boolean): DeskReadOnlyAttachment[] {\n if (attachments === undefined) return []\n if (!Array.isArray(attachments)) throw new DeskError('readOnlyAttachments must be an array.')\n return attachments.map((attachment, index) => {\n if (!attachment || !['block', 'pmem'].includes(attachment.kind) || !/^[a-f0-9]{64}$/.test(attachment.sha256)) throw new DeskError(`Invalid readOnlyAttachments[${index}].`)\n const path = absolutePath(attachment.path, `readOnlyAttachments[${index}].path`)\n if (path.includes(',') || !pathExists(path)) throw new DeskError(`Invalid attachment path: ${path}`)\n return { path, kind: attachment.kind, sha256: attachment.sha256 }\n })\n}\n\n/** Validate shares as given: tags, absolute existing directories, explicit access. */\nfunction cleanShares(\n shares: readonly DeskShare[] | undefined,\n isDirectory: (path: string) => boolean,\n): DeskShare[] {\n if (shares === undefined) return []\n if (!Array.isArray(shares)) throw new DeskError('shares must be an array.')\n const tags = new Set<string>()\n return shares.map((share: DeskShare, index) => {\n const field = `shares[${index}]`\n if (typeof share !== 'object' || share === null) throw new DeskError(`${field} must be an object.`)\n if (typeof share.tag !== 'string' || !SHARE_TAG_PATTERN.test(share.tag)) {\n throw new DeskError(\n `${field}.tag must be 1–36 lowercase letters, digits, or hyphens, starting with a letter or digit.`,\n )\n }\n if (tags.has(share.tag)) throw new DeskError(`${field}.tag ${share.tag} is already used by another share.`)\n tags.add(share.tag)\n if (typeof share.path !== 'string') throw new DeskError(`${field}.path must be an absolute path.`)\n const path = absolutePath(share.path, `${field}.path`)\n if (!isDirectory(path)) throw new DeskError(`${field}.path is not an existing directory: ${path}`)\n if (typeof share.readOnly !== 'boolean') throw new DeskError(`${field}.readOnly must be a boolean.`)\n return { tag: share.tag, path, readOnly: share.readOnly }\n })\n}\n\n/**\n * One `virtiofsd` per share. `--cache=auto` lets the guest cache for a second\n * at a time, so changes the host makes under a share reach running guests;\n * `always` would let a guest keep serving a file the host has replaced.\n * `--readonly` is the enforcement for a read-only share — the guest is never\n * trusted to honour a read-only mount.\n *\n * The migration flags are for parking. Cloud Hypervisor carries the daemon's\n * state — the files and directories the guest holds — inside a snapshot, and\n * hands it to the fresh daemon on restore, which reopens each by path. A file\n * that has no path by then (unlinked on the host, or by the guest while held\n * open) becomes an error for the guest to see on that file alone, rather than\n * a restore that fails and costs the whole desk its memory.\n */\nfunction cloudHypervisorShares(\n shares: readonly DeskShare[],\n context: {\n deskId: string\n runtimeDir: string\n virtiofsdPath: string | undefined\n sandbox: DeskVirtiofsdSandbox\n pathExists: (path: string) => boolean\n searchPath: string\n },\n): CloudHypervisorShare[] {\n if (shares.length === 0) return []\n if (context.sandbox !== 'namespace' && context.sandbox !== 'chroot') {\n throw new DeskError(\"virtiofsdSandbox must be 'namespace' or 'chroot'.\")\n }\n const command = resolveVirtiofsd(context.virtiofsdPath, context.pathExists, context.searchPath)\n return shares.map((share) => {\n // A dot cannot appear in a tag, so `<desk>.<tag>` names one socket for\n // exactly one desk and share even though desk IDs may contain hyphens.\n const socketPath = join(context.runtimeDir, `desk-${context.deskId}.${share.tag}.fs.sock`)\n if (Buffer.byteLength(socketPath) > LINUX_SOCKET_PATH_LIMIT) {\n throw new DeskError(\n `Socket path ${socketPath} is longer than the ${LINUX_SOCKET_PATH_LIMIT} bytes Linux allows; `\n + 'use a shorter runtimeDir, deskId, or share tag.',\n )\n }\n return {\n ...share,\n socketPath,\n daemon: {\n command,\n args: [\n `--socket-path=${socketPath}`,\n `--shared-dir=${share.path}`,\n `--sandbox=${context.sandbox}`,\n '--cache=auto',\n '--migration-mode=find-paths',\n '--migration-on-error=guest-error',\n ...(share.readOnly ? ['--readonly'] : []),\n ],\n },\n }\n })\n}\n\nfunction resolveVirtiofsd(\n configured: string | undefined,\n pathExists: (path: string) => boolean,\n searchPath: string,\n): string {\n if (configured !== undefined) {\n const path = absolutePath(configured, 'virtiofsdPath')\n if (!pathExists(path)) {\n throw new DeskError(`virtiofsd was not found at ${path}. Install virtiofsd or configure virtiofsdPath.`)\n }\n return path\n }\n const candidates = [\n ...searchPath.split(delimiter).filter((entry) => isAbsolute(entry)).map((entry) => join(entry, 'virtiofsd')),\n DEFAULT_VIRTIOFSD_PATH,\n ]\n const found = candidates.find((candidate) => pathExists(candidate))\n if (found === undefined) {\n throw new DeskError(\n `virtiofsd was not found on PATH or at ${DEFAULT_VIRTIOFSD_PATH}. Install virtiofsd 1.13 or later, or configure virtiofsdPath.`,\n )\n }\n return found\n}\n\nfunction directoryExists(path: string): boolean {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true\n}\n\nfunction cleanGuestNetwork(\n options: DeskGuestNetworkOptions,\n): Omit<VirtualizationLaunchPlan['network'], 'mac'> {\n if (options.allowLan !== undefined && typeof options.allowLan !== 'boolean') {\n throw new DeskError('guestNetwork.allowLan must be a boolean.')\n }\n const guestAddress = ipv4(options.guestAddress ?? DEFAULT_VZ_GUEST_ADDRESS, 'guestNetwork.guestAddress')\n const gatewayAddress = ipv4(options.gatewayAddress ?? DEFAULT_VZ_GATEWAY_ADDRESS, 'guestNetwork.gatewayAddress')\n const prefixLength = options.prefixLength ?? DEFAULT_VZ_PREFIX_LENGTH\n if (!Number.isInteger(prefixLength) || prefixLength < 8 || prefixLength > 30) {\n throw new DeskError('guestNetwork.prefixLength must be an integer between 8 and 30.')\n }\n const mask = (0xffff_ffff << (32 - prefixLength)) >>> 0\n if (\n guestAddress === gatewayAddress\n || ((ipv4Number(guestAddress) & mask) >>> 0) !== ((ipv4Number(gatewayAddress) & mask) >>> 0)\n ) {\n throw new DeskError(\"guestNetwork.guestAddress must be a different address in the gateway's subnet.\")\n }\n const dns = [...(options.dns ?? DEFAULT_VZ_DNS)]\n if (dns.length < 1 || dns.length > 3) {\n throw new DeskError('guestNetwork.dns must list one to three IPv4 resolvers.')\n }\n return {\n allowLan: options.allowLan ?? false,\n guestAddress,\n gatewayAddress,\n prefixLength,\n dns: dns.map((entry) => ipv4(entry, 'guestNetwork.dns')),\n }\n}\n\n/** Stable per desk, so a restored guest finds the NIC it was saved with. */\nfunction deskMacAddress(deskId: string): string {\n const digest = createHash('sha256').update(`appkit-desk:${deskId}`).digest()\n const octets = [0x06, ...digest.subarray(0, 5)]\n return octets.map((octet) => octet.toString(16).padStart(2, '0')).join(':')\n}\n\nfunction socketPath(path: string): string {\n if (Buffer.byteLength(path) > DARWIN_SOCKET_PATH_LIMIT) {\n throw new DeskError(\n `Socket path ${path} is longer than the ${DARWIN_SOCKET_PATH_LIMIT} bytes macOS allows; `\n + 'use a shorter runtimeDir or deskId.',\n )\n }\n return path\n}\n\nfunction ipv4(value: string, field: string): string {\n if (typeof value !== 'string' || isIP(value) !== 4) {\n throw new DeskError(`${field} must be an IPv4 address.`)\n }\n return value\n}\n\nfunction ipv4Number(address: string): number {\n return address.split('.').reduce((value, octet) => ((value << 8) | Number(octet)) >>> 0, 0)\n}\n\nfunction defaultTapDevice(cid: number): string {\n return `dsk${cid}`\n}\n\nfunction defaultMacAddress(cid: number): string {\n // Locally administered, unicast prefix; the low four octets carry the CID so\n // the address is stable per desk and never collides across resident desks.\n const octets = [0x06, 0x00, (cid >>> 24) & 0xff, (cid >>> 16) & 0xff, (cid >>> 8) & 0xff, cid & 0xff]\n return octets.map((octet) => octet.toString(16).padStart(2, '0')).join(':')\n}\n\nfunction cleanCid(value: number): number {\n if (!Number.isInteger(value) || value < MIN_GUEST_CID || value > MAX_GUEST_CID) {\n throw new DeskError(\n `vsockCid must be an integer between ${MIN_GUEST_CID} and ${MAX_GUEST_CID}.`,\n )\n }\n return value\n}\n\nfunction cleanTapDevice(value: string): string {\n if (!TAP_DEVICE_PATTERN.test(value)) {\n throw new DeskError('tapDevice must be 1–15 characters of letters, numbers, underscores, or hyphens.')\n }\n return value\n}\n\nfunction cleanMacAddress(value: string): string {\n if (!MAC_ADDRESS_PATTERN.test(value)) {\n throw new DeskError(`macAddress is not a valid MAC address: ${value}`)\n }\n return value.toLowerCase()\n}\n\nexport function cleanLauncherIdentity(\n identity: DeskLauncherIdentity | undefined,\n): DeskLauncherIdentity | undefined {\n if (!identity) return undefined\n const max = 2_147_483_647\n if (!Number.isInteger(identity.uid) || identity.uid < 1 || identity.uid > max) {\n throw new DeskError(`launcherIdentity.uid must be an integer between 1 and ${max}.`)\n }\n if (!Number.isInteger(identity.gid) || identity.gid < 0 || identity.gid > max) {\n throw new DeskError(`launcherIdentity.gid must be an integer between 0 and ${max}.`)\n }\n return { uid: identity.uid, gid: identity.gid }\n}\n\nfunction absolutePath(value: string, field: string): string {\n if (!value || !isAbsolute(value)) {\n throw new DeskError(`${field} must be an absolute path.`)\n }\n return resolve(value)\n}\n\nfunction positiveInteger(value: number, field: string): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new DeskError(`${field} must be a positive integer.`)\n }\n return value\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"virtualization.d.ts","sourceRoot":"","sources":["../src/virtualization.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAA;AAQjE,iGAAiG;AACjG,MAAM,WAAW,4BAA4B;IAC3C,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,mBAAmB,CAAA;IAC9B,OAAO,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,MAAM,CAAA;IACxC,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,sEAAsE;IACtE,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;CAC3B;AAED,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,4BAA4B,GAAG,WAAW,CAmG9F"}
1
+ {"version":3,"file":"virtualization.d.ts","sourceRoot":"","sources":["../src/virtualization.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAA;AAQjE,iGAAiG;AACjG,MAAM,WAAW,4BAA4B;IAC3C,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,mBAAmB,CAAA;IAC9B,OAAO,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,MAAM,CAAA;IACxC,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,sEAAsE;IACtE,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;CAC3B;AAED,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,4BAA4B,GAAG,WAAW,CA2G9F"}
package/virtualization.js CHANGED
@@ -5,7 +5,7 @@ import { dirname, isAbsolute, join } from 'node:path';
5
5
  import { createInterface } from 'node:readline';
6
6
  import { DeskError } from './plan.js';
7
7
  import { GUEST_AGENT_VSOCK_PORT } from './protocol.js';
8
- import { attemptHandshake, connectWithRetry, createGuestMachine, defaultConnect, drainOutput, errorMessage, runToCompletion, terminate, watchExit, } from './machine.js';
8
+ import { assertShareManifest, attemptHandshake, connectWithRetry, createGuestMachine, defaultConnect, drainOutput, errorMessage, runToCompletion, terminate, watchExit, writeShareManifest, } from './machine.js';
9
9
  export function createVirtualizationBackend(options) {
10
10
  if (options.consoleLogPath && !isAbsolute(options.consoleLogPath))
11
11
  throw new DeskError('consoleLogPath must be an absolute path.');
@@ -25,6 +25,12 @@ export function createVirtualizationBackend(options) {
25
25
  throw new DeskError('Virtualization requires macOS.');
26
26
  if (plan.overlay.create)
27
27
  await runToCompletion(launcher(plan.overlay.create.command, plan.overlay.create.args, { identity: plan.launcherIdentity }), `overlay creation for desk ${plan.deskId}`);
28
+ // A saved machine restores only into the device list it was saved with.
29
+ if (plan.snapshot.restoring) {
30
+ await assertShareManifest(plan.snapshot.dir, plan.shares).catch((error) => {
31
+ throw new DeskError(`Virtualization desk ${plan.deskId} cannot be restored: ${errorMessage(error)}`);
32
+ });
33
+ }
28
34
  await mkdir(dirname(plan.vsock.socketPath), { recursive: true, mode: 0o700 });
29
35
  const child = launcher(options.helperPath, [], { identity: plan.launcherIdentity });
30
36
  const exit = watchExit(child);
@@ -102,6 +108,7 @@ export function createVirtualizationBackend(options) {
102
108
  ...(options.consoleLogPath ? { consoleLog: options.consoleLogPath } : {}),
103
109
  disk: plan.overlay.path, memoryMb: plan.memoryMb, vcpus: plan.vcpus,
104
110
  vsockSocket: plan.vsock.socketPath, portSocket: plan.ports.socketPath,
111
+ shares: plan.shares.map(({ tag, path, readOnly }) => ({ tag, path, readOnly })),
105
112
  ...(plan.snapshot.restoring ? { restoreFrom: join(plan.snapshot.dir, 'state'), machineIdentifier: identifier } : {}),
106
113
  network: { ...plan.network, macAddress: plan.network.mac },
107
114
  });
@@ -130,6 +137,7 @@ export function createVirtualizationBackend(options) {
130
137
  try {
131
138
  await call('save', { path: join(dir, 'state') });
132
139
  await writeFile(join(dir, 'machine-id'), machineIdentifier, { mode: 0o600 });
140
+ await writeShareManifest(dir, plan.shares);
133
141
  }
134
142
  finally {
135
143
  await stop();