@adea-ai/app-framework 0.31.0 → 0.32.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 (107) hide show
  1. package/README.md +26 -11
  2. package/dist/app/create-application.js +4 -3
  3. package/dist/app/serial-queue.d.ts +5 -0
  4. package/dist/app/serial-queue.js +14 -0
  5. package/dist/app/value-guards.d.ts +15 -0
  6. package/dist/app/value-guards.js +29 -0
  7. package/dist/ci/toolchain-identity.js +1 -1
  8. package/dist/desktop/channel-proof.js +2 -1
  9. package/dist/desktop/client-asset-stream.js +6 -12
  10. package/dist/desktop/desktop-host.d.ts +25 -5
  11. package/dist/desktop/desktop-host.js +75 -20
  12. package/dist/framework-source.json +1 -1
  13. package/dist/installer/command-artifact.js +4 -3
  14. package/dist/installer/command-qualification-command.js +6 -5
  15. package/dist/installer/hosted-runner.d.ts +9 -2
  16. package/dist/installer/hosted-runner.js +18 -5
  17. package/dist/installer/installed-payload.js +20 -46
  18. package/dist/installer/installer-archive.d.ts +33 -0
  19. package/dist/installer/installer-archive.js +116 -0
  20. package/dist/installer/installer-ci-bootstrap.js +10 -6
  21. package/dist/installer/installer-extraction.js +54 -120
  22. package/dist/installer/installer-identity.js +33 -111
  23. package/dist/installer/installer-observation.js +3 -2
  24. package/dist/installer/installer-process-cleanup.js +7 -46
  25. package/dist/installer/installer-qualification-command.js +6 -5
  26. package/dist/installer/installer-upgrade-command.js +5 -5
  27. package/dist/installer/installer-worker-guard.js +2 -1
  28. package/dist/native/canonical-path.d.ts +5 -0
  29. package/dist/native/canonical-path.js +10 -0
  30. package/dist/native/cef-helper.js +5 -4
  31. package/dist/native/electrobun-source-patch.js +3 -2
  32. package/dist/native/{directory-exchange.d.ts → native-rename.d.ts} +2 -0
  33. package/dist/native/native-rename.js +126 -0
  34. package/dist/native/native-secret-store.js +2 -6
  35. package/dist/native/native-utilities.js +4 -4
  36. package/dist/native/posix-launcher-build.js +1 -1
  37. package/dist/native/posix-tree-removal.js +2 -2
  38. package/dist/native/windows-process.d.ts +9 -0
  39. package/dist/native/windows-process.js +60 -0
  40. package/dist/release/feed-release-cut.js +2 -1
  41. package/dist/release/framework-package-publish.js +1 -1
  42. package/dist/release/framework-update-lock.js +2 -1
  43. package/dist/release/github-cli.d.ts +18 -0
  44. package/dist/release/github-cli.js +13 -1
  45. package/dist/release/github-release-cut.js +3 -2
  46. package/dist/release/github-release-provenance.js +2 -1
  47. package/dist/release/github-release-publisher.js +2 -1
  48. package/dist/release/local-provenance.js +3 -2
  49. package/dist/release/local-release.js +6 -6
  50. package/dist/release/qualification-run.d.ts +25 -0
  51. package/dist/release/qualification-run.js +43 -0
  52. package/dist/release/release-artifact.js +3 -11
  53. package/dist/release/release-assets-plan.js +16 -6
  54. package/dist/release/release-config.js +14 -14
  55. package/dist/release/release-cut-command.js +14 -4
  56. package/dist/release/release-cut.js +3 -2
  57. package/dist/release/release-descriptor-staging.js +13 -27
  58. package/dist/release/release-finalize.js +2 -1
  59. package/dist/release/release-publication.js +3 -11
  60. package/dist/release/release-publish-command.js +15 -6
  61. package/dist/release/release-qualification.js +3 -2
  62. package/dist/release/retained-release-build.js +12 -12
  63. package/dist/update-helper.bundle.js +250 -190
  64. package/dist/updates/desktop-updater.js +53 -58
  65. package/dist/updates/packaged-launch-admission.js +3 -2
  66. package/dist/updates/packaged-release-config.js +6 -5
  67. package/dist/updates/release-feed.js +9 -9
  68. package/dist/updates/signed-release.js +5 -5
  69. package/dist/updates/stable-file.d.ts +18 -0
  70. package/dist/updates/stable-file.js +54 -1
  71. package/dist/updates/update-adapter.d.ts +2 -13
  72. package/dist/updates/update-arm.js +7 -5
  73. package/dist/updates/update-channel-store.js +7 -9
  74. package/dist/updates/update-discovery.js +30 -34
  75. package/dist/updates/update-download-cleanup.js +2 -1
  76. package/dist/updates/update-download.js +2 -4
  77. package/dist/updates/update-extraction.js +1 -1
  78. package/dist/updates/update-generation-lease.js +4 -3
  79. package/dist/updates/update-handoff-plan.js +3 -2
  80. package/dist/updates/update-helper.js +8 -6
  81. package/dist/updates/update-instance-lease.js +3 -2
  82. package/dist/updates/update-launch-gate.js +12 -25
  83. package/dist/updates/update-launch.js +3 -2
  84. package/dist/updates/update-lock.js +3 -2
  85. package/dist/updates/update-marker.js +3 -2
  86. package/dist/updates/update-process-fence.js +10 -39
  87. package/dist/updates/update-process-liveness.js +2 -1
  88. package/dist/updates/update-resume.js +26 -22
  89. package/dist/updates/update-retention-marker.js +7 -5
  90. package/dist/updates/update-retention-plan.js +2 -2
  91. package/dist/updates/update-retirement.js +40 -39
  92. package/dist/updates/update-state-store.js +29 -37
  93. package/dist/updates/update-state.d.ts +8 -3
  94. package/dist/updates/update-swap-stage.js +6 -5
  95. package/dist/updates/update-swap.d.ts +1 -1
  96. package/dist/updates/update-swap.js +8 -6
  97. package/package.json +4 -12
  98. package/src/desktop/client-asset-stream.ts +6 -12
  99. package/src/updates/update-adapter.ts +2 -14
  100. package/src/updates/update-state.ts +11 -2
  101. package/dist/native/directory-exchange.js +0 -90
  102. package/dist/native/exclusive-rename.d.ts +0 -2
  103. package/dist/native/exclusive-rename.js +0 -52
  104. package/dist/release/retention-dry-run.d.ts +0 -46
  105. package/dist/release/retention-dry-run.js +0 -94
  106. package/dist/updates/update-exclusive-rename.d.ts +0 -3
  107. package/dist/updates/update-exclusive-rename.js +0 -5
