Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/docs/src/content/getting-started/express.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
Expand Down
27 changes: 21 additions & 6 deletions apps/docs/src/content/getting-started/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 11 additions & 9 deletions apps/docs/src/content/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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.

Expand Down
50 changes: 50 additions & 0 deletions packages/devtools/src/__tests__/dev-server-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
DEV_SERVERS,
createDevServerBuilder,
devServerArguments,
devServerHubOptions,
devtoolsUrl,
pickDevServer,
type DevServerHost,
Expand Down Expand Up @@ -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) });
Expand Down Expand Up @@ -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)) {
Expand All @@ -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');
});
});

Expand Down
32 changes: 29 additions & 3 deletions packages/devtools/src/__tests__/hub-express-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ afterEach(async () => {
delete (globalThis as { __PANGULAR_HUB__?: unknown }).__PANGULAR_HUB__;
});

async function expressLike() {
async function expressLike(options: Parameters<typeof initPangularHub>[0] = {}) {
const hub = initPangularHub({
cwd: makeProject({ 'package.json': '{}' }),
ws: false,
auth: false,
...options,
});
hubs.push(hub);
await hub.ready;
Expand All @@ -36,9 +37,13 @@ async function expressLike() {
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
return (headers: Record<string, string>, path = '/__devframes/__connection.json') =>
return (
headers: Record<string, string>,
path = '/__devframes/__connection.json',
method = 'GET',
) =>
new Promise<number>((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);
});
Expand Down Expand Up @@ -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<ReturnType<typeof expressLike>>) =>
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);
Expand Down
12 changes: 12 additions & 0 deletions packages/devtools/src/__tests__/hub-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading