@adea-ai/app-framework 0.31.0 → 0.33.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 (111) hide show
  1. package/README.md +33 -15
  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 -178
  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/packaged-update-startup.d.ts +25 -5
  68. package/dist/updates/packaged-update-startup.js +30 -5
  69. package/dist/updates/release-feed.js +9 -9
  70. package/dist/updates/signed-release.js +5 -5
  71. package/dist/updates/stable-file.d.ts +18 -0
  72. package/dist/updates/stable-file.js +65 -2
  73. package/dist/updates/update-adapter.d.ts +2 -13
  74. package/dist/updates/update-arm.js +13 -13
  75. package/dist/updates/update-channel-store.js +7 -9
  76. package/dist/updates/update-discovery.js +30 -34
  77. package/dist/updates/update-download-cleanup.js +2 -1
  78. package/dist/updates/update-download.js +2 -4
  79. package/dist/updates/update-extraction.js +1 -1
  80. package/dist/updates/update-generation-lease.js +4 -3
  81. package/dist/updates/update-handoff-plan.js +3 -2
  82. package/dist/updates/update-helper.js +8 -6
  83. package/dist/updates/update-instance-lease.js +3 -2
  84. package/dist/updates/update-launch-gate.js +12 -25
  85. package/dist/updates/update-launch.js +3 -2
  86. package/dist/updates/update-lock.js +3 -2
  87. package/dist/updates/update-marker.js +3 -2
  88. package/dist/updates/update-process-fence.js +10 -39
  89. package/dist/updates/update-process-liveness.js +2 -1
  90. package/dist/updates/update-resume.js +30 -27
  91. package/dist/updates/update-retention-marker.js +7 -5
  92. package/dist/updates/update-retention-plan.js +2 -2
  93. package/dist/updates/update-retirement.js +52 -52
  94. package/dist/updates/update-state-store.d.ts +2 -0
  95. package/dist/updates/update-state-store.js +34 -38
  96. package/dist/updates/update-state.d.ts +8 -3
  97. package/dist/updates/update-swap-stage.js +6 -5
  98. package/dist/updates/update-swap.d.ts +1 -1
  99. package/dist/updates/update-swap.js +8 -6
  100. package/package.json +4 -12
  101. package/src/desktop/client-asset-stream.ts +6 -12
  102. package/src/updates/update-adapter.ts +2 -14
  103. package/src/updates/update-state.ts +11 -2
  104. package/templates/application/src/bun/index.ts +13 -9
  105. package/dist/native/directory-exchange.js +0 -90
  106. package/dist/native/exclusive-rename.d.ts +0 -2
  107. package/dist/native/exclusive-rename.js +0 -52
  108. package/dist/release/retention-dry-run.d.ts +0 -46
  109. package/dist/release/retention-dry-run.js +0 -94
  110. package/dist/updates/update-exclusive-rename.d.ts +0 -3
  111. 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");
@@ -16,16 +16,35 @@ export type PreparedPackagedUpdateStartup = Readonly<{
16
16
  release(): Promise<void>;
17
17
  };
18
18
  }>;
