@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,387 +0,0 @@
1
- /**
2
- * Language-agnostic sidecar host: runs a bundled executable, written in any
3
- * language, and calls it over stdio with line-delimited JSON.
4
- *
5
- * Wire protocol, one JSON object per line in each direction:
6
- *
7
- * host → sidecar {"id": 1, "command": "name", "args": {...}}
8
- * sidecar → host {"id": 1, "ok": true, "value": ...}
9
- * {"id": 1, "ok": false, "error": "readable message"}
10
- *
11
- * Ids are positive JavaScript-safe integers; replies may arrive in any order.
12
- * A sidecar must exit when its stdin closes so it never outlives the host, and
13
- * should answer a request it cannot parse with `"id": null` (logged here).
14
- *
15
- * The host starts the process on the first call, respawns it on the next call
16
- * after it exits (within the restart budget), and kills it on `stop()` or when
17
- * the host process exits. `call()` never throws: every failure resolves as
18
- * `{ok: false, reason, error}` with a readable message.
19
- */
20
-
21
- export type SidecarFailure =
22
- /** The sidecar answered with `ok: false`. */
23
- | 'command_failed'
24
- | 'timeout'
25
- | 'aborted'
26
- | 'request_too_large'
27
- | 'reply_too_large'
28
- /** The executable could not be started (missing, not executable, ...). */
29
- | 'unavailable'
30
- /** The process exited before replying. */
31
- | 'exited'
32
- /** The process exited too often within the restart window. */
33
- | 'restart_limit'
34
- | 'stopped'
35
- | 'invalid_request'
36
-
37
- export type SidecarReply<Value = unknown> =
38
- | { ok: true; value: Value }
39
- | { ok: false; reason: SidecarFailure; error: string }
40
-
41
- /** Describe a sidecar's commands to type `call`: `{ command: { args; value } }`. */
42
- export type SidecarCommands = Record<string, { args: Record<string, unknown>; value: unknown }>
43
-
44
- export type SidecarState = 'idle' | 'running' | 'stopped'
45
-
46
- export type SidecarOptions = {
47
- /** Absolute path of the executable; see `packagedSidecarPath` in `app-bundle`. */
48
- executable: string
49
- args?: readonly string[]
50
- /** Replaces the inherited environment when given. */
51
- env?: Record<string, string | undefined>
52
- /** Shown in error messages and logs. Default `sidecar`. */
53
- name?: string
54
- /** Default 30 s. */
55
- requestTimeoutMs?: number
56
- /** Default 1 MiB per request line. */
57
- maxRequestBytes?: number
58
- /** Default 8 MiB per reply line, plus 1 KiB of framing. */
59
- maxReplyBytes?: number
60
- /** Respawns allowed after an exit within `windowMs`; the first start is not a restart. */
61
- restart: { maxRestarts: number; windowMs: number }
62
- /** Bytes of recent stderr kept for `stderr()`. Default 64 KiB. */
63
- maxStderrBytes?: number
64
- /** Receives stderr lines and lifecycle notes. */
65
- log?: (line: string) => void
66
- }
67
-
68
- export type Sidecar<Commands extends SidecarCommands = SidecarCommands> = {
69
- call<Command extends keyof Commands & string>(
70
- command: Command,
71
- args?: Commands[Command]['args'],
72
- options?: { signal?: AbortSignal; timeoutMs?: number }
73
- ): Promise<SidecarReply<Commands[Command]['value']>>
74
- /** Start now instead of on the first call. Returns false when it could not start. */
75
- start(): boolean
76
- /** Kill the process and fail pending calls. Later calls resolve as `stopped`. */
77
- stop(): void
78
- readonly state: SidecarState
79
- readonly pid: number | undefined
80
- /** Recent stderr, bounded, for diagnostics. Never send it to the web side. */
81
- stderr(): string
82
- }
83
-
84
- type Pending = {
85
- resolve(reply: SidecarReply): void
86
- cleanup(): void
87
- }
88
-
89
- type Running = {
90
- process: Bun.Subprocess<'pipe', 'pipe', 'pipe'>
91
- pending: Map<number, Pending>
92
- }
93
-
94
- const MAX_REQUEST_ID = Number.MAX_SAFE_INTEGER
95
- const NEWLINE = 0x0a
96
-
97
- type Failed = Extract<SidecarReply, { ok: false }>
98
- const fail = (reason: SidecarFailure, error: string): Failed => ({ ok: false, reason, error })
99
- const positive = (value: unknown, max = Number.MAX_SAFE_INTEGER): value is number =>
100
- Number.isSafeInteger(value) && (value as number) > 0 && (value as number) <= max
101
-
102
- export function createSidecar<Commands extends SidecarCommands = SidecarCommands>(
103
- options: SidecarOptions
104
- ): Sidecar<Commands> {
105
- const name = options.name ?? 'sidecar'
106
- const requestTimeoutMs = options.requestTimeoutMs ?? 30_000
107
- const maxRequestBytes = options.maxRequestBytes ?? 1024 * 1024
108
- const maxReplyBytes = options.maxReplyBytes ?? 8 * 1024 * 1024 + 1024
109
- const maxStderrBytes = options.maxStderrBytes ?? 64 * 1024
110
- const { maxRestarts, windowMs } = options.restart ?? {}
111
- if (
112
- typeof options.executable !== 'string' ||
113
- !options.executable ||
114
- (options.args !== undefined &&
115
- (!Array.isArray(options.args) || options.args.some((arg) => typeof arg !== 'string'))) ||
116
- typeof name !== 'string' ||
117
- !name ||
118
- name.length > 100 ||
119
- !positive(requestTimeoutMs, 2_147_483_647) ||
120
- !positive(maxRequestBytes) ||
121
- !positive(maxReplyBytes) ||
122
- !positive(maxStderrBytes) ||
123
- !Number.isSafeInteger(maxRestarts) ||
124
- maxRestarts < 0 ||
125
- !positive(windowMs)
126
- )
127
- throw new Error('Invalid sidecar options')
128
- const log = options.log ?? (() => {})
129
- const encoder = new TextEncoder()
130
-
131
- let running: Running | undefined
132
- let stopped = false
133
- let nextId = 1
134
- let starts: number[] = []
135
- let stderrTail = ''
136
-
137
- const note = (line: string) => {
138
- try {
139
- log(line)
140
- } catch {
141
- /* Diagnostics cannot change supervision. */
142
- }
143
- }
144
-
145
- function failAll(state: Running, reason: SidecarFailure, error: string) {
146
- for (const [id, pending] of state.pending) {
147
- state.pending.delete(id)
148
- pending.cleanup()
149
- pending.resolve(fail(reason, error))
150
- }
151
- }
152
-
153
- // Kill the child if the host exits without calling stop().
154
- let hooked = false
155
- const onHostExit = () => kill()
156
- const hook = (on: boolean) => {
157
- if (on === hooked) return
158
- hooked = on
159
- if (on) process.on('exit', onHostExit)
160
- else process.off('exit', onHostExit)
161
- }
162
-
163
- function spawn(): Running | Failed {
164
- const now = performance.now()
165
- starts = starts.filter((at) => now - at < windowMs)
166
- if (starts.length > maxRestarts)
167
- return fail('restart_limit', `The ${name} stopped repeatedly; try again shortly`)
168
- starts.push(now)
169
- let child: Running['process']
170
- try {
171
- child = Bun.spawn({
172
- cmd: [options.executable, ...(options.args ?? [])],
173
- env: options.env ?? Bun.env,
174
- stdin: 'pipe',
175
- stdout: 'pipe',
176
- stderr: 'pipe',
177
- })
178
- } catch (error) {
179
- note(`${name} failed to start: ${String(error)}`)
180
- return fail('unavailable', `The ${name} could not be started`)
181
- }
182
- const state: Running = { process: child, pending: new Map() }
183
- hook(true)
184
- void readReplies(state)
185
- void readStderr(child.stderr)
186
- void child.exited.then((code) => {
187
- if (running === state) {
188
- running = undefined
189
- hook(false)
190
- }
191
- if (!stopped) note(`${name} exited with code ${code}`)
192
- failAll(state, 'exited', `The ${name} stopped before replying`)
193
- return null
194
- })
195
- return state
196
- }
197
-
198
- async function readReplies(state: Running) {
199
- const decoder = new TextDecoder()
200
- // Bytes of an incomplete line, kept as chunks so long replies are not re-copied.
201
- let parts: Uint8Array[] = []
202
- let partial = 0
203
- const tooLarge = () => {
204
- note(`${name} reply exceeded ${maxReplyBytes} bytes; restarting it`)
205
- failAll(state, 'reply_too_large', `The ${name} sent an oversized reply`)
206
- state.process.kill()
207
- }
208
- try {
209
- for await (const chunk of state.process.stdout) {
210
- let start = 0
211
- let newline: number
212
- while ((newline = chunk.indexOf(NEWLINE, start)) !== -1) {
213
- const piece = chunk.subarray(start, newline)
214
- start = newline + 1
215
- if (partial + piece.byteLength > maxReplyBytes) return tooLarge()
216
- let line: Uint8Array = piece
217
- if (parts.length) {
218
- line = new Uint8Array(partial + piece.byteLength)
219
- let offset = 0
220
- for (const part of parts) {
221
- line.set(part, offset)
222
- offset += part.byteLength
223
- }
224
- line.set(piece, offset)
225
- parts = []
226
- partial = 0
227
- }
228
- deliver(state, decoder.decode(line))
229
- }
230
- if (start < chunk.byteLength) {
231
- const rest = chunk.subarray(start)
232
- partial += rest.byteLength
233
- if (partial > maxReplyBytes) return tooLarge()
234
- parts.push(rest.slice())
235
- }
236
- }
237
- } catch (error) {
238
- note(`${name} stdout failed: ${String(error)}`)
239
- }
240
- }
241
-
242
- function deliver(state: Running, line: string) {
243
- if (!line.trim()) return
244
- let reply: unknown
245
- try {
246
- reply = JSON.parse(line)
247
- } catch {
248
- note(`${name} wrote a line that is not JSON`)
249
- return
250
- }
251
- if (typeof reply !== 'object' || reply === null || Array.isArray(reply)) return
252
- const record = reply as Record<string, unknown>
253
- if (typeof record.id !== 'number') {
254
- note(`${name} rejected a request: ${String(record.error).slice(0, 4096)}`)
255
- return
256
- }
257
- const pending = state.pending.get(record.id)
258
- if (!pending) return
259
- state.pending.delete(record.id)
260
- pending.cleanup()
261
- if (record.ok === true) pending.resolve({ ok: true, value: record.value ?? null })
262
- else
263
- pending.resolve(
264
- fail(
265
- 'command_failed',
266
- typeof record.error === 'string' && record.error
267
- ? record.error
268
- : `The ${name} command failed`
269
- )
270
- )
271
- }
272
-
273
- async function readStderr(stream: ReadableStream<Uint8Array>) {
274
- const decoder = new TextDecoder()
275
- let buffer = ''
276
- try {
277
- for await (const chunk of stream) {
278
- const text = decoder.decode(chunk, { stream: true })
279
- stderrTail += text
280
- if (stderrTail.length > maxStderrBytes) stderrTail = stderrTail.slice(-maxStderrBytes)
281
- buffer += text
282
- const lines = buffer.split('\n')
283
- buffer = lines.pop() ?? ''
284
- // Bound what a misbehaving sidecar can make the host retain.
285
- if (buffer.length > maxStderrBytes) buffer = ''
286
- for (const line of lines) if (line.trim()) note(`${name}: ${line.slice(0, 4096)}`)
287
- }
288
- } catch {
289
- /* stderr closes with the process */
290
- }
291
- }
292
-
293
- function ensure(): Running | Failed {
294
- if (stopped) return fail('stopped', `The ${name} is shut down`)
295
- if (running) return running
296
- const state = spawn()
297
- if ('process' in state) running = state
298
- return state
299
- }
300
-
301
- function kill() {
302
- const state = running
303
- running = undefined
304
- hook(false)
305
- if (!state) return
306
- failAll(state, 'stopped', `The ${name} is shut down`)
307
- try {
308
- void state.process.stdin.end()
309
- } catch {
310
- /* already closed */
311
- }
312
- state.process.kill()
313
- }
314
-
315
- function call(
316
- command: string,
317
- args?: Record<string, unknown>,
318
- callOptions?: { signal?: AbortSignal; timeoutMs?: number }
319
- ): Promise<SidecarReply> {
320
- const signal = callOptions?.signal
321
- const timeoutMs = callOptions?.timeoutMs ?? requestTimeoutMs
322
- if (typeof command !== 'string' || !command || command.length > 128)
323
- return Promise.resolve(fail('invalid_request', `Invalid ${name} command`))
324
- if (!positive(timeoutMs, 2_147_483_647))
325
- return Promise.resolve(fail('invalid_request', `Invalid ${name} timeout`))
326
- if (signal?.aborted) return Promise.resolve(fail('aborted', `The ${name} call was cancelled`))
327
- if (nextId > MAX_REQUEST_ID) nextId = 1
328
- const id = nextId++
329
- let line: string
330
- try {
331
- line = JSON.stringify({ id, command, args: args ?? {} })
332
- } catch {
333
- return Promise.resolve(fail('invalid_request', `The ${name} request is not JSON`))
334
- }
335
- if (encoder.encode(line).byteLength > maxRequestBytes)
336
- return Promise.resolve(fail('request_too_large', `The ${name} request is too large`))
337
- const state = ensure()
338
- if (!('process' in state)) return Promise.resolve(state)
339
- return new Promise((resolve) => {
340
- const settle = (reply: SidecarReply) => {
341
- if (state.pending.delete(id)) {
342
- cleanup()
343
- resolve(reply)
344
- }
345
- }
346
- const onAbort = () => settle(fail('aborted', `The ${name} call was cancelled`))
347
- const timer = setTimeout(
348
- () => settle(fail('timeout', `The ${name} did not reply in time`)),
349
- timeoutMs
350
- )
351
- const cleanup = () => {
352
- clearTimeout(timer)
353
- signal?.removeEventListener('abort', onAbort)
354
- }
355
- signal?.addEventListener('abort', onAbort, { once: true })
356
- state.pending.set(id, { resolve, cleanup })
357
- try {
358
- state.process.stdin.write(line + '\n')
359
- void Promise.resolve(state.process.stdin.flush()).catch(() => {})
360
- } catch {
361
- settle(fail('exited', `The ${name} is not accepting requests`))
362
- }
363
- })
364
- }
365
-
366
- const sidecar: Sidecar = {
367
- call,
368
- start() {
369
- const state = ensure()
370
- if ('process' in state) return true
371
- note(state.error)
372
- return false
373
- },
374
- stop() {
375
- stopped = true
376
- kill()
377
- },
378
- get state(): SidecarState {
379
- return stopped ? 'stopped' : running ? 'running' : 'idle'
380
- },
381
- get pid() {
382
- return running?.process.pid
383
- },
384
- stderr: () => stderrTail,
385
- }
386
- return sidecar as Sidecar<Commands>
387
- }
@@ -1,77 +0,0 @@
1
- import { createHash, randomBytes, randomUUID } from 'node:crypto'
2
- import { createChannelProofVerifier, type SignedRequest } from '../desktop/channel-proof'
3
- import type { createChannelAuthority } from '../desktop/channel-handshake'
4
- import { createLoopbackPolicy } from '../desktop/loopback-policy'
5
-
6
- /**
7
- * Window-specific proof key and preload. This requires a native renderer that
8
- * protects the preload secret from untrusted frames and enforces a navigation
9
- * allowlist before injecting it. Native injection behavior must be verified for
10
- * each renderer and platform before this can be used in a packaged app.
11
- */
12
- export function createNativeWindowGrant<Principal>(options: {
13
- origin: string
14
- authority: ReturnType<typeof createChannelAuthority<Principal>>
15
- principal: Principal
16
- now?: () => number
17
- lifetimeMs?: number
18
- }) {
19
- const origin = createLoopbackPolicy(options.origin).origin
20
- const clock = options.now ?? Date.now
21
- const lifetime = options.lifetimeMs ?? 12 * 60 * 60 * 1000
22
- const started = clock()
23
- if (
24
- !Number.isSafeInteger(lifetime) ||
25
- lifetime < 1 ||
26
- !Number.isSafeInteger(started) ||
27
- started < 0 ||
28
- started > Number.MAX_SAFE_INTEGER - lifetime
29
- )
30
- throw new Error('Invalid window grant lifetime')
31
- const expiresAt = started + lifetime
32
- const secret = randomBytes(32)
33
- const channelId = randomUUID()
34
- const credentialId = randomUUID()
35
- let live = true
36
- const verifier = createChannelProofVerifier({
37
- now: clock,
38
- context: 'framework-window-bootstrap-v1',
39
- resolve: (identity) =>
40
- live && identity.channelId === channelId && identity.credentialId === credentialId
41
- ? { secret, expiresAt, principal: options.principal }
42
- : undefined,
43
- })
44
- const bodySha256 = createHash('sha256').update('{}').digest('hex')
45
- // The script and key are native-window secrets. Never return them in HTTP or logs.
46
- const preload = `(() => {
47
- if (window.top !== window || location.origin !== ${JSON.stringify(origin)}) return;
48
- const keyBytes = Uint8Array.from(atob(${JSON.stringify(secret.toString('base64'))}), c => c.charCodeAt(0));
49
- const nativeFetch = fetch.bind(window);
50
- const encode = bytes => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');
51
- Object.defineProperty(window, '__frameworkAcquireBootstrap', { configurable: false, value: async () => {
52
- const nonce = encode(crypto.getRandomValues(new Uint8Array(24)));
53
- const timestamp = String(Date.now());
54
- const fields = ['framework-window-bootstrap-v1', ${JSON.stringify(channelId)}, ${JSON.stringify(credentialId)}, nonce, timestamp, ${JSON.stringify(bodySha256)}];
55
- const key = await crypto.subtle.importKey('raw', keyBytes, {name:'HMAC', hash:'SHA-256'}, false, ['sign']);
56
- const proof = encode(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(fields.join('\\u001f'))));
57
- const response = await nativeFetch(${JSON.stringify(origin + '/__framework/bootstrap')}, {method:'POST', headers:{'content-type':'application/json', 'x-adea-channel':${JSON.stringify(channelId)}, 'x-adea-credential':${JSON.stringify(credentialId)}, 'x-adea-nonce':nonce, 'x-adea-timestamp':timestamp, 'x-adea-proof':proof}, body:'{}'});
58
- if (!response.ok) throw new Error('Window bootstrap unavailable');
59
- return response.json();
60
- }});
61
- })();`
62
- return {
63
- origin,
64
- preload,
65
- /** Called only after the gateway has checked origin and bounded the body. */
66
- acquire(request: SignedRequest): { bootstrap: string; expiresAt: number } | undefined {
67
- if (request.body !== '{}' || !verifier.verify(request).ok) return undefined
68
- options.authority.revokeAll()
69
- return options.authority.issue(options.principal)
70
- },
71
- revoke() {
72
- live = false
73
- secret.fill(0)
74
- options.authority.revokeAll()
75
- },
76
- }
77
- }
@@ -1,49 +0,0 @@
1
- import { randomUUID } from 'node:crypto'
2
- import { lstat, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises'
3
- import { isAbsolute, join, relative } from 'node:path'
4
- import { assertPortableAppName } from '../installer/installer-layout'
5
-
6
- /** Internal hook plumbing; the public hook always supplies the pinned patch. */
7
- export async function patchWindowsBuildForTest(
8
- env: Record<string, string | undefined>,
9
- patch: (input: Buffer) => Buffer
10
- ): Promise<void> {
11
- if (env.ELECTROBUN_OS === 'macos' || env.ELECTROBUN_OS === 'linux') return
12
- if (
13
- env.ELECTROBUN_OS !== 'win' ||
14
- env.ELECTROBUN_ARCH !== 'x64' ||
15
- !env.ELECTROBUN_BUILD_DIR ||
16
- !env.ELECTROBUN_APP_NAME ||
17
- !['dev', 'canary', 'stable'].includes(env.ELECTROBUN_BUILD_ENV ?? '')
18
- )
19
- throw new Error('Invalid Electrobun build context')
20
- assertPortableAppName(env.ELECTROBUN_APP_NAME)
21
- const buildRoot = await realpath(env.ELECTROBUN_BUILD_DIR)
22
- const suffix = env.ELECTROBUN_BUILD_ENV === 'stable' ? '' : `-${env.ELECTROBUN_BUILD_ENV}`
23
- const path = join(
24
- buildRoot,
25
- env.ELECTROBUN_APP_NAME.replaceAll(' ', '') + suffix,
26
- 'bin',
27
- 'libNativeWrapper.dll'
28
- )
29
- const info = await lstat(path)
30
- if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024)
31
- throw new Error('Invalid Windows build runtime')
32
- const physical = await realpath(path)
33
- const within = relative(buildRoot, physical)
34
- if (
35
- !within ||
36
- within === '..' ||
37
- within.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) ||
38
- isAbsolute(within)
39
- )
40
- throw new Error('Runtime escaped the build directory')
41
- const output = patch(await readFile(physical))
42
- const temp = `${physical}.${randomUUID()}.tmp`
43
- try {
44
- await writeFile(temp, output, { flag: 'wx' })
45
- await rename(temp, physical)
46
- } finally {
47
- await rm(temp, { force: true })
48
- }
49
- }
@@ -1,12 +0,0 @@
1
- import { createHash } from 'node:crypto'
2
- import { patchWindowsBuildForTest } from './windows-build-hook-internal'
3
- import { patchPinnedWindowsRuntime, SECURE_WINDOWS_WRAPPER_SHA256 } from './windows-runtime-patch'
4
-
5
- /** Electrobun postBuild hook; runs before release hashing, packaging and signing. */
6
- export default async function secureWindowsBuild(): Promise<void> {
7
- await patchWindowsBuildForTest(process.env, (input) => {
8
- if (createHash('sha256').update(input).digest('hex') === SECURE_WINDOWS_WRAPPER_SHA256)
9
- return input
10
- return patchPinnedWindowsRuntime(input)
11
- })
12
- }
@@ -1,48 +0,0 @@
1
- import { createHash } from 'node:crypto'
2
-
3
- export const UNSAFE_WEBVIEW_ARGUMENTS =
4
- '--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --allow-insecure-localhost --disable-web-security'
5
- const digest = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex')
6
-
7
- /** Internal deterministic patch primitive. Callers should use the pinned wrapper below. */
8
- export function patchWindowsBinaryForDigest(input: Buffer, expectedSha256: string): Buffer {
9
- if (
10
- !Buffer.isBuffer(input) ||
11
- input.length < 512 ||
12
- input.length > 64 * 1024 * 1024 ||
13
- digest(input) !== expectedSha256 ||
14
- input.toString('ascii', 0, 2) !== 'MZ'
15
- )
16
- throw new Error('Unexpected Windows runtime binary')
17
- const pe = input.readUInt32LE(60)
18
- if (
19
- pe > input.length - 24 ||
20
- input.toString('binary', pe, pe + 4) !== 'PE\0\0' ||
21
- input.readUInt16LE(pe + 4) !== 0x8664 ||
22
- (input.readUInt16LE(pe + 22) & 0x2000) === 0
23
- )
24
- throw new Error('Expected a Windows x64 DLL')
25
- const optional = pe + 24
26
- const optionalSize = input.readUInt16LE(pe + 20)
27
- if (
28
- optionalSize < 152 ||
29
- optional + optionalSize > input.length ||
30
- input.readUInt16LE(optional) !== 0x20b ||
31
- input.readUInt32LE(optional + 108) < 5 ||
32
- input.readUInt32LE(optional + 144) !== 0 ||
33
- input.readUInt32LE(optional + 148) !== 0
34
- )
35
- throw new Error('Expected an unsigned Windows x64 DLL')
36
- const marker = Buffer.from(UNSAFE_WEBVIEW_ARGUMENTS, 'utf16le')
37
- const offset = input.indexOf(marker)
38
- if (
39
- offset < 0 ||
40
- input.indexOf(marker, offset + marker.length) >= 0 ||
41
- offset + marker.length + 2 > input.length ||
42
- input.readUInt16LE(offset + marker.length) !== 0
43
- )
44
- throw new Error('Unexpected WebView2 argument declaration')
45
- const output = Buffer.from(input)
46
- output.fill(0, offset, offset + marker.length)
47
- return output
48
- }
@@ -1,15 +0,0 @@
1
- import { createHash } from 'node:crypto'
2
- import { patchWindowsBinaryForDigest } from './windows-runtime-patch-internal'
3
-
4
- // Electrobun v2.0.5 core-win-x64 release asset, built from MIT-licensed source.
5
- export const ELECTROBUN_WINDOWS_WRAPPER_SHA256 =
6
- 'e162c21696c1676bd4522e0c94d934aa32a6394aea852687d111ab86ed97fe1b'
7
- export const SECURE_WINDOWS_WRAPPER_SHA256 =
8
- '4806357dc333785ae22cdf3526d623cd56283d9c374ceafbf847c3ba6d5d59c3'
9
- /** Patch only the exact pinned unsigned SDK. Sign the application after applying it. */
10
- export function patchPinnedWindowsRuntime(input: Buffer): Buffer {
11
- const output = patchWindowsBinaryForDigest(input, ELECTROBUN_WINDOWS_WRAPPER_SHA256)
12
- if (createHash('sha256').update(output).digest('hex') !== SECURE_WINDOWS_WRAPPER_SHA256)
13
- throw new Error('Unexpected patched runtime digest')
14
- return output
15
- }