diff --git a/docs/contracts.md b/docs/contracts.md index c8b7f07b5..d7387a576 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -164,8 +164,13 @@ failure from a previous navigation cannot reload the new page. `dev:network` and `dev:setNetwork` (`shared/ipc/devNetwork.ts`) carry the phone preview: whether the project's dev server listens on the local network (`--host 0.0.0.0`) or on 127.0.0.1 only. The request -names the project and a mode, `local` or `network`; the state is `off`, or `on` with the server's port and -at most eight IPv4 addresses with their interface names; a refused change is one of five failure codes +names the project and a mode, `local` or `network`, and on the network an access, `open` (anyone on it) or +`key` (only the devices that scan the code); the state is `off`, or `on` with the server's port, at most +eight IPv4 addresses with their interface names and the access, which for `key` carries the key the code +holds (43 base64url characters). Main makes a new key each time `key` is chosen, keeps it in memory only +and gives it to the dev server in `STACKI_PREVIEW_KEY`; the guard answers the code's address with an +`HttpOnly` cookie and a redirect without the key, lets that cookie in, and refuses every other request +from the network with 403, Vite's live-reload WebSocket included. A refused change is one of five failure codes (`no-address`, `no-server`, `external`, `busy`, `restart-failed`), each a toast in the renderer. The mode lives in main for the running app only: it is never written, it is off at launch, and `stop()` (project close, quit) clears it. The canvas, thumbnails and main's own requests keep the loopback address in both diff --git a/electron/handlers/devServers.ts b/electron/handlers/devServers.ts index c2557c19a..94569a9f6 100644 --- a/electron/handlers/devServers.ts +++ b/electron/handlers/devServers.ts @@ -7,6 +7,7 @@ import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import { execFile, type ChildProcess } from 'child_process'; +import { randomBytes } from 'crypto'; import { assert } from '../../shared/core/assert'; import { toRecord } from '../../shared/core/record'; import type { IpcResults } from '../../shared/ipc/ipcResults'; @@ -46,7 +47,18 @@ import { configOf } from '../../shared/properties/projectFolders'; import type { Thumbnails } from './thumbnails'; import { devServerArgs, devServerURL, networkAllowedHosts } from '../preview/devServerArgs'; import { selectLanAddresses, type InterfaceTable } from '../preview/lanAddresses'; -import { DEV_NETWORK_OFF, type DevNetworkMode, type DevNetworkReply, type DevNetworkState } from '../../shared/ipc/devNetwork'; +import { + DEV_NETWORK_OFF, + NETWORK_ACCESS_OPEN, + PREVIEW_KEY_ENV, + toPreviewKey, + type DevNetworkMode, + type DevNetworkReply, + type DevNetworkRequest, + type DevNetworkState, + type NetworkAccess, + type PreviewKey, +} from '../../shared/ipc/devNetwork'; import { err, ok } from '../../shared/core/result'; // Subscribe before sending the stop signal so a fast exit cannot be missed. @@ -119,6 +131,13 @@ const TOUCHABLE_FILE = /\.(astro|md|mdx)$/i; /** A touch that gets no answer by now is left to the file watcher. */ const TOUCH_TIMEOUT_MS = 1500; +/** The key only scanned devices hold: 32 random bytes, 43 base64url characters, made new each time the option is turned on. */ +function newPreviewKey(): PreviewKey { + const key = toPreviewKey(randomBytes(32).toString('base64url')); + assert(key.length === 43, 'newPreviewKey: 32 bytes in base64url'); + return key; +} + export class DevServers { private server: DevServer | undefined = undefined; // Whether the running server's project had a content config when it started. @@ -135,6 +154,10 @@ export class DevServers { // only: never written anywhere, so it is off at every launch, and cleared when the project closes or // the app quits (stop()). A restart for any other reason (an .env change, a branch switch) keeps it. private networkProject: string | undefined = undefined; + // Who may open it from the network, while it is open there: anyone, or only the devices that scanned the + // code, with the key the code carries. Kept like networkProject, in memory only, and cleared with it; a new + // key is made each time the option is turned on (restartInMode), so an older code stops working. + private networkAccess: NetworkAccess = NETWORK_ACCESS_OPEN; // One change of mode at a time: each is a restart of the dev server, and a second toggle while one // restarts would race it. private networkChange: 'idle' | 'changing' = 'idle'; @@ -199,6 +222,7 @@ export class DevServers { // A stop that cancels is the project closing or the app quitting, never a restart (pause): the // preview goes back to this computer only (see networkProject). this.networkProject = undefined; + this.networkAccess = NETWORK_ACCESS_OPEN; } if (!this.server) { return; @@ -355,7 +379,7 @@ export class DevServers { const port = Number(new URL(server.url).port); assert(Number.isSafeInteger(port), 'networkState: the server has a port'); assert(port > 0, 'networkState: the port is positive'); - return { kind: 'on', port, addresses: selectLanAddresses(interfaces) }; + return { kind: 'on', port, addresses: selectLanAddresses(interfaces), access: this.networkAccess }; } /** @@ -363,41 +387,55 @@ export class DevServers { * restarting its dev server with the other `--host` (devServerArgs.ts). The canvas keeps its loopback * address and reconnects by itself. A restart that fails leaves the mode off and the server started * again on loopback, once; the reply says it failed, for the renderer's toast. At most two restarts. + * While it is on, asking for the other access (anyone, or only scanned devices) restarts it the same way. */ - async setNetwork(projectPath: string, mode: DevNetworkMode, interfaces: InterfaceTable = os.networkInterfaces()): Promise { + async setNetwork(request: DevNetworkRequest, interfaces: InterfaceTable = os.networkInterfaces()): Promise { // First: while a change restarts the server there is no server to judge, and the answer is "wait". if (this.networkChange === 'changing') { return err('busy'); } const server = this.server; - if (server === undefined || !sameFilesystemPath(server.projectPath, projectPath)) { + if (server === undefined || !sameFilesystemPath(server.projectPath, request.projectPath)) { return err('no-server'); } // A server the user runs themselves has no command line of ours to change. if (server.external === true) { return err('external'); } - if (this.networkMode(projectPath) === mode) { - return ok(this.networkState(projectPath, interfaces)); + if (this.runsAsAsked(request)) { + return ok(this.networkState(request.projectPath, interfaces)); } // A machine on no network has no address for a phone to open: stay local and say so. - if (mode === 'network' && selectLanAddresses(interfaces).length === 0) { + if (request.mode === 'network' && selectLanAddresses(interfaces).length === 0) { return err('no-address'); } this.networkChange = 'changing'; try { - return await this.restartInMode(server.projectPath, server.url, mode, interfaces); + return await this.restartInMode(server.projectPath, server.url, request, interfaces); } finally { this.networkChange = 'idle'; } } - private async restartInMode(projectPath: string, devUrl: string, mode: DevNetworkMode, interfaces: InterfaceTable): Promise { + /** Whether the server already runs as `request` asks: in its mode and, on the network, with its access. */ + private runsAsAsked(request: DevNetworkRequest): boolean { + if (this.networkMode(request.projectPath) !== request.mode) { + return false; + } + if (request.mode === 'local') { + return true; + } + return this.networkAccess.kind === request.access; + } + + private async restartInMode(projectPath: string, devUrl: string, request: DevNetworkRequest, interfaces: InterfaceTable): Promise { assert(this.networkChange === 'changing', 'restartInMode: one change at a time'); + const mode: DevNetworkMode = request.mode; this.networkProject = mode === 'network' ? projectPath : undefined; + this.networkAccess = request.mode === 'network' && request.access === 'key' ? { kind: 'key', key: newPreviewKey() } : NETWORK_ACCESS_OPEN; this.pushLog( mode === 'network' - ? '\n[stacki] opening the preview on the local network; restarting it with --host 0.0.0.0.\n' + ? `\n[stacki] opening the preview on the local network${this.networkAccess.kind === 'key' ? ', to the devices that scan its code' : ''}; restarting it with --host 0.0.0.0.\n` : '\n[stacki] taking the preview back to this computer only; restarting it with --host 127.0.0.1.\n', ); try { @@ -409,6 +447,7 @@ export class DevServers { } // The second and last restart: back to this computer only, the mode that started before. this.networkProject = undefined; + this.networkAccess = NETWORK_ACCESS_OPEN; try { await this.restartAt(projectPath, devUrl); } catch { @@ -418,6 +457,18 @@ export class DevServers { return err('restart-failed'); } + /** + * The key the dev server checks (previewServer/loopbackGuard.ts), in its environment and nowhere else: only + * on the network, and only while only scanned devices may open the preview. + */ + private previewKeyEnvironment(mode: DevNetworkMode): Readonly> { + const access = this.networkAccess; + if (mode === 'network' && access.kind === 'key') { + return { [PREVIEW_KEY_ENV]: access.key }; + } + return {}; + } + /** The generated config's path, or undefined when the dev server runs without it. `networkHosts`: the hosts Vite answers to on the local network, only in that mode. */ writeMarkerConfig(projectPath: string, networkHosts?: readonly string[]): string | undefined { try { @@ -504,6 +555,7 @@ export class DevServers { // The mode belongs to the project that turned it on: another project starts on this computer only. if (this.networkProject !== undefined && !sameFilesystemPath(this.networkProject, projectPath)) { this.networkProject = undefined; + this.networkAccess = NETWORK_ACCESS_OPEN; } this.stop(false); this.logBuffer = []; @@ -580,7 +632,7 @@ export class DevServers { const args = devServerArgs({ port, mode, configPath: markerConfig ? toPosix(path.relative(projectPath, markerConfig)) : undefined, force }); const startedAtMs = Date.now(); - const extra = this.previewEnvironment(fs.realpathSync(projectPath)); + const extra = { ...this.previewEnvironment(fs.realpathSync(projectPath)), ...this.previewKeyEnvironment(mode) }; const proc = spawnAstroServer(projectPath, localBin, args, extra); // Loopback in every mode: the canvas, thumbnails and main's own requests never change address. @@ -740,7 +792,7 @@ export function registerDevServerHandlers({ ipcMain.handle('dev:network', (_event, projectPath) => devServers.networkState(projectPath)); - ipcMain.handle('dev:setNetwork', (_event, request) => devServers.setNetwork(request.projectPath, request.mode)); + ipcMain.handle('dev:setNetwork', (_event, request) => devServers.setNetwork(request)); ipcMain.handle('dev:diagnose', async (_event, projectPath) => { const nodePath = resolveNodeBin() ?? undefined; diff --git a/electron/preview/markerConfig.ts b/electron/preview/markerConfig.ts index abf765f4a..23ae41148 100644 --- a/electron/preview/markerConfig.ts +++ b/electron/preview/markerConfig.ts @@ -342,7 +342,7 @@ import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; const require = createRequire(import.meta.url); // Marking happens in electron/previewServer/previewMarkers.ts, in memory: it reads project // files and returns strings, and nothing it returns is ever written back. -const { loopbackGuardMiddleware, markCanvasSourceFile, markChunkFile, scanStyleBlocks, variantScopeMiddleware } = require(`, +const { loopbackGuardMiddleware, loopbackGuardUpgrade, markCanvasSourceFile, markChunkFile, scanStyleBlocks, variantScopeMiddleware } = require(`, `); const componentPreviewModule = `, `; @@ -756,11 +756,14 @@ const avbAllowedHosts = (own) => { // Stacki's own routes (/__avb/*, /studio, Vite's /__open-in-editor) answer this computer only, in every // mode: the guard runs before any of them and before Vite's own middleware (previewServer/loopbackGuard.ts). // First among the plugins and enforce:'pre', so its configureServer adds the first middleware of ours. +// With a preview key, the same guard keeps a device that did not scan the code out of the site and of the +// live-reload WebSocket, whose upgrade never reaches a middleware: its listener goes before Vite's. const avbLoopbackGuard = { name: 'avb-loopback-guard', enforce: 'pre', configureServer(server) { server.middlewares.use(loopbackGuardMiddleware); + server.httpServer?.prependListener('upgrade', loopbackGuardUpgrade); }, }; diff --git a/electron/previewServer/loopbackGuard.ts b/electron/previewServer/loopbackGuard.ts index 0ee40f1e1..6c001131b 100644 --- a/electron/previewServer/loopbackGuard.ts +++ b/electron/previewServer/loopbackGuard.ts @@ -17,17 +17,33 @@ // rest of the network. All three hold in both modes: on loopback alone they cost nothing, since every // request the app makes already passes them. // -// A request from the network to any other route is the site, and passes. The hover-preview header -// (previewMarkers.ts variantScopeMiddleware) is honoured from loopback only, so a device on the network -// renders the page as written, never an override. +// A request from the network to any other route is the site, and passes, unless the person chose that only +// the devices that scanned the code may open it (shared/ipc/devNetwork.ts). Then main starts the server with +// a random key in its environment, and a request from the network to the site passes only +// - with the key in its query (the code's address): it is answered with a cookie holding the key and a +// redirect to the same page without it, so the key does not stay in the address bar or the history, or +// - with that cookie. +// Anything else from the network is refused with 403, and so is Vite's live-reload WebSocket, which never +// reaches a middleware (loopbackGuardUpgrade). This computer always passes: the canvas never needs a key. +// The hover-preview header (previewMarkers.ts variantScopeMiddleware) is honoured from loopback only, so a +// device on the network renders the page as written, never an override. +import { timingSafeEqual } from 'node:crypto'; import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { Duplex } from 'node:stream'; import { assert } from '../../shared/core/assert'; +import { PREVIEW_KEY_COOKIE, PREVIEW_KEY_ENV, PREVIEW_KEY_PARAM, toPreviewKey, type PreviewKey } from '../../shared/ipc/devNetwork'; /** Paths only this computer may use: the editor's control routes, the local Studio and Vite's editor launcher. */ export const LOOPBACK_ONLY_PREFIXES = ['/__avb', '/studio', '/__open-in-editor'] as const; // A Host or Origin header longer than this is not one this app sends. const HEADER_CHARS_MAX = 512; +// A Cookie header past this is read as holding no key; the cookies before the bound are all a device needs. +const COOKIE_HEADER_CHARS_MAX = 8192; +const COOKIES_MAX = 64; + +/** The key main started this server with, or undefined while anyone on the network may open the preview. */ +const SERVER_KEY = previewKeyOf(process.env[PREVIEW_KEY_ENV]); /** Whether `remote`, a socket's remote address, is this computer. */ export function isLoopbackAddress(remote: string | undefined): boolean { @@ -92,18 +108,30 @@ export function isLoopbackOnlyRoute(url: string | undefined): boolean { return LOOPBACK_ONLY_PREFIXES.some((prefix) => normalized === prefix || normalized.startsWith(prefix + '/') || normalized.startsWith(prefix + '?')); } -/** The verdict on one request: whether it may continue. */ -export type LoopbackVerdict = { readonly kind: 'pass' } | { readonly kind: 'refuse'; readonly reason: 'remote' | 'host' | 'origin' }; +/** + * The verdict on one request: whether it may continue, or, for the code's address, be let in with the cookie + * and sent to `location`, the same page without the key. + */ +export type LoopbackVerdict = + | { readonly kind: 'pass' } + | { readonly kind: 'admit'; readonly location: string } + | { readonly kind: 'refuse'; readonly reason: 'remote' | 'host' | 'origin' | 'key' }; -/** Pure: what the guard decides for a request with these properties. */ -export function judgeRequest(request: { +export interface GuardedRequest { readonly url: string | undefined; + readonly method: string | undefined; readonly remoteAddress: string | undefined; readonly host: string | undefined; readonly origin: string | undefined; -}): LoopbackVerdict { + readonly cookie: string | undefined; + /** The server's key, or undefined while anyone on the network may open the preview. */ + readonly key: PreviewKey | undefined; +} + +/** Pure: what the guard decides for a request with these properties. */ +export function judgeRequest(request: GuardedRequest): LoopbackVerdict { if (!isLoopbackOnlyRoute(request.url)) { - return { kind: 'pass' }; + return judgeSiteRequest(request); } if (!isLoopbackAddress(request.remoteAddress)) { return { kind: 'refuse', reason: 'remote' }; @@ -117,23 +145,75 @@ export function judgeRequest(request: { return { kind: 'pass' }; } +/** + * Pure: the site's routes, which pass unless the server has a key. With one, this computer passes, the code's + * address (a GET or HEAD carrying the key) is admitted, a device with the cookie passes, and the rest is refused. + */ +export function judgeSiteRequest(request: GuardedRequest): LoopbackVerdict { + const key = request.key; + if (key === undefined) { + return { kind: 'pass' }; + } + if (isLoopbackAddress(request.remoteAddress)) { + return { kind: 'pass' }; // This computer: the canvas, thumbnails and main never need the key. + } + const url = new URL(request.url ?? '/', 'http://preview.invalid'); + const given = url.searchParams.get(PREVIEW_KEY_PARAM) ?? undefined; + if (given !== undefined && sameKey(given, key)) { + if (request.method === 'GET' || request.method === 'HEAD') { + url.searchParams.delete(PREVIEW_KEY_PARAM); + const location = `${url.pathname}${url.search}`; + assert(location.startsWith('/'), 'judgeSiteRequest: the redirect stays on this server'); + return { kind: 'admit', location }; + } + } + if (cookieKeys(request.cookie).some((value) => sameKey(value, key))) { + return { kind: 'pass' }; + } + return { kind: 'refuse', reason: 'key' }; +} + +/** The guard's two halves for a server started with `key` (or none): the middleware and the `upgrade` listener. */ +export interface LoopbackGuard { + readonly middleware: (request: IncomingMessage, response: ServerResponse, next: () => void) => void; + readonly upgrade: (request: IncomingMessage, socket: Duplex) => void; +} + +export function loopbackGuard(key: PreviewKey | undefined): LoopbackGuard { + return { + middleware: (request, response, next) => guardMiddleware(key, request, response, next), + upgrade: (request, socket) => guardUpgrade(key, request, socket), + }; +} + +const SERVER_GUARD = loopbackGuard(SERVER_KEY); /** The dev server middleware: registered first, before any Stacki route and before Vite's own. */ -export function loopbackGuardMiddleware(request: IncomingMessage, response: ServerResponse, next: () => void): void { - const verdict = judgeRequest({ - url: request.url, - remoteAddress: request.socket.remoteAddress, - host: headerText(request.headers.host), - origin: headerText(request.headers.origin), - }); +export const loopbackGuardMiddleware = SERVER_GUARD.middleware; +/** The dev server's `upgrade` listener, put before Vite's own (guardUpgrade). */ +export const loopbackGuardUpgrade = SERVER_GUARD.upgrade; + +function guardMiddleware(key: PreviewKey | undefined, request: IncomingMessage, response: ServerResponse, next: () => void): void { + const verdict = judgeRequest(guardedRequest(request, key)); switch (verdict.kind) { case 'pass': { next(); return; } + case 'admit': { + assert(key !== undefined, 'loopbackGuardMiddleware: only a server with a key admits'); + response.writeHead(303, { + location: verdict.location, + // Lax, not Strict: a code opened from the camera, or a link from a message, is a navigation from no + // site, and the device must send the cookie on the very next request. HttpOnly: no page script reads it. + 'set-cookie': `${PREVIEW_KEY_COOKIE}=${key}; Path=/; HttpOnly; SameSite=Lax`, + 'cache-control': 'no-store', + }); + response.end(); + return; + } case 'refuse': { - assert(isLoopbackOnlyRoute(request.url), 'loopbackGuardMiddleware: only Stacki routes are refused'); response.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }); - response.end('Forbidden'); + response.end(verdict.reason === 'key' ? 'Forbidden: scan the preview code in Stacki to open this page on this device.' : 'Forbidden'); return; } default: { @@ -143,6 +223,61 @@ export function loopbackGuardMiddleware(request: IncomingMessage, response: Serv } } +// Vite's live-reload WebSocket never passes a middleware, so a device the key keeps out of the site is kept out +// of it here too. Only the key is judged: an upgrade asks for no Stacki route, and the page's own socket carries +// the cookie like any request. +function guardUpgrade(key: PreviewKey | undefined, request: IncomingMessage, socket: Duplex): void { + const verdict = judgeSiteRequest(guardedRequest(request, key)); + if (verdict.kind === 'pass') { + return; + } + // An admit is a page's address, never a socket's: a socket without the cookie is refused either way. + socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'); + socket.destroy(); +} + +function guardedRequest(request: IncomingMessage, key: PreviewKey | undefined): GuardedRequest { + return { + url: request.url, + method: request.method, + remoteAddress: request.socket.remoteAddress, + host: headerText(request.headers.host), + origin: headerText(request.headers.origin), + cookie: headerText(request.headers.cookie), + key, + }; +} + +/** The values of every cookie named PREVIEW_KEY_COOKIE in a Cookie header, within the header's bounds. */ +export function cookieKeys(header: string | undefined): readonly string[] { + if (header === undefined || header.length > COOKIE_HEADER_CHARS_MAX) { + return []; + } + const values: string[] = []; + for (const pair of header.split(';').slice(0, COOKIES_MAX)) { + const equals = pair.indexOf('='); + if (equals !== -1 && pair.slice(0, equals).trim() === PREVIEW_KEY_COOKIE) { + values.push(pair.slice(equals + 1).trim()); + } + } + assert(values.length <= COOKIES_MAX, 'cookieKeys: bounded by the cookies read'); + return values; +} + +// Compared in constant time, so the time a refusal takes says nothing about how much of a guess was right. +function sameKey(given: string, key: PreviewKey): boolean { + const left = Buffer.from(given); + const right = Buffer.from(key); + if (left.byteLength !== right.byteLength) { + return false; + } + return timingSafeEqual(left, right); +} + +function previewKeyOf(value: string | undefined): PreviewKey | undefined { + return value === undefined || value === '' ? undefined : toPreviewKey(value); +} + function headerText(value: string | readonly string[] | undefined): string | undefined { if (typeof value === 'string') { return value; diff --git a/electron/previewServer/previewMarkers.ts b/electron/previewServer/previewMarkers.ts index b715d7ccc..4f069d9e3 100644 --- a/electron/previewServer/previewMarkers.ts +++ b/electron/previewServer/previewMarkers.ts @@ -27,7 +27,7 @@ import { withScopeCapture } from './scopeCapture'; // The generated config counts a file's extracted