19
- /**
20
- * Validate bundled release trust, select only its channel from private app state,
21
- * then reconcile and lease retained assets before a managed packaged host starts.
22
- */
23
- export declare function preparePackagedUpdateStartup(options: {
19
+ /** Why an unmanaged launch runs without an updater. */
20
+ export type UnavailablePackagedUpdateStartup = Readonly<{
21
+ status: 'unavailable';
22
+ reason: string;
23
+ }>;
24
+ type PackagedUpdateStartupOptions = {
24
25
  entryDirectory: string;
25
26
  dataDirectory: string;
26
27
  identity: PackagedReleaseIdentity;
27
28
  loadManifest(root: string): Promise<ReadonlyMap<string, string>>;
29
+ };
30
+ /**
31
+ * Validate bundled release trust, select only its channel from private app
32
+ * state, and reconcile any earlier update before the packaged host starts.
33
+ *
34
+ * `acquired` (the default) is a launch admitted under an inherited instance
35
+ * lease: it also leases retained asset generations for the host, and any
36
+ * failure pauses startup. `unmanaged` is a launch without that lease (stock
37
+ * packaging, Windows): it reconciles under the install lock alone, retains no
38
+ * generations, and reports `unavailable` instead of throwing so the app still
39
+ * starts. The update helper waits for this process to exit before it swaps
40
+ * either way.
41
+ */
42
+ export declare function preparePackagedUpdateStartup(options: PackagedUpdateStartupOptions & {
43
+ admission?: 'acquired';
28
44
  }): Promise<PreparedPackagedUpdateStartup>;
45
+ export declare function preparePackagedUpdateStartup(options: PackagedUpdateStartupOptions & {
46
+ admission: 'acquired' | 'unmanaged';
47
+ }): Promise<PreparedPackagedUpdateStartup | UnavailablePackagedUpdateStartup>;
29
48
  /**
30
49
  * Pre-launch dispatcher for an update launch gate left behind by a helper
31
50
  * that crashed mid-transition. Call it before launch admission, while this
@@ -42,3 +61,4 @@ export declare function recoverPackagedUpdateLaunchGate(options: {
42
61
  dataDirectory: string;
43
62
  identity: PackagedReleaseIdentity;
44
63
  }): Promise<UpdateLaunchGateRecoveryResult>;
64
+ export {};
@@ -2,16 +2,13 @@ import { readPackagedVersion } from "../native/app-bundle.js";
2
2
  import { feedUrl } from "./release-feed.js";
3
3
  import { readUpdateLaunchGate } from "./update-launch-gate.js";
4
4
  import { createUpdateChannelStore, releaseChannelForUpdate } from "./update-channel-store.js";
5
- import { recoverUpdateLaunchGate } from "./update-resume.js";
5
+ import { recoverUpdateLaunchGate, resumeUpdate } from "./update-resume.js";
6
6
  import { installTarget, resumeAndAcquireRetainedDesktopClientAssets, updatePlatform, updateTrust } from "./desktop-updater.js";
7
7
  import { readPackagedReleaseConfig } from "./packaged-release-config.js";
8
8
  import { realpath } from "node:fs/promises";
9
9
  // src/updates/packaged-update-startup.ts
10
- /**
11
- * Validate bundled release trust, select only its channel from private app state,
12
- * then reconcile and lease retained assets before a managed packaged host starts.
13
- */
14
10
  async function preparePackagedUpdateStartup(options) {
11
+ if (options.admission === "unmanaged") return prepareUnmanagedUpdateStartup(options);
15
12
  const { release, trust, savedChannel, channel } = await packagedReleaseTrust(options);
16
13
  const { version: currentVersion } = readPackagedVersion(options.entryDirectory);
17
14
  const resumed = await resumeAndAcquireRetainedDesktopClientAssets({
@@ -34,6 +31,34 @@ async function preparePackagedUpdateStartup(options) {
34
31
  releaseLease: { release: resumed.release }
35
32
  };
36
33
  }
34
+ var releaseNothing = { release: async () => {} };
35
+ async function prepareUnmanagedUpdateStartup(options) {
36
+ try {
37
+ const { release, platform, trust, savedChannel, channel } = await packagedReleaseTrust(options);
38
+ const { version: currentVersion } = readPackagedVersion(options.entryDirectory);
39
+ return {
40
+ status: "ready",
41
+ release,
42
+ currentVersion,
43
+ savedChannel,
44
+ resume: await resumeUpdate({
45
+ target: await realpath(installTarget(options.entryDirectory, platform)),
46
+ trust: {
47
+ ...trust,
48
+ channel
49
+ },
50
+ currentVersion
51
+ }),
52
+ retainedClientAssets: [],
53
+ releaseLease: releaseNothing
54
+ };
55
+ } catch (error) {
56
+ return {
57
+ status: "unavailable",
58
+ reason: error instanceof Error ? error.message : String(error)
59
+ };
60
+ }
61
+ }
37
62
  /** Bundled release trust narrowed to the channel saved in private app state. */
38
63
  async function packagedReleaseTrust(options) {
39
64
  const release = await readPackagedReleaseConfig(options.entryDirectory, options.identity);
@@ -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 { open } from "node:fs/promises";
1
+ import { errorCode } from "../app/value-guards.js";
2
+ import { lstat, 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,65 @@ 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 linkFree;
57
+ if (constants$1.O_NOFOLLOW === void 0) {
58
+ try {
59
+ linkFree = await lstat(path);
60
+ } catch (error) {
61
+ if (errorCode(error) === "ENOENT") return void 0;
62
+ throw error;
63
+ }
64
+ if (linkFree.isSymbolicLink()) throw new Error(message);
65
+ }
66
+ let file;
67
+ try {
68
+ file = await open(path, constants$1.O_RDONLY | (constants$1.O_NOFOLLOW ?? 0) | (constants$1.O_NONBLOCK ?? 0));
69
+ } catch (error) {
70
+ const code = errorCode(error);
71
+ if (code === "ENOENT") return void 0;
72
+ if (code === "ELOOP" || code === "EMLINK") throw new Error(message, { cause: error });
73
+ throw error;
74
+ }
75
+ try {
76
+ const info = await file.stat();
77
+ if (!info.isFile() || info.size < 1 || info.size > maximum || linkFree && (linkFree.dev !== info.dev || linkFree.ino !== info.ino)) throw new Error(message);
78
+ const text = await file.readFile("utf8");
79
+ if (Buffer.byteLength(text) !== info.size) throw new Error(message);
80
+ return text;
81
+ } finally {
82
+ await file.close();
83
+ }
84
+ }
85
+ 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,15 +1,17 @@
1
+ import { isUuid } from "../app/value-guards.js";
2
+ import { isCanonicalPath } from "../native/canonical-path.js";
1
3
  import { verifyReleaseDescriptor } from "./signed-release.js";
2
- import { acquireUpdateLock, readUpdateStageState, writeUpdateStageState } from "./update-state-store.js";
4
+ import { acquireUpdateLock, readUpdateHelperRequestFile, readUpdateStageState, writeUpdateStageState } from "./update-state-store.js";
3
5
  import { readUpdateTreeDigest, readUpdateTreeIdentity, sameUpdateTreeDigest, sameUpdateTreeIdentity, updateStagingFor } from "./update-swap.js";
4
6
  import { isUpdateHelperReadyMarker, readUpdateMarker } from "./update-marker.js";
5
7
  import { updateLauncherPath } from "./update-launch.js";
6
8
  import { publishUpdateLaunchGateCancellationRequest, readUpdateLaunchGate } from "./update-launch-gate.js";
7
9
  import { hasUpdateHelperArtifacts, parseUpdateHelperRequest } from "./update-helper.js";
8
10
  import { UpdateCleanupPendingError, UpdateCleanupTerminalError } from "./update-cleanup-error.js";
9
- 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";
11
+ import { copyFile, lstat, mkdir, realpath, rm, writeFile } from "node:fs/promises";
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;
@@ -67,7 +69,9 @@ async function armUpdateHelper(options) {
67
69
  const current = await readUpdateStageState(staging);
68
70
  if (!current || current.generation !== generation) throw new Error("Update cancellation no longer owns this staging generation");
69
71
  if (current.phase === "staged") {
70
- const request = parseUpdateHelperRequest(JSON.parse(await readFile(join(staging, "request.json"), "utf8")));
72
+ const text = await readUpdateHelperRequestFile(staging);
73
+ if (text === void 0) throw new Error("Update helper request is missing");
74
+ const request = parseUpdateHelperRequest(JSON.parse(text));
71
75
  if (request.generation !== generation || request.helperOwner !== helperOwner || current.helperPid !== void 0 && current.helperPid !== child.pid || current.helperOwner !== void 0 && current.helperOwner !== helperOwner) throw new Error("Another helper owns this staging generation");
72
76
  helperBoundFromStaged = true;
73
77
  if (!exited(child)) await writeUpdateStageState(staging, {
@@ -98,13 +102,9 @@ async function armUpdateHelper(options) {
98
102
  if (!child || child.pid === void 0 || current.helperPid !== child.pid || !helperOwner || current.helperOwner !== helperOwner) throw new Error("Another helper owns this staging generation");
99
103
  if (child.pid !== void 0 && !exited(child)) throw new Error("Update helper is still running during cancellation cleanup");
100
104
  }
101
- const requestPath = join(staging, "request.json");
102
105
  let request;
103
- try {
104
- request = parseUpdateHelperRequest(JSON.parse(await readFile(requestPath, "utf8")));
105
- } catch (error) {
106
- if (error.code !== "ENOENT") throw error;
107
- }
106
+ const requestText = await readUpdateHelperRequestFile(staging);
107
+ if (requestText !== void 0) request = parseUpdateHelperRequest(JSON.parse(requestText));
108
108
  if (request && (request.schema !== 2 && request.schema !== 3 || request.generation !== generation || request.helperOwner !== helperOwner)) throw new Error("Another helper owns this staging generation");
109
109
  if (child?.pid !== void 0) {
110
110
  if (!helperOwner || !exited(child)) throw new Error("Update helper is still running during cancellation cleanup");
@@ -284,7 +284,7 @@ async function armUpdateHelper(options) {
284
284
  if (readiness !== void 0) {
285
285
  if (!isUpdateHelperReadyMarker(readiness, generation, helperOwner)) throw new Error("Update helper readiness marker does not match its owner");
286
286
  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");
287
+ if (typeof launchGateOwner !== "string" || !isUuid(launchGateOwner)) throw new Error("Update helper readiness marker does not acknowledge a launch gate");
288
288
  const [mapped, gate] = await Promise.all([readUpdateStageState(staging), readUpdateLaunchGate(options.target)]);
289
289
  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
290
  if (exited(child)) throw new Error("Update helper exited before readiness was accepted");