/** * Tests for the devflow proxy CLI pure functions. * * Strategy: import exported pure functions from proxy.ts and test them directly — * no I/O, no Commander, no network. All tests operate on plain JSON strings or * plain Settings objects. runProxyPreflight tests use injected ProxyPreflightDeps * so every branch is exercised without real TCP/HTTP/spawn. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { promises as fsAsync } from 'fs'; import * as path from 'path'; import * as os from 'os'; import * as net from 'net'; import * as http from 'http'; import { spawn as cpSpawn } from 'child_process'; import color from 'picocolors'; import { applyProxyEnv, stripProxyEnv, readProxyEnvState, addProxyHooks, removeProxyHooks, hasProxyHooks, applyDisableToSettings, applyProxyTeardownToSettings, runProxyPreflight, runPostSpawnVerification, isOurRelayBody, resolvePort, formatExternalModelsLine, formatCodexAuthLine, realHttpGet, terminateRelay, type ProxyPreflightDeps, type PostSpawnDoctorDeps, type TerminateRelayDeps, } from '../src/cli/commands/proxy.js'; import { revertExternalAgents, saveAgentMapping, type AgentMappingFile, } from '../src/core/agent-models.js'; import { writeCache } from '../src/core/cache.js'; import type { ExternalModelCatalog } from '../src/core/model-discovery.js'; import type { RoutingProviderId } from '../src/core/routing-providers.js'; import type { Settings } from '../src/targets/claude-code/hooks.js'; const DEVFLOW_DIR = '/home/test/.devflow'; const DEFAULT_PORT = 4141; const OUR_URL = `http://127.0.0.1:${DEFAULT_PORT}`; // ─── applyProxyEnv ─────────────────────────────────────────────────────────── describe('applyProxyEnv', () => { it('sets ANTHROPIC_BASE_URL to relay URL', () => { const result = JSON.parse(applyProxyEnv(JSON.stringify({}), DEFAULT_PORT)); expect((result.env as Record).ANTHROPIC_BASE_URL).toBe(OUR_URL); }); it('creates env object when settings has none', () => { const result = JSON.parse(applyProxyEnv(JSON.stringify({ hooks: {} }), DEFAULT_PORT)); expect((result.env as Record).ANTHROPIC_BASE_URL).toBe(OUR_URL); }); it('preserves other env vars', () => { const input = JSON.stringify({ env: { SOME_OTHER_VAR: 'keep' } }); const result = JSON.parse(applyProxyEnv(input, DEFAULT_PORT)); const env = result.env as Record; expect(env.ANTHROPIC_BASE_URL).toBe(OUR_URL); expect(env.SOME_OTHER_VAR).toBe('keep'); }); it('uses the correct port in URL', () => { const result = JSON.parse(applyProxyEnv(JSON.stringify({}), 9999)); expect((result.env as Record).ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:9999'); }); it('is idempotent — double apply produces same result', () => { const once = applyProxyEnv(JSON.stringify({}), DEFAULT_PORT); const twice = applyProxyEnv(once, DEFAULT_PORT); expect(JSON.parse(twice).env.ANTHROPIC_BASE_URL).toBe(OUR_URL); }); it('does not mutate input — returns new serialized string', () => { const input = JSON.stringify({}); applyProxyEnv(input, DEFAULT_PORT); expect(JSON.parse(input).env).toBeUndefined(); }); it('throws on malformed JSON', () => { expect(() => applyProxyEnv('not json', DEFAULT_PORT)).toThrow(SyntaxError); }); }); // ─── stripProxyEnv ─────────────────────────────────────────────────────────── // // REG-1 regression: the old implementation used OUR_BASE_URL_PATTERN which matched // ANY localhost port. A user with LiteLLM on 127.0.0.1:4000 had ANTHROPIC_BASE_URL // silently deleted on every `devflow init`. The fix scopes the strip to the exact // managed port Devflow owns (proxy.json.port or DEFAULT_PROXY_PORT). describe('stripProxyEnv', () => { it('removes ANTHROPIC_BASE_URL when it matches our relay on the managed port', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: OUR_URL, OTHER: 'keep' } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); expect((result.env as Record).ANTHROPIC_BASE_URL).toBeUndefined(); expect((result.env as Record).OTHER).toBe('keep'); }); it('removes env object entirely when relay URL was the only key', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: OUR_URL } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); expect(result.env).toBeUndefined(); }); it('does NOT remove ANTHROPIC_BASE_URL when it points to a foreign HTTPS gateway', () => { const foreignUrl = 'https://my-custom-gateway.example.com'; const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: foreignUrl } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); expect((result.env as Record).ANTHROPIC_BASE_URL).toBe(foreignUrl); }); it('does NOT remove ANTHROPIC_BASE_URL when it uses HTTPS (not our relay)', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://127.0.0.1:4141' } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); expect((result.env as Record).ANTHROPIC_BASE_URL).toBe('https://127.0.0.1:4141'); }); // REG-1 regression: foreign localhost URL must survive init-path strip it('REG-1: does NOT strip a localhost URL on a port Devflow does not manage', () => { // User has their own LiteLLM gateway on 4000; Devflow manages 4141. const litellmUrl = 'http://127.0.0.1:4000'; const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: litellmUrl } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT /* 4141 */)); // 4000 ≠ 4141 → must NOT be stripped expect((result.env as Record).ANTHROPIC_BASE_URL).toBe(litellmUrl); }); // REG-1 regression: our port IS stripped when managed port matches it('REG-1: strips relay URL on a non-default managed port when port matches', () => { const customPortUrl = 'http://127.0.0.1:9999'; const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: customPortUrl } }); const result = JSON.parse(stripProxyEnv(input, 9999 /* managedPort */)); expect(result.env).toBeUndefined(); }); // REG-1 regression: ours-other-port (not managed) is left alone it('REG-1: does NOT strip ours-other-port URL when managed port is different', () => { // URL=5000 (old enable), managed port now 4141 → 5000 is not our current port const oldUrl = 'http://127.0.0.1:5000'; const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: oldUrl } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT /* 4141 */)); expect((result.env as Record).ANTHROPIC_BASE_URL).toBe(oldUrl); }); it('is a no-op when ANTHROPIC_BASE_URL not set', () => { const input = JSON.stringify({ env: { SOME_VAR: 'value' } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); expect((result.env as Record).SOME_VAR).toBe('value'); }); it('is a no-op when env block absent', () => { const input = JSON.stringify({ hooks: {} }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); expect(result.env).toBeUndefined(); }); it('is idempotent — double strip is the same as single strip', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: OUR_URL } }); const once = stripProxyEnv(input, DEFAULT_PORT); const twice = stripProxyEnv(once, DEFAULT_PORT); expect(JSON.parse(twice).env).toBeUndefined(); }); it('does not mutate input', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: OUR_URL } }); stripProxyEnv(input, DEFAULT_PORT); expect(JSON.parse(input).env.ANTHROPIC_BASE_URL).toBe(OUR_URL); }); }); // ─── readProxyEnvState ─────────────────────────────────────────────────────── describe('readProxyEnvState', () => { it('returns "ours" when ANTHROPIC_BASE_URL matches relay on given port', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: OUR_URL } }); expect(readProxyEnvState(input, DEFAULT_PORT)).toBe('ours'); }); it('returns "ours-other-port" when relay URL but different port', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:9999' } }); expect(readProxyEnvState(input, DEFAULT_PORT)).toBe('ours-other-port'); }); it('returns "foreign" when ANTHROPIC_BASE_URL points to a different gateway', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://custom.gateway.io' } }); expect(readProxyEnvState(input, DEFAULT_PORT)).toBe('foreign'); }); it('returns "absent" when ANTHROPIC_BASE_URL not set', () => { const input = JSON.stringify({ env: { OTHER_VAR: 'value' } }); expect(readProxyEnvState(input, DEFAULT_PORT)).toBe('absent'); }); it('returns "absent" when env block absent', () => { const input = JSON.stringify({}); expect(readProxyEnvState(input, DEFAULT_PORT)).toBe('absent'); }); it('returns "foreign" for HTTPS relay-looking URL (we only use http)', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://127.0.0.1:4141' } }); expect(readProxyEnvState(input, DEFAULT_PORT)).toBe('foreign'); }); }); // ─── addProxyHooks / removeProxyHooks / hasProxyHooks ──────────────────────── describe('addProxyHooks', () => { it('adds ensure-proxy to both SessionStart and UserPromptSubmit', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); expect(hasProxyHooks(settings)).toBe(true); const sessionHooks = settings.hooks?.['SessionStart']; const promptHooks = settings.hooks?.['UserPromptSubmit']; expect(sessionHooks?.some(m => m.hooks.some(h => h.command.includes('ensure-proxy')))).toBe(true); expect(promptHooks?.some(m => m.hooks.some(h => h.command.includes('ensure-proxy')))).toBe(true); }); it('sets timeout 15 on added hooks', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); const sessionEntry = settings.hooks?.['SessionStart']?.[0].hooks[0]; expect(sessionEntry?.timeout).toBe(15); const promptEntry = settings.hooks?.['UserPromptSubmit']?.[0].hooks[0]; expect(promptEntry?.timeout).toBe(15); }); it('includes run-hook ensure-proxy in command string', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); const cmd = settings.hooks?.['SessionStart']?.[0].hooks[0].command ?? ''; expect(cmd).toContain('run-hook'); expect(cmd).toContain('ensure-proxy'); }); it('uses devflowDir to build hook command path', () => { const settings: Settings = {}; addProxyHooks(settings, '/custom/devflow'); const cmd = settings.hooks?.['SessionStart']?.[0].hooks[0].command ?? ''; expect(cmd).toContain('/custom/devflow'); }); it('is idempotent — adding twice does not duplicate hooks', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); addProxyHooks(settings, DEVFLOW_DIR); const sessionHooks = settings.hooks?.['SessionStart'] ?? []; const proxyCount = sessionHooks.filter(m => m.hooks.some(h => h.command.includes('ensure-proxy'))).length; expect(proxyCount).toBe(1); }); it('repairs partial state — adds missing event when other is present', () => { // Only SessionStart exists const settings: Settings = { hooks: { 'SessionStart': [{ hooks: [{ type: 'command', command: `${DEVFLOW_DIR}/scripts/hooks/run-hook ensure-proxy`, timeout: 15 }] }], }, }; const changed = addProxyHooks(settings, DEVFLOW_DIR); expect(changed).toBe(true); // UserPromptSubmit now also has it expect(settings.hooks?.['UserPromptSubmit']?.some(m => m.hooks.some(h => h.command.includes('ensure-proxy')))).toBe(true); }); it('preserves other hooks on the same events', () => { const settings: Settings = { hooks: { 'SessionStart': [{ hooks: [{ type: 'command', command: 'other-hook', timeout: 5 }] }], }, }; addProxyHooks(settings, DEVFLOW_DIR); const sessionHooks = settings.hooks?.['SessionStart'] ?? []; // Both hooks should be present expect(sessionHooks.some(m => m.hooks.some(h => h.command === 'other-hook'))).toBe(true); expect(sessionHooks.some(m => m.hooks.some(h => h.command.includes('ensure-proxy')))).toBe(true); }); it('returns true when hooks were added', () => { const settings: Settings = {}; expect(addProxyHooks(settings, DEVFLOW_DIR)).toBe(true); }); it('returns false when hooks already present (no-op)', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); expect(addProxyHooks(settings, DEVFLOW_DIR)).toBe(false); }); }); describe('removeProxyHooks', () => { it('removes ensure-proxy from both events', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); removeProxyHooks(settings); expect(hasProxyHooks(settings)).toBe(false); }); it('preserves other hooks on the same events', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); settings.hooks!['SessionStart']!.push({ hooks: [{ type: 'command', command: 'other-hook', timeout: 5 }] }); removeProxyHooks(settings); const sessionHooks = settings.hooks?.['SessionStart'] ?? []; expect(sessionHooks.some(m => m.hooks.some(h => h.command === 'other-hook'))).toBe(true); expect(sessionHooks.some(m => m.hooks.some(h => h.command.includes('ensure-proxy')))).toBe(false); }); it('cleans up empty hooks event array', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); // remove leaves hooks.SessionStart/UserPromptSubmit empty — should delete keys removeProxyHooks(settings); expect(settings.hooks?.['SessionStart']).toBeUndefined(); expect(settings.hooks?.['UserPromptSubmit']).toBeUndefined(); }); it('cleans up empty hooks object', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); removeProxyHooks(settings); expect(settings.hooks).toBeUndefined(); }); it('is a no-op when hooks are not present', () => { const settings: Settings = {}; expect(() => removeProxyHooks(settings)).not.toThrow(); }); it('returns true when hooks were removed', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); expect(removeProxyHooks(settings)).toBe(true); }); it('returns false when nothing to remove', () => { const settings: Settings = {}; expect(removeProxyHooks(settings)).toBe(false); }); it('is idempotent — removing twice does not throw', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); removeProxyHooks(settings); expect(() => removeProxyHooks(settings)).not.toThrow(); expect(removeProxyHooks(settings)).toBe(false); }); }); describe('hasProxyHooks', () => { it('returns false for empty settings', () => { expect(hasProxyHooks({})).toBe(false); }); it('returns true after addProxyHooks', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); expect(hasProxyHooks(settings)).toBe(true); }); it('returns false after removeProxyHooks', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); removeProxyHooks(settings); expect(hasProxyHooks(settings)).toBe(false); }); it('accepts a JSON string (object or string)', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); expect(hasProxyHooks(JSON.stringify(settings))).toBe(true); }); it('returns true when only one event is present (partial state)', () => { const settings: Settings = { hooks: { 'SessionStart': [{ hooks: [{ type: 'command', command: `${DEVFLOW_DIR}/scripts/hooks/run-hook ensure-proxy`, timeout: 15 }] }], }, }; expect(hasProxyHooks(settings)).toBe(true); }); it('returns false when hooks exist but none are ensure-proxy', () => { const settings: Settings = { hooks: { 'SessionStart': [{ hooks: [{ type: 'command', command: 'other-hook', timeout: 5 }] }], }, }; expect(hasProxyHooks(settings)).toBe(false); }); }); // ─── D-EXACT-HOOK-OWNER: ensure-proxy is matched exactly (#391) ───────────── describe('ensure-proxy hook ownership is exact (#391)', () => { const RUN = `${DEVFLOW_DIR}/scripts/hooks/run-hook ensure-proxy`; /** User groups whose every hook mentions ensure-proxy; none is devflow's. */ const USER_SESSION = { matcher: 'startup', hooks: [ { type: 'command', command: '~/bin/ensure-proxy.sh', timeout: 3 }, { type: 'command', command: '/opt/tools/run-hook ensure-proxy' }, ] }; const USER_PROMPT = { hooks: [{ type: 'command', command: 'echo ensure-proxy >> /tmp/log' }] }; const userSettings = (): Settings => ({ hooks: { SessionStart: [USER_SESSION], UserPromptSubmit: [USER_PROMPT] } }); it('user hooks that contain the word ensure-proxy are not the proxy hook', () => { expect(hasProxyHooks(userSettings())).toBe(false); }); it('disable on settings holding only user groups changes nothing', () => { const settings = userSettings(); expect(removeProxyHooks(settings)).toBe(false); expect(settings).toEqual(userSettings()); }); it('enable registers devflow\'s hook on both events after the untouched user groups; disable restores them', () => { const settings = userSettings(); expect(addProxyHooks(settings, DEVFLOW_DIR)).toBe(true); expect(settings.hooks?.SessionStart).toEqual([USER_SESSION, { hooks: [{ type: 'command', command: RUN, timeout: 15 }] }]); expect(settings.hooks?.UserPromptSubmit).toEqual([USER_PROMPT, { hooks: [{ type: 'command', command: RUN, timeout: 15 }] }]); expect(removeProxyHooks(settings)).toBe(true); expect(settings).toEqual(userSettings()); }); it('removes only devflow\'s hook from a shared group and keeps the siblings in order', () => { const settings: Settings = { hooks: { SessionStart: [{ hooks: [ { type: 'command', command: 'say hello' }, { type: 'command', command: RUN, timeout: 15 }, { type: 'command', command: 'say ready' }, ] }] } }; expect(removeProxyHooks(settings)).toBe(true); expect(settings.hooks?.SessionStart).toEqual([{ hooks: [ { type: 'command', command: 'say hello' }, { type: 'command', command: 'say ready' }, ] }]); }); it.each([ ['another directory', '/srv/old/.devflow/scripts/hooks/run-hook ensure-proxy'], ['a Windows path', 'C:\\Users\\u\\.devflow\\scripts\\hooks\\run-hook ensure-proxy'], ])('still recognises and removes devflow\'s hook registered under %s', (_label, command) => { const settings: Settings = { hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command }] }] } }; expect(hasProxyHooks(settings)).toBe(true); expect(removeProxyHooks(settings)).toBe(true); expect(settings.hooks).toBeUndefined(); }); }); // ─── applyDisableToSettings ────────────────────────────────────────────────── // // Regression for the || short-circuit bug: when hooks were present, the old // code `removeProxyHooks(s) || _stripProxyEnv(s)` short-circuited and never // stripped ANTHROPIC_BASE_URL, leaving sessions pointed at a disabled relay. // // REG-1: the second argument is the managed port. Tests use DEFAULT_PORT (4141) // which matches OUR_URL — callers in production read proxy.json.port. describe('applyDisableToSettings', () => { it('removes BOTH proxy hooks AND ANTHROPIC_BASE_URL when both are present (regression)', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); (settings as Record).env = { ANTHROPIC_BASE_URL: OUR_URL }; const changed = applyDisableToSettings(settings, DEFAULT_PORT); expect(changed).toBe(true); expect(hasProxyHooks(settings)).toBe(false); expect((settings as Record).env).toBeUndefined(); }); it('removes only hooks when env var absent', () => { const settings: Settings = {}; addProxyHooks(settings, DEVFLOW_DIR); const changed = applyDisableToSettings(settings, DEFAULT_PORT); expect(changed).toBe(true); expect(hasProxyHooks(settings)).toBe(false); }); it('removes only ANTHROPIC_BASE_URL when hooks absent', () => { const settings = { env: { ANTHROPIC_BASE_URL: OUR_URL } } as unknown as Settings; const changed = applyDisableToSettings(settings, DEFAULT_PORT); expect(changed).toBe(true); expect((settings as Record).env).toBeUndefined(); }); it('returns false when settings already clean (no-op)', () => { const settings: Settings = {}; expect(applyDisableToSettings(settings, DEFAULT_PORT)).toBe(false); }); it('does NOT strip ANTHROPIC_BASE_URL when it points to a foreign HTTPS gateway', () => { const settings = { env: { ANTHROPIC_BASE_URL: 'https://my-custom-gateway.example.com' }, } as unknown as Settings; const changed = applyDisableToSettings(settings, DEFAULT_PORT); expect(changed).toBe(false); expect( (settings as Record & { env: Record }).env.ANTHROPIC_BASE_URL, ).toBe('https://my-custom-gateway.example.com'); }); // REG-1: disable strips OUR port but not a foreign localhost port it('REG-1: strips relay URL on the managed port', () => { const settings = { env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:5000' } } as unknown as Settings; const changed = applyDisableToSettings(settings, 5000 /* managedPort = our port */); expect(changed).toBe(true); expect((settings as Record).env).toBeUndefined(); }); it('REG-1: does NOT strip a foreign localhost URL on a different port from managedPort', () => { // User's own LiteLLM on 4000; we manage 4141 → leave 4000 alone const settings = { env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:4000' } } as unknown as Settings; const changed = applyDisableToSettings(settings, DEFAULT_PORT /* 4141 */); expect(changed).toBe(false); expect( (settings as Record & { env: Record }).env.ANTHROPIC_BASE_URL, ).toBe('http://127.0.0.1:4000'); }); }); // ─── runProxyPreflight ──────────────────────────────────────────────────────── /** Build a complete passing set of preflight deps for customization. */ function makeDeps(overrides: Partial = {}): ProxyPreflightDeps { return { resolveProxyBin: vi.fn().mockResolvedValue({ ok: true, value: { binPath: '/path/to/relay.js', npxWarning: false } }), fileExists: vi.fn().mockResolvedValue(true), tcpConnectable: vi.fn().mockResolvedValue(false), // port free by default httpGet: vi.fn().mockResolvedValue({ ok: true, value: '{"name":"subswitch","version":"0.2.0","providers":[{"id":"anthropic","configured":true,"modelCount":0}]}' }), readSettingsJson: vi.fn().mockResolvedValue('{}'), spawnDoctor: vi.fn().mockResolvedValue(0), onWarn: vi.fn(), ...overrides, }; } describe('runProxyPreflight', () => { const port = DEFAULT_PORT; const codexAuthPath = '/home/test/.codex/auth.json'; const configPath = '/home/test/.devflow/proxy-routing.json'; const logPath = '/home/test/.devflow/logs/proxy.log'; // ① Routing runtime bin it('returns Err when resolveProxyBin fails', async () => { const deps = makeDeps({ resolveProxyBin: vi.fn().mockResolvedValue({ ok: false, error: 'routing runtime missing — reinstall devflow-kit' }), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toContain('routing runtime missing'); } }); // ② Codex auth it('returns Err when codex auth file absent', async () => { const deps = makeDeps({ fileExists: vi.fn().mockResolvedValue(false), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toContain('codex login'); } }); // ③ Port probe — free it('returns Ok when all checks pass with port free', async () => { const deps = makeDeps(); // tcpConnectable=false const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(true); if (result.ok) { expect(result.value.adopted).toBe(false); expect(result.value.binPath).toBe('/path/to/relay.js'); } // Doctor is no longer called by preflight — it moved to runPostSpawnVerification expect(deps.spawnDoctor).not.toHaveBeenCalled(); }); // ③ Port probe — already ours (adopt) it('returns Ok with adopted:true when port is up and health matches our relay', async () => { const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), // port up httpGet: vi.fn().mockResolvedValue({ ok: true, value: '{"name":"subswitch","version":"0.2.0","providers":[{"id":"anthropic","configured":true,"modelCount":0}]}' }), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(true); if (result.ok) { expect(result.value.adopted).toBe(true); } }); // ③ Port probe — squatted by another app it('returns Err when port is up but health does not match our relay', async () => { const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), httpGet: vi.fn().mockResolvedValue({ ok: true, value: '{"name":"some-other-app"}' }), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toContain('in use by another application'); } }); // ③ Port probe — squatted, health fails too it('returns Err when port is up but health request fails (not our relay)', async () => { const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), httpGet: vi.fn().mockResolvedValue({ ok: false, error: 'connection refused' }), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toContain('in use by another application'); } }); // ④ Settings check — foreign ANTHROPIC_BASE_URL it('returns Err when ANTHROPIC_BASE_URL is set to a foreign gateway', async () => { const deps = makeDeps({ readSettingsJson: vi.fn().mockResolvedValue(JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://custom.gateway.example.com' }, })), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toContain('ANTHROPIC_BASE_URL'); } }); // ④ Settings check — ANTHROPIC_API_KEY warning (non-fatal) it('calls onWarn when ANTHROPIC_API_KEY is present in settings', async () => { const onWarn = vi.fn(); const deps = makeDeps({ readSettingsJson: vi.fn().mockResolvedValue(JSON.stringify({ env: { ANTHROPIC_API_KEY: 'sk-test-key' }, })), onWarn, }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(true); // warning is non-fatal expect(onWarn).toHaveBeenCalledWith(expect.stringContaining('ANTHROPIC_API_KEY')); }); // ④ Settings check — our own relay URL (not foreign) it('does not fail when ANTHROPIC_BASE_URL is already our relay URL', async () => { const deps = makeDeps({ readSettingsJson: vi.fn().mockResolvedValue(JSON.stringify({ env: { ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}` }, })), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(true); }); // ④ Settings check — settings.json unreadable it('returns Err when readSettingsJson throws', async () => { const deps = makeDeps({ readSettingsJson: vi.fn().mockRejectedValue(new Error('ENOENT')), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toContain('settings.json'); } }); // npxWarning propagated (from check ①) it('propagates npxWarning from resolveProxyBin', async () => { const deps = makeDeps({ resolveProxyBin: vi.fn().mockResolvedValue({ ok: true, value: { binPath: '/path/.../relay.js', npxWarning: true } }), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(true); if (result.ok) { expect(result.value.npxWarning).toBe(true); } }); // TEST-11: Health-check timeout path — httpGet Err('timeout') must fold into the // port-conflict Err, not a separate path. Pinned explicitly so a future refactor // cannot accidentally diverge timeout from connection-refused. it('returns port-conflict Err when port is up but health check times out (timeout folds into port-conflict path)', async () => { const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), httpGet: vi.fn().mockResolvedValue({ ok: false, error: 'timeout' }), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(false); if (!result.ok) { // timeout folds into the same port-conflict path as connection-refused expect(result.error).toContain('in use by another application'); } }); // Ordering: later checks not run if earlier checks fail it('does not check codex auth when bin resolution fails', async () => { const fileExists = vi.fn(); const deps = makeDeps({ resolveProxyBin: vi.fn().mockResolvedValue({ ok: false, error: 'routing runtime missing — reinstall devflow-kit' }), fileExists, }); await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(fileExists).not.toHaveBeenCalled(); }); // Preflight never calls spawnDoctor — doctor runs post-spawn in runPostSpawnVerification it('never calls spawnDoctor — doctor moved to post-spawn verification', async () => { const spawnDoctor = vi.fn(); // Test across the non-adopt path (port free, all checks pass) const deps = makeDeps({ spawnDoctor }); await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(spawnDoctor).not.toHaveBeenCalled(); }); it('never calls spawnDoctor even when port is squatted (early return path)', async () => { const spawnDoctor = vi.fn(); const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), httpGet: vi.fn().mockResolvedValue({ ok: true, value: '{"name":"other"}' }), spawnDoctor, }); await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(spawnDoctor).not.toHaveBeenCalled(); }); }); // ─── runPostSpawnVerification ───────────────────────────────────────────────── // // D-EFR-2: Doctor runs post-spawn against a live relay, not pre-spawn where the // relay port is always down on a cold path. Kill-on-rollback is restricted to // self-spawned relays (spawnedPid defined) — adopted relays must not be killed. /** Build a complete passing set of PostSpawnDoctorDeps for customisation. */ function makePostSpawnDeps(overrides: Partial = {}): PostSpawnDoctorDeps { return { spawnDoctor: vi.fn().mockResolvedValue(0), killProcess: vi.fn(), writeDisabledProxyState: vi.fn().mockResolvedValue({ ok: true, value: undefined }), ...overrides, }; } describe('runPostSpawnVerification', () => { const BIN = '/path/to/relay.js'; const CONFIG = '/home/test/.devflow/proxy-routing.json'; const LOG = '/home/test/.devflow/logs/proxy.log'; // (a) doctor runs after port is confirmed up (i.e. spawnDoctor is called by this function) it('calls spawnDoctor — runs against the live relay, not during preflight', async () => { const deps = makePostSpawnDeps(); await runPostSpawnVerification(BIN, CONFIG, LOG, undefined, deps); expect(deps.spawnDoctor).toHaveBeenCalled(); }); // (d) doctor exits zero → Ok; no rollback, no kill it('doctor exits zero — returns Ok (settings pass proceeds)', async () => { const deps = makePostSpawnDeps({ spawnDoctor: vi.fn().mockResolvedValue(0) }); const result = await runPostSpawnVerification(BIN, CONFIG, LOG, 1234, deps); expect(result.ok).toBe(true); expect(deps.writeDisabledProxyState).not.toHaveBeenCalled(); expect(deps.killProcess).not.toHaveBeenCalled(); }); // (b) doctor non-zero + self-spawned → rollback AND kill it('doctor non-zero with self-spawned relay — rolls back proxy state and kills spawned pid', async () => { const deps = makePostSpawnDeps({ spawnDoctor: vi.fn().mockResolvedValue(1) }); const result = await runPostSpawnVerification(BIN, CONFIG, LOG, 1234, deps); expect(result.ok).toBe(false); expect(deps.writeDisabledProxyState).toHaveBeenCalled(); expect(deps.killProcess).toHaveBeenCalledWith(1234); }); it('returns a verification error and rolls back when doctor rejects', async () => { const deps = makePostSpawnDeps({ spawnDoctor: vi.fn().mockRejectedValue(new Error('spawn failed')) }); await expect(runPostSpawnVerification(BIN, CONFIG, LOG, undefined, deps)).resolves.toMatchObject({ ok: false, error: expect.stringContaining('Routing verification failed'), }); expect(deps.writeDisabledProxyState).toHaveBeenCalledOnce(); }); it('appends the rollback error on a new line when the state write fails', async () => { const deps = makePostSpawnDeps({ spawnDoctor: vi.fn().mockResolvedValue(1), writeDisabledProxyState: vi.fn().mockResolvedValue({ ok: false, error: 'X' }), }); await expect(runPostSpawnVerification(BIN, CONFIG, LOG, undefined, deps)).resolves.toMatchObject({ ok: false, error: expect.stringMatching(/^Routing verification failed[^\n]*\nX$/), }); }); // (c) doctor non-zero + adopted (spawnedPid undefined) → rollback WITHOUT kill it('doctor non-zero with adopted relay — rolls back proxy state without killing', async () => { const deps = makePostSpawnDeps({ spawnDoctor: vi.fn().mockResolvedValue(1) }); const result = await runPostSpawnVerification(BIN, CONFIG, LOG, undefined, deps); expect(result.ok).toBe(false); expect(deps.writeDisabledProxyState).toHaveBeenCalled(); expect(deps.killProcess).not.toHaveBeenCalled(); }); // Branding constraint: error message must not expose internal relay package name it('error message does not expose internal relay package name', async () => { const deps = makePostSpawnDeps({ spawnDoctor: vi.fn().mockResolvedValue(1) }); const result = await runPostSpawnVerification(BIN, CONFIG, LOG, undefined, deps); if (!result.ok) { expect(result.error.toLowerCase()).not.toContain('subswitch'); } else { throw new Error('Expected Err result'); } }); // Error message references the log path for diagnostics it('error message references the log path', async () => { const deps = makePostSpawnDeps({ spawnDoctor: vi.fn().mockResolvedValue(1) }); const result = await runPostSpawnVerification(BIN, CONFIG, LOG, undefined, deps); if (!result.ok) { expect(result.error).toContain(LOG); } else { throw new Error('Expected Err result'); } }); }); // ─── isOurRelayBody ────────────────────────────────────────────────────────── // // CPLX-9: extracted helper used by both runProxyPreflight and resolveProcessState // to identify the relay without duplicating the parse/check logic. describe('isOurRelayBody', () => { it('returns true for a valid relay health body with name=subswitch (0.2.0 shape with providers)', () => { expect(isOurRelayBody('{"name":"subswitch","version":"0.2.0","providers":[{"id":"anthropic","configured":true,"modelCount":0}]}')).toBe(true); }); it('returns false for a body with a different name field', () => { expect(isOurRelayBody('{"name":"some-other-app"}')).toBe(false); }); it('returns false for invalid JSON', () => { expect(isOurRelayBody('not json')).toBe(false); }); it('returns false for an empty string', () => { expect(isOurRelayBody('')).toBe(false); }); it('returns false for valid JSON without a name field', () => { expect(isOurRelayBody('{"status":"ok","version":"0.1.0"}')).toBe(false); }); it('returns false for a body where name is not exactly "subswitch"', () => { expect(isOurRelayBody('{"name":"Subswitch"}')).toBe(false); expect(isOurRelayBody('{"name":"subswitch2"}')).toBe(false); }); }); // ─── resolvePort ───────────────────────────────────────────────────────────── // // TS-1 regression: commander had `.option('--port ', ..., String(DEFAULT_PROXY_PORT))` // which made options.port always the string '4141' — never undefined. The remembered-port // fallback inside runEnable was dead code: a user who enabled on port 5000, disabled, then // re-enabled without --port would silently revert to 4141 (spawning a second relay, leaking // the old one on 5000). // // Fix: drop the commander default so omission is detectable as undefined; resolvePort treats // undefined as "use prior port". describe('resolvePort', () => { it('prior port 5000 + no --port → uses remembered port 5000 (TS-1 regression)', () => { const result = resolvePort(undefined, 5000); expect(result.ok).toBe(true); if (result.ok) expect(result.value).toBe(5000); }); it('explicit --port 8080 overrides prior port', () => { const result = resolvePort('8080', 5000); expect(result.ok).toBe(true); if (result.ok) expect(result.value).toBe(8080); }); it('returns prior port when portOption is undefined regardless of prior value', () => { const result = resolvePort(undefined, 4141); expect(result.ok).toBe(true); if (result.ok) expect(result.value).toBe(4141); }); it('returns Err for non-numeric --port (NaN)', () => { const result = resolvePort('not-a-port', 4141); expect(result.ok).toBe(false); if (!result.ok) expect(result.error).toContain('Invalid port'); }); it('returns Err for port 0 (out of range)', () => { const result = resolvePort('0', 4141); expect(result.ok).toBe(false); }); it('returns Err for port 65536 (out of range)', () => { const result = resolvePort('65536', 4141); expect(result.ok).toBe(false); }); it('returns Ok for port 1 (min valid)', () => { const result = resolvePort('1', 4141); expect(result.ok).toBe(true); if (result.ok) expect(result.value).toBe(1); }); it('returns Ok for port 65535 (max valid)', () => { const result = resolvePort('65535', 4141); expect(result.ok).toBe(true); if (result.ok) expect(result.value).toBe(65535); }); }); // ─── T7 / AC-F8: disable full post-state — whole-end-state assertion ── // // Toggle correctness is only proven by asserting the WHOLE end-state from // a fully-enabled starting state — not by checking individual artifacts per step. // // AC-F8: devflow proxy --disable reverts settings (hooks + ANTHROPIC_BASE_URL). // The reversion is independent of model discovery: applyDisableToSettings is a pure // Settings function that does not call discoverExternalModels or // getExternalModelsCached. All three discovery scenarios (cache hit, cache miss, no // binary) produce IDENTICAL Settings post-state. describe('T7 / AC-F8: disable full post-state — whole-end-state assertion', () => { /** Fully-enabled settings: proxy hooks on both event types + ANTHROPIC_BASE_URL set. */ function buildFullyEnabledSettings(extraEnv?: Record): Settings { const s: Settings = {}; addProxyHooks(s, DEVFLOW_DIR); (s as Record).env = { ANTHROPIC_BASE_URL: OUR_URL, ...extraEnv, }; return s; } it('full post-state: hooks removed, relay URL removed, extra env vars preserved', () => { const s = buildFullyEnabledSettings({ EXTRA: 'keep' }); const changed = applyDisableToSettings(s, DEFAULT_PORT); // Assert the WHOLE final state, not per-step booleans expect(changed).toBe(true); expect(hasProxyHooks(s)).toBe(false); const env = (s as Record).env as Record | undefined; expect(env?.ANTHROPIC_BASE_URL).toBeUndefined(); // Unrelated env vars are not over-deleted expect(env?.EXTRA).toBe('keep'); // No ensure-proxy hook entries survive on any event const hooksBlock = s.hooks ?? {}; for (const eventMatchers of Object.values(hooksBlock)) { for (const matcher of eventMatchers ?? []) { for (const h of matcher.hooks ?? []) { expect(h.command).not.toContain('ensure-proxy'); } } } }); it('env block removed entirely when relay URL was the only env key', () => { const s = buildFullyEnabledSettings(); // no extras applyDisableToSettings(s, DEFAULT_PORT); // Whole post-state: env gone entirely, no hooks expect(hasProxyHooks(s)).toBe(false); expect((s as Record).env).toBeUndefined(); }); it('unconditional both-operations invariant: all three settings states produce a clean post-state', () => { // applyDisableToSettings MUST call removeProxyHooks AND _stripProxyEnvFromObject // unconditionally — regardless of each other's return value. // // The guarded bug: "removeProxyHooks(s) || _stripProxyEnvFromObject(s, port)" short-circuits // when hooks are present (removeProxyHooks returns true), leaving ANTHROPIC_BASE_URL set. // // Three scenarios that differ in REAL settings state (not in a label string). // The "both-hooks-and-URL" case is the critical one: it goes RED when || is used // because removeProxyHooks(s) returns true → _stripProxyEnvFromObject never runs → // ANTHROPIC_BASE_URL survives → expect(env?.ANTHROPIC_BASE_URL).toBeUndefined() fails. const scenarios = [ { name: 'only-URL (no hooks)', build: (): Settings => { const s: Settings = {}; (s as Record).env = { ANTHROPIC_BASE_URL: OUR_URL }; return s; }, }, { name: 'only-hooks (no URL)', build: (): Settings => { const s: Settings = {}; addProxyHooks(s, DEVFLOW_DIR); return s; }, }, { name: 'both-hooks-and-URL (critical: proves unconditional evaluation)', build: (): Settings => { const s: Settings = {}; addProxyHooks(s, DEVFLOW_DIR); (s as Record).env = { ANTHROPIC_BASE_URL: OUR_URL }; return s; }, }, ] as const; for (const { name, build } of scenarios) { const s = build(); const changed = applyDisableToSettings(s, DEFAULT_PORT); const env = (s as Record).env as Record | undefined; expect(changed, `[${name}] changed`).toBe(true); expect(hasProxyHooks(s), `[${name}] no proxy hooks`).toBe(false); expect(env?.ANTHROPIC_BASE_URL, `[${name}] relay URL removed`).toBeUndefined(); } }); // ── Agent reversion: revertExternalAgents — 3 real cache states produce identical result ── // // When proxy --disable runs, revertExternalAgents is called to rewrite installed agent // files back to their shipped Claude defaults. This must happen regardless of the prior // model-discovery cache state (cache-hit, cache-miss, no cache dir). Proves that // reversion is independent of discovery. let tmpInstallDir: string; let tmpDevflowDir: string; beforeEach(async () => { tmpInstallDir = await fsAsync.mkdtemp(path.join(os.tmpdir(), 'devflow-t7-agents-')); tmpDevflowDir = await fsAsync.mkdtemp(path.join(os.tmpdir(), 'devflow-t7-state-')); }); afterEach(async () => { await fsAsync.rm(tmpInstallDir, { recursive: true, force: true }); await fsAsync.rm(tmpDevflowDir, { recursive: true, force: true }); }); const cacheStateScenarios: Array<{ name: string; setupCache: (cacheDir: string) => Promise; }> = [ { name: 'cache-hit', setupCache: async (cacheDir) => { await fsAsync.mkdir(cacheDir, { recursive: true }); const stub = JSON.stringify({ schemaVersion: 1, kind: 'models', providers: [{ id: 'codex', routing: 'direct' }], models: [{ id: 'gpt-5.6-sol', provider: 'codex', routable: true, retired: false, aliases: [] }], }); await writeCache(cacheDir, 'external-models-v1-0.2.0', stub, 24 * 60 * 60 * 1_000); }, }, { name: 'cache-miss', setupCache: async (cacheDir) => { await fsAsync.mkdir(cacheDir, { recursive: true }); // dir exists, empty }, }, { name: 'no-cache-dir', setupCache: async (_cacheDir) => { // don't create the cache dir — mimics relay never started }, }, ]; for (const scenario of cacheStateScenarios) { it(`revertExternalAgents reverts GPT models to shipped defaults [${scenario.name}]`, async () => { const cacheDir = path.join(tmpDevflowDir, 'cache', 'models'); await scenario.setupCache(cacheDir); // Installed file has GPT model already applied (as if proxy was enabled before) await fsAsync.writeFile( path.join(tmpInstallDir, 'code.md'), '---\nname: Code\nmodel: gpt-5.6-sol\n---\n\nbody\n', 'utf-8', ); const mapping: AgentMappingFile = { version: 1, agents: { code: { model: 'gpt-5.6-sol' } } }; await saveAgentMapping(tmpDevflowDir, mapping); await revertExternalAgents({ installDir: tmpInstallDir, devflowDir: tmpDevflowDir }); const content = await fsAsync.readFile(path.join(tmpInstallDir, 'code.md'), 'utf-8'); // GPT model must be gone, replaced with a Claude model (the shipped default) expect(content, `[${scenario.name}] no GPT model in reverted file`).not.toContain('gpt-'); // The file must still have a valid model: line expect(content, `[${scenario.name}] model line exists`).toMatch(/model:\s*\w+/); }); } }); // ─── AC-F6: formatExternalModelsLine ───────────────────────────────────────── // // Pure formatter for the external models status line shown by --status. // Extracted so it can be tested without clack I/O (AC-F6). describe('formatExternalModelsLine (AC-F6)', () => { const LOG_PATH = '/home/user/.devflow/logs/proxy.log'; const codexOnly: ReadonlySet = new Set(['codex']); it('unknown catalog → "unavailable" and log path', () => { const result = formatExternalModelsLine({ known: false }, LOG_PATH, codexOnly); // Strip ANSI — content assertion only const stripped = result.replace(/\x1b\[[0-9;]*m/g, ''); expect(stripped).toContain('unavailable'); expect(stripped).toContain(LOG_PATH); }); const mixedCatalog: ExternalModelCatalog = { known: true, cursorPool: ['composer-2.5'], source: 'cache', models: [ { id: 'gpt-5.6', provider: 'codex', aliases: ['sol', 'terra'] }, { id: 'kimi-k2', provider: 'kimi', aliases: ['kimi'] }, { id: 'gemini-3', provider: 'gemini', aliases: ['gemini'] }, { id: 'gpt-5.5', provider: 'codex', aliases: [] }, ], selectableNames: ['sol', 'terra', 'kimi', 'gemini', 'gpt-5.6', 'kimi-k2', 'gemini-3', 'gpt-5.5'], aliasToId: new Map([ ['sol', 'gpt-5.6'], ['terra', 'gpt-5.6'], ['kimi', 'kimi-k2'], ['gemini', 'gemini-3'], ['gpt-5.6', 'gpt-5.6'], ['kimi-k2', 'kimi-k2'], ['gemini-3', 'gemini-3'], ['gpt-5.5', 'gpt-5.5'], ]), }; it('keeps the default Codex-only line byte-identical with a mixed catalog', () => { expect(formatExternalModelsLine(mixedCatalog, LOG_PATH, codexOnly)) .toBe(`External models: ${color.cyan('sol, terra, gpt-5.6, gpt-5.5')}`); }); it('lists Gemini names and qualified Cursor pool ids without names from Kimi when it is off', () => { const enabled = new Set(['codex', 'gemini', 'cursor']); expect(formatExternalModelsLine(mixedCatalog, LOG_PATH, enabled)) .toBe(`External models: ${color.cyan('sol, terra, gemini, gpt-5.6, gemini-3, gpt-5.5, cursor:composer-2.5')}`); }); it('lists Kimi names but no Gemini or Cursor names when those providers are off', () => { const enabled = new Set(['codex', 'kimi']); expect(formatExternalModelsLine(mixedCatalog, LOG_PATH, enabled)) .toBe(`External models: ${color.cyan('sol, terra, kimi, gpt-5.6, kimi-k2, gpt-5.5')}`); }); it('adds no Cursor names when its block is on but the pool is unknown', () => { const enabled = new Set(['codex', 'cursor']); expect(formatExternalModelsLine({ ...mixedCatalog, cursorPool: null }, LOG_PATH, enabled)) .toBe(`External models: ${color.cyan('sol, terra, gpt-5.6, gpt-5.5')}`); }); it('known catalog with empty model list → no names shown, no log path', () => { const catalog = { known: true as const, cursorPool: null, source: 'live' as const, models: [], selectableNames: [] as string[], aliasToId: new Map(), }; const result = formatExternalModelsLine(catalog, LOG_PATH, codexOnly); const stripped = result.replace(/\x1b\[[0-9;]*m/g, ''); expect(stripped).toContain('External models:'); expect(stripped).not.toContain('unavailable'); expect(stripped).not.toContain(LOG_PATH); }); // ─── formatCodexAuthLine ─────────────────────────────────────────────────── // // Pure formatter for the Codex auth status line. Expiry must read as // information; only `unreadable` may read as a problem the user must fix. describe('formatCodexAuthLine', () => { const AUTH_PATH = '/home/user/.codex/auth.json'; const NOW = new Date('2026-08-14T00:00:00Z'); const strip = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, ''); it('absent → actionable codex login hint', () => { const { msg } = formatCodexAuthLine({ kind: 'absent' }, AUTH_PATH, NOW); const out = strip(msg); expect(out).toContain('absent'); expect(out).toContain('codex login'); }); it('unreadable → surfaces the reason, the path, and the remedy', () => { const { msg } = formatCodexAuthLine({ kind: 'unreadable', reason: 'not valid JSON' }, AUTH_PATH, NOW); const out = strip(msg); expect(out).toContain('unreadable'); expect(out).toContain('not valid JSON'); expect(out).toContain(AUTH_PATH); expect(out).toContain('codex login'); }); it('present + future expiry → validity stated, no remedy suggested', () => { const { msg } = formatCodexAuthLine( { kind: 'present', authMode: 'chatgpt', accountSuffix: '…d8e65c', expiresAt: new Date('2026-08-17T18:24:42Z'), }, AUTH_PATH, NOW, ); const out = strip(msg); expect(out).toContain('present'); expect(out).toContain('chatgpt, …d8e65c'); expect(out).toContain('valid through 2026-08-17'); expect(out).not.toContain('codex login'); }); it('present + past expiry → informational, never told to re-login', () => { const { msg } = formatCodexAuthLine( { kind: 'present', authMode: 'chatgpt', accountSuffix: '…d8e65c', expiresAt: new Date('2026-08-01T00:00:00Z'), }, AUTH_PATH, NOW, ); const out = strip(msg); expect(out).toContain('expired 2026-08-01'); expect(out).toContain('refreshes on next request'); expect(out).not.toContain('codex login'); }); it('present without decodable expiry → no expiry claim either way', () => { const { msg } = formatCodexAuthLine( { kind: 'present', authMode: 'chatgpt', accountSuffix: '…d8e65c', expiresAt: undefined }, AUTH_PATH, NOW, ); const out = strip(msg); expect(out).toContain('present'); expect(out).not.toContain('valid through'); expect(out).not.toContain('expired'); }); it('expiry exactly at now counts as expired (boundary)', () => { const { msg } = formatCodexAuthLine( { kind: 'present', authMode: 'chatgpt', accountSuffix: '…d8e65c', expiresAt: NOW }, AUTH_PATH, NOW, ); const out = strip(msg); expect(out).toContain('expired'); expect(out).not.toContain('valid through'); }); // C2-CONS-10: formatCodexAuthLine returns {level, msg} — level encodes the // "unreadable warns" rule so callers don't re-derive it from state.kind. it('C2-CONS-10: unreadable → level=warn (caller must not re-derive)', () => { const result = formatCodexAuthLine({ kind: 'unreadable', reason: 'bad JSON' }, AUTH_PATH, NOW); expect(result.level).toBe('warn'); }); it('C2-CONS-10: absent → level=info', () => { const result = formatCodexAuthLine({ kind: 'absent' }, AUTH_PATH, NOW); expect(result.level).toBe('info'); }); it('C2-CONS-10: present → level=info', () => { const result = formatCodexAuthLine( { kind: 'present', authMode: 'chatgpt', accountSuffix: '…d8e65c', expiresAt: undefined }, AUTH_PATH, NOW, ); expect(result.level).toBe('info'); }); // C2-SEC-3: authMode comes from a third-party file (~/.codex/auth.json) and was // printed verbatim. An OSC-8 hyperlink or other escape sequence in the field // would render directly in the user's terminal. it('C2-SEC-3: OSC-8 hyperlink in authMode is stripped from the rendered msg', () => { // OSC-8 hyperlink: \x1b]8;;\x07\x1b]8;;\x07 const osc8Mode = '\x1b]8;;https://evil.com\x07chatgpt\x1b]8;;\x07'; const { msg } = formatCodexAuthLine( { kind: 'present', authMode: osc8Mode, accountSuffix: '…d8e65c', expiresAt: undefined }, AUTH_PATH, NOW, ); // The raw rendered msg must not contain the OSC-8 opener expect(msg).not.toContain('\x1b]8;'); // The visible text (chatgpt) must still appear after stripping const visibleMsg = msg.replace(/\x1b(?:\[[0-9;?]*[ -\/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g, ''); expect(visibleMsg).toContain('chatgpt'); }); it('C2-SEC-3: SGR escape sequence in authMode is stripped from the rendered msg', () => { const ansiMode = '\x1b[31mapikey\x1b[0m'; // red "apikey" const { msg } = formatCodexAuthLine( { kind: 'present', authMode: ansiMode, accountSuffix: '…d8e65c', expiresAt: undefined }, AUTH_PATH, NOW, ); // Raw msg must not contain the injected SGR sequence expect(msg).not.toContain('\x1b[31m'); }); it('C2-SEC-3: authMode is capped to prevent unbounded terminal output', () => { const longMode = 'x'.repeat(500); const { msg } = formatCodexAuthLine( { kind: 'present', authMode: longMode, accountSuffix: '…d8e65c', expiresAt: undefined }, AUTH_PATH, NOW, ); // The rendered msg should not carry 500 'x' characters — it must be capped // 400 is a generous upper bound that still proves the cap fires for 500-char input expect(msg.length).toBeLessThan(400); }); }); it('does not mention "subswitch" (branding rule)', () => { const result = formatExternalModelsLine({ known: false }, LOG_PATH, codexOnly); expect(result.toLowerCase()).not.toContain('subswitch'); }); }); // ─── C2-REL-1: realHttpGet reliability ──────────────────────────────────────── // // realHttpGet is the production HTTP implementation used by resolveProcessState // (health check in --status) and runDisable (identity cross-check, SEC-3). // The disable path fires precisely when the port is NOT confirmed as our relay, // so any local service that trickles bytes can pin --disable forever with growing // memory. Three bounded-resource invariants must hold: // 1. Wall-clock total deadline — `end` never fires on SSE / trickle endpoints // 2. 64KB body cap — rejects oversized responses before accumulating them // 3. res.on('error') listener — response stream errors must not become unhandled // // These tests run real local HTTP servers — no mocking of the function under test. describe('realHttpGet (C2-REL-1 reliability)', () => { it('slow-trickle server: wall-clock deadline fires, returns Err (RED: hangs without it)', async () => { // Server sends one byte every 30ms but never closes the response — simulates // an SSE endpoint or a log tailer that keeps a connection alive indefinitely. const server = http.createServer((_req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); const iv = setInterval(() => { res.write('x'); }, 30); res.on('close', () => clearInterval(iv)); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); const addr = server.address() as net.AddressInfo; const url = `http://127.0.0.1:${addr.port}/`; try { const result = await realHttpGet(url, 200); // 200ms wall-clock deadline expect(result.ok).toBe(false); // must not succeed — 'end' never fires if (!result.ok) { expect(result.error).toMatch(/deadline|timeout/); } } finally { await new Promise((resolve) => server.close(() => resolve())); } }, 3000 /* test timeout: 3s, must complete well before this */); it('oversized body (>64KB): returns Err before buffering full response (RED: returns Ok without cap)', async () => { const BIG = Buffer.alloc(70 * 1024, 0x41); // 70KB of 'A' const server = http.createServer((_req, res) => { res.writeHead(200, { 'Content-Type': 'application/octet-stream' }); res.end(BIG); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); const addr = server.address() as net.AddressInfo; const url = `http://127.0.0.1:${addr.port}/`; try { const result = await realHttpGet(url, 5000); expect(result.ok).toBe(false); // must be rejected before buffering 70KB if (!result.ok) { expect(result.error).toMatch(/too large|body/i); } } finally { await new Promise((resolve) => server.close(() => resolve())); } }); it('normal response: returns Ok with body under cap', async () => { const server = http.createServer((_req, res) => { res.writeHead(200); res.end('{"name":"subswitch"}'); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); const addr = server.address() as net.AddressInfo; const url = `http://127.0.0.1:${addr.port}/`; try { const result = await realHttpGet(url, 2000); expect(result.ok).toBe(true); if (result.ok) { expect(result.value).toContain('subswitch'); } } finally { await new Promise((resolve) => server.close(() => resolve())); } }); it('connection error: returns Err (no unhandled rejection)', async () => { // Port 1 is privileged and will refuse the connection immediately const result = await realHttpGet('http://127.0.0.1:1/', 2000); expect(result.ok).toBe(false); }); }); // ─── terminateRelay ────────────────────────────────────────────────────────── // // Tests for the relay-termination helper used by `devflow proxy --disable`. // Strategy: real temp dirs and processes; no mocking of network or signals. describe('terminateRelay — not-running cases', () => { let tmpDir: string; beforeEach(async () => { tmpDir = await fsAsync.mkdtemp(path.join(os.tmpdir(), 'devflow-terminate-relay-test-')); }); afterEach(async () => { await fsAsync.rm(tmpDir, { recursive: true, force: true }); }); it('returns not-running when pid file is absent', async () => { const pidPath = path.join(tmpDir, 'proxy.pid'); const lockPath = path.join(tmpDir, '.proxy-spawn.lock'); const result = await terminateRelay(pidPath, lockPath, 65000); expect(result).toBe('not-running'); }); it('returns not-running when pid file contains an implausibly large PID', async () => { const pidPath = path.join(tmpDir, 'proxy.pid'); const lockPath = path.join(tmpDir, '.proxy-spawn.lock'); // PID 999999999 will not be alive on any real system await fsAsync.writeFile(pidPath, '999999999', 'utf-8'); const result = await terminateRelay(pidPath, lockPath, 65000); expect(result).toBe('not-running'); }); it('removes the pid file when the recorded process is already dead', async () => { const pidPath = path.join(tmpDir, 'proxy.pid'); const lockPath = path.join(tmpDir, '.proxy-spawn.lock'); await fsAsync.writeFile(pidPath, '999999999', 'utf-8'); await terminateRelay(pidPath, lockPath, 65000); // Pid file should be cleaned up await expect(fsAsync.access(pidPath)).rejects.toThrow(); }); }); describe('terminateRelay — identity-unconfirmed case', () => { let tmpDir: string; beforeEach(async () => { tmpDir = await fsAsync.mkdtemp(path.join(os.tmpdir(), 'devflow-terminate-relay-id-test-')); }); afterEach(async () => { await fsAsync.rm(tmpDir, { recursive: true, force: true }); }); it('returns identity-unconfirmed when process is alive but port is not our relay', async () => { // Write our own PID — current process is definitely alive. // Use port 1 (privileged, always refused) to ensure TCP probe fails → identity unconfirmed. const pidPath = path.join(tmpDir, 'proxy.pid'); const lockPath = path.join(tmpDir, '.proxy-spawn.lock'); await fsAsync.writeFile(pidPath, String(process.pid), 'utf-8'); const result = await terminateRelay(pidPath, lockPath, 1); expect(result).toBe('identity-unconfirmed'); // Pid file must NOT be removed — we did not kill it await expect(fsAsync.access(pidPath)).resolves.toBeUndefined(); }); }); // ─── terminateRelay — PID-port identity gate (D-EFR-5) ─────────────────────── // // These tests directly exercise the new lsof-based PID-port binding gate added // by D-EFR-5. They use injected TerminateRelayDeps to avoid requiring a real // lsof binary and to precisely control what the binding check returns. describe('terminateRelay — PID-port identity gate (D-EFR-5)', () => { let tmpDir: string; beforeEach(async () => { tmpDir = await fsAsync.mkdtemp(path.join(os.tmpdir(), 'devflow-terminate-relay-id-gate-')); }); afterEach(async () => { await fsAsync.rm(tmpDir, { recursive: true, force: true }); }); it('returns identity-unconfirmed and does NOT signal when lsof returns a different PID', async () => { // Spin up an HTTP server that passes the health check. const server = http.createServer((_req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ name: 'subswitch', status: 'ok', running: true })); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); const addr = server.address() as net.AddressInfo; const port = addr.port; // Spawn a separate child process — this is the PID we put in the pid file. // Its PID is different from what lsof would return (the HTTP server's process PID). const child = cpSpawn(process.execPath, ['-e', 'setInterval(()=>{},1000)'], { detached: false, stdio: 'ignore', }); await new Promise((resolve) => child.on('spawn', resolve)); const childPid = child.pid!; const pidPath = path.join(tmpDir, 'proxy.pid'); const lockPath = path.join(tmpDir, '.proxy-spawn.lock'); await fsAsync.writeFile(pidPath, String(childPid), 'utf-8'); // Inject a deps that returns a different PID than childPid — simulating the // lsof result that would be returned by the HTTP server's process. const differentPid = childPid + 1; const deps: TerminateRelayDeps = { resolveListeningPid: async () => differentPid, }; const result = await terminateRelay(pidPath, lockPath, port, deps); expect(result).toBe('identity-unconfirmed'); // The child must NOT have been signalled — this is the critical safety assertion. expect(() => process.kill(childPid, 0)).not.toThrow(); // Clean up child.kill(); await new Promise((resolve) => server.close(() => resolve())); }, 10_000); it('returns identity-unconfirmed and does NOT signal when lsof is unavailable (null)', async () => { // Health server is up, but lsof returns null (e.g. absent binary or EPERM). const server = http.createServer((_req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ name: 'subswitch', status: 'ok', running: true })); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); const addr = server.address() as net.AddressInfo; const port = addr.port; const child = cpSpawn(process.execPath, ['-e', 'setInterval(()=>{},1000)'], { detached: false, stdio: 'ignore', }); await new Promise((resolve) => child.on('spawn', resolve)); const childPid = child.pid!; const pidPath = path.join(tmpDir, 'proxy.pid'); const lockPath = path.join(tmpDir, '.proxy-spawn.lock'); await fsAsync.writeFile(pidPath, String(childPid), 'utf-8'); // lsof returns null — simulates absent binary or restricted execution. const deps: TerminateRelayDeps = { resolveListeningPid: async () => null, }; const result = await terminateRelay(pidPath, lockPath, port, deps); expect(result).toBe('identity-unconfirmed'); // Child must NOT have been signalled. expect(() => process.kill(childPid, 0)).not.toThrow(); // Clean up child.kill(); await new Promise((resolve) => server.close(() => resolve())); }, 10_000); }); describe('terminateRelay — kill path (integration)', () => { let tmpDir: string; beforeEach(async () => { tmpDir = await fsAsync.mkdtemp(path.join(os.tmpdir(), 'devflow-terminate-relay-kill-test-')); }); afterEach(async () => { await fsAsync.rm(tmpDir, { recursive: true, force: true }); }); it('kills the relay process and removes pid file when identity is confirmed', async () => { // Spin up a child process that serves the relay health endpoint on its own port. // This ensures child PID === lsof-returned listening PID (both are the same process). const childScript = [ "const http = require('http');", 'const server = http.createServer((_req, res) => {', " res.writeHead(200, { 'Content-Type': 'application/json' });", " res.end(JSON.stringify({ name: 'subswitch', status: 'ok', running: true }));", '});', "server.listen(0, '127.0.0.1', () => {", ' process.stdout.write(JSON.stringify({ port: server.address().port }) + "\\n");', '});', 'setInterval(() => {}, 1000);', ].join('\n'); const child = cpSpawn(process.execPath, ['-e', childScript], { detached: false, stdio: ['ignore', 'pipe', 'ignore'], }); await new Promise((resolve) => child.on('spawn', resolve)); const childPid = child.pid!; // Read the port from the child's stdout const port = await new Promise((resolve, reject) => { let buf = ''; child.stdout!.on('data', (chunk: Buffer) => { buf += chunk.toString(); const nl = buf.indexOf('\n'); if (nl !== -1) { try { const parsed = JSON.parse(buf.slice(0, nl)) as { port: number }; resolve(parsed.port); } catch (e) { reject(e); } } }); child.on('error', reject); }); // Confirm the child is alive before we call terminateRelay expect(() => process.kill(childPid, 0)).not.toThrow(); const pidPath = path.join(tmpDir, 'proxy.pid'); const lockPath = path.join(tmpDir, '.proxy-spawn.lock'); await fsAsync.writeFile(pidPath, String(childPid), 'utf-8'); // Inject a deps that returns the child's own PID — the child owns the port. const deps: TerminateRelayDeps = { resolveListeningPid: async () => childPid, }; const result = await terminateRelay(pidPath, lockPath, port, deps); expect(result).toBe('killed'); // Process must be gone expect(() => process.kill(childPid, 0)).toThrow(); // Pid file must be removed await expect(fsAsync.access(pidPath)).rejects.toThrow(); }, 15_000 /* 15s: SIGTERM+SIGKILL poll at most ~4s, plus child startup */); it('cleans up a stale spawn lock directory when the relay is killed', async () => { const childScript = [ "const http = require('http');", 'const server = http.createServer((_req, res) => {', " res.writeHead(200, { 'Content-Type': 'application/json' });", " res.end(JSON.stringify({ name: 'subswitch', status: 'ok', running: true }));", '});', "server.listen(0, '127.0.0.1', () => {", ' process.stdout.write(JSON.stringify({ port: server.address().port }) + "\\n");', '});', 'setInterval(() => {}, 1000);', ].join('\n'); const child = cpSpawn(process.execPath, ['-e', childScript], { detached: false, stdio: ['ignore', 'pipe', 'ignore'], }); await new Promise((resolve) => child.on('spawn', resolve)); const childPid = child.pid!; const port = await new Promise((resolve, reject) => { let buf = ''; child.stdout!.on('data', (chunk: Buffer) => { buf += chunk.toString(); const nl = buf.indexOf('\n'); if (nl !== -1) { try { const parsed = JSON.parse(buf.slice(0, nl)) as { port: number }; resolve(parsed.port); } catch (e) { reject(e); } } }); child.on('error', reject); }); const pidPath = path.join(tmpDir, 'proxy.pid'); const lockPath = path.join(tmpDir, '.proxy-spawn.lock'); await fsAsync.mkdir(lockPath); // simulate a stale lock await fsAsync.writeFile(pidPath, String(childPid), 'utf-8'); const deps: TerminateRelayDeps = { resolveListeningPid: async () => childPid, }; const result = await terminateRelay(pidPath, lockPath, port, deps); expect(result).toBe('killed'); // Lock directory cleaned up await expect(fsAsync.access(lockPath)).rejects.toThrow(); }, 15_000); }); // ─── Phase 4: CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT ──────────── // // Proxy models trigger surprise context-window compaction because Claude Code // does not recognise them as Claude models and enforces a conservative limit. // The fix: pair ANTHROPIC_BASE_URL with CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT // so the enforcement is lifted for the relay session. // // Strip gate: ANTHROPIC_BASE_URL ownership (port match) gates the URL delete only. // UNKNOWN_MODEL_WINDOW_ENV is always removed — Devflow is its only producer so there // is no foreign value to protect. const WINDOW_ENV = 'CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT'; describe('Phase 4 / applyProxyEnv: sets UNKNOWN_MODEL_WINDOW_ENV', () => { it('sets CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT to "1"', () => { const result = JSON.parse(applyProxyEnv(JSON.stringify({}), DEFAULT_PORT)); expect((result.env as Record)[WINDOW_ENV]).toBe('1'); }); it('idempotent re-apply: window var stays "1" on second call', () => { const once = applyProxyEnv(JSON.stringify({}), DEFAULT_PORT); const twice = applyProxyEnv(once, DEFAULT_PORT); expect(JSON.parse(twice).env[WINDOW_ENV]).toBe('1'); }); it('preserves unrelated env keys alongside both relay vars', () => { const input = JSON.stringify({ env: { MY_VAR: 'keep' } }); const result = JSON.parse(applyProxyEnv(input, DEFAULT_PORT)); const env = result.env as Record; expect(env.ANTHROPIC_BASE_URL).toBe(OUR_URL); expect(env[WINDOW_ENV]).toBe('1'); expect(env.MY_VAR).toBe('keep'); }); it('port-change re-apply: ANTHROPIC_BASE_URL updates; window var stays "1"', () => { const afterFirst = applyProxyEnv(JSON.stringify({}), 4141); const afterSecond = applyProxyEnv(afterFirst, 5000); const env = JSON.parse(afterSecond).env as Record; expect(env.ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:5000'); expect(env[WINDOW_ENV]).toBe('1'); }); }); describe('Phase 4 / stripProxyEnv: ownership-gated strip of both relay vars', () => { it('ownership match: removes BOTH ANTHROPIC_BASE_URL and the window var', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: OUR_URL, [WINDOW_ENV]: '1' } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); // Both proxy vars removed; env cleaned up entirely expect(result.env).toBeUndefined(); }); it('ownership match with extra env: removes both vars, preserves unrelated', () => { const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: OUR_URL, [WINDOW_ENV]: '1', EXTRA: 'keep' }, }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); const env = result.env as Record; expect(env.ANTHROPIC_BASE_URL).toBeUndefined(); expect(env[WINDOW_ENV]).toBeUndefined(); expect(env.EXTRA).toBe('keep'); }); it('foreign URL: ANTHROPIC_BASE_URL NOT removed; window var IS always removed', () => { // URL gate protects a foreign url value — but the window var has no foreign value; // Devflow is its only producer so it is always removed. const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://foreign.example.com', [WINDOW_ENV]: '1' }, }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); const env = result.env as Record; expect(env.ANTHROPIC_BASE_URL).toBe('https://foreign.example.com'); expect(env[WINDOW_ENV]).toBeUndefined(); }); it('absent URL with orphan window var: window var IS removed (Devflow is its only producer)', () => { // No ANTHROPIC_BASE_URL → URL gate does not fire, but the window var is always ours to remove. // The env block is cleaned up entirely when the window var was the only key. const input = JSON.stringify({ env: { [WINDOW_ENV]: '1' } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); expect(result.env).toBeUndefined(); }); it('ours-other-port URL with window var: URL NOT removed (different managed port), window var IS removed', () => { const otherPortUrl = 'http://127.0.0.1:5000'; // not managed by DEFAULT_PORT (4141) const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: otherPortUrl, [WINDOW_ENV]: '1' } }); const result = JSON.parse(stripProxyEnv(input, DEFAULT_PORT)); const env = result.env as Record; expect(env.ANTHROPIC_BASE_URL).toBe(otherPortUrl); // URL preserved — not our port expect(env[WINDOW_ENV]).toBeUndefined(); // always removed — Devflow is the only producer }); // SEC-M2 regression: port-drift orphan — UNKNOWN_MODEL_WINDOW_ENV must not survive a // strip attempt when ANTHROPIC_BASE_URL is present but on a different managed port. // Reachable via: port drift between enable/disable, hand-edited URL, or uninstall's // DEFAULT_PROXY_PORT fallback. Both behaviors must be asserted together from a // fully-enabled starting state. it('SEC-M2: port-mismatch strip — window var removed, mismatched ANTHROPIC_BASE_URL untouched', () => { const enabledPort = DEFAULT_PORT; // 4141 — the port that was active at enable time const disablePort = 9999; // different port — simulates port drift between enable and disable const input = JSON.stringify({ env: { ANTHROPIC_BASE_URL: `http://127.0.0.1:${enabledPort}`, [WINDOW_ENV]: '1', }, }); const result = JSON.parse(stripProxyEnv(input, disablePort)); const env = result.env as Record; // (a) window var MUST be gone — Devflow is its only producer; no foreign value to protect expect(env[WINDOW_ENV]).toBeUndefined(); // (b) ANTHROPIC_BASE_URL MUST be untouched — port mismatch means it is not ours to remove expect(env.ANTHROPIC_BASE_URL).toBe(`http://127.0.0.1:${enabledPort}`); }); }); describe('Phase 4 / T7-extended: fully-enabled state includes UNKNOWN_MODEL_WINDOW_ENV', () => { /** Fully-enabled settings: hooks + ANTHROPIC_BASE_URL + window-enforcement var. */ function buildFullyEnabledSettingsP4(extraEnv?: Record): Settings { const s: Settings = {}; addProxyHooks(s, DEVFLOW_DIR); (s as Record).env = { ANTHROPIC_BASE_URL: OUR_URL, [WINDOW_ENV]: '1', ...extraEnv, }; return s; } it('whole-end-state: applyDisableToSettings removes hooks, relay URL, AND window var', () => { const s = buildFullyEnabledSettingsP4({ EXTRA: 'keep' }); const changed = applyDisableToSettings(s, DEFAULT_PORT); expect(changed).toBe(true); expect(hasProxyHooks(s)).toBe(false); const env = (s as Record).env as Record | undefined; expect(env?.ANTHROPIC_BASE_URL).toBeUndefined(); expect(env?.[WINDOW_ENV]).toBeUndefined(); // Unrelated env vars survive expect(env?.EXTRA).toBe('keep'); }); it('env block removed entirely when both relay vars are the only env keys', () => { const s = buildFullyEnabledSettingsP4(); // no extras applyDisableToSettings(s, DEFAULT_PORT); expect(hasProxyHooks(s)).toBe(false); expect((s as Record).env).toBeUndefined(); }); it('applyProxyEnv produces a fully-enabled env containing both relay vars', () => { const result = JSON.parse(applyProxyEnv(JSON.stringify({}), DEFAULT_PORT)); const env = result.env as Record; expect(env.ANTHROPIC_BASE_URL).toBe(OUR_URL); expect(env[WINDOW_ENV]).toBe('1'); }); }); // ─── FIX 3 (issue #313): runProxyPreflight — D-EFR-5 ordering ─────────────── // // Foreign-env check (check ④) must evaluate BEFORE the adopted early-return // (check ③). Previously, a healthy relay on the port caused an early-return that // silently skipped the foreign-gateway refusal entirely. // // Regression tests: // REG-EFR-1: foreign URL + healthy relay → Err (refusal), not adopted // REG-EFR-2: no foreign URL + healthy relay → Ok(adopted:true) (normal adopt) // REG-EFR-3: foreign URL + port free → Err (check ④ on the free-port path, unchanged) describe('runProxyPreflight — FIX 3 D-EFR-5 foreign-env check ordering (issue #313)', () => { const port = DEFAULT_PORT; const codexAuthPath = '/home/test/.codex/auth.json'; const configPath = '/home/test/.devflow/proxy-routing.json'; const logPath = '/home/test/.devflow/logs/proxy.log'; const ourHealthBody = '{"name":"subswitch","version":"0.2.0","providers":[{"id":"anthropic","configured":true,"modelCount":0}]}'; // REG-EFR-1: healthy relay + foreign URL → must be refused (not adopted silently) it('REG-EFR-1: returns Err when relay is healthy but ANTHROPIC_BASE_URL is a foreign gateway', async () => { const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), // port up httpGet: vi.fn().mockResolvedValue({ ok: true, value: ourHealthBody }), // our relay readSettingsJson: vi.fn().mockResolvedValue(JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://litellm.mycompany.internal' }, // foreign URL })), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); // Must be refused — not adopted silently expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toContain('ANTHROPIC_BASE_URL'); } }); // REG-EFR-2: healthy relay + no foreign URL → normal adopt it('REG-EFR-2: returns Ok(adopted:true) when relay is healthy and no foreign URL', async () => { const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), httpGet: vi.fn().mockResolvedValue({ ok: true, value: ourHealthBody }), readSettingsJson: vi.fn().mockResolvedValue('{}'), // no foreign URL }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(true); if (result.ok) { expect(result.value.adopted).toBe(true); } }); // REG-EFR-3: port free + foreign URL → check ④ on the free-port path (already tested above, // reconfirmed here to show both paths refuse a foreign URL) it('REG-EFR-3: returns Err when port is free but ANTHROPIC_BASE_URL is a foreign gateway', async () => { const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(false), // port free readSettingsJson: vi.fn().mockResolvedValue(JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://litellm.mycompany.internal' }, })), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error).toContain('ANTHROPIC_BASE_URL'); } }); // REG-EFR-1b: healthy relay + our own relay URL on the port → adopted (not foreign) it('REG-EFR-1b: adopted when relay is healthy and ANTHROPIC_BASE_URL is already our relay URL', async () => { const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), httpGet: vi.fn().mockResolvedValue({ ok: true, value: ourHealthBody }), readSettingsJson: vi.fn().mockResolvedValue(JSON.stringify({ env: { ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}` }, // our URL → not foreign })), }); const result = await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(result.ok).toBe(true); if (result.ok) { expect(result.value.adopted).toBe(true); } }); // Verify that readSettingsJson is called in the adopt path (D-EFR-5 gate is wired) it('calls readSettingsJson in the adopted path to evaluate foreign-env state', async () => { const readSettingsJson = vi.fn().mockResolvedValue('{}'); const deps = makeDeps({ tcpConnectable: vi.fn().mockResolvedValue(true), httpGet: vi.fn().mockResolvedValue({ ok: true, value: ourHealthBody }), readSettingsJson, }); await runProxyPreflight(port, codexAuthPath, configPath, logPath, deps); expect(readSettingsJson).toHaveBeenCalledTimes(1); }); }); // ─── FIX 2 (issue #313): applyProxyTeardownToSettings — D-STRIP-1 gate ──────── // // Every proxy-off path (devflow proxy --disable, devflow uninstall) routes its // settings teardown through this one function so the two removals cannot drift: // - hooks → always removed (they are Devflow's own artifacts) // - ANTHROPIC_BASE_URL + window var → removed only when the caller supplies a // managedPort, which it may do only when proxy.json exists (the sole evidence // that Devflow ever wrote them). // // Falsification: gating the whole call on the evidence (the shape this replaced) // leaves Devflow's hooks in settings.json after uninstall — REG-TEARDOWN-1 fails. describe('applyProxyTeardownToSettings — FIX 2 D-STRIP-1 (issue #313)', () => { const DEVFLOW_DIR = '/home/test/.devflow'; /** Settings in the fully-enabled shape: proxy hooks + both env vars. */ function enabledSettings(port: number): Settings { const s = { env: { ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`, [WINDOW_ENV]: '1', MY_VAR: 'keep', }, } as unknown as Settings; addProxyHooks(s, DEVFLOW_DIR); return s; } // REG-TEARDOWN-1: hooks go regardless of evidence — an uninstall that leaves them // behind points every later session at a hook script that no longer exists. it('REG-TEARDOWN-1: removes proxy hooks even with no managed port (unmanaged)', () => { const settings = enabledSettings(DEFAULT_PORT); expect(hasProxyHooks(settings)).toBe(true); const changed = applyProxyTeardownToSettings(settings, undefined); expect(changed).toBe(true); expect(hasProxyHooks(settings)).toBe(false); }); it('leaves both env vars untouched when no managed port is supplied', () => { const settings = enabledSettings(DEFAULT_PORT); applyProxyTeardownToSettings(settings, undefined); const env = (settings as unknown as { env: Record }).env; // Not ours to remove: without proxy.json there is no evidence Devflow wrote these. expect(env.ANTHROPIC_BASE_URL).toBe(`http://127.0.0.1:${DEFAULT_PORT}`); expect(env[WINDOW_ENV]).toBe('1'); expect(env.MY_VAR).toBe('keep'); }); it('removes hooks AND both env vars when a managed port is supplied', () => { const settings = enabledSettings(DEFAULT_PORT); const changed = applyProxyTeardownToSettings(settings, DEFAULT_PORT); expect(changed).toBe(true); expect(hasProxyHooks(settings)).toBe(false); const env = (settings as unknown as { env?: Record }).env; expect(env?.ANTHROPIC_BASE_URL).toBeUndefined(); expect(env?.[WINDOW_ENV]).toBeUndefined(); expect(env?.MY_VAR).toBe('keep'); }); it('keeps the both-operations invariant: env is stripped even when hooks are present', () => { // The regression applyDisableToSettings guards against — hooks present must not // short-circuit the env strip. Re-pinned through the teardown entry point. const settings = enabledSettings(DEFAULT_PORT); applyProxyTeardownToSettings(settings, DEFAULT_PORT); const env = (settings as unknown as { env?: Record }).env; expect(env?.ANTHROPIC_BASE_URL).toBeUndefined(); expect(env?.[WINDOW_ENV]).toBeUndefined(); }); it('REG-1 preserved: a foreign gateway on another port survives a managed teardown', () => { const settings = { env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:9999' }, } as unknown as Settings; addProxyHooks(settings, DEVFLOW_DIR); applyProxyTeardownToSettings(settings, DEFAULT_PORT); const env = (settings as unknown as { env: Record }).env; expect(env.ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:9999'); expect(hasProxyHooks(settings)).toBe(false); }); it('returns false when there is nothing to remove (unmanaged, no hooks)', () => { const settings = { env: { ANTHROPIC_BASE_URL: 'https://gw.example.com' } } as unknown as Settings; expect(applyProxyTeardownToSettings(settings, undefined)).toBe(false); const env = (settings as unknown as { env: Record }).env; expect(env.ANTHROPIC_BASE_URL).toBe('https://gw.example.com'); }); });