Skip to content
Merged
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
32 changes: 26 additions & 6 deletions apps/docs/src/content/getting-started/vite.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ It records Analog page renders, `load()` fetches, server functions and API calls

The plugin only answers requests from a loopback address (any `127.x.x.x` address or `::1`). Other requests to the devtools get `403` with the message "ng-devtools only answers requests from this machine." WebSocket upgrades follow the same rules.

The Vite plugin turns the one-time code off. The loopback and origin checks take its place. [Access and redaction](/security) covers both checks.
By default the plugin leaves the one-time code off, and the loopback and origin checks take its place. If `server.allowedHosts` or `allowedOrigins` allows a host that is not a loopback host, the plugin also asks for the code. See [`auth`](#auth). [Access and redaction](/security) covers every check.

## Options

Expand All @@ -99,11 +99,12 @@ ngDevtools({
});
```

| Option | Default | What it does |
| ---------------- | -------------------------------- | ------------------------------------------------------------------------ |
| `base` | `'/__devframes/'` | Where the hub is mounted. |
| `apiPrefix` | Analog's `apiPrefix`, or `'api'` | The prefix of your server routes, used to classify API calls. |
| `allowedOrigins` | none | Extra exact origins allowed to reach the devtools, for example a tunnel. |
| Option | Default | What it does |
| ---------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `base` | `'/__devframes/'` | Where the hub is mounted. |
| `apiPrefix` | Analog's `apiPrefix`, or `'api'` | The prefix of your server routes, used to classify API calls. |
| `allowedOrigins` | none | Extra exact origins allowed to reach the devtools, for example a tunnel. |
| `auth` | on if a non-loopback host or origin is allowed, otherwise off | Whether the devtools ask for the one-time code. |

### `base`

Expand All @@ -117,6 +118,23 @@ The plugin reads `apiPrefix` from your Analog config. Set it here only when the

Each entry is an exact origin, such as `https://tunnel.example`. The request itself must still come from a loopback address.

### `auth`

A tunnel forwards other people's requests to your machine, and those requests arrive from a loopback address. So the plugin turns the one-time code on when Vite's `server.allowedHosts` or `allowedOrigins` allows anything other than `localhost` or a loopback address (`allowedHosts: true` counts too). The server prints the code in the terminal, and a browser reads data only after it exchanges that code.

| Value | Effect |
| ------- | ------------------------------------------------------------------- |
| not set | The code is on only if a non-loopback host or origin is allowed. |
| `true` | The code is always on. |
| `false` | The code is always off. The loopback and origin checks still apply. |

If your tunnel rewrites the `Host` header to `localhost`, you don't list it in `server.allowedHosts`, so the plugin leaves the code off. Pass `auth: true`:

```ts
// vite.config.ts
ngDevtools({auth: true});
```

## Hostnames other than localhost

### Local hostnames
Expand Down Expand Up @@ -144,6 +162,8 @@ Add other origins with `allowedOrigins`:
ngDevtools({allowedOrigins: ['https://tunnel.example']});
```

A non-loopback entry in `server.allowedHosts` or `allowedOrigins` turns the one-time code on. See [`auth`](#auth).

## Angular CLI apps

<ngmd-alert severity="important">
Expand Down
18 changes: 14 additions & 4 deletions apps/docs/src/content/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ The devtools read your running app and send what they find to a server on your m

<ngmd-card-grid columns="2">
<ngmd-card icon="zap" title="Vite plugin">
Loopback requests only. A request that sends an <code>Origin</code> must come from a loopback host, a Chrome extension, <code>allowedOrigins</code> or Vite's <code>server.allowedHosts</code>.
Loopback requests only. A request that sends an <code>Origin</code> must come from a loopback host, a Chrome extension, <code>allowedOrigins</code> or Vite's <code>server.allowedHosts</code>. Asks for a one-time code when a non-loopback host or origin is allowed.
</ngmd-card>
<ngmd-card icon="layers" title="Express hub">
A one-time code and a loopback origin check. Both on by default.
Expand Down Expand Up @@ -59,10 +59,20 @@ export default defineConfig({
});
```

The Vite plugin turns the one-time code off. The loopback and origin checks take its place.
#### One-time code

The plugin's `auth` option decides whether the devtools also ask for the one-time code. The server prints the code in the terminal, and a browser reads data only after it exchanges that code.

| `auth` | One-time code |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| not set | On if `server.allowedHosts` or `allowedOrigins` allows a host other than `localhost` or a loopback address, otherwise off. `allowedHosts: true` turns it on. |
| `true` | Always on. |
| `false` | Always off. The loopback and origin checks still apply. |

With only loopback hosts allowed, the loopback and origin checks take the place of the code.

<ngmd-callout type="warning" title="Tunnels look local">
A tunnel client runs on your machine, so the requests it forwards come from a loopback address. Anyone who can reach the tunnel can then reach the devtools. Only allow a tunnel origin that only you can reach.
A tunnel client runs on your machine, so the requests it forwards come from a loopback address. That is why an allowed tunnel host or origin turns the one-time code on. If your tunnel rewrites the <code>Host</code> header to <code>localhost</code>, nothing in your config names the tunnel, so pass <code>auth: true</code>. Don't pass <code>auth: false</code> while a tunnel is allowed.
</ngmd-callout>

### Express hub
Expand Down Expand Up @@ -178,7 +188,7 @@ Response previews and TransferState values in the [SSR & HTTP tab](/inspectors/s
Open the app on <code>localhost</code>. Add other hostnames or origins one by one, only when you need them.
</ngmd-step>
<ngmd-step title="Leave the checks on">
Keep <code>auth</code> and the origin check on in the Express hub unless the machine is yours alone.
Keep <code>auth</code> and the origin check on in the Express hub unless the machine is yours alone. In the Vite plugin, don't pass <code>auth: false</code> while a tunnel host or origin is allowed.
</ngmd-step>
<ngmd-step title="Use test data">
Keep real credentials out of forms and API responses you inspect.
Expand Down
80 changes: 80 additions & 0 deletions packages/ng-devtools/src/__tests__/vite-auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { describe, expect, it, vi } from 'vitest';

const hubOptions = vi.hoisted(() => [] as { auth?: unknown }[]);

vi.mock('../hub.ts', () => ({
NG_DEVTOOLS_HUB_BASE: '/__devframes/',
initNgDevtoolsHub: (options: { auth?: unknown }) => {
hubOptions.push(options);
return { nodeMiddleware: vi.fn(), close: vi.fn() };
},
}));

const { allowsRemoteOrigins, default: ngDevtoolsVite, hubAuthFor } = await import('../vite.ts');

function hubAuth(
options: Parameters<typeof ngDevtoolsVite>[0],
allowedHosts?: readonly string[] | true,
) {
hubOptions.length = 0;
const plugin = ngDevtoolsVite({ apiPrefix: 'api', ...options });
const server = {
config: { root: process.cwd(), server: { allowedHosts } },
middlewares: { use: vi.fn() },
httpServer: null,
};
(plugin.configureServer as (server: unknown) => void)(server);
return hubOptions[0]?.auth;
}

describe('allowsRemoteOrigins', () => {
it('is false when only loopback hosts and origins are trusted', () => {
expect(allowsRemoteOrigins()).toBe(false);
expect(allowsRemoteOrigins({ allowedHosts: [] })).toBe(false);
expect(
allowsRemoteOrigins({
allowedHosts: ['localhost', '.localhost', '127.0.0.1', '::1', '[::1]'],
allowedOrigins: ['http://localhost:4200', 'https://127.0.0.1:5173', 'http://[::1]:3000'],
}),
).toBe(false);
});

it('is true when a tunnel host or any other remote origin is trusted', () => {
expect(allowsRemoteOrigins({ allowedHosts: true })).toBe(true);
expect(allowsRemoteOrigins({ allowedHosts: ['localhost', 'myapp.test'] })).toBe(true);
expect(allowsRemoteOrigins({ allowedHosts: ['.ngrok-free.app'] })).toBe(true);
expect(allowsRemoteOrigins({ allowedHosts: ['127.attacker.example'] })).toBe(true);
expect(allowsRemoteOrigins({ allowedOrigins: ['https://tunnel.example:8443'] })).toBe(true);
expect(allowsRemoteOrigins({ allowedOrigins: ['not a url'] })).toBe(true);
expect(allowsRemoteOrigins({ allowedOrigins: ['ws://localhost:5173'] })).toBe(true);
});
});

describe('hubAuthFor', () => {
it('follows the origin policy unless auth is set explicitly', () => {
const remote = { allowedOrigins: ['https://tunnel.example'] };
expect(hubAuthFor({})).toBe(false);
expect(hubAuthFor(remote)).toBe(true);
expect(hubAuthFor(remote, false)).toBe(false);
expect(hubAuthFor({}, true)).toBe(true);
});
});

describe('ngDevtoolsVite hub auth', () => {
it('skips the one-time code for a purely local dev server', () => {
expect(hubAuth({})).toBe(false);
expect(hubAuth({ allowedOrigins: ['http://localhost:4200'] }, ['localhost'])).toBe(false);
});

it('keeps the one-time code when a tunnel host or origin is allowed', () => {
expect(hubAuth({}, ['abc.trycloudflare.com'])).toBe(true);
expect(hubAuth({}, true)).toBe(true);
expect(hubAuth({ allowedOrigins: ['https://tunnel.example'] })).toBe(true);
});

it('lets the user turn the one-time code off or on explicitly', () => {
expect(hubAuth({ auth: false, allowedOrigins: ['https://tunnel.example'] })).toBe(false);
expect(hubAuth({ auth: false }, true)).toBe(false);
expect(hubAuth({ auth: true })).toBe(true);
});
});
27 changes: 26 additions & 1 deletion packages/ng-devtools/src/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface NgDevtoolsViteOptions {
base?: string;
apiPrefix?: string;
allowedOrigins?: string[];
auth?: boolean;
}

export interface HubOriginPolicy {
Expand Down Expand Up @@ -51,6 +52,30 @@ export function isAllowedHubOrigin(
}
}

function isLoopbackOrigin(origin: string): boolean {
try {
const url = new URL(origin);
return (
(url.protocol === 'http:' || url.protocol === 'https:') && isLoopbackHostname(url.hostname)
);
} catch {
return false;
}
}

export function allowsRemoteOrigins(policy: HubOriginPolicy = {}): boolean {
if (policy.allowedHosts === true) return true;
const hosts = policy.allowedHosts ?? [];
if (hosts.some((entry) => !isLoopbackHostname(entry.replace(/^\./, '').toLowerCase()))) {
return true;
}
return (policy.allowedOrigins ?? []).some((origin) => !isLoopbackOrigin(origin));
}

export function hubAuthFor(policy: HubOriginPolicy, auth?: boolean): boolean {
return auth ?? allowsRemoteOrigins(policy);
}

export function hubOriginRegistryFor(policy: HubOriginPolicy = {}): WsOriginRegistry {
return {
token: '',
Expand Down Expand Up @@ -135,7 +160,7 @@ export default function ngDevtoolsVite(options: NgDevtoolsViteOptions = {}): Plu
...(server.httpServer instanceof HttpServer
? { server: server.httpServer }
: { ws: { sidecar: true } }),
auth: false,
auth: hubAuthFor(policy, options.auth),
allowedOrigins: hubOriginRegistryFor(policy),
});
if (shared) guardNewUpgrades(shared, upgradesBefore, base, policy);
Expand Down
Loading