@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,335 +0,0 @@
1
- import { lstatSync, readFileSync, writeFileSync } from 'node:fs'
2
- import { serveClient } from './client-assets'
3
- import { createChannelAuthority } from './channel-handshake'
4
- import { createDesktopGateway } from './desktop-gateway'
5
- import { createNativeWindowGrant } from '../native/window-bootstrap'
6
- import {
7
- createSecureWindow,
8
- type NativeWindow,
9
- type SecureWindowOptions,
10
- } from '../native/secure-window'
11
- import type { DesktopRenderer } from '../native/renderer-profile'
12
- import type { WindowFrame } from '../native/window-options'
13
- import type { createServiceRegistry } from '../app/service-registry'
14
- import { createDesktopStreams } from './desktop-stream'
15
- import { createLoopbackPolicy, matchesLoopbackOrigin } from './loopback-policy'
16
-
17
- class DesktopPortInUseError extends Error {
18
- readonly code = 'EADDRINUSE'
19
- constructor(cause: unknown) {
20
- super('Desktop origin port is in use', { cause })
21
- }
22
- }
23
-
24
- /** Bind an isolated client server and open a window with a per-window channel. */
25
- export function startDesktopHost<Principal, Window extends NativeWindow>(options: {
26
- clientRoot: string
27
- /** Existing app-owned file or new path for a stable loopback origin. */
28
- portFile?: string
29
- /** Preserve an existing loopback origin when creating the port file. */
30
- initialPort?: number
31
- title: string
32
- renderer: DesktopRenderer
33
- platform: string
34
- principal: Principal
35
- services: ReturnType<typeof createServiceRegistry<Principal>>
36
- configureStreams?: (streams: ReturnType<typeof createDesktopStreams<Principal>>) => void
37
- /** App-owned same-origin HTTP routes. Handlers must apply their own authorization. */
38
- routes?: readonly { prefix: string; handle(request: Request): Response | Promise<Response> }[]
39
- construct(options: SecureWindowOptions): Window
40
- frame?: WindowFrame
41
- transparent?: boolean
42
- hidden?: boolean
43
- onRequest?: (
44
- kind: 'client' | 'bootstrap' | 'handshake' | 'invoke' | 'route' | 'rejected',
45
- result?: {
46
- status: number
47
- origin: 'matching' | 'missing' | 'opaque' | 'same-host' | 'other'
48
- fetchSite: string | null
49
- }
50
- ) => void
51
- }) {
52
- const configuredRoutes = options.routes ?? []
53
- if (
54
- !Array.isArray(configuredRoutes) ||
55
- configuredRoutes.length > 32 ||
56
- configuredRoutes.some(
57
- (route) =>
58
- !route ||
59
- typeof route.prefix !== 'string' ||
60
- !/^\/[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)*$/.test(route.prefix) ||
61
- route.prefix.length > 200 ||
62
- route.prefix === '/__framework' ||
63
- route.prefix.startsWith('/__framework/') ||
64
- typeof route.handle !== 'function'
65
- ) ||
66
- configuredRoutes.some((route, index) =>
67
- configuredRoutes
68
- .slice(index + 1)
69
- .some(
70
- (other) =>
71
- route.prefix === other.prefix ||
72
- route.prefix.startsWith(other.prefix + '/') ||
73
- other.prefix.startsWith(route.prefix + '/')
74
- )
75
- )
76
- )
77
- throw new Error('Invalid desktop route policy')
78
- const routes = configuredRoutes.map(({ prefix, handle }) => ({ prefix, handle }))
79
- if (options.portFile !== undefined && (typeof options.portFile !== 'string' || !options.portFile))
80
- throw new Error('Invalid desktop port file')
81
- if (
82
- options.initialPort !== undefined &&
83
- (!Number.isInteger(options.initialPort) ||
84
- options.initialPort < 1024 ||
85
- options.initialPort > 65535)
86
- )
87
- throw new Error('Invalid initial desktop port')
88
- let port = options.initialPort ?? 0
89
- let savePort = false
90
- if (options.portFile !== undefined) {
91
- try {
92
- const info = lstatSync(options.portFile)
93
- if (!info.isFile() || info.isSymbolicLink() || info.size > 6)
94
- throw new Error('Invalid desktop port file')
95
- const value = readFileSync(options.portFile, 'utf8')
96
- if (!/^[1-9]\d{3,4}\n$/.test(value) || Number(value) < 1024 || Number(value) > 65535)
97
- throw new Error('Invalid desktop port file')
98
- const savedPort = Number(value)
99
- if (options.initialPort !== undefined && options.initialPort !== savedPort)
100
- throw new Error('Saved desktop port does not match initial port')
101
- port = savedPort
102
- } catch (error) {
103
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
104
- savePort = true
105
- }
106
- }
107
- let origin = ''
108
- let gateway: ReturnType<typeof createDesktopGateway<Principal>> | undefined
109
- let streams: ReturnType<typeof createDesktopStreams<Principal>> | undefined
110
- type StreamConnection = NonNullable<
111
- ReturnType<ReturnType<typeof createDesktopStreams<Principal>>['accept']>
112
- >
113
- type SocketData = { connection?: StreamConnection }
114
- let server: ReturnType<typeof Bun.serve<SocketData>>
115
- try {
116
- server = Bun.serve<SocketData>({
117
- hostname: '127.0.0.1',
118
- port,
119
- async fetch(request, connection) {
120
- if (!origin || !gateway) return new Response(null, { status: 503 })
121
- const url = new URL(request.url)
122
- if (url.origin !== origin || request.headers.get('host') !== new URL(origin).host) {
123
- try {
124
- options.onRequest?.('rejected')
125
- } catch {
126
- /* Diagnostics must not affect requests. */
127
- }
128
- return new Response(null, { status: 403 })
129
- }
130
- if (url.pathname === '/__framework/stream') {
131
- if (
132
- !streams ||
133
- request.method !== 'GET' ||
134
- url.search ||
135
- !matchesLoopbackOrigin(
136
- {
137
- host: request.headers.get('host'),
138
- origin: request.headers.get('origin'),
139
- secFetchSite: request.headers.get('sec-fetch-site'),
140
- },
141
- createLoopbackPolicy(origin)
142
- )
143
- )
144
- return new Response(null, { status: 403 })
145
- if (connection.upgrade(request, { data: {} })) return undefined
146
- return new Response(null, { status: 400 })
147
- }
148
- const kind =
149
- url.pathname === '/__framework/bootstrap'
150
- ? 'bootstrap'
151
- : url.pathname === '/__framework/handshake'
152
- ? 'handshake'
153
- : url.pathname === '/__framework/invoke'
154
- ? 'invoke'
155
- : 'client'
156
- if (url.pathname.startsWith('/__framework/')) {
157
- // Services own their deadlines (a sidecar call can run for minutes), so an
158
- // invoke must not hit the server's 10 s idle timeout.
159
- if (kind === 'invoke') connection.timeout(request, 0)
160
- const result = await gateway.handle(request)
161
- const header = request.headers.get('origin')
162
- try {
163
- options.onRequest?.(kind, {
164
- status: result.status,
165
- origin:
166
- header === origin
167
- ? 'matching'
168
- : header === null
169
- ? 'missing'
170
- : header === 'null'
171
- ? 'opaque'
172
- : /^http:\/\/127\.0\.0\.1(?::[0-9]{1,5})?$/.test(header)
173
- ? 'same-host'
174
- : 'other',
175
- fetchSite: request.headers.get('sec-fetch-site'),
176
- })
177
- } catch {
178
- /* Diagnostics must not affect requests. */
179
- }
180
- return result
181
- }
182
- const route = routes.find(
183
- (value) => url.pathname === value.prefix || url.pathname.startsWith(value.prefix + '/')
184
- )
185
- if (route) {
186
- if (
187
- !matchesLoopbackOrigin(
188
- {
189
- host: request.headers.get('host'),
190
- origin: request.headers.get('origin'),
191
- secFetchSite: request.headers.get('sec-fetch-site'),
192
- },
193
- createLoopbackPolicy(origin)
194
- )
195
- )
196
- return new Response(null, { status: 403 })
197
- try {
198
- options.onRequest?.('route')
199
- } catch {
200
- /* Diagnostics must not affect requests. */
201
- }
202
- try {
203
- const result = await route.handle(request)
204
- return result instanceof Response ? result : new Response(null, { status: 500 })
205
- } catch {
206
- return new Response(null, { status: 500 })
207
- }
208
- }
209
- try {
210
- options.onRequest?.(kind)
211
- } catch {
212
- /* Diagnostics must not affect requests. */
213
- }
214
- if (request.method !== 'GET' && request.method !== 'HEAD')
215
- return new Response(null, { status: 405 })
216
- const result = await serveClient(request, { root: options.clientRoot })
217
- // WebView2 applies Electrobun navigation rules to top-level navigation only.
218
- // A privileged shell must not embed untrusted documents in child frames.
219
- result.headers.set(
220
- 'content-security-policy',
221
- "frame-src 'none'; frame-ancestors 'none'; object-src 'none'; base-uri 'none'"
222
- )
223
- result.headers.set('x-content-type-options', 'nosniff')
224
- result.headers.set('referrer-policy', 'no-referrer')
225
- return result
226
- },
227
- websocket: {
228
- maxPayloadLength: 256 * 1024,
229
- backpressureLimit: 1024 * 1024,
230
- closeOnBackpressureLimit: true,
231
- open(socket) {
232
- socket.data.connection = streams?.accept({
233
- send: (payload) => socket.send(payload) > 0,
234
- close: () => socket.close(),
235
- })
236
- if (!socket.data.connection) socket.close()
237
- },
238
- message(socket, message) {
239
- void socket.data.connection?.receive(message)
240
- },
241
- close(socket) {
242
- socket.data.connection?.close()
243
- },
244
- },
245
- })
246
- } catch (error) {
247
- if ((error as NodeJS.ErrnoException)?.code === 'EADDRINUSE')
248
- throw new DesktopPortInUseError(error)
249
- throw error
250
- }
251
- if (options.portFile !== undefined && savePort) {
252
- try {
253
- writeFileSync(options.portFile, `${server.port}\n`, { flag: 'wx', mode: 0o600 })
254
- } catch (error) {
255
- server.stop(true)
256
- throw error
257
- }
258
- }
259
- origin = `http://127.0.0.1:${server.port}`
260
- const authority = createChannelAuthority<Principal>()
261
- if (options.configureStreams) {
262
- streams = createDesktopStreams({ authority })
263
- try {
264
- options.configureStreams(streams)
265
- } catch (error) {
266
- streams.stop()
267
- server.stop(true)
268
- throw error
269
- }
270
- }
271
- const grant = createNativeWindowGrant({ origin, authority, principal: options.principal })
272
- gateway = createDesktopGateway({
273
- origin,
274
- authority,
275
- services: options.services,
276
- windowGrant: grant,
277
- })
278
- let window: Window | undefined
279
- let stopped = false
280
- const stop = () => {
281
- if (stopped) return
282
- stopped = true
283
- streams?.stop()
284
- grant.revoke()
285
- server.stop(true)
286
- window?.close()
287
- }
288
- try {
289
- window = createSecureWindow({
290
- origin,
291
- grant,
292
- renderer: options.renderer,
293
- platform: options.platform,
294
- title: options.title,
295
- frame: options.frame,
296
- transparent: options.transparent,
297
- hidden: options.hidden,
298
- construct: options.construct,
299
- })
300
- window.on('close', stop)
301
- // Revoke live window channels when the app's authorization scope changes.
302
- // The native window grant remains valid so the client can reconnect.
303
- return { origin, window, stop, revokeChannels: () => authority.revokeAll() }
304
- } catch (error) {
305
- stop()
306
- throw error
307
- }
308
- }
309
-
310
- /** Retry only a failed loopback bind while the previous process exits. */
311
- export async function startDesktopHostWithRetry<Principal, Window extends NativeWindow>(
312
- options: Parameters<typeof startDesktopHost<Principal, Window>>[0],
313
- retry: { timeoutMs?: number; intervalMs?: number } = {}
314
- ) {
315
- const timeoutMs = retry.timeoutMs ?? 30000,
316
- intervalMs = retry.intervalMs ?? 250
317
- if (
318
- !Number.isSafeInteger(timeoutMs) ||
319
- timeoutMs < 1 ||
320
- timeoutMs > 120000 ||
321
- !Number.isSafeInteger(intervalMs) ||
322
- intervalMs < 1 ||
323
- intervalMs > 5000
324
- )
325
- throw new Error('Invalid desktop bind retry policy')
326
- const deadline = performance.now() + timeoutMs
327
- for (;;) {
328
- try {
329
- return startDesktopHost(options)
330
- } catch (error) {
331
- if (!(error instanceof DesktopPortInUseError) || performance.now() >= deadline) throw error
332
- await Bun.sleep(Math.min(intervalMs, Math.max(1, deadline - performance.now())))
333
- }
334
- }
335
- }
@@ -1,324 +0,0 @@
1
- import {
2
- createChannelProofVerifier,
3
- type ChannelIdentity,
4
- type SignedRequest,
5
- } from './channel-proof'
6
- import type { createChannelAuthority } from './channel-handshake'
7
-
8
- type Payload = string | Uint8Array
9
- function payloadSize(payload: Payload): number {
10
- return typeof payload === 'string'
11
- ? new TextEncoder().encode(payload).byteLength
12
- : payload.byteLength
13
- }
14
- type StreamHandler = { receive(payload: Payload): void | Promise<void>; close(): void }
15
- type StreamProvider<Principal> = {
16
- parse(value: unknown): unknown
17
- authorize(principal: Principal, input: unknown): boolean | Promise<boolean>
18
- open(
19
- principal: Principal,
20
- input: unknown,
21
- context: {
22
- signal: AbortSignal
23
- send(payload: Payload): boolean
24
- current(): boolean
25
- close(): void
26
- }
27
- ): StreamHandler | Promise<StreamHandler>
28
- }
29
- type Socket = { send(payload: Payload): boolean; close(): void }
30
-
31
- /** Application-owned stream authorization and lifecycle, independent of the socket implementation. */
32
- export function createDesktopStreams<Principal>(options: {
33
- authority: ReturnType<typeof createChannelAuthority<Principal>>
34
- now?: () => number
35
- handshakeTimeoutMs?: number
36
- maxConnections?: number
37
- maxFrameBytes?: number
38
- }) {
39
- const now = options.now ?? Date.now
40
- const timeout = options.handshakeTimeoutMs ?? 5000
41
- const limit = options.maxConnections ?? 32
42
- const maxFrameBytes = options.maxFrameBytes ?? 256 * 1024
43
- if (![timeout, limit, maxFrameBytes].every((value) => Number.isSafeInteger(value) && value > 0))
44
- throw new Error('Invalid stream limits')
45
- const verifier = createChannelProofVerifier({
46
- resolve: options.authority.resolve,
47
- now,
48
- context: 'framework-stream-attach-v1',
49
- maxBodyBytes: 4096,
50
- })
51
- const providers = new Map<string, StreamProvider<Principal>>()
52
- const connections = new Set<{
53
- identity?: ChannelIdentity
54
- provider?: StreamProvider<Principal>
55
- close(): void
56
- }>()
57
- const unsubscribe = options.authority.onRevoke((identity) => {
58
- for (const connection of connections)
59
- if (
60
- connection.identity?.channelId === identity.channelId &&
61
- connection.identity.credentialId === identity.credentialId
62
- )
63
- connection.close()
64
- })
65
- let stopped = false
66
- return {
67
- register(name: string, provider: StreamProvider<Principal>) {
68
- if (
69
- stopped ||
70
- !/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(name) ||
71
- name.length > 128 ||
72
- providers.has(name) ||
73
- typeof provider.parse !== 'function' ||
74
- typeof provider.authorize !== 'function' ||
75
- typeof provider.open !== 'function'
76
- )
77
- throw new Error('Invalid stream provider')
78
- providers.set(name, provider)
79
- return () => {
80
- if (providers.get(name) !== provider) return
81
- providers.delete(name)
82
- for (const connection of connections)
83
- if (connection.provider === provider) connection.close()
84
- }
85
- },
86
- accept(socket: Socket) {
87
- if (stopped || connections.size >= limit) {
88
- socket.close()
89
- return undefined
90
- }
91
- let closed = false,
92
- identity: ChannelIdentity | undefined,
93
- principal: Principal | undefined,
94
- handler: StreamHandler | undefined,
95
- phase: 'attach' | 'opening' | 'open' = 'attach',
96
- busy = false
97
- let queue = Promise.resolve(),
98
- queuedBytes = 0,
99
- queuedCount = 0
100
- const outbound: Payload[] = []
101
- let outboundBytes = 0
102
- const abort = new AbortController()
103
- let expiry: ReturnType<typeof setTimeout> | undefined
104
- const current = () => {
105
- if (closed || !identity) return false
106
- const channel = options.authority.resolve(identity)
107
- return !!channel && channel.expiresAt > now() && Object.is(channel.principal, principal)
108
- }
109
- const close = () => {
110
- if (closed) return
111
- closed = true
112
- clearTimeout(timer)
113
- if (expiry) clearTimeout(expiry)
114
- connections.delete(connection)
115
- abort.abort()
116
- try {
117
- handler?.close()
118
- } catch {
119
- /* cleanup must continue */
120
- }
121
- try {
122
- socket.close()
123
- } catch {
124
- /* socket may already be closed */
125
- }
126
- }
127
- const connection: {
128
- identity?: ChannelIdentity
129
- provider?: StreamProvider<Principal>
130
- close(): void
131
- } = { close }
132
- const timer = setTimeout(close, timeout)
133
- connections.add(connection)
134
- const send = (payload: Payload) => {
135
- if (
136
- !current() ||
137
- (typeof payload !== 'string' && !(payload instanceof Uint8Array)) ||
138
- payloadSize(payload) > maxFrameBytes
139
- ) {
140
- close()
141
- return false
142
- }
143
- if (phase === 'opening') {
144
- if (outbound.length >= 64 || outboundBytes + payloadSize(payload) > 1024 * 1024) {
145
- close()
146
- return false
147
- }
148
- const copy = typeof payload === 'string' ? payload : Uint8Array.from(payload)
149
- outbound.push(copy)
150
- outboundBytes += payloadSize(copy)
151
- return true
152
- }
153
- if (phase !== 'open') {
154
- close()
155
- return false
156
- }
157
- try {
158
- if (socket.send(payload) === true) return true
159
- } catch {
160
- /* closed or backpressured */
161
- }
162
- close()
163
- return false
164
- }
165
- return {
166
- close,
167
- async receive(payload: Payload) {
168
- if (closed) return
169
- if (phase === 'open') {
170
- if (
171
- (typeof payload !== 'string' && !(payload instanceof Uint8Array)) ||
172
- payloadSize(payload) > maxFrameBytes ||
173
- queuedCount >= 64 ||
174
- queuedBytes + payloadSize(payload) > 1024 * 1024
175
- ) {
176
- close()
177
- return
178
- }
179
- // Socket buffers are not owned by providers once the callback returns.
180
- const copy = typeof payload === 'string' ? payload : Uint8Array.from(payload)
181
- const bytes = payloadSize(copy)
182
- queuedCount++
183
- queuedBytes += bytes
184
- const task = queue
185
- .then(async () => {
186
- if (!current()) {
187
- close()
188
- return
189
- }
190
- await handler!.receive(copy)
191
- })
192
- .catch(() => {
193
- close()
194
- })
195
- .finally(() => {
196
- queuedCount--
197
- queuedBytes -= bytes
198
- })
199
- queue = task
200
- await task
201
- return
202
- }
203
- if (
204
- (typeof payload !== 'string' && !(payload instanceof Uint8Array)) ||
205
- payloadSize(payload) > (phase === 'attach' ? 8192 : maxFrameBytes) ||
206
- busy
207
- ) {
208
- close()
209
- return
210
- }
211
- busy = true
212
- try {
213
- if (phase === 'attach') {
214
- if (typeof payload !== 'string') {
215
- close()
216
- return
217
- }
218
- let request: SignedRequest
219
- try {
220
- request = JSON.parse(payload) as SignedRequest
221
- } catch {
222
- close()
223
- return
224
- }
225
- const result = verifier.verify(request)
226
- if (!result.ok) {
227
- close()
228
- return
229
- }
230
- let input: { name?: unknown; input?: unknown }
231
- try {
232
- input = JSON.parse(request.body) as typeof input
233
- } catch {
234
- close()
235
- return
236
- }
237
- if (
238
- !input ||
239
- typeof input !== 'object' ||
240
- Array.isArray(input) ||
241
- typeof input.name !== 'string'
242
- ) {
243
- close()
244
- return
245
- }
246
- const provider = providers.get(input.name)
247
- if (!provider) {
248
- close()
249
- return
250
- }
251
- connection.provider = provider
252
- let parsed: unknown
253
- try {
254
- parsed = provider.parse(input.input)
255
- } catch {
256
- close()
257
- return
258
- }
259
- identity = { channelId: request.channelId, credentialId: request.credentialId }
260
- connection.identity = identity
261
- principal = result.principal
262
- phase = 'opening'
263
- if (
264
- !current() ||
265
- (await provider.authorize(result.principal, parsed)) !== true ||
266
- !current() ||
267
- providers.get(input.name) !== provider
268
- ) {
269
- close()
270
- return
271
- }
272
- const channel = options.authority.resolve(identity)
273
- if (!channel) {
274
- close()
275
- return
276
- }
277
- expiry = setTimeout(close, Math.min(channel.expiresAt - now(), 2147483647))
278
- const opened = await provider.open(result.principal, parsed, {
279
- signal: abort.signal,
280
- send,
281
- current,
282
- close,
283
- })
284
- if (
285
- !opened ||
286
- typeof opened.receive !== 'function' ||
287
- typeof opened.close !== 'function'
288
- ) {
289
- close()
290
- return
291
- }
292
- if (!current()) {
293
- try {
294
- opened.close()
295
- } catch {
296
- /* already closed */
297
- }
298
- close()
299
- return
300
- }
301
- handler = opened
302
- phase = 'open'
303
- clearTimeout(timer)
304
- if (!send(JSON.stringify({ ok: true }))) return
305
- for (const value of outbound.splice(0)) if (!send(value)) return
306
- outboundBytes = 0
307
- } else close()
308
- } catch {
309
- close()
310
- } finally {
311
- busy = false
312
- }
313
- },
314
- }
315
- },
316
- stop() {
317
- if (stopped) return
318
- stopped = true
319
- unsubscribe()
320
- for (const connection of connections) connection.close()
321
- providers.clear()
322
- },
323
- }
324
- }
@@ -1,41 +0,0 @@
1
- /** Origin screening adapted from adea-ai/adea channel/loopback.ts and shell boot,
2
- * commit 6155d18941acbb14d9099bc2a33a50ee9683a068 (Apache-2.0).
3
- * Headers are not authentication: a local process can forge all of them.
4
- * Never disclose credentials or dispatch privileged commands on this basis alone. */
5
- export type LoopbackPolicy = Readonly<{ origin: string; host: string }>
6
- export type RequestMetadata = Readonly<{
7
- host?: string | null
8
- origin?: string | null
9
- secFetchSite?: string | null
10
- secFetchDest?: string | null
11
- }>
12
-
13
- export function createLoopbackPolicy(origin: string): LoopbackPolicy {
14
- const match = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})\/?$/.exec(origin)
15
- if (!match || Number(match[1]) === 80 || Number(match[1]) > 65535)
16
- throw new Error('Invalid loopback origin')
17
- const host = `127.0.0.1:${match[1]}`
18
- return Object.freeze({ origin: `http://${host}`, host })
19
- }
20
-
21
- /** Screen out foreign Host, Origin and browser fetch-site metadata before authentication. */
22
- export function matchesLoopbackOrigin(request: RequestMetadata, policy: LoopbackPolicy): boolean {
23
- if (request.host !== policy.host) return false
24
- if (request.secFetchSite && !['same-origin', 'none'].includes(request.secFetchSite)) return false
25
- if (request.origin === policy.origin) return true
26
- if (request.origin !== null && request.origin !== undefined) return false
27
- return request.secFetchSite === 'same-origin'
28
- }
29
-
30
- /** Classify document requests for rendering only; this is not proof of a trusted window. */
31
- export function isDocumentNavigationRequest(
32
- request: RequestMetadata,
33
- policy: LoopbackPolicy
34
- ): boolean {
35
- return (
36
- request.host === policy.host &&
37
- request.secFetchDest === 'document' &&
38
- (request.secFetchSite === 'none' || request.secFetchSite === 'same-origin') &&
39
- (request.origin === undefined || request.origin === null || request.origin === policy.origin)
40
- )
41
- }