@adea-ai/app-framework 0.24.0 → 0.25.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 (137) hide show
  1. package/README.md +49 -1
  2. package/dist/cli/macos-signing-cli.d.ts +2 -0
  3. package/dist/cli/macos-signing-cli.js +14 -0
  4. package/dist/desktop/channel-proof.js +7 -1
  5. package/dist/framework-source.json +1 -1
  6. package/dist/release/framework-package-publish.js +4 -2
  7. package/dist/release/local-release.d.ts +2 -0
  8. package/dist/release/local-release.js +25 -2
  9. package/dist/release/macos-signing.d.ts +27 -0
  10. package/dist/release/macos-signing.js +101 -0
  11. package/dist/shell/app-shell.js +21 -33
  12. package/dist/shell/navigation-drawer.d.ts +12 -0
  13. package/dist/shell/navigation-drawer.js +42 -0
  14. package/dist/updates/release-feed.d.ts +2 -0
  15. package/dist/updates/release-feed.js +11 -2
  16. package/package.json +16 -4
  17. package/src/shell/app-shell.tsx +29 -20
  18. package/src/shell/navigation-drawer.tsx +36 -0
  19. package/src/app/create-application.ts +0 -245
  20. package/src/app/service-registry.ts +0 -124
  21. package/src/ci/toolchain-identity.ts +0 -244
  22. package/src/cli/cef-helper-cli.ts +0 -21
  23. package/src/cli/cli-runner.ts +0 -29
  24. package/src/cli/create-application-cli.ts +0 -62
  25. package/src/cli/electrobun-shortcut-patch-cli.ts +0 -24
  26. package/src/cli/framework-update-cli.ts +0 -41
  27. package/src/cli/release-assets-plan-cli.ts +0 -14
  28. package/src/cli/release-cut-cli.ts +0 -41
  29. package/src/cli/release-descriptor-staging-cli.ts +0 -57
  30. package/src/cli/release-finalize-cli.ts +0 -34
  31. package/src/cli/release-promote-cli.ts +0 -31
  32. package/src/cli/release-publish-cli.ts +0 -46
  33. package/src/cli/release-sign-cli.ts +0 -24
  34. package/src/cli/release-step-cli.ts +0 -71
  35. package/src/cli/toolchain-identity-cli.ts +0 -12
  36. package/src/cli/update-helper-cli.ts +0 -12
  37. package/src/cli/windows-runtime-patch-cli.ts +0 -17
  38. package/src/desktop/application-command-client.ts +0 -43
  39. package/src/desktop/channel-handshake.ts +0 -136
  40. package/src/desktop/channel-proof.ts +0 -122
  41. package/src/desktop/desktop-client.ts +0 -303
  42. package/src/desktop/desktop-gateway.ts +0 -189
  43. package/src/desktop/desktop-host.ts +0 -335
  44. package/src/desktop/desktop-stream.ts +0 -324
  45. package/src/desktop/loopback-policy.ts +0 -41
  46. package/src/desktop/open-url-channel.ts +0 -79
  47. package/src/desktop/string-policy.ts +0 -9
  48. package/src/installer/archive-entry.ts +0 -32
  49. package/src/installer/command-artifact.ts +0 -307
  50. package/src/installer/command-qualification-command.ts +0 -75
  51. package/src/installer/hosted-runner.ts +0 -11
  52. package/src/installer/installed-payload.ts +0 -408
  53. package/src/installer/installer-ci-bootstrap.ts +0 -199
  54. package/src/installer/installer-ci-preflight.ts +0 -61
  55. package/src/installer/installer-ci-worker.ts +0 -105
  56. package/src/installer/installer-extraction.ts +0 -367
  57. package/src/installer/installer-fetch-guard.ts +0 -75
  58. package/src/installer/installer-identity.ts +0 -331
  59. package/src/installer/installer-layout.ts +0 -167
  60. package/src/installer/installer-observation.ts +0 -671
  61. package/src/installer/installer-process-cleanup.ts +0 -167
  62. package/src/installer/installer-qualification-command.ts +0 -81
  63. package/src/installer/installer-renderer-evidence.ts +0 -268
  64. package/src/installer/installer-upgrade-command.ts +0 -226
  65. package/src/installer/installer-worker-guard.ts +0 -112
  66. package/src/installer/native-executable.ts +0 -37
  67. package/src/installer/upgrade-asset-download.ts +0 -72
  68. package/src/installer/write-all.ts +0 -19
  69. package/src/native/app-bundle.ts +0 -86
  70. package/src/native/cef-helper.ts +0 -471
  71. package/src/native/desktop-build-hook.ts +0 -21
  72. package/src/native/electrobun-source-patch.ts +0 -107
  73. package/src/native/linux-cef-links.ts +0 -14
  74. package/src/native/native-secret-store.ts +0 -99
  75. package/src/native/native-utilities.ts +0 -166
  76. package/src/native/partitioned-window.ts +0 -62
  77. package/src/native/secure-window.ts +0 -115
  78. package/src/native/sidecar-services.ts +0 -71
  79. package/src/native/sidecar.ts +0 -387
  80. package/src/native/window-bootstrap.ts +0 -77
  81. package/src/native/windows-build-hook-internal.ts +0 -49
  82. package/src/native/windows-build-hook.ts +0 -12
  83. package/src/native/windows-runtime-patch-internal.ts +0 -48
  84. package/src/native/windows-runtime-patch.ts +0 -15
  85. package/src/release/feed-release-cut.ts +0 -110
  86. package/src/release/feed-state.ts +0 -135
  87. package/src/release/framework-package-publish.ts +0 -163
  88. package/src/release/framework-update.ts +0 -196
  89. package/src/release/github-cli.ts +0 -27
  90. package/src/release/github-release-assets.ts +0 -36
  91. package/src/release/github-release-cut.ts +0 -237
  92. package/src/release/github-release-lookup.ts +0 -39
  93. package/src/release/github-release-promotion.ts +0 -112
  94. package/src/release/github-release-provenance.ts +0 -65
  95. package/src/release/github-release-publisher.ts +0 -90
  96. package/src/release/github-release-qualification.ts +0 -144
  97. package/src/release/local-provenance.ts +0 -92
  98. package/src/release/local-release.ts +0 -525
  99. package/src/release/macos-dmg.ts +0 -113
  100. package/src/release/release-artifact.ts +0 -53
  101. package/src/release/release-assets-plan.ts +0 -118
  102. package/src/release/release-config.ts +0 -420
  103. package/src/release/release-cut-command.ts +0 -80
  104. package/src/release/release-cut.ts +0 -133
  105. package/src/release/release-descriptor-staging.ts +0 -242
  106. package/src/release/release-finalize.ts +0 -191
  107. package/src/release/release-promotion-command.ts +0 -36
  108. package/src/release/release-promotion.ts +0 -132
  109. package/src/release/release-publication.ts +0 -213
  110. package/src/release/release-publish-command.ts +0 -163
  111. package/src/release/release-qualification.ts +0 -397
  112. package/src/release/release-staging.ts +0 -87
  113. package/src/release/release-steps.ts +0 -173
  114. package/src/release/retained-release-build.ts +0 -217
  115. package/src/shell/application-menu-commands.ts +0 -6
  116. package/src/shell/application-menu.ts +0 -250
  117. package/src/updates/channel-update-manager.ts +0 -127
  118. package/src/updates/desktop-updater.ts +0 -440
  119. package/src/updates/release-feed.ts +0 -187
  120. package/src/updates/release-location.ts +0 -101
  121. package/src/updates/signed-release.ts +0 -311
  122. package/src/updates/stable-file.ts +0 -32
  123. package/src/updates/update-arm.ts +0 -107
  124. package/src/updates/update-channel-store.ts +0 -86
  125. package/src/updates/update-discovery.ts +0 -113
  126. package/src/updates/update-download.ts +0 -82
  127. package/src/updates/update-exclusive-rename.ts +0 -58
  128. package/src/updates/update-extraction.ts +0 -261
  129. package/src/updates/update-handoff-plan.ts +0 -75
  130. package/src/updates/update-helper.ts +0 -87
  131. package/src/updates/update-launch.ts +0 -33
  132. package/src/updates/update-manager.ts +0 -130
  133. package/src/updates/update-process-fence.ts +0 -125
  134. package/src/updates/update-resume.ts +0 -34
  135. package/src/updates/update-shutdown.ts +0 -37
  136. package/src/updates/update-swap-stage.ts +0 -75
  137. package/src/updates/update-swap.ts +0 -30