@@ -1,17 +1,16 @@
1
1
  import { assertSidecarNames, sidecarBundlePath } from "../native/app-bundle.js";
2
+ import { runnerTemp } from "./hosted-runner.js";
2
3
  import { assertBuildMetadata, assertInstallerContext, assertPayloadLayout, assertPortableAppName } from "./installer-layout.js";
4
+ import { hashFileAt } from "../updates/stable-file.js";
3
5
  import { assertNativeExecutable } from "./native-executable.js";
6
+ import { assertArchiveUnchanged, findArchiveMember, isWithin } from "./installer-archive.js";
4
7
  import { lstat, open, realpath, rm } from "node:fs/promises";
5
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ import { join, resolve } from "node:path";
6
9
  import { createHash } from "node:crypto";
7
10
  import { Parser } from "tar";
8
11
  import { once } from "node:events";
9
12
  import { createZstdDecompress } from "node:zlib";
10
13
  // src/installer/installed-payload.ts
11
- function within(root, path) {
12
- const value = relative(root, path);
13
- return value !== "" && value !== ".." && !value.startsWith(".." + sep) && !isAbsolute(value);
14
- }
15
14
  function cleanEnv(parent, forceLocal) {
16
15
  const env = {};
17
16
  for (const name of [
@@ -135,27 +134,12 @@ async function readMembers(archive, limits, collect) {
135
134
  }
136
135
  async function installed(path, root, limit) {
137
136
  const info = await lstat(path);
138
- if (!info.isFile() || info.isSymbolicLink() || !Number.isSafeInteger(info.size) || info.size < 1 || info.size > limit || !within(root, await realpath(path))) throw new Error("Invalid installed file");
139
- const file = await open(path, "r");
140
- try {
141
- const before = await file.stat();
142
- if (before.dev !== info.dev || before.ino !== info.ino || before.size !== info.size) throw new Error("Installed file changed");
143
- const hash = createHash("sha256");
144
- let size = 0;
145
- for await (const chunk of file.createReadStream({ autoClose: false })) {
146
- size += chunk.length;
147
- if (size > before.size) throw new Error("Installed file changed");
148
- hash.update(chunk);
149
- }
150
- const after = await file.stat();
151
- if (size !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.dev !== before.dev || after.ino !== before.ino) throw new Error("Installed file changed");
152
- return {
153
- digest: hash.digest("hex"),
154
- size
155
- };
156
- } finally {
157
- await file.close();
158
- }
137
+ if (!info.isFile() || info.isSymbolicLink() || !Number.isSafeInteger(info.size) || info.size < 1 || info.size > limit || !isWithin(root, await realpath(path))) throw new Error("Invalid installed file");
138
+ const { size, sha256 } = await hashFileAt(path, info, "Installed file changed");
139
+ return {
140
+ digest: sha256,
141
+ size
142
+ };
159
143
  }
160
144
  async function assertRuntimeBinary(path, platform) {
161
145
  const info = await lstat(path), file = await open(path, "r");
@@ -173,7 +157,7 @@ async function verifyInstalledPayload(options) {
173
157
  const sidecars = assertSidecarNames(options.sidecars ?? [], options.platform).map((name) => sidecarBundlePath(name, options.platform));
174
158
  if (!/^\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(options.version) || options.version.length > 64) throw new Error("Invalid installed version");
175
159
  const profile = await realpath(options.profile), root = await realpath(options.installedRoot), archive = resolve(options.archive);
176
- if (!(await lstat(profile)).isDirectory() || !(await lstat(root)).isDirectory() || !within(profile, root)) throw new Error("Installed root escapes isolated profile");
160
+ if (!(await lstat(profile)).isDirectory() || !(await lstat(root)).isDirectory() || !isWithin(profile, root)) throw new Error("Installed root escapes isolated profile");
177
161
  const { archiveInfo, entries } = await listArchive(archive, options.platform, env);
178
162
  assertPayloadLayout({
179
163
  platform: options.platform,
@@ -198,16 +182,11 @@ async function verifyInstalledPayload(options) {
198
182
  const metadata = name === "Resources/version.json" || name === "Resources/build.json";
199
183
  const limit = metadata ? 1048576 : name === `${bin}/bun${suffix}` || sidecars.includes(name) ? 268435456 : 67108864;
200
184
  const expected = `${prefix}/${name}`;
201
- const candidates = entries.filter((entry) => {
202
- const normalized = entry.replace(/^\.\//, "").replaceAll("\\", "/");
203
- return options.platform === "windows-x64" ? normalized.toLowerCase() === expected.toLowerCase() : normalized === expected;
204
- });
205
- if (candidates.length !== 1) throw new Error("Archive member missing or ambiguous");
206
185
  return {
207
186
  name,
208
187
  metadata,
209
188
  limit,
210
- path: candidates[0]
189
+ path: findArchiveMember(entries, expected, options.platform, "Archive member missing or ambiguous")
211
190
  };
212
191
  });
213
192
  const members = await readMembers(archive, new Map(selected.map(({ path, limit }) => [path, limit])), new Set(selected.filter(({ metadata }) => metadata).map(({ path }) => path)));
@@ -223,8 +202,7 @@ async function verifyInstalledPayload(options) {
223
202
  assertBuildMetadata(JSON.parse(member.bytes.toString("utf8")), options.renderer);
224
203
  }
225
204
  }
226
- const after = await lstat(archive);
227
- if (!after.isFile() || after.isSymbolicLink() || after.dev !== archiveInfo.dev || after.ino !== archiveInfo.ino || after.size !== archiveInfo.size || after.mtimeMs !== archiveInfo.mtimeMs) throw new Error("Staged archive changed during verification");
205
+ await assertArchiveUnchanged(archive, archiveInfo, "Staged archive changed during verification");
228
206
  return { files };
229
207
  }
230
208
  /** Extract only the candidate Bun executable to an isolated profile for guard preflight. */
@@ -232,9 +210,10 @@ async function extractCandidateRuntime(options) {
232
210
  const env = options.env ?? process.env;
233
211
  assertInstallerContext(env, options.platform, process.platform, process.arch);
234
212
  assertPortableAppName(options.appName);
235
- if (!env.RUNNER_TEMP || !isAbsolute(env.RUNNER_TEMP)) throw new Error("Missing runner temp directory");
236
- const tempRoot = await realpath(env.RUNNER_TEMP), profile = await realpath(options.profile), archive = resolve(options.archive);
237
- if (!within(tempRoot, profile) || !(await lstat(profile)).isDirectory()) throw new Error("Runtime profile escapes runner temp");
213
+ const temp = runnerTemp(env);
214
+ if (!temp) throw new Error("Missing runner temp directory");
215
+ const tempRoot = await realpath(temp), profile = await realpath(options.profile), archive = resolve(options.archive);
216
+ if (!isWithin(tempRoot, profile) || !(await lstat(profile)).isDirectory()) throw new Error("Runtime profile escapes runner temp");
238
217
  const { archiveInfo, tarEnv, entries } = await listArchive(archive, options.platform, env);
239
218
  assertPayloadLayout({
240
219
  platform: options.platform,
@@ -244,11 +223,7 @@ async function extractCandidateRuntime(options) {
244
223
  });
245
224
  const prefix = options.platform === "macos-arm64" ? `${options.appName}.app/Contents/MacOS` : `${options.appName.replaceAll(" ", "")}/bin`, suffix = options.platform === "windows-x64" ? ".exe" : "";
246
225
  const expected = `${prefix}/bun${suffix}`;
247
- const candidates = entries.filter((entry) => {
248
- const normalized = entry.replace(/^\.\//, "").replaceAll("\\", "/");
249
- return options.platform === "windows-x64" ? normalized.toLowerCase() === expected.toLowerCase() : normalized === expected;
250
- });
251
- if (candidates.length !== 1) throw new Error("Runtime archive member missing or ambiguous");
226
+ const member = findArchiveMember(entries, expected, options.platform, "Runtime archive member missing or ambiguous");
252
227
  const destination = join(profile, `candidate-bun${suffix}`), output = await open(destination, "wx", 448);
253
228
  const spawn = () => Bun.spawn({
254
229
  cmd: [
@@ -257,7 +232,7 @@ async function extractCandidateRuntime(options) {
257
232
  "-xOf",
258
233
  archive,
259
234
  "--",
260
- candidates[0]
235
+ member
261
236
  ],
262
237
  env: tarEnv,
263
238
  stdout: "pipe",
@@ -285,8 +260,7 @@ async function extractCandidateRuntime(options) {
285
260
  }
286
261
  if (await child.exited !== 0 || size < 4096) throw new Error("Invalid candidate runtime");
287
262
  await errors;
288
- const after = await lstat(archive);
289
- if (!after.isFile() || after.isSymbolicLink() || after.dev !== archiveInfo.dev || after.ino !== archiveInfo.ino || after.size !== archiveInfo.size || after.mtimeMs !== archiveInfo.mtimeMs) throw new Error("Staged archive changed during extraction");
263
+ await assertArchiveUnchanged(archive, archiveInfo, "Staged archive changed during extraction");
290
264
  const digest = hash.digest("hex");
291
265
  await output.sync();
292
266
  const copied = await installed(destination, profile, 268435456);
@@ -0,0 +1,33 @@
1
+ import type { Stats } from 'node:fs';
2
+ import type { InstallerPlatform } from './installer-layout';
3
+ /** Whether `path` lies strictly inside `root`, judged lexically. */
4
+ export declare function isWithin(root: string, path: string): boolean;
5
+ /** An archive member name without a leading `./`, with `/` separators. */
6
+ export declare function normalizeArchiveMember(name: string): string;
7
+ /** The one listed member named `expected` (case-insensitively on Windows), else `message`. */
8
+ export declare function findArchiveMember(entries: readonly string[], expected: string, platform: InstallerPlatform, message: string): string;
9
+ /** Fail with `message` unless `archive` is still the regular file `before` (lstat) described. */
10
+ export declare function assertArchiveUnchanged(archive: string, before: Stats, message: string): Promise<void>;
11
+ /**
12
+ * Stream one archive member through `tar -xOf` into a new private file, refusing
13
+ * members larger than `maximum`, and return its size. Installer stderr is drained
14
+ * and discarded; a failed or empty extraction rejects.
15
+ */
16
+ export declare function extractArchiveMember(options: {
17
+ tar: string;
18
+ archive: string;
19
+ member: string;
20
+ destination: string;
21
+ maximum: number;
22
+ env: Record<string, string>;
23
+ }): Promise<number>;
24
+ /** Require a regular, native executable for `platform` at `path`. */
25
+ export declare function assertInstallerExecutable(path: string, platform: InstallerPlatform): Promise<void>;
26
+ /**
27
+ * Require that a Linux self-extracting installer of `size` bytes ends with the
28
+ * Electrobun archive marker followed by exactly the release archive.
29
+ */
30
+ export declare function assertEmbeddedArchive(path: string, size: number, archive: {
31
+ size: number;
32
+ digest: string;
33
+ }): Promise<void>;
@@ -0,0 +1,116 @@
1
+ import { sameFile } from "../updates/stable-file.js";
2
+ import { assertNativeExecutable } from "./native-executable.js";
3
+ import { lstat, open } from "node:fs/promises";
4
+ import { isAbsolute, relative, sep } from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ // src/installer/installer-archive.ts
7
+ var EMBEDDED_ARCHIVE_MARKER = Buffer.from("ELECTROBUN_ARCHIVE_V1");
8
+ /** Whether `path` lies strictly inside `root`, judged lexically. */
9
+ function isWithin(root, path) {
10
+ const rel = relative(root, path);
11
+ return rel !== "" && rel !== ".." && !rel.startsWith(".." + sep) && !isAbsolute(rel);
12
+ }
13
+ /** An archive member name without a leading `./`, with `/` separators. */
14
+ function normalizeArchiveMember(name) {
15
+ return name.replace(/^\.\//, "").replaceAll("\\", "/");
16
+ }
17
+ /** The one listed member named `expected` (case-insensitively on Windows), else `message`. */
18
+ function findArchiveMember(entries, expected, platform, message) {
19
+ const windows = platform === "windows-x64", wanted = windows ? expected.toLowerCase() : expected;
20
+ const found = entries.filter((entry) => {
21
+ const name = normalizeArchiveMember(entry);
22
+ return (windows ? name.toLowerCase() : name) === wanted;
23
+ });
24
+ if (found.length !== 1) throw new Error(message);
25
+ return found[0];
26
+ }
27
+ /** Fail with `message` unless `archive` is still the regular file `before` (lstat) described. */
28
+ async function assertArchiveUnchanged(archive, before, message) {
29
+ const after = await lstat(archive);
30
+ if (!after.isFile() || after.isSymbolicLink() || !sameFile(after, before)) throw new Error(message);
31
+ }
32
+ /**
33
+ * Stream one archive member through `tar -xOf` into a new private file, refusing
34
+ * members larger than `maximum`, and return its size. Installer stderr is drained
35
+ * and discarded; a failed or empty extraction rejects.
36
+ */
37
+ async function extractArchiveMember(options) {
38
+ const output = await open(options.destination, "wx", 384);
39
+ try {
40
+ const child = Bun.spawn({
41
+ cmd: [
42
+ options.tar,
43
+ "-xOf",
44
+ options.archive,
45
+ options.member
46
+ ],
47
+ env: options.env,
48
+ stdout: "pipe",
49
+ stderr: "pipe",
50
+ signal: AbortSignal.timeout(12e4)
51
+ });
52
+ const errors = (async () => {
53
+ for await (const _chunk of child.stderr);
54
+ })();
55
+ let count = 0;
56
+ try {
57
+ for await (const chunk of child.stdout) {
58
+ count += chunk.length;
59
+ if (!Number.isSafeInteger(count) || count > options.maximum) throw new Error("Installer member exceeds bound");
60
+ let offset = 0;
61
+ while (offset < chunk.length) {
62
+ const result = await output.write(chunk, offset, chunk.length - offset);
63
+ if (!result.bytesWritten) throw new Error("Cannot extract installer member");
64
+ offset += result.bytesWritten;
65
+ }
66
+ }
67
+ if (await child.exited !== 0 || count === 0) throw new Error("Cannot extract installer member");
68
+ await errors;
69
+ return count;
70
+ } catch (error) {
71
+ child.kill();
72
+ await child.exited;
73
+ await errors;
74
+ throw error;
75
+ }
76
+ } finally {
77
+ await output.close();
78
+ }
79
+ }
80
+ /** Require a regular, native executable for `platform` at `path`. */
81
+ async function assertInstallerExecutable(path, platform) {
82
+ const info = await lstat(path);
83
+ if (!info.isFile() || info.isSymbolicLink() || info.size < 4096) throw new Error("Invalid installer executable");
84
+ const file = await open(path, "r");
85
+ try {
86
+ await assertNativeExecutable(file, info.size, platform, "installer executable");
87
+ } finally {
88
+ await file.close();
89
+ }
90
+ }
91
+ /**
92
+ * Require that a Linux self-extracting installer of `size` bytes ends with the
93
+ * Electrobun archive marker followed by exactly the release archive.
94
+ */
95
+ async function assertEmbeddedArchive(path, size, archive) {
96
+ const marker = EMBEDDED_ARCHIVE_MARKER;
97
+ if (size <= archive.size + marker.length) throw new Error("Installer archive is incomplete");
98
+ const file = await open(path, "r");
99
+ try {
100
+ const position = size - archive.size - marker.length, actual = Buffer.alloc(marker.length);
101
+ if ((await file.read(actual, 0, actual.length, position)).bytesRead !== actual.length || !actual.equals(marker)) throw new Error("Installer archive marker is missing");
102
+ const hash = createHash("sha256");
103
+ let read = 0;
104
+ for await (const chunk of file.createReadStream({
105
+ start: position + marker.length,
106
+ autoClose: false
107
+ })) {
108
+ read += chunk.length;
109
+ hash.update(chunk);
110
+ }
111
+ if (read !== archive.size || "sha256:" + hash.digest("hex") !== archive.digest) throw new Error("Installer archive differs from release archive");
112
+ } finally {
113
+ await file.close();
114
+ }
115
+ }
116
+ export { assertArchiveUnchanged, assertEmbeddedArchive, assertInstallerExecutable, extractArchiveMember, findArchiveMember, isWithin, normalizeArchiveMember };
@@ -1,4 +1,5 @@
1
- import { isHostedRunner } from "./hosted-runner.js";
1
+ import { errorCode } from "../app/value-guards.js";
2
+ import { isHostedRunner, runnerTemp } from "./hosted-runner.js";
2
3
  import { lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
3
4
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
4
5
  import { randomBytes } from "node:crypto";
@@ -6,6 +7,7 @@ import { fileURLToPath } from "node:url";
6
7
  // src/installer/installer-ci-bootstrap.ts
7
8
  /** The modules copied into the runner. The worker and preflight scripts import the rest. */
8
9
  var bootstrapModules = [
10
+ "app/value-guards.js",
9
11
  "installer/installer-ci-worker.js",
10
12
  "installer/installer-ci-preflight.js",
11
13
  "installer/installer-worker-guard.js",
@@ -18,8 +20,9 @@ var bootstrapModules = [
18
20
  ];
19
21
  /** Copy a bounded external preload into the current disposable runner's temp directory. */
20
22
  async function prepareInstallerCiBootstrap(env = process.env) {
21
- if (!isHostedRunner(env) || !env.RUNNER_TEMP || !isAbsolute(env.RUNNER_TEMP)) throw new Error("Installer bootstrap requires a disposable GitHub-hosted runner");
22
- const parent = await realpath(env.RUNNER_TEMP);
23
+ const temp = runnerTemp(env);
24
+ if (!isHostedRunner(env) || !temp) throw new Error("Installer bootstrap requires a disposable hosted runner");
25
+ const parent = await realpath(temp);
23
26
  if (/\s/.test(parent) || !(await lstat(parent)).isDirectory()) throw new Error("Runner temp cannot represent a Bun preload path");
24
27
  const source = dirname(dirname(fileURLToPath(import.meta.url)));
25
28
  const directory = await mkdtemp(join(parent, "framework-ci-"));
@@ -60,8 +63,9 @@ async function prepareInstallerCiBootstrap(env = process.env) {
60
63
  /** Exercise the externally prepared guard with the actual candidate Bun runtime. */
61
64
  async function preflightInstallerRuntime(options) {
62
65
  const { env, runtime, bootstrap } = options;
63
- if (!isHostedRunner(env) || !env.RUNNER_TEMP || !isAbsolute(env.RUNNER_TEMP) || !isAbsolute(runtime)) throw new Error("Runtime preflight requires a disposable hosted runner");
64
- const tempRoot = await realpath(env.RUNNER_TEMP), bootstrapRoot = await realpath(bootstrap.directory);
66
+ const temp = runnerTemp(env);
67
+ if (!isHostedRunner(env) || !temp || !isAbsolute(runtime)) throw new Error("Runtime preflight requires a disposable hosted runner");
68
+ const tempRoot = await realpath(temp), bootstrapRoot = await realpath(bootstrap.directory);
65
69
  const relativeBootstrap = relative(tempRoot, bootstrapRoot);
66
70
  if (!relativeBootstrap || relativeBootstrap === ".." || relativeBootstrap.startsWith(".." + sep) || isAbsolute(relativeBootstrap) || /\s/.test(bootstrapRoot) || bootstrap.worker !== join(bootstrapRoot, "installer/installer-ci-worker.js") || bootstrap.preflight !== join(bootstrapRoot, "installer/installer-ci-preflight.js") || bootstrap.bunOptions !== `--preload=${bootstrap.worker}`) throw new Error("Invalid installer bootstrap location");
67
71
  await runInstallerPreflight({
@@ -149,7 +153,7 @@ async function runInstallerPreflight(options) {
149
153
  await lstat(join(temporary, "unexpected"));
150
154
  throw new Error("Runtime preflight recorded unexpected activity");
151
155
  } catch (error) {
152
- if (error.code !== "ENOENT") throw error;
156
+ if (errorCode(error) !== "ENOENT") throw error;
153
157
  }
154
158
  } finally {
155
159
  await rm(temporary, {
@@ -1,11 +1,12 @@
1
+ import { runnerTemp } from "./hosted-runner.js";
1
2
  import { assertInstallerContext, assertInstallerLayout, assertPortableAppName } from "./installer-layout.js";
2
- import { assertNativeExecutable } from "./native-executable.js";
3
+ import { hashFileAt } from "../updates/stable-file.js";
4
+ import { assertEmbeddedArchive, assertInstallerExecutable, extractArchiveMember, findArchiveMember, isWithin } from "./installer-archive.js";
3
5
  import { cleanupInstallerDirectoryAfterFailure, defaultInstallerImageMountIo, withInstallerImageRetries } from "./installer-image-mount.js";
4
6
  import { runInstallerCommand } from "./installer-command.js";
5
7
  import { verifyInstallerPayload } from "./installer-identity.js";
6
- import { chmod, lstat, mkdir, mkdtemp, open, readdir, realpath } from "node:fs/promises";
7
- import { isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
8
- import { createHash } from "node:crypto";
8
+ import { chmod, lstat, mkdir, mkdtemp, readdir, realpath } from "node:fs/promises";
9
+ import { join, resolve, win32 } from "node:path";
9
10
  // src/installer/installer-extraction.ts
10
11
  async function run(cmd, env) {
11
12
  return runInstallerCommand(cmd, env, {
@@ -14,106 +15,14 @@ async function run(cmd, env) {
14
15
  failureMessage: "Installer preparation command failed"
15
16
  });
16
17
  }
17
- async function extract(tar, archive, member, destination, maximum, env) {
18
- const output = await open(destination, "wx", 384);
19
- const spawn = () => Bun.spawn({
20
- cmd: [
21
- tar,
22
- "-xOf",
23
- archive,
24
- member
25
- ],
26
- env,
27
- stdout: "pipe",
28
- stderr: "pipe",
29
- signal: AbortSignal.timeout(12e4)
30
- });
31
- try {
32
- const child = spawn();
33
- const errors = (async () => {
34
- for await (const _chunk of child.stderr);
35
- })();
36
- let count = 0;
37
- try {
38
- for await (const chunk of child.stdout) {
39
- count += chunk.length;
40
- if (!Number.isSafeInteger(count) || count > maximum) throw new Error("Installer member exceeds bound");
41
- let offset = 0;
42
- while (offset < chunk.length) {
43
- const result = await output.write(chunk, offset, chunk.length - offset);
44
- if (!result.bytesWritten) throw new Error("Cannot copy installer member");
45
- offset += result.bytesWritten;
46
- }
47
- }
48
- if (await child.exited !== 0 || count === 0) throw new Error("Cannot copy installer member");
49
- await errors;
50
- } catch (error) {
51
- child.kill();
52
- await child.exited;
53
- await errors;
54
- throw error;
55
- }
56
- } finally {
57
- await output.close();
58
- }
59
- }
60
18
  async function digest(path) {
61
19
  const info = await lstat(path);
62
20
  if (!info.isFile() || info.isSymbolicLink() || !Number.isSafeInteger(info.size) || info.size < 1) throw new Error("Invalid extracted file");
63
- const file = await open(path, "r");
64
- try {
65
- const before = await file.stat();
66
- if (before.dev !== info.dev || before.ino !== info.ino || before.size !== info.size) throw new Error("Extracted file changed");
67
- const hash = createHash("sha256");
68
- let size = 0;
69
- for await (const chunk of file.createReadStream({ autoClose: false })) {
70
- size += chunk.length;
71
- if (size > before.size) throw new Error("Extracted file changed");
72
- hash.update(chunk);
73
- }
74
- const after = await file.stat();
75
- if (size !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ino !== before.ino || after.dev !== before.dev) throw new Error("Extracted file changed");
76
- return {
77
- size,
78
- digest: "sha256:" + hash.digest("hex")
79
- };
80
- } finally {
81
- await file.close();
82
- }
83
- }
84
- function normalizeArchiveMember(name) {
85
- return name.replace(/^\.\//, "").replaceAll("\\", "/");
86
- }
87
- async function assertExecutable(path, platform) {
88
- const info = await lstat(path);
89
- if (!info.isFile() || info.isSymbolicLink() || info.size < 4096) throw new Error("Invalid copied installer executable");
90
- const file = await open(path, "r");
91
- try {
92
- await assertNativeExecutable(file, info.size, platform, "installer executable");
93
- } finally {
94
- await file.close();
95
- }
96
- }
97
- async function assertLinuxEmbedded(path, archive) {
98
- const info = await lstat(path), marker = Buffer.from("ELECTROBUN_ARCHIVE_V1");
99
- if (info.size <= archive.size + marker.length) throw new Error("Copied installer archive is incomplete");
100
- const file = await open(path, "r");
101
- try {
102
- const position = info.size - archive.size - marker.length, actual = Buffer.alloc(marker.length);
103
- if ((await file.read(actual, 0, actual.length, position)).bytesRead !== actual.length || !actual.equals(marker)) throw new Error("Copied installer archive marker missing");
104
- const hash = createHash("sha256");
105
- for await (const chunk of file.createReadStream({
106
- start: position + marker.length,
107
- autoClose: false
108
- })) hash.update(chunk);
109
- if ("sha256:" + hash.digest("hex") !== archive.digest) throw new Error("Copied installer archive differs");
110
- } finally {
111
- await file.close();
112
- }
113
- }
114
- function within(root, value) {
115
- const path = relative(root, value);
116
- return path !== "" && path !== ".." && !path.startsWith(".." + sep) && !isAbsolute(path);
21
+ const { size, sha256 } = await hashFileAt(path, info, "Extracted file changed");
22
+ return {
23
+ size,
24
+ digest: "sha256:" + sha256
25
+ };
117
26
  }
118
27
  function cleanEnv(parent) {
119
28
  const result = {};
@@ -139,8 +48,9 @@ async function prepareInstallerExecution(options) {
139
48
  const env = options.env ?? process.env;
140
49
  assertInstallerContext(env, options.platform, process.platform, process.arch);
141
50
  assertPortableAppName(options.appName);
142
- if (!env.RUNNER_TEMP || !isAbsolute(env.RUNNER_TEMP)) throw new Error("Missing runner temp directory");
143
- const parent = await realpath(env.RUNNER_TEMP), sourceInstaller = resolve(options.installer), sourceArchive = resolve(options.archive);
51
+ const temp = runnerTemp(env);
52
+ if (!temp) throw new Error("Missing runner temp directory");
53
+ const parent = await realpath(temp), sourceInstaller = resolve(options.installer), sourceArchive = resolve(options.archive);
144
54
  if (!(await lstat(parent)).isDirectory()) throw new Error("Invalid runner temp directory");
145
55
  const verified = await verifyInstallerPayload({
146
56
  ...options,
@@ -165,8 +75,8 @@ async function prepareInstallerExecution(options) {
165
75
  work: async (mount) => {
166
76
  const appName = `${options.appName}.app`, apps = (await readdir(mount)).filter((name) => name.endsWith(".app"));
167
77
  if (apps.length !== 1 || apps[0] !== appName) throw new Error("Unexpected installer application");
168
- const sourceApp = await realpath(join(mount, appName));
169
- if (!within(await realpath(mount), sourceApp)) throw new Error("Installer application escapes image");
78
+ const sourceApp = await realpath(join(mount, appName)), mountRoot = await realpath(mount);
79
+ if (!isWithin(mountRoot, sourceApp)) throw new Error("Installer application escapes image");
170
80
  const app = join(incoming, appName);
171
81
  await run([
172
82
  "/usr/bin/ditto",
@@ -174,7 +84,7 @@ async function prepareInstallerExecution(options) {
174
84
  app
175
85
  ], clean);
176
86
  const actualApp = await realpath(app), resources = await realpath(join(actualApp, "Contents", "Resources"));
177
- if (!within(await realpath(incoming), actualApp) || !within(actualApp, resources)) throw new Error("Copied installer escapes profile");
87
+ if (!isWithin(await realpath(incoming), actualApp) || !isWithin(actualApp, resources)) throw new Error("Copied installer escapes profile");
178
88
  const plist = join(actualApp, "Contents", "Info.plist"), plistInfo = await lstat(plist);
179
89
  if (!plistInfo.isFile() || plistInfo.isSymbolicLink() || plistInfo.size < 1 || plistInfo.size > 1048576) throw new Error("Invalid installer property list");
180
90
  const name = (await run([
@@ -186,8 +96,8 @@ async function prepareInstallerExecution(options) {
186
96
  if (!name || name === "." || name === ".." || /[\\/]/.test(name)) throw new Error("Invalid installer executable");
187
97
  const appExecutable = join(actualApp, "Contents", "MacOS", name);
188
98
  const sourceExecutable = join(sourceApp, "Contents", "MacOS", name);
189
- if (!within(actualApp, await realpath(appExecutable)) || !within(sourceApp, await realpath(sourceExecutable))) throw new Error("Installer executable escapes application");
190
- await assertExecutable(appExecutable, options.platform);
99
+ if (!isWithin(actualApp, await realpath(appExecutable)) || !isWithin(sourceApp, await realpath(sourceExecutable))) throw new Error("Installer executable escapes application");
100
+ await assertInstallerExecutable(appExecutable, options.platform);
191
101
  if (JSON.stringify(await digest(sourceExecutable)) !== JSON.stringify(await digest(appExecutable))) throw new Error("Copied installer executable differs");
192
102
  const archives = (await readdir(resources)).filter((value) => value.endsWith(".tar.zst"));
193
103
  if (archives.length !== 1) throw new Error("Missing installer archive");
@@ -206,27 +116,51 @@ async function prepareInstallerExecution(options) {
206
116
  sourceInstaller
207
117
  ], clean)).split(/\r?\n/).filter(Boolean);
208
118
  assertInstallerLayout(options.platform, options.appName, names);
209
- const find = (name) => {
210
- const found = names.filter((value) => options.platform === "windows-x64" ? normalizeArchiveMember(value).toLowerCase() === name.toLowerCase() : normalizeArchiveMember(value) === name);
211
- if (found.length !== 1) throw new Error("Installer member missing or ambiguous");
212
- return found[0];
213
- };
119
+ const find = (name) => findArchiveMember(names, name, options.platform, "Installer member missing or ambiguous");
214
120
  if (options.platform === "windows-x64") {
215
121
  const subdirectory = join(incoming, ".installer");
216
122
  await mkdir(subdirectory);
217
123
  executable = join(incoming, `${options.appName}-Setup.exe`);
218
- await extract(tar, sourceInstaller, find(`${options.appName}-Setup.exe`), executable, 268435456, clean);
219
- await assertExecutable(executable, options.platform);
220
- await extract(tar, sourceInstaller, find(`.installer/${options.appName}-Setup.metadata.json`), join(subdirectory, `${options.appName}-Setup.metadata.json`), 1048576, clean);
124
+ await extractArchiveMember({
125
+ tar,
126
+ archive: sourceInstaller,
127
+ member: find(`${options.appName}-Setup.exe`),
128
+ destination: executable,
129
+ maximum: 268435456,
130
+ env: clean
131
+ });
132
+ await assertInstallerExecutable(executable, options.platform);
133
+ await extractArchiveMember({
134
+ tar,
135
+ archive: sourceInstaller,
136
+ member: find(`.installer/${options.appName}-Setup.metadata.json`),
137
+ destination: join(subdirectory, `${options.appName}-Setup.metadata.json`),
138
+ maximum: 1048576,
139
+ env: clean
140
+ });
221
141
  const embeddedPath = join(subdirectory, `${options.appName}-Setup.tar.zst`);
222
- await extract(tar, sourceInstaller, find(`.installer/${options.appName}-Setup.tar.zst`), embeddedPath, verified.archive.size, clean);
142
+ await extractArchiveMember({
143
+ tar,
144
+ archive: sourceInstaller,
145
+ member: find(`.installer/${options.appName}-Setup.tar.zst`),
146
+ destination: embeddedPath,
147
+ maximum: verified.archive.size,
148
+ env: clean
149
+ });
223
150
  const embedded = await digest(embeddedPath);
224
151
  if (embedded.size !== verified.archive.size || embedded.digest !== verified.archive.digest) throw new Error("Copied installer archive differs");
225
152
  } else {
226
153
  executable = join(incoming, "installer");
227
- await extract(tar, sourceInstaller, find("installer"), executable, verified.archive.size + 268435456, clean);
228
- await assertExecutable(executable, options.platform);
229
- await assertLinuxEmbedded(executable, verified.archive);
154
+ await extractArchiveMember({
155
+ tar,
156
+ archive: sourceInstaller,
157
+ member: find("installer"),
158
+ destination: executable,
159
+ maximum: verified.archive.size + 268435456,
160
+ env: clean
161
+ });
162
+ await assertInstallerExecutable(executable, options.platform);
163
+ await assertEmbeddedArchive(executable, (await lstat(executable)).size, verified.archive);
230
164
  await chmod(executable, 448);
231
165
  }
232
166
  }