@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,36 +1,21 @@
1
1
  import { assertInstallerContext, assertInstallerHost, assertInstallerLayout, assertPortableAppName } from "./installer-layout.js";
2
- import { assertNativeExecutable } from "./native-executable.js";
2
+ import { hashFileAt } from "../updates/stable-file.js";
3
+ import { assertEmbeddedArchive, assertInstallerExecutable, extractArchiveMember, findArchiveMember, isWithin, normalizeArchiveMember } from "./installer-archive.js";
3
4
  import { InstallerImageLifecycleError, cleanupInstallerDirectoryAfterFailure, defaultInstallerImageMountIo, installerImageMountState, withInstallerImageRetries } from "./installer-image-mount.js";
4
5
  import { runInstallerCommand } from "./installer-command.js";
5
- import { lstat, mkdtemp, open, readdir, realpath } from "node:fs/promises";
6
- import { basename, dirname, isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
7
- import { createHash } from "node:crypto";
6
+ import { lstat, mkdtemp, readdir, realpath } from "node:fs/promises";
7
+ import { basename, dirname, join, resolve, win32 } from "node:path";
8
8
  import { tmpdir } from "node:os";
9
9
  // src/installer/installer-identity.ts
10
10
  async function identity(path) {
11
11
  const info = await lstat(path);
12
12
  if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || !Number.isSafeInteger(info.size)) throw new Error("Invalid installer artifact");
13
- const file = await open(path, "r");
14
- try {
15
- const before = await file.stat();
16
- if (before.ino !== info.ino || before.dev !== info.dev || before.size !== info.size) throw new Error("Installer artifact changed");
17
- const hash = createHash("sha256");
18
- let size = 0;
19
- for await (const chunk of file.createReadStream({ autoClose: false })) {
20
- size += chunk.length;
21
- if (size > before.size) throw new Error("Installer artifact changed");
22
- hash.update(chunk);
23
- }
24
- const after = await file.stat();
25
- if (size !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ino !== before.ino || after.dev !== before.dev) throw new Error("Installer artifact changed");
26
- return {
27
- name: basename(path),
28
- size,
29
- digest: "sha256:" + hash.digest("hex")
30
- };
31
- } finally {
32
- await file.close();
33
- }
13
+ const { size, sha256 } = await hashFileAt(path, info, "Installer artifact changed");
14
+ return {
15
+ name: basename(path),
16
+ size,
17
+ digest: "sha256:" + sha256
18
+ };
34
19
  }
35
20
  function environment(parent) {
36
21
  const env = {};
@@ -103,68 +88,6 @@ async function command(args, env) {
103
88
  failureMessage: "Installer inspection command failed"
104
89
  });
105
90
  }
