@adea-ai/app-framework 0.30.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 (148) hide show
  1. package/README.md +26 -11
  2. package/dist/app/application.js +4 -2
  3. package/dist/app/create-application.js +4 -3
  4. package/dist/app/serial-queue.d.ts +5 -0
  5. package/dist/app/serial-queue.js +14 -0
  6. package/dist/app/value-guards.d.ts +15 -0
  7. package/dist/app/value-guards.js +29 -0
  8. package/dist/appearance/appearance-host.js +6 -0
  9. package/dist/appearance/appearance-preferences.js +6 -2
  10. package/dist/appearance/composition.d.ts +1 -1
  11. package/dist/appearance/custom-theme-import.js +12 -19
  12. package/dist/appearance/custom-theme-library.d.ts +5 -4
  13. package/dist/appearance/custom-theme-library.js +20 -2
  14. package/dist/appearance/editor.js +4 -1
  15. package/dist/appearance/legacy-imported-theme-token-projection.d.ts +84 -0
  16. package/dist/appearance/legacy-imported-theme-token-projection.js +142 -0
  17. package/dist/appearance/theme-record-adapter.js +37 -9
  18. package/dist/ci/toolchain-identity.js +1 -1
  19. package/dist/desktop/channel-proof.js +2 -1
  20. package/dist/desktop/client-asset-stream.js +6 -12
  21. package/dist/desktop/desktop-host.d.ts +25 -5
  22. package/dist/desktop/desktop-host.js +75 -20
  23. package/dist/framework-source.json +1 -1
  24. package/dist/installer/command-artifact.js +4 -3
  25. package/dist/installer/command-qualification-command.js +6 -5
  26. package/dist/installer/hosted-runner.d.ts +9 -2
  27. package/dist/installer/hosted-runner.js +18 -5
  28. package/dist/installer/installed-payload.js +20 -46
  29. package/dist/installer/installer-archive.d.ts +33 -0
  30. package/dist/installer/installer-archive.js +116 -0
  31. package/dist/installer/installer-ci-bootstrap.js +10 -6
  32. package/dist/installer/installer-extraction.js +54 -120
  33. package/dist/installer/installer-identity.js +33 -111
  34. package/dist/installer/installer-observation.js +3 -2
  35. package/dist/installer/installer-process-cleanup.js +7 -46
  36. package/dist/installer/installer-qualification-command.js +6 -5
  37. package/dist/installer/installer-upgrade-command.js +5 -5
  38. package/dist/installer/installer-worker-guard.js +2 -1
  39. package/dist/native/canonical-path.d.ts +5 -0
  40. package/dist/native/canonical-path.js +10 -0
  41. package/dist/native/cef-helper.js +5 -4
  42. package/dist/native/electrobun-source-patch.js +3 -2
  43. package/dist/native/{directory-exchange.d.ts → native-rename.d.ts} +2 -0
  44. package/dist/native/native-rename.js +126 -0
  45. package/dist/native/native-secret-store.js +2 -6
  46. package/dist/native/native-utilities.js +4 -4
  47. package/dist/native/posix-launcher-build.js +1 -1
  48. package/dist/native/posix-tree-removal.js +2 -2
  49. package/dist/native/windows-process.d.ts +9 -0
  50. package/dist/native/windows-process.js +60 -0
  51. package/dist/release/feed-release-cut.js +2 -1
  52. package/dist/release/framework-package-publish.js +1 -1
  53. package/dist/release/framework-update-lock.js +2 -1
  54. package/dist/release/github-cli.d.ts +18 -0
  55. package/dist/release/github-cli.js +13 -1
  56. package/dist/release/github-release-cut.js +3 -2
  57. package/dist/release/github-release-provenance.js +2 -1
  58. package/dist/release/github-release-publisher.js +2 -1
  59. package/dist/release/local-provenance.js +3 -2
  60. package/dist/release/local-release.js +6 -6
  61. package/dist/release/qualification-run.d.ts +25 -0
  62. package/dist/release/qualification-run.js +43 -0
  63. package/dist/release/release-artifact.js +3 -11
  64. package/dist/release/release-assets-plan.js +16 -6
  65. package/dist/release/release-config.js +14 -14
  66. package/dist/release/release-cut-command.js +14 -4
  67. package/dist/release/release-cut.js +3 -2
  68. package/dist/release/release-descriptor-staging.js +13 -27
  69. package/dist/release/release-finalize.js +2 -1
  70. package/dist/release/release-publication.js +3 -11
  71. package/dist/release/release-publish-command.js +15 -6
  72. package/dist/release/release-qualification.js +3 -2
  73. package/dist/release/retained-release-build.js +12 -12
  74. package/dist/shell/app-shell.js +76 -48
  75. package/dist/shell/app-utilities.d.ts +5 -3
  76. package/dist/shell/app-utilities.js +15 -7
  77. package/dist/shell/help-shortcuts.d.ts +4 -0
  78. package/dist/shell/help-shortcuts.js +38 -7
  79. package/dist/shell/keyboard-target.d.ts +2 -0
  80. package/dist/shell/keyboard-target.js +54 -0
  81. package/dist/shell/settings-sections.d.ts +5 -0
  82. package/dist/shell/settings-shortcuts.d.ts +10 -0
  83. package/dist/shell/settings-shortcuts.js +67 -0
  84. package/dist/update-helper.bundle.js +250 -190
  85. package/dist/updates/desktop-updater.js +53 -58
  86. package/dist/updates/packaged-launch-admission.js +3 -2
  87. package/dist/updates/packaged-release-config.js +6 -5
  88. package/dist/updates/release-feed.js +9 -9
  89. package/dist/updates/signed-release.js +5 -5
  90. package/dist/updates/stable-file.d.ts +18 -0
  91. package/dist/updates/stable-file.js +54 -1
  92. package/dist/updates/update-adapter.d.ts +2 -13
  93. package/dist/updates/update-arm.js +7 -5
  94. package/dist/updates/update-channel-store.js +7 -9
  95. package/dist/updates/update-discovery.js +30 -34
  96. package/dist/updates/update-download-cleanup.js +2 -1
  97. package/dist/updates/update-download.js +2 -4
  98. package/dist/updates/update-extraction.js +1 -1
  99. package/dist/updates/update-generation-lease.js +4 -3
  100. package/dist/updates/update-handoff-plan.js +3 -2
  101. package/dist/updates/update-helper.js +8 -6
  102. package/dist/updates/update-instance-lease.js +3 -2
  103. package/dist/updates/update-launch-gate.js +12 -25
  104. package/dist/updates/update-launch.js +3 -2
  105. package/dist/updates/update-lock.js +3 -2
  106. package/dist/updates/update-marker.js +3 -2
  107. package/dist/updates/update-process-fence.js +10 -39
  108. package/dist/updates/update-process-liveness.js +2 -1
  109. package/dist/updates/update-resume.js +26 -22
  110. package/dist/updates/update-retention-marker.js +7 -5
  111. package/dist/updates/update-retention-plan.js +2 -2
  112. package/dist/updates/update-retirement.js +40 -39
  113. package/dist/updates/update-state-store.js +29 -37
  114. package/dist/updates/update-state.d.ts +8 -3
  115. package/dist/updates/update-swap-stage.js +6 -5
  116. package/dist/updates/update-swap.d.ts +1 -1
  117. package/dist/updates/update-swap.js +8 -6
  118. package/dist/views/app-help.js +2 -1
  119. package/dist/views/app-settings.js +5 -2
  120. package/dist/views/appearance-surface.js +33 -19
  121. package/package.json +7 -13
  122. package/src/app/application.tsx +3 -1
  123. package/src/appearance/appearance-host.tsx +6 -0
  124. package/src/appearance/appearance-preferences.ts +7 -1
  125. package/src/appearance/composition.ts +3 -1
  126. package/src/appearance/custom-theme-import.ts +21 -37
  127. package/src/appearance/custom-theme-library.ts +21 -5
  128. package/src/appearance/editor.ts +7 -6
  129. package/src/appearance/legacy-imported-theme-token-projection.ts +51 -0
  130. package/src/appearance/theme-record-adapter.ts +58 -11
  131. package/src/desktop/client-asset-stream.ts +6 -12
  132. package/src/shell/app-shell.tsx +88 -58
  133. package/src/shell/app-utilities.tsx +29 -17
  134. package/src/shell/help-shortcuts.ts +77 -6
  135. package/src/shell/keyboard-target.ts +74 -0
  136. package/src/shell/settings-sections.ts +5 -0
  137. package/src/shell/settings-shortcuts.ts +116 -0
  138. package/src/updates/update-adapter.ts +2 -14
  139. package/src/updates/update-state.ts +11 -2
  140. package/src/views/app-settings.tsx +5 -3
  141. package/src/views/appearance-surface.tsx +63 -27
  142. package/dist/native/directory-exchange.js +0 -90
  143. package/dist/native/exclusive-rename.d.ts +0 -2
  144. package/dist/native/exclusive-rename.js +0 -52
  145. package/dist/release/retention-dry-run.d.ts +0 -46
  146. package/dist/release/retention-dry-run.js +0 -94
  147. package/dist/updates/update-exclusive-rename.d.ts +0 -3
  148. package/dist/updates/update-exclusive-rename.js +0 -5
