@adea-ai/app-framework 0.24.0 → 0.24.1

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 (128) hide show
  1. package/README.md +43 -1
  2. package/dist/framework-source.json +1 -1
  3. package/dist/release/framework-package-publish.js +4 -2
  4. package/dist/shell/app-shell.js +21 -33
  5. package/dist/shell/navigation-drawer.d.ts +12 -0
  6. package/dist/shell/navigation-drawer.js +42 -0
  7. package/package.json +13 -2
  8. package/src/shell/app-shell.tsx +29 -20
  9. package/src/shell/navigation-drawer.tsx +36 -0
  10. package/src/app/create-application.ts +0 -245
  11. package/src/app/service-registry.ts +0 -124
  12. package/src/ci/toolchain-identity.ts +0 -244
  13. package/src/cli/cef-helper-cli.ts +0 -21
  14. package/src/cli/cli-runner.ts +0 -29
  15. package/src/cli/create-application-cli.ts +0 -62
  16. package/src/cli/electrobun-shortcut-patch-cli.ts +0 -24
  17. package/src/cli/framework-update-cli.ts +0 -41
  18. package/src/cli/release-assets-plan-cli.ts +0 -14
  19. package/src/cli/release-cut-cli.ts +0 -41
  20. package/src/cli/release-descriptor-staging-cli.ts +0 -57
  21. package/src/cli/release-finalize-cli.ts +0 -34
  22. package/src/cli/release-promote-cli.ts +0 -31
  23. package/src/cli/release-publish-cli.ts +0 -46
  24. package/src/cli/release-sign-cli.ts +0 -24
  25. package/src/cli/release-step-cli.ts +0 -71
  26. package/src/cli/toolchain-identity-cli.ts +0 -12
  27. package/src/cli/update-helper-cli.ts +0 -12
  28. package/src/cli/windows-runtime-patch-cli.ts +0 -17
  29. package/src/desktop/application-command-client.ts +0 -43
  30. package/src/desktop/channel-handshake.ts +0 -136
  31. package/src/desktop/channel-proof.ts +0 -122
  32. package/src/desktop/desktop-client.ts +0 -303
  33. package/src/desktop/desktop-gateway.ts +0 -189
  34. package/src/desktop/desktop-host.ts +0 -335
  35. package/src/desktop/desktop-stream.ts +0 -324
  36. package/src/desktop/loopback-policy.ts +0 -41
  37. package/src/desktop/open-url-channel.ts +0 -79
  38. package/src/desktop/string-policy.ts +0 -9
  39. package/src/installer/archive-entry.ts +0 -32
  40. package/src/installer/command-artifact.ts +0 -307
  41. package/src/installer/command-qualification-command.ts +0 -75
  42. package/src/installer/hosted-runner.ts +0 -11
  43. package/src/installer/installed-payload.ts +0 -408
  44. package/src/installer/installer-ci-bootstrap.ts +0 -199
  45. package/src/installer/installer-ci-preflight.ts +0 -61
  46. package/src/installer/installer-ci-worker.ts +0 -105
  47. package/src/installer/installer-extraction.ts +0 -367
  48. package/src/installer/installer-fetch-guard.ts +0 -75
  49. package/src/installer/installer-identity.ts +0 -331
  50. package/src/installer/installer-layout.ts +0 -167
  51. package/src/installer/installer-observation.ts +0 -671
  52. package/src/installer/installer-process-cleanup.ts +0 -167
  53. package/src/installer/installer-qualification-command.ts +0 -81
  54. package/src/installer/installer-renderer-evidence.ts +0 -268
  55. package/src/installer/installer-upgrade-command.ts +0 -226
  56. package/src/installer/installer-worker-guard.ts +0 -112
  57. package/src/installer/native-executable.ts +0 -37
  58. package/src/installer/upgrade-asset-download.ts +0 -72
  59. package/src/installer/write-all.ts +0 -19
  60. package/src/native/app-bundle.ts +0 -86
  61. package/src/native/cef-helper.ts +0 -471
  62. package/src/native/desktop-build-hook.ts +0 -21
  63. package/src/native/electrobun-source-patch.ts +0 -107
  64. package/src/native/linux-cef-links.ts +0 -14
  65. package/src/native/native-secret-store.ts +0 -99
  66. package/src/native/native-utilities.ts +0 -166
  67. package/src/native/partitioned-window.ts +0 -62
  68. package/src/native/secure-window.ts +0 -115
  69. package/src/native/sidecar-services.ts +0 -71
  70. package/src/native/sidecar.ts +0 -387
  71. package/src/native/window-bootstrap.ts +0 -77
  72. package/src/native/windows-build-hook-internal.ts +0 -49
  73. package/src/native/windows-build-hook.ts +0 -12
  74. package/src/native/windows-runtime-patch-internal.ts +0 -48
  75. package/src/native/windows-runtime-patch.ts +0 -15
  76. package/src/release/feed-release-cut.ts +0 -110
  77. package/src/release/feed-state.ts +0 -135
  78. package/src/release/framework-package-publish.ts +0 -163
  79. package/src/release/framework-update.ts +0 -196
  80. package/src/release/github-cli.ts +0 -27
  81. package/src/release/github-release-assets.ts +0 -36
  82. package/src/release/github-release-cut.ts +0 -237
  83. package/src/release/github-release-lookup.ts +0 -39
  84. package/src/release/github-release-promotion.ts +0 -112
  85. package/src/release/github-release-provenance.ts +0 -65
  86. package/src/release/github-release-publisher.ts +0 -90
  87. package/src/release/github-release-qualification.ts +0 -144
  88. package/src/release/local-provenance.ts +0 -92
  89. package/src/release/local-release.ts +0 -525
  90. package/src/release/macos-dmg.ts +0 -113
  91. package/src/release/release-artifact.ts +0 -53
  92. package/src/release/release-assets-plan.ts +0 -118
  93. package/src/release/release-config.ts +0 -420
  94. package/src/release/release-cut-command.ts +0 -80
  95. package/src/release/release-cut.ts +0 -133
  96. package/src/release/release-descriptor-staging.ts +0 -242
  97. package/src/release/release-finalize.ts +0 -191
  98. package/src/release/release-promotion-command.ts +0 -36
  99. package/src/release/release-promotion.ts +0 -132
  100. package/src/release/release-publication.ts +0 -213
  101. package/src/release/release-publish-command.ts +0 -163
  102. package/src/release/release-qualification.ts +0 -397
  103. package/src/release/release-staging.ts +0 -87
  104. package/src/release/release-steps.ts +0 -173
  105. package/src/release/retained-release-build.ts +0 -217
  106. package/src/shell/application-menu-commands.ts +0 -6
  107. package/src/shell/application-menu.ts +0 -250
  108. package/src/updates/channel-update-manager.ts +0 -127
  109. package/src/updates/desktop-updater.ts +0 -440
  110. package/src/updates/release-feed.ts +0 -187
  111. package/src/updates/release-location.ts +0 -101
  112. package/src/updates/signed-release.ts +0 -311
  113. package/src/updates/stable-file.ts +0 -32
  114. package/src/updates/update-arm.ts +0 -107
  115. package/src/updates/update-channel-store.ts +0 -86
  116. package/src/updates/update-discovery.ts +0 -113
  117. package/src/updates/update-download.ts +0 -82
  118. package/src/updates/update-exclusive-rename.ts +0 -58
  119. package/src/updates/update-extraction.ts +0 -261
  120. package/src/updates/update-handoff-plan.ts +0 -75
  121. package/src/updates/update-helper.ts +0 -87
  122. package/src/updates/update-launch.ts +0 -33
  123. package/src/updates/update-manager.ts +0 -130
  124. package/src/updates/update-process-fence.ts +0 -125
  125. package/src/updates/update-resume.ts +0 -34
  126. package/src/updates/update-shutdown.ts +0 -37
  127. package/src/updates/update-swap-stage.ts +0 -75
  128. package/src/updates/update-swap.ts +0 -30
