@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
package/README.md CHANGED
@@ -56,6 +56,16 @@ promotion; inputs must come from the authenticated release provider and the
56
56
  application's trusted release configuration. These functions do not fetch or
57
57
  verify release signatures, create artifacts, publish releases, or promote them.
58
58
 
59
+ Installer and command qualification (`adea-release-step qualify`) runs on a
60
+ disposable runner: a GitHub-hosted Actions runner in the release-assets
61
+ workflow, or a GitLab CI job in the tag pipeline for the release, whose
62
+ executor creates a fresh container or VM per job and which sets
63
+ `FRAMEWORK_DISPOSABLE_RUNNER=true`. Never set that variable on a shell
64
+ executor. On GitLab the job needs a clean, full-history checkout of the tagged
65
+ commit with `origin/main` fetched, a per-job absolute `TMPDIR`, and payloads
66
+ downloaded outside the checkout; receipts name the tagged commit as source and
67
+ workflow commit and `CI_PIPELINE_ID` as the run, attempt 1.
68
+
59
69
  ## Package entry points
60
70
 
61
71
  Import a subpath; the package has no root export. Entries marked _solid_ also
@@ -65,16 +75,16 @@ TypeScript source alone, and the rest resolve to `dist`. The package ships only
65
75
  the source those entries reach, plus the Electrobun patches in `src/native`; a
66
76
  test checks the file list against the exports.
67
77
 
68
- | Area | Subpaths (`@adea-ai/app-framework/<subpath>`) |
69
- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
70
- | Application and shell | `application`, `app-shell`, `app-utilities`, `app-settings`, `app-help`, `app-about`, `update-surface` (all _solid_), `service-registry`, `application-menu`, `application-command-client` |
71
- | Appearance | `appearance-host`, `appearance-preferences`, `appearance-surface`, `custom-theme-library`, `window-surface` (all _solid_) |
72
- | Desktop host | `desktop-host`, `desktop-gateway`, `desktop-client`, `desktop-stream`, `channel-handshake`, `channel-proof`, `loopback-policy`, `open-url-channel`, `client-asset-manifest`, `client-assets` (source only) |
73
- | Native windows and OS | `renderer-profile`, `secure-window`, `partitioned-window`, `window-options` (source only), `native-utilities`, `native-secret-store`, `app-bundle`, `sidecar`, `sidecar-services`, `desktop-build-hook`, `windows-runtime-patch` |
74
- | Updates | `desktop-updater`, `update-manager`, `update-launch-gate`, `update-inherited-launch-lease`, `packaged-launch-admission`, `packaged-release-config`, `packaged-update-startup`, `update-resume`, `channel-update-manager`, `update-channel-store`, `update-discovery`, `update-download`, `update-extraction`, `signed-release`, `update-adapter` (_solid_), `update-state` and `release-version` (source only), `update-helper.js` (bundled helper) |
75
- | Release tooling | `release-config`, `release-cut`, `release-steps`, `release-staging`, `release-artifact`, `release-assets-plan`, `release-descriptor-staging`, `release-publication`, `release-publish-command`, `release-promotion`, `retained-release-build`, `github-release-publisher`, `github-release-qualification`, `github-release-promotion`, `macos-dmg` |
76
- | Installer qualification | `installer-layout`, `installer-identity`, `installer-extraction`, `installed-payload`, `installer-observation`, `installer-qualification-command`, `installer-renderer-evidence` |
77
- | CI | `toolchain-identity` |
78
+ | Area | Subpaths (`@adea-ai/app-framework/<subpath>`) |
79
+ | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
80
+ | Application and shell | `application`, `app-shell`, `app-utilities`, `app-settings`, `app-help`, `app-about`, `update-surface` (all _solid_), `service-registry`, `application-menu`, `application-command-client` |
81
+ | Appearance | `appearance-host`, `appearance-preferences`, `appearance-surface`, `custom-theme-library`, `window-surface` (all _solid_) |
82
+ | Desktop host | `desktop-host`, `desktop-gateway`, `desktop-client`, `desktop-stream`, `channel-handshake`, `channel-proof`, `loopback-policy`, `open-url-channel`, `client-asset-manifest`, `client-assets` (source only) |
83
+ | Native windows and OS | `renderer-profile`, `secure-window`, `partitioned-window`, `window-options` (source only), `native-utilities`, `native-secret-store`, `app-bundle`, `sidecar`, `sidecar-services`, `desktop-build-hook`, `windows-runtime-patch` |
84
+ | Updates | `desktop-updater`, `update-manager`, `update-inherited-launch-lease`, `packaged-launch-admission`, `packaged-update-startup`, `update-resume`, `channel-update-manager`, `update-channel-store`, `update-discovery`, `update-download`, `update-extraction`, `signed-release`, `update-adapter` (_solid_), `update-state` and `release-version` (source only), `update-helper.js` (bundled helper) |
85
+ | Release tooling | `release-config`, `release-cut`, `release-steps`, `release-staging`, `release-artifact`, `release-assets-plan`, `release-descriptor-staging`, `release-publication`, `release-publish-command`, `release-promotion`, `retained-release-build`, `github-release-publisher`, `github-release-qualification`, `github-release-promotion`, `macos-dmg` |
86
+ | Installer qualification | `installer-layout`, `installer-identity`, `installer-extraction`, `installed-payload`, `installer-observation`, `installer-qualification-command`, `installer-renderer-evidence` |
87
+ | CI | `toolchain-identity` |
78
88
 