@@ -1,3 +1,5 @@
1
+ import { errorCode } from "../app/value-guards.js";
2
+ import { isCanonicalPath } from "../native/canonical-path.js";
1
3
  import { ServiceError } from "../app/service-registry.js";
2
4
  import { feedUrl, parseReleaseFeed } from "./release-feed.js";
3
5
  import { isUpdateChannel } from "./release-version.js";
@@ -13,7 +15,7 @@ import { armUpdateHelper } from "./update-arm.js";
13
15
  import { resumeUpdate, resumeUpdateWithRetainedTrees } from "./update-resume.js";
14
16
  import { scheduleUpdateShutdown } from "./update-shutdown.js";
15
17
  import { lstat, mkdir, readlink, realpath } from "node:fs/promises";
16
- import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
18
+ import { basename, dirname, join, relative, resolve } from "node:path";
17
19
  // src/updates/desktop-updater.ts
18
20
  /**
19
21
  * The desktop host's signed updater, the same for every framework app: the
@@ -64,9 +66,9 @@ async function canonicalTargetForRecovery(target, seen = /* @__PURE__ */ new Set
64
66
  try {
65
67
  return await realpath(target);
66
68
  } catch (error) {
67
- if (error.code !== "ENOENT") throw error;
69
+ if (errorCode(error) !== "ENOENT") throw error;
68
70
  const info = await lstat(target).then((value) => value, (statError) => {
69
- if (statError.code === "ENOENT") return void 0;
71
+ if (errorCode(statError) === "ENOENT") return void 0;
70
72
  throw statError;
71
73
  });
72
74
  if (info?.isSymbolicLink()) return canonicalTargetForRecovery(resolve(dirname(target), await readlink(target)), seen);
@@ -75,6 +77,40 @@ async function canonicalTargetForRecovery(target, seen = /* @__PURE__ */ new Set
75
77
  }
76
78
  }