@@ -1,440 +0,0 @@
1
- /**
2
- * The desktop host's signed updater, the same for every framework app: the
3
- * channel the user picked, discovery of that channel's signed descriptor for
4
- * this platform, verified download, a staged swap beside the install and the
5
- * post-exit helper that swaps it in and relaunches. `resumeUpdate` reports and
6
- * cleans up after a helper on the next start.
7
- *
8
- * `registerUpdateServices` serves it as the `desktop_update_*` services that
9
- * the web client's update adapter drives.
10
- */
11
- import { mkdir, realpath, rm } from 'node:fs/promises'
12
- import { join, resolve } from 'node:path'
13
- import { ServiceError, type createServiceRegistry } from '../app/service-registry'
14
- import type { InstallerPlatform, InstallerRenderer } from '../installer/installer-layout'
15
- import { createChannelUpdateManager } from './channel-update-manager'
16
- import { isUpdateChannel, type UpdateChannel } from './release-version'
17
- import { feedUrl, parseReleaseFeed } from './release-feed'
18
- import type { ReleaseTrust } from './signed-release'
19
- import type { UpdateState } from './update-adapter'
20
- import { createUpdateChannelStore } from './update-channel-store'
21
- import { armUpdateHelper } from './update-arm'
22
- import { resumeUpdate } from './update-resume'
23
- import { scheduleUpdateShutdown } from './update-shutdown'
24
- import { stageUpdateSwap } from './update-swap-stage'
25
- import type { NativeUpdateState } from './update-state'
26
-
27
- /** Largest signed archive accepted for download. */
28
- const MAX_DOWNLOAD_BYTES = 1024 * 1024 * 1024
29
- /** Largest tree an archive may expand to. */
30
- const MAX_EXPANDED_BYTES = 4 * 1024 * 1024 * 1024
31
- /** Lets the install reply reach the window before the app quits. */
32
- const QUIT_DELAY_MS = 250
33
-
34
- export type DesktopUpdatePhase = UpdateState['phase']
35
- /** The snapshot every update service returns. */
36
- export type DesktopUpdateStatus = NativeUpdateState<DesktopUpdatePhase>
37
-
38
- type Manager = Pick<
39
- ReturnType<typeof createChannelUpdateManager>,
40
- 'status' | 'readChannel' | 'saveChannel' | 'check' | 'install'
41
- >
42
- type ManagerPhase = ReturnType<Manager['status']>['phase']
43
-
44
- /** The release identity an app's release-config.json declares. */
45
- export type DesktopRelease = {
46
- appId: string
47
- appName: string
48
- releaseSigningKeys: Readonly<Record<string, string>>
49
- /** Where releases are published: `{ base: 'https://adea.dev/releases/', app: 'adea' }`. */
50
- releaseFeed: Readonly<{ base: string; app: string }>
51
- sidecars?: readonly string[]
52
- }
53
-
54
- /** The release platform this host runs on, or null where framework apps ship no build. */
55
- export function updatePlatform(
56
- platform: string = process.platform,
57
- arch: string = process.arch
58
- ): InstallerPlatform | null {
59
- if (platform === 'darwin' && arch === 'arm64') return 'macos-arm64'
60
- if (platform === 'win32' && arch === 'x64') return 'windows-x64'
61
- if (platform === 'linux' && arch === 'x64') return 'linux-x64'
62
- return null
63
- }
64
-
65
- /**
66
- * The installed app tree the swap replaces: the `.app` bundle on macOS, the
67
- * app directory elsewhere. The host entry runs from `Resources/app/bun`.
68
- */
69
- export function installTarget(entryDirectory: string, platform: InstallerPlatform): string {
70
- return resolve(
71
- entryDirectory,
72
- ...(platform === 'macos-arm64' ? ['..', '..', '..', '..'] : ['..', '..', '..'])
73
- )
74
- }
75
-
76
- /** Each channel's signed descriptor for `platform`, as the release workflows publish them. */
77
- export function discoveryNames(platform: InstallerPlatform): Record<UpdateChannel, string> {
78
- return {
79
- stable: `stable-${platform}.json`,
80
- 'pre-release': `daily-${platform}.json`,
81
- dev: `dev-${platform}.json`,
82
- }
83
- }
84
-
85
- /**
86
- * What a descriptor must match: this app, repository and platform, signed by a
87
- * configured key. Null until a key is configured, so such a build reports
88
- * updates as unavailable instead of failing.
89
- */
90
- export function updateTrust(
91
- platform: InstallerPlatform,
92
- identity: {
93
- appId: string
94
- repository: string
95
- feed: string
96
- keys: Readonly<Record<string, string>>
97
- }
98
- ): Omit<ReleaseTrust, 'channel'> | null {
99
- const entries = Object.entries(identity.keys)
100
- if (entries.length === 0) return null
101
- const [os, arch] = {
102
- 'macos-arm64': ['darwin', 'arm64'],
103
- 'windows-x64': ['win32', 'x64'],
104
- 'linux-x64': ['linux', 'x64'],
105
- }[platform] as [ReleaseTrust['platform'], ReleaseTrust['arch']]
106
- return {
107
- appId: identity.appId,
108
- repository: identity.repository,
109
- platform: os,
110
- arch,
111
- feed: identity.feed,
112
- keys: new Map(entries),
113
- }
114
- }
115
-
116
- const PHASES: Readonly<Record<ManagerPhase, DesktopUpdatePhase>> = {
117
- idle: 'idle',
118
- checking: 'checking',
119
- current: 'current',
120
- available: 'available',
121
- downloading: 'downloading',
122
- staging: 'installing',
123
- staged: 'installed',
124
- failed: 'failed',
125
- }
126
-
127
- export type UpdateInstallRequest = { expectedVersion: string; approved: boolean; restart?: boolean }
128
-
129
- export type UpdaterOptions = {
130
- appName: string
131
- repository: string
132
- currentVersion: string
133
- changelog?: string
134
- /** Null where updates cannot apply: an unsupported platform or no trusted key. */
135
- manager: Manager | null
136
- /** A status read while idle starts the one check, so a badge needs no second checker. */
137
- checkWhenIdle?: boolean
138
- /** Hand off to the post-exit helper and quit, after a staged install the user asked to restart. */
139
- restart(version: string): Promise<void>
140
- /** Aborts the download in flight. */
141
- abortDownload?(): void
142
- }
143
-
144
- /** The update commands over a framework channel update manager. */
145
- export function createUpdater(options: UpdaterOptions) {
146
- const { manager, currentVersion } = options
147
- const releases = `https://github.com/${options.repository}/releases`
148
- let cancelRequested = false
149
- let lastTag: string | null = null
150
- // One check at a time.
151
- let inFlight: Promise<DesktopUpdateStatus> | null = null
152
- const snapshot = (): DesktopUpdateStatus => {
153
- const state = manager?.status()
154
- const available = state?.availableVersion ?? null
155
- if (available) lastTag = `v${available}`
156
- // An aborted download fails in the manager; report it as cancelled.
157
- const phase: DesktopUpdatePhase = !state
158
- ? 'unavailable'
159
- : cancelRequested && state.phase === 'downloading'
160
- ? 'cancelling'
161
- : cancelRequested && state.phase === 'failed'
162
- ? 'cancelled'
163
- : PHASES[state.phase]
164
- return {
165
- current_version: currentVersion,
166
- available_version: available,
167
- release_date: null,
168
- release_notes: null,
169
- changelog: options.changelog ?? '',
170
- github_url: lastTag ? `${releases}/tag/${lastTag}` : releases,
171
- phase,
172
- downloaded_bytes: 0,
173
- total_bytes: null,
174
- error: phase === 'cancelled' ? null : (state?.error ?? null),
175
- restart_required: state?.phase === 'staged',
176
- }
177
- }
178
- const active = (): Manager => {
179
- if (!manager)
180
- throw new ServiceError(
181
- 'unsupported',
182
- `Signed updates are not available for this ${options.appName} build`
183
- )
184
- return manager
185
- }
186
- const check = async (): Promise<DesktopUpdateStatus> => {
187
- if (!manager) return snapshot()
188
- cancelRequested = false
189
- inFlight ??= manager
190
- .check()
191
- .then(snapshot)
192
- .finally(() => {
193
- inFlight = null
194
- })
195
- return inFlight
196
- }
197
- return {
198
- async status(): Promise<DesktopUpdateStatus> {
199
- if (options.checkWhenIdle && manager?.status().phase === 'idle') return check()
200
- return inFlight ?? snapshot()
201
- },
202
- check,
203
- async channel(): Promise<UpdateChannel> {
204
- return manager ? manager.readChannel() : 'stable'
205
- },
206
- async saveChannel(channel: UpdateChannel): Promise<UpdateChannel> {
207
- return active().saveChannel(channel)
208
- },
209
- async install(request: UpdateInstallRequest): Promise<DesktopUpdateStatus> {
210
- const updates = active()
211
- if (!request.approved)
212
- throw new ServiceError('command_failed', 'update installation requires explicit approval')
213
- cancelRequested = false
214
- const state = await updates.install({
215
- approved: true,
216
- expectedVersion: request.expectedVersion,
217
- })
218
- if (state.phase === 'staged' && request.restart !== false && state.availableVersion)
219
- await options.restart(state.availableVersion)
220
- return snapshot()
221
- },
222
- async cancel(): Promise<DesktopUpdateStatus> {
223
- // Only a download can stop; staging and a staged update finish.
224
- if (manager?.status().phase === 'downloading' && options.abortDownload) {
225
- cancelRequested = true
226
- options.abortDownload()
227
- }
228
- return snapshot()
229
- },
230
- }
231
- }
232
-
233
- export type DesktopUpdater = ReturnType<typeof createUpdater>
234
-
235
- /**
236
- * The updater for the packaged app at `entryDirectory`. Clears downloads left
237
- * by an earlier run and reports what an earlier helper did.
238
- */
239
- export async function createDesktopUpdater(options: {
240
- release: DesktopRelease
241
- repository: string
242
- renderer: InstallerRenderer
243
- entryDirectory: string
244
- dataDirectory: string
245
- /** Where the chosen channel is kept; the data directory unless given. */
246
- stateDirectory?: string
247
- currentVersion: string
248
- changelog?: string
249
- /** The shipped update helper, relative to `Resources/app`. */
250
- helperScript: string
251
- checkWhenIdle?: boolean
252
- quit(): void
253
- log(line: string): void
254
- }): Promise<DesktopUpdater> {
255
- const { release } = options
256
- const platform = updatePlatform()
257
- const trust =
258
- platform &&
259
- updateTrust(platform, {
260
- appId: release.appId,
261
- repository: options.repository,
262
- feed: feedUrl(parseReleaseFeed(release.releaseFeed)),
263
- keys: release.releaseSigningKeys,
264
- })
265
- let controller = new AbortController()
266
- const updater = {
267
- appName: release.appName,
268
- repository: options.repository,
269
- currentVersion: options.currentVersion,
270
- changelog: options.changelog,
271
- checkWhenIdle: options.checkWhenIdle,
272
- abortDownload() {
273
- controller.abort()
274
- controller = new AbortController()
275
- },
276
- }
277
- if (!platform || !trust)
278
- return createUpdater({ ...updater, manager: null, restart: async () => {} })
279
- const target = installTarget(options.entryDirectory, platform)
280
- const resumed = await resumeUpdate({ target }).catch((error: unknown) => {
281
- options.log(`update resume failed: ${String(error)}`)
282
- return null
283
- })
284
- if (resumed?.status === 'updated') options.log(`updated to ${release.appName} ${resumed.version}`)
285
- const state = options.stateDirectory ?? options.dataDirectory
286
- await mkdir(state, { recursive: true, mode: 0o700 })
287
- const downloads = join(options.dataDirectory, 'updates')
288
- await rm(downloads, { recursive: true, force: true })
289
- await mkdir(downloads, { recursive: true, mode: 0o700 })
290
- const manager = createChannelUpdateManager({
291
- store: createUpdateChannelStore(await realpath(state)),
292
- trust,
293
- discoveryNames: discoveryNames(platform),
294
- currentVersion: options.currentVersion,
295
- directory: await realpath(downloads),
296
- maxBytes: MAX_DOWNLOAD_BYTES,
297
- fetch: (input, init) =>
298
- fetch(input, {
299
- ...init,
300
- signal: init?.signal
301
- ? AbortSignal.any([init.signal, controller.signal])
302
- : controller.signal,
303
- }),
304
- async stage({ descriptor, path, directory }) {
305
- try {
306
- await stageUpdateSwap({
307
- descriptor,
308
- trust: { ...trust, channel: descriptor.channel },
309
- currentVersion: options.currentVersion,
310
- approved: true,
311
- approvedVersion: descriptor.version,
312
- target,
313
- appName: release.appName,
314
- platform,
315
- renderer: options.renderer,
316
- archive: path,
317
- maxCompressedBytes: MAX_DOWNLOAD_BYTES,
318
- maxExpandedBytes: MAX_EXPANDED_BYTES,
319
- ...(release.sidecars ? { sidecars: release.sidecars } : {}),
320
- })
321
- } finally {
322
- await rm(directory, { recursive: true, force: true })
323
- }
324
- },
325
- })
326
- return createUpdater({
327
- ...updater,
328
- manager,
329
- async restart(version) {
330
- await scheduleUpdateShutdown({
331
- reserve: () => ({}),
332
- cancelReservation: () => {},
333
- arm: () =>
334
- armUpdateHelper({
335
- target,
336
- platform,
337
- version,
338
- helperScript: join(options.entryDirectory, '..', options.helperScript),
339
- }),
340
- quit: () => {
341
- setTimeout(options.quit, QUIT_DELAY_MS)
342
- return true
343
- },
344
- })
345
- },
346
- })
347
- }
348
-
349
- type Services<Principal> = ReturnType<typeof createServiceRegistry<Principal>>
350
-
351
- function record(value: unknown, keys: readonly string[]): Record<string, unknown> {
352
- if (
353
- typeof value !== 'object' ||
354
- value === null ||
355
- Array.isArray(value) ||
356
- Object.keys(value).some((key) => !keys.includes(key))
357
- )
358
- throw new Error('Invalid input')
359
- return value as Record<string, unknown>
360
- }
361
-
362
- function parseNone(value: unknown): null {
363
- if (value !== undefined && value !== null) record(value, [])
364
- return null
365
- }
366
-
367
- /** The `desktop_update_channel_save` argument. */
368
- export function parseUpdateChannel(value: unknown): UpdateChannel {
369
- const { channel } = record(value, ['channel'])
370
- if (!isUpdateChannel(channel)) throw new Error('Invalid input')
371
- return channel
372
- }
373
-
374
- /** The `desktop_update_install` argument. */
375
- export function parseUpdateInstall(value: unknown): UpdateInstallRequest {
376
- const { expectedVersion, approved, restart } = record(value, [
377
- 'expectedVersion',
378
- 'approved',
379
- 'restart',
380
- ])
381
- if (
382
- typeof expectedVersion !== 'string' ||
383
- expectedVersion.length > 64 ||
384
- typeof approved !== 'boolean' ||
385
- (restart !== undefined && typeof restart !== 'boolean')
386
- )
387
- throw new Error('Invalid input')
388
- return { expectedVersion, approved, ...(restart === undefined ? {} : { restart }) }
389
- }
390
-
391
- /** Pass a service error through; give any other failure the update error code. */
392
- function failure(error: unknown): never {
393
- if (error instanceof ServiceError) throw error
394
- throw new ServiceError('update_failed', error instanceof Error ? error.message : String(error))
395
- }
396
-
397
- /** Register the `desktop_update_*` services the web client's update adapter calls. */
398
- export function registerUpdateServices<Principal>(options: {
399
- services: Services<Principal>
400
- updater: DesktopUpdater
401
- authorize(principal: Principal): boolean
402
- }): () => void {
403
- const { services, updater } = options
404
- const authorize = (principal: Principal) => options.authorize(principal)
405
- const unregister = [
406
- services.register('desktop_update_status', {
407
- parse: parseNone,
408
- authorize,
409
- run: () => updater.status().catch(failure),
410
- }),
411
- services.register('desktop_update_channel', {
412
- parse: parseNone,
413
- authorize,
414
- run: () => updater.channel().catch(failure),
415
- }),
416
- services.register('desktop_update_channel_save', {
417
- parse: parseUpdateChannel,
418
- authorize,
419
- run: (_principal, channel) => updater.saveChannel(channel).catch(failure),
420
- }),
421
- services.register('desktop_update_check', {
422
- parse: parseNone,
423
- authorize,
424
- run: () => updater.check().catch(failure),
425
- }),
426
- services.register('desktop_update_install', {
427
- parse: parseUpdateInstall,
428
- authorize,
429
- run: (_principal, request) => updater.install(request).catch(failure),
430
- }),
431
- services.register('desktop_update_cancel', {
432
- parse: parseNone,
433
- authorize,
434
- run: () => updater.cancel(),
435
- }),
436
- ]
437
- return () => {
438
- for (const remove of unregister) remove()
439
- }
440
- }
@@ -1,187 +0,0 @@
1
- /**
2
- * The HTTPS release feed an app publishes to and updates from (Cloudflare R2 behind
3
- * adea.dev). Object keys are relative to the feed base, one prefix per app:
4
- * `<app>/<tag>/<asset>` immutable assets and signed descriptors, `<app>/<tag>/release.json`
5
- * the release's asset inventory, `<app>/index.json` the bounded release ledger and
6
- * `<app>/channels/<channel>.json` a copy of the newest release.json on that channel.
7
- */
8
- export type ReleaseFeed = Readonly<{ base: string; app: string }>
9
- export type FeedChannel = 'dev' | 'daily' | 'stable'
10
- type FeedAsset = Readonly<{ name: string; size: number; sha256: string }>
11
- /** `<app>/<tag>/release.json` and the channel pointers that copy it; unsigned. */
12
- export type FeedRelease = Readonly<{
13
- tag: string
14
- channel: FeedChannel
15
- publishedAt: string
16
- assets: readonly FeedAsset[]
17
- }>
18
- export type LedgerEntry = Readonly<{
19
- tag: string
20
- kind: FeedChannel
21
- version: string
22
- sourceSha: string
23
- publishedAt: string
24
- /** When a daily became stable; present exactly on stable entries. */
25
- promotedAt?: string
26
- }>
27
- /** `<app>/index.json`: newest first. */
28
- export type ReleaseLedger = Readonly<{ schema: 1; app: string; releases: readonly LedgerEntry[] }>
29
-
30
- /** Ledger entries kept; the oldest fall off a full ledger. */
31
- export const MAX_LEDGER_RELEASES = 500
32
- const MAX_RELEASE_ASSETS = 256
33
-
34
- const record = (value: unknown): value is Record<string, unknown> =>
35
- typeof value === 'object' && value !== null && !Array.isArray(value)
36
- const exactKeys = (value: Record<string, unknown>, keys: readonly string[]) =>
37
- Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key))
38
- const segment = /^[a-z0-9][a-z0-9-]{0,62}$/
39
- const tagPattern = /^v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.[1-9]\d*)?$/
40
- const timestamp = (value: unknown): value is string =>
41
- typeof value === 'string' &&
42
- /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value) &&
43
- Number.isFinite(Date.parse(value)) &&
44
- new Date(value).toISOString().replace('.000Z', 'Z') === value.replace('.000Z', 'Z')
45
- /** A release tag in the feed: `vX.Y.Z` or `vX.Y.Z-dev.N`. */
46
- export const isFeedTag = (value: unknown): value is string =>
47
- typeof value === 'string' && value.length <= 65 && tagPattern.test(value)
48
- export const isFeedAssetName = (value: unknown): value is string =>
49
- typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(value)
50
-
51
- /** Validate a feed: an https origin and path prefix ending in `/`, with no credentials,
52
- * port, query or fragment, and an app slug. */
53
- export function parseReleaseFeed(value: unknown): ReleaseFeed {
54
- if (!record(value) || !exactKeys(value, ['base', 'app']) || typeof value.base !== 'string')
55
- throw new Error('Invalid release feed')
56
- let url: URL
57
- try {
58
- url = new URL(value.base)
59
- } catch {
60
- throw new Error('Invalid release feed')
61
- }
62
- const parts = url.pathname.split('/').slice(1, -1)
63
- if (
64
- value.base.length > 200 ||
65
- url.href !== value.base ||
66
- url.protocol !== 'https:' ||
67
- url.username ||
68
- url.password ||
69
- url.port ||
70
- url.search ||
71
- url.hash ||
72
- !url.pathname.endsWith('/') ||
73
- !parts.every((part) => segment.test(part)) ||
74
- typeof value.app !== 'string' ||
75
- !/^[a-z][a-z0-9-]{0,63}$/.test(value.app)
76
- )
77
- throw new Error('Invalid release feed')
78
- return { base: value.base, app: value.app }
79
- }
80
-
81
- /** The URL every key of this app's feed lives under, ending in `/`. */
82
- export const feedUrl = (feed: ReleaseFeed) => `${feed.base}${feed.app}/`
83
- /** The bucket key of one release asset. */
84
- export function feedAssetKey(feed: ReleaseFeed, tag: string, name: string): string {
85
- if (!isFeedTag(tag) || !isFeedAssetName(name)) throw new Error('Invalid release asset')
86
- return `${feed.app}/${tag}/${name}`
87
- }
88
- export const feedReleaseKey = (feed: ReleaseFeed, tag: string) =>
89
- feedAssetKey(feed, tag, 'release.json')
90
- export const feedIndexKey = (feed: ReleaseFeed) => `${feed.app}/index.json`
91
- export const feedChannelKey = (feed: ReleaseFeed, channel: FeedChannel) =>
92
- `${feed.app}/channels/${channel}.json`
93
-
94
- const channelOf = (tag: string): 'dev' | 'daily' => (tag.includes('-dev.') ? 'dev' : 'daily')
95
-
96
- /** Validate a release.json or channel pointer: a tag of its channel and a bounded,
97
- * unique asset inventory. */
98
- export function parseFeedRelease(value: unknown): FeedRelease {
99
- if (
100
- !record(value) ||
101
- !exactKeys(value, ['tag', 'channel', 'publishedAt', 'assets']) ||
102
- !isFeedTag(value.tag) ||
103
- !['dev', 'daily', 'stable'].includes(String(value.channel)) ||
104
- (value.channel === 'dev') !== (channelOf(value.tag) === 'dev') ||
105
- !timestamp(value.publishedAt) ||
106
- !Array.isArray(value.assets) ||
107
- value.assets.length < 1 ||
108
- value.assets.length > MAX_RELEASE_ASSETS
109
- )
110
- throw new Error('Invalid feed release')
111
- const names = new Set<string>()
112
- const assets = value.assets.map((asset: unknown): FeedAsset => {
113
- if (
114
- !record(asset) ||
115
- !exactKeys(asset, ['name', 'size', 'sha256']) ||
116
- !isFeedAssetName(asset.name) ||
117
- asset.name === 'release.json' ||
118
- names.has(asset.name) ||
119
- !Number.isSafeInteger(asset.size) ||
120
- Number(asset.size) < 1 ||
121
- typeof asset.sha256 !== 'string' ||
122
- !/^[a-f0-9]{64}$/.test(asset.sha256)
123
- )
124
- throw new Error('Invalid feed release asset')
125
- names.add(asset.name)
126
- return { name: asset.name, size: Number(asset.size), sha256: asset.sha256 }
127
- })
128
- return {
129
- tag: value.tag,
130
- channel: value.channel as FeedChannel,
131
- publishedAt: value.publishedAt,
132
- assets,
133
- }
134
- }
135
-
136
- /** Validate the ledger: this app, at most MAX_LEDGER_RELEASES unique tags, newest first,
137
- * each kind matching its tag and only stable entries carrying a promotion time. */
138
- export function parseReleaseLedger(value: unknown, app: string): ReleaseLedger {
139
- if (
140
- !record(value) ||
141
- !exactKeys(value, ['schema', 'app', 'releases']) ||
142
- value.schema !== 1 ||
143
- value.app !== app ||
144
- !Array.isArray(value.releases) ||
145
- value.releases.length > MAX_LEDGER_RELEASES
146
- )
147
- throw new Error('Invalid release ledger')
148
- const tags = new Set<string>()
149
- let previous = Infinity
150
- const releases = value.releases.map((entry: unknown): LedgerEntry => {
151
- const stable = record(entry) && entry.kind === 'stable'
152
- if (
153
- !record(entry) ||
154
- !exactKeys(entry, [
155
- 'tag',
156
- 'kind',
157
- 'version',
158
- 'sourceSha',
159
- 'publishedAt',
160
- ...(stable ? ['promotedAt'] : []),
161
- ]) ||
162
- !isFeedTag(entry.tag) ||
163
- tags.has(entry.tag) ||
164
- entry.version !== entry.tag.slice(1) ||
165
- !(stable ? channelOf(entry.tag) === 'daily' : entry.kind === channelOf(entry.tag)) ||
166
- typeof entry.sourceSha !== 'string' ||
167
- !/^[a-f0-9]{40}$/.test(entry.sourceSha) ||
168
- !timestamp(entry.publishedAt) ||
169
- Date.parse(entry.publishedAt) > previous ||
170
- (stable &&
171
- (!timestamp(entry.promotedAt) ||
172
- Date.parse(entry.promotedAt) < Date.parse(entry.publishedAt)))
173
- )
174
- throw new Error('Invalid release ledger entry')
175
- tags.add(entry.tag)
176
- previous = Date.parse(entry.publishedAt)
177
- return {
178
- tag: entry.tag,
179
- kind: entry.kind as FeedChannel,
180
- version: entry.version,
181
- sourceSha: entry.sourceSha,
182
- publishedAt: entry.publishedAt,
183
- ...(stable ? { promotedAt: entry.promotedAt as string } : {}),
184
- }
185
- })
186
- return { schema: 1, app, releases }
187
- }