@@ -1,101 +0,0 @@
1
- /** A fetch implementation. Bun's `typeof fetch` also requires `preconnect`, which callers never use. */
2
- export type FetchFunction = (...args: Parameters<typeof fetch>) => Promise<Response>
3
-
4
- /** `value` as a URL inside `scope`: the same https origin, under its path prefix, with no
5
- * credentials, port, fragment or dot segments. */
6
- function releaseUrl(value: string, scope: URL): URL {
7
- const url = new URL(value)
8
- if (
9
- url.protocol !== 'https:' ||
10
- url.origin !== scope.origin ||
11
- url.port ||
12
- url.username ||
13
- url.password ||
14
- url.hash ||
15
- !url.pathname.startsWith(scope.pathname) ||
16
- /(?:^|\/)\.{1,2}(?:\/|$)|%2e|%2f|%5c/i.test(url.pathname)
17
- )
18
- throw new Error('Untrusted release location')
19
- return url
20
- }
21
-
22
- /** GET a release feed object without credentials, following at most five redirects that
23
- * stay under `scope`, the app's feed URL. The caller reads or cancels the response body. */
24
- export async function fetchReleaseLocation(
25
- location: string,
26
- scope: string,
27
- fetcher: FetchFunction,
28
- signal: AbortSignal
29
- ): Promise<Response> {
30
- const root = new URL(scope)
31
- if (
32
- root.protocol !== 'https:' ||
33
- root.href !== scope ||
34
- !root.pathname.endsWith('/') ||
35
- root.search ||
36
- root.hash
37
- )
38
- throw new Error('Untrusted release location')
39
- let url = releaseUrl(location, root)
40
- for (let redirects = 0; ; redirects++) {
41
- const response = await fetcher(url, {
42
- method: 'GET',
43
- redirect: 'manual',
44
- credentials: 'omit',
45
- headers: { 'accept-encoding': 'identity' },
46
- signal,
47
- })
48
- if (![301, 302, 303, 307, 308].includes(response.status)) return response
49
- const next = response.headers.get('location')
50
- await response.body?.cancel()
51
- if (!next || redirects === 5) throw new Error('Invalid release redirect')
52
- url = releaseUrl(new URL(next, url).href, root)
53
- }
54
- }
55
-
56
- /** Read a 200 response body of at most `maximum` bytes. */
57
- export async function readReleaseBytes(response: Response, maximum: number): Promise<Uint8Array> {
58
- if (response.status !== 200 || !response.body) {
59
- await response.body?.cancel()
60
- throw new Error('Release feed request failed')
61
- }
62
- const length = response.headers.get('content-length')
63
- if (length !== null && (!/^\d+$/.test(length) || Number(length) > maximum)) {
64
- await response.body.cancel()
65
- throw new Error('Release feed response exceeds bound')
66
- }
67
- const reader = response.body.getReader(),
68
- chunks: Uint8Array[] = []
69
- let total = 0
70
- try {
71
- for (;;) {
72
- const { value, done } = await reader.read()
73
- if (done) break
74
- total += value.length
75
- if (total > maximum) {
76
- await reader.cancel()
77
- throw new Error('Release feed response exceeds bound')
78
- }
79
- chunks.push(value)
80
- }
81
- } finally {
82
- reader.releaseLock()
83
- }
84
- const bytes = new Uint8Array(total)
85
- let offset = 0
86
- for (const chunk of chunks) {
87
- bytes.set(chunk, offset)
88
- offset += chunk.length
89
- }
90
- return bytes
91
- }
92
-
93
- /** Parse a 200 response of at most `maximum` bytes as UTF-8 JSON. */
94
- export async function readReleaseJson(response: Response, maximum: number): Promise<unknown> {
95
- const bytes = await readReleaseBytes(response, maximum)
96
- try {
97
- return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))
98
- } catch {
99
- throw new Error('Invalid release feed response')
100
- }
101
- }
@@ -1,311 +0,0 @@
1
- import {
2
- createHash,
3
- createPublicKey,
4
- sign,
5
- timingSafeEqual,
6
- verify,
7
- type KeyObject,
8
- } from 'node:crypto'
9
-
10
- export type ReleaseDescriptor = Readonly<{
11
- schema: 2
12
- appId: string
13
- repository: string
14
- channel: 'dev' | 'daily' | 'stable'
15
- tag: string
16
- version: string
17
- sourceSha: string
18
- workflowSha: string
19
- runId: string
20
- runAttempt: number
21
- platform: 'darwin' | 'win32' | 'linux'
22
- arch: 'arm64' | 'x64'
23
- asset: Readonly<{ name: string; url: string; size: number; sha256: string }>
24
- keyId: string
25
- }>
26
- declare const verifiedBrand: unique symbol
27
- export type VerifiedRelease = ReleaseDescriptor & { readonly [verifiedBrand]: true }
28
- const verifiedDescriptors = new WeakMap<object, { key: string; signature: string }>()
29
- export type SignedRelease = Readonly<{ descriptor: ReleaseDescriptor; signature: string }>
30
- export type ReleaseTrust = Readonly<{
31
- appId: string
32
- repository: string
33
- channel: ReleaseDescriptor['channel']
34
- platform: ReleaseDescriptor['platform']
35
- arch: ReleaseDescriptor['arch']
36
- /** The app's release feed URL, ending in `/`; every asset URL is `<feed><tag>/<name>`. */
37
- feed: string
38
- keys: ReadonlyMap<string, string>
39
- }>
40
- /** A GitHub `owner/name` slug that is safe to place in API and download paths. */
41
- export function isRepositorySlug(value: string): boolean {
42
- return (
43
- /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(value) &&
44
- value.length <= 200 &&
45
- value.split('/').every((part) => part !== '.' && part !== '..')
46
- )
47
- }
48
- export function assertRepositorySlug(value: string): void {
49
- if (!isRepositorySlug(value)) throw new Error('Invalid GitHub repository')
50
- }
51
- const keys = [
52
- 'schema',
53
- 'appId',
54
- 'repository',
55
- 'channel',
56
- 'tag',
57
- 'version',
58
- 'sourceSha',
59
- 'workflowSha',
60
- 'runId',
61
- 'runAttempt',
62
- 'platform',
63
- 'arch',
64
- 'asset',
65
- 'keyId',
66
- ]
67
- const assetKeys = ['name', 'url', 'size', 'sha256']
68
- const record = (value: unknown): value is Record<string, unknown> =>
69
- typeof value === 'object' && value !== null && !Array.isArray(value)
70
- const exactKeys = (value: Record<string, unknown>, expected: string[]) =>
71
- Object.keys(value).length === expected.length &&
72
- expected.every((key) => Object.hasOwn(value, key))
73
- function valid(value: unknown): value is ReleaseDescriptor {
74
- if (
75
- !record(value) ||
76
- !exactKeys(value, keys) ||
77
- !record(value.asset) ||
78
- !exactKeys(value.asset, assetKeys)
79
- )
80
- return false
81
- if (
82
- value.schema !== 2 ||
83
- typeof value.appId !== 'string' ||
84
- !/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/.test(value.appId) ||
85
- value.appId.length > 255
86
- )
87
- return false
88
- if (
89
- typeof value.repository !== 'string' ||
90
- !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(value.repository) ||
91
- value.repository.length > 200
92
- )
93
- return false
94
- if (value.channel !== 'dev' && value.channel !== 'daily' && value.channel !== 'stable')
95
- return false
96
- if (
97
- typeof value.version !== 'string' ||
98
- value.version.length > 64 ||
99
- !/^\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(value.version) ||
100
- value.tag !== `v${value.version}` ||
101
- (value.channel === 'dev') !== /-dev\.\d+$/.test(value.version)
102
- )
103
- return false
104
- if (
105
- typeof value.sourceSha !== 'string' ||
106
- !/^[a-f0-9]{40}$/.test(value.sourceSha) ||
107
- typeof value.workflowSha !== 'string' ||
108
- !/^[a-f0-9]{40}$/.test(value.workflowSha)
109
- )
110
- return false
111
- if (
112
- typeof value.runId !== 'string' ||
113
- !/^[1-9]\d{0,19}$/.test(value.runId) ||
114
- !Number.isSafeInteger(value.runAttempt) ||
115
- Number(value.runAttempt) < 1
116
- )
117
- return false
118
- if (
119
- !['darwin', 'win32', 'linux'].includes(String(value.platform)) ||
120
- !['arm64', 'x64'].includes(String(value.arch))
121
- )
122
- return false
123
- if (typeof value.keyId !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(value.keyId))
124
- return false
125
- const asset = value.asset
126
- if (
127
- typeof asset.name !== 'string' ||
128
- !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(asset.name) ||
129
- typeof asset.url !== 'string' ||
130
- asset.url.length > 2048 ||
131
- typeof asset.sha256 !== 'string' ||
132
- !/^[a-f0-9]{64}$/.test(asset.sha256) ||
133
- !Number.isSafeInteger(asset.size) ||
134
- Number(asset.size) < 1
135
- )
136
- return false
137
- try {
138
- const url = new URL(asset.url)
139
- return (
140
- url.protocol === 'https:' &&
141
- url.href === asset.url &&
142
- !url.port &&
143
- !url.username &&
144
- !url.password &&
145
- !url.search &&
146
- !url.hash &&
147
- url.pathname.endsWith(`/${value.tag}/${asset.name}`)
148
- )
149
- } catch {
150
- return false
151
- }
152
- }
153
- /** Whether the asset URL is exactly this release's object in the trusted feed. */
154
- const inFeed = (value: ReleaseDescriptor, feed: string) =>
155
- typeof feed === 'string' &&
156
- feed.startsWith('https://') &&
157
- feed.endsWith('/') &&
158
- value.asset.url === `${feed}${value.tag}/${value.asset.name}`
159
- function message(value: ReleaseDescriptor): Buffer {
160
- return Buffer.from(
161
- JSON.stringify([
162
- 'adea-app-framework-release-v2',
163
- value.schema,
164
- value.appId,
165
- value.repository,
166
- value.channel,
167
- value.tag,
168
- value.version,
169
- value.sourceSha,
170
- value.workflowSha,
171
- value.runId,
172
- value.runAttempt,
173
- value.platform,
174
- value.arch,
175
- value.asset.name,
176
- value.asset.url,
177
- value.asset.size,
178
- value.asset.sha256,
179
- value.keyId,
180
- ]),
181
- 'utf8'
182
- )
183
- }
184
- /** Sign canonical release metadata with an application-owned Ed25519 private key. */
185
- export function signReleaseDescriptor(
186
- descriptor: ReleaseDescriptor,
187
- privateKey: KeyObject
188
- ): SignedRelease {
189
- if (
190
- !valid(descriptor) ||
191
- privateKey.type !== 'private' ||
192
- privateKey.asymmetricKeyType !== 'ed25519'
193
- )
194
- throw new Error('Invalid release descriptor or signing key')
195
- return {
196
- descriptor,
197
- signature: sign(null, message(descriptor), privateKey).toString('base64url'),
198
- }
199
- }
200
- /** Authenticate the entire descriptor against an application-owned trust policy. */
201
- export function verifyReleaseDescriptor(
202
- value: unknown,
203
- trust: ReleaseTrust
204
- ): { ok: true; descriptor: VerifiedRelease } | { ok: false } {
205
- try {
206
- if (
207
- !record(value) ||
208
- !exactKeys(value, ['descriptor', 'signature']) ||
209
- typeof value.signature !== 'string' ||
210
- !/^[A-Za-z0-9_-]{86}$/.test(value.signature)
211
- )
212
- return { ok: false }
213
- if (!valid(value.descriptor)) return { ok: false }
214
- const descriptor: unknown = structuredClone(value.descriptor)
215
- if (!valid(descriptor)) return { ok: false }
216
- if (
217
- descriptor.appId !== trust.appId ||
218
- descriptor.repository !== trust.repository ||
219
- descriptor.channel !== trust.channel ||
220
- descriptor.platform !== trust.platform ||
221
- descriptor.arch !== trust.arch ||
222
- !inFeed(descriptor, trust.feed)
223
- )
224
- return { ok: false }
225
- const encoded = trust.keys.get(descriptor.keyId)
226
- if (!encoded) return { ok: false }
227
- const raw = Buffer.from(encoded, 'base64')
228
- const signature = Buffer.from(value.signature, 'base64url')
229
- if (
230
- raw.length !== 32 ||
231
- signature.length !== 64 ||
232
- signature.toString('base64url') !== value.signature
233
- )
234
- return { ok: false }
235
- const key = createPublicKey({
236
- key: Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'), raw]),
237
- format: 'der',
238
- type: 'spki',
239
- })
240
- if (!verify(null, message(descriptor), key, signature)) return { ok: false }
241
- Object.freeze(descriptor.asset)
242
- Object.freeze(descriptor)
243
- verifiedDescriptors.set(descriptor, { key: encoded, signature: value.signature })
244
- return { ok: true, descriptor: descriptor as VerifiedRelease }
245
- } catch {
246
- return { ok: false }
247
- }
248
- }
249
- /** A verified descriptor remains valid only in the process that authenticated it. */
250
- export function isVerifiedRelease(value: unknown): value is VerifiedRelease {
251
- return typeof value === 'object' && value !== null && verifiedDescriptors.has(value)
252
- }
253
-
254
- /** Check that an authenticated descriptor used this exact application's current trust key. */
255
- export function isVerifiedReleaseForTrust(
256
- value: unknown,
257
- trust: ReleaseTrust
258
- ): value is VerifiedRelease {
259
- return (
260
- isVerifiedRelease(value) &&
261
- value.appId === trust.appId &&
262
- value.repository === trust.repository &&
263
- value.channel === trust.channel &&
264
- value.platform === trust.platform &&
265
- value.arch === trust.arch &&
266
- inFeed(value, trust.feed) &&
267
- verifiedDescriptors.get(value)?.key === trust.keys.get(value.keyId)
268
- )
269
- }
270
-
271
- /** Return the authenticated signed envelope for re-verification in another process. */
272
- export function exportVerifiedRelease(value: VerifiedRelease, trust: ReleaseTrust): SignedRelease {
273
- if (!isVerifiedReleaseForTrust(value, trust)) throw new Error('Untrusted release descriptor')
274
- return Object.freeze({ descriptor: value, signature: verifiedDescriptors.get(value)!.signature })
275
- }
276
-
277
- /** Check exact archive bytes after the descriptor has been authenticated. */
278
- export function verifyReleaseBytes(bytes: Uint8Array, descriptor: VerifiedRelease): boolean {
279
- if (
280
- !(bytes instanceof Uint8Array) ||
281
- !verifiedDescriptors.has(descriptor) ||
282
- bytes.byteLength !== descriptor.asset.size
283
- )
284
- return false
285
- const actual = createHash('sha256').update(bytes).digest()
286
- return timingSafeEqual(actual, Buffer.from(descriptor.asset.sha256, 'hex'))
287
- }
288
-
289
- /** Check a streamed archive without buffering the whole artifact. */
290
- export async function verifyReleaseStream(
291
- chunks: AsyncIterable<Uint8Array>,
292
- descriptor: VerifiedRelease
293
- ): Promise<boolean> {
294
- if (!verifiedDescriptors.has(descriptor)) return false
295
- const hash = createHash('sha256')
296
- let size = 0
297
- try {
298
- for await (const chunk of chunks) {
299
- if (!(chunk instanceof Uint8Array)) return false
300
- size += chunk.byteLength
301
- if (!Number.isSafeInteger(size) || size > descriptor.asset.size) return false
302
- hash.update(chunk)
303
- }
304
- return (
305
- size === descriptor.asset.size &&
306
- timingSafeEqual(hash.digest(), Buffer.from(descriptor.asset.sha256, 'hex'))
307
- )
308
- } catch {
309
- return false
310
- }
311
- }
@@ -1,32 +0,0 @@
1
- import type { Stats } from 'node:fs'
2
- import { constants } from 'node:fs'
3
- import { open, type FileHandle } from 'node:fs/promises'
4
-
5
- /** Whether two stats describe the same, unmodified file. */
6
- export function sameFile(left: Stats, right: Stats): boolean {
7
- return (
8
- left.dev === right.dev &&
9
- left.ino === right.ino &&
10
- left.size === right.size &&
11
- left.mtimeMs === right.mtimeMs
12
- )
13
- }
14
-
15
- /** Open the regular file `info` (from lstat) described, without following a link or
16
- * blocking on a FIFO, and only if it has not been swapped or modified since. */
17
- export async function openUnchangedFile(
18
- path: string,
19
- info: Stats,
20
- message: string
21
- ): Promise<{ file: FileHandle; before: Stats }> {
22
- const file = await open(
23
- path,
24
- constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
25
- )
26
- const before = await file.stat()
27
- if (!before.isFile() || !sameFile(before, info)) {
28
- await file.close()
29
- throw new Error(message)
30
- }
31
- return { file, before }
32
- }
@@ -1,107 +0,0 @@
1
- import { spawn, type ChildProcess } from 'node:child_process'
2
- import { copyFile, lstat, mkdir, realpath, rm, unlink, writeFile } from 'node:fs/promises'
3
- import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
4
- import { updateLauncherPath } from './update-launch'
5
- import { updateStagingFor } from './update-swap'
6
- import type { UpdateHelperRequest } from './update-helper'
7
-
8
- function exited(child: ChildProcess): boolean {
9
- return child.exitCode !== null || child.signalCode !== null
10
- }
11
-
12
- /** The Bun runtime inside an installed app tree, which the helper copy runs on. */
13
- function updateRuntimePath(platform: UpdateHelperRequest['platform'], target: string) {
14
- const launcher = updateLauncherPath(platform, target)
15
- return join(dirname(launcher), platform === 'windows-x64' ? 'bun.exe' : 'bun')
16
- }
17
-
18
- /**
19
- * Start the post-exit update helper for a staged update, then resolve once the
20
- * helper has verified this app's processes. The helper runs from copies of the
21
- * app's Bun runtime and bundled helper script inside the private staging
22
- * directory, because the install tree is about to move.
23
- *
24
- * Use it as the `arm` step of `scheduleUpdateShutdown`: quit only after it
25
- * resolves, and call `cancel()` if the quit is vetoed.
26
- */
27
- export async function armUpdateHelper(options: {
28
- target: string
29
- platform: UpdateHelperRequest['platform']
30
- version: string
31
- /** Absolute path of the bundled helper script shipped with the app. */
32
- helperScript: string
33
- /** Processes that must exit before the swap. Defaults to this process and its launcher parent. */
34
- processes?: UpdateHelperRequest['processes']
35
- processTimeoutMs?: number
36
- armTimeoutMs?: number
37
- env?: Record<string, string | undefined>
38
- }): Promise<{ cancel(): Promise<void> }> {
39
- const staging = updateStagingFor(options.target)
40
- if (!isAbsolute(options.helperScript) || resolve(options.helperScript) !== options.helperScript)
41
- throw new Error('Invalid update helper script')
42
- const info = await lstat(staging)
43
- if (!info.isDirectory() || info.isSymbolicLink() || (await realpath(staging)) !== staging)
44
- throw new Error('Invalid update staging directory')
45
- const helper = join(staging, 'helper')
46
- const runtime = join(helper, basename(updateRuntimePath(options.platform, options.target)))
47
- const script = join(helper, 'update-helper.js')
48
- const request: UpdateHelperRequest = {
49
- schema: 1,
50
- target: options.target,
51
- platform: options.platform,
52
- version: options.version,
53
- processes: options.processes ?? [
54
- { pid: process.pid, executable: process.execPath },
55
- ...(process.ppid > 1
56
- ? [{ pid: process.ppid, executable: updateLauncherPath(options.platform, options.target) }]
57
- : []),
58
- ],
59
- processTimeoutMs: options.processTimeoutMs ?? 30000,
60
- }
61
- const armed = join(staging, 'helper-armed')
62
- let child: ChildProcess | undefined
63
- async function reset() {
64
- if (child && !exited(child) && child.pid !== undefined) {
65
- try {
66
- process.kill(child.pid)
67
- } catch {
68
- /* Already gone. */
69
- }
70
- }
71
- for (const name of ['request.json', 'helper-armed'])
72
- await unlink(join(staging, name)).catch(() => undefined)
73
- await rm(helper, { recursive: true, force: true })
74
- }
75
- try {
76
- await mkdir(helper, { mode: 0o700 })
77
- await copyFile(updateRuntimePath(options.platform, options.target), runtime)
78
- await copyFile(options.helperScript, script)
79
- await writeFile(join(staging, 'request.json'), JSON.stringify(request) + '\n', {
80
- flag: 'wx',
81
- mode: 0o600,
82
- })
83
- const started = spawn(runtime, [script, '--staging', staging], {
84
- cwd: helper,
85
- detached: true,
86
- stdio: 'ignore',
87
- env: options.env ?? process.env,
88
- windowsHide: true,
89
- })
90
- child = started
91
- await new Promise<void>((done, reject) => {
92
- started.once('spawn', () => done())
93
- started.once('error', reject)
94
- })
95
- started.unref()
96
- const deadline = Date.now() + (options.armTimeoutMs ?? 15000)
97
- while (!(await lstat(armed).catch(() => undefined))) {
98
- if (exited(started)) throw new Error('Update helper exited before arming')
99
- if (Date.now() >= deadline) throw new Error('Update helper did not arm in time')
100
- await Bun.sleep(50)
101
- }
102
- } catch (error) {
103
- await reset()
104
- throw error
105
- }
106
- return { cancel: reset }
107
- }
@@ -1,86 +0,0 @@
1
- import { randomUUID } from 'node:crypto'
2
- import { lstat, open, realpath, rename, unlink } from 'node:fs/promises'
3
- import { isAbsolute, join, resolve } from 'node:path'
4
- import { openUnchangedFile, sameFile } from './stable-file'
5
- import { isUpdateChannel, type UpdateChannel } from './release-version'
6
-
7
- /** Persist one app-owned update channel; the caller must supply a private state directory. */
8
- export function createUpdateChannelStore(directory: string) {
9
- if (typeof directory !== 'string' || !isAbsolute(directory) || resolve(directory) !== directory)
10
- throw new Error('Invalid update channel directory')
11
- const path = join(directory, 'update-channel.json')
12
- let queue = Promise.resolve()
13
- async function assertDirectory() {
14
- const info = await lstat(directory)
15
- if (!info.isDirectory() || info.isSymbolicLink() || (await realpath(directory)) !== directory)
16
- throw new Error('Invalid update channel directory')
17
- }
18
- async function read(): Promise<UpdateChannel> {
19
- await assertDirectory()
20
- let info
21
- try {
22
- info = await lstat(path)
23
- } catch (error) {
24
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'stable'
25
- throw error
26
- }
27
- if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > 4096)
28
- throw new Error('Invalid update channel file')
29
- const { file, before } = await openUnchangedFile(path, info, 'Invalid update channel file')
30
- try {
31
- const bytes = Buffer.alloc(before.size + 1)
32
- const fileRead = await file.read(bytes, 0, bytes.length, 0)
33
- if (fileRead.bytesRead !== before.size) throw new Error('Invalid update channel file')
34
- const value: unknown = JSON.parse(bytes.subarray(0, fileRead.bytesRead).toString('utf8'))
35
- const after = await file.stat()
36
- if (
37
- !sameFile(before, after) ||
38
- typeof value !== 'object' ||
39
- value === null ||
40
- Array.isArray(value) ||
41
- Object.keys(value).length !== 1 ||
42
- !isUpdateChannel((value as { channel?: unknown }).channel)
43
- )
44
- throw new Error('Invalid update channel file')
45
- return (value as { channel: UpdateChannel }).channel
46
- } finally {
47
- await file.close()
48
- }
49
- }
50
- function ordered<T>(task: () => Promise<T>): Promise<T> {
51
- const result = queue.then(task)
52
- queue = result.then(
53
- () => {},
54
- () => {}
55
- )
56
- return result
57
- }
58
- return {
59
- read: () => ordered(read),
60
- save: (channel: UpdateChannel) =>
61
- ordered(async () => {
62
- if (!isUpdateChannel(channel)) throw new Error('Invalid update channel')
63
- await assertDirectory()
64
- const temporary = join(directory, `.update-channel-${randomUUID()}.tmp`)
65
- const file = await open(temporary, 'wx', 0o600)
66
- let moved = false
67
- try {
68
- await file.writeFile(JSON.stringify({ channel }) + '\n')
69
- await file.sync()
70
- await file.close()
71
- await rename(temporary, path)
72
- moved = true
73
- if ((await read()) !== channel) throw new Error('Update channel write did not persist')
74
- return channel
75
- } finally {
76
- await file.close().catch(() => {})
77
- if (!moved) await unlink(temporary).catch(() => {})
78
- }
79
- }),
80
- }
81
- }
82
- /** Shared UI uses pre-release; release descriptors use daily. */
83
- export function releaseChannelForUpdate(channel: UpdateChannel): 'stable' | 'daily' | 'dev' {
84
- if (!isUpdateChannel(channel)) throw new Error('Invalid update channel')
85
- return channel === 'pre-release' ? 'daily' : channel
86
- }