79
89
  Commands (package `bin` entries):
80
90
 
@@ -364,7 +374,12 @@ so side effects may already have occurred when the call rejects. Set `portFile`
364
374
  app-owned data directory to preserve the loopback origin and its browser
365
375
  preferences across restarts. First publication requires hard-link support in that
366
376
  directory; unsupported filesystems fail closed. A malformed record or occupied
367
- port also fails closed; the host never silently selects a new origin. Electrobun 2.0.5 configures CEF
377
+ port also fails closed; the host never silently selects a new origin. App-owned
378
+ `routes` serve same-origin requests after the host refuses any non-loopback
379
+ Origin; a route that declares `websocket` handlers may accept a socket by calling
380
+ `context.upgrade(data)` from `handle`. Client documents get
381
+ `frame-src 'none'` unless `frameSources` names exact https or loopback origins
382
+ (at most 8) the app may embed. Electrobun 2.0.5 configures CEF
368
383
  with Chromium's operating-system sandbox disabled; the bridge sandbox and
369
384
  web-security flags do not provide that OS process isolation. A packaged native
370
385
  probe exercises both
@@ -1132,10 +1147,13 @@ ordering does not depend on watcher polling. Schema-1 and schema-2 requests
1132
1147
  keep their prior helper transition behavior and do not participate in this
1133
1148
  launch-gate protocol.
1134
1149
 
1135
- This helper integration remains WIP. Generated bootstrap consumes a
1136
- launcher-supplied launch lease and runs packaged trust validation when that
1137
- descriptor is present, but stock generated packages do not enable the opt-in
1138
- native launcher. The opt-in launcher rejects an existing update gate before
1150
+ This helper integration remains WIP. Generated bootstrap creates the updater
1151
+ on every packaged launch. With a launcher-supplied launch lease it also leases
1152
+ retained asset generations and pauses startup if recovery fails; without one
1153
+ (stock packaging and Windows) `preparePackagedUpdateStartup({ admission:
1154
+ 'unmanaged' })` reconciles under the install lock alone and returns
1155
+ `unavailable`, which the app reports and starts without updates, instead of
1156
+ throwing. Stock generated packages do not enable the opt-in native launcher. The opt-in launcher rejects an existing update gate before
1139
1157
  starting the worker, so a gate left by a crashed helper still blocks a managed
1140
1158
  launch until it is recovered. Generated startup without a launcher lease (stock
1141
1159
  packaging) dispatches that recovery before launch admission:
@@ -1,5 +1,6 @@
1
+ import { errorCode } from "./value-guards.js";
1
2
  import { createRendererProfile } from "../native/renderer-profile.js";
2
- import { renameExclusive } from "../native/exclusive-rename.js";
3
+ import { renameExclusive } from "../native/native-rename.js";
3
4
  import { containsAsciiControl } from "../desktop/string-policy.js";
4
5
  import { assertPortableAppName } from "../installer/installer-layout.js";
5
6
  import { isPrivateGroup, readAccountDatabase } from "./private-group.js";
@@ -11,7 +12,7 @@ async function exists(path) {
11
12
  await lstat(path);
12
13
  return true;
13
14
  } catch (error) {
14
- if (error.code === "ENOENT") return false;
15
+ if (errorCode(error) === "ENOENT") return false;
15
16
  throw error;
16
17
  }
17
18
  }
