From 16fb90fb182ff33adcd533a94c2aaa7722afa206 Mon Sep 17 00:00:00 2001 From: Kam Date: Wed, 30 Sep 2026 10:22:11 +0300 Subject: [PATCH 1/4] fix(vite): require the one-time code when a tunnel host is allowed Allowing a non-loopback host in server.allowedHosts or allowedOrigins usually means a tunnel, whose client connects from loopback, so the loopback check no longer keeps other people out. Keep the hub's one-time code on in that case, keep it off for purely local setups, and add an auth option to override either way. --- README.md | 2 + .../src/__tests__/vite-auth.test.ts | 80 +++++++++++++++++++ packages/ng-devtools/src/vite.ts | 27 ++++++- 3 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 packages/ng-devtools/src/__tests__/vite-auth.test.ts diff --git a/README.md b/README.md index de8669f5..f3cba7d1 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,8 @@ The floating button appears on the page, the full viewer is at `/__devframes/` o The devtools only answer this machine, and only pages served from `localhost`, `127.0.0.1` or the Chrome extension, so another website open in your browser can't reach them. If you open the dev server through another hostname that points to your machine (for example `myapp.test`), list it in Vite's `server.allowedHosts` and the devtools trust it too. Other origins can be added with `ngDevtools({ allowedOrigins: ['https://tunnel.example'] })`. +A tunnel forwards other people's requests to your machine, so once `server.allowedHosts` or `allowedOrigins` names anything other than `localhost` or a loopback address, the devtools ask for a one-time code (printed in the terminal) before they connect. Pass `ngDevtools({ auth: false })` to skip the code, or `ngDevtools({ auth: true })` to require it everywhere, for example behind a tunnel that rewrites the `Host` header to `localhost`. + The Analog dock shows: - Routes: every page, layout and markdown file with its URL, route groups, `[param]` and catch-all segments, `.server.ts` files and routeMeta. Test a URL to see which files render it. diff --git a/packages/ng-devtools/src/__tests__/vite-auth.test.ts b/packages/ng-devtools/src/__tests__/vite-auth.test.ts new file mode 100644 index 00000000..071cee17 --- /dev/null +++ b/packages/ng-devtools/src/__tests__/vite-auth.test.ts @@ -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[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); + }); +}); diff --git a/packages/ng-devtools/src/vite.ts b/packages/ng-devtools/src/vite.ts index b8b02103..9dd25fb3 100644 --- a/packages/ng-devtools/src/vite.ts +++ b/packages/ng-devtools/src/vite.ts @@ -13,6 +13,7 @@ export interface NgDevtoolsViteOptions { base?: string; apiPrefix?: string; allowedOrigins?: string[]; + auth?: boolean; } export interface HubOriginPolicy { @@ -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: '', @@ -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); From 9b8c8023bb8616fd31b6142d0ac99801d63b1928 Mon Sep 17 00:00:00 2001 From: Kam Date: Wed, 30 Sep 2026 10:48:53 +0300 Subject: [PATCH 2/4] fix(hub): require a bearer token on the MCP route when auth is on The hub mounted MCP without authorization under mcp: 'auto', so a non-browser client behind a tunnel could call tools even with the one-time code on. When auth is on, the MCP route now requires Authorization: Bearer with NG_DEVTOOLS_MCP_TOKEN or a generated token printed at startup. Local-only setups stay open, and the stdio mcp command is unchanged. --- README.md | 23 ++++++- .../ng-devtools/src/__tests__/hub.test.ts | 61 +++++++++++++++- .../src/__tests__/vite-mcp-auth.test.ts | 69 +++++++++++++++++++ packages/ng-devtools/src/hub.ts | 21 ++++++ 4 files changed, 170 insertions(+), 4 deletions(-) create mode 100644 packages/ng-devtools/src/__tests__/vite-mcp-auth.test.ts diff --git a/README.md b/README.md index f3cba7d1..85a4f1f6 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,26 @@ npx @santoshyadavdev/ng-devtools mcp } ``` -When embedded in Express, the MCP endpoint is also available over HTTP at `/__devframes/__mcp` (or `/__ng-devtools/__mcp` without the hub). +When embedded in Express or Vite, the MCP endpoint is also available over HTTP at `/__devframes/__mcp` (or `/__ng-devtools/__mcp` without the hub). + +If the hub asks for a one-time code, the HTTP endpoint also asks for a token. That is the Express hub by default, and the Vite plugin once it trusts a tunnel host or origin. The hub prints a generated token in the terminal when it starts. Set `NG_DEVTOOLS_MCP_TOKEN` to use your own token and keep it across restarts. The endpoint only accepts requests with a loopback `Origin` header, so the client sends both headers. For example, in Claude Code's `.mcp.json`: + +```json +{ + "mcpServers": { + "ng-devtools": { + "type": "http", + "url": "http://localhost:4000/__devframes/__mcp", + "headers": { + "Authorization": "Bearer ${NG_DEVTOOLS_MCP_TOKEN}", + "Origin": "http://localhost:4000" + } + } + } +} +``` + +Without the one-time code (`auth: false`, or a Vite dev server that only trusts `localhost`), the endpoint needs no token. The `mcp` command above runs over stdio and never needs one. #### Agent Tools @@ -227,7 +246,7 @@ The floating button appears on the page, the full viewer is at `/__devframes/` o The devtools only answer this machine, and only pages served from `localhost`, `127.0.0.1` or the Chrome extension, so another website open in your browser can't reach them. If you open the dev server through another hostname that points to your machine (for example `myapp.test`), list it in Vite's `server.allowedHosts` and the devtools trust it too. Other origins can be added with `ngDevtools({ allowedOrigins: ['https://tunnel.example'] })`. -A tunnel forwards other people's requests to your machine, so once `server.allowedHosts` or `allowedOrigins` names anything other than `localhost` or a loopback address, the devtools ask for a one-time code (printed in the terminal) before they connect. Pass `ngDevtools({ auth: false })` to skip the code, or `ngDevtools({ auth: true })` to require it everywhere, for example behind a tunnel that rewrites the `Host` header to `localhost`. +A tunnel forwards other people's requests to your machine, so once `server.allowedHosts` or `allowedOrigins` names anything other than `localhost` or a loopback address, the devtools ask for a one-time code (printed in the terminal) before they connect. Pass `ngDevtools({ auth: false })` to skip the code, or `ngDevtools({ auth: true })` to require it everywhere, for example behind a tunnel that rewrites the `Host` header to `localhost`. While the code is on, the HTTP MCP endpoint asks for a token too (see [MCP Server for Coding Agents](#mcp-server-for-coding-agents)). The Analog dock shows: diff --git a/packages/ng-devtools/src/__tests__/hub.test.ts b/packages/ng-devtools/src/__tests__/hub.test.ts index cf68b592..5d218143 100644 --- a/packages/ng-devtools/src/__tests__/hub.test.ts +++ b/packages/ng-devtools/src/__tests__/hub.test.ts @@ -1,5 +1,5 @@ -import { afterEach, describe, expect, it } from 'vitest'; -import { initNgDevtoolsHub } from '../hub.ts'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { initNgDevtoolsHub, type NgDevtoolsHubOptions } from '../hub.ts'; import { makeProject } from './analog-fixture.ts'; const hubs: { close: () => Promise }[] = []; @@ -21,7 +21,29 @@ async function boot(cwd: string) { return { hub, ctx, docks }; } +async function bootMcp(options: NgDevtoolsHubOptions) { + const cwd = makeProject({ 'package.json': '{}' }); + const hub = initNgDevtoolsHub({ cwd, ws: false, allowedOrigins: false, ...options }); + hubs.push(hub); + await hub.ready; + return (token?: string) => + hub.handler( + new Request('http://localhost/__devframes/__mcp', { + method: 'POST', + headers: { + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + origin: 'http://localhost:4000', + ...(token === undefined ? {} : { authorization: `Bearer ${token}` }), + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }), + }), + ); +} + afterEach(async () => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); for (const hub of hubs.splice(0)) await hub.close(); }); @@ -56,3 +78,38 @@ describe('ng-devtools hub', () => { expect(forms.markdown).toContain('No forms'); }); }); + +describe('ng-devtools hub MCP route', () => { + it('stays open when the hub runs without auth', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + const mcp = await bootMcp({ auth: false }); + expect((await mcp()).status).toBe(200); + expect(log.mock.calls.flat().join('\n')).not.toContain('MCP token'); + }); + + it('requires the token from NG_DEVTOOLS_MCP_TOKEN when auth is on', async () => { + vi.stubEnv('NG_DEVTOOLS_MCP_TOKEN', 'env-secret'); + const mcp = await bootMcp({}); + expect((await mcp()).status).toBe(401); + expect((await mcp('wrong')).status).toBe(401); + const allowed = await mcp('env-secret'); + expect(allowed.status).toBe(200); + expect(await allowed.text()).toContain('ng-devtools_get-routes'); + }); + + it('prints a generated token when none is configured', async () => { + vi.stubEnv('NG_DEVTOOLS_MCP_TOKEN', ''); + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + const mcp = await bootMcp({ auth: true }); + const token = /MCP token: (\S+)/.exec(log.mock.calls.flat().join('\n'))?.[1]; + expect(token).toMatch(/^[\w-]{32}$/); + expect((await mcp()).status).toBe(401); + expect((await mcp(token)).status).toBe(200); + }); + + it('keeps an explicit mcp setting', async () => { + const mcp = await bootMcp({ auth: true, mcp: { authorization: 'own-secret' } }); + expect((await mcp()).status).toBe(401); + expect((await mcp('own-secret')).status).toBe(200); + }); +}); diff --git a/packages/ng-devtools/src/__tests__/vite-mcp-auth.test.ts b/packages/ng-devtools/src/__tests__/vite-mcp-auth.test.ts new file mode 100644 index 00000000..5303e08e --- /dev/null +++ b/packages/ng-devtools/src/__tests__/vite-mcp-auth.test.ts @@ -0,0 +1,69 @@ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import ngDevtoolsVite from '../vite.ts'; + +type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void; + +const servers: Server[] = []; + +async function devServer(allowedHosts?: readonly string[] | true) { + const middlewares: Middleware[] = []; + const httpServer = createServer((req, res) => { + const run = (i: number): void => { + const middleware = middlewares[i]; + if (!middleware) { + res.statusCode = 404; + res.end(); + return; + } + middleware(req, res, () => run(i + 1)); + }; + run(0); + }); + servers.push(httpServer); + const plugin = ngDevtoolsVite({ apiPrefix: 'api' }); + (plugin.configureServer as (server: unknown) => void)({ + config: { root: process.cwd(), server: { allowedHosts } }, + middlewares: { use: (middleware: Middleware) => middlewares.push(middleware) }, + httpServer, + }); + await new Promise((resolve) => httpServer.listen(0, '127.0.0.1', resolve)); + const { port } = httpServer.address() as AddressInfo; + return (token?: string) => + fetch(`http://127.0.0.1:${port}/__devframes/__mcp`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + origin: `http://localhost:${port}`, + ...(token === undefined ? {} : { authorization: `Bearer ${token}` }), + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }), + }); +} + +afterEach(async () => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + for (const server of servers.splice(0)) { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } +}); + +describe('ngDevtoolsVite MCP route', () => { + it('stays open for a purely local dev server', async () => { + const mcp = await devServer(); + expect((await mcp()).status).toBe(200); + }); + + it('asks for the MCP token once a tunnel host is allowed', async () => { + vi.stubEnv('NG_DEVTOOLS_MCP_TOKEN', 'tunnel-secret'); + vi.spyOn(console, 'log').mockImplementation(() => {}); + const mcp = await devServer(['abc.trycloudflare.com']); + expect((await mcp()).status).toBe(401); + expect((await mcp('wrong')).status).toBe(401); + expect((await mcp('tunnel-secret')).status).toBe(200); + }); +}); diff --git a/packages/ng-devtools/src/hub.ts b/packages/ng-devtools/src/hub.ts index fae6e0cc..3f01f23b 100644 --- a/packages/ng-devtools/src/hub.ts +++ b/packages/ng-devtools/src/hub.ts @@ -1,3 +1,4 @@ +import { randomBytes } from 'node:crypto'; import { existsSync } from 'node:fs'; import { createRequire } from 'node:module'; import { dirname, join } from 'node:path'; @@ -11,6 +12,8 @@ const LOGO = `>; function hubUiClientDir(): string | undefined { @@ -41,12 +44,30 @@ function hubUi() { }; } +function mcpToken(): string { + const fromEnv = process.env[NG_DEVTOOLS_MCP_TOKEN_ENV]; + if (fromEnv) return fromEnv; + const token = randomBytes(24).toString('base64url'); + console.log( + `\n ng-devtools MCP token: ${token}\n` + + ` HTTP MCP clients send it as "Authorization: Bearer ".\n` + + ` Set ${NG_DEVTOOLS_MCP_TOKEN_ENV} to keep it the same across restarts.\n`, + ); + return token; +} + +function hubMcpFor(options: NgDevtoolsHubOptions): InitHubOptions['mcp'] { + if (options.mcp !== undefined || options.auth === false) return options.mcp; + return { authorization: mcpToken() }; +} + export function initNgDevtoolsHub(options: NgDevtoolsHubOptions = {}) { return initHub({ name: 'ng-devtools', version: pkg.version, base: NG_DEVTOOLS_HUB_BASE, ...options, + mcp: hubMcpFor(options), devframes: [ngDevtools], ui: hubUi(), }); From 909b3ce2d4a0d5b3eae61643f83e2d19316e1c60 Mon Sep 17 00:00:00 2001 From: Kam Date: Wed, 30 Sep 2026 13:03:33 +0300 Subject: [PATCH 3/4] docs: describe the Vite plugin's auth option and when the one-time code turns on --- apps/docs/src/content/getting-started/vite.md | 32 +++++++++++++++---- apps/docs/src/content/security.md | 18 ++++++++--- 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/apps/docs/src/content/getting-started/vite.md b/apps/docs/src/content/getting-started/vite.md index 67605990..9c258347 100644 --- a/apps/docs/src/content/getting-started/vite.md +++ b/apps/docs/src/content/getting-started/vite.md @@ -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 @@ -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` @@ -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 @@ -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 diff --git a/apps/docs/src/content/security.md b/apps/docs/src/content/security.md index 3136d7ff..71dc2de6 100644 --- a/apps/docs/src/content/security.md +++ b/apps/docs/src/content/security.md @@ -19,7 +19,7 @@ The devtools read your running app and send what they find to a server on your m - Loopback requests only. A request that sends an Origin must come from a loopback host, a Chrome extension, allowedOrigins or Vite's server.allowedHosts. + Loopback requests only. A request that sends an Origin must come from a loopback host, a Chrome extension, allowedOrigins or Vite's server.allowedHosts. Asks for a one-time code when a non-loopback host or origin is allowed. A one-time code and a loopback origin check. Both on by default. @@ -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. - 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 Host header to localhost, nothing in your config names the tunnel, so pass auth: true. Don't pass auth: false while a tunnel is allowed. ### Express hub @@ -178,7 +188,7 @@ Response previews and TransferState values in the [SSR & HTTP tab](/inspectors/s Open the app on localhost. Add other hostnames or origins one by one, only when you need them. - Keep auth and the origin check on in the Express hub unless the machine is yours alone. + Keep auth and the origin check on in the Express hub unless the machine is yours alone. In the Vite plugin, don't pass auth: false while a tunnel host or origin is allowed. Keep real credentials out of forms and API responses you inspect. From b9bba91d9e33f4279f8704cc54f1f79ba8dc5e70 Mon Sep 17 00:00:00 2001 From: Kam Date: Wed, 30 Sep 2026 13:06:16 +0300 Subject: [PATCH 4/4] docs: describe the bearer token on the HTTP MCP endpoint --- apps/docs/src/content/agents/mcp-server.md | 52 +++++++++++++++++-- .../src/content/getting-started/express.md | 14 ++--- apps/docs/src/content/security.md | 4 +- 3 files changed, 57 insertions(+), 13 deletions(-) diff --git a/apps/docs/src/content/agents/mcp-server.md b/apps/docs/src/content/agents/mcp-server.md index 84f2a53d..706616bf 100644 --- a/apps/docs/src/content/agents/mcp-server.md +++ b/apps/docs/src/content/agents/mcp-server.md @@ -104,11 +104,37 @@ If you mount the devtools panel without the hub, at `/__ng-devtools/`, the endpo The header value is the origin of your dev server. Every example below sets it. +### Send a token + +If the hub asks for the one-time code, the HTTP endpoint also asks for a bearer token. Requests without the right token get `401`. + +| Setup | Token required | +| --------------------------------------- | ------------------------------------------------------------------------------------------------ | +| [Express hub](/getting-started/express) | Yes, unless you pass `auth: false` or your own `mcp` option. | +| [Vite plugin](/getting-started/vite) | Only when the one-time code is on. See the plugin's [`auth` option](/getting-started/vite#auth). | + +The hub prints a generated token in the terminal when it starts. The token changes on every restart. To keep the same token across restarts, set `NG_DEVTOOLS_MCP_TOKEN` in the environment of the server. The hub then uses that value and prints nothing. + +Send the token in an `Authorization: Bearer ` header, next to the `Origin` header. If your setup needs no token, leave the `Authorization` header out. + +The stdio server never needs a token. + ### Add the HTTP endpoint to your client -```bash group="http" name="Claude Code" active -claude mcp add --transport http ng-devtools http://localhost:4000/__devframes/__mcp \ - --header "Origin: http://localhost:4000" +```json group="http" name="Claude Code" active +// .mcp.json +{ + "mcpServers": { + "ng-devtools": { + "type": "http", + "url": "http://localhost:4000/__devframes/__mcp", + "headers": { + "Authorization": "Bearer ${NG_DEVTOOLS_MCP_TOKEN}", + "Origin": "http://localhost:4000" + } + } + } +} ``` ```json group="http" name="Cursor" @@ -117,7 +143,10 @@ claude mcp add --transport http ng-devtools http://localhost:4000/__devframes/__ "mcpServers": { "ng-devtools": { "url": "http://localhost:4000/__devframes/__mcp", - "headers": {"Origin": "http://localhost:4000"} + "headers": { + "Authorization": "Bearer ${env:NG_DEVTOOLS_MCP_TOKEN}", + "Origin": "http://localhost:4000" + } } } } @@ -126,16 +155,29 @@ claude mcp add --transport http ng-devtools http://localhost:4000/__devframes/__ ```json group="http" name="VS Code" // .vscode/mcp.json { + "inputs": [ + { + "type": "promptString", + "id": "ng-devtools-token", + "description": "ng-devtools MCP token", + "password": true + } + ], "servers": { "ng-devtools": { "type": "http", "url": "http://localhost:4000/__devframes/__mcp", - "headers": {"Origin": "http://localhost:4000"} + "headers": { + "Authorization": "Bearer ${input:ng-devtools-token}", + "Origin": "http://localhost:4000" + } } } } ``` +The Claude Code and Cursor examples read the token from `NG_DEVTOOLS_MCP_TOKEN`, so set the same value for the server and the client. VS Code asks for the token the first time it starts the server. + ### Open the app in a browser The live tools read what the page reports. Without an open page, they have nothing to answer with. diff --git a/apps/docs/src/content/getting-started/express.md b/apps/docs/src/content/getting-started/express.md index 532322c6..bd47bbdd 100644 --- a/apps/docs/src/content/getting-started/express.md +++ b/apps/docs/src/content/getting-started/express.md @@ -91,13 +91,13 @@ With `ws: {sidecar: true}`, the WebSocket runs on its own port, picked automatic `initNgDevtoolsHub()` accepts the options of `initHub()` from `@devframes/hub`, apart from `devframes` and `ui`. These are the ones you are most likely to set: -| Option | Default | What it does | -| ---------------- | ----------------- | --------------------------------------------------------------------------------------------- | -| `base` | `'/__devframes/'` | Where the hub is mounted. The devtools panel lives at `ng-devtools/`. | -| `ws` | | `false` uses server-sent events only. `{ sidecar: true }` runs the WebSocket on its own port. | -| `auth` | on | `false` turns off the one-time code. | -| `allowedOrigins` | loopback origins | Extra origins allowed to open the WebSocket. `false` turns the origin check off. | -| `mcp` | `'auto'` | Mounts the MCP endpoint at `__mcp` once agent tools exist. | +| Option | Default | What it does | +| ---------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `base` | `'/__devframes/'` | Where the hub is mounted. The devtools panel lives at `ng-devtools/`. | +| `ws` | | `false` uses server-sent events only. `{ sidecar: true }` runs the WebSocket on its own port. | +| `auth` | on | `false` turns off the one-time code. | +| `allowedOrigins` | loopback origins | Extra origins allowed to open the WebSocket. `false` turns the origin check off. | +| `mcp` | a bearer token | Mounts the MCP endpoint at `__mcp` and asks for a bearer token. With `auth: false` the default is `'auto'`: it mounts once agent tools exist and asks for no token. See [Send a token](/agents/mcp-server#send-a-token). | ### Access control diff --git a/apps/docs/src/content/security.md b/apps/docs/src/content/security.md index 71dc2de6..8593dc9b 100644 --- a/apps/docs/src/content/security.md +++ b/apps/docs/src/content/security.md @@ -107,7 +107,9 @@ The CLI server binds to `localhost` and asks for a one-time code. `--host` chang ### MCP endpoint -The HTTP MCP endpoint answers only requests from a loopback address that carry a loopback `Origin` header. See [MCP server](/agents/mcp-server). +The HTTP MCP endpoint answers only requests from a loopback address that carry a loopback `Origin` header. + +While the one-time code is on, the endpoint also asks for a bearer token. That is the Express hub by default, and the Vite plugin when its code is on. The hub prints a generated token when it starts. Set `NG_DEVTOOLS_MCP_TOKEN` to choose the token yourself. Requests without the right `Authorization: Bearer ` header get `401`. The stdio server needs no token. See [Send a token](/agents/mcp-server#send-a-token). ### Chrome extension