Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): rename publicUrl to externalUrl with aliases (PRD-7944) (#3434)
omar-inkeep42c12dc3d6b1
diff --git a/.changeset/external-url-rename.md b/.changeset/external-url-rename.mdnew file mode 100644index 000000000..84b5e70b1--- /dev/null+++ b/.changeset/external-url-rename.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": minor+---++The canonical external origin setting is renamed from `publicUrl` to `externalUrl` across all three configuration surfaces: the config key is now `server.externalUrl`, the environment variable `OK_EXTERNAL_URL`, and the CLI flag `ok start --external-url <url>`. "Public" wrongly implied an internet-public, unauthenticated server; the field really names the external-facing origin, which commonly sits behind Tailscale, Cloudflare Access, or other edge auth. The old spellings — `server.publicUrl`, `OK_PUBLIC_URL`, and `--public-url` — keep working as deprecated aliases with identical semantics and precedence, and each use prints a deprecation notice naming the new spelling. They will be removed in a later release.++One caution for shared (committed) configs: older app versions read only `server.publicUrl` and silently ignore `server.externalUrl`, so renaming the committed key strands collaborators who have not upgraded on a loopback-derived origin. While a team is mid-upgrade, commit both keys with the same value — new versions prefer `server.externalUrl` (no notice when both are set) and old versions keep reading `server.publicUrl`; drop the old key once everyone is current.diff --git a/docs/content/deploy/remote-access.mdx b/docs/content/deploy/remote-access.mdxindex e1ef01491..c933f5908 100644--- a/docs/content/deploy/remote-access.mdx+++ b/docs/content/deploy/remote-access.mdx@@ -6,7 +6,7 @@ description: Reach your knowledge base from your other devices.By default, only agents on the same machine as your knowledge base can reach it. Remote access puts that same endpoint behind an HTTPS tunnel (ngrok, Cloudflare Tunnel, Tailscale, or your own reverse proxy) so your other devices can connect to one shared knowledge base.<Callout type="warn">-`--remote` is deprecated. It still works exactly as documented below, but it is now an alias for the general networking keys: `OK_IDLE_SHUTDOWN=off OK_ALLOW_EXTERNAL=1 ok start --public-url <url>` is the equivalent invocation (or set `server.publicUrl`, `server.allowExternal`, and `server.idleShutdown: off` in config — without `idleShutdown: off` the server shuts down after 30 idle minutes even while remote agents are using it, because the idle timer only counts editor connections). Prefer that spelling for new setups — `--remote` will be removed in a later release.+`--remote` is deprecated. It still works exactly as documented below, but it is now an alias for the general networking keys: `OK_IDLE_SHUTDOWN=off OK_ALLOW_EXTERNAL=1 ok start --external-url <url>` is the equivalent invocation (or set `server.externalUrl`, `server.allowExternal`, and `server.idleShutdown: off` in config — without `idleShutdown: off` the server shuts down after 30 idle minutes even while remote agents are using it, because the idle timer only counts editor connections). Prefer that spelling for new setups — `--remote` will be removed in a later release.</Callout>OpenKnowledge does not authenticate remote callers. Once you pass `--remote`, anyone who can reach your tunnel URL has full read-write control, so restricting who reaches it is up to the tunnel. Put it on a private network like Tailscale, add edge auth like ngrok OAuth or Cloudflare Access, or just keep the URL to yourself. The server ignores tunneled traffic until you start it with `--remote`, so you never expose the base by accident.diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 8da6af5a4..8d95f89a7 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -118,8 +118,8 @@ Serve this project's web UI and `/mcp` endpoint to your other devices through an| Command | What it does || --- | --- |-| `ok start --public-url <url>` | Declare the canonical external origin clients dial (sets `server.publicUrl` for this run) — its host joins the Host/Origin allowlists and issued URLs. External exposure additionally requires consent (`OK_ALLOW_EXTERNAL=1` or `server.allowExternal`). For remote MCP use also set `OK_IDLE_SHUTDOWN=off` — the idle timer only counts editor (WS) connections and would stop the server under a live remote agent |-| `ok start --remote [url]` | Deprecated alias for `--public-url <url>` plus `OK_ALLOW_EXTERNAL` consent on a loopback bind. Starts the server admitting requests from the tunnel URL (no server-side auth; restrict reach at the tunnel). Bare `--remote` uses `remote.url` from `.ok/config.yml` |+| `ok start --external-url <url>` | Declare the canonical external origin clients dial (sets `server.externalUrl` for this run) — its host joins the Host/Origin allowlists and issued URLs. External exposure additionally requires consent (`OK_ALLOW_EXTERNAL=1` or `server.allowExternal`). For remote MCP use also set `OK_IDLE_SHUTDOWN=off` — the idle timer only counts editor (WS) connections and would stop the server under a live remote agent. `--public-url` (the flag's former name) remains a deprecated alias |+| `ok start --remote [url]` | Deprecated alias for `--external-url <url>` plus `OK_ALLOW_EXTERNAL` consent on a loopback bind. Starts the server admitting requests from the tunnel URL (no server-side auth; restrict reach at the tunnel). Bare `--remote` uses `remote.url` from `.ok/config.yml` |## More commandsdiff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex 0d231445a..3ac633ff0 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -49,10 +49,11 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi| `autoSync.default` | `"off" \| "follow" \| "full" \| boolean \| null` | `null` | project | Committed seed for each machine's first-open sync mode: `off` / `follow` / `full`, or the legacy boolean (`true` = full, `false` = off). `null` = ask. Lets a maintainer pre-answer the onboarding prompt for everyone who clones; a per-machine `autoSync.mode` overrides it. Compatibility note: a committed string value (`off` / `follow` / `full`) is rejected by app versions released before `autoSync.mode` existed, resetting that machine to config defaults until it updates (it never silently syncs). The legacy boolean seed (`true` / `false`) stays readable by older apps — commit `follow` only once collaborators are on a current version. || `server.bind` | list of addresses | `["127.0.0.1"]` | project | Addresses the server binds, e.g. `[127.0.0.1]` or `[0.0.0.0]`. The loopback default keeps everything off-machine out. A non-loopback bind additionally requires the `server.allowExternal` consent interlock. Lists replace, never merge. Env: `OK_BIND` (space-separated). Read at server start. || `server.port` | number | (unset) | project | TCP port the server listens on. Unset = a local start picks a free port dynamically (deployment platforms inject `PORT` instead). Supersedes `remote.port`, which is still read while this key is absent. Read at server start. |-| `server.publicUrl` | string | (unset) | project | Canonical external origin the server is reached at, e.g. `https://kb.example.com` — its host joins the Host/Origin allowlists and issued URLs. Setting it declares external exposure, which additionally requires the `server.allowExternal` consent interlock. Supersedes `remote.url` (still read while this key is absent). Env: `OK_PUBLIC_URL`; flag: `ok start --public-url <url>`. Read at server start. |-| `server.allowExternal` | boolean | `false` | project-local | Exposure consent interlock: a non-loopback `server.bind` (or external requests behind a proxy declared via `server.publicUrl`) is refused without it. Per-machine — consent never travels via git, clone, or share; containers consent via `OK_ALLOW_EXTERNAL=1` instead. There is no server-side auth: restrict who can reach the server at the edge. |+| `server.externalUrl` | string | (unset) | project | Canonical external origin the server is reached at, e.g. `https://kb.example.com` — its host joins the Host/Origin allowlists and issued URLs. Setting it declares external exposure, which additionally requires the `server.allowExternal` consent interlock. Supersedes `server.publicUrl` (the key's former name — still read as a deprecated alias while this key is absent) and `remote.url`. Env: `OK_EXTERNAL_URL` (`OK_PUBLIC_URL` remains a deprecated alias); flag: `ok start --external-url <url>`. Read at server start. Compatibility note: app versions from before this key existed read only `server.publicUrl` and silently ignore `server.externalUrl` (config is open-shape), so committing only the new key drops the declared host from those versions' Host/Origin allowlists and external requests 403. While collaborators are still on older versions, commit **both** keys with the same value — current versions prefer `server.externalUrl` (no deprecation notice when both are set) and older versions keep reading `server.publicUrl`; drop the old key once everyone has upgraded. |+| `server.publicUrl` | string | (unset) | project | Deprecated alias of `server.externalUrl` (the key's former name) — read only while that key is absent, with identical semantics; the CLI prints a rename notice when it is the one in effect. Env alias: `OK_PUBLIC_URL`; flag alias: `ok start --public-url <url>`. May be committed alongside `server.externalUrl` during a mixed-version window (see that key's compatibility note). Slated for removal after a deprecation window. |+| `server.allowExternal` | boolean | `false` | project-local | Exposure consent interlock: a non-loopback `server.bind` (or external requests behind a proxy declared via `server.externalUrl`) is refused without it. Per-machine — consent never travels via git, clone, or share; containers consent via `OK_ALLOW_EXTERNAL=1` instead. There is no server-side auth: restrict who can reach the server at the edge. || `server.idleShutdown` | `"off"` or duration (`90s`, `30m`, `2h`) | derived: `30m` loopback-only, `off` otherwise | project-local | Shut the server down after this long with no connected editor (WebSocket) clients. Remote MCP sessions are plain HTTP the timer cannot see — set `off` (or `OK_IDLE_SHUTDOWN=off`) when remote agents use the server, or it tears down under them mid-session. |-| `remote.url` | string | (unset) | project | Superseded by `server.publicUrl` (read only while that key is absent). Public tunnel URL remote clients connect to (e.g. `https://myproject.ngrok.app`); its host is admitted through the Host-header allowlist. Used only when the server is started with the deprecated `ok start --remote` (config alone never enables remote access, and there is no server-side auth). See [Remote access](/docs/deploy/remote-access). |+| `remote.url` | string | (unset) | project | Superseded by `server.externalUrl` (read only while that key is absent). Public tunnel URL remote clients connect to (e.g. `https://myproject.ngrok.app`); its host is admitted through the Host-header allowlist. Used only when the server is started with the deprecated `ok start --remote` (config alone never enables remote access, and there is no server-side auth). See [Remote access](/docs/deploy/remote-access). || `remote.port` | number | `24550` | project | Superseded by `server.port` (read only while that key is absent). Fixed TCP port the server binds when remote access is enabled, so the tunnel's port mapping survives restarts. See [Remote access](/docs/deploy/remote-access). || `editor.wordWrap` | boolean | `true` | user | Soft-wrap long lines in the source-mode CodeMirror editor. A personal preference, not project-shared. Toggle from the Settings pane. || `editor.previewTabs` | boolean | `true` | user | Reuse one replaceable preview tab for single clicks in the Files tree and Skills sidebar, so browsing does not accumulate tabs. Double-click the tab title, pin it, or choose **Keep open** from its context menu to make it permanent. Set `false` to open every click in its own tab. Rename transitions still reuse the current tab; back/forward navigation focuses the target's existing tab, or opens a permanent one when it is no longer open. A personal preference; toggle it from **Settings → Preferences → Preview tabs**. |diff --git a/knip.config.ts b/knip.config.tsindex f9179f2d4..78162ec09 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -123,9 +123,7 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: [- '@types/shell-quote',- ],+ ignoreDependencies: ['@types/shell-quote'],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.tsindex 1e3a69056..43a1b03c8 100644--- a/packages/app/src/server/hocuspocus-plugin.ts+++ b/packages/app/src/server/hocuspocus-plugin.ts@@ -319,8 +319,8 @@ export function hocuspocusPlugin(): Plugin {// the browser actually sends. Known dev-mode limitation: under// `vite --host` (LAN testing from a phone/second machine) content// assets 403 while the shell still loads, so images render broken —- // there is no dev-side publicUrl to admit the LAN Host. For LAN/tailnet- // testing use `ok start --bind <ip>` + `OK_PUBLIC_URL`, which builds a+ // there is no dev-side externalUrl to admit the LAN Host. For LAN/tailnet+ // testing use `ok start --bind <ip>` + `OK_EXTERNAL_URL`, which builds a// real policy that admits the declared Host.ingressPolicy: buildIngressPolicy({}),});diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.tsindex 350df5971..6ed06199a 100644--- a/packages/cli/src/commands/start.test.ts+++ b/packages/cli/src/commands/start.test.ts@@ -25,11 +25,13 @@ import {isLoopbackHost,isServerLockCollision,OkDirMissingError,+ parseExternalUrlFlag,parseIdleShutdownFlag,parseOnlyModule,parsePublicUrlFlag,resolveBundledReactShellDir,resolveCollabPort,+ resolveFlagExternalUrl,resolveHost,resolveServerReuse,resolveStartConsoleLevel,@@ -103,15 +105,15 @@ describe('expandRemoteAlias — --remote is a thin alias over the server.* keys'return alias;}- test('expands to exactly the ratified keys — publicUrl + allowExternal + idleShutdown off', () => {+ test('expands to exactly the ratified keys — externalUrl + allowExternal + idleShutdown off', () => {expect(expandRemoteAlias(TUNNEL_URL, undefined)).toEqual({ok: true,url: TUNNEL_URL,- serverOverlay: { publicUrl: TUNNEL_URL, allowExternal: true, idleShutdown: 'off' },+ serverOverlay: { externalUrl: TUNNEL_URL, allowExternal: true, idleShutdown: 'off' },});});- test('resolves an identical server runtime to the equivalent --public-url invocation', () => {+ test('resolves an identical server runtime to the equivalent --external-url invocation', () => {const config = makeTestConfig();const alias = expectExpanded(expandRemoteAlias(TUNNEL_URL, undefined));// What runStartCommand overlays for `ok start --remote <url>` …@@ -121,17 +123,17 @@ describe('expandRemoteAlias — --remote is a thin alias over the server.* keys'}) as Config,);// … versus the ratified spelling of the same deployment:- // `OK_ALLOW_EXTERNAL=1 OK_IDLE_SHUTDOWN=off ok start --public-url <url> --bind 127.0.0.1`.+ // `OK_ALLOW_EXTERNAL=1 OK_IDLE_SHUTDOWN=off ok start --external-url <url> --bind 127.0.0.1`.const env = resolveEnvConfigLayer({ OK_ALLOW_EXTERNAL: '1', OK_IDLE_SHUTDOWN: 'off' });const explicitRuntime = resolveServerRuntimeConfig(applyConfigOverlay(applyConfigOverlay(config, env.layer), {- server: { bind: ['127.0.0.1'], publicUrl: TUNNEL_URL },+ server: { bind: ['127.0.0.1'], externalUrl: TUNNEL_URL },}) as Config,);expect(aliasRuntime).toEqual(explicitRuntime);- // The load-bearing shape: successor-key publicUrl (drives the ingress+ // The load-bearing shape: successor-key externalUrl (drives the ingress// policy + issued URLs), consent armed, loopback-only bind.- expect(aliasRuntime.publicUrlSource).toBe('server');+ expect(aliasRuntime.externalUrlSource).toBe('server');expect(aliasRuntime.allowExternal).toBe(true);expect(aliasRuntime.loopbackOnly).toBe(true);expect(aliasRuntime.idleShutdown).toBe('off');@@ -152,7 +154,7 @@ describe('expandRemoteAlias — --remote is a thin alias over the server.* keys'test('trailing slashes are stripped, matching the legacy resolver', () => {const alias = expectExpanded(expandRemoteAlias(`${TUNNEL_URL}/`, undefined));expect(alias.url).toBe(TUNNEL_URL);- expect(alias.serverOverlay.publicUrl).toBe(TUNNEL_URL);+ expect(alias.serverOverlay.externalUrl).toBe(TUNNEL_URL);});test('missing url anywhere refuses with the fix instruction', () => {@@ -174,7 +176,7 @@ describe('expandRemoteAlias — --remote is a thin alias over the server.* keys'describe('scopeRemoteAliasConsentToBind — self-consent is loopback-scoped', () => {const overlay = {- publicUrl: 'https://myproject.ngrok.app',+ externalUrl: 'https://myproject.ngrok.app',allowExternal: true,idleShutdown: 'off',} as const;@@ -191,7 +193,7 @@ describe('scopeRemoteAliasConsentToBind — self-consent is loopback-scoped', ()// consent in.const scoped = scopeRemoteAliasConsentToBind(overlay, ['192.168.1.5']);expect('allowExternal' in scoped).toBe(false);- expect(scoped.publicUrl).toBe(overlay.publicUrl);+ expect(scoped.externalUrl).toBe(overlay.externalUrl);const runtime = resolveServerRuntimeConfig(applyConfigOverlay(makeTestConfig(), {server: { bind: ['192.168.1.5'], ...scoped },@@ -208,18 +210,71 @@ describe('scopeRemoteAliasConsentToBind — self-consent is loopback-scoped', ()});});-describe('parsePublicUrlFlag', () => {+describe('parseExternalUrlFlag', () => {test('accepts http and https origins (http covers tailnet/LAN deployments)', () => {- expect(parsePublicUrlFlag('https://kb.example.com')).toBe('https://kb.example.com');- expect(parsePublicUrlFlag('http://laptop.tail:55222')).toBe('http://laptop.tail:55222');+ expect(parseExternalUrlFlag('https://kb.example.com')).toBe('https://kb.example.com');+ expect(parseExternalUrlFlag('http://laptop.tail:55222')).toBe('http://laptop.tail:55222');});test('rejects garbage and non-http(s) schemes', () => {- expect(() => parsePublicUrlFlag('not a url')).toThrow(/not a valid URL/);+ expect(() => parseExternalUrlFlag('not a url')).toThrow(/not a valid URL/);+ expect(() => parseExternalUrlFlag('ftp://kb.example.com')).toThrow(/http\(s\) origin/);+ });++ test('flag errors name the flag the user typed', () => {+ expect(() => parseExternalUrlFlag('not a url')).toThrow(/--external-url/);+ expect(() => parsePublicUrlFlag('not a url')).toThrow(/--public-url/);+ });+});++describe('parsePublicUrlFlag (deprecated --public-url alias)', () => {+ test('validates with the same http(s)-origin shape as --external-url', () => {+ expect(parsePublicUrlFlag('https://kb.example.com')).toBe('https://kb.example.com');+ expect(parsePublicUrlFlag('http://laptop.tail:55222')).toBe('http://laptop.tail:55222');expect(() => parsePublicUrlFlag('ftp://kb.example.com')).toThrow(/http\(s\) origin/);});});+describe('resolveFlagExternalUrl (the flag-layer fold)', () => {+ test('the deprecated --public-url spelling still sets the value when it is the only flag given', () => {+ // The regression this pins: dropping the publicUrl fallback would leave a+ // --public-url-only start with externalUrl undefined — no CORS/Host+ // admission for the declared host and no issued URLs, with no parse error+ // to signal it during the deprecation window.+ expect(resolveFlagExternalUrl({ publicUrl: 'https://kb.example.com' })).toBe(+ 'https://kb.example.com',+ );+ expect(resolveFlagExternalUrl({ externalUrl: 'https://kb.example.com' })).toBe(+ 'https://kb.example.com',+ );+ expect(resolveFlagExternalUrl({})).toBeUndefined();+ });++ test('a --public-url-only invocation resolves the identical runtime to --external-url', () => {+ // Mirrors the expandRemoteAlias parity test above: apply exactly what+ // runStartCommand overlays for each spelling and compare the resolved+ // runtimes end to end.+ const url = 'https://kb.example.com';+ const config = makeTestConfig();+ const viaDeprecated = resolveServerRuntimeConfig(+ applyConfigOverlay(config, {+ server: { bind: ['127.0.0.1'], externalUrl: resolveFlagExternalUrl({ publicUrl: url }) },+ }) as Config,+ );+ const viaCanonical = resolveServerRuntimeConfig(+ applyConfigOverlay(config, {+ server: { bind: ['127.0.0.1'], externalUrl: resolveFlagExternalUrl({ externalUrl: url }) },+ }) as Config,+ );+ expect(viaDeprecated).toEqual(viaCanonical);+ expect(viaDeprecated.externalUrl).toBe(url);+ // Both spellings write the successor key, so the runtime reads as the+ // canonical server-section origin with no deprecated-config-key signal.+ expect(viaDeprecated.externalUrlSource).toBe('server');+ expect(viaDeprecated.externalUrlFromDeprecatedKey).toBe(false);+ });+});+describe('formatShutdownNotice', () => {test('SIGINT includes the headline, the wait notice, and the force-quit hint', () => {const lines = formatShutdownNotice('SIGINT');@@ -1776,8 +1831,8 @@ describe('--idle-shutdown threading through Commander (regression)', () => {});describe('startCommand — flag-conflict guards (exit 2)', () => {- function quietCommand() {- const cmd = startCommand(() => makeTestConfig());+ function quietCommand(config?: Config) {+ const cmd = startCommand(() => config ?? makeTestConfig());cmd.exitOverride();cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} });return cmd;@@ -1790,8 +1845,9 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {*/async function captureGuard(argv: string[],+ config?: Config,): Promise<{ code: number | undefined; stderr: string }> {- const cmd = quietCommand();+ const cmd = quietCommand(config);let code: number | undefined;let stderr = '';const originalExit = process.exit;@@ -1879,7 +1935,18 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {expect(stderr).toContain('--single-file');});- test('--remote + --public-url exits 2 (the alias IS a public-url; one must win)', async () => {+ test('--remote + --external-url exits 2 (the alias IS an external-url; one must win)', async () => {+ const { code, stderr } = await captureGuard([+ '--remote',+ 'https://tunnel.example.com',+ '--external-url',+ 'https://kb.example.com',+ ]);+ expect(code).toBe(2);+ expect(stderr).toContain('--external-url');+ });++ test('--remote + deprecated --public-url exits 2 with the alias named', async () => {const { code, stderr } = await captureGuard(['--remote','https://tunnel.example.com',@@ -1890,6 +1957,17 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {expect(stderr).toContain('--public-url');});+ test('--external-url + deprecated --public-url exits 2 (same flag under two names)', async () => {+ const { code, stderr } = await captureGuard([+ '--external-url',+ 'https://new.example.com',+ '--public-url',+ 'https://old.example.com',+ ]);+ expect(code).toBe(2);+ expect(stderr).toContain('deprecated alias');+ });+/*** The pre-boot `--remote` refusals print via console.warn/console.error* (vitest intercepts the console, so `captureGuard`'s stderr stub never@@ -1897,6 +1975,7 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {*/async function captureRemoteRefusal(argv: string[],+ config?: Config,): Promise<{ code: number | undefined; output: string }> {const lines: string[] = [];const record = (...args: unknown[]) => {@@ -1905,7 +1984,7 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {const warnSpy = vi.spyOn(console, 'warn').mockImplementation(record);const errorSpy = vi.spyOn(console, 'error').mockImplementation(record);try {- const { code, stderr } = await captureGuard(argv);+ const { code, stderr } = await captureGuard(argv, config);return { code, output: `${stderr}\n${lines.join('\n')}` };} finally {warnSpy.mockRestore();@@ -1918,13 +1997,13 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {expect(code).toBe(78);expect(output).toContain('--remote requires a public tunnel URL');// The deprecation notice fires even on the refusal path — EXACTLY once —- // and names every key the alias pins (--public-url / --bind /+ // and names every key the alias pins (--external-url / --bind /// OK_ALLOW_EXTERNAL / OK_IDLE_SHUTDOWN=off), so an operator learns the// full ratified spelling from the same run that errors. Omitting the// idle-shutdown key would hand migrators a server that tears itself down// after 30 idle minutes under a live remote MCP client.expect(output.split('--remote is deprecated').length - 1).toBe(1);- expect(output).toContain('--public-url');+ expect(output).toContain('--external-url');expect(output).toContain('--bind');expect(output).toContain('OK_ALLOW_EXTERNAL');expect(output).toContain('OK_IDLE_SHUTDOWN=off');@@ -1946,4 +2025,98 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {expect(output.split('`--only ui` is deprecated').length - 1).toBe(1);expect(output).toContain('ok start');});++ // The rename notices share the --remote ordering contract: they print+ // BEFORE the env layer parses, so pairing the deprecated spelling with a+ // malformed env var proves the notice survives a refusal path without+ // booting a server (env refusal = exit 78).+ test('deprecated --public-url still parses and prints the rename notice (refusal path)', async () => {+ const prior = process.env.OK_OPEN_BROWSER;+ process.env.OK_OPEN_BROWSER = 'not-a-boolean';+ try {+ const { code, output } = await captureRemoteRefusal([+ '--public-url',+ 'https://kb.example.com',+ ]);+ expect(code).toBe(78);+ expect(output.split('--public-url is deprecated').length - 1).toBe(1);+ expect(output).toContain('--external-url');+ } finally {+ if (prior === undefined) delete process.env.OK_OPEN_BROWSER;+ else process.env.OK_OPEN_BROWSER = prior;+ }+ });++ test('a config-file server.publicUrl prints the rename notice (refusal path)', async () => {+ const prior = process.env.OK_OPEN_BROWSER;+ process.env.OK_OPEN_BROWSER = 'not-a-boolean';+ try {+ const config = ConfigSchema.parse({+ server: { publicUrl: 'https://kb.example.com' },+ });+ const { code, output } = await captureRemoteRefusal([], config);+ expect(code).toBe(78);+ expect(output.split('server.publicUrl is deprecated').length - 1).toBe(1);+ expect(output).toContain('server.externalUrl');+ } finally {+ if (prior === undefined) delete process.env.OK_OPEN_BROWSER;+ else process.env.OK_OPEN_BROWSER = prior;+ }+ });++ test('the config-file notice still fires when a flag or env override masks the value', async () => {+ // The notice is keyed off the FILE layers before the env/flag overlay: a+ // masking override changes which value wins for this run, but the stale+ // committed key still needs renaming, so suppressing the notice would+ // hide exactly the config the operator has to fix.+ const prior = process.env.OK_OPEN_BROWSER;+ process.env.OK_OPEN_BROWSER = 'not-a-boolean';+ try {+ const config = ConfigSchema.parse({+ server: { publicUrl: 'https://committed.example.com' },+ });+ const flagMasked = await captureRemoteRefusal(+ ['--external-url', 'https://flag.example.com'],+ config,+ );+ expect(flagMasked.code).toBe(78);+ expect(flagMasked.output.split('server.publicUrl is deprecated').length - 1).toBe(1);+ } finally {+ if (prior === undefined) delete process.env.OK_OPEN_BROWSER;+ else process.env.OK_OPEN_BROWSER = prior;+ }++ const priorEnv = process.env.OK_EXTERNAL_URL;+ const priorOpen = process.env.OK_OPEN_BROWSER;+ process.env.OK_EXTERNAL_URL = 'https://env.example.com';+ process.env.OK_OPEN_BROWSER = 'not-a-boolean';+ try {+ const config = ConfigSchema.parse({+ server: { publicUrl: 'https://committed.example.com' },+ });+ const envMasked = await captureRemoteRefusal([], config);+ expect(envMasked.code).toBe(78);+ expect(envMasked.output.split('server.publicUrl is deprecated').length - 1).toBe(1);+ } finally {+ if (priorEnv === undefined) delete process.env.OK_EXTERNAL_URL;+ else process.env.OK_EXTERNAL_URL = priorEnv;+ if (priorOpen === undefined) delete process.env.OK_OPEN_BROWSER;+ else process.env.OK_OPEN_BROWSER = priorOpen;+ }+ });++ test('a config-file server.externalUrl (successor) prints no rename notice', async () => {+ const prior = process.env.OK_OPEN_BROWSER;+ process.env.OK_OPEN_BROWSER = 'not-a-boolean';+ try {+ const config = ConfigSchema.parse({+ server: { externalUrl: 'https://kb.example.com' },+ });+ const { output } = await captureRemoteRefusal([], config);+ expect(output).not.toContain('server.publicUrl is deprecated');+ } finally {+ if (prior === undefined) delete process.env.OK_OPEN_BROWSER;+ else process.env.OK_OPEN_BROWSER = prior;+ }+ });});diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.tsindex 536e463e2..e0363d8cd 100644--- a/packages/cli/src/commands/start.ts+++ b/packages/cli/src/commands/start.ts@@ -238,7 +238,7 @@ export function coerceRemoteBindHost(/** The `server.*` keys `--remote` expands into — nothing beyond the ratified surface. */interface RemoteAliasServerOverlay {- publicUrl: string;+ externalUrl: string;allowExternal: true;idleShutdown: 'off';}@@ -261,14 +261,14 @@ export type RemoteAliasExpansion =export function scopeRemoteAliasConsentToBind(serverOverlay: RemoteAliasServerOverlay,bindList: readonly string[],-): { publicUrl: string; idleShutdown: 'off'; allowExternal?: true } {+): { externalUrl: string; idleShutdown: 'off'; allowExternal?: true } {if (isLoopbackOnlyBind(bindList)) return serverOverlay;- return { publicUrl: serverOverlay.publicUrl, idleShutdown: serverOverlay.idleShutdown };+ return { externalUrl: serverOverlay.externalUrl, idleShutdown: serverOverlay.idleShutdown };}/*** `--remote [url]` is a deprecated thin alias over the ratified `server.*`- * networking keys: it expands to `server.publicUrl` = the tunnel url (its+ * networking keys: it expands to `server.externalUrl` = the tunnel url (its* host joins the Host/Origin allowlists), a loopback bind (tunnels proxy to* `127.0.0.1` — the deployer's tunnel agent covers ingress, see* `coerceRemoteBindHost`), and `server.allowExternal` consent, which@@ -313,28 +313,55 @@ export function expandRemoteAlias(return {ok: true,url: normalizedUrl,- serverOverlay: { publicUrl: normalizedUrl, allowExternal: true, idleShutdown: 'off' },+ serverOverlay: { externalUrl: normalizedUrl, allowExternal: true, idleShutdown: 'off' },};}/**- * Validator for Commander's `--public-url` parser — the flag-layer setter for- * `server.publicUrl`, matching the schema leaf's http(s)-origin shape so a- * flag value can never smuggle in what the config file would reject.+ * Validator shared by the `--external-url` parser and its deprecated+ * `--public-url` spelling — the flag-layer setter for `server.externalUrl`,+ * matching the schema leaf's http(s)-origin shape so a flag value can never+ * smuggle in what the config file would reject. `flagName` keeps the error+ * text naming the flag the user actually typed.*/-export function parsePublicUrlFlag(value: string): string {+function parseHttpOriginFlag(flagName: string, value: string): string {let parsed: URL;try {parsed = new URL(value);} catch {- throw new InvalidArgumentError(`--public-url is not a valid URL: ${value}`);+ throw new InvalidArgumentError(`${flagName} is not a valid URL: ${value}`);}if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {- throw new InvalidArgumentError(`--public-url must be an http(s) origin (got: ${value})`);+ throw new InvalidArgumentError(`${flagName} must be an http(s) origin (got: ${value})`);}return value;}+export function parseExternalUrlFlag(value: string): string {+ return parseHttpOriginFlag('--external-url', value);+}++/**+ * The flag-layer external-URL fold: `--external-url` wins, the deprecated+ * `--public-url` spelling fills in when it is the only one given (the two+ * flags cannot legally co-occur — the action guard exits 2 — so the `??` is+ * precedence bookkeeping, not conflict resolution). Extracted so a test pins+ * that the deprecated flag keeps setting `server.externalUrl` through its+ * removal window: dropping the fallback would silently strand `--public-url`+ * operators on `externalUrl: undefined` (no CORS/Host admission, no issued+ * URLs) with no parse error to signal it.+ */+export function resolveFlagExternalUrl(+ opts: Pick<StartCommandOptions, 'externalUrl' | 'publicUrl'>,+): string | undefined {+ return opts.externalUrl ?? opts.publicUrl;+}++/** Parser for the deprecated `--public-url` alias of `--external-url`. */+export function parsePublicUrlFlag(value: string): string {+ return parseHttpOriginFlag('--public-url', value);+}+/** Hard cap on the project-name suffix in `process.title` to keep `ps`/Activity Monitor lines readable. */const PROCESS_TITLE_PROJECT_NAME_MAX = 64;@@ -951,7 +978,9 @@ interface StartCommandOptions {* `remote.url` in config.*/remote?: string | boolean;- /** From `--public-url <url>`: flag-layer `server.publicUrl` for this run. */+ /** From `--external-url <url>`: flag-layer `server.externalUrl` for this run. */+ externalUrl?: string;+ /** From the deprecated `--public-url` alias of `--external-url`. */publicUrl?: string;}@@ -1046,7 +1075,33 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)if (remoteFlagSet) {console.warn(warning(- '--remote is deprecated — use `OK_IDLE_SHUTDOWN=off OK_ALLOW_EXTERNAL=1 ok start --public-url <url>` instead (add --bind to serve a non-loopback address; keep OK_IDLE_SHUTDOWN=off — the idle timer only counts WS clients and would tear the server down under a live remote MCP client). The flag now just expands to those server.* keys and will be removed in a later release.',+ '--remote is deprecated — use `OK_IDLE_SHUTDOWN=off OK_ALLOW_EXTERNAL=1 ok start --external-url <url>` instead (add --bind to serve a non-loopback address; keep OK_IDLE_SHUTDOWN=off — the idle timer only counts WS clients and would tear the server down under a live remote MCP client). The flag now just expands to those server.* keys and will be removed in a later release.',+ ),+ );+ }++ // Same ordering contract as the --remote notice above: the rename notices+ // print even when a later step refuses, so the operator learns the+ // successor spelling from the same run.+ if (opts.publicUrl !== undefined) {+ console.warn(+ warning(+ '--public-url is deprecated — use --external-url <url> (same value and semantics; the key was renamed to server.externalUrl). The old spelling will be removed in a later release.',+ ),+ );+ }++ // Config-file rename notice, keyed off the FILE layers (before the env/flag+ // overlay — those spellings write the successor key and warn on their own,+ // and a masking override doesn't make the stale file key any less stale).+ if (resolveServerRuntimeConfig(config).externalUrlFromDeprecatedKey) {+ // "Use X instead", not "rename it": in a committed shared config, keeping+ // BOTH keys is the sanctioned mixed-version state — older app versions+ // read only server.publicUrl and silently ignore server.externalUrl, so+ // a literal rename would 403 collaborators who have not upgraded.+ console.warn(+ warning(+ '[config] server.publicUrl is deprecated — use server.externalUrl instead (same value and semantics). If this config is committed and shared, keep both keys until every collaborator has upgraded — older versions read only server.publicUrl; see https://openknowledge.ai/docs/reference/configuration. The old key will be removed in a later release.',),);}@@ -1153,9 +1208,11 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)// loopback yet still trips ExposureConsentError off the uncoerced list.const bindList = remoteEnabled ? [host] : requestedBind;// The flag-layer overlay, applied ABOVE the env layer: the resolved bind- // list, the `--remote` alias expansion (publicUrl + allowExternal ++ // list, the `--remote` alias expansion (externalUrl + allowExternal +// idleShutdown 'off' — the SAME server.* resolution path any other exposure- // route uses), and `--public-url`. Nothing here is remote-specific+ // route uses), and `--external-url` (or its deprecated `--public-url`+ // spelling — both write the successor key so the flag layer keeps its+ // precedence over env and file layers). Nothing here is remote-specific// machinery; the alias is only these keys. Self-consent is loopback-scoped// (see scopeRemoteAliasConsentToBind) — a non-loopback bind under --remote// still needs explicit consent, so the interlock refusal below matches the@@ -1169,12 +1226,13 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)),);}+ const flagExternalUrl = resolveFlagExternalUrl(opts);const runtime: ServerRuntimeConfig = resolveServerRuntimeConfig(applyConfigOverlay(envConfig, {server: {bind: bindList,...aliasOverlay,- ...(opts.publicUrl !== undefined ? { publicUrl: opts.publicUrl } : {}),+ ...(flagExternalUrl !== undefined ? { externalUrl: flagExternalUrl } : {}),},}) as Config,);@@ -1185,10 +1243,10 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)// surface (clone, GitHub sign-in, PAT storage, repo spawn) to every external// peer, with NO server-side auth. Fire whenever consent is armed AND there is// a real exposure vector — a non-loopback bind (direct) or a declared- // publicUrl (a same-host reverse proxy forwards to a loopback bind). The+ // externalUrl (a same-host reverse proxy forwards to a loopback bind). The// --remote flow prints its own warning, so skip the duplicate there.- if (!remoteEnabled && runtime.allowExternal && (!runtime.loopbackOnly || runtime.publicUrl)) {- const reach = runtime.publicUrl ?? runtime.bind.join(', ');+ if (!remoteEnabled && runtime.allowExternal && (!runtime.loopbackOnly || runtime.externalUrl)) {+ const reach = runtime.externalUrl ?? runtime.bind.join(', ');console.warn(warning([@@ -1301,7 +1359,7 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)process.exit(78);}- // Exposure without consent (non-loopback bind or publicUrl set while+ // Exposure without consent (non-loopback bind or externalUrl set while// server.allowExternal is off) — the interlock's message IS the one-line// fix. EX_CONFIG, same contract as the other config-shaped boot errors.if (err instanceof serverModule.ExposureConsentError) {@@ -1673,14 +1731,19 @@ export function startCommand(getConfig: () => Config): Command {'--project-dir <dir>','Throwaway project root for --single-file (where ephemeral .ok/ state lives)',)+ .option(+ '--external-url <url>',+ 'Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists and issued URLs. External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).',+ parseExternalUrlFlag,+ ).option('--public-url <url>',- 'Canonical external origin clients dial (sets server.publicUrl for this run) — its host joins the Host/Origin allowlists and issued URLs. External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).',+ 'Deprecated alias of --external-url (the former name of that flag) — same value and semantics.',parsePublicUrlFlag,).option('--remote [url]',- 'Deprecated alias: expands to --public-url <url> + OK_ALLOW_EXTERNAL consent on a loopback bind. Serves through a tunnel with NO server-side auth (anyone who can reach the URL has full control — restrict access at the tunnel with edge auth). Bare --remote uses remote.url from .ok/config.yml; --remote <url> supplies it for this run.',+ 'Deprecated alias: expands to --external-url <url> + OK_ALLOW_EXTERNAL consent on a loopback bind. Serves through a tunnel with NO server-side auth (anyone who can reach the URL has full control — restrict access at the tunnel with edge auth). Bare --remote uses remote.url from .ok/config.yml; --remote <url> supplies it for this run.',).action(async (opts: StartCommandOptions) => {const config = getConfig();@@ -1691,11 +1754,26 @@ export function startCommand(getConfig: () => Config): Command {process.exit(2);}- // `--remote` IS a `--public-url` (plus consent) — combining them would- // make one silently win. Fail loud; pass one.- if (opts.publicUrl !== undefined && opts.remote !== undefined && opts.remote !== false) {+ // `--external-url` and its deprecated `--public-url` spelling are the+ // same flag under two names — combining them would make one silently+ // win. Fail loud; pass one.+ if (opts.externalUrl !== undefined && opts.publicUrl !== undefined) {+ process.stderr.write(+ "error: option '--public-url' cannot be combined with '--external-url' (--public-url is a deprecated alias of --external-url)\n",+ );+ process.exit(2);+ }++ // `--remote` IS an `--external-url` (plus consent) — combining them+ // would make one silently win. Fail loud; pass one.+ if (+ (opts.externalUrl !== undefined || opts.publicUrl !== undefined) &&+ opts.remote !== undefined &&+ opts.remote !== false+ ) {+ const conflicting = opts.externalUrl !== undefined ? '--external-url' : '--public-url';process.stderr.write(- "error: option '--remote' cannot be combined with '--public-url' (--remote is a deprecated alias that sets server.publicUrl)\n",+ `error: option '--remote' cannot be combined with '${conflicting}' (--remote is a deprecated alias that sets server.externalUrl)\n`,);process.exit(2);}@@ -1796,6 +1874,7 @@ export function startCommand(getConfig: () => Config): Command {if (opts.serverUrl !== undefined) ignored.push('--server-url');if (opts.idleShutdown !== undefined) ignored.push('--idle-shutdown');if (opts.openBrowser === false) ignored.push('--no-open-browser');+ if (opts.externalUrl !== undefined) ignored.push('--external-url');if (opts.publicUrl !== undefined) ignored.push('--public-url');if (opts.remote !== undefined && opts.remote !== false) ignored.push('--remote');if (ignored.length > 0) {diff --git a/packages/cli/src/commands/ui.ts b/packages/cli/src/commands/ui.tsindex 5c9e3e3db..baacd0b61 100644--- a/packages/cli/src/commands/ui.ts+++ b/packages/cli/src/commands/ui.ts@@ -282,7 +282,7 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe// Loopback-only, matching this surface's `/api` gate. `ok ui`'s API// gate is `rejectIfNotLoopbackApi` (loopback-shaped Host only, never// policy-aware), so the content-serve gate must admit no wider a set —- // otherwise a config-declared `publicUrl` would serve content assets+ // otherwise a config-declared `externalUrl` would serve content assets// to a Host that every `/api` call on the same surface 403s, a// half-broken app. `ok ui` is a loopback sidecar; the data server// (`ok start`) is the exposable surface and builds the real policy.diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex dfd95ef49..d7a845280 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,4 +1,3 @@-import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 8bfdb40cd..005627195 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,4 +1,3 @@-import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 01ef76a9f..8fb428b90 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 463e89595..9d9c244b0 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,4 +1,3 @@-const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.tsindex 0939885bb..c43fdd7e7 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,4 +1,3 @@-export function rawLineCounts(doc: string): Map<string, number> {const counts = new Map<string, number>();for (const line of doc.split('\n')) {diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex c0dc65705..251560a35 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,7 +65,6 @@ export function tryLineLevelCombine(return { clean: true, merged };}-export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex dcc5b0690..01ac80099 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,4 +1,3 @@-import { stripFrontmatter } from '../extensions/frontmatter.ts';import { bodyEdgeEmpties } from './doc-boundary-space.ts';diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 0be5203e4..754dc5cc2 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;-interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}-/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}-export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex dca644141..af20de1e2 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,4 +1,3 @@-/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/config/env-layer.test.ts b/packages/core/src/config/env-layer.test.tsindex 566b8bf4a..64f02e330 100644--- a/packages/core/src/config/env-layer.test.ts+++ b/packages/core/src/config/env-layer.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import {+ DEPRECATED_ENV_ALIASES,EnvVarError,listConfigLeafPaths,mechanicalEnvName,@@ -11,7 +12,7 @@ import {describe('mechanical naming rule', () => {it('server-section leaves map to bare OK_<LEAF>', () => {expect(mechanicalEnvName(['server', 'bind'])).toBe('OK_BIND');- expect(mechanicalEnvName(['server', 'publicUrl'])).toBe('OK_PUBLIC_URL');+ expect(mechanicalEnvName(['server', 'externalUrl'])).toBe('OK_EXTERNAL_URL');expect(mechanicalEnvName(['server', 'allowExternal'])).toBe('OK_ALLOW_EXTERNAL');expect(mechanicalEnvName(['server', 'idleShutdown'])).toBe('OK_IDLE_SHUTDOWN');expect(mechanicalEnvName(['server', 'openBrowser'])).toBe('OK_OPEN_BROWSER');@@ -40,13 +41,24 @@ describe('recognized surface pin', () => {new Map([['PORT', ['server', 'port']],['OK_BIND', ['server', 'bind']],- ['OK_PUBLIC_URL', ['server', 'publicUrl']],+ ['OK_EXTERNAL_URL', ['server', 'externalUrl']],['OK_ALLOW_EXTERNAL', ['server', 'allowExternal']],['OK_OPEN_BROWSER', ['server', 'openBrowser']],['OK_IDLE_SHUTDOWN', ['server', 'idleShutdown']],]),);});++ // Same name-lock reasoning for the deprecated set: entries leave only when+ // their removal window closes, and each must target the SUCCESSOR path so+ // the env layer keeps its precedence over the file layers.+ it('deprecated aliases are exactly OK_PUBLIC_URL → server.externalUrl', () => {+ expect(new Map(DEPRECATED_ENV_ALIASES)).toEqual(+ new Map([+ ['OK_PUBLIC_URL', { successor: 'OK_EXTERNAL_URL', path: ['server', 'externalUrl'] }],+ ]),+ );+ });});describe('resolveEnvConfigLayer', () => {@@ -54,7 +66,7 @@ describe('resolveEnvConfigLayer', () => {const { layer, overrides, diagnostics } = resolveEnvConfigLayer({PORT: '8080',OK_BIND: '127.0.0.1 100.64.0.7',- OK_PUBLIC_URL: 'https://kb.example.com',+ OK_EXTERNAL_URL: 'https://kb.example.com',OK_ALLOW_EXTERNAL: '1',OK_OPEN_BROWSER: 'false',OK_IDLE_SHUTDOWN: 'off',@@ -63,7 +75,7 @@ describe('resolveEnvConfigLayer', () => {server: {port: 8080,bind: ['127.0.0.1', '100.64.0.7'],- publicUrl: 'https://kb.example.com',+ externalUrl: 'https://kb.example.com',allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -92,20 +104,22 @@ describe('resolveEnvConfigLayer', () => {it('rejects malformed values with the env var named', () => {expect(() => resolveEnvConfigLayer({ PORT: 'dynamic' })).toThrow(/^PORT:/);expect(() => resolveEnvConfigLayer({ PORT: '70000' })).toThrow(EnvVarError);- expect(() => resolveEnvConfigLayer({ OK_PUBLIC_URL: 'not a url' })).toThrow(/OK_PUBLIC_URL/);- expect(() => resolveEnvConfigLayer({ OK_PUBLIC_URL: 'ftp://kb.example.com' })).toThrow(+ expect(() => resolveEnvConfigLayer({ OK_EXTERNAL_URL: 'not a url' })).toThrow(+ /OK_EXTERNAL_URL/,+ );+ expect(() => resolveEnvConfigLayer({ OK_EXTERNAL_URL: 'ftp://kb.example.com' })).toThrow(EnvVarError,);expect(() => resolveEnvConfigLayer({ OK_IDLE_SHUTDOWN: '30x' })).toThrow(/OK_IDLE_SHUTDOWN/);});- it('accepts http publicUrl (tailnet/LAN use) and duration idleShutdown', () => {+ it('accepts http externalUrl (tailnet/LAN use) and duration idleShutdown', () => {const { layer } = resolveEnvConfigLayer({- OK_PUBLIC_URL: 'http://laptop.tail:55222',+ OK_EXTERNAL_URL: 'http://laptop.tail:55222',OK_IDLE_SHUTDOWN: '45m',});expect(layer).toEqual({- server: { publicUrl: 'http://laptop.tail:55222', idleShutdown: '45m' },+ server: { externalUrl: 'http://laptop.tail:55222', idleShutdown: '45m' },});});@@ -129,6 +143,64 @@ describe('resolveEnvConfigLayer', () => {expect(diagnostics[0]?.message).toContain('OK_BIND');});+ it('a near-miss of a deprecated alias still hints, steering to the successor', () => {+ // OK_PUBLIC_URL left the recognized set for the deprecated table; its+ // typos are nowhere near OK_EXTERNAL_URL by edit distance, so they must+ // keep matching the old name — silently dropping the hint would regress+ // the pre-rename diagnostic.+ const { diagnostics, overrides } = resolveEnvConfigLayer({+ OK_PUBLI_URL: 'https://kb.example.com',+ });+ expect(overrides).toEqual([]);+ expect(diagnostics).toHaveLength(1);+ expect(diagnostics[0]?.message).toContain('OK_PUBLIC_URL');+ expect(diagnostics[0]?.message).toContain('OK_EXTERNAL_URL');+ expect(diagnostics[0]?.message).toContain('deprecated');+ });++ it('deprecated OK_PUBLIC_URL still resolves — to the successor path — and warns', () => {+ const { layer, overrides, diagnostics } = resolveEnvConfigLayer({+ OK_PUBLIC_URL: 'https://kb.example.com',+ });+ // Successor path, NOT ['server', 'publicUrl'] — writing the deprecated+ // config leaf would let a config-file server.externalUrl outrank the env+ // var, breaking env > file precedence for 0.51.x deployments.+ expect(layer).toEqual({ server: { externalUrl: 'https://kb.example.com' } });+ expect(overrides).toEqual([+ {+ path: ['server', 'externalUrl'],+ envVar: 'OK_PUBLIC_URL',+ value: 'https://kb.example.com',+ },+ ]);+ expect(diagnostics).toHaveLength(1);+ expect(diagnostics[0]?.message).toContain('deprecated');+ expect(diagnostics[0]?.message).toContain('OK_EXTERNAL_URL');+ });++ it('OK_EXTERNAL_URL wins when both spellings are set, with an ignored-var warning', () => {+ const { layer, overrides, diagnostics } = resolveEnvConfigLayer({+ OK_EXTERNAL_URL: 'https://new.example.com',+ OK_PUBLIC_URL: 'https://old.example.com',+ });+ expect(layer).toEqual({ server: { externalUrl: 'https://new.example.com' } });+ expect(overrides).toHaveLength(1);+ expect(diagnostics).toHaveLength(1);+ expect(diagnostics[0]?.envVar).toBe('OK_PUBLIC_URL');+ expect(diagnostics[0]?.message).toContain('ignored');+ });++ it('deprecated OK_PUBLIC_URL keeps the fail-loud validation of the recognized set', () => {+ expect(() => resolveEnvConfigLayer({ OK_PUBLIC_URL: 'not a url' })).toThrow(/OK_PUBLIC_URL/);+ expect(() => resolveEnvConfigLayer({ OK_PUBLIC_URL: 'ftp://kb.example.com' })).toThrow(+ EnvVarError,+ );+ // Empty/whitespace reads as unset — and unset never warns.+ const { overrides, diagnostics } = resolveEnvConfigLayer({ OK_PUBLIC_URL: ' ' });+ expect(overrides).toEqual([]);+ expect(diagnostics).toEqual([]);+ });+it('stays silent on legitimate operational OK_* vars and non-OK vars', () => {const { diagnostics, overrides } = resolveEnvConfigLayer({OK_LOCK_KIND: 'mcp-spawned',diff --git a/packages/core/src/config/env-layer.ts b/packages/core/src/config/env-layer.tsindex 9fe11b56f..d99a61407 100644--- a/packages/core/src/config/env-layer.ts+++ b/packages/core/src/config/env-layer.ts@@ -3,7 +3,7 @@** Naming rule (the only one there is, so no per-key naming decisions ever* again): a leaf under the `server.` section maps to bare `OK_<LEAF>`- * (`server.publicUrl` → `OK_PUBLIC_URL`); every other section maps to+ * (`server.externalUrl` → `OK_EXTERNAL_URL`); every other section maps to* `OK_<SECTION>_<LEAF>` (`autoSync.mode` → `OK_AUTO_SYNC_MODE`). camelCase* segments render as underscore-separated uppercase. One pinned exception:* `server.port` is read from unprefixed `PORT` — the platform-injection@@ -81,12 +81,25 @@ export class EnvVarError extends Error {export const RECOGNIZED_ENV_VARS: ReadonlyMap<string, readonly string[]> = new Map([['PORT', ['server', 'port']],['OK_BIND', ['server', 'bind']],- ['OK_PUBLIC_URL', ['server', 'publicUrl']],+ ['OK_EXTERNAL_URL', ['server', 'externalUrl']],['OK_ALLOW_EXTERNAL', ['server', 'allowExternal']],['OK_OPEN_BROWSER', ['server', 'openBrowser']],['OK_IDLE_SHUTDOWN', ['server', 'idleShutdown']],]);+/**+ * Deprecated env spellings kept through their removal window. Each maps to+ * the SUCCESSOR config path — not the deprecated config leaf — so the env+ * layer keeps its precedence over the file layers (an old `OK_PUBLIC_URL`+ * must still beat a config-file `server.externalUrl`, exactly as it beat+ * `server.publicUrl` before the rename). The successor env var wins when both+ * are set. Every use emits a deprecation diagnostic naming the new spelling.+ */+export const DEPRECATED_ENV_ALIASES: ReadonlyMap<+ string,+ { successor: string; path: readonly string[] }+> = new Map([['OK_PUBLIC_URL', { successor: 'OK_EXTERNAL_URL', path: ['server', 'externalUrl'] }]]);+function camelToScreamingSnake(segment: string): string {return segment.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase();}@@ -205,9 +218,16 @@ function diagnoseUnknownOkVar(message: `${envVar} maps to config key ${mapped.join('.')}, which is not env-configurable — set it in the config file instead.`,};}- for (const known of RECOGNIZED_ENV_VARS.keys()) {+ // Deprecated aliases stay in the near-miss pool: a typo of OK_PUBLIC_URL is+ // nowhere near OK_EXTERNAL_URL by edit distance, so dropping the old names+ // here would turn a once-hinted typo into silence. The hint steers the user+ // to the successor spelling rather than the deprecated one it matched.+ for (const known of [...RECOGNIZED_ENV_VARS.keys(), ...DEPRECATED_ENV_ALIASES.keys()]) {if (known !== 'PORT' && levenshtein(envVar, known) <= 2) {- return { envVar, message: `Unknown variable ${envVar} — did you mean ${known}?` };+ const alias = DEPRECATED_ENV_ALIASES.get(known);+ const hint =+ alias === undefined ? known : `${known} (deprecated — use ${alias.successor} instead)`;+ return { envVar, message: `Unknown variable ${envVar} — did you mean ${hint}?` };}}return null;@@ -268,8 +288,40 @@ export function resolveEnvConfigLayer(env: Record<string, string | undefined>):overrides.push({ path, envVar, value: checked.data });}+ // Deprecated spellings: parsed with the same fail-loud validation as the+ // recognized set, but only while the successor is unset — the successor+ // always wins, and every use (honored or shadowed) warns with the rename.+ for (const [envVar, { successor, path }] of DEPRECATED_ENV_ALIASES) {+ const raw = env[envVar];+ if (raw === undefined || raw.trim() === '') continue;+ const successorRaw = env[successor];+ if (successorRaw !== undefined && successorRaw.trim() !== '') {+ diagnostics.push({+ envVar,+ message: `${envVar} is deprecated and ignored because ${successor} is also set — remove ${envVar}.`,+ });+ continue;+ }+ diagnostics.push({+ envVar,+ message: `${envVar} is deprecated — use ${successor} instead.`,+ });+ const leaf = resolveLeafSchema(ConfigSchema, path);+ if (leaf === undefined) {+ throw new EnvVarError(envVar, `internal: config path ${path.join('.')} does not resolve`);+ }+ const parsed = parseByLeafType(envVar, raw.trim(), leaf);+ const checked = leaf.safeParse(parsed);+ if (!checked.success) {+ const detail = checked.error.issues.map((i) => i.message).join('; ') || 'invalid value';+ throw new EnvVarError(envVar, `${detail} (got ${JSON.stringify(raw)})`);+ }+ overrides.push({ path, envVar, value: checked.data });+ }+for (const envVar of Object.keys(env)) {if (!envVar.startsWith('OK_') || RECOGNIZED_ENV_VARS.has(envVar)) continue;+ if (DEPRECATED_ENV_ALIASES.has(envVar)) continue;if (env[envVar] === undefined) continue;const diagnostic = diagnoseUnknownOkVar(envVar, mechanicalTable);if (diagnostic !== null) diagnostics.push(diagnostic);diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.tsindex 24c021e4d..ce3c1f24f 100644--- a/packages/core/src/config/field-registry.test.ts+++ b/packages/core/src/config/field-registry.test.ts@@ -267,11 +267,12 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)''lossCapture.maxBytes','remote.port','remote.url',- // `server.{port,bind,publicUrl}` are the committed, reviewed shape of+ // `server.{port,bind,externalUrl}` are the committed, reviewed shape of// this knowledge base's server — project scope, like the `remote.*`// keys they supersede. Their consent/workflow siblings are// project-local (below).'server.bind',+ 'server.externalUrl','server.port','server.publicUrl','telemetry.localSink.attributeDenylist',@@ -380,6 +381,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)''remote.url','server.allowExternal','server.bind',+ 'server.externalUrl','server.openBrowser','server.port','server.publicUrl',diff --git a/packages/core/src/config/resolve-server-config.test.ts b/packages/core/src/config/resolve-server-config.test.tsindex 1477254c8..235535c2c 100644--- a/packages/core/src/config/resolve-server-config.test.ts+++ b/packages/core/src/config/resolve-server-config.test.ts@@ -58,7 +58,7 @@ describe('resolveServerRuntimeConfig — defaults', () => {expect(resolved.bind).toEqual(['127.0.0.1']);expect(resolved.loopbackOnly).toBe(true);expect(resolved.port).toBeUndefined();- expect(resolved.publicUrl).toBeUndefined();+ expect(resolved.externalUrl).toBeUndefined();expect(resolved.allowExternal).toBe(false);// Loopback-only derivations: a laptop start pops the UI and idles out.expect(resolved.openBrowser).toBe(true);@@ -102,28 +102,76 @@ describe('resolveServerRuntimeConfig — remote.* alias-reads', () => {).toBe(8080);});- test('remote.url fills server.publicUrl only while it is absent', () => {+ test('remote.url fills server.externalUrl only while it is absent', () => {const legacyOnly = resolveServerRuntimeConfig(parse({ remote: { url: 'https://kb.example.com' } }),);- expect(legacyOnly.publicUrl).toBe('https://kb.example.com');+ expect(legacyOnly.externalUrl).toBe('https://kb.example.com');const both = resolveServerRuntimeConfig(parse({- server: { publicUrl: 'https://new.example.com' },+ server: { externalUrl: 'https://new.example.com' },remote: { url: 'https://old.example.com' },}),);- expect(both.publicUrl).toBe('https://new.example.com');+ expect(both.externalUrl).toBe('https://new.example.com');});test('an empty-string remote.url reads as unset', () => {const resolved = resolveServerRuntimeConfig(parse({ remote: { url: '' } }));- expect(resolved.publicUrl).toBeUndefined();+ expect(resolved.externalUrl).toBeUndefined();expect(requiresExternalConsent(resolved)).toBe(false);});});+describe('resolveServerRuntimeConfig — deprecated server.publicUrl spelling', () => {+ test('server.publicUrl fills externalUrl with full successor semantics (source stays server)', () => {+ // The old spelling is the SAME key, not the remote.* legacy flow: consumers+ // keying exposure decisions off `externalUrlSource === 'server'` (interlock,+ // issued URLs, Host/Origin admission) must see a 0.51.x config behave+ // exactly as it did before the rename.+ const resolved = resolveServerRuntimeConfig(+ parse({ server: { publicUrl: 'https://kb.example.com' } }),+ );+ expect(resolved.externalUrl).toBe('https://kb.example.com');+ expect(resolved.externalUrlSource).toBe('server');+ expect(resolved.externalUrlFromDeprecatedKey).toBe(true);+ });++ test('server.externalUrl wins over the deprecated spelling when both are set', () => {+ const resolved = resolveServerRuntimeConfig(+ parse({+ server: {+ externalUrl: 'https://new.example.com',+ publicUrl: 'https://old.example.com',+ },+ }),+ );+ expect(resolved.externalUrl).toBe('https://new.example.com');+ expect(resolved.externalUrlSource).toBe('server');+ expect(resolved.externalUrlFromDeprecatedKey).toBe(false);+ });++ test('the deprecated spelling still wins over the remote.url legacy alias', () => {+ const resolved = resolveServerRuntimeConfig(+ parse({+ server: { publicUrl: 'https://renamed.example.com' },+ remote: { url: 'https://legacy.example.com' },+ }),+ );+ expect(resolved.externalUrl).toBe('https://renamed.example.com');+ expect(resolved.externalUrlSource).toBe('server');+ });++ test('externalUrlFromDeprecatedKey is false for unset and for the remote.url alias', () => {+ expect(resolveServerRuntimeConfig(parse({})).externalUrlFromDeprecatedKey).toBe(false);+ const aliased = resolveServerRuntimeConfig(+ parse({ remote: { url: 'https://kb.example.com' } }),+ );+ expect(aliased.externalUrlFromDeprecatedKey).toBe(false);+ });+});+describe('requiresExternalConsent', () => {test('false for the loopback-only default', () => {expect(requiresExternalConsent(resolveServerRuntimeConfig(parse({})))).toBe(false);@@ -134,24 +182,24 @@ describe('requiresExternalConsent', () => {expect(requiresExternalConsent(resolved)).toBe(true);});- test('a committed publicUrl under a loopback bind is inert — does NOT trip the interlock', () => {- // publicUrl is project-scoped (committed, shared): a team deploying to a+ test('a committed externalUrl under a loopback bind is inert — does NOT trip the interlock', () => {+ // externalUrl is project-scoped (committed, shared): a team deploying to a// VPS commits it. Under a loopback bind it is inert metadata — nothing// external reaches the server directly, and a same-box proxy's forwarded// requests are still gated at request time. Tripping the boot interlock on- // publicUrl alone would lock out every teammate who clones the repo and+ // externalUrl alone would lock out every teammate who clones the repo and// opens it locally (loopback), especially in desktop where config-derived// consent is forced off. Only a non-loopback bind is a boot-time question.const explicit = resolveServerRuntimeConfig(- parse({ server: { publicUrl: 'https://kb.example.com' } }),+ parse({ server: { externalUrl: 'https://kb.example.com' } }),);- expect(explicit.publicUrlSource).toBe('server');+ expect(explicit.externalUrlSource).toBe('server');expect(explicit.loopbackOnly).toBe(true);expect(requiresExternalConsent(explicit)).toBe(false);- // A non-loopback bind WITH a publicUrl still trips it (the bind exposes).+ // A non-loopback bind WITH a externalUrl still trips it (the bind exposes).const exposedWithUrl = resolveServerRuntimeConfig(- parse({ server: { bind: ['0.0.0.0'], publicUrl: 'https://kb.example.com' } }),+ parse({ server: { bind: ['0.0.0.0'], externalUrl: 'https://kb.example.com' } }),);expect(requiresExternalConsent(exposedWithUrl)).toBe(true);@@ -159,7 +207,7 @@ describe('requiresExternalConsent', () => {const aliased = resolveServerRuntimeConfig(parse({ remote: { url: 'https://kb.example.com' } }),);- expect(aliased.publicUrlSource).toBe('remote-alias');+ expect(aliased.externalUrlSource).toBe('remote-alias');expect(requiresExternalConsent(aliased)).toBe(false);});diff --git a/packages/core/src/config/resolve-server-config.ts b/packages/core/src/config/resolve-server-config.tsindex 7580d4114..100922ea3 100644--- a/packages/core/src/config/resolve-server-config.ts+++ b/packages/core/src/config/resolve-server-config.ts@@ -3,11 +3,13 @@** Two jobs no zod `.default()` can do:*- * 1. **Alias-read of the superseded `remote.*` keys.** `remote.url` is read- * only while `server.publicUrl` is absent; `remote.port` only while- * `server.port` is absent — the same shape as the `autoSync.enabled` →- * `autoSync.mode` alias. This resolver is the single alias-read point;- * no other reader should consult `remote.*` for these values.+ * 1. **Alias-read of the superseded keys.** `server.publicUrl` (the former+ * name of `server.externalUrl`) is read only while `server.externalUrl`+ * is absent; `remote.url` only while both are absent; `remote.port` only+ * while `server.port` is absent — the same shape as the+ * `autoSync.enabled` → `autoSync.mode` alias. This resolver is the single+ * alias-read point; no other reader should consult `remote.*` or+ * `server.publicUrl` for these values.** 2. **Derived defaults.** `openBrowser` and `idleShutdown` default off the* resolved bind: a loopback-only server pops the UI and idles out after@@ -39,17 +41,26 @@ export interface ServerRuntimeConfig {* Canonical external origin; `undefined` means derive* `http://localhost:<port>` for a loopback server.*/- publicUrl: string | undefined;+ externalUrl: string | undefined;/**- * Where `publicUrl` came from: the successor key (`'server'`) or the- * superseded `remote.url` alias (`'remote-alias'`); `undefined` when unset.+ * Where `externalUrl` came from: the `server.*` section (`'server'` — the+ * canonical `server.externalUrl` key or its deprecated `server.publicUrl`+ * spelling, which are the same key under two names) or the superseded+ * `remote.url` alias (`'remote-alias'`); `undefined` when unset.* Load-bearing distinction: a `remote.url` left in config does NOT arm* anything by itself (`ok start --remote` is the explicit opt-in), so- * consumers that treat a declared public origin as an exposure signal —+ * consumers that treat a declared external origin as an exposure signal —* the consent interlock, issued-URL preference — must key off `'server'`* only and leave the alias to the legacy remote flow.*/- publicUrlSource: 'server' | 'remote-alias' | undefined;+ externalUrlSource: 'server' | 'remote-alias' | undefined;+ /**+ * True when `externalUrl` was read from the deprecated `server.publicUrl`+ * spelling (i.e. `server.externalUrl` itself was absent) — the CLI's signal+ * to print the rename notice. Never true for the `remote.url` alias, which+ * carries its own deprecation flow (`--remote`).+ */+ externalUrlFromDeprecatedKey: boolean;/** Exposure consent interlock (see `requiresExternalConsent`). */allowExternal: boolean;/** Open the UI in a browser at start. Derived when not set explicitly. */@@ -86,16 +97,16 @@ export function isLoopbackOnlyBind(bind: readonly string[]): boolean {/*** The single predicate behind the exposure interlock: consent is required* when THE SERVER'S OWN BIND reaches beyond this machine — i.e. a non-loopback- * `server.bind`. `server.publicUrl` deliberately does NOT trip it on its own:- * publicUrl is a project-scoped, committed, SHARED key (a team deploying to a+ * `server.bind`. `server.externalUrl` deliberately does NOT trip it on its own:+ * externalUrl is a project-scoped, committed, SHARED key (a team deploying to a* VPS legitimately commits `https://notes.example.com`), so refusing to boot* whenever it is set would lock out every teammate who clones that repo and* opens it locally (loopback bind) — especially in desktop, where* config-derived consent is forced off. Under a loopback bind a committed- * publicUrl is inert metadata: nothing external reaches the server directly,+ * externalUrl is inert metadata: nothing external reaches the server directly,* and a same-box reverse proxy's forwarded requests are still gated at request* time (the forwarded-header tripwire refuses them without consent). Only the- * actual bind exposing the port is a boot-time consent question; publicUrl's+ * actual bind exposing the port is a boot-time consent question; externalUrl's* consent need surfaces at request time where a proxy actually appears.** The boot path that enforces this MUST resolve `allowExternal`@@ -146,19 +157,22 @@ export function resolveServerRuntimeConfig(config: Config | undefined): ServerRu// `remote.url` reads as unset (matching the CLI's `expandRemoteAlias`).const port = server?.port ?? remote?.port;const legacyUrl = remote?.url === '' ? undefined : remote?.url;- const publicUrl = server?.publicUrl ?? legacyUrl;- const publicUrlSource =- server?.publicUrl !== undefined+ const externalUrl = server?.externalUrl ?? server?.publicUrl ?? legacyUrl;+ const externalUrlSource =+ server?.externalUrl !== undefined || server?.publicUrl !== undefined? ('server' as const): legacyUrl !== undefined? ('remote-alias' as const): undefined;+ const externalUrlFromDeprecatedKey =+ server?.externalUrl === undefined && server?.publicUrl !== undefined;return {port,bind,- publicUrl,- publicUrlSource,+ externalUrl,+ externalUrlSource,+ externalUrlFromDeprecatedKey,allowExternal: server?.allowExternal ?? false,openBrowser: server?.openBrowser ?? loopbackOnly,idleShutdown: server?.idleShutdown ?? (loopbackOnly ? DEFAULT_LOOPBACK_IDLE_SHUTDOWN : 'off'),diff --git a/packages/core/src/config/schema-jsonschema.test.ts b/packages/core/src/config/schema-jsonschema.test.tsindex 73729fde7..09ea616a6 100644--- a/packages/core/src/config/schema-jsonschema.test.ts+++ b/packages/core/src/config/schema-jsonschema.test.ts@@ -188,22 +188,22 @@ const FIXTURES: Fixture[] = [shouldAccept: false,},{- name: 'server.publicUrl https URL accepted',- input: { server: { publicUrl: 'https://kb.example.com' } },+ name: 'server.externalUrl https URL accepted',+ input: { server: { externalUrl: 'https://kb.example.com' } },shouldAccept: true,},{- name: 'server.publicUrl non-URL rejected',- input: { server: { publicUrl: 'not a url' } },+ name: 'server.externalUrl non-URL rejected',+ input: { server: { externalUrl: 'not a url' } },shouldAccept: false,},{// The protocol restriction must appear in the published JSON schema, not// just at runtime — otherwise a $schema-aware editor green-lights a scheme- // (ftp:, javascript:) that ConfigSchema rejects at boot. publicUrl drives+ // (ftp:, javascript:) that ConfigSchema rejects at boot. externalUrl drives// CORS + URL issuance, so the divergence is security-relevant.- name: 'server.publicUrl ftp:// rejected in both validators (protocol pattern serializes)',- input: { server: { publicUrl: 'ftp://kb.example.com' } },+ name: 'server.externalUrl ftp:// rejected in both validators (protocol pattern serializes)',+ input: { server: { externalUrl: 'ftp://kb.example.com' } },shouldAccept: false,},{diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.tsindex 9ccf4919a..482feb9f9 100644--- a/packages/core/src/config/schema.test.ts+++ b/packages/core/src/config/schema.test.ts@@ -396,7 +396,7 @@ describe('server.* (canonical listener/exposure surface)', () => {// No schema default: unset means dynamic locally / platform PORT env in// images, and keeps the remote.port alias-read detectable.expect(config.server.port).toBeUndefined();- expect(config.server.publicUrl).toBeUndefined();+ expect(config.server.externalUrl).toBeUndefined();// Derived defaults resolve in resolveServerRuntimeConfig, not here.expect(config.server.openBrowser).toBeUndefined();expect(config.server.idleShutdown).toBeUndefined();@@ -420,19 +420,29 @@ describe('server.* (canonical listener/exposure surface)', () => {expect(ConfigSchema.safeParse({ server: { bind: '127.0.0.1' } }).success).toBe(false);});- test('publicUrl accepts http(s) URLs and rejects other schemes or non-URLs', () => {+ test('the deprecated publicUrl spelling still validates with the same URL shape', () => {expect(ConfigSchema.parse({ server: { publicUrl: 'https://kb.example.com' } }).server.publicUrl,).toBe('https://kb.example.com');- expect(- ConfigSchema.parse({ server: { publicUrl: 'http://localhost:8080' } }).server.publicUrl,- ).toBe('http://localhost:8080');expect(ConfigSchema.safeParse({ server: { publicUrl: 'not a url' } }).success).toBe(false);expect(ConfigSchema.safeParse({ server: { publicUrl: 'ftp://kb.example.com' } }).success).toBe(false,);});+ test('externalUrl accepts http(s) URLs and rejects other schemes or non-URLs', () => {+ expect(+ ConfigSchema.parse({ server: { externalUrl: 'https://kb.example.com' } }).server.externalUrl,+ ).toBe('https://kb.example.com');+ expect(+ ConfigSchema.parse({ server: { externalUrl: 'http://localhost:8080' } }).server.externalUrl,+ ).toBe('http://localhost:8080');+ expect(ConfigSchema.safeParse({ server: { externalUrl: 'not a url' } }).success).toBe(false);+ expect(+ ConfigSchema.safeParse({ server: { externalUrl: 'ftp://kb.example.com' } }).success,+ ).toBe(false);+ });+test("idleShutdown accepts 'off' and s/m/h durations, rejects bare numbers and other units", () => {for (const good of ['off', '90s', '30m', '2h']) {expect(ConfigSchema.parse({ server: { idleShutdown: good } }).server.idleShutdown).toBe(good);diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex 1d4c4e61c..015ab597f 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -88,7 +88,7 @@ export const DEFAULT_SERVER_BIND: readonly string[] = Object.freeze(['127.0.0.1'export const IDLE_SHUTDOWN_DURATION_RE = /^[1-9]\d*(s|m|h)$/;/**- * `server.publicUrl` scheme guard, paired with the runtime `z.url({ protocol })`+ * `server.externalUrl` scheme guard, paired with the runtime `z.url({ protocol })`* check. Zod's URL `protocol` option validates at runtime but does NOT* serialize through `z.toJSONSchema` (which emits only `format: "uri"`, a* scheme it would accept `ftp:`/`javascript:` under). Attaching this as a@@ -1199,7 +1199,7 @@ export const ConfigSchema = z.looseObject({// `agentSettable: false` everywhere so an agent can't self-expose the box.//// SUPERSEDED by the `server.*` section below: `remote.url` by- // `server.publicUrl`, `remote.port` by `server.port`. Each is alias-read+ // `server.externalUrl`, `remote.port` by `server.port`. Each is alias-read// only while its successor is absent (`resolveServerRuntimeConfig` — the// same shape as the `autoSync.enabled` → `autoSync.mode` alias). The keys// stay readable so existing configs keep working; removal (REMOVED_KEYS +@@ -1220,7 +1220,7 @@ export const ConfigSchema = z.looseObject({reload: 'boot',defaultScope: 'project',description:- 'Superseded by server.publicUrl — read only while server.publicUrl is absent. Public URL your tunnel gives you, e.g. https://myproject.ngrok.app. Used only with `ok start --remote` (config alone never enables remote access); its host is admitted through the Host-header allowlist. There is no server-side auth, so restrict access at the tunnel (ngrok OAuth, Cloudflare Access, Tailscale ACLs).',+ 'Superseded by server.externalUrl — read only while server.externalUrl (and its deprecated server.publicUrl spelling) is absent. Public URL your tunnel gives you, e.g. https://myproject.ngrok.app. Used only with `ok start --remote` (config alone never enables remote access); its host is admitted through the Host-header allowlist. There is no server-side auth, so restrict access at the tunnel (ngrok OAuth, Cloudflare Access, Tailscale ACLs).',}).optional(),port: z@@ -1245,7 +1245,7 @@ export const ConfigSchema = z.looseObject({// target that drifts from the values that actually matter; "hosted" is// just what a non-loopback bind, a public URL, and consent look like.//- // Scopes: `port` / `bind` / `publicUrl` are PROJECT — the committed,+ // Scopes: `port` / `bind` / `externalUrl` are PROJECT — the committed,// reviewed shape of this knowledge base's server. `openBrowser` /// `idleShutdown` are PROJECT-LOCAL — personal workflow, like the sidebar// toggles. `allowExternal` is PROJECT-LOCAL consent, the same posture as@@ -1290,7 +1290,7 @@ export const ConfigSchema = z.looseObject({'Addresses the server binds, e.g. [127.0.0.1] or [0.0.0.0]. Default loopback-only ([127.0.0.1]): nothing off this machine can connect. A non-loopback bind additionally requires the server.allowExternal consent interlock. Lists replace, never merge. Read at server start; changing it requires a restart.',}).default([...DEFAULT_SERVER_BIND]),- publicUrl: z+ externalUrl: z.url({ protocol: /^https?$/ })// Runtime protocol check + the JSON-schema-serializable pattern (see// HTTP_URL_SCHEME_RE) — together they keep the published schema and the@@ -1302,7 +1302,22 @@ export const ConfigSchema = z.looseObject({reload: 'boot',defaultScope: 'project',description:- 'Canonical external origin the server is reached at, e.g. https://kb.example.com — drives issued URLs and CORS. Unset by default: a loopback server derives http://localhost:<port>. Setting it declares external exposure, which additionally requires the server.allowExternal consent interlock. Supersedes remote.url (still read while this key is absent). Read at server start; changing it requires a restart.',+ 'Canonical external origin the server is reached at, e.g. https://kb.example.com — drives issued URLs and CORS. Unset by default: a loopback server derives http://localhost:<port>. Setting it declares external exposure, which additionally requires the server.allowExternal consent interlock. Supersedes server.publicUrl (its former name) and remote.url — both still read while this key is absent. Read at server start; changing it requires a restart.',+ })+ .optional(),+ // The former name of `server.externalUrl`, shipped in stable 0.51.x —+ // kept as a deprecated alias (alias-read in `resolveServerRuntimeConfig`,+ // same shape as `remote.url`), removed only after a deprecation window.+ publicUrl: z+ .url({ protocol: /^https?$/ })+ .regex(HTTP_URL_SCHEME_RE)+ .register(fieldRegistry, {+ scope: 'project',+ agentSettable: false,+ reload: 'boot',+ defaultScope: 'project',+ description:+ 'Deprecated alias of server.externalUrl (the former name of that key) — read only while server.externalUrl is absent, with identical semantics. Use server.externalUrl instead; if this config is committed and shared, keep both keys until every collaborator has upgraded (older versions read only server.publicUrl).',}).optional(),allowExternal: z@@ -1313,7 +1328,7 @@ export const ConfigSchema = z.looseObject({reload: 'boot',defaultScope: 'project-local',description:- 'Exposure consent interlock. Once the unified server boot lands, a non-loopback server.bind or a server.publicUrl without allowExternal: true will be refused at boot with a one-line fix. Default off. Per-machine (project-local) — consent never travels via git, clone, or share; containers consent via the environment instead.',+ 'Exposure consent interlock. Once the unified server boot lands, a non-loopback server.bind or a server.externalUrl without allowExternal: true will be refused at boot with a one-line fix. Default off. Per-machine (project-local) — consent never travels via git, clone, or share; containers consent via the environment instead.',}).default(false),openBrowser: zdiff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex a363dfd54..83d47404a 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,4 +1,3 @@-import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 4499dbc92..9807a7e82 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,4 +1,3 @@-export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 34704165b..7415c474a 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex b6299a948..ece5c02a1 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,4 +1,3 @@-import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex acd398aa6..54774764a 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsindex ba9b56384..43ecdc709 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex 4513da9bb..6d3f3643e 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,4 +1,3 @@-const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 6931623c7..00f5771ee 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}-interface GfmExample {section: string;markdown: string;@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}-interface MdxCrashEntry {id: string;input: string;@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}-export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}-export interface NgPinnedCase {id: string;name: string;@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}-export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex daa3ef82b..8b1eb8519 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;-function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}-const WORDS = ['lorem','ipsum',@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}-type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}-function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 32c055c5b..420dc0fe5 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,7 +7,6 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';-export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 283913255..2653473da 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,4 +1,3 @@-export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex 5d1000cc4..da0a81d23 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 9681c0056..787315157 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,4 +1,3 @@-import type { Element as HastElement, Root as HastRoot } from 'hast';import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -129,8 +128,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified()- .use(rehypeParse, { fragment: true });+ const processor = unified().use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 994eb6917..706fa9afb 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,4 +1,3 @@-import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex ec1ac1b7e..779e27500 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromPmMark,@@ -207,7 +206,6 @@ export class MarkdownManager {}}-const registry = createRegistry();function destructureAttrs(@@ -256,7 +254,6 @@ function destructureAttrs(return result;}-function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -279,7 +276,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}-function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}-import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(}));}-if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(}));}-if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(};}-const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1106,7 +1098,6 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}-function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex b79e9aef7..fa0be9e86 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,4 +1,3 @@-import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 94b34dee1..312c9c74b 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,4 +1,3 @@-const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex 1e3ad29c6..c400441b2 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -39,7 +39,6 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;-export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex a51f2ffb0..d48eea5e4 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};-export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex 9c9542661..ef478e268 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,4 +1,3 @@-import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex b96d19182..0d4c9a0df 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,4 +1,3 @@-import Ajv, { type ValidateFunction } from 'ajv';import Ajv2019 from 'ajv/dist/2019.js';import Ajv2020 from 'ajv/dist/2020.js';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex 1ca263610..af38c2ae2 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,4 +1,3 @@-import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex be5871ed9..5e832aa19 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,4 +1,3 @@-import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -14,7 +13,6 @@ import {type MarkdownlintSlice,} from './types.ts';-const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 3dae5c031..01ce4a5af 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,4 +1,3 @@-import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;@@ -99,7 +98,6 @@ export interface FrontmatterSlice {schemas: ResolvedFrontmatterSchemaEntry[];}-interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.tsindex 437cc539a..98238656e 100644--- a/packages/core/src/markdown/lint/validation-counts.ts+++ b/packages/core/src/markdown/lint/validation-counts.ts@@ -1,4 +1,3 @@-export interface ValidationSourceCounts {errorCount: number;warningCount: number;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex bd79424c7..a5b511f25 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 00fbc0035..ed89371d0 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex df788a80d..8ce2b2492 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,4 +1,3 @@-import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 17ed2b829..1a897fca8 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 4aa0490c4..d988f4b8b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,7 +168,6 @@ export function parseRecursive(}}-interface VFilePlace {offset?: number;start?: { offset?: number };@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}-interface Region {start: number;end: number;@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}-export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}-interface SourceBlock {src: string;start: number;@@ -456,7 +452,6 @@ function tryPerBlockFallback(};}-function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex 43d420187..e6ab4fd57 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,4 +1,3 @@-export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 55736041c..0e3224206 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex ccf06e94d..91cdf658f 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,4 +1,3 @@-import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';import { isBlankLineParagraph } from './zero-emission-blocks.ts';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex e5b4c9eba..0f399d34c 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,4 +1,3 @@-import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- }- else if (first === '[') {+ } else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex ca225ce9b..db10fa54b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,4 +1,3 @@-import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 3a2524a9a..34068d103 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 2279a0189..93151d43b 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex a0f467c42..188f02d83 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4e8542a21..4ba2c3418 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex a3c96b24a..1a74b1272 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex e95cf43d6..de35e7b79 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex ffdb4d5b5..b4be1b2ea 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex e2a96d1a7..3c8d88b7c 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex 0389575ac..cf2c9da8e 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,4 +1,3 @@-import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 96304e7a5..0dd54070e 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,4 +1,3 @@-import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 93798cf83..7cac5b042 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,4 +1,3 @@-import type { Node as PmNode } from '@tiptap/pm/model';import type {MdxJsxAttribute,diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex 8c08b7a04..b012a5aff 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,4 +1,3 @@-import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 959cc0bd2..3e79f8cb6 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,4 +1,3 @@-import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.tsindex 6e6d73400..0f1b0f27d 100644--- a/packages/core/src/markdown/underline-promoter.ts+++ b/packages/core/src/markdown/underline-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex 932d7d2a8..1a082bda7 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,4 +1,3 @@-import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex ac9f5239b..d578476a7 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,4 +1,3 @@-const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex afd9936fe..6dad26200 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {}}-const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {};}-function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};-const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/server/src/api-admission-composition.test.ts b/packages/server/src/api-admission-composition.test.tsindex a81e646bd..312fed461 100644--- a/packages/server/src/api-admission-composition.test.ts+++ b/packages/server/src/api-admission-composition.test.ts@@ -66,7 +66,7 @@ describe('/api admission over the composed listener — normal mode', () => {test('read route under a rebound Host is refused (read-posture hardening)', async () => {// Flipped pin: reads are Host-gated in every mode now, same predicate the- // mutating gate uses (loopback names + bind literals + publicUrl host).+ // mutating gate uses (loopback names + bind literals + externalUrl host).// A DNS-rebound page's no-Origin fetch can no longer read /api bodies —// the no-auth compensating control.const res = await rawRequest(normal.port, '/api/server-info', {diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 614d70df3..67215e421 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -2833,7 +2833,7 @@ export function createApiExtension(): boolean => checkLocalOpSecurityBase(req, res, { ...opts, policy: ingressPolicy });// Same shadow for the route-level Host gates (principal, workspace, metrics,// the write-path gates): every admitted public name (bind literals,- // declared publicUrl, legacy tunnel host) is as legitimate as a loopback+ // declared externalUrl, legacy tunnel host) is as legitimate as a loopback// name — the mount's admit gate already vetted the surface.const isAllowedWorkspaceHostHeader = (host: string | undefined): boolean =>isHostAdmitted(host, ingressPolicy);diff --git a/packages/server/src/api-origin.test.ts b/packages/server/src/api-origin.test.tsindex b96742011..9406739b9 100644--- a/packages/server/src/api-origin.test.ts+++ b/packages/server/src/api-origin.test.ts@@ -24,10 +24,10 @@ describe('API origin guards', () => {});// Tunnel/public origins are an ingress-policy concern now — `isOriginAdmitted`-// admits the declared `server.publicUrl` origin (see ingress-policy.test.ts);+// admits the declared `server.externalUrl` origin (see ingress-policy.test.ts);// this helper stays loopback-only.describe('isAllowedApiOrigin stays loopback-only', () => {- test('refuses a tunnel origin — publicUrl admission lives in the ingress policy', () => {+ test('refuses a tunnel origin — externalUrl admission lives in the ingress policy', () => {expect(isAllowedApiOrigin('https://myproject.ngrok.app')).toBe(false);expect(isAllowedApiOrigin('http://localhost:5173')).toBe(true);});diff --git a/packages/server/src/boot.test.ts b/packages/server/src/boot.test.tsindex a0e5aab45..8d5a86ccd 100644--- a/packages/server/src/boot.test.ts+++ b/packages/server/src/boot.test.ts@@ -1161,35 +1161,35 @@ describeEvenOnCI('bootServer — exposure consent interlock', () => {expect(e.message).toContain('.ok/local/config.yml');});- test('a committed publicUrl under a loopback bind is inert — boots, no lockout (CLI path)', async () => {- // publicUrl is project-scoped (committed, shared); a team commits their VPS+ test('a committed externalUrl under a loopback bind is inert — boots, no lockout (CLI path)', async () => {+ // externalUrl is project-scoped (committed, shared); a team commits their VPS// origin. Under a loopback bind it must NOT trip the interlock, or every// teammate cloning that repo and opening it locally would be locked out.- const err = await tryBoot({ publicUrl: 'https://notes.example.com' }, true);+ const err = await tryBoot({ externalUrl: 'https://notes.example.com' }, true);expect((err as Error | null)?.constructor.name).not.toBe('ExposureConsentError');});- test('a committed publicUrl under a loopback bind is inert — boots on the desktop / embedder path too', async () => {+ test('a committed externalUrl under a loopback bind is inert — boots on the desktop / embedder path too', async () => {// Same, with NO explicit serverRuntime (the desktop utility path). A repo- // committing publicUrl for its VPS deploy opens fine in desktop.- const err = await tryBoot({ publicUrl: 'https://notes.example.com' });+ // committing externalUrl for its VPS deploy opens fine in desktop.+ const err = await tryBoot({ externalUrl: 'https://notes.example.com' });expect((err as Error | null)?.constructor.name).not.toBe('ExposureConsentError');});- test('a loopback-only server with no publicUrl never trips the interlock', async () => {+ test('a loopback-only server with no externalUrl never trips the interlock', async () => {// Reaches past the interlock and boots; success is the absence of an// ExposureConsentError (any later failure would be a different class).const err = await tryBoot({});expect((err as Error | null)?.constructor.name).not.toBe('ExposureConsentError');});- test('the --remote alias shape (publicUrl + consent on a loopback bind) boots outright', async () => {+ test('the --remote alias shape (externalUrl + consent on a loopback bind) boots outright', async () => {// `ok start --remote <url>` expands to exactly this runtime with NO// OK_ALLOW_EXTERNAL in the environment — the alias carries its own// consent. Historically the flag WAS the consent; if this shape ever// trips the interlock, every existing --remote user breaks at boot.const err = await tryBoot(- { publicUrl: 'https://myproject.ngrok.app', allowExternal: true },+ { externalUrl: 'https://myproject.ngrok.app', allowExternal: true },true,);expect(err).toBeNull();diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex 8d87bc007..679031ff6 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -245,7 +245,7 @@ export interface BootServerOptions*/skipAutoInit?: boolean;/**- * The resolved `server.*` runtime (bind list, publicUrl, consent, derived+ * The resolved `server.*` runtime (bind list, externalUrl, consent, derived* defaults). The CLI passes the fully-layered resolution (flags > env >* project-local > project > user); callers that omit it get a files-only* resolution from `opts.config`. One resolution feeds every consumer —@@ -562,7 +562,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// correct load exists to prevent). Config-derived consent is therefore// untrusted here: force `allowExternal` off so only a caller that resolved// it scope-correctly (the CLI's explicit `serverRuntime`) can consent. A- // committed non-loopback bind or `publicUrl` then trips the interlock below+ // committed non-loopback bind or `externalUrl` then trips the interlock below// — the correct refusal, not a silent exposure. Desktop's own consent path// (the network pane writes project-local, and this boot reads all three// layers) is a follow-up; until then desktop is loopback-only by construction.@@ -588,7 +588,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// The exposure consent interlock: a NON-LOOPBACK bind reaches beyond this// machine, and the server refuses to boot without recorded consent. Checked// against the EFFECTIVE bind (above) AND the resolved serverRuntime — either- // being non-loopback trips it. A committed server.publicUrl under a loopback+ // being non-loopback trips it. A committed server.externalUrl under a loopback// bind is inert metadata and does NOT trip this (see requiresExternalConsent)// — that would lock out a teammate who clones a VPS-deploy repo and opens it// locally. Enforced here — the single boot chokepoint every launcher goes@@ -611,7 +611,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// ONE ingress policy for the whole listener — HTTP gates, WS upgrade// admission, config-doc admission, and the local-op checks all consult this// object. Built from the resolved server.* runtime (consent, declared bind- // literals, publicUrl); `ok start --remote` reaches here through the same+ // literals, externalUrl); `ok start --remote` reaches here through the same// runtime, expanded by the CLI into these keys.//// The policy's admitted Host names come from `serverRuntime.bind` — the@@ -629,26 +629,26 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {if (serverRuntime.allowExternal &&!serverRuntime.loopbackOnly &&- serverRuntime.publicUrlSource !== 'server'+ serverRuntime.externalUrlSource !== 'server') {if (ingressPolicy.bindLiterals.length === 0) {// Wildcard bind (0.0.0.0 / ::) contributes NO admissible Host name, and- // with no server.publicUrl the Host allowlist is loopback-only — so+ // with no server.externalUrl the Host allowlist is loopback-only — so// every external request 403s and the server is externally unusable// despite consent. This is a misconfiguration, not a refusal (a// container behind a platform edge that rewrites Host is legitimate),// so warn loudly and name the fix.log.warn({ bind: serverRuntime.bind },- '[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.publicUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.publicUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.',+ '[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.',);} else {// A specific non-loopback bind (e.g. a tailnet IP) IS admissible as a// Host literal, so direct-IP access works; only friendly names need- // server.publicUrl.+ // server.externalUrl.log.info({ bind: serverRuntime.bind },- '[ingress] server.allowExternal is set with no server.publicUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.publicUrl to admit a hostname.',+ '[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.',);}}@@ -836,8 +836,8 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// issued URLs, and the server.lock URL stays loopback below: the lock is// same-machine discovery by contract.const issuedBaseUrl = (): string =>- serverRuntime.publicUrlSource === 'server' && serverRuntime.publicUrl !== undefined- ? serverRuntime.publicUrl.replace(/\/+$/, '')+ serverRuntime.externalUrlSource === 'server' && serverRuntime.externalUrl !== undefined+ ? serverRuntime.externalUrl.replace(/\/+$/, ''): `http://${mcpHost}:${boundPort}`;// No-project ephemeral single-file mode mounts NO MCP endpoint:// there are no agent capabilities. `mountMcpAndApi` leaves `/mcp`diff --git a/packages/server/src/collaboration-host.test.ts b/packages/server/src/collaboration-host.test.tsindex c8812282b..4c95a3a5a 100644--- a/packages/server/src/collaboration-host.test.ts+++ b/packages/server/src/collaboration-host.test.ts@@ -169,15 +169,15 @@ describe('createCollaborationHost', () => {expect(raw.destroy).toHaveBeenCalledOnce();expect(hocuspocus.handleConnection).not.toHaveBeenCalled();// Posture flip: the tripwire hint names the consent surface- // (OK_ALLOW_EXTERNAL + OK_PUBLIC_URL) now that it exists, with the+ // (OK_ALLOW_EXTERNAL + OK_EXTERNAL_URL) now that it exists, with the// legacy --remote flow as the alternative.expect(log.warn).toHaveBeenCalledWith({ url: '/collab', host: 'localhost' },- '[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_PUBLIC_URL, or start with `ok start --remote <url>`',+ '[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL, or start with `ok start --remote <url>`',);});- test('uses the tunnel-shape admission (publicUrl + consent) for bare collaboration upgrades', () => {+ test('uses the tunnel-shape admission (externalUrl + consent) for bare collaboration upgrades', () => {const log = createLog();const hocuspocus = createHocuspocus();const host = createCollaborationHost({@@ -189,8 +189,9 @@ describe('createCollaborationHost', () => {serverRuntime: {port: undefined,bind: ['127.0.0.1'],- publicUrl: 'https://myproject.ngrok.app',- publicUrlSource: 'server',+ externalUrl: 'https://myproject.ngrok.app',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -222,7 +223,7 @@ describe('createCollaborationHost', () => {// The #5 gap: before, plain /collab was gated only under legacy --remote,// so consented exposure (allowExternal, no --remote) left it ungated and// any Host reached full CRDT read/write. It now runs the consolidated- // admit gate — loopback + bind literals + publicUrl — under consent too.+ // admit gate — loopback + bind literals + externalUrl — under consent too.const log = createLog();const hocuspocus = createHocuspocus();const host = createCollaborationHost({@@ -232,8 +233,9 @@ describe('createCollaborationHost', () => {serverRuntime: {port: undefined,bind: ['127.0.0.1', '100.64.0.7'],- publicUrl: undefined,- publicUrlSource: undefined,+ externalUrl: undefined,+ externalUrlSource: undefined,+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -276,7 +278,7 @@ describe('createCollaborationHost', () => {test('under allowExternal consent, plain /collab refuses a foreign Origin (CSWSH defense)', () => {// CWE-1275: WS upgrades bypass CORS, so a page on a foreign origin can open- // wss://<publicUrl>/collab — the Host passes (publicUrl) and, under consent,+ // wss://<externalUrl>/collab — the Host passes (externalUrl) and, under consent,// so does the relaxed peer gate. A present-but-foreign Origin is the only// signal separating that cross-site hijack from a first-party client, so it// MUST be refused here exactly as /collab/thread refuses it. A missing@@ -290,8 +292,9 @@ describe('createCollaborationHost', () => {serverRuntime: {port: undefined,bind: ['127.0.0.1', '100.64.0.7'],- publicUrl: 'https://kb.example.com',- publicUrlSource: 'server',+ externalUrl: 'https://kb.example.com',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -300,7 +303,7 @@ describe('createCollaborationHost', () => {}),});- // Attack: the publicUrl Host is admitted, but the foreign Origin is not.+ // Attack: the externalUrl Host is admitted, but the foreign Origin is not.const attacker = createSocket();expect(host.handleUpgrade(@@ -312,7 +315,7 @@ describe('createCollaborationHost', () => {expect(attacker.destroy).toHaveBeenCalledOnce();expect(hocuspocus.handleConnection).not.toHaveBeenCalled();- // A first-party page on the publicUrl origin is admitted.+ // A first-party page on the externalUrl origin is admitted.const firstPartyWs = new EventEmitter();callbackUpgrade(host, firstPartyWs);const sameOrigin = createSocket();@@ -401,8 +404,9 @@ describe('createCollaborationHost', () => {serverRuntime: {port: undefined,bind: ['127.0.0.1', '100.64.0.7'],- publicUrl: 'https://kb.example.com',- publicUrlSource: 'server',+ externalUrl: 'https://kb.example.com',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -411,7 +415,7 @@ describe('createCollaborationHost', () => {}),});- // Attack: publicUrl Host is admitted, but the foreign Origin is refused.+ // Attack: externalUrl Host is admitted, but the foreign Origin is refused.const attacker = createSocket();host.handleUpgrade(request(@@ -452,8 +456,9 @@ describe('createCollaborationHost', () => {serverRuntime: {port: undefined,bind: ['127.0.0.1', '100.64.0.7'],- publicUrl: 'https://kb.example.com',- publicUrlSource: 'server',+ externalUrl: 'https://kb.example.com',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -462,7 +467,7 @@ describe('createCollaborationHost', () => {}),});- // Attack: the publicUrl Host is admitted, but the foreign Origin is refused.+ // Attack: the externalUrl Host is admitted, but the foreign Origin is refused.const attacker = createSocket();host.handleUpgrade(request('/collab/thread', 'kb.example.com', 'https://evil.example'),@@ -472,7 +477,7 @@ describe('createCollaborationHost', () => {expect(attacker.destroy).toHaveBeenCalledOnce();expect(hocuspocus.handleConnection).not.toHaveBeenCalled();- // A first-party thread on the publicUrl origin is admitted (message wired).+ // A first-party thread on the externalUrl origin is admitted (message wired).const threadWs = new EventEmitter() as EventEmitter & { close: () => void; send: () => void };threadWs.close = () => {};threadWs.send = () => {};diff --git a/packages/server/src/collaboration-host.ts b/packages/server/src/collaboration-host.tsindex 818fc228f..1c46294f3 100644--- a/packages/server/src/collaboration-host.ts+++ b/packages/server/src/collaboration-host.ts@@ -287,7 +287,7 @@ export function createCollaborationHost(options: CollaborationHostOptions): Collif (tripsForwardedHeaderTripwire(req, ingressPolicy)) {log.warn({ url: req.url, host: req.headers.host },- '[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_PUBLIC_URL, or start with `ok start --remote <url>`',+ '[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL, or start with `ok start --remote <url>`',);socket.destroy();return true;@@ -338,7 +338,7 @@ export function createCollaborationHost(options: CollaborationHostOptions): Coll// header, and axis (1) refuses the foreign-Origin shape// unconditionally. Under consent the loopback bind no longer implies// a loopback peer, so `admitted()` (loopback + bind literals +- // publicUrl, identical to the HTTP API gate) keeps direct-IP access+ // externalUrl, identical to the HTTP API gate) keeps direct-IP access// matching what `/api` accepts.const foreignOrigin =req.headers.origin !== undefined && !isOriginAdmitted(req.headers.origin, ingressPolicy);diff --git a/packages/server/src/deployment-cases-composition.test.ts b/packages/server/src/deployment-cases-composition.test.tsindex c6c22fea9..af698a78c 100644--- a/packages/server/src/deployment-cases-composition.test.ts+++ b/packages/server/src/deployment-cases-composition.test.ts@@ -26,17 +26,17 @@ let tmpRoot: string;let case2: BootedServer;let case3: BootedServer;-/** Case 2 env, exactly as the deck draws it (publicUrl per the corrected slide). */+/** Case 2 env, exactly as the deck draws it (externalUrl per the corrected slide). */const CASE2_ENV = {OK_BIND: '127.0.0.1 100.64.0.7',OK_ALLOW_EXTERNAL: '1',- OK_PUBLIC_URL: 'http://laptop.tail:55222',+ OK_EXTERNAL_URL: 'http://laptop.tail:55222',};/** Case 3 env, exactly as the deck draws it. */const CASE3_ENV = {PORT: '8080',- OK_PUBLIC_URL: 'https://notes.example.com',+ OK_EXTERNAL_URL: 'https://notes.example.com',OK_ALLOW_EXTERNAL: '1',};@@ -79,36 +79,36 @@ afterAll(async () => {});describe('deck env spellings resolve to the booted config', () => {- test('Case 2: OK_BIND (space-separated) + OK_ALLOW_EXTERNAL=1 + OK_PUBLIC_URL', () => {+ test('Case 2: OK_BIND (space-separated) + OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL', () => {expect(resolveEnvConfigLayer(CASE2_ENV).layer).toEqual({server: {bind: ['127.0.0.1', '100.64.0.7'],allowExternal: true,- publicUrl: 'http://laptop.tail:55222',+ externalUrl: 'http://laptop.tail:55222',},});});- test('Case 3: platform PORT + OK_PUBLIC_URL + OK_ALLOW_EXTERNAL=1', () => {+ test('Case 3: platform PORT + OK_EXTERNAL_URL + OK_ALLOW_EXTERNAL=1', () => {expect(resolveEnvConfigLayer(CASE3_ENV).layer).toEqual({server: {port: 8080,- publicUrl: 'https://notes.example.com',+ externalUrl: 'https://notes.example.com',allowExternal: true,},});});});-describe('Case 2 — tailnet bind + consent + publicUrl', () => {- test("a teammate's browser read under the publicUrl Host answers", async () => {+describe('Case 2 — tailnet bind + consent + externalUrl', () => {+ test("a teammate's browser read under the externalUrl Host answers", async () => {const res = await rawRequest(case2.port, '/api/server-info', {headers: { Host: 'laptop.tail:55222' },});expect(res.status).toBe(200);});- test("a teammate's mutating write is admitted (Host + Origin from publicUrl)", async () => {+ test("a teammate's mutating write is admitted (Host + Origin from externalUrl)", async () => {const res = await rawRequest(case2.port, '/api/create-page', {method: 'POST',headers: {@@ -138,7 +138,7 @@ describe('Case 2 — tailnet bind + consent + publicUrl', () => {expect(write.status).toBe(200);});- test('an MCP client (no Origin header) is admitted under the publicUrl Host', async () => {+ test('an MCP client (no Origin header) is admitted under the externalUrl Host', async () => {const res = await rawRequest(case2.port, '/api/create-page', {method: 'POST',headers: { Host: 'laptop.tail:55222', 'Content-Type': 'application/json' },@@ -170,7 +170,7 @@ describe('Case 2 — tailnet bind + consent + publicUrl', () => {});});-describe('Case 3 — loopback bind behind a reverse proxy + publicUrl + consent', () => {+describe('Case 3 — loopback bind behind a reverse proxy + externalUrl + consent', () => {/** What Caddy/nginx deliver: loopback peer, public Host, forwarding headers. */const proxied = (extra: Record<string, string> = {}) => ({Host: 'notes.example.com',diff --git a/packages/server/src/handoff-api.test.ts b/packages/server/src/handoff-api.test.tsindex e3e2ca4a5..195a741e2 100644--- a/packages/server/src/handoff-api.test.ts+++ b/packages/server/src/handoff-api.test.ts@@ -483,15 +483,16 @@ describe('GET /api/installed-agents (integration — real HTTP + real createApiEreturn scheme === 'claude' || scheme === 'cursor';},// Declared remote deployment: the /api read gate admits only loopback +- // bind literals + the publicUrl host, so the remote-web capability-tier+ // bind literals + the externalUrl host, so the remote-web capability-tier// Hosts below must be declared names to reach the handler at all (an// undeclared foreign Host is refused at the gate; see the gate test).ingressPolicy: buildIngressPolicy({serverRuntime: {port: undefined,bind: ['127.0.0.1', '192.168.1.100'],- publicUrl: 'http://example.com:5173',- publicUrlSource: 'server',+ externalUrl: 'http://example.com:5173',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -588,7 +589,7 @@ describe('GET /api/installed-agents (integration — real HTTP + real createApiE// dialog be the truth signal). The remote-web case is normally reached via// SSH tunnels / reverse proxies where the connection still terminates on// loopback. Since the read-posture hardening, a non-loopback Host reaches- // the handler only when the deployment DECLARES it (`server.publicUrl` /+ // the handler only when the deployment DECLARES it (`server.externalUrl` /// `server.bind`) — the rig's policy above declares both test Hosts, and an// undeclared one is pinned as refused at the gate below.diff --git a/packages/server/src/http/admit-request-surface.test.ts b/packages/server/src/http/admit-request-surface.test.tsindex e45dff9ad..6783e95f5 100644--- a/packages/server/src/http/admit-request-surface.test.ts+++ b/packages/server/src/http/admit-request-surface.test.ts@@ -8,7 +8,7 @@ import { admitRequestSurface } from './http-app.ts';// BEFORE dispatch for EVERY request — /mcp, /api, the static SPA shell, and// project content assets. These pin the #6 fix: under `allowExternal` consent// (no legacy --remote), it validates Host with the consolidated predicate-// (loopback + bind literals + publicUrl), so a rebound / foreign Host cannot+// (loopback + bind literals + externalUrl), so a rebound / foreign Host cannot// read the static shell or content while the peer is admitted.function req(@@ -44,8 +44,9 @@ const consentPolicy = buildIngressPolicy({serverRuntime: {port: undefined,bind: ['127.0.0.1', '100.64.0.7'],- publicUrl: 'http://laptop.tail:55222',- publicUrlSource: 'server',+ externalUrl: 'http://laptop.tail:55222',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -54,7 +55,7 @@ const consentPolicy = buildIngressPolicy({});describe('admitRequestSurface under allowExternal consent', () => {- test('admits loopback, the bind literal, and the declared publicUrl host', () => {+ test('admits loopback, the bind literal, and the declared externalUrl host', () => {for (const host of ['localhost:5173', '100.64.0.7:55222', 'laptop.tail:55222']) {const { res, status } = fakeRes();expect(admitRequestSurface(req(host), res, consentPolicy, 'test')).toBe(true);@@ -85,10 +86,10 @@ describe('admitRequestSurface under allowExternal consent', () => {expect(status()).toBe(403);});- test('Gate 1: a consented policy with a publicUrl tolerates forwarding headers', () => {- // Under consent with a declared publicUrl the server sits behind a reverse+ test('Gate 1: a consented policy with a externalUrl tolerates forwarding headers', () => {+ // Under consent with a declared externalUrl the server sits behind a reverse// proxy / tunnel on purpose, so forwarded headers are expected and- // tolerated; the Host still gates in Gate 2 (admitted here via publicUrl).+ // tolerated; the Host still gates in Gate 2 (admitted here via externalUrl).const { res, status } = fakeRes();expect(admitRequestSurface(diff --git a/packages/server/src/http/api-pipeline.ts b/packages/server/src/http/api-pipeline.tsindex cd45df923..005dc4cb6 100644--- a/packages/server/src/http/api-pipeline.ts+++ b/packages/server/src/http/api-pipeline.ts@@ -142,7 +142,7 @@ export function createApiRequestPipeline(opts: ApiPipelineOptions): ApiRequestPiconst { log, ephemeral, table } = opts;const policy = opts.policy ?? buildIngressPolicy({});// The policy's Host predicate: loopback names plus every admitted public- // name (bind literals, declared publicUrl, legacy tunnel host) — the same+ // name (bind literals, declared externalUrl, legacy tunnel host) — the same// widening the api-extension applies to its route-level Host gates.const isAllowedWorkspaceHostHeader = (host: string | undefined): boolean =>isHostAdmitted(host, policy);@@ -339,7 +339,7 @@ export function createApiRequestPipeline(opts: ApiPipelineOptions): ApiRequestPi// tag so its counters stay continuous, while normal-mode refusals tag// `api-read-gate` so the universalized posture's fire rate is observable// in isolation. Native clients (curl, MCP) are unaffected: they dial an- // admitted name (loopback, bind literal, or publicUrl host), and Origin+ // admitted name (loopback, bind literal, or externalUrl host), and Origin// logic is untouched.if (url.startsWith('/api/')) {const gateHandler = ephemeral ? 'api-ephemeral-gate' : 'api-read-gate';diff --git a/packages/server/src/http/http-app.ts b/packages/server/src/http/http-app.tsindex ad146a5c5..5a167ff86 100644--- a/packages/server/src/http/http-app.ts+++ b/packages/server/src/http/http-app.ts@@ -87,7 +87,7 @@ export function admitRequestSurface(res,403,'urn:ok:error:host-not-allowed',- 'Proxied request refused: this server has not consented to external exposure. Set OK_PUBLIC_URL to the public origin and OK_ALLOW_EXTERNAL=1 (or server.publicUrl + server.allowExternal in config), or restart with `ok start --remote <url>`.',+ 'Proxied request refused: this server has not consented to external exposure. Set OK_EXTERNAL_URL to the public origin and OK_ALLOW_EXTERNAL=1 (or server.externalUrl + server.allowExternal in config), or restart with `ok start --remote <url>`.',{ handler },);return false;@@ -95,7 +95,7 @@ export function admitRequestSurface(// Gate 2 runs whenever the surface is EXPOSED (`allowExternal` consent).// This covers every surface the prelude fronts: `/mcp`, `/api/*`, the// static shell, and project-mode content assets. The predicate is the- // consolidated one (loopback + bind literals + publicUrl), identical to the+ // consolidated one (loopback + bind literals + externalUrl), identical to the// `/api` pipeline gate, so direct-IP access to the shell/content matches// what the API admits. Pure-local (no exposure) skips this SURFACE-wide// gate on purpose — the read-sensitive legs behind it carry their owndiff --git a/packages/server/src/ingress-policy.test.ts b/packages/server/src/ingress-policy.test.tsindex 225ace2e2..be65f645d 100644--- a/packages/server/src/ingress-policy.test.ts+++ b/packages/server/src/ingress-policy.test.ts@@ -4,7 +4,7 @@ import {buildIngressPolicy,getIngressContext,hasForwardingHeaders,- hostHeaderMatchesPublicHost,+ hostHeaderMatchesExternalHost,isHostAdmitted,isOriginAdmitted,isPeerAdmitted,@@ -17,8 +17,9 @@ function runtime(overrides: Partial<ServerRuntimeConfig> = {}): ServerRuntimeConreturn {port: undefined,bind: ['127.0.0.1'],- publicUrl: undefined,- publicUrlSource: undefined,+ externalUrl: undefined,+ externalUrlSource: undefined,+ externalUrlFromDeprecatedKey: false,allowExternal: false,openBrowser: true,idleShutdown: '30m',@@ -32,8 +33,8 @@ function runtime(overrides: Partial<ServerRuntimeConfig> = {}): ServerRuntimeCon* origin + consent on a loopback bind — no dedicated tunnel shape.*/const REMOTE_ALIAS_RUNTIME: Partial<ServerRuntimeConfig> = {- publicUrl: 'https://myproject.ngrok.app',- publicUrlSource: 'server',+ externalUrl: 'https://myproject.ngrok.app',+ externalUrlSource: 'server',allowExternal: true,idleShutdown: 'off',openBrowser: false,@@ -44,7 +45,7 @@ describe('buildIngressPolicy', () => {const policy = buildIngressPolicy({});expect(policy.allowExternal).toBe(false);expect(policy.bindLiterals).toEqual([]);- expect(policy.publicOrigin).toBeUndefined();+ expect(policy.externalOrigin).toBeUndefined();expect(policy.tolerateForwardedHeaders).toBe(false);});@@ -58,24 +59,24 @@ describe('buildIngressPolicy', () => {expect(policy.bindLiterals).toEqual(['100.64.0.7', '2001:db8::1']);});- test('publicOrigin comes from the successor key only, never the remote alias', () => {+ test('externalOrigin comes from the successor key only, never the remote alias', () => {const explicit = buildIngressPolicy({serverRuntime: runtime({- publicUrl: 'http://laptop.tail:55222',- publicUrlSource: 'server',+ externalUrl: 'http://laptop.tail:55222',+ externalUrlSource: 'server',}),});- expect(explicit.publicOrigin).toEqual({ host: 'laptop.tail:55222', protocol: 'http:' });+ expect(explicit.externalOrigin).toEqual({ host: 'laptop.tail:55222', protocol: 'http:' });const aliased = buildIngressPolicy({serverRuntime: runtime({- publicUrl: 'https://kb.example.com',- publicUrlSource: 'remote-alias',+ externalUrl: 'https://kb.example.com',+ externalUrlSource: 'remote-alias',}),});- expect(aliased.publicOrigin).toBeUndefined();+ expect(aliased.externalOrigin).toBeUndefined();});- test('forwarded headers are tolerated only under consent + declared publicUrl', () => {+ test('forwarded headers are tolerated only under consent + declared externalUrl', () => {// The --remote alias lands exactly here: its expansion carries both keys.expect(buildIngressPolicy({ serverRuntime: runtime(REMOTE_ALIAS_RUNTIME) }).tolerateForwardedHeaders,@@ -84,25 +85,26 @@ describe('buildIngressPolicy', () => {buildIngressPolicy({serverRuntime: runtime({allowExternal: true,- publicUrl: 'https://kb.example.com',- publicUrlSource: 'server',+ externalUrl: 'https://kb.example.com',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,}),}).tolerateForwardedHeaders,).toBe(true);// Consent without a declared public origin does NOT relax the tripwire —- // a proxy in front of a bind-exposed server still needs publicUrl.+ // a proxy in front of a bind-exposed server still needs externalUrl.expect(buildIngressPolicy({serverRuntime: runtime({ allowExternal: true, loopbackOnly: false }),}).tolerateForwardedHeaders,).toBe(false);- // A declared publicUrl without consent never tolerates them either+ // A declared externalUrl without consent never tolerates them either// (that combination is a boot refusal once the interlock enforces).expect(buildIngressPolicy({serverRuntime: runtime({- publicUrl: 'https://kb.example.com',- publicUrlSource: 'server',+ externalUrl: 'https://kb.example.com',+ externalUrlSource: 'server',}),}).tolerateForwardedHeaders,).toBe(false);@@ -132,13 +134,13 @@ describe('isPeerAdmitted — consent relaxes the peer gate ONLY', () => {describe('isHostAdmitted — names validate in every mode, never widened by consent', () => {const case2 = buildIngressPolicy({- // Deck Case 2: tailnet bind + consent, publicUrl per the corrected deck.+ // Deck Case 2: tailnet bind + consent, externalUrl per the corrected deck.serverRuntime: runtime({bind: ['127.0.0.1', '100.64.0.7'],loopbackOnly: false,allowExternal: true,- publicUrl: 'http://laptop.tail:55222',- publicUrlSource: 'server',+ externalUrl: 'http://laptop.tail:55222',+ externalUrlSource: 'server',}),});@@ -148,7 +150,7 @@ describe('isHostAdmitted — names validate in every mode, never widened by consexpect(isHostAdmitted('100.64.0.7', case2)).toBe(true);});- test('the declared publicUrl host is admitted exactly (host:port)', () => {+ test('the declared externalUrl host is admitted exactly (host:port)', () => {expect(isHostAdmitted('laptop.tail:55222', case2)).toBe(true);// A different port is a different name — refused.expect(isHostAdmitted('laptop.tail:9999', case2)).toBe(false);@@ -180,13 +182,13 @@ describe('isHostAdmitted — names validate in every mode, never widened by cons});});-describe('isOriginAdmitted — if present, must match; scheme-matched for publicUrl', () => {+describe('isOriginAdmitted — if present, must match; scheme-matched for externalUrl', () => {const case3 = buildIngressPolicy({- // Deck Case 3: loopback bind behind a proxy, https publicUrl + consent.+ // Deck Case 3: loopback bind behind a proxy, https externalUrl + consent.serverRuntime: runtime({allowExternal: true,- publicUrl: 'https://notes.example.com',- publicUrlSource: 'server',+ externalUrl: 'https://notes.example.com',+ externalUrlSource: 'server',}),});@@ -196,12 +198,12 @@ describe('isOriginAdmitted — if present, must match; scheme-matched for publicexpect(isOriginAdmitted('https://evil.example.com', case3)).toBe(false);});- test('an http publicUrl admits its http origin (tailnet/LAN posture)', () => {+ test('an http externalUrl admits its http origin (tailnet/LAN posture)', () => {const httpPublic = buildIngressPolicy({serverRuntime: runtime({allowExternal: true,- publicUrl: 'http://laptop.tail:55222',- publicUrlSource: 'server',+ externalUrl: 'http://laptop.tail:55222',+ externalUrlSource: 'server',}),});expect(isOriginAdmitted('http://laptop.tail:55222', httpPublic)).toBe(true);@@ -231,7 +233,7 @@ describe('isOriginAdmitted — if present, must match; scheme-matched for publictest('a malformed / unparseable Origin fails closed under consent', () => {// A garbage Origin must not fall through to admission — even under consent- // with a declared publicUrl, an Origin that `new URL()` cannot parse is+ // with a declared externalUrl, an Origin that `new URL()` cannot parse is// refused rather than loosely compared.expect(isOriginAdmitted('http://[not-closed', case3)).toBe(false);expect(isOriginAdmitted('://missing-scheme', case3)).toBe(false);@@ -267,20 +269,20 @@ describe('the --remote alias shape — tunnel admission via the ratified keys',});});-describe('normalizeHostHeader / hostHeaderMatchesPublicHost', () => {+describe('normalizeHostHeader / hostHeaderMatchesExternalHost', () => {test('matches the public host, with or without default-port suffix, case-insensitively', () => {expect(normalizeHostHeader('MyProject.NGROK.app:443')).toBe('myproject.ngrok.app');expect(normalizeHostHeader('host.example:8080')).toBe('host.example:8080');- expect(hostHeaderMatchesPublicHost('myproject.ngrok.app', 'myproject.ngrok.app')).toBe(true);- expect(hostHeaderMatchesPublicHost('myproject.ngrok.app:443', 'myproject.ngrok.app')).toBe(+ expect(hostHeaderMatchesExternalHost('myproject.ngrok.app', 'myproject.ngrok.app')).toBe(true);+ expect(hostHeaderMatchesExternalHost('myproject.ngrok.app:443', 'myproject.ngrok.app')).toBe(true,);- expect(hostHeaderMatchesPublicHost('MyProject.NGROK.app', 'myproject.ngrok.app')).toBe(true);+ expect(hostHeaderMatchesExternalHost('MyProject.NGROK.app', 'myproject.ngrok.app')).toBe(true);});test('refuses other hosts and missing Host', () => {- expect(hostHeaderMatchesPublicHost('evil.example.com', 'myproject.ngrok.app')).toBe(false);- expect(hostHeaderMatchesPublicHost(undefined, 'myproject.ngrok.app')).toBe(false);+ expect(hostHeaderMatchesExternalHost('evil.example.com', 'myproject.ngrok.app')).toBe(false);+ expect(hostHeaderMatchesExternalHost(undefined, 'myproject.ngrok.app')).toBe(false);});});@@ -300,8 +302,8 @@ describe('tripsForwardedHeaderTripwire', () => {const consented = buildIngressPolicy({serverRuntime: runtime({allowExternal: true,- publicUrl: 'https://notes.example.com',- publicUrlSource: 'server',+ externalUrl: 'https://notes.example.com',+ externalUrlSource: 'server',}),});expect(tripsForwardedHeaderTripwire(req, consented)).toBe(false);diff --git a/packages/server/src/ingress-policy.ts b/packages/server/src/ingress-policy.tsindex 842e6e92b..94c522ead 100644--- a/packages/server/src/ingress-policy.ts+++ b/packages/server/src/ingress-policy.ts@@ -8,7 +8,7 @@* WS halves of the server can never disagree about who is admitted.** The `ok start --remote <url>` flag is CLI sugar over the same keys (it- * expands to `server.publicUrl` + loopback `server.bind` ++ * expands to `server.externalUrl` + loopback `server.bind` +* `server.allowExternal`) — there is no separate tunnel policy shape.** The three predicates and what governs each:@@ -19,17 +19,17 @@* may trust non-loopback peers". Nothing else relaxes it.* - HOST (`isHostAdmitted`) — the name the client dialed (DNS-rebinding* defense). Always validates, in every mode, against loopback names + the- * non-loopback bind-address literals + the declared `server.publicUrl`+ * non-loopback bind-address literals + the declared `server.externalUrl`* host. Consent does NOT widen this set: an unconfigured name stays* refused, so a rebound page presenting the attacker's domain is refused* no matter what the peer looks like.* - ORIGIN (`isOriginAdmitted`) — browser CSRF defense; "if present, must* match" (curl and MCP clients send none). Admits the loopback set, the* null/file:// Electron shapes, the bind literals, and the declared- * public origin scheme-matched against `publicUrl`'s own scheme.+ * public origin scheme-matched against `externalUrl`'s own scheme.** Wildcard binds (`0.0.0.0`, `::`) contribute no Host names — they are not- * nameable addresses. A deployment binding wide needs `server.publicUrl` for+ * nameable addresses. A deployment binding wide needs `server.externalUrl` for* any non-loopback name to be admitted; the boot hint says so.*/@@ -44,8 +44,11 @@ export function normalizeHostHeader(host: string): string {}/** True when a raw `Host` names the declared public host — for the Host gates. */-export function hostHeaderMatchesPublicHost(host: string | undefined, publicHost: string): boolean {- return host !== undefined && normalizeHostHeader(host) === publicHost;+export function hostHeaderMatchesExternalHost(+ host: string | undefined,+ externalHost: string,+): boolean {+ return host !== undefined && normalizeHostHeader(host) === externalHost;}/**@@ -81,7 +84,7 @@ export function hasForwardingHeaders(req: Pick<IncomingMessage, 'headers'>): boo* `host-not-allowed` so the guidance never drifts between sites.*/export const HOST_NOT_ADMITTED_REMEDIATION =- 'Add this host to server.bind or set server.publicUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.';+ 'Add this host to server.bind or set server.externalUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.';export interface IngressPolicy {/**@@ -98,12 +101,12 @@ export interface IngressPolicy {*/bindLiterals: readonly string[];/**- * The declared canonical origin — the EXPLICIT `server.publicUrl` only- * (`publicUrlSource === 'server'`). `host` is `host[:port]` with default+ * The declared canonical origin — the EXPLICIT `server.externalUrl` only+ * (`externalUrlSource === 'server'`). `host` is `host[:port]` with default* ports stripped; `protocol` is `http:`/`https:`, matched exactly for* Origin checks since the key admits http for tailnet/LAN deployments.*/- publicOrigin: { host: string; protocol: string } | undefined;+ externalOrigin: { host: string; protocol: string } | undefined;/*** Proxy-forwarding headers tolerated (never trusted — addressing and* identity stay socket/config-derived). True under consent with a declared@@ -115,7 +118,7 @@ export interface IngressPolicy {/*** Boot refusal from the exposure consent interlock: the resolved runtime- * declares external exposure (non-loopback bind, or `server.publicUrl`)+ * declares external exposure (non-loopback bind, or `server.externalUrl`)* without `server.allowExternal`. The message IS the one-line fix; the CLI* maps it to EX_CONFIG like the other config-shaped boot errors.*/@@ -147,20 +150,20 @@ export function buildIngressPolicy(input: BuildIngressPolicyInput): IngressPolic.map(normalizeBindLiteral).filter((addr) => !NON_NAMEABLE_BINDS.has(addr) && !addr.startsWith('127.'));- let publicOrigin: IngressPolicy['publicOrigin'];- if (runtime?.publicUrlSource === 'server' && runtime.publicUrl !== undefined) {+ let externalOrigin: IngressPolicy['externalOrigin'];+ if (runtime?.externalUrlSource === 'server' && runtime.externalUrl !== undefined) {// The schema guarantees a parseable http(s) URL; a throw here would be a// schema/resolver drift bug, so let it propagate loudly at boot.- const parsed = new URL(runtime.publicUrl);- publicOrigin = { host: normalizeHostHeader(parsed.host), protocol: parsed.protocol };+ const parsed = new URL(runtime.externalUrl);+ externalOrigin = { host: normalizeHostHeader(parsed.host), protocol: parsed.protocol };}const allowExternal = runtime?.allowExternal === true;return {allowExternal,bindLiterals,- publicOrigin,- tolerateForwardedHeaders: allowExternal && publicOrigin !== undefined,+ externalOrigin,+ tolerateForwardedHeaders: allowExternal && externalOrigin !== undefined,};}@@ -187,7 +190,7 @@ function hostnameOfHostHeader(host: string): string | null {/*** HOST gate: loopback names, the bind literals (any port), and the declared- * `publicUrl` host (exact host[:port] after default-port normalization).+ * `externalUrl` host (exact host[:port] after default-port normalization).* Never widened by consent.*/export function isHostAdmitted(host: string | undefined, policy: IngressPolicy): boolean {@@ -198,14 +201,15 @@ export function isHostAdmitted(host: string | undefined, policy: IngressPolicy):if (hostname !== null && policy.bindLiterals.includes(hostname)) return true;}return (- policy.publicOrigin !== undefined && hostHeaderMatchesPublicHost(host, policy.publicOrigin.host)+ policy.externalOrigin !== undefined &&+ hostHeaderMatchesExternalHost(host, policy.externalOrigin.host));}/*** ORIGIN gate ("if present, must match" — callers skip when absent): the* loopback/null/file:// set, the declared public origin (scheme-matched- * against `publicUrl`'s own scheme), and the bind literals over http or+ * against `externalUrl`'s own scheme), and the bind literals over http or* https.*/export function isOriginAdmitted(origin: string, policy: IngressPolicy): boolean {@@ -218,9 +222,9 @@ export function isOriginAdmitted(origin: string, policy: IngressPolicy): boolean}if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;if (- policy.publicOrigin !== undefined &&- parsed.protocol === policy.publicOrigin.protocol &&- normalizeHostHeader(parsed.host) === policy.publicOrigin.host+ policy.externalOrigin !== undefined &&+ parsed.protocol === policy.externalOrigin.protocol &&+ normalizeHostHeader(parsed.host) === policy.externalOrigin.host) {return true;}diff --git a/packages/server/src/local-op-security.test.ts b/packages/server/src/local-op-security.test.tsindex f4421be07..4c8caf1d5 100644--- a/packages/server/src/local-op-security.test.ts+++ b/packages/server/src/local-op-security.test.ts@@ -726,8 +726,9 @@ describe('hasValidLocalOpOrigin with a remote public host', () => {serverRuntime: {port: undefined,bind: ['127.0.0.1'],- publicUrl: 'https://myproject.ngrok.app',- publicUrlSource: 'server',+ externalUrl: 'https://myproject.ngrok.app',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',@@ -759,8 +760,9 @@ describe('hasValidLocalOpOrigin with a remote public host', () => {serverRuntime: {port: undefined,bind: ['100.64.0.7'],- publicUrl: undefined,- publicUrlSource: undefined,+ externalUrl: undefined,+ externalUrlSource: undefined,+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',diff --git a/packages/server/src/local-op-security.ts b/packages/server/src/local-op-security.tsindex 05c540fe3..239d651ef 100644--- a/packages/server/src/local-op-security.ts+++ b/packages/server/src/local-op-security.ts@@ -228,7 +228,7 @@ export function isLoopbackRequest(req: IncomingMessage): boolean {* header is allowed (same-origin browser requests / CLI tools).** The admitted set beyond loopback comes from the ingress policy: the- * declared `publicUrl` origin (scheme-matched) and the bind literals — an+ * declared `externalUrl` origin (scheme-matched) and the bind literals — an* empty policy keeps the historical loopback-only set.** Parses the URL and compares hostname exactly; a raw `startsWith` would@@ -253,9 +253,9 @@ export function hasValidLocalOpOrigin(req: IncomingMessage, policy?: IngressPoli}if (policy === undefined) return false;if (- policy.publicOrigin !== undefined &&- url.protocol === policy.publicOrigin.protocol &&- normalizeOriginHost(url.host) === policy.publicOrigin.host+ policy.externalOrigin !== undefined &&+ url.protocol === policy.externalOrigin.protocol &&+ normalizeOriginHost(url.host) === policy.externalOrigin.host) {return true;}diff --git a/packages/server/src/mcp-mount.ts b/packages/server/src/mcp-mount.tsindex fd05db403..580ccda72 100644--- a/packages/server/src/mcp-mount.ts+++ b/packages/server/src/mcp-mount.ts@@ -438,7 +438,7 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandlif (tripsForwardedHeaderTripwire(req, ingressPolicy)) {log.warn({ url: req.url, host: req.headers.host },- '[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_PUBLIC_URL, or start with `ok start --remote <url>`',+ '[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL, or start with `ok start --remote <url>`',);}socket.destroy();diff --git a/packages/server/src/remote-mcp.test.ts b/packages/server/src/remote-mcp.test.tsindex 8b1d45577..c56b587d2 100644--- a/packages/server/src/remote-mcp.test.ts+++ b/packages/server/src/remote-mcp.test.ts@@ -9,7 +9,7 @@* transport itself is the only untested hop.** The ingress policy is built from the SAME `server.*` runtime shape the- * `ok start --remote <url>` alias expands to (`server.publicUrl` + consent+ * `ok start --remote <url>` alias expands to (`server.externalUrl` + consent* on a loopback bind); these tests are the behavior-preservation pins for* the legacy tunnel contract now that the dedicated remote topology is* gone. With the tunnel shape armed there is ONE gate: Host on the@@ -39,14 +39,14 @@ import { createMcpHttpHandler, type McpHttpHandler } from './mcp-http.ts';import { type MountMcpAndApiHandle, mountMcpAndApi } from './mcp-mount.ts';const MCP_PROTOCOL_VERSION = '2025-06-18';-const PUBLIC_URL = 'https://myproject.ngrok.app';-const PUBLIC_HOST = 'myproject.ngrok.app';+const EXTERNAL_URL = 'https://myproject.ngrok.app';+const EXTERNAL_HOST = 'myproject.ngrok.app';/** What any tunnel's local agent delivers: public Host over a loopback socket. */-const TUNNEL_HEADERS = { host: PUBLIC_HOST };+const TUNNEL_HEADERS = { host: EXTERNAL_HOST };/** Same, with the forwarding headers mainstream tunnels inject. */const TUNNEL_FORWARDED_HEADERS = {- host: PUBLIC_HOST,+ host: EXTERNAL_HOST,'x-forwarded-for': '203.0.113.7','x-forwarded-proto': 'https',};@@ -87,7 +87,7 @@ interface RigExtras {acpThreadManager?: unknown;}-async function bootRemoteRig(publicUrl: string | null, extras: RigExtras = {}): Promise<Rig> {+async function bootRemoteRig(externalUrl: string | null, extras: RigExtras = {}): Promise<Rig> {const contentDir = mkdtempSync(join(tmpdir(), 'ok-remote-mcp-'));const localDir = join(contentDir, '.ok', 'local');mkdirSync(localDir, { recursive: true });@@ -95,7 +95,7 @@ async function bootRemoteRig(publicUrl: string | null, extras: RigExtras = {}):// origin + consent; the rig's listener stays loopback like the coerced// remote bind.const config = ConfigSchema.parse(- publicUrl === null ? {} : { server: { publicUrl, allowExternal: true } },+ externalUrl === null ? {} : { server: { externalUrl, allowExternal: true } },);const port = await getFreeLoopbackPort();const handler: McpHttpHandler = createMcpHttpHandler({@@ -300,7 +300,7 @@ function attemptCollabUpgrade(describe('remote enabled — trust-the-tunnel admission', () => {test('tunnel-Host /mcp is admitted with the full tool set (no server-side auth tier)', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);const names = await listToolNames(rig.port, TUNNEL_HEADERS);expect(names).toContain('exec');expect(names).toContain('search');@@ -308,13 +308,13 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('local loopback sessions keep the full tool set when remote is enabled', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);const names = await listToolNames(rig.port, { host: `127.0.0.1:${rig.port}` });for (const tool of WRITE_TOOLS) expect(names).toContain(tool);});test('wrong Host is refused everywhere (DNS-rebinding shape)', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);const mcp = await raw(rig.port, {method: 'POST',path: '/mcp',@@ -327,7 +327,7 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('non-/mcp surfaces are reachable under the tunnel Host (one gate for everything)', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);// The mocked hocuspocus answers nothing, so the mount's own 404 backstop// responding at all (vs a 403) proves admission.const api = await raw(rig.port, { path: '/api/pages', headers: TUNNEL_HEADERS });@@ -337,17 +337,17 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('forwarding headers are fine when remote is enabled (tunnels always inject them)', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);const api = await raw(rig.port, { path: '/api/pages', headers: TUNNEL_FORWARDED_HEADERS });expect(api.status).toBe(404);});test('vendor identity/marker headers are inert — admission is Host-only', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);// Pre-R0 these headers switched tiers (tailnet/funnel). Now they must// change nothing: same Host, same admission, same tool set.const names = await listToolNames(rig.port, {- host: PUBLIC_HOST,+ host: EXTERNAL_HOST,'tailscale-funnel-request': '?1','tailscale-user-login': 'someone@example',});@@ -355,17 +355,17 @@ describe('remote enabled — trust-the-tunnel admission', () => {});test('/collab upgrade admits the tunnel Host and drops wrong Hosts', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);- await expect(attemptCollabUpgrade(rig.port, { Host: PUBLIC_HOST })).resolves.toBe('upgraded');+ const rig = await bootRemoteRig(EXTERNAL_URL);+ await expect(attemptCollabUpgrade(rig.port, { Host: EXTERNAL_HOST })).resolves.toBe('upgraded');await expect(attemptCollabUpgrade(rig.port, { Host: 'evil.example.com' })).resolves.toBe('closed',);});test('/collab/keepalive upgrade admits the tunnel Host and drops wrong Hosts', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);await expect(- attemptCollabUpgrade(rig.port, { Host: PUBLIC_HOST }, '/collab/keepalive'),+ attemptCollabUpgrade(rig.port, { Host: EXTERNAL_HOST }, '/collab/keepalive'),).resolves.toBe('upgraded');await expect(attemptCollabUpgrade(rig.port, { Host: 'evil.example.com' }, '/collab/keepalive'),@@ -376,9 +376,9 @@ describe('remote enabled — trust-the-tunnel admission', () => {// The stub thread manager only clears the fail-closed `acp == null` guard;// the socket touches it solely when a client sends a frame (this raw// upgrade never does), so admission is the only thing under test.- const rig = await bootRemoteRig(PUBLIC_URL, { acpThreadManager: { listThreads: () => [] } });+ const rig = await bootRemoteRig(EXTERNAL_URL, { acpThreadManager: { listThreads: () => [] } });await expect(- attemptCollabUpgrade(rig.port, { Host: PUBLIC_HOST }, '/collab/thread'),+ attemptCollabUpgrade(rig.port, { Host: EXTERNAL_HOST }, '/collab/thread'),).resolves.toBe('upgraded');await expect(attemptCollabUpgrade(rig.port, { Host: 'evil.example.com' }, '/collab/thread'),@@ -387,17 +387,17 @@ describe('remote enabled — trust-the-tunnel admission', () => {await expect(attemptCollabUpgrade(rig.port,- { Host: PUBLIC_HOST, Origin: 'https://evil.example.com' },+ { Host: EXTERNAL_HOST, Origin: 'https://evil.example.com' },'/collab/thread',),).resolves.toBe('closed');});test('default-port Host suffix still matches', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);const api = await raw(rig.port, {path: '/api/pages',- headers: { host: `${PUBLIC_HOST}:443` },+ headers: { host: `${EXTERNAL_HOST}:443` },});expect(api.status).toBe(404);});@@ -452,7 +452,7 @@ describe('remote disabled — the forwarding-header tripwire', () => {const res = await raw(rig.port, {method: 'POST',path: '/mcp',- headers: { host: PUBLIC_HOST },+ headers: { host: EXTERNAL_HOST },});expect(res.status).toBe(403);});@@ -469,7 +469,7 @@ describe('remote enabled — UI over the same port', () => {};test('the shell serves at / and /assets/* under the tunnel Host', async () => {- const rig = await bootRemoteRig(PUBLIC_URL, { reactShellMiddleware: shell });+ const rig = await bootRemoteRig(EXTERNAL_URL, { reactShellMiddleware: shell });const root = await raw(rig.port, { path: '/', headers: TUNNEL_HEADERS });expect(root.status).toBe(200);expect(root.body).toContain('SHELL /');@@ -481,26 +481,26 @@ describe('remote enabled — UI over the same port', () => {});test('the shell is refused under a wrong Host', async () => {- const rig = await bootRemoteRig(PUBLIC_URL, { reactShellMiddleware: shell });+ const rig = await bootRemoteRig(EXTERNAL_URL, { reactShellMiddleware: shell });const res = await raw(rig.port, { path: '/', headers: { host: 'evil.example.com' } });expect(res.status).toBe(403);});test('a browser Origin from the tunnel host is admitted on /mcp', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);const names = await listToolNames(rig.port, {- host: PUBLIC_HOST,- origin: `https://${PUBLIC_HOST}`,+ host: EXTERNAL_HOST,+ origin: `https://${EXTERNAL_HOST}`,});expect(names).toContain('search');});test('a foreign browser Origin is still refused on /mcp', async () => {- const rig = await bootRemoteRig(PUBLIC_URL);+ const rig = await bootRemoteRig(EXTERNAL_URL);const res = await raw(rig.port, {method: 'POST',path: '/mcp',- headers: { host: PUBLIC_HOST, origin: 'https://evil.example.com' },+ headers: { host: EXTERNAL_HOST, origin: 'https://evil.example.com' },});expect(res.status).toBe(403);});diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex 19f94c444..6e23f0eaf 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -2732,8 +2732,9 @@ describe('createServer() — config-doc admission guard', () => {serverRuntime: {port: undefined,bind: ['127.0.0.1'],- publicUrl: 'https://myproject.ngrok.app',- publicUrlSource: 'server',+ externalUrl: 'https://myproject.ngrok.app',+ externalUrlSource: 'server',+ externalUrlFromDeprecatedKey: false,allowExternal: true,openBrowser: false,idleShutdown: 'off',