GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — chore (stackpress-desktop): harden desktop event dispatch and compile… · stackpress/stackpress@b711b13

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/stackpress-desktop
    • src
      • events
        • build.ts
      • runtime.ts
      • scripts
        • build.ts
        • main.ts
        • package.ts
    • tests
      • MenuRegistry.test.ts
      • build-event.test.ts
      • package-event.test.ts
      • plugin.test.ts
      • runtime-route-guard.test.ts
      • runtime.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/stackpress-desktop/src/events/build.ts‎

Copy file name to clipboardExpand all lines: packages/stackpress-desktop/src/events/build.ts
+27-5Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,16 @@ import { action } from '@stackpress/ingest/Server';
33

44
//client
55
import { normalizeDesktopConfig } from '../config.js';
6+
import MenuRegistry from '../MenuRegistry.js';
7+
import {
8+
getDesktopPlugin,
9+
markDesktopInitialized
10+
} from '../plugin.js';
611
import { collectDesktopRoutes } from '../routeRules.js';
712
import { writeDesktopBuildOutput } from '../scripts/build.js';
813
import type {
914
DesktopBuildOutput,
15+
DesktopCompiledMenuGroup,
1016
DesktopConfig,
1117
DesktopRouteRecord,
1218
NormalizedDesktopConfig
@@ -26,6 +32,7 @@ type DesktopBuildTerminal = {
2632
// and whether the normal Stackpress build lifecycle should run.
2733
export type CreateDesktopBuildOutputOptions = {
2834
cwd?: string;
35+
menu?: DesktopCompiledMenuGroup[];
2936
registeredRoutes?: DesktopRouteRecord[];
3037
runStackpressBuild?: () => Promise<unknown>;
3138
};
@@ -44,6 +51,7 @@ export async function createDesktopBuildOutput(
4451
//then write the desktop manifest and generated Electron entry files
4552
return await writeDesktopBuildOutput(config, {
4653
cwd: options.cwd,
54+
menu: options.menu,
4755
registeredRoutes: options.registeredRoutes
4856
});
4957
}
@@ -53,12 +61,21 @@ export async function createDesktopBuildOutput(
5361
*/
5462
export default action(async function DesktopBuild({ res, ctx }) {
5563
const terminal = ctx.plugin<DesktopBuildTerminal>('terminal');
64+
const desktop = getDesktopPlugin(ctx);
5665

57-
//read desktop config from the Stackpress config tree and normalize it before
58-
// writing build artifacts.
59-
const config = normalizeDesktopConfig(
60-
ctx.config.path<DesktopConfig>('desktop', {})
61-
);
66+
//load base config from the Stackpress config tree before contribution hooks
67+
desktop.config = ctx.config.path<DesktopConfig>('desktop', {});
68+
await ctx.resolve('desktop:config');
69+
70+
//normalize config after contribution hooks have applied all patches
71+
const config = normalizeDesktopConfig(desktop.config);
72+
desktop.config = config;
73+
74+
//collect menu contributions before packaged Electron source is generated
75+
await ctx.resolve('desktop:menu');
76+
const menu = desktop.menu instanceof MenuRegistry
77+
? desktop.menu.compile()
78+
: [];
6279
const registeredRoutes = collectDesktopRoutes(ctx);
6380

6481
//verbose mode mirrors the existing terminal plugin convention
@@ -69,10 +86,15 @@ export default action(async function DesktopBuild({ res, ctx }) {
6986
//create the output after running the normal build lifecycle
7087
const output = await createDesktopBuildOutput(config, {
7188
cwd: ctx.loader.cwd,
89+
menu,
7290
registeredRoutes,
7391
runStackpressBuild: async () => await ctx.resolve('build')
7492
});
7593

94+
//after build artifacts are generated, late desktop contributions would desync
95+
// packaged source from plugin state.
96+
markDesktopInitialized(ctx);
97+
7698
//report output location and store the build payload on the response
7799
terminal?.verbose && terminal.control?.success(
78100
`Desktop build output written to ${output.manifestPath}`
Collapse file

‎packages/stackpress-desktop/src/runtime.ts‎

Copy file name to clipboardExpand all lines: packages/stackpress-desktop/src/runtime.ts
+117-9Lines changed: 117 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
ServerResponse
77
} from 'node:http';
88
import { spawn } from 'node:child_process';
9+
import { randomBytes } from 'node:crypto';
910
import fs from 'node:fs/promises';
1011
import path from 'node:path';
1112

@@ -40,6 +41,8 @@ export type DesktopRuntimeServer = Pick<Server<any, any, any>, 'create'>
4041
//A started desktop runtime session owns the loopback HTTP service and its
4142
// teardown function.
4243
export type DesktopRuntimeSession = {
44+
allowDesktopEvents: (events: Iterable<string>) => void;
45+
desktopEventToken: string;
4346
host: string;
4447
port: number;
4548
url: string;
@@ -83,6 +86,21 @@ export type DesktopElectronLaunchOptions = {
8386
spawn?: DesktopElectronSpawn;
8487
};
8588

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+
86104
type ElectronPackage = {
87105
default?: unknown;
88106
};
@@ -95,6 +113,36 @@ export type DesktopMenuDispatch = (event: string) => void | Promise<void>;
95113
// into the local Stackpress runtime.
96114
export const DESKTOP_EVENT_ROUTE = '/__stackpress_desktop_event';
97115

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+
98146
/**
99147
* Decide whether a URL points outside the active desktop app origin.
100148
*/
@@ -229,9 +277,7 @@ export function isDesktopRouteAllowed(
229277
*/
230278
export async function writeDesktopRuntimeFiles(
231279
config: NormalizedDesktopConfig,
232-
runtime: Pick<DesktopRuntimeSession, 'url'> & {
233-
menu?: DesktopCompiledMenuGroup[];
234-
},
280+
runtime: DesktopRuntimeFileSession,
235281
cwd = process.cwd()
236282
): Promise<DesktopRuntimeFiles> {
237283
//resolve runtime entry targets from normalized build config
@@ -254,7 +300,10 @@ export async function writeDesktopRuntimeFiles(
254300
createElectronMainSource(config, {
255301
url: runtime.url,
256302
preload: preloadPath,
257-
menu: runtime.menu
303+
menu: runtime.menu,
304+
desktopEventToken: runtime.desktopEventToken,
305+
desktopEventEvents: runtime.desktopEventEvents
306+
|| collectDesktopMenuEvents(runtime.menu || [])
258307
})
259308
);
260309

@@ -293,13 +342,20 @@ export async function resolveElectronPath(electronPath?: string) {
293342
export async function launchDesktopElectron(
294343
config: NormalizedDesktopConfig,
295344
runtime: Pick<DesktopRuntimeSession, 'url'> & {
345+
allowDesktopEvents?: DesktopRuntimeSession['allowDesktopEvents'];
346+
desktopEventToken?: string;
296347
menu?: DesktopCompiledMenuGroup[];
297348
},
298349
options: DesktopElectronLaunchOptions = {}
299350
): Promise<DesktopElectronProcess> {
300351
//resolve filesystem and executable inputs before spawning Electron
301352
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);
303359
const electronPath = await resolveElectronPath(options.electronPath);
304360
const spawnElectron = options.spawn || spawn;
305361

@@ -343,7 +399,8 @@ export function sendBlockedDesktopRoute(
343399
export function installDesktopRouteGuard(
344400
service: HttpServer,
345401
config: NormalizedDesktopConfig,
346-
server?: DesktopRuntimeEventServer
402+
server?: DesktopRuntimeEventServer,
403+
authorization?: DesktopEventAuthorization
347404
) {
348405
const canDispatchEvents = typeof server?.resolve === 'function';
349406

@@ -367,7 +424,7 @@ export function installDesktopRouteGuard(
367424

368425
//desktop menu dispatch uses a private route before normal route guards
369426
if (route === DESKTOP_EVENT_ROUTE) {
370-
await sendDesktopEventResult(request, response, server);
427+
await sendDesktopEventResult(request, response, server, authorization);
371428
return;
372429
}
373430

@@ -391,13 +448,42 @@ export function installDesktopRouteGuard(
391448
export async function sendDesktopEventResult(
392449
request: IncomingMessage,
393450
response: ServerResponse,
394-
server?: DesktopRuntimeEventServer
451+
server?: DesktopRuntimeEventServer,
452+
authorization?: DesktopEventAuthorization
395453
) {
396454
//parse the event name from the private runtime route query string
397455
const url = new URL(request.url || '/', 'http://127.0.0.1');
398456
const event = url.searchParams.get('event');
457+
const method = request.method || 'GET';
399458
response.setHeader('Content-Type', 'application/json');
400459

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+
401487
//event is required because the route is shared by all menu contributions
402488
if (!event) {
403489
response.statusCode = 400;
@@ -409,6 +495,18 @@ export async function sendDesktopEventResult(
409495
return;
410496
}
411497

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+
412510
//without a resolver, runtime event dispatch is unavailable in this session
413511
if (!server?.resolve) {
414512
response.statusCode = 501;
@@ -451,7 +549,11 @@ export async function startDesktopRuntime(
451549
): Promise<DesktopRuntimeSession> {
452550
//create the app service through the Stackpress server boundary
453551
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);
455557
const host = config.server.host || '127.0.0.1';
456558
const requestedPort = config.server.port ?? 0;
457559

@@ -471,6 +573,12 @@ export async function startDesktopRuntime(
471573
//return the runtime session and a close hook that handles already-closed
472574
// services cleanly.
473575
return {
576+
allowDesktopEvents(events) {
577+
for (const event of events) {
578+
authorization.allowedEvents.add(event);
579+
}
580+
},
581+
desktopEventToken: authorization.token,
474582
host,
475583
port,
476584
url: resolveDesktopUrl(config, port),

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.