106
- async function extractMember(tar, installer, member, output, maximum, env) {
107
- const file = await open(output, "wx", 384);
108
- const spawn = () => Bun.spawn({
109
- cmd: [
110
- tar,
111
- "-xOf",
112
- installer,
113
- member
114
- ],
115
- env,
116
- stdout: "pipe",
117
- stderr: "pipe",
118
- signal: AbortSignal.timeout(12e4)
119
- });
120
- let child;
121
- try {
122
- child = spawn();
123
- } catch (error) {
124
- await file.close();
125
- throw error;
126
- }
127
- const errors = (async () => {
128
- for await (const _chunk of child.stderr);
129
- })();
130
- let count = 0;
131
- try {
132
- for await (const chunk of child.stdout) {
133
- count += chunk.length;
134
- if (!Number.isSafeInteger(count) || count > maximum) throw new Error("Installer member exceeds bound");
135
- let offset = 0;
136
- while (offset < chunk.length) {
137
- const result = await file.write(chunk, offset, chunk.length - offset);
138
- if (!result.bytesWritten) throw new Error("Cannot read installer member");
139
- offset += result.bytesWritten;
140
- }
141
- }
142
- if (await child.exited !== 0) throw new Error("Cannot read installer member");
143
- await errors;
144
- return count;
145
- } catch (error) {
146
- child.kill();
147
- await child.exited;
148
- await errors;
149
- throw error;
150
- } finally {
151
- await file.close();
152
- }
153
- }
154
- async function assertExecutable(path, platform) {
155
- const info = await lstat(path);
156
- if (!info.isFile() || info.isSymbolicLink() || info.size < 4096) throw new Error("Invalid installer executable");
157
- const file = await open(path, "r");
158
- try {
159
- await assertNativeExecutable(file, info.size, platform, "installer executable");
160
- } finally {
161
- await file.close();
162
- }
163
- }
164
- function within(root, path) {
165
- const rel = relative(root, path);
166
- return rel !== "" && rel !== ".." && !rel.startsWith(".." + sep) && !isAbsolute(rel);
167
- }
168
91
  /**
169
92
  * Inspect a shipped installer without executing it, on a matching disposable runner, or with
170
93
  * `local` on the maintainer's own matching machine for a local release (read-only inspection of
@@ -198,7 +121,7 @@ async function verifyInstallerPayload(options) {
198
121
  if (apps.length !== 1) throw new Error("Installer application is missing or ambiguous");
199
122
  const resources = join(mount, apps[0], "Contents", "Resources");
200
123
  const actualRoot = await realpath(mount), actualApp = await realpath(join(mount, apps[0])), actualResources = await realpath(resources);
201
- if (!within(actualRoot, actualApp) || !within(actualApp, actualResources)) throw new Error("Installer resources escape mounted image");
124
+ if (!isWithin(actualRoot, actualApp) || !isWithin(actualApp, actualResources)) throw new Error("Installer resources escape mounted image");
202
125
  const plist = join(actualApp, "Contents", "Info.plist"), plistInfo = await lstat(plist);
203
126
  if (!plistInfo.isFile() || plistInfo.isSymbolicLink() || plistInfo.size < 1 || plistInfo.size > 1048576) throw new Error("Invalid installer property list");
204
127
  const executable = (await command([
@@ -208,7 +131,7 @@ async function verifyInstallerPayload(options) {
208
131
  plist
209
132
  ], env)).trim();
210
133
  if (!executable || executable === "." || executable === ".." || /[\\/]/.test(executable)) throw new Error("Invalid installer executable name");
211
- await assertExecutable(join(actualApp, "Contents", "MacOS", executable), options.platform);
134
+ await assertInstallerExecutable(join(actualApp, "Contents", "MacOS", executable), options.platform);
212
135
  const archives = (await readdir(actualResources)).filter((name) => name.endsWith(".tar.zst"));
213
136
  if (archives.length !== 1) throw new Error("Installer archive is missing or ambiguous");
214
137
  const embedded = await identity(join(actualResources, archives[0]));
@@ -227,35 +150,34 @@ async function verifyInstallerPayload(options) {
227
150
  ], env)).split(/\r?\n/).filter(Boolean);
228
151
  assertInstallerLayout(options.platform, options.appName, names);
229
152
  const candidates = options.platform === "windows-x64" ? [`.installer/${options.appName}-Setup.tar.zst`] : ["installer"];
230
- const matches = names.filter((name) => candidates.includes(name.replace(/^\.\//, "").replaceAll("\\", "/")));
153
+ const matches = names.filter((name) => candidates.includes(normalizeArchiveMember(name)));
231
154
  if (matches.length !== 1) throw new Error("Installer archive is missing or ambiguous");
232
155
  const extracted = join(temporary, "member");
233
- const count = await extractMember(tar, installerPath, matches[0], extracted, before.archive.size + 268435456, env);
156
+ const count = await extractArchiveMember({
157
+ tar,
158
+ archive: installerPath,
159
+ member: matches[0],
160
+ destination: extracted,
161
+ maximum: before.archive.size + 268435456,
162
+ env
163
+ });
234
164
  if (options.platform === "windows-x64") {
235
- const setup = names.find((name) => name.replace(/^\.\//, "").replaceAll("\\", "/").toLowerCase() === `${options.appName}-Setup.exe`.toLowerCase());
236
- if (!setup) throw new Error("Installer executable is missing");
165
+ const setup = findArchiveMember(names, `${options.appName}-Setup.exe`, options.platform, "Installer executable is missing or ambiguous");
237
166
  const executable = join(temporary, "setup.exe");
238
- await extractMember(tar, installerPath, setup, executable, 268435456, env);
239
- await assertExecutable(executable, options.platform);
167
+ await extractArchiveMember({
168
+ tar,
169
+ archive: installerPath,
170
+ member: setup,
171
+ destination: executable,
172
+ maximum: 268435456,
173
+ env
174
+ });
175
+ await assertInstallerExecutable(executable, options.platform);
240
176
  const embedded = await identity(extracted);
241
177
  if (embedded.size !== before.archive.size || embedded.digest !== before.archive.digest) throw new Error("Installer archive differs from release archive");
242
178
  } else {
243
- await assertExecutable(extracted, options.platform);
244
- const marker = Buffer.from("ELECTROBUN_ARCHIVE_V1");
245
- if (count <= before.archive.size + marker.length) throw new Error("Installer archive is incomplete");
246
- const file = await open(extracted, "r");
247
- try {
248
- const position = count - before.archive.size - marker.length, actual = Buffer.alloc(marker.length);
249
- if ((await file.read(actual, 0, actual.length, position)).bytesRead !== actual.length || !actual.equals(marker)) throw new Error("Installer archive marker is missing");
250
- const hash = createHash("sha256");
251
- for await (const chunk of file.createReadStream({
252
- start: position + marker.length,
253
- autoClose: false
254
- })) hash.update(chunk);
255
- if ("sha256:" + hash.digest("hex") !== before.archive.digest) throw new Error("Installer archive differs from release archive");
256
- } finally {
257
- await file.close();
258
- }
179
+ await assertInstallerExecutable(extracted, options.platform);
180
+ await assertEmbeddedArchive(extracted, count, before.archive);
259
181
  }
260
182
  }
261
183
  const after = {
@@ -1,3 +1,4 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { assertInstallerContext, assertPortableAppName } from "./installer-layout.js";
2
3
  import { parseOfflinePolicy } from "../release/release-qualification.js";
3
4
  import { verifyInstallerPayload } from "./installer-identity.js";
@@ -69,7 +70,7 @@ async function exists(path) {
69
70
  await lstat(path);
70
71
  return true;
71
72
  } catch (error) {
72
- if (error.code === "ENOENT") return false;
73
+ if (errorCode(error) === "ENOENT") return false;
73
74
  throw error;
74
75
  }
75
76
  }
@@ -313,7 +314,7 @@ async function observeInstalledApp(options) {
313
314
  process.kill(guardedPid, 0);
314
315
  workerState = "present";
315
316
  } catch (error) {
316
- workerState = error.code === "ESRCH" ? "exited" : "unknown";
317
+ workerState = errorCode(error) === "ESRCH" ? "exited" : "unknown";
317
318
  }
318
319
  const appState = app ? app.exitCode ?? "running" : mac ? "not-spawned" : "installer-launched";
319
320
  throw new Error(`Installed renderer observation missing or unexpected activity observed (start=${run.start}, permitted=${granted}, observed=${observed}, unexpected=${unexpectedObserved}, workerPid=${workerState}, installerExit=${installer ? installer.exitCode ?? "running" : "none"}, appExit=${appState})`);
@@ -1,6 +1,6 @@
1
1
  import { assertInstallerContext } from "./installer-layout.js";
2
+ import { windowsProcessImage } from "../native/windows-process.js";
2
3
  import { realpath } from "node:fs/promises";
3
- import { FFIType, dlopen, ptr } from "bun:ffi";
4
4
  import { execFile } from "node:child_process";
5
5
  import { promisify } from "node:util";
6
6
  // src/installer/installer-process-cleanup.ts
@@ -106,53 +106,14 @@ async function runningExecutable(pid, platform, env) {
106
106
  }
107
107
  return windowsRunningExecutable(pid);
108
108
  }
109
- var PROCESS_QUERY_LIMITED_INFORMATION = 4096;
110
- var STILL_ACTIVE = 259;
111
- /** Ask the kernel directly: an exited process keeps no STILL_ACTIVE exit code even while
112
- * another process holds a handle to it. */
109
+ /** The executable of a still-running process, or undefined once it has exited. */
113
110
  async function windowsRunningExecutable(pid) {
114
- const kernel = dlopen("kernel32.dll", {
115
- OpenProcess: {
116
- args: [
117
- FFIType.u32,
118
- FFIType.i32,
119
- FFIType.u32
120
- ],
121
- returns: FFIType.ptr
122
- },
123
- GetExitCodeProcess: {
124
- args: [FFIType.ptr, FFIType.ptr],
125
- returns: FFIType.i32
126
- },
127
- QueryFullProcessImageNameW: {
128
- args: [
129
- FFIType.ptr,
130
- FFIType.u32,
131
- FFIType.ptr,
132
- FFIType.ptr
133
- ],
134
- returns: FFIType.i32
135
- },
136
- CloseHandle: {
137
- args: [FFIType.ptr],
138
- returns: FFIType.i32
139
- }
140
- });
111
+ let image;
141
112
  try {
142
- const handle = kernel.symbols.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
143
- if (!handle) return void 0;
144
- try {
145
- const code = /* @__PURE__ */ new Uint32Array(1);
146
- if (!kernel.symbols.GetExitCodeProcess(handle, ptr(code))) throw new Error("Unable to query guarded process state");
147
- if (code[0] !== STILL_ACTIVE) return void 0;
148
- const name = /* @__PURE__ */ new Uint16Array(32768), length = new Uint32Array([name.length]);
149
- if (!kernel.symbols.QueryFullProcessImageNameW(handle, 0, ptr(name), ptr(length))) throw new Error("Unable to query guarded process executable");
150
- return realpath(Buffer.from(name.buffer, 0, length[0] * 2).toString("utf16le"));
151
- } finally {
152
- kernel.symbols.CloseHandle(handle);
153
- }
154
- } finally {
155
- kernel.close();
113
+ image = windowsProcessImage(pid, { requireRunning: true });
114
+ } catch (error) {
115
+ throw new Error("Unable to query guarded process executable", { cause: error });
156
116
  }
117
+ return image === "missing" ? void 0 : realpath(image);
157
118
  }
