@@ -6,6 +6,7 @@ import type { |
6 | 6 | ServerResponse |
7 | 7 | } from 'node:http'; |
8 | 8 | import { spawn } from 'node:child_process'; |
| 9 | +import { randomBytes } from 'node:crypto'; |
9 | 10 | import fs from 'node:fs/promises'; |
10 | 11 | import path from 'node:path'; |
11 | 12 |
|
@@ -40,6 +41,8 @@ export type DesktopRuntimeServer = Pick<Server<any, any, any>, 'create'> |
40 | 41 | //A started desktop runtime session owns the loopback HTTP service and its |
41 | 42 | // teardown function. |
42 | 43 | export type DesktopRuntimeSession = { |
| 44 | + allowDesktopEvents: (events: Iterable<string>) => void; |
| 45 | + desktopEventToken: string; |
43 | 46 | host: string; |
44 | 47 | port: number; |
45 | 48 | url: string; |
@@ -83,6 +86,21 @@ export type DesktopElectronLaunchOptions = { |
83 | 86 | spawn?: DesktopElectronSpawn; |
84 | 87 | }; |
85 | 88 |
|
| 89 | +//Desktop event authorization is held by the runtime guard and updated when the |
| 90 | +// generated Electron menu source is written for the active session. |
| 91 | +type DesktopEventAuthorization = { |
| 92 | + allowedEvents: Set<string>; |
| 93 | + token: string; |
| 94 | +}; |
| 95 | + |
| 96 | +//Runtime file generation can be exercised directly in tests or through a full |
| 97 | +// runtime session that carries the private desktop event token. |
| 98 | +type DesktopRuntimeFileSession = Pick<DesktopRuntimeSession, 'url'> & { |
| 99 | + desktopEventEvents?: string[]; |
| 100 | + desktopEventToken?: string; |
| 101 | + menu?: DesktopCompiledMenuGroup[]; |
| 102 | +}; |
| 103 | + |
86 | 104 | type ElectronPackage = { |
87 | 105 | default?: unknown; |
88 | 106 | }; |
@@ -95,6 +113,36 @@ export type DesktopMenuDispatch = (event: string) => void | Promise<void>; |
95 | 113 | // into the local Stackpress runtime. |
96 | 114 | export const DESKTOP_EVENT_ROUTE = '/__stackpress_desktop_event'; |
97 | 115 |
|
| 116 | +//Private desktop event requests must prove they came from generated Electron |
| 117 | +// menu code for the current runtime session. |
| 118 | +export const DESKTOP_EVENT_TOKEN_HEADER = 'x-stackpress-desktop-event-token'; |
| 119 | + |
| 120 | +/** |
| 121 | + * Collect unique event names from compiled desktop menu groups. |
| 122 | + */ |
| 123 | +export function collectDesktopMenuEvents(groups: DesktopCompiledMenuGroup[]) { |
| 124 | + const events = new Set<string>(); |
| 125 | + |
| 126 | + /** |
| 127 | + * Walk a menu contribution tree and remember every event-backed item. |
| 128 | + */ |
| 129 | + function collect(items: DesktopMenuContribution[]) { |
| 130 | + for (const item of items) { |
| 131 | + if (item.event) { |
| 132 | + events.add(item.event); |
| 133 | + } |
| 134 | + if (item.submenu?.length) { |
| 135 | + collect(item.submenu); |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + for (const group of groups) { |
| 141 | + collect(group.items); |
| 142 | + } |
| 143 | + return [ ...events ]; |
| 144 | +} |
| 145 | + |
98 | 146 | /** |
99 | 147 | * Decide whether a URL points outside the active desktop app origin. |
100 | 148 | */ |
@@ -229,9 +277,7 @@ export function isDesktopRouteAllowed( |
229 | 277 | */ |
230 | 278 | export async function writeDesktopRuntimeFiles( |
231 | 279 | config: NormalizedDesktopConfig, |
232 | | - runtime: Pick<DesktopRuntimeSession, 'url'> & { |
233 | | - menu?: DesktopCompiledMenuGroup[]; |
234 | | - }, |
| 280 | + runtime: DesktopRuntimeFileSession, |
235 | 281 | cwd = process.cwd() |
236 | 282 | ): Promise<DesktopRuntimeFiles> { |
237 | 283 | //resolve runtime entry targets from normalized build config |
@@ -254,7 +300,10 @@ export async function writeDesktopRuntimeFiles( |
254 | 300 | createElectronMainSource(config, { |
255 | 301 | url: runtime.url, |
256 | 302 | preload: preloadPath, |
257 | | - menu: runtime.menu |
| 303 | + menu: runtime.menu, |
| 304 | + desktopEventToken: runtime.desktopEventToken, |
| 305 | + desktopEventEvents: runtime.desktopEventEvents |
| 306 | + || collectDesktopMenuEvents(runtime.menu || []) |
258 | 307 | }) |
259 | 308 | ); |
260 | 309 |
|
@@ -293,13 +342,20 @@ export async function resolveElectronPath(electronPath?: string) { |
293 | 342 | export async function launchDesktopElectron( |
294 | 343 | config: NormalizedDesktopConfig, |
295 | 344 | runtime: Pick<DesktopRuntimeSession, 'url'> & { |
| 345 | + allowDesktopEvents?: DesktopRuntimeSession['allowDesktopEvents']; |
| 346 | + desktopEventToken?: string; |
296 | 347 | menu?: DesktopCompiledMenuGroup[]; |
297 | 348 | }, |
298 | 349 | options: DesktopElectronLaunchOptions = {} |
299 | 350 | ): Promise<DesktopElectronProcess> { |
300 | 351 | //resolve filesystem and executable inputs before spawning Electron |
301 | 352 | const cwd = options.cwd || process.cwd(); |
302 | | - const files = await writeDesktopRuntimeFiles(config, runtime, cwd); |
| 353 | + const desktopEventEvents = collectDesktopMenuEvents(runtime.menu || []); |
| 354 | + runtime.allowDesktopEvents?.(desktopEventEvents); |
| 355 | + const files = await writeDesktopRuntimeFiles(config, { |
| 356 | + ...runtime, |
| 357 | + desktopEventEvents |
| 358 | + }, cwd); |
303 | 359 | const electronPath = await resolveElectronPath(options.electronPath); |
304 | 360 | const spawnElectron = options.spawn || spawn; |
305 | 361 |
|
@@ -343,7 +399,8 @@ export function sendBlockedDesktopRoute( |
343 | 399 | export function installDesktopRouteGuard( |
344 | 400 | service: HttpServer, |
345 | 401 | config: NormalizedDesktopConfig, |
346 | | - server?: DesktopRuntimeEventServer |
| 402 | + server?: DesktopRuntimeEventServer, |
| 403 | + authorization?: DesktopEventAuthorization |
347 | 404 | ) { |
348 | 405 | const canDispatchEvents = typeof server?.resolve === 'function'; |
349 | 406 |
|
@@ -367,7 +424,7 @@ export function installDesktopRouteGuard( |
367 | 424 |
|
368 | 425 | //desktop menu dispatch uses a private route before normal route guards |
369 | 426 | if (route === DESKTOP_EVENT_ROUTE) { |
370 | | - await sendDesktopEventResult(request, response, server); |
| 427 | + await sendDesktopEventResult(request, response, server, authorization); |
371 | 428 | return; |
372 | 429 | } |
373 | 430 |
|
@@ -391,13 +448,42 @@ export function installDesktopRouteGuard( |
391 | 448 | export async function sendDesktopEventResult( |
392 | 449 | request: IncomingMessage, |
393 | 450 | response: ServerResponse, |
394 | | - server?: DesktopRuntimeEventServer |
| 451 | + server?: DesktopRuntimeEventServer, |
| 452 | + authorization?: DesktopEventAuthorization |
395 | 453 | ) { |
396 | 454 | //parse the event name from the private runtime route query string |
397 | 455 | const url = new URL(request.url || '/', 'http://127.0.0.1'); |
398 | 456 | const event = url.searchParams.get('event'); |
| 457 | + const method = request.method || 'GET'; |
399 | 458 | response.setHeader('Content-Type', 'application/json'); |
400 | 459 |
|
| 460 | + //menu dispatch is intentionally not a navigable/readable route |
| 461 | + if (method.toUpperCase() !== 'POST') { |
| 462 | + response.statusCode = 405; |
| 463 | + response.setHeader('Allow', 'POST'); |
| 464 | + response.end(JSON.stringify({ |
| 465 | + code: 405, |
| 466 | + status: 'Method Not Allowed', |
| 467 | + error: 'Desktop menu events require POST.' |
| 468 | + })); |
| 469 | + return; |
| 470 | + } |
| 471 | + |
| 472 | + //the per-session token keeps unrelated loopback web pages from invoking |
| 473 | + // events even though they can reach the local server port. |
| 474 | + const token = request.headers[DESKTOP_EVENT_TOKEN_HEADER]; |
| 475 | + const isAuthorized = typeof token === 'string' |
| 476 | + && token === authorization?.token; |
| 477 | + if (!isAuthorized) { |
| 478 | + response.statusCode = 401; |
| 479 | + response.end(JSON.stringify({ |
| 480 | + code: 401, |
| 481 | + status: 'Unauthorized', |
| 482 | + error: 'Desktop menu event authorization failed.' |
| 483 | + })); |
| 484 | + return; |
| 485 | + } |
| 486 | + |
401 | 487 | //event is required because the route is shared by all menu contributions |
402 | 488 | if (!event) { |
403 | 489 | response.statusCode = 400; |
@@ -409,6 +495,18 @@ export async function sendDesktopEventResult( |
409 | 495 | return; |
410 | 496 | } |
411 | 497 |
|
| 498 | + //only events emitted by the generated Electron menu for this session are |
| 499 | + // eligible for Stackpress dispatch. |
| 500 | + if (!authorization.allowedEvents.has(event)) { |
| 501 | + response.statusCode = 403; |
| 502 | + response.end(JSON.stringify({ |
| 503 | + code: 403, |
| 504 | + status: 'Forbidden', |
| 505 | + error: 'Desktop menu event is not registered for this session.' |
| 506 | + })); |
| 507 | + return; |
| 508 | + } |
| 509 | + |
412 | 510 | //without a resolver, runtime event dispatch is unavailable in this session |
413 | 511 | if (!server?.resolve) { |
414 | 512 | response.statusCode = 501; |
@@ -451,7 +549,11 @@ export async function startDesktopRuntime( |
451 | 549 | ): Promise<DesktopRuntimeSession> { |
452 | 550 | //create the app service through the Stackpress server boundary |
453 | 551 | const service = server.create() as HttpServer; |
454 | | - installDesktopRouteGuard(service, config, server); |
| 552 | + const authorization: DesktopEventAuthorization = { |
| 553 | + allowedEvents: new Set<string>(), |
| 554 | + token: randomBytes(32).toString('base64url') |
| 555 | + }; |
| 556 | + installDesktopRouteGuard(service, config, server, authorization); |
455 | 557 | const host = config.server.host || '127.0.0.1'; |
456 | 558 | const requestedPort = config.server.port ?? 0; |
457 | 559 |
|
@@ -471,6 +573,12 @@ export async function startDesktopRuntime( |
471 | 573 | //return the runtime session and a close hook that handles already-closed |
472 | 574 | // services cleanly. |
473 | 575 | return { |
| 576 | + allowDesktopEvents(events) { |
| 577 | + for (const event of events) { |
| 578 | + authorization.allowedEvents.add(event); |
| 579 | + } |
| 580 | + }, |
| 581 | + desktopEventToken: authorization.token, |
474 | 582 | host, |
475 | 583 | port, |
476 | 584 | url: resolveDesktopUrl(config, port), |
|