From cc4daa5fee54478b6189fe1b9222a001aeb9ab05 Mon Sep 17 00:00:00 2001 From: Guiomesch Date: Thu, 3 Dec 2026 08:36:10 +0100 Subject: [PATCH 1/2] fix(hub): read the request host from :authority under HTTP/2 The request gate read only the Host header. Under HTTP/2, which the Angular dev server uses with --ssl, browsers send :authority and no Host. With allowedHosts: true the gate then refused a same-origin page, and the Host check against DNS rebinding was skipped. Fall back to :authority when Host is missing. --- packages/devtools/src/__tests__/hub-gate.test.ts | 12 ++++++++++++ packages/devtools/src/hub-gate.ts | 14 ++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/devtools/src/__tests__/hub-gate.test.ts b/packages/devtools/src/__tests__/hub-gate.test.ts index 6417a996..5485c864 100644 --- a/packages/devtools/src/__tests__/hub-gate.test.ts +++ b/packages/devtools/src/__tests__/hub-gate.test.ts @@ -70,6 +70,18 @@ describe('the Host check', () => { expect(status({ host: 'a.test', origin: 'https://b.test' }, policy)).toBe(403); }); + it('reads the host from :authority under HTTP/2, where browsers send no Host', () => { + const page = 'https://myapp.dev.example.test:4200'; + const h2 = (origin: string) => ({ ':authority': 'myapp.dev.example.test:4200', origin }); + // allowedHosts: true lets a same-origin page in, as it does over HTTP/1.1. + expect(status(h2(page), { allowedHosts: true })).toBe('next'); + expect(status(h2('https://evil.example'), { allowedHosts: true })).toBe(403); + // The Host check applies to :authority too, so a rebound name is refused. + expect(status({ ':authority': 'evil.test:4200' })).toBe(403); + expect(status(h2(page), { allowedHosts: ['myapp.dev.example.test'] })).toBe('next'); + expect(status(h2(page))).toBe(403); + }); + it('refuses a Host header that is not a plain host and port', () => { expect(isAllowedHubHost('localhost@evil.test')).toBe(false); expect(isAllowedHubHost('localhost/evil')).toBe(false); diff --git a/packages/devtools/src/hub-gate.ts b/packages/devtools/src/hub-gate.ts index afac0cc0..931b1209 100644 --- a/packages/devtools/src/hub-gate.ts +++ b/packages/devtools/src/hub-gate.ts @@ -244,6 +244,16 @@ function isAllowedRemoteHost(host: string | undefined, policy: HubOriginPolicy): return isAllowedHubHost(host, policy); } +/** + * The host a request was sent to: `Host`, or `:authority` under HTTP/2, where + * a browser sends no `Host` (the Angular dev server with `--ssl`). + */ +function requestHost(req: IncomingMessage): string | undefined { + const headers = req.headers ?? {}; + const authority = headers[':authority']; + return headers.host ?? (typeof authority === 'string' ? authority : undefined); +} + /** What the gate refused: an `Origin`, or the `Host` a request was sent to. */ export type BlockedRequest = (value: string, kind?: 'origin' | 'host') => void; @@ -255,7 +265,7 @@ export function isAllowedHubRequest( if (!isAllowedFetchSite(req)) return false; const local = isLoopback(req.socket?.remoteAddress); if (!local && !policy.remote) return isAllowedLanRequest(req, policy); - const host = req.headers?.host; + const host = requestHost(req); if (local && !isAllowedHubHost(host, policy) && !isEmulatorHost(host)) { if (host !== undefined) onBlocked?.(host, 'host'); return false; @@ -280,7 +290,7 @@ function isAllowedLanRequest(req: IncomingMessage, policy: HubOriginPolicy): boo if (!policy.lan || !policy.allowedOrigins?.length) return false; let origin = req.headers?.origin; if (origin === undefined) { - const host = req.headers?.host; + const host = requestHost(req); if (!host) return false; const secure = (req.socket as { encrypted?: boolean } | undefined)?.encrypted === true; // Only a plain host and port, then read like an allowedOrigins entry: From 5e9734b4a5b002fe95b70fac54942707cd6cf65e Mon Sep 17 00:00:00 2001 From: Guiomesch Date: Thu, 3 Dec 2026 08:36:11 +0100 Subject: [PATCH 2/2] feat(hub): trust the dev-server builder's allowedHosts, host and allowedOrigins The dev-server builder started the hub with its defaults, so a page opened on a custom hostname that points to this machine got 403 on the panel's SSE POST, even with the name in allowedHosts. initPangularHub() takes an allowedHosts option, read like Vite's server.allowedHosts, in its request gate and in the origin check of its transports. The builder forwards the dev server's allowedHosts, its host when it is a name, and a new allowedOrigins option, which it keeps from the Angular dev server's own options. --- .../src/content/getting-started/express.md | 1 + .../content/getting-started/installation.md | 27 +++++++-- apps/docs/src/content/security.md | 20 ++++--- .../src/__tests__/dev-server-builder.test.ts | 50 ++++++++++++++++ .../src/__tests__/hub-express-gate.test.ts | 32 +++++++++- .../devtools/src/builders/dev-server/index.ts | 60 +++++++++++++++++-- .../src/builders/dev-server/schema.json | 7 +++ packages/devtools/src/hub.ts | 30 ++++++++-- 8 files changed, 199 insertions(+), 28 deletions(-) diff --git a/apps/docs/src/content/getting-started/express.md b/apps/docs/src/content/getting-started/express.md index 685bba87..f3da4818 100644 --- a/apps/docs/src/content/getting-started/express.md +++ b/apps/docs/src/content/getting-started/express.md @@ -120,6 +120,7 @@ devtools.attach(server); | `enabled` | on unless this is production | `false` mounts nothing: the middlewares only call `next()`. `true` mounts the hub in production too, with a warning. See [Production](#production). | | `auth` | on | `false` turns off the one-time code. `{tokens: [...]}` keeps it on and trusts clients that send one of the [pairing tokens](../security.md#pairing-tokens). | | `allowedOrigins` | loopback origins and the Chrome extension | Extra origins allowed to reach the hub, such as a tunnel. `false` turns the origin check and the request gate off. | +| `allowedHosts` | none | Other names this machine answers to, such as `myapp.test`, read like Vite's `server.allowedHosts`. The hub trusts them as `Host` and as origin. `true` lets any `Host` through, but only a page on that same host as origin. | | `allowLan` | `false` | Answer other machines, such as a phone on Wi-Fi. Needs the one-time code on. | | `terminals` | `false` | Add a dock that runs the project's build and test commands. See [Terminals](./terminals.md). | | `extraDevframes` | none | Other devframes to mount on the same hub, after Pangular Inspector, the same input as `initHub({ devframes })`. See [Extra devframes](./configuration.md#extra-devframes). | diff --git a/apps/docs/src/content/getting-started/installation.md b/apps/docs/src/content/getting-started/installation.md index e4610a6e..0615b65f 100644 --- a/apps/docs/src/content/getting-started/installation.md +++ b/apps/docs/src/content/getting-started/installation.md @@ -325,14 +325,29 @@ An app created with `ng new --ssr=false` only runs `ng serve`. Mount the devtool Then load the overlay in `main.ts`, as in the [browser part](#browser-part) above, and run `ng serve`. It prints the panel URL next to the app URL, and the button appears on the page. -The builder takes every option of the dev server it runs, such as `port`, `proxyConfig` and `ssl`, and that builder checks them and applies its defaults. It adds two options of its own: +The builder takes every option of the dev server it runs, such as `port`, `proxyConfig` and `ssl`, and that builder checks them and applies its defaults. It adds three options of its own: -| Option | Default | What it does | -| ---------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `devtools` | `true` | Mounts the hub. Set it to `false`, for example in a configuration, to serve the app without the devtools. | -| `builder` | `@angular/build:dev-server`, or `@angular-devkit/build-angular:dev-server` when only it is installed | The dev server to run. It is loaded from your workspace, so it is the version your app already uses. | +| Option | Default | What it does | +| ---------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| `allowedOrigins` | none | Other origins the hub trusts, such as a tunnel. The dev server never sees this option. | +| `devtools` | `true` | Mounts the hub. Set it to `false`, for example in a configuration, to serve the app without the devtools. | +| `builder` | `@angular/build:dev-server`, or `@angular-devkit/build-angular:dev-server` when only it is installed | The dev server to run. It is loaded from your workspace, so it is the version your app already uses. | -The hub runs with its defaults: the one-time code, the origin check, requests from this machine only, and server-sent events instead of a WebSocket. It is off when `NODE_ENV` is `production`. The builder needs an `application` or `browser-esbuild` build. The webpack `browser` build has a dev server that takes no middleware, so use the standalone CLI there. +The hub runs with its defaults: the one-time code, the origin check, requests from this machine only, and server-sent events instead of a WebSocket. It also trusts the hosts in the dev server's `allowedHosts`, and `host` when it is a name such as `myapp.test`, as `Host` and as origin. It is off when `NODE_ENV` is `production`. The builder needs an `application` or `browser-esbuild` build. The webpack `browser` build has a dev server that takes no middleware, so use the standalone CLI there. + +If you open the app through another hostname that points to your machine, list it in `allowedHosts` (excerpt of the `serve` target): + +```json {4} +{ + "builder": "@pangular-inspector/devtools:dev-server", + "options": { + "allowedHosts": ["myapp.dev.example.test"], + "ssl": true + } +} +``` + +Without it, the panel stays blank and `ng serve` prints `Refused a devtools request from https://myapp.dev.example.test:4200`. #### With the standalone CLI and a proxy diff --git a/apps/docs/src/content/security.md b/apps/docs/src/content/security.md index 9e52ed26..6c854055 100644 --- a/apps/docs/src/content/security.md +++ b/apps/docs/src/content/security.md @@ -47,7 +47,7 @@ In detail, a request to the devtools must: A loopback origin means any port on a loopback host, so a page served by another dev server on this machine passes the origin check. It still needs the one-time code or a session token, which are on by default. -The `Host` check stops DNS rebinding: a website that points its own name at `127.0.0.1` still sends that name as the `Host`. Clients that send neither `Origin` nor `Sec-Fetch-Site`, such as curl or a native app, are not browsers, so they pass the last check. A request without a `Host` header passes the `Host` check, since browsers always send one. The emulator addresses are IP literals, which DNS rebinding cannot send, and the emulator forwards them to your machine's loopback interface, so only the emulator can send them from a loopback address. +The `Host` check stops DNS rebinding: a website that points its own name at `127.0.0.1` still sends that name as the `Host`. Clients that send neither `Origin` nor `Sec-Fetch-Site`, such as curl or a native app, are not browsers, so they pass the last check. Under HTTP/2, which the dev server uses with HTTPS, the check reads the `:authority` header instead. A request with neither passes the `Host` check, since browsers always send one. The emulator addresses are IP literals, which DNS rebinding cannot send, and the emulator forwards them to your machine's loopback interface, so only the emulator can send them from a loopback address. Other requests get `403` with the message "Pangular Inspector only answers requests from this machine." A request from another machine also gets the fix: set `allowLan: true` and list its origin in `allowedOrigins`. WebSocket upgrades follow the same rules. @@ -114,6 +114,8 @@ Version 0.0.7 and earlier kept the tokens in `~/.devframes/devframe/auth.json` ( | One-time code | `auth` | The server prints a code. A browser can read data only after it exchanges that code. | | Origin check | `allowedOrigins` | Only loopback origins, the Pangular Inspector extension, or clients that send no `Origin`, can reach the hub. Pass a list to allow more origins. | +To open the app through another hostname that points to your machine, such as `myapp.test`, pass it in `allowedHosts`. The hub trusts it as `Host` and as origin, read like Vite's `server.allowedHosts`, and prints the same warning for `allowedHosts: true`. + The request gate covers `nodeMiddleware`, `handler`, `handleUpgrade`, and the upgrades of a Node server passed to `attach(server)` or to the `server` option. A web request reaches `handler` without the address it came from, so `handler` applies the `Host`, `Origin` and `Sec-Fetch-Site` checks only. With `allowLan: true` and the one-time code on, a request from another machine passes when its `Origin` passes the origin check, or when it sends none, and when its `Host` is an IP address, a `.local` name or a host the origin check allows. A DNS rebinding name pointed at your network address is refused. `allowLan` needs the code: with `auth: false`, the hub ignores it and prints a warning. `allowedOrigins: false` turns the request gate off along with the origin check. The hub is off in production: when `NODE_ENV` is `production`, or when the server is a production Angular build, where `ngDevMode` is `false`. Its middlewares then only call `next()`. Pass `enabled: true` to mount it anyway. The hub then prints a warning when it starts. A server that is neither, such as one that loads the package without bundling it, keeps the hub on: pass `enabled` yourself, as in [Production](./getting-started/express.md#production). @@ -229,14 +231,14 @@ Agent tools and the panel don't report pages, so these rules don't apply to them The **Security** block on the [Dashboard](./inspectors/dashboard.md#security-block) shows how the running server lets clients in. The panel reads it with the `security-status` RPC, which answers trusted clients only: a panel or page that exchanged the one-time code, sent a trusted token or a pairing token, or any client while auth is off. -| Row | What it says | -| --------------- | ---------------------------------------------------------------------------------------------------------------------- | -| One-time code | On, with when the current code expires; off; or locked after too many wrong codes. | -| Trusted clients | How many session tokens the server trusts, and when the first and the last of them expire. | -| Pairing tokens | How many [pairing tokens](#pairing-tokens) the server accepts. Only shown when it accepts any. | -| Reach | This machine only, or other machines too (`allowLan`, `--host` with a network address, or no origin check). | -| Allowed origins | The origins allowed beyond this machine and the Chrome extension, at most 20, or **Any** when the origin check is off. | -| Allowed hosts | The `Host` names allowed beyond loopback, from Vite's `server.allowedHosts`. Only shown when there are any. | +| Row | What it says | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| One-time code | On, with when the current code expires; off; or locked after too many wrong codes. | +| Trusted clients | How many session tokens the server trusts, and when the first and the last of them expire. | +| Pairing tokens | How many [pairing tokens](#pairing-tokens) the server accepts. Only shown when it accepts any. | +| Reach | This machine only, or other machines too (`allowLan`, `--host` with a network address, or no origin check). | +| Allowed origins | The origins allowed beyond this machine and the Chrome extension, at most 20, or **Any** when the origin check is off. | +| Allowed hosts | The `Host` names allowed beyond loopback, from `allowedHosts` (Vite's `server.allowedHosts`, the hub option or the `dev-server` builder). Only shown when there are any. | The answer never holds a token, a pairing token or the one-time code. It holds counts, times and the origins and hosts from your own config, masked like other text. Agent tools can't read it. A static report built with `pangular build` has no server, so its Dashboard shows no **Security** block. diff --git a/packages/devtools/src/__tests__/dev-server-builder.test.ts b/packages/devtools/src/__tests__/dev-server-builder.test.ts index 6bc8adf5..fcf7d226 100644 --- a/packages/devtools/src/__tests__/dev-server-builder.test.ts +++ b/packages/devtools/src/__tests__/dev-server-builder.test.ts @@ -16,6 +16,7 @@ import { DEV_SERVERS, createDevServerBuilder, devServerArguments, + devServerHubOptions, devtoolsUrl, pickDevServer, type DevServerHost, @@ -130,6 +131,33 @@ describe('the dev-server builder', () => { expect(hub.close).toHaveBeenCalledOnce(); }); + it('has the hub trust allowedOrigins, allowedHosts and a host name, and keeps allowedOrigins from the dev server', async () => { + const calls: Call[] = []; + const { devHost, startHub } = host({ '@angular/build': fakeDevServer(calls) }); + const { output, run } = await serve(devHost, { + host: 'myapp.dev.example.test', + ssl: true, + allowedHosts: ['.example.test'], + allowedOrigins: ['https://tunnel.example/'], + }); + expect(output.success).toBe(true); + expect(startHub).toHaveBeenCalledWith({ + allowedOrigins: ['https://tunnel.example'], + allowedHosts: ['.example.test', 'myapp.dev.example.test'], + }); + // The Angular dev server's own schema refuses options it does not know. + expect(calls[0]?.options).not.toHaveProperty('allowedOrigins'); + expect(calls[0]?.options).toMatchObject({ allowedHosts: ['.example.test'] }); + await run.stop(); + }); + + it('starts the hub with its defaults on localhost', async () => { + const { devHost, startHub } = host({ '@angular/build': fakeDevServer([]) }); + const { run } = await serve(devHost, {}); + expect(startHub).toHaveBeenCalledWith({}); + await run.stop(); + }); + it('serves without the hub when devtools is false', async () => { const calls: Call[] = []; const { devHost, startHub } = host({ '@angular/build': fakeDevServer(calls) }); @@ -213,6 +241,26 @@ describe('pickDevServer', () => { }); }); +describe('devServerHubOptions', () => { + it('skips loopback and wildcard hosts, and keeps allowedHosts: true', () => { + for (const host of ['localhost', '127.0.0.1', '::1', '0.0.0.0', '::', 'app.localhost']) { + expect( + devServerHubOptions(undefined, { host }, () => undefined), + host, + ).toEqual({}); + } + expect( + devServerHubOptions(undefined, { host: 'myapp.test', allowedHosts: true }, () => undefined), + ).toEqual({ allowedHosts: true }); + }); + + it('warns about an allowedOrigins entry that is not an origin', () => { + const warn = vi.fn(); + expect(devServerHubOptions(['not a url'], {}, warn)).toEqual({}); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring allowedOrigins entry')); + }); +}); + describe('the builder schema', () => { it('takes every option of the @angular/build dev server, without its defaults', () => { for (const name of Object.keys(angularSchema.properties)) { @@ -221,6 +269,8 @@ describe('the builder schema', () => { } expect(ownSchema.additionalProperties).toBe(true); expect(ownSchema.properties['devtools']?.default).toBe(true); + expect(ownSchema.properties).toHaveProperty('allowedOrigins'); + expect(angularSchema.properties).not.toHaveProperty('allowedOrigins'); }); }); diff --git a/packages/devtools/src/__tests__/hub-express-gate.test.ts b/packages/devtools/src/__tests__/hub-express-gate.test.ts index 268c6b9a..e8fbb4d1 100644 --- a/packages/devtools/src/__tests__/hub-express-gate.test.ts +++ b/packages/devtools/src/__tests__/hub-express-gate.test.ts @@ -19,11 +19,12 @@ afterEach(async () => { delete (globalThis as { __PANGULAR_HUB__?: unknown }).__PANGULAR_HUB__; }); -async function expressLike() { +async function expressLike(options: Parameters[0] = {}) { const hub = initPangularHub({ cwd: makeProject({ 'package.json': '{}' }), ws: false, auth: false, + ...options, }); hubs.push(hub); await hub.ready; @@ -36,9 +37,13 @@ async function expressLike() { servers.push(server); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); const { port } = server.address() as AddressInfo; - return (headers: Record, path = '/__devframes/__connection.json') => + return ( + headers: Record, + path = '/__devframes/__connection.json', + method = 'GET', + ) => new Promise((resolve, reject) => { - const req = request({ host: '127.0.0.1', port, path, headers }, (res) => { + const req = request({ host: '127.0.0.1', port, path, headers, method }, (res) => { res.resume(); resolve(res.statusCode ?? 0); }); @@ -95,6 +100,27 @@ describe('the Express hub request gate', () => { expect(await get('http://localhost:4000/__devframes/__connection.json')).toBe(200); }); + it('trusts a custom hostname listed in allowedHosts, as Host and as Origin', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const page = { + host: 'myapp.dev.example.test:4200', + origin: 'https://myapp.dev.example.test:4200', + }; + // The panel's SSE POST carries an Origin, which the hub's transport checks again. + const post = (get: Awaited>) => + get({ ...page, 'content-type': 'application/json' }, '/__devframes/__sse', 'POST'); + const listed = await expressLike({ allowedHosts: ['.example.test'] }); + expect(await listed(page)).toBe(200); + expect(await post(listed)).not.toBe(403); + expect(await listed({ ...page, origin: 'https://evil.example' })).toBe(403); + const byOrigin = await expressLike({ allowedOrigins: ['https://myapp.dev.example.test:4200'] }); + expect(await byOrigin(page)).toBe(200); + expect(await post(byOrigin)).not.toBe(403); + const unlisted = await expressLike(); + expect(await unlisted(page)).toBe(403); + expect(await post(unlisted)).toBe(403); + }); + it('leaves routes outside the hub alone', async () => { const get = await expressLike(); expect(await get({ host: 'evil.test' }, '/products')).toBe(404); diff --git a/packages/devtools/src/builders/dev-server/index.ts b/packages/devtools/src/builders/dev-server/index.ts index 90cefcb6..01851578 100644 --- a/packages/devtools/src/builders/dev-server/index.ts +++ b/packages/devtools/src/builders/dev-server/index.ts @@ -14,6 +14,7 @@ import { createRequire } from 'node:module'; import { join } from 'node:path'; import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import { normalizeAllowedOrigins } from '../../allowed-origins.ts'; /** The builder's own options; every other option goes to the dev server it runs. */ export interface DevServerOptions { @@ -21,6 +22,8 @@ export interface DevServerOptions { builder?: string; /** Mount the hub. On by default. */ devtools?: boolean; + /** Other origins the hub trusts, such as a tunnel. Not passed to the dev server. */ + allowedOrigins?: string[]; [option: string]: unknown; } @@ -56,12 +59,18 @@ export interface DevServerHub { close(): Promise; } +/** What the hub trusts beyond this machine's loopback names. */ +export interface DevServerHubOptions { + allowedOrigins?: string[]; + allowedHosts?: string[] | true; +} + /** What the builder loads, passed in by tests. */ export interface DevServerHost { /** Loads a package from the workspace, or `undefined` when it is not installed. */ load(name: string, workspaceRoot: string): unknown; /** Starts the hub (`initPangularHub` from `@pangular-inspector/devtools/hub`). */ - startHub(): Promise; + startHub(options: DevServerHubOptions): Promise; } /** Loads `name` from this package's own location, then from the workspace root. */ @@ -80,17 +89,53 @@ function loadPackage(name: string, workspaceRoot: string): unknown { export const nodeDevServerHost: DevServerHost = { load: loadPackage, - startHub: async () => { + startHub: async (options) => { // The published hub entry, which loads the hub's server code on first use. const hub = (await import('@pangular-inspector/devtools/hub')) as { - initPangularHub(options: { ws: false }): DevServerHub; + initPangularHub(options: DevServerHubOptions & { ws: false }): DevServerHub; }; // `ws: false`: the dev server hands out no upgrade hook, so the panel and // the overlay talk to the hub over server-sent events. - return hub.initPangularHub({ ws: false }); + return hub.initPangularHub({ ws: false, ...options }); }, }; +/** A `host` that names this machine on every interface, or only on loopback. */ +const LOCAL_HOSTS = + /^(?:localhost|.*\.localhost|127(?:\.\d{1,3}){3}|::1|\[::1\]|0\.0\.0\.0|::|\[::\])$/i; + +/** + * What the hub trusts, from the serve options: `allowedOrigins`, the dev + * server's `allowedHosts`, and `host` when it is a name such as + * `myapp.test`, which Vite allows by itself too. + */ +export function devServerHubOptions( + allowedOrigins: unknown, + serveOptions: Record, + warn: (message: string) => void, +): DevServerHubOptions { + const origins = normalizeAllowedOrigins( + Array.isArray(allowedOrigins) ? allowedOrigins.filter((o) => typeof o === 'string') : [], + warn, + ); + const { allowedHosts, host } = serveOptions; + let hosts: string[] | true | undefined; + if (allowedHosts === true) hosts = true; + else { + const listed = Array.isArray(allowedHosts) + ? allowedHosts.filter((entry): entry is string => typeof entry === 'string' && !!entry) + : []; + if (typeof host === 'string' && host && !LOCAL_HOSTS.test(host) && !listed.includes(host)) { + listed.push(host); + } + if (listed.length) hosts = listed; + } + return { + ...(origins.length ? { allowedOrigins: origins } : {}), + ...(hosts ? { allowedHosts: hosts } : {}), + }; +} + /** The package of a builder name, such as `@angular/build` for `@angular/build:dev-server`. */ function packageOf(builder: string): string { return builder.slice(0, builder.lastIndexOf(':')); @@ -178,7 +223,7 @@ export async function* runDevServer( context: BuilderContext, host: DevServerHost = nodeDevServerHost, ): AsyncIterable { - const { builder, devtools = true, ...serveOptions } = options; + const { builder, devtools = true, allowedOrigins, ...serveOptions } = options; const picked = pickDevServer(builder, context.workspaceRoot, host); if ('error' in picked) { context.logger.error(picked.error); @@ -190,7 +235,10 @@ export async function* runDevServer( const validated = await context.validateOptions(json, picked.name); let hub: DevServerHub | undefined; if (devtools) { - const started = await host.startHub(); + const trusted = devServerHubOptions(allowedOrigins, validated, (message) => + context.logger.warn(message), + ); + const started = await host.startHub(trusted); // Off with NODE_ENV=production; the dev server then runs without it. if (started.enabled) hub = started; else await started.close(); diff --git a/packages/devtools/src/builders/dev-server/schema.json b/packages/devtools/src/builders/dev-server/schema.json index 5a652f50..ad66e298 100644 --- a/packages/devtools/src/builders/dev-server/schema.json +++ b/packages/devtools/src/builders/dev-server/schema.json @@ -14,6 +14,13 @@ "description": "Mount the Pangular Inspector hub in the dev server. Set it to false to serve the app without the devtools.", "default": true }, + "allowedOrigins": { + "type": "array", + "description": "Other origins the Pangular Inspector hub trusts, such as \"https://tunnel.example\". Hosts in \"allowedHosts\", and \"host\" when it is a name, are trusted too.", + "items": { + "type": "string" + } + }, "buildTarget": { "type": "string", "description": "A build builder target to serve in the format of `project:target[:configuration]`. You can also pass in more than one configuration name as a comma-separated list. Example: `project:target:production,staging`.", diff --git a/packages/devtools/src/hub.ts b/packages/devtools/src/hub.ts index c51abc88..a5392793 100644 --- a/packages/devtools/src/hub.ts +++ b/packages/devtools/src/hub.ts @@ -12,7 +12,9 @@ import type { PangularServerPlugin } from './plugin.ts'; import { withMessagesPanel } from './hub-messages-panel.ts'; import { hubTerminals, terminalsEnabled, withTerminals } from './hub-terminals.ts'; import { + allowedHostsWarning, blockedOriginReporter, + hubOriginRegistryFor, isAllowedHubRequest, isHubPath, refuseHubRequest, @@ -58,6 +60,14 @@ export type PangularHubOptions = Partial, remote = false, + allowedHosts?: HubOriginPolicy['allowedHosts'], ): HubOriginPolicy | undefined { if (allowedOrigins === false) return undefined; const isAllowed = Array.isArray(allowedOrigins) ? (origin: string) => isAllowedOrigin(origin, allowedOrigins) : (origin: string) => (allowedOrigins as WsOriginRegistry).isAllowed(origin); - return { isAllowedOrigin: isAllowed, remote }; + return { isAllowedOrigin: isAllowed, remote, ...(allowedHosts ? { allowedHosts } : {}) }; } /** Puts the gate in front of the hub's Express middleware and WebSocket upgrades. */ @@ -388,7 +399,7 @@ function gatedTransport( * `Host`, and the origin check. Off in production unless `enabled` is `true`. */ export function initPangularHub(options: PangularHubOptions = {}): PangularHub { - const { enabled, allowLan, terminals, ...hubOptions } = options; + const { enabled, allowLan, terminals, allowedHosts, ...hubOptions } = options; const base = normalizeHubBase(hubOptions.base ?? PANGULAR_HUB_BASE); if (!hubEnabled(enabled)) return disabledHub(base); const authOn = hubOptions.auth !== false; @@ -402,7 +413,9 @@ export function initPangularHub(options: PangularHubOptions = {}): PangularHub { const policy = hubOptions.allowedOrigins === false ? undefined - : hubGatePolicy(hubAllowedOrigins(hubOptions.allowedOrigins), remote); + : hubGatePolicy(hubAllowedOrigins(hubOptions.allowedOrigins), remote, allowedHosts); + const hostsWarning = policy && allowedHostsWarning(allowedHosts, authOn); + if (hostsWarning) console.warn(hostsWarning); const terminalsOn = terminalsEnabled(terminals, { originCheckOff: hubOptions.allowedOrigins === false, remote, @@ -413,8 +426,17 @@ export function initPangularHub(options: PangularHubOptions = {}): PangularHub { originCheck: origins !== false, allowedOrigins: Array.isArray(origins) ? origins : [], customOrigins: !!origins && !Array.isArray(origins), + ...(policy?.allowedHosts === undefined ? {} : { allowedHosts: policy.allowedHosts }), // Without the origin check there is no gate, so other machines get answers too. network: remote || origins === false, }; - return startPangularHub({ ...hubOptions, terminals: terminalsOn, security }, policy); + // The hub's transports check `Origin` again, without the `Host`. The gate + // already ran on every request, so they accept what it let through. + const hubOrigins = policy?.allowedHosts + ? { allowedOrigins: hubOriginRegistryFor(policy, true) } + : {}; + return startPangularHub( + { ...hubOptions, ...hubOrigins, terminals: terminalsOn, security }, + policy, + ); }