@@ -42,7 +43,7 @@ async function removeOwnedStaging(staging, identity, remove) {
42
43
  try {
43
44
  info = await lstat(staging);
44
45
  } catch (error) {
45
- if (error.code === "ENOENT") return;
46
+ if (errorCode(error) === "ENOENT") return;
46
47
  throw error;
47
48
  }
48
49
  if (!info.isDirectory() || info.dev !== identity.dev || info.ino !== identity.ino) throw new Error("Application staging directory was replaced; it was not removed");
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Run async tasks one at a time in call order. A rejected task rejects only its
3
+ * own caller; later tasks still run.
4
+ */
5
+ export declare function createSerialQueue(): <T>(task: () => Promise<T>) => Promise<T>;
@@ -0,0 +1,14 @@
1
+ // src/app/serial-queue.ts
2
+ /**
3
+ * Run async tasks one at a time in call order. A rejected task rejects only its
4
+ * own caller; later tasks still run.
5
+ */
6
+ function createSerialQueue() {
7
+ let tail = Promise.resolve();
8
+ return (task) => {
9
+ const result = tail.then(task);
10
+ tail = result.then(() => {}, () => {});
11
+ return result;
12
+ };
13
+ }
14
+ export { createSerialQueue };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Shape checks every trust boundary in the framework shares. Keep each one here so
3
+ * a validator cannot drift between the updater, installer and release paths.
4
+ */
5
+ /** A plain JSON-style object: not null and not an array. */
6
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
7
+ /** RFC 4122 UUID text (versions 1-8), as `crypto.randomUUID()` produces; case-insensitive. */
8
+ export declare const UUID_SOURCE: string;
9
+ export declare function isUuid(value: unknown): boolean;
10
+ /** A full 40-character lowercase git commit or tree SHA. */
11
+ export declare function isGitSha(value: unknown): boolean;
12
+ /** A lowercase hex SHA-256 digest. */
13
+ export declare function isSha256Hex(value: unknown): boolean;
14
+ /** The Node.js `code` of a thrown system error (`ENOENT`, `EEXIST`, ...), if it has one. */
15
+ export declare function errorCode(error: unknown): string | undefined;
@@ -0,0 +1,29 @@
1
+ // src/app/value-guards.ts
2
+ /**
3
+ * Shape checks every trust boundary in the framework shares. Keep each one here so
4
+ * a validator cannot drift between the updater, installer and release paths.
5
+ */
6
+ /** A plain JSON-style object: not null and not an array. */
7
+ function isRecord(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9
+ }
10
+ /** RFC 4122 UUID text (versions 1-8), as `crypto.randomUUID()` produces; case-insensitive. */
11
+ var UUID_SOURCE = /[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/.source;
12
+ var UUID = new RegExp(`^${UUID_SOURCE}$`, "i");
13
+ function isUuid(value) {
14
+ return typeof value === "string" && UUID.test(value);
15
+ }
16
+ /** A full 40-character lowercase git commit or tree SHA. */
17
+ function isGitSha(value) {
18
+ return typeof value === "string" && /^[a-f0-9]{40}$/.test(value);
19
+ }
20
+ /** A lowercase hex SHA-256 digest. */
21
+ function isSha256Hex(value) {
22
+ return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
23
+ }
24
+ /** The Node.js `code` of a thrown system error (`ENOENT`, `EEXIST`, ...), if it has one. */
25
+ function errorCode(error) {
26
+ const code = isRecord(error) || error instanceof Error ? error.code : void 0;
27
+ return typeof code === "string" ? code : void 0;
28
+ }
29
+ export { UUID_SOURCE, errorCode, isGitSha, isRecord, isSha256Hex, isUuid };
@@ -1,7 +1,7 @@
1
1
  import { delimiter, join } from "node:path";
2
+ import { createHash } from "node:crypto";
2
3
  import { accessSync, closeSync, constants, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
3
4
  import { execFileSync } from "node:child_process";
4
- import { createHash } from "node:crypto";
5
5
  // src/ci/toolchain-identity.ts
6
6
  /**
7
7
  * Identifies the toolchain cached `vp` tasks run on, so every cache key covers
@@ -1,3 +1,4 @@
1
+ import { isSha256Hex } from "../app/value-guards.js";
1
2
  import { containsAsciiControl } from "./string-policy.js";
2
3
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
3
4
  // src/desktop/channel-proof.ts
@@ -5,7 +6,7 @@ var separator = "";
5
6
  var field = (value) => typeof value === "string" && value.length > 0 && value.length <= 128 && !containsAsciiControl(value);
6
7
  /** Exact wire input used by Adea's current signed invoke bridge. */
7
8
  function legacyProofMessage(input, context = "adea-invoke-v1") {
8
- if (!field(context) || !field(input.channelId) || !field(input.credentialId) || !field(input.nonce) || !/^\d{1,16}$/.test(input.timestamp) || !/^[a-f0-9]{64}$/.test(input.bodySha256)) throw new Error("Invalid proof fields");
9
+ if (!field(context) || !field(input.channelId) || !field(input.credentialId) || !field(input.nonce) || !/^\d{1,16}$/.test(input.timestamp) || !isSha256Hex(input.bodySha256)) throw new Error("Invalid proof fields");
9
10
  return [
10
11
  context,
11
12
  input.channelId,
@@ -219,29 +219,23 @@ function createClientAssetStream(path, expected, openAsset = open, limit) {
219
219
  if (cancelled) return;
220
220
  const current = file;
221
221
  if (!current) return;
222
- if (offset === expected.size) {
222
+ const finish = async (last) => {
223
223
  const actual = await current.stat();
224
224
  if (cancelled) return;
225
225
  if (!sameFile(expected, actual)) throw new Error("Client asset changed during request");
226
226
  await close();
227
227
  if (cancelled) return;
228
+ if (last) controller.enqueue(last);
228
229
  controller.close();
229
- return;
230
- }
230
+ };
231
+ if (offset === expected.size) return await finish();
231
232
  const buffer = Buffer.allocUnsafe(Math.min(FILE_CHUNK_BYTES, expected.size - offset));
232
233
  const { bytesRead } = await current.read(buffer, 0, buffer.length, offset);
233
234
  if (cancelled) return;
234
235
  if (!bytesRead) throw new Error("Client asset changed during request");
235
236
  offset += bytesRead;
236
- if (offset === expected.size) {
237
- const actual = await current.stat();
238
- if (cancelled) return;
239
- if (!sameFile(expected, actual)) throw new Error("Client asset changed during request");
240
- await close();
241
- if (cancelled) return;
242
- controller.enqueue(buffer.subarray(0, bytesRead));
243
- controller.close();
244
- } else controller.enqueue(buffer.subarray(0, bytesRead));
237
+ if (offset === expected.size) await finish(buffer.subarray(0, bytesRead));
238
+ else controller.enqueue(buffer.subarray(0, bytesRead));
245
239
  } catch (error) {
246
240
  await close().catch(() => {});
247
241
  if (!cancelled) controller.error(error);
@@ -4,6 +4,27 @@ import type { DesktopRenderer } from '../native/renderer-profile';
4
4
  import type { WindowFrame } from '../native/window-options';
5
5
  import type { createServiceRegistry } from '../app/service-registry';
6
6
  import { createDesktopStreams } from './desktop-stream';
7
+ /** A WebSocket an app-owned route accepted; `data` is what the route passed to `upgrade`. */
8
+ export type DesktopRouteSocket = {
9
+ readonly data: unknown;
10
+ send(message: string | Uint8Array): number;
11
+ close(code?: number, reason?: string): void;
12
+ };
13
+ /** An app-owned same-origin route. Handlers must apply their own authorization; the host has
14
+ * already refused requests whose Origin is not the window's loopback origin. */
15
+ export type DesktopRoute = {
16
+ prefix: string;
17
+ /** Return a response, or call `context.upgrade` (routes with `websocket` only) and return
18
+ * undefined to accept a WebSocket. */
19
+ handle(request: Request, context: {
20
+ upgrade(data?: unknown): boolean;
21
+ }): Response | undefined | Promise<Response | undefined>;
22
+ websocket?: {
23
+ open?(socket: DesktopRouteSocket): void;
24
+ message?(socket: DesktopRouteSocket, message: string | Buffer): void;
25
+ close?(socket: DesktopRouteSocket, code: number, reason: string): void;
26
+ };
27
+ };
7
28
  /** Bind an isolated client server and open a window with a per-window channel. */
8
29
  type DesktopHostOptions<Principal, Window extends NativeWindow> = {
9
30
  clientRoot: string;
@@ -32,11 +53,10 @@ type DesktopHostOptions<Principal, Window extends NativeWindow> = {
32
53
  * callback's responsibility.
33
54
  */
34
55
  configureStreams?: (streams: ReturnType<typeof createDesktopStreams<Principal>>) => void;
35
- /** App-owned same-origin HTTP routes. Handlers must apply their own authorization. */
36
- routes?: readonly {
37
- prefix: string;
38
- handle(request: Request): Response | Promise<Response>;
39
- }[];
56
+ /** App-owned same-origin HTTP and WebSocket routes. Handlers must apply their own authorization. */
57
+ routes?: readonly DesktopRoute[];
58
+ /** Exact https or loopback origins the client may embed in child frames (at most 8). */
59
+ frameSources?: readonly string[];
40
60
  construct(options: SecureWindowOptions): Window;
41
61
  frame?: WindowFrame;
42
62
  transparent?: boolean;
@@ -1,3 +1,4 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { createChannelAuthority } from "./channel-handshake.js";
2
3
  import { createClientAssetFileLimit, createClientAssetVerificationCache } from "./client-asset-stream.js";
3
4
  import { createClientAssetResolver } from "./client-assets.js";
@@ -18,6 +19,22 @@ var DesktopPortInUseError = class extends Error {
18
19
  super("Desktop origin port is in use", { cause });
19
20
  }
20
21
  };
22
+ var FRAME_SOURCE = /^(?:https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[1-9][0-9]{0,4})?|http:\/\/(?:127\.0\.0\.1|localhost):[1-9][0-9]{0,4})$/;
23
+ /** The asset CSP: no child frames unless the app names exact frame origins. */
24
+ function contentSecurityPolicy(frameSources) {
25
+ const sources = frameSources ?? [];
26
+ if (!Array.isArray(sources) || sources.length > 8 || sources.some((source) => typeof source !== "string" || !FRAME_SOURCE.test(source) || Number(/:([0-9]+)$/.exec(source)?.[1] ?? 443) > 65535)) throw new Error("Invalid desktop frame sources");
27
+ return `frame-src ${sources.length ? [...new Set(sources)].join(" ") : "'none'"}; frame-ancestors 'none'; object-src 'none'; base-uri 'none'`;
28
+ }
29
+ /** Run an app socket handler; a throw closes the socket instead of reaching the server. */
30
+ function routeSocketCall(run, socket) {
31
+ try {
32
+ const result = run();
33
+ if (result instanceof Promise) result.catch(() => socket?.close(1011));
34
+ } catch {
35
+ socket?.close(1011);
36
+ }
37
+ }
21
38
  function startDesktopHost(options) {
22
39
  return createDesktopHost(options);
23
40
  }
@@ -41,11 +58,17 @@ function createDesktopHost(options, lifecycle) {
41
58
  verificationCache: clientAssetVerificationCache
42
59
  }, options.retainedClientAssets);
43
60
  const configuredRoutes = options.routes ?? [];
44
- if (!Array.isArray(configuredRoutes) || configuredRoutes.length > 32 || configuredRoutes.some((route) => !route || typeof route.prefix !== "string" || !/^\/[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)*$/.test(route.prefix) || route.prefix.length > 200 || route.prefix === "/__framework" || route.prefix.startsWith("/__framework/") || typeof route.handle !== "function") || configuredRoutes.some((route, index) => configuredRoutes.slice(index + 1).some((other) => route.prefix === other.prefix || route.prefix.startsWith(other.prefix + "/") || other.prefix.startsWith(route.prefix + "/")))) throw new Error("Invalid desktop route policy");
45
- const routes = configuredRoutes.map(({ prefix, handle }) => ({
61
+ if (!Array.isArray(configuredRoutes) || configuredRoutes.length > 32 || configuredRoutes.some((route) => !route || typeof route.prefix !== "string" || !/^\/[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)*$/.test(route.prefix) || route.prefix.length > 200 || route.prefix === "/__framework" || route.prefix.startsWith("/__framework/") || typeof route.handle !== "function" || route.websocket !== void 0 && (typeof route.websocket !== "object" || route.websocket === null || [
62
+ "open",
63
+ "message",
64
+ "close"
65
+ ].some((name) => route.websocket[name] !== void 0 && typeof route.websocket[name] !== "function"))) || configuredRoutes.some((route, index) => configuredRoutes.slice(index + 1).some((other) => route.prefix === other.prefix || route.prefix.startsWith(other.prefix + "/") || other.prefix.startsWith(route.prefix + "/")))) throw new Error("Invalid desktop route policy");
66
+ const routes = configuredRoutes.map(({ prefix, handle, websocket }) => ({
46
67
  prefix,
47
- handle
68
+ handle,
69
+ websocket: websocket && { ...websocket }
48
70
  }));
71
+ const csp = contentSecurityPolicy(options.frameSources);
49
72
  if (options.portFile !== void 0 && (typeof options.portFile !== "string" || !options.portFile)) throw new Error("Invalid desktop port file");
50
73
  if (options.initialPort !== void 0 && (!Number.isInteger(options.initialPort) || options.initialPort < 1024 || options.initialPort > 65535)) throw new Error("Invalid initial desktop port");
51
74
  let port = options.initialPort ?? 0;
@@ -59,10 +82,16 @@ function createDesktopHost(options, lifecycle) {
59
82
  if (options.initialPort !== void 0 && options.initialPort !== savedPort) throw new Error("Saved desktop port does not match initial port");
60
83
  port = savedPort;
61
84
  } catch (error) {
62
- if (error.code !== "ENOENT") throw error;
85
+ if (errorCode(error) !== "ENOENT") throw error;
63
86
  savePort = true;
64
87
  }
65
88
  let origin = "";
89
+ let loopbackPolicy;
90
+ const fromLoopbackOrigin = (request) => loopbackPolicy !== void 0 && matchesLoopbackOrigin({
91
+ host: request.headers.get("host"),
92
+ origin: request.headers.get("origin"),
93
+ secFetchSite: request.headers.get("sec-fetch-site")
94
+ }, loopbackPolicy);
66
95
  let gateway;
67
96
  let streams;
68
97
  let grant;
@@ -74,18 +103,14 @@ function createDesktopHost(options, lifecycle) {
74
103
  hostname: "127.0.0.1",
75
104
  port,
76
105
  async fetch(request, connection) {
77
- if (stopped || !origin || !gateway) return new Response(null, { status: 503 });
106
+ if (stopped || !origin || !loopbackPolicy || !gateway) return new Response(null, { status: 503 });
78
107
  const url = new URL(request.url);
79
- if (url.origin !== origin || request.headers.get("host") !== new URL(origin).host) {
108
+ if (url.origin !== origin || request.headers.get("host") !== loopbackPolicy.host) {
80
109
  reportRequest("rejected");
81
110
  return new Response(null, { status: 403 });
82
111
  }
83
112
  if (url.pathname === "/__framework/stream") {
84
- if (!streams || request.method !== "GET" || url.search || !matchesLoopbackOrigin({
85
- host: request.headers.get("host"),
86
- origin: request.headers.get("origin"),
87
- secFetchSite: request.headers.get("sec-fetch-site")
88
- }, createLoopbackPolicy(origin))) return new Response(null, { status: 403 });
113
+ if (!streams || request.method !== "GET" || url.search || !fromLoopbackOrigin(request)) return new Response(null, { status: 403 });
89
114
  if (connection.upgrade(request, { data: {} })) return void 0;
90
115
  return new Response(null, { status: 400 });
91
116
  }
@@ -103,17 +128,23 @@ function createDesktopHost(options, lifecycle) {
103
128
  }
104
129
  const route = routes.find((value) => url.pathname === value.prefix || url.pathname.startsWith(value.prefix + "/"));
105
130
  if (route) {
106
- if (!matchesLoopbackOrigin({
107
- host: request.headers.get("host"),
108
- origin: request.headers.get("origin"),
109
- secFetchSite: request.headers.get("sec-fetch-site")
110
- }, createLoopbackPolicy(origin))) return new Response(null, { status: 403 });
131
+ if (!fromLoopbackOrigin(request)) return new Response(null, { status: 403 });
111
132
  reportRequest("route");
133
+ let upgraded = false;
134
+ const context = { upgrade(data) {
135
+ if (upgraded || !route.websocket || request.method !== "GET") return false;
136
+ upgraded = connection.upgrade(request, { data: { route: {
137
+ handlers: route.websocket,
138
+ data
139
+ } } });
140
+ return upgraded;
141
+ } };
112
142
  try {
113
- const result = await route.handle(request);
143
+ const result = await route.handle(request, context);
144
+ if (upgraded) return void 0;
114
145
  return result instanceof Response ? result : new Response(null, { status: 500 });
115
146
  } catch {
116
- return new Response(null, { status: 500 });
147
+ return upgraded ? void 0 : new Response(null, { status: 500 });
117
148
  }
118
149
  }
119
150
  reportRequest(kind);
@@ -124,7 +155,7 @@ function createDesktopHost(options, lifecycle) {
124
155
  if (error instanceof ClientResponseLifecycleClosedError) return new Response(null, { status: 503 });
125
156
  throw error;
126
157
  }
127
- result.headers.set("content-security-policy", "frame-src 'none'; frame-ancestors 'none'; object-src 'none'; base-uri 'none'");
158
+ result.headers.set("content-security-policy", csp);
128
159
  result.headers.set("x-content-type-options", "nosniff");
129
160
  result.headers.set("referrer-policy", "no-referrer");
130
161
  return result;
@@ -134,6 +165,17 @@ function createDesktopHost(options, lifecycle) {
134
165
  backpressureLimit: DESKTOP_STREAM_BACKPRESSURE_LIMIT,
135
166
  closeOnBackpressureLimit: true,
136
167
  open(socket) {
168
+ const route = socket.data.route;
169
+ if (route) {
170
+ const wrapped = {
171
+ data: route.data,
172
+ send: (message) => socket.send(message),
173
+ close: (code, reason) => socket.close(code, reason)
174
+ };
175
+ route.socket = wrapped;
176
+ routeSocketCall(() => route.handlers.open?.(wrapped), socket);
177
+ return;
178
+ }
137
179
  socket.data.connection = streams?.accept({
138
180
  send: (payload) => sendDesktopStreamPayload(socket, payload),
139
181
  close: () => socket.close()
@@ -141,9 +183,21 @@ function createDesktopHost(options, lifecycle) {
141
183
  if (!socket.data.connection) socket.close();
142
184
  },
143
185
  message(socket, message) {
186
+ const route = socket.data.route;
187
+ if (route?.socket) {
188
+ const wrapped = route.socket;
189
+ routeSocketCall(() => route.handlers.message?.(wrapped, message), socket);
190
+ return;
191
+ }
144
192
  socket.data.connection?.receive(message);
145
193
  },
146
- close(socket) {
194
+ close(socket, code, reason) {
195
+ const route = socket.data.route;
196
+ if (route?.socket) {
197
+ const wrapped = route.socket;
198
+ routeSocketCall(() => route.handlers.close?.(wrapped, code, reason));
199
+ return;
200
+ }
147
201
  socket.data.connection?.close();
148
202
  }
149
203
  }
@@ -176,6 +230,7 @@ function createDesktopHost(options, lifecycle) {
176
230
  try {
177
231
  if (options.portFile !== void 0 && savePort) publishDesktopPort(options.portFile, server.port);
178
232
  origin = `http://127.0.0.1:${server.port}`;
233
+ loopbackPolicy = createLoopbackPolicy(origin);
179
234
  const authority = createChannelAuthority();
180
235
  if (options.configureStreams) {
181
236
  streams = createDesktopStreams({ authority });
@@ -1 +1 @@
1
- {"version":"0.31.0","commit":"970131b382d646d07de21bdd58359188bf171df4"}
1
+ {"version":"0.33.0","commit":"c0d47a5bed1a1d47838e66063839560804f3374d"}
@@ -1,3 +1,4 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { safeArchivePath } from "./archive-entry.js";
2
3
  import { linuxProcessGroupIsExited } from "./linux-process-group.js";
3
4
  import { lstat, mkdir, mkdtemp, readFile, readdir, rm } from "node:fs/promises";
@@ -146,7 +147,7 @@ function signalProcessGroup(pid, signal) {
146
147
  try {
147
148
  process.kill(-pid, signal);
148
149
  } catch (error) {
149
- if (!processGroupIsGone(error.code)) throw error;
150
+ if (!processGroupIsGone(errorCode(error))) throw error;
150
151
  }
151
152
  }
152
153
  async function serviceExitStatus(path) {
@@ -156,7 +157,7 @@ async function serviceExitStatus(path) {
156
157
  const status = Number(value);
157
158
  return status <= 255 ? status : void 0;
158
159
  } catch (error) {
159
- if (error.code === "ENOENT") return void 0;
160
+ if (errorCode(error) === "ENOENT") return void 0;
160
161
  throw error;
161
162
  }
162
163
  }
@@ -176,7 +177,7 @@ async function processGroupExited(pid, milliseconds) {
176
177
  try {
177
178
  process.kill(-pid, 0);
178
179
  } catch (error) {
179
- if (processGroupIsGone(error.code)) return true;
180
+ if (processGroupIsGone(errorCode(error))) return true;
180
181
  throw error;
181
182
  }
182
183
  if (process.platform === "linux" && await linuxProcessGroupIsExited(pid)) return true;
@@ -1,8 +1,9 @@
1
+ import { errorCode } from "../app/value-guards.js";
1
2
  import { assertInstallerContext } from "./installer-layout.js";
2
3
  import { validateCommandReceipt } from "../release/release-qualification.js";
3
4
  import { parseReleaseConfig } from "../release/release-config.js";
4
- import { planReleaseAssets } from "../release/release-assets-plan.js";
5
5
  import { qualifyCommandArtifact } from "./command-artifact.js";
6
+ import { planQualificationRun } from "../release/qualification-run.js";
6
7
  import { fileIdentity } from "../release/release-publication.js";
7
8
  import { lstat, writeFile } from "node:fs/promises";
8
9
  import { join, resolve } from "node:path";
@@ -16,7 +17,7 @@ async function qualifyCommandArtifactsCommand(options) {
16
17
  if (!parsed.commandArtifacts.length) return [];
17
18
  assertInstallerContext(env, platform, process.platform, process.arch);
18
19
  if (env.RELEASE_TAG !== tag) throw new Error("Command artifact release tag mismatch");
19
- const plan = await planReleaseAssets({
20
+ const plan = await planQualificationRun({
20
21
  env,
21
22
  config,
22
23
  tag
@@ -28,8 +29,8 @@ async function qualifyCommandArtifactsCommand(options) {
28
29
  tag,
29
30
  sourceSha: plan.sourceSha,
30
31
  workflowSha: plan.workflowSha,
31
- runId: env.GITHUB_RUN_ID,
32
- runAttempt: Number(env.GITHUB_RUN_ATTEMPT)
32
+ runId: plan.runId,
33
+ runAttempt: plan.runAttempt
33
34
  };
34
35
  const receipts = [];
35
36
  for (const policy of parsed.commandArtifacts) {
@@ -39,7 +40,7 @@ async function qualifyCommandArtifactsCommand(options) {
39
40
  await lstat(destination);
40
41
  throw new Error("Command artifact receipt already exists");
41
42
  } catch (error) {
42
- if (error.code !== "ENOENT") throw error;
43
+ if (errorCode(error) !== "ENOENT") throw error;
43
44
  }
44
45
  const path = join(directory, name);
45
46
  const asset = await fileIdentity(path, name);
@@ -1,4 +1,11 @@
1
- /** True only on a disposable GitHub-hosted Actions runner. */
1
+ /**
2
+ * True only on a disposable CI runner: a GitHub-hosted Actions runner, or a GitLab CI job
3
+ * whose configuration declares its executor disposable (a fresh container or VM per job)
4
+ * with `FRAMEWORK_DISPOSABLE_RUNNER=true`. Installer qualification installs software, so a
5
+ * shell executor or developer machine must never set that variable.
6
+ */
2
7
  export declare function isHostedRunner(env: Record<string, string | undefined>): boolean;
3
- /** Refuse `subject` anywhere but a disposable GitHub-hosted runner. */
8
+ /** Refuse `subject` anywhere but a disposable hosted runner. */
4
9
  export declare function assertHostedRunner(env: Record<string, string | undefined>, subject: string): void;
10
+ /** The runner's per-job temporary directory: `RUNNER_TEMP` on GitHub, `TMPDIR` on GitLab. */
11
+ export declare function runnerTemp(env: Record<string, string | undefined>): string | undefined;
@@ -1,10 +1,23 @@
1
+ import { isAbsolute } from "node:path";
1
2
  // src/installer/hosted-runner.ts
2
- /** True only on a disposable GitHub-hosted Actions runner. */
3
+ /**
4
+ * True only on a disposable CI runner: a GitHub-hosted Actions runner, or a GitLab CI job
5
+ * whose configuration declares its executor disposable (a fresh container or VM per job)
6
+ * with `FRAMEWORK_DISPOSABLE_RUNNER=true`. Installer qualification installs software, so a
7
+ * shell executor or developer machine must never set that variable.
8
+ */
3
9
  function isHostedRunner(env) {
4
- return env.CI === "true" && env.GITHUB_ACTIONS === "true" && env.RUNNER_ENVIRONMENT === "github-hosted";
10
+ if (env.CI !== "true") return false;
11
+ if (env.GITHUB_ACTIONS === "true") return env.RUNNER_ENVIRONMENT === "github-hosted";
12
+ return env.GITLAB_CI === "true" && env.FRAMEWORK_DISPOSABLE_RUNNER === "true" && /^[1-9]\d{0,19}$/.test(env.CI_JOB_ID ?? "");
5
13
  }
6
- /** Refuse `subject` anywhere but a disposable GitHub-hosted runner. */
14
+ /** Refuse `subject` anywhere but a disposable hosted runner. */
7
15
  function assertHostedRunner(env, subject) {
8
- if (!isHostedRunner(env)) throw new Error(`${subject} requires a disposable GitHub-hosted runner`);
16
+ if (!isHostedRunner(env)) throw new Error(`${subject} requires a disposable hosted runner`);
9
17
  }
10
- export { assertHostedRunner, isHostedRunner };
18
+ /** The runner's per-job temporary directory: `RUNNER_TEMP` on GitHub, `TMPDIR` on GitLab. */
19
+ function runnerTemp(env) {
20
+ const path = env.GITHUB_ACTIONS === "true" ? env.RUNNER_TEMP : env.TMPDIR;
21
+ return path && isAbsolute(path) ? path : void 0;
22
+ }
23
+ export { assertHostedRunner, isHostedRunner, runnerTemp };