158
119
  export { macosProcess, macosWorkerExited, terminateGuardedWorker };
@@ -1,6 +1,7 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { validateInstallerReceipt } from "../release/release-qualification.js";
2
3
  import { parseReleaseConfig } from "../release/release-config.js";
3
- import { planReleaseAssets } from "../release/release-assets-plan.js";
4
+ import { planQualificationRun } from "../release/qualification-run.js";
4
5
  import { observeInstalledApp } from "./installer-observation.js";
5
6
  import { lstat, writeFile } from "node:fs/promises";
6
7
  import { join, resolve } from "node:path";
@@ -15,7 +16,7 @@ async function qualifyInstallerCommand(options) {
15
16
  "linux-arm64"
16
17
  ].includes(platform) || !["native", "cef"].includes(renderer) || typeof config !== "object" || config === null || Array.isArray(config) || typeof config.appName !== "string" || typeof config.appId !== "string") throw new Error("Invalid installer qualification context");
17
18
  if (env.RELEASE_TAG !== tag) throw new Error("Installer release tag mismatch");
18
- const plan = await planReleaseAssets({
19
+ const plan = await planQualificationRun({
19
20
  env,
20
21
  config,
21
22
  tag
@@ -28,7 +29,7 @@ async function qualifyInstallerCommand(options) {
28
29
  await lstat(destination);
29
30
  throw new Error("Installer receipt already exists");
30
31
  } catch (error) {
31
- if (error.code !== "ENOENT") throw error;
32
+ if (errorCode(error) !== "ENOENT") throw error;
32
33
  }
33
34
  const app = config;
34
35
  const result = await observeInstalledApp({
@@ -49,8 +50,8 @@ async function qualifyInstallerCommand(options) {
49
50
  tag,
50
51
  sourceSha: plan.sourceSha,
51
52
  workflowSha: plan.workflowSha,
52
- runId: env.GITHUB_RUN_ID,
53
- runAttempt: Number(env.GITHUB_RUN_ATTEMPT)
53
+ runId: plan.runId,
54
+ runAttempt: plan.runAttempt
54
55
  };
55
56
  const receipt = {
56
57
  schema: 2,
@@ -1,3 +1,4 @@
1
+ import { errorCode, isRecord } from "../app/value-guards.js";
1
2
  import { verifyReleaseDescriptor } from "../updates/signed-release.js";
2
3
  import { feedUrl } from "../updates/release-feed.js";
3
4
  import { parseReleaseConfig } from "../release/release-config.js";
@@ -18,15 +19,14 @@ var targets = {
18
19
  "linux-x64": ["linux", "x64"],
19
20
  "linux-arm64": ["linux", "arm64"]
20
21
  };
21
- var object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
22
22
  /** The channel descriptor the app discovers for `platform`, as the release config names it. */
23
23
  function discoveryName(config, channel, platform) {
24
24
  const names = config[`${channel}DiscoveryAssets`], policies = config.descriptors;
25
- if (!Array.isArray(names) || !object(policies)) throw new Error("Invalid discovery policy");
25
+ if (!Array.isArray(names) || !isRecord(policies)) throw new Error("Invalid discovery policy");
26
26
  const [os, arch] = targets[platform];
27
27
  const matches = names.filter((name) => {
28
28
  const policy = typeof name === "string" ? policies[name] : void 0;
29
- return object(policy) && policy.channel === channel && policy.platform === os && policy.arch === arch;
29
+ return isRecord(policy) && policy.channel === channel && policy.platform === os && policy.arch === arch;
30
30
  });
31
31
  if (matches.length !== 1 || matches[0].includes("{tag}")) throw new Error("Invalid discovery policy");
32
32
  return matches[0];
@@ -49,7 +49,7 @@ async function readBounded(path, maximum) {
49
49
  */
50
50
  async function qualifyUpgradeCommand(options) {
51
51
  const { env, config, tag, platform, renderer } = options;
52
- if (!Object.hasOwn(targets, platform) || !["native", "cef"].includes(renderer) || !object(config) || typeof config.appName !== "string" || typeof config.appId !== "string" || !object(config.releaseSigningKeys) || typeof env.GITHUB_REPOSITORY !== "string") throw new Error("Invalid upgrade qualification context");
52
+ if (!Object.hasOwn(targets, platform) || !["native", "cef"].includes(renderer) || !isRecord(config) || typeof config.appName !== "string" || typeof config.appId !== "string" || !isRecord(config.releaseSigningKeys) || typeof env.GITHUB_REPOSITORY !== "string") throw new Error("Invalid upgrade qualification context");
53
53
  if (env.RELEASE_TAG !== tag) throw new Error("Upgrade release tag mismatch");
54
54
  const plan = await planReleaseAssets({
55
55
  env,
@@ -64,7 +64,7 @@ async function qualifyUpgradeCommand(options) {
64
64
  await lstat(destination);
65
65
  throw new Error("Upgrade receipt already exists");
66
66
  } catch (error) {
67
- if (error.code !== "ENOENT") throw error;
67
+ if (errorCode(error) !== "ENOENT") throw error;
68
68
  }
69
69
  const keys = /* @__PURE__ */ new Map();
70
70
  for (const [id, value] of Object.entries(config.releaseSigningKeys)) if (typeof value === "string") keys.set(id, value);
@@ -1,3 +1,4 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { assertHostedRunner } from "./hosted-runner.js";
2
3
  import { lstat, open, writeFile } from "node:fs/promises";
3
4
  import { resolve } from "node:path";
@@ -63,7 +64,7 @@ async function awaitInstallerWorkerPermit(options) {
63
64
  if (!expected.startsWith(contents)) throw new Error("Invalid worker permit");
64
65
  if (contents === expected) return pathToFileURL(resolve(entry)).href;
65
66
  } catch (error) {
66
- if (error.code !== "ENOENT") throw error;
67
+ if (errorCode(error) !== "ENOENT") throw error;
67
68
  }
68
69
  await new Promise((done) => setTimeout(done, Math.min(100, Math.max(1, deadline - Date.now()))));
69
70
  }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * True for an absolute, already-normalized path with no NUL byte: the form every
3
+ * filesystem boundary in the framework accepts before touching disk.
4
+ */
5
+ export declare function isCanonicalPath(value: unknown): value is string;
@@ -0,0 +1,10 @@
1
+ import { isAbsolute, resolve } from "node:path";
2
+ // src/native/canonical-path.ts
3
+ /**
4
+ * True for an absolute, already-normalized path with no NUL byte: the form every
5
+ * filesystem boundary in the framework accepts before touching disk.
6
+ */
7
+ function isCanonicalPath(value) {
8
+ return typeof value === "string" && isAbsolute(value) && resolve(value) === value && !value.includes("\0");
9
+ }
10
+ export { isCanonicalPath };
@@ -1,9 +1,10 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { downloadCefHelperInput } from "./cef-helper-download.js";
2
3
  import { CEF_BRIDGE_PATCH_PATH, CEF_HELPER_SOURCES, ELECTROBUN_COMMIT, PINNED_CEF_BRIDGE_PATCH, applyElectrobunPatch } from "./electrobun-source-patch.js";
3
4
  import { chmod, lstat, mkdir, mkdtemp, open, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
4
5
  import { dirname, isAbsolute, join } from "node:path";
5
- import { spawnSync } from "node:child_process";
6
6
  import { createHash, randomUUID } from "node:crypto";
7
+ import { spawnSync } from "node:child_process";
7
8
  import { availableParallelism, homedir } from "node:os";
8
9
  // src/native/cef-helper.ts
9
10
  /** The CEF build Electrobun 2.0.5 pins (its src/shared/cef-version.ts). */
@@ -147,7 +148,7 @@ async function verifyCachedHelper(entry, output, key) {
147
148
  ...actual
148
149
  }) + "\n") throw new Error("Invalid cached CEF helper");
149
150
  } catch (error) {
150
- if (error.code === "ENOENT") throw new Error("Invalid cached CEF helper", { cause: error });
151
+ if (errorCode(error) === "ENOENT") throw new Error("Invalid cached CEF helper", { cause: error });
151
152
  throw error;
152
153
  }
153
154
  }
@@ -161,7 +162,7 @@ async function ensurePatchedCefHelper(env, os, arch, build = buildPatchedCefHelp
161
162
  try {
162
163
  await lstat(entry);
163
164
  } catch (error) {
164
- if (error.code !== "ENOENT") throw error;
165
+ if (errorCode(error) !== "ENOENT") throw error;
165
166
  await mkdir(root, { recursive: true });
166
167
  const work = await mkdtemp(join(root, ".build-"));
167
168
  try {
@@ -181,7 +182,7 @@ async function ensurePatchedCefHelper(env, os, arch, build = buildPatchedCefHelp
181
182
  "EEXIST",
182
183
  "ENOTEMPTY",
183
184
  "EPERM"
184
- ].includes(publishError.code ?? "")) throw publishError;
185
+ ].includes(errorCode(publishError) ?? "")) throw publishError;
185
186
  }
186
187
  } finally {
187
188
  await rm(work, {
@@ -1,7 +1,8 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { dirname, isAbsolute, join, normalize } from "node:path";
3
+ import { createHash } from "node:crypto";
2
4
  import { lstatSync, readFileSync } from "node:fs";
3
5
  import { execFileSync } from "node:child_process";
4
- import { createHash } from "node:crypto";
5
6
  import { fileURLToPath } from "node:url";
6
7
  // src/native/electrobun-source-patch.ts
7
8
  /** Electrobun 2.0.5 (MIT), tag v2.0.5: the only source these patches target. */
@@ -67,7 +68,7 @@ function sourceDigest(root, path) {
67
68
  try {
68
69
  info = lstatSync(full);
69
70
  } catch (error) {
70
- if (error.code === "ENOENT") return null;
71
+ if (errorCode(error) === "ENOENT") return null;
71
72
  throw error;
72
73
  }
73
74
  if (!info.isFile() || info.isSymbolicLink()) throw new Error("Unexpected Electrobun source type");
@@ -1,3 +1,5 @@
1
+ /** Rename without replacing an existing destination on supported desktop platforms. */
2
+ export declare function renameExclusive(source: string, destination: string): void;
1
3
  /** Atomically exchange two existing paths on supported Darwin and Linux filesystems. */
2
4
  export declare function exchangeDirectories(source: string, destination: string): void;
3
5
  /**
@@ -0,0 +1,126 @@
1
+ import { isCanonicalPath } from "./canonical-path.js";
2
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { FFIType, dlopen, ptr } from "bun:ffi";
6
+ // src/native/native-rename.ts
7
+ var DARWIN_RENAME_SWAP = 2;
8
+ var DARWIN_RENAME_EXCL = 4;
9
+ var LINUX_RENAME_NOREPLACE = 1;
10
+ var LINUX_RENAME_EXCHANGE = 2;
11
+ var AT_FDCWD = -100;
12
+ var library;
13
+ /** Open the platform rename entry point once; the process keeps it for its lifetime. */
14
+ function renameLibrary() {
15
+ if (library) return library;
16
+ if (process.platform === "darwin") {
17
+ const { symbols } = dlopen("libSystem.B.dylib", { renamex_np: {
18
+ args: [
19
+ FFIType.ptr,
20
+ FFIType.ptr,
21
+ FFIType.u32
22
+ ],
23
+ returns: FFIType.i32
24
+ } });
25
+ library = {
26
+ platform: "darwin",
27
+ rename: (from, to, flags) => symbols.renamex_np(ptr(from), ptr(to), flags) === 0
28
+ };
29
+ } else if (process.platform === "linux") {
30
+ const { symbols } = dlopen("libc.so.6", { renameat2: {
31
+ args: [
32
+ FFIType.i32,
33
+ FFIType.ptr,
34
+ FFIType.i32,
35
+ FFIType.ptr,
36
+ FFIType.u32
37
+ ],
38
+ returns: FFIType.i32
39
+ } });
40
+ library = {
41
+ platform: "linux",
42
+ rename: (from, to, flags) => symbols.renameat2(AT_FDCWD, ptr(from), AT_FDCWD, ptr(to), flags) === 0
43
+ };
44
+ } else if (process.platform === "win32") {
45
+ const { symbols } = dlopen("kernel32.dll", { MoveFileW: {
46
+ args: [FFIType.ptr, FFIType.ptr],
47
+ returns: FFIType.i32
48
+ } });
49
+ library = {
50
+ platform: "win32",
51
+ move: (from, to) => symbols.MoveFileW(ptr(from), ptr(to)) !== 0
52
+ };
53
+ } else throw new Error("Unsupported native rename platform");
54
+ return library;
55
+ }
56
+ function renamePaths(source, destination) {
57
+ return isCanonicalPath(source) && isCanonicalPath(destination) && source !== destination;
58
+ }
59
+ var cString = (path) => Buffer.from(path + "\0");
60
+ /** Rename without replacing an existing destination on supported desktop platforms. */
61
+ function renameExclusive(source, destination) {
62
+ if (!renamePaths(source, destination)) throw new Error("Invalid exclusive rename paths");
63
+ let native;
64
+ try {
65
+ native = renameLibrary();
66
+ } catch {
67
+ throw new Error("Unsupported exclusive rename platform");
68
+ }
69
+ if (!(native.platform === "win32" ? native.move(Buffer.from(source + "\0", "utf16le"), Buffer.from(destination + "\0", "utf16le")) : native.rename(cString(source), cString(destination), native.platform === "darwin" ? DARWIN_RENAME_EXCL : LINUX_RENAME_NOREPLACE))) throw new Error("Exclusive rename failed");
70
+ }
71
+ /** Atomically exchange two existing paths on supported Darwin and Linux filesystems. */
72
+ function exchangeDirectories(source, destination) {
73
+ if (!renamePaths(source, destination)) throw new Error("Invalid atomic directory exchange paths");
74
+ if (process.platform !== "darwin" && process.platform !== "linux") throw new Error("Atomic directory exchange is unsupported on this platform");
75
+ const native = renameLibrary();
76
+ if (native.platform === "win32") throw new Error("Atomic directory exchange is unsupported on this platform");
77
+ const flags = native.platform === "darwin" ? DARWIN_RENAME_SWAP : LINUX_RENAME_EXCHANGE;
78
+ if (!native.rename(cString(source), cString(destination), flags)) throw new Error("Atomic directory exchange is unsupported or failed");
79
+ }
80
+ /**
81
+ * Exercise the actual volume using two disposable directories before exchanging
82
+ * an install tree. This qualifies only that same-volume probe pair; it cannot
83
+ * prove a provider will behave identically for every later object or survive a
84
+ * power failure. The caller also verifies the real trees' versions and inode
85
+ * identities immediately after the exchange.
86
+ */
87
+ async function probeDirectoryExchange(parent, exchange = exchangeDirectories) {
88
+ if (!isCanonicalPath(parent)) throw new Error("Invalid directory exchange probe parent");
89
+ const id = randomUUID();
90
+ const first = join(parent, `.framework-exchange-probe-${id}-a`);
91
+ const second = join(parent, `.framework-exchange-probe-${id}-b`);
92
+ const marker = "exchange-probe";
93
+ const firstValue = `${id}:first`;
94
+ const secondValue = `${id}:second`;
95
+ let firstCreated = false;
96
+ let secondCreated = false;
97
+ try {
98
+ await mkdir(first, { mode: 448 });
99
+ firstCreated = true;
100
+ await mkdir(second, { mode: 448 });
101
+ secondCreated = true;
102
+ await writeFile(join(first, marker), firstValue, {
103
+ flag: "wx",
104
+ mode: 384
105
+ });
106
+ await writeFile(join(second, marker), secondValue, {
107
+ flag: "wx",
108
+ mode: 384
109
+ });
110
+ exchange(first, second);
111
+ const [firstAfter, secondAfter] = await Promise.all([readFile(join(first, marker), "utf8"), readFile(join(second, marker), "utf8")]);
112
+ if (firstAfter !== secondValue || secondAfter !== firstValue) throw new Error("Directory exchange did not exchange both probe trees");
113
+ } finally {
114
+ const cleanup = [];
115
+ if (firstCreated) cleanup.push(rm(first, {
116
+ recursive: true,
117
+ force: true
118
+ }));
119
+ if (secondCreated) cleanup.push(rm(second, {
120
+ recursive: true,
121
+ force: true
122
+ }));
123
+ await Promise.all(cleanup);
124
+ }
125
+ }
126
+ export { exchangeDirectories, probeDirectoryExchange, renameExclusive };
@@ -1,3 +1,4 @@
1
+ import { createSerialQueue } from "../app/serial-queue.js";
1
2
  // src/native/native-secret-store.ts
2
3
  var identifier = (value) => typeof value === "string" && value.length > 0 && value.length <= 128 && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value);
3
4
  /** Native credentials only. Apps choose the service namespace and own authorization and migration. */
@@ -7,16 +8,11 @@ function createNativeSecretStore(options) {
7
8
  if (!identifier(service) || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 2048) throw new Error("Invalid credential store configuration");
8
9
  const backend = options.backend ?? Bun.secrets;
9
10
  if (!backend || typeof backend.get !== "function" || typeof backend.set !== "function" || typeof backend.delete !== "function") throw new Error("Credential store unavailable");
10
- let queue = Promise.resolve();
11
+ const ordered = createSerialQueue();
11
12
  const name = (value) => {
12
13
  if (!identifier(value)) throw new Error("Invalid credential name");
13
14
  return value;
14
15
  };
15
- function ordered(task) {
16
- const result = queue.then(task);
17
- queue = result.then(() => {}, () => {});
18
- return result;
19
- }
20
16
  async function read(account) {
21
17
  try {
22
18
  const value = await backend.get({
@@ -1,8 +1,8 @@
1
+ import { isRecord } from "../app/value-guards.js";
1
2
  import { containsAsciiControl } from "../desktop/string-policy.js";
2
3
  import { isAbsolute } from "node:path";
3
4
  // src/native/native-utilities.ts
4
5
  var MAX_PICKED_FILES = 1e3;
5
- var object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
6
  var path = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !containsAsciiControl(value) && isAbsolute(value) && (process.platform !== "win32" || /^[A-Za-z]:[\\/]/.test(value) || /^\\\\[A-Za-z0-9][A-Za-z0-9._-]*\\[^\\/?]+(?:\\|$)/.test(value));
7
7
  /** Register shared native utilities behind the host's authenticated principal and policy. */
8
8
  function registerNativeUtilities(options) {
@@ -32,7 +32,7 @@ function registerNativeUtilities(options) {
32
32
  }));
33
33
  unregister.push(services.register("shell.open-external", {
34
34
  parse(value) {
35
- if (!object(value) || Object.keys(value).length !== 1 || typeof value.url !== "string" || value.url.length > 2048 || containsAsciiControl(value.url, true)) throw new Error("Invalid URL");
35
+ if (!isRecord(value) || Object.keys(value).length !== 1 || typeof value.url !== "string" || value.url.length > 2048 || containsAsciiControl(value.url, true)) throw new Error("Invalid URL");
36
36
  const url = new URL(value.url);
37
37
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new Error("Invalid URL");
38
38
  return url.href;
@@ -46,7 +46,7 @@ function registerNativeUtilities(options) {
46
46
  }));
47
47
  unregister.push(services.register("shell.pick-folder", {
48
48
  parse(value) {
49
- if (!object(value) || Object.keys(value).some((key) => key !== "startingFolder") || value.startingFolder !== void 0 && !path(value.startingFolder)) throw new Error("Invalid folder request");
49
+ if (!isRecord(value) || Object.keys(value).some((key) => key !== "startingFolder") || value.startingFolder !== void 0 && !path(value.startingFolder)) throw new Error("Invalid folder request");
50
50
  return value.startingFolder;
51
51
  },
52
52
  authorize: (principal) => authorize(principal, "pick-folder"),
@@ -58,7 +58,7 @@ function registerNativeUtilities(options) {
58
58
  }));
59
59
  if (pickFiles) unregister.push(services.register("shell.pick-files", {
60
60
  parse(value) {
61
- if (!object(value) || Object.keys(value).some((key) => ![
61
+ if (!isRecord(value) || Object.keys(value).some((key) => ![
62
62
  "startingFolder",
63
63
  "extensions",
64
64
  "multiple"
@@ -1,8 +1,8 @@
1
1
  import { ELECTROBUN_COMMIT, PINNED_POSIX_LAUNCH_LEASE_PATCH, POSIX_LAUNCH_LEASE_PATCH_PATH, applyElectrobunPatch } from "./electrobun-source-patch.js";
2
2
  import { chmod, copyFile, lstat, mkdir, mkdtemp, open, readFile, rename, rm } from "node:fs/promises";
3
3
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
- import { execFileSync, spawnSync } from "node:child_process";
5
4
  import { createHash, randomUUID } from "node:crypto";
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
6
  import { tmpdir } from "node:os";
7
7
  // src/native/posix-launcher-build.ts
8
8
  var POSIX_LAUNCH_LEASE_OPT_IN = "ADEA_ENABLE_POSIX_LAUNCH_LEASE";