77
79
  /**
80
+ * Validate a packaged entry directory and locate its install root plus the
81
+ * client directory relative to it, which every retained generation shares.
82
+ */
83
+ async function packagedClientLayout(options, platform) {
84
+ if (!isCanonicalPath(options.entryDirectory) || typeof options.loadManifest !== "function") throw new Error("Invalid packaged client asset lookup");
85
+ const lexicalTarget = installTarget(options.entryDirectory, platform);
86
+ const clientRelative = relative(lexicalTarget, resolve(options.entryDirectory, "..", "client"));
87
+ if (clientRelative !== join(...platform === "macos-arm64" ? ["Contents"] : [], "Resources", "app", "client")) throw new Error("Invalid packaged client asset layout");
88
+ return {
89
+ target: await realpath(lexicalTarget),
90
+ clientRelative
91
+ };
92
+ }
93
+ /**
94
+ * Load every retained generation's client manifest while its lease is held. The
95
+ * loads run concurrently; all of them settle before a failure releases the
96
+ * leases, so no load still reads a tree that may be pruned.
97
+ */
98
+ async function loadRetainedClientAssets(trees, clientRelative, loadManifest, release) {
99
+ const roots = trees.map(({ tree }) => join(tree, clientRelative));
100
+ const loaded = await Promise.allSettled(roots.map((root) => loadManifest(root)));
101
+ const failed = loaded.find((outcome) => outcome.status === "rejected");
102
+ if (!failed) return roots.map((root, index) => ({
103
+ root,
104
+ immutableAssets: loaded[index].value
105
+ }));
106
+ try {
107
+ await release();
108
+ } catch (releaseError) {
109
+ throw new AggregateError([failed.reason, releaseError], "Retained client asset preparation failed", { cause: releaseError });
110
+ }
111
+ throw failed.reason;
112
+ }
113
+ /**
78
114
  * Acquire the updater's retained generations and map their packaged client
79
115
  * directories to manifests. The caller must already hold any required native
80
116
  * launch admission lease and must retain the returned generation leases until
@@ -84,38 +120,17 @@ async function canonicalTargetForRecovery(target, seen = /* @__PURE__ */ new Set
84
120
  async function acquireRetainedDesktopClientAssets(options) {
85
121
  const platform = updatePlatform();
86
122
  if (!platform) return { status: "unsupported" };
87
- if (typeof options.entryDirectory !== "string" || !isAbsolute(options.entryDirectory) || resolve(options.entryDirectory) !== options.entryDirectory || typeof options.loadManifest !== "function") throw new Error("Invalid packaged client asset lookup");
88
- const lexicalTarget = installTarget(options.entryDirectory, platform);
89
- const clientRelative = relative(lexicalTarget, resolve(options.entryDirectory, "..", "client"));
90
- if (clientRelative !== join(...platform === "macos-arm64" ? ["Contents"] : [], "Resources", "app", "client")) throw new Error("Invalid packaged client asset layout");
91
- const target = await realpath(lexicalTarget);
123
+ const { target, clientRelative } = await packagedClientLayout(options, platform);
92
124
  const retained = await acquireRetainedUpdateTrees({
93
125
  target,
94
126
  currentVersion: options.currentVersion
95
127
  });
96
128
  if (retained.status !== "acquired") return retained;
97
- try {
98
- const retainedClientAssets = [];
99
- for (const tree of retained.trees) {
100
- const root = join(tree.tree, clientRelative);
101
- retainedClientAssets.push({
102
- root,
103
- immutableAssets: await options.loadManifest(root)
104
- });
105
- }
106
- return {
107
- status: "acquired",
108
- retainedClientAssets,
109
- release: retained.release
110
- };
111
- } catch (error) {
112
- try {
113
- await retained.release();
114
- } catch (releaseError) {
115
- throw new AggregateError([error, releaseError], "Retained client asset preparation failed", { cause: releaseError });
116
- }
117
- throw error;
118
- }
129
+ return {
130
+ status: "acquired",
131
+ retainedClientAssets: await loadRetainedClientAssets(retained.trees, clientRelative, options.loadManifest, retained.release),
132
+ release: retained.release
133
+ };
119
134
  }
120
135
  /**
121
136
  * Trusted startup variant for callers that must preserve normal pending staged
@@ -126,11 +141,7 @@ async function acquireRetainedDesktopClientAssets(options) {
126
141
  async function resumeAndAcquireRetainedDesktopClientAssets(options) {
127
142
  const platform = updatePlatform();
128
143
  if (!platform) return { status: "unsupported" };
129
- if (typeof options.entryDirectory !== "string" || !isAbsolute(options.entryDirectory) || resolve(options.entryDirectory) !== options.entryDirectory || typeof options.loadManifest !== "function") throw new Error("Invalid packaged client asset lookup");
130
- const lexicalTarget = installTarget(options.entryDirectory, platform);
131
- const clientRelative = relative(lexicalTarget, resolve(options.entryDirectory, "..", "client"));
132
- if (clientRelative !== join(...platform === "macos-arm64" ? ["Contents"] : [], "Resources", "app", "client")) throw new Error("Invalid packaged client asset layout");
133
- const target = await realpath(lexicalTarget);
144
+ const { target, clientRelative } = await packagedClientLayout(options, platform);
134
145
  const result = await resumeUpdateWithRetainedTrees({
135
146
  target,
136
147
  trust: options.trust,
@@ -146,29 +157,13 @@ async function resumeAndAcquireRetainedDesktopClientAssets(options) {
146
157
  release: async () => {}
147
158
  };
148
159
  }
149
- try {
150
- const retainedClientAssets = [];
151
- for (const tree of result.retained.trees) {
152
- const root = join(tree.tree, clientRelative);
153
- retainedClientAssets.push({
154
- root,
155
- immutableAssets: await options.loadManifest(root)
156
- });
157
- }
158
- return {
159
- status: "ready",
160
- resume: result.resume,
161
- retainedClientAssets,
162
- release: result.retained.release
163
- };
164
- } catch (error) {
165
- try {
166
- await result.retained.release();
167
- } catch (releaseError) {
168
- throw new AggregateError([error, releaseError], "Retained client asset preparation failed", { cause: releaseError });
169
- }
170
- throw error;
171
- }
160
+ const retainedClientAssets = await loadRetainedClientAssets(result.retained.trees, clientRelative, options.loadManifest, result.retained.release);
161
+ return {
162
+ status: "ready",
163
+ resume: result.resume,
164
+ retainedClientAssets,
165
+ release: result.retained.release
166
+ };
172
167
  }
173
168
  /** Each channel's signed descriptor for `platform`, as the release workflows publish them. */
