import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; const fixture = vi.hoisted(() => ({ options: [] as Array>, })); vi.mock('../src/server.ts', () => ({ startServer: async (options: Record) => { fixture.options.push(options); return { addresses: [], close: async () => {} }; }, })); vi.mock('../src/environment.ts', () => ({ bundledStim: () => ({ cli: 'unused', version: '1.0.0' }), })); vi.mock('@stim-cli/core/toolchain', () => ({ discoverToolchain: (env: NodeJS.ProcessEnv) => ({ env: { ...env }, entries: [] }), })); vi.mock('@stim-cli/transport-tailscale', async (original) => { const actual = await original(); const snapshot = { binary: null, state: { state: 'unavailable' as const, reason: 'fixture' } }; return { ...actual, createTransport: async ({ env }: { env: NodeJS.ProcessEnv }) => actual.tailscaleTransport({ env, snapshot, monitor: { current: () => snapshot, stop: () => {}, onChange: () => () => {} }, }), }; }); async function serve(...flags: string[]): Promise> { const home = mkdtempSync(join(tmpdir(), 'stim-server-loopback-')); const previousHome = process.env.STIM_HOME; process.env.STIM_HOME = home; const argv = process.argv; process.argv = [process.execPath, join(import.meta.dirname, '../bin/stim-server.ts'), ...flags]; fixture.options.length = 0; vi.spyOn(process, 'on').mockImplementation(() => process); vi.spyOn(console, 'log').mockImplementation(() => {}); vi.spyOn(console, 'error').mockImplementation(() => {}); try { vi.resetModules(); const { serve: serveServer } = await import('../src/cli.ts'); await serveServer( { port: 7787, extraEnv: [], pathPrepend: [], loopbackOnly: flags.includes('--loopback-only'), shareOnly: false, desktopKey: Buffer.alloc(32, 7).toString('base64url'), script: 'unused', }, () => {}, ); await vi.waitFor(() => expect(fixture.options).toHaveLength(1)); return fixture.options[0]!; } finally { process.argv = argv; if (previousHome === undefined) delete process.env.STIM_HOME; else process.env.STIM_HOME = previousHome; rmSync(home, { recursive: true, force: true }); vi.restoreAllMocks(); } } test('--loopback-only tells the server to listen on 127.0.0.1 alone and to refuse forwarded peers', async () => { const options = await serve('--loopback-only'); expect(options.hosts).toEqual(['127.0.0.1']); expect(options.loopbackOnly).toBe(true); });