174
169
  function discoveryNames(platform) {
@@ -1,6 +1,7 @@
1
+ import { isCanonicalPath } from "../native/canonical-path.js";
1
2
  import { INHERITED_LAUNCH_LEASE_ENV } from "./launch-environment.js";
2
3
  import { realpath } from "node:fs/promises";
3
- import { isAbsolute, resolve } from "node:path";
4
+ import { resolve } from "node:path";
4
5
  // src/updates/packaged-launch-admission.ts
5
6
  var processLeases = /* @__PURE__ */ new Set();
6
7
  var admissionStarted = false;
@@ -16,7 +17,7 @@ async function acquirePackagedLaunchAdmission(options) {
16
17
  const { adoptInheritedUpdateLaunchLease } = await import("./update-inherited-launch-lease.js");
17
18
  const platform = updatePlatform();
18
19
  if (!platform || platform !== "macos-arm64" && platform !== "linux-x64" && platform !== "linux-arm64") throw new Error("Inherited launch admission is unavailable on this platform");
19
- if (typeof options.entryDirectory !== "string" || !isAbsolute(options.entryDirectory) || resolve(options.entryDirectory) !== options.entryDirectory || typeof options.descriptor !== "string" || !/^[1-9]\d{0,9}$/.test(options.descriptor)) throw new Error("Invalid packaged launch admission");
20
+ if (!isCanonicalPath(options.entryDirectory) || typeof options.descriptor !== "string" || !/^[1-9]\d{0,9}$/.test(options.descriptor)) throw new Error("Invalid packaged launch admission");
20
21
  const descriptor = Number(options.descriptor);
21
22
  if (!Number.isSafeInteger(descriptor) || descriptor < 3 || descriptor > 2147483647) throw new Error("Invalid packaged launch admission");
22
23
  const timeoutMs = options.timeoutMs ?? 5e3;
@@ -1,14 +1,15 @@
1
+ import { isRecord } from "../app/value-guards.js";
2
+ import { isCanonicalPath } from "../native/canonical-path.js";
1
3
  import { isRepositorySlug } from "./signed-release.js";
2
4
  import { parseReleaseConfig } from "../release/release-config.js";
3
5
  import { openUnchangedFile, sameFile } from "./stable-file.js";
4
6
  import { lstat } from "node:fs/promises";
5
- import { isAbsolute, join, resolve } from "node:path";
7
+ import { join } from "node:path";
6
8
  // src/updates/packaged-release-config.ts
7
9
  var MAX_CONFIG_BYTES = 262144;
8
- var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9
10
  /** Read only the release identity and public keys shipped beside the Bun entry. */
10
11
  async function readPackagedReleaseConfig(entryDirectory, identity) {
11
- if (typeof entryDirectory !== "string" || !isAbsolute(entryDirectory) || resolve(entryDirectory) !== entryDirectory) throw new Error("Invalid packaged release config location");
12
+ if (!isCanonicalPath(entryDirectory)) throw new Error("Invalid packaged release config location");
12
13
  const path = join(entryDirectory, "..", "release-config.json");
13
14
  const info = await lstat(path);
14
15
  if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > MAX_CONFIG_BYTES) throw new Error("Invalid packaged release config file");
@@ -31,7 +32,7 @@ async function readPackagedReleaseConfig(entryDirectory, identity) {
31
32
  }
32
33
  /** Validate packaged trust against the generated app's compile-time identity. */
33
34
  function parsePackagedReleaseConfig(value, identity) {
34
- if (!record(value) || typeof identity?.slug !== "string" || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(identity.slug) || typeof identity.identifier !== "string" || !/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/.test(identity.identifier) || typeof identity.name !== "string" || !identity.name.trim() || identity.name.length > 80 || typeof value.appId !== "string" || value.appId !== identity.identifier || typeof value.appName !== "string" || value.appName !== identity.name || typeof value.repository !== "string" || !isRepositorySlug(value.repository)) throw new Error("Packaged release identity does not match the application");
35
+ if (!isRecord(value) || typeof identity?.slug !== "string" || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(identity.slug) || typeof identity.identifier !== "string" || !/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/.test(identity.identifier) || typeof identity.name !== "string" || !identity.name.trim() || identity.name.length > 80 || typeof value.appId !== "string" || value.appId !== identity.identifier || typeof value.appName !== "string" || value.appName !== identity.name || typeof value.repository !== "string" || !isRepositorySlug(value.repository)) throw new Error("Packaged release identity does not match the application");
35
36
  let parsedConfig;
36
37
  try {
37
38
  parsedConfig = parseReleaseConfig(value);
@@ -40,7 +41,7 @@ function parsePackagedReleaseConfig(value, identity) {
40
41
  }
41
42
  const releaseFeed = parsedConfig.feed;
42
43
  if (releaseFeed.app !== identity.slug) throw new Error("Packaged release feed identity mismatch");
43
- if (!record(value.releaseSigningKeys) || Object.keys(value.releaseSigningKeys).length > 8) throw new Error("Invalid packaged release signing keys");
44
+ if (!isRecord(value.releaseSigningKeys) || Object.keys(value.releaseSigningKeys).length > 8) throw new Error("Invalid packaged release signing keys");
44
45
  const keys = Object.create(null);
45
46
  for (const [id, encoded] of Object.entries(value.releaseSigningKeys)) {
46
47
  if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(id) || typeof encoded !== "string") throw new Error("Invalid packaged release signing keys");
@@ -1,8 +1,8 @@
1
+ import { isGitSha, isRecord, isSha256Hex } from "../app/value-guards.js";
1
2
  // src/updates/release-feed.ts
2
3
  /** Ledger entries kept; the oldest fall off a full ledger. */
3
4
  var MAX_LEDGER_RELEASES = 500;
4
5
  var MAX_RELEASE_ASSETS = 256;
5
- var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
6
  var exactKeys = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
7
7
  var segment = /^[a-z0-9][a-z0-9-]{0,62}$/;
8
8
  var tagPattern = /^v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.[1-9]\d*)?$/;
@@ -13,7 +13,7 @@ var isFeedAssetName = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za
13
13
  /** Validate a feed: an https origin and path prefix ending in `/`, with no credentials,
14
14
  * port, query or fragment, and an app slug. */
15
15
  function parseReleaseFeed(value) {
16
- if (!record(value) || !exactKeys(value, ["base", "app"]) || typeof value.base !== "string") throw new Error("Invalid release feed");
16
+ if (!isRecord(value) || !exactKeys(value, ["base", "app"]) || typeof value.base !== "string") throw new Error("Invalid release feed");
17
17
  let url;
18
18
  try {
19
19
  url = new URL(value.base);
@@ -41,7 +41,7 @@ var channelOf = (tag) => tag.includes("-dev.") ? "dev" : "daily";
41
41
  /** Validate a release.json or channel pointer: a tag of its channel and a bounded,
42
42
  * unique asset inventory. */
43
43
  function parseFeedRelease(value) {
44
- if (!record(value) || !exactKeys(value, Object.hasOwn(value, "missingPlatforms") ? [
44
+ if (!isRecord(value) || !exactKeys(value, Object.hasOwn(value, "missingPlatforms") ? [
45
45
  "tag",
46
46
  "channel",
47
47
  "publishedAt",
@@ -59,11 +59,11 @@ function parseFeedRelease(value) {
59
59
  ].includes(String(value.channel)) || value.channel === "dev" !== (channelOf(value.tag) === "dev") || !timestamp(value.publishedAt) || !Array.isArray(value.assets) || value.assets.length < 1 || value.assets.length > MAX_RELEASE_ASSETS) throw new Error("Invalid feed release");
60
60
  const names = /* @__PURE__ */ new Set();
61
61
  const assets = value.assets.map((asset) => {
62
- if (!record(asset) || !exactKeys(asset, [
62
+ if (!isRecord(asset) || !exactKeys(asset, [
63
63
  "name",
64
64
  "size",
65
65
  "sha256"
66
- ]) || !isFeedAssetName(asset.name) || asset.name === "release.json" || names.has(asset.name) || !Number.isSafeInteger(asset.size) || Number(asset.size) < 1 || typeof asset.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(asset.sha256)) throw new Error("Invalid feed release asset");
66
+ ]) || !isFeedAssetName(asset.name) || asset.name === "release.json" || names.has(asset.name) || !Number.isSafeInteger(asset.size) || Number(asset.size) < 1 || typeof asset.sha256 !== "string" || !isSha256Hex(asset.sha256)) throw new Error("Invalid feed release asset");
67
67
  names.add(asset.name);
68
68
  return {
69
69
  name: asset.name,
@@ -84,7 +84,7 @@ function parseFeedRelease(value) {
84
84
  /** Validate the ledger: this app, at most MAX_LEDGER_RELEASES unique tags, newest first,
85
85
  * each kind matching its tag and only stable entries carrying a promotion time. */
86
86
  function parseReleaseLedger(value, app) {
87
- if (!record(value) || !exactKeys(value, [
87
+ if (!isRecord(value) || !exactKeys(value, [
88
88
  "schema",
89
89
  "app",
90
90
  "releases"
@@ -95,15 +95,15 @@ function parseReleaseLedger(value, app) {
95
95
  schema: 1,
96
96
  app,
97
97
  releases: value.releases.map((entry) => {
98
- const stable = record(entry) && entry.kind === "stable";
99
- if (!record(entry) || !exactKeys(entry, [
98
+ const stable = isRecord(entry) && entry.kind === "stable";
99
+ if (!isRecord(entry) || !exactKeys(entry, [
100
100
  "tag",
101
101
  "kind",
102
102
  "version",
103
103
  "sourceSha",
104
104
  "publishedAt",
105
105
  ...stable ? ["promotedAt"] : []
106
- ]) || !isFeedTag(entry.tag) || tags.has(entry.tag) || entry.version !== entry.tag.slice(1) || !(stable ? channelOf(entry.tag) === "daily" : entry.kind === channelOf(entry.tag)) || typeof entry.sourceSha !== "string" || !/^[a-f0-9]{40}$/.test(entry.sourceSha) || !timestamp(entry.publishedAt) || Date.parse(entry.publishedAt) > previous || stable && (!timestamp(entry.promotedAt) || Date.parse(entry.promotedAt) < Date.parse(entry.publishedAt))) throw new Error("Invalid release ledger entry");
106
+ ]) || !isFeedTag(entry.tag) || tags.has(entry.tag) || entry.version !== entry.tag.slice(1) || !(stable ? channelOf(entry.tag) === "daily" : entry.kind === channelOf(entry.tag)) || typeof entry.sourceSha !== "string" || !isGitSha(entry.sourceSha) || !timestamp(entry.publishedAt) || Date.parse(entry.publishedAt) > previous || stable && (!timestamp(entry.promotedAt) || Date.parse(entry.promotedAt) < Date.parse(entry.publishedAt))) throw new Error("Invalid release ledger entry");
107
107
  tags.add(entry.tag);
108
108
  previous = Date.parse(entry.publishedAt);
109
109
  return {
@@ -1,3 +1,4 @@
1
+ import { isGitSha, isRecord, isSha256Hex } from "../app/value-guards.js";
1
2
  import { createHash, createPublicKey, sign, timingSafeEqual, verify } from "node:crypto";
2
3
  // src/updates/signed-release.ts
3
4
  var verifiedDescriptors = /* @__PURE__ */ new WeakMap();
@@ -30,15 +31,14 @@ var assetKeys = [
30
31
  "size",
31
32
  "sha256"
32
33
  ];
33
- var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
34
34
  var exactKeys = (value, expected) => Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
35
35
  function valid(value) {
36
- if (!record(value) || !exactKeys(value, keys) || !record(value.asset) || !exactKeys(value.asset, assetKeys)) return false;
36
+ if (!isRecord(value) || !exactKeys(value, keys) || !isRecord(value.asset) || !exactKeys(value.asset, assetKeys)) return false;
37
37
  if (value.schema !== 2 || typeof value.appId !== "string" || !/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/.test(value.appId) || value.appId.length > 255) return false;
38
38
  if (typeof value.repository !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(value.repository) || value.repository.length > 200) return false;
39
39
  if (value.channel !== "dev" && value.channel !== "daily" && value.channel !== "stable") return false;
40
40
  if (typeof value.version !== "string" || value.version.length > 64 || !/^\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(value.version) || value.tag !== `v${value.version}` || value.channel === "dev" !== /-dev\.\d+$/.test(value.version)) return false;
41
- if (typeof value.sourceSha !== "string" || !/^[a-f0-9]{40}$/.test(value.sourceSha) || typeof value.workflowSha !== "string" || !/^[a-f0-9]{40}$/.test(value.workflowSha)) return false;
41
+ if (typeof value.sourceSha !== "string" || !isGitSha(value.sourceSha) || typeof value.workflowSha !== "string" || !isGitSha(value.workflowSha)) return false;
42
42
  if (typeof value.runId !== "string" || !/^[1-9]\d{0,19}$/.test(value.runId) || !Number.isSafeInteger(value.runAttempt) || Number(value.runAttempt) < 1) return false;
43
43
  if (![
44
44
  "darwin",
@@ -47,7 +47,7 @@ function valid(value) {
47
47
  ].includes(String(value.platform)) || !["arm64", "x64"].includes(String(value.arch))) return false;
48
48
  if (typeof value.keyId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(value.keyId)) return false;
49
49
  const asset = value.asset;
50
- if (typeof asset.name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(asset.name) || typeof asset.url !== "string" || asset.url.length > 2048 || typeof asset.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(asset.sha256) || !Number.isSafeInteger(asset.size) || Number(asset.size) < 1) return false;
50
+ if (typeof asset.name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(asset.name) || typeof asset.url !== "string" || asset.url.length > 2048 || typeof asset.sha256 !== "string" || !isSha256Hex(asset.sha256) || !Number.isSafeInteger(asset.size) || Number(asset.size) < 1) return false;
51
51
  try {
52
52
  const url = new URL(asset.url);
53
53
  return url.protocol === "https:" && url.href === asset.url && !url.port && !url.username && !url.password && !url.search && !url.hash && url.pathname.endsWith(`/${value.tag}/${asset.name}`);
@@ -90,7 +90,7 @@ function signReleaseDescriptor(descriptor, privateKey) {
90
90
  /** Authenticate the entire descriptor against an application-owned trust policy. */
91
91
  function verifyReleaseDescriptor(value, trust) {
92
92
  try {
93
- if (!record(value) || !exactKeys(value, ["descriptor", "signature"]) || typeof value.signature !== "string" || !/^[A-Za-z0-9_-]{86}$/.test(value.signature)) return { ok: false };
93
+ if (!isRecord(value) || !exactKeys(value, ["descriptor", "signature"]) || typeof value.signature !== "string" || !/^[A-Za-z0-9_-]{86}$/.test(value.signature)) return { ok: false };
94
94
  if (!valid(value.descriptor)) return { ok: false };
95
95
  const descriptor = structuredClone(value.descriptor);
96
96
  if (!valid(descriptor)) return { ok: false };
@@ -8,3 +8,21 @@ export declare function openUnchangedFile(path: string, info: Stats, message: st
8
8
  file: FileHandle;
9
9
  before: Stats;
10
10
  }>;
11
+ /**
12
+ * Stream and SHA-256 an open regular file, failing with `message` if it grows,
13
+ * shrinks, or is replaced while it is read. `before` is the handle's stat from
14
+ * before reading, as {@link openUnchangedFile} returns it.
15
+ */
16
+ export declare function hashUnchangedFile(file: FileHandle, before: Stats, message: string): Promise<{
17
+ size: number;
18
+ sha256: string;
19
+ }>;
20
+ /** Open the regular file `info` (from lstat) described and stream its SHA-256, failing with
21
+ * `message` if it was swapped or changes while it is read. */
22
+ export declare function hashFileAt(path: string, info: Stats, message: string): Promise<{
23
+ size: number;
24
+ sha256: string;
25
+ }>;
26
+ /** Read a small regular state file without following a link. Missing reads as undefined; a
27
+ * link, non-file, empty or oversized file fails with `message`. */
28
+ export declare function readSmallStateFile(path: string, maximum: number, message: string): Promise<string | undefined>;
@@ -1,4 +1,6 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { open } from "node:fs/promises";
3
+ import { createHash } from "node:crypto";
2
4
  import { constants as constants$1 } from "node:fs";
3
5
  // src/updates/stable-file.ts
4
6
  /** Whether two stats describe the same, unmodified file. */
@@ -19,4 +21,55 @@ async function openUnchangedFile(path, info, message) {
19
21
  before
20
22
  };
21
23
  }
22
- export { openUnchangedFile, sameFile };
24
+ /**
25
+ * Stream and SHA-256 an open regular file, failing with `message` if it grows,
26
+ * shrinks, or is replaced while it is read. `before` is the handle's stat from
27
+ * before reading, as {@link openUnchangedFile} returns it.
28
+ */
29
+ async function hashUnchangedFile(file, before, message) {
30
+ const hash = createHash("sha256");
31
+ let size = 0;
32
+ for await (const chunk of file.createReadStream({ autoClose: false })) {
33
+ size += chunk.length;
34
+ if (size > before.size) throw new Error(message);
35
+ hash.update(chunk);
36
+ }
37
+ if (size !== before.size || !sameFile(before, await file.stat())) throw new Error(message);
38
+ return {
39
+ size,
40
+ sha256: hash.digest("hex")
41
+ };
42
+ }
43
+ /** Open the regular file `info` (from lstat) described and stream its SHA-256, failing with
44
+ * `message` if it was swapped or changes while it is read. */
45
+ async function hashFileAt(path, info, message) {
46
+ const { file, before } = await openUnchangedFile(path, info, message);
47
+ try {
48
+ return await hashUnchangedFile(file, before, message);
49
+ } finally {
50
+ await file.close();
51
+ }
52
+ }
53
+ /** Read a small regular state file without following a link. Missing reads as undefined; a
54
+ * link, non-file, empty or oversized file fails with `message`. */
55
+ async function readSmallStateFile(path, maximum, message) {
56
+ let file;
57
+ try {
58
+ file = await open(path, constants$1.O_RDONLY | (constants$1.O_NOFOLLOW ?? 0) | (constants$1.O_NONBLOCK ?? 0));
59
+ } catch (error) {
60
+ const code = errorCode(error);
61
+ if (code === "ENOENT") return void 0;
62
+ if (code === "ELOOP" || code === "EMLINK") throw new Error(message, { cause: error });
63
+ throw error;
64
+ }
65
+ try {
66
+ const info = await file.stat();
67
+ if (!info.isFile() || info.size < 1 || info.size > maximum) throw new Error(message);
68
+ const text = await file.readFile("utf8");
69
+ if (Buffer.byteLength(text) !== info.size) throw new Error(message);
70
+ return text;
71
+ } finally {
72
+ await file.close();
73
+ }
74
+ }
75
+ export { hashFileAt, hashUnchangedFile, openUnchangedFile, readSmallStateFile, sameFile };
@@ -1,4 +1,5 @@
1
1
  import type { UpdateAdapter, UpdateChannel, UpdateState } from '@adea-ai/ui/components/composites/update-dialog';
2
+ import { type NativeUpdateSnapshotOf } from './update-state';
2
3
  export type { UpdateAdapter, UpdateChannel, UpdateState };
3
4
  /** Channel persistence as a `read`/`persist` pair. */
4
5
  export type UpdateChannelStore = Readonly<{
@@ -22,19 +23,7 @@ export declare function updateChannelStore(source: UpdateChannelSource): UpdateC
22
23
  */
23
24
  export declare function mirrorUpdateState(adapter: UpdateAdapter, onState: (state: UpdateState) => void): UpdateAdapter;
24
25
  /** A native updater snapshot in snake_case, as Rust and older desktop hosts report it. */
25
- export type NativeUpdateSnapshot = Readonly<{
26
- available_version: string | null;
27
- changelog: string;
28
- current_version: string;
29
- downloaded_bytes: number;
30
- error: string | null;
31
- github_url: string | null;
32
- phase: UpdateState['phase'];
33
- release_date: string | null;
34
- release_notes?: string | null;
35
- restart_required: boolean;
36
- total_bytes: number | null;
37
- }>;
26
+ export type NativeUpdateSnapshot = NativeUpdateSnapshotOf<UpdateState['phase'], string | null>;
38
27
  /** A native updater that answers with snake_case snapshots. */
39
28
  export type NativeUpdateAdapter = Readonly<{
40
29
  check(): Promise<NativeUpdateSnapshot>;
@@ -1,3 +1,5 @@
1
+ import { errorCode, isUuid } from "../app/value-guards.js";
2
+ import { isCanonicalPath } from "../native/canonical-path.js";
1
3
  import { verifyReleaseDescriptor } from "./signed-release.js";
2
4
  import { acquireUpdateLock, readUpdateStageState, writeUpdateStageState } from "./update-state-store.js";
3
5
  import { readUpdateTreeDigest, readUpdateTreeIdentity, sameUpdateTreeDigest, sameUpdateTreeIdentity, updateStagingFor } from "./update-swap.js";
@@ -7,9 +9,9 @@ import { publishUpdateLaunchGateCancellationRequest, readUpdateLaunchGate } from
7
9
  import { hasUpdateHelperArtifacts, parseUpdateHelperRequest } from "./update-helper.js";
8
10
  import { UpdateCleanupPendingError, UpdateCleanupTerminalError } from "./update-cleanup-error.js";
9
11
  import { copyFile, lstat, mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
10
- import { basename, dirname, isAbsolute, join, resolve } from "node:path";
11
- import { spawn } from "node:child_process";
12
+ import { basename, dirname, join } from "node:path";
12
13
  import { randomUUID } from "node:crypto";
14
+ import { spawn } from "node:child_process";
13
15
  // src/updates/update-arm.ts
14
16
  function exited(child) {
15
17
  return child.pid === void 0 || child.exitCode !== null || child.signalCode !== null;
@@ -45,7 +47,7 @@ function updateRuntimePath(platform, target) {
45
47
  */
46
48
  async function armUpdateHelper(options) {
47
49
  const staging = updateStagingFor(options.target);
48
- if (!isAbsolute(options.helperScript) || resolve(options.helperScript) !== options.helperScript) throw new Error("Invalid update helper script");
50
+ if (!isCanonicalPath(options.helperScript)) throw new Error("Invalid update helper script");
49
51
  const info = await lstat(staging);
50
52
  if (!info.isDirectory() || info.isSymbolicLink() || await realpath(staging) !== staging) throw new Error("Invalid update staging directory");
51
53
  let child;
@@ -103,7 +105,7 @@ async function armUpdateHelper(options) {
103
105
  try {
104
106
  request = parseUpdateHelperRequest(JSON.parse(await readFile(requestPath, "utf8")));
105
107
  } catch (error) {
106
- if (error.code !== "ENOENT") throw error;
108
+ if (errorCode(error) !== "ENOENT") throw error;
107
109
  }
108
110
  if (request && (request.schema !== 2 && request.schema !== 3 || request.generation !== generation || request.helperOwner !== helperOwner)) throw new Error("Another helper owns this staging generation");
109
111
  if (child?.pid !== void 0) {
@@ -284,7 +286,7 @@ async function armUpdateHelper(options) {
284
286
  if (readiness !== void 0) {
285
287
  if (!isUpdateHelperReadyMarker(readiness, generation, helperOwner)) throw new Error("Update helper readiness marker does not match its owner");
286
288
  const launchGateOwner = readiness.launchGateOwner;
287
- if (typeof launchGateOwner !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(launchGateOwner)) throw new Error("Update helper readiness marker does not acknowledge a launch gate");
289
+ if (typeof launchGateOwner !== "string" || !isUuid(launchGateOwner)) throw new Error("Update helper readiness marker does not acknowledge a launch gate");
288
290
  const [mapped, gate] = await Promise.all([readUpdateStageState(staging), readUpdateLaunchGate(options.target)]);
289
291
  if (!mapped || mapped.phase !== "armed" || mapped.generation !== generation || mapped.version !== options.version || mapped.helperPid !== child.pid || mapped.helperOwner !== helperOwner || mapped.launchGateOwner !== launchGateOwner || gate?.generation !== generation || gate.version !== options.version || gate.owner !== launchGateOwner) throw new Error("Update helper readiness does not match the exact published launch gate");
290
292
  if (exited(child)) throw new Error("Update helper exited before readiness was accepted");
@@ -1,14 +1,17 @@
1
+ import { errorCode } from "../app/value-guards.js";
2
+ import { isCanonicalPath } from "../native/canonical-path.js";
3
+ import { createSerialQueue } from "../app/serial-queue.js";
1
4
  import { isUpdateChannel } from "./release-version.js";
2
5
  import { openUnchangedFile, sameFile } from "./stable-file.js";
3
6
  import { lstat, open, realpath, rename, unlink } from "node:fs/promises";
4
- import { isAbsolute, join, resolve } from "node:path";
7
+ import { join } from "node:path";
5
8
  import { randomUUID } from "node:crypto";
6
9
  // src/updates/update-channel-store.ts
7
10
  /** Persist one app-owned update channel; the caller must supply a private state directory. */
8
11
  function createUpdateChannelStore(directory) {
9
- if (typeof directory !== "string" || !isAbsolute(directory) || resolve(directory) !== directory) throw new Error("Invalid update channel directory");
12
+ if (!isCanonicalPath(directory)) throw new Error("Invalid update channel directory");
10
13
  const path = join(directory, "update-channel.json");
11
- let queue = Promise.resolve();
14
+ const ordered = createSerialQueue();
12
15
  async function assertDirectory() {
13
16
  const info = await lstat(directory);
14
17
  if (!info.isDirectory() || info.isSymbolicLink() || await realpath(directory) !== directory) throw new Error("Invalid update channel directory");
@@ -19,7 +22,7 @@ function createUpdateChannelStore(directory) {
19
22
  try {
20
23
  info = await lstat(path);
21
24
  } catch (error) {
22
- if (error.code === "ENOENT") return "stable";
25
+ if (errorCode(error) === "ENOENT") return "stable";
23
26
  throw error;
24
27
  }
25
28
  if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > 4096) throw new Error("Invalid update channel file");
@@ -36,11 +39,6 @@ function createUpdateChannelStore(directory) {
36
39
  await file.close();
37
40
  }
38
41
  }
39
- function ordered(task) {
40
- const result = queue.then(task);
41
- queue = result.then(() => {}, () => {});
42
- return result;
43
- }
44
42
  return {
45
43
  read: () => ordered(read),
46
44
  save: (channel) => ordered(async () => {
@@ -15,43 +15,39 @@ async function discoverSignedRelease(options) {
15
15
  "daily",
16
16
  "dev"
17
17
  ].includes(trust.channel) || typeof trust.feed !== "string" || typeof discoveryName !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}\.json$/.test(discoveryName) || discoveryName === "release.json" || !Number.isSafeInteger(timeout) || timeout < 1 || timeout > 6e4) throw new Error("Invalid release discovery policy");
18
- const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeout);
19
- const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
18
+ const deadline = AbortSignal.timeout(timeout);
19
+ const signal = options.signal ? AbortSignal.any([deadline, options.signal]) : deadline;
20
20
  const fetcher = options.fetch ?? globalThis.fetch;
21
21
  const get = (path) => fetchReleaseLocation(`${trust.feed}${path}`, trust.feed, fetcher, signal);
22
- try {
23
- if (signal.aborted) throw new Error("Release discovery cancelled");
24
- let selected = null;
25
- if (olderThan === void 0) {
26
- selected = parseFeedRelease(await readReleaseJson(await get(`channels/${trust.channel}.json`), MAX_POINTER_BYTES));
27
- if (selected.channel !== trust.channel) throw new Error("Invalid channel pointer");
28
- } else {
29
- const kinds = trust.channel === "stable" ? ["stable"] : trust.channel === "dev" ? ["dev"] : ["daily", "stable"];
30
- const entry = parseReleaseLedger(await readReleaseJson(await get("index.json"), MAX_LEDGER_BYTES), new URL(trust.feed).pathname.split("/").at(-2)).releases.reduce((best, item) => kinds.includes(item.kind) && versionLessThan(item.tag, olderThan) && (!best || versionLessThan(best.tag, item.tag)) ? item : best, void 0);
31
- if (entry) {
32
- selected = parseFeedRelease(await readReleaseJson(await get(`${entry.tag}/release.json`), MAX_POINTER_BYTES));
33
- if (selected.tag !== entry.tag) throw new Error("Invalid feed release");
34
- if (!selected.assets.some((asset) => asset.name === discoveryName)) throw new Error("Selected previous release does not advertise this descriptor");
35
- }
36
- }
37
- const listed = selected?.assets.find((asset) => asset.name === discoveryName);
38
- if (!selected || !listed) throw new Error("No qualified channel descriptor is available");
39
- const { tag } = selected;
40
- const bytes = await readReleaseBytes(await get(`${tag}/${discoveryName}`), 65536);
41
- if (bytes.length !== listed.size || createHash("sha256").update(bytes).digest("hex") !== listed.sha256) throw new Error("Channel descriptor differs from its release");
42
- let signed;
43
- try {
44
- signed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
45
- } catch {
46
- throw new Error("Invalid release feed response");
22
+ if (signal.aborted) throw new Error("Release discovery cancelled");
23
+ let selected = null;
24
+ if (olderThan === void 0) {
25
+ selected = parseFeedRelease(await readReleaseJson(await get(`channels/${trust.channel}.json`), MAX_POINTER_BYTES));
26
+ if (selected.channel !== trust.channel) throw new Error("Invalid channel pointer");
27
+ } else {
28
+ const kinds = trust.channel === "stable" ? ["stable"] : trust.channel === "dev" ? ["dev"] : ["daily", "stable"];
29
+ const entry = parseReleaseLedger(await readReleaseJson(await get("index.json"), MAX_LEDGER_BYTES), new URL(trust.feed).pathname.split("/").at(-2)).releases.reduce((best, item) => kinds.includes(item.kind) && versionLessThan(item.tag, olderThan) && (!best || versionLessThan(best.tag, item.tag)) ? item : best, void 0);
30
+ if (entry) {
31
+ selected = parseFeedRelease(await readReleaseJson(await get(`${entry.tag}/release.json`), MAX_POINTER_BYTES));
32
+ if (selected.tag !== entry.tag) throw new Error("Invalid feed release");
33
+ if (!selected.assets.some((asset) => asset.name === discoveryName)) throw new Error("Selected previous release does not advertise this descriptor");
47
34
  }
48
- const result = verifyReleaseDescriptor(signed, trust);
49
- if (!result.ok || result.descriptor.tag !== tag) throw new Error("Untrusted channel descriptor");
50
- const payload = selected.assets.find((asset) => asset.name === result.descriptor.asset.name);
51
- if (!payload || payload.size !== result.descriptor.asset.size || payload.sha256 !== result.descriptor.asset.sha256) throw new Error("Release payload is missing or differs from its descriptor");
52
- return result.descriptor;
53
- } finally {
54
- clearTimeout(timer);
55
35
  }
36
+ const listed = selected?.assets.find((asset) => asset.name === discoveryName);
37
+ if (!selected || !listed) throw new Error("No qualified channel descriptor is available");
38
+ const { tag } = selected;
39
+ const bytes = await readReleaseBytes(await get(`${tag}/${discoveryName}`), 65536);
40
+ if (bytes.length !== listed.size || createHash("sha256").update(bytes).digest("hex") !== listed.sha256) throw new Error("Channel descriptor differs from its release");
41
+ let signed;
42
+ try {
43
+ signed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
44
+ } catch {
45
+ throw new Error("Invalid release feed response");
46
+ }
47
+ const result = verifyReleaseDescriptor(signed, trust);
48
+ if (!result.ok || result.descriptor.tag !== tag) throw new Error("Untrusted channel descriptor");
49
+ const payload = selected.assets.find((asset) => asset.name === result.descriptor.asset.name);
50
+ if (!payload || payload.size !== result.descriptor.asset.size || payload.sha256 !== result.descriptor.asset.sha256) throw new Error("Release payload is missing or differs from its descriptor");
51
+ return result.descriptor;
56
52
  }
57
53
  export { discoverSignedRelease };
@@ -1,3 +1,4 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { acquireUpdateDownloadLease, withUpdateDownloadRootLock } from "./update-download-lock.js";
2
3
  import { lstat, mkdir, mkdtemp, readdir, realpath, rm } from "node:fs/promises";
3
4
  import { basename, dirname, join, resolve } from "node:path";
@@ -101,7 +102,7 @@ async function removeAbandonedUpdateDownloads(root) {
101
102
  await lstat(directory);
102
103
  continue;
103
104
  } catch (error) {
104
- if (error.code !== "ENOENT") continue;
105
+ if (errorCode(error) !== "ENOENT") continue;
105
106
  }
106
107
  try {
107
108
  const lease = await acquireUpdateDownloadLease(directory, true);