Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): fail loudly on blocked test network requests (#4415)
Nick Gomezeb0b20cd9af3
diff --git a/knip.config.ts b/knip.config.tsindex 802352af8..dd620604a 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -101,6 +101,9 @@ export default {'packages/native-config/index.js': ['unlisted', 'unresolved'],},workspaces: {+ '.': {+ entry: ['test-support/fixtures/no-net-connect/no-net-connect.fixture.ts'],+ },'packages/app': {entry: ['src/**/*.test.{ts,tsx}',diff --git a/package.json b/package.jsonindex bf6a737ae..cb9eb16af 100644--- a/package.json+++ b/package.json@@ -43,7 +43,8 @@"prepare": "bash scripts/husky-prepare.sh","changeset": "changeset","version": "changeset version",- "release": "changeset publish"+ "release": "changeset publish",+ "typecheck:no-net-connect": "tsc --noEmit -p test-support/tsconfig.no-net-connect.json"},"lint-staged": {"packages/**/*.{ts,tsx,js,jsx,json,md}": [@@ -67,6 +68,7 @@"devDependencies": {"@biomejs/biome": "2.5.11","@changesets/cli": "^2.29.7",+ "@types/node": "^24.7.0","@typescript/native": "npm:typescript@~7.0.2","husky": "^9.1.7","knip": "^6.26.0",@@ -79,6 +81,7 @@"tsx": "^4.20.0","turbo": "^2.7.0","typescript": "~6.0.3",+ "undici": "~7.29.0","vitest": "^4.1.0","yaml": "^2.8.3"},diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex fc2e39e24..8211d5efa 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -191,6 +191,9 @@ importers:'@changesets/cli':specifier: ^2.29.7version: 2.31.0(@types/[email protected])+ '@types/node':+ specifier: ^24.7.0+ version: 24.13.3'@typescript/native':specifier: npm:typescript@~7.0.2version: [email protected]@@ -227,6 +230,9 @@ importers:typescript:specifier: ~6.0.3version: 6.0.3+ undici:+ specifier: ~7.29.0+ version: 7.29.0vitest:specifier: ^4.1.0version: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))diff --git a/test-support/fixtures/no-net-connect/no-net-connect.fixture.ts b/test-support/fixtures/no-net-connect/no-net-connect.fixture.tsnew file mode 100644index 000000000..e451d29bf--- /dev/null+++ b/test-support/fixtures/no-net-connect/no-net-connect.fixture.ts@@ -0,0 +1,189 @@+import { Agent } from 'undici';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import {+ type DispatcherRequestInit,+ expectBlockedNetworkRequest,+ NetConnectBlockedError,+} from '../../no-net-connect';++const dispatcher = new Agent({+ connect: {+ lookup(_hostname, _options, callback) {+ callback(null, [{ address: '127.0.0.1', family: 4 }]);+ },+ },+});++async function captureBlockedRequest(hostname: string): Promise<unknown> {+ return fetch(`http://${hostname}:4/resource`, {+ dispatcher,+ } as DispatcherRequestInit).catch((error: unknown) => error);+}++afterAll(() => dispatcher.close());++if (process.env.OK_FIXTURE_COLLECTION_BLOCK === '1') {+ try {+ await fetch('https://collection-time.invalid/resource');+ } catch {}+}++test('swallowed undeclared forbidden fetch fails', async () => {+ await captureBlockedRequest('undeclared.invalid');+});++test('declared exact hostname block passes', async () => {+ expectBlockedNetworkRequest('expected.invalid');+ const error = await captureBlockedRequest('expected.invalid');+ expect(error).toBeInstanceOf(NetConnectBlockedError);+});++test('unused hostname expectation fails', () => {+ expectBlockedNetworkRequest('unused.invalid');+});++test('mismatched hostname expectation fails', async () => {+ expectBlockedNetworkRequest('expected.invalid');+ const error = await captureBlockedRequest('actual.invalid');+ expect(error).toBeInstanceOf(NetConnectBlockedError);+});++test('ordinary assertion and swallowed forbidden fetch both surface', async () => {+ await captureBlockedRequest('combined-failure.invalid');+ expect('ordinary-actual').toBe('ordinary-expected');+});++describe('suite setup swallowed block fails', () => {+ beforeAll(async () => {+ await captureBlockedRequest('suite-setup.invalid');+ });++ test('suite body completes', () => {+ expect(true).toBe(true);+ });+});++describe('suite teardown swallowed block fails', () => {+ afterAll(async () => {+ await captureBlockedRequest('suite-teardown.invalid');+ });++ test('suite body completes', () => {+ expect(true).toBe(true);+ });+});++describe('suite hook declarations cannot authorize sibling suite blocks', () => {+ describe('declaration sibling', () => {+ let rejection: unknown;++ beforeAll(() => {+ try {+ expectBlockedNetworkRequest('cross-suite.invalid');+ } catch (error) {+ rejection = error;+ }+ });++ test('declaration rejection body passes', () => {+ expect(rejection).toEqual(+ new Error('Expected network blocks must be declared inside a test, not suite hooks'),+ );+ });+ });++ describe('blocking sibling', () => {+ beforeAll(async () => {+ await captureBlockedRequest('cross-suite.invalid');+ });++ test('swallowed block body passes', () => {+ expect(true).toBe(true);+ });+ });+});++describe('a block that lands after its scope drained is reported, not enforced', () => {+ test('schedules a forbidden fetch that lands after it returns', () => {+ setTimeout(() => {+ void fetch('https://orphan.invalid/resource').catch(() => {});+ }, 10);+ });++ test('schedules a late declaration that cannot re-open its scope', () => {+ setTimeout(() => {+ expectBlockedNetworkRequest('late-declaration.invalid');+ void fetch('https://late-declaration.invalid/resource').catch(() => {});+ }, 10);+ });++ test('a later test gives the orphan time to land', async () => {+ await new Promise((resolve) => setTimeout(resolve, 250));+ });+});++test('unrelated console error passes', () => {+ console.error('fixture diagnostic unrelated to network blocking');+});++describe('concurrent siblings isolate exact hostname expectations', () => {+ let releaseAlpha: (() => void) | undefined;+ let releaseBeta: (() => void) | undefined;+ const alphaDeclared = new Promise<void>((resolve) => {+ releaseAlpha = resolve;+ });+ const betaDeclared = new Promise<void>((resolve) => {+ releaseBeta = resolve;+ });++ test.concurrent('alpha request', async () => {+ expectBlockedNetworkRequest('alpha.invalid');+ releaseAlpha?.();+ await betaDeclared;+ const error = await captureBlockedRequest('alpha.invalid');+ expect(error).toBeInstanceOf(NetConnectBlockedError);+ });++ test.concurrent('beta request', async () => {+ await alphaDeclared;+ expectBlockedNetworkRequest('beta.invalid');+ releaseBeta?.();+ const error = await captureBlockedRequest('beta.invalid');+ expect(error).toBeInstanceOf(NetConnectBlockedError);+ });+});++describe('concurrent unexpected block stays with its owning test', () => {+ let releaseOffenderStarted: (() => void) | undefined;+ let releaseInnocentReady: (() => void) | undefined;+ let releaseOffenderBlocked: (() => void) | undefined;+ let releaseInnocentDone: (() => void) | undefined;+ const offenderStarted = new Promise<void>((resolve) => {+ releaseOffenderStarted = resolve;+ });+ const innocentReady = new Promise<void>((resolve) => {+ releaseInnocentReady = resolve;+ });+ const offenderBlocked = new Promise<void>((resolve) => {+ releaseOffenderBlocked = resolve;+ });+ const innocentDone = new Promise<void>((resolve) => {+ releaseInnocentDone = resolve;+ });++ test.concurrent('offender swallows its unexpected block', async () => {+ releaseOffenderStarted?.();+ await innocentReady;+ await captureBlockedRequest('concurrent-offender.invalid');+ releaseOffenderBlocked?.();+ await innocentDone;+ });++ test.concurrent('innocent sibling passes', async () => {+ await offenderStarted;+ releaseInnocentReady?.();+ await offenderBlocked;+ expect(true).toBe(true);+ releaseInnocentDone?.();+ });+});diff --git a/test-support/fixtures/no-net-connect/vitest.no-net-connect-fixture.config.ts b/test-support/fixtures/no-net-connect/vitest.no-net-connect-fixture.config.tsnew file mode 100644index 000000000..c2ce72c33--- /dev/null+++ b/test-support/fixtures/no-net-connect/vitest.no-net-connect-fixture.config.ts@@ -0,0 +1,11 @@+import { defineConfig } from 'vitest/config';+import { okVitestBase } from '../../vitest.base';++export default defineConfig({+ ...okVitestBase,+ test: {+ ...okVitestBase.test,+ include: ['test-support/fixtures/no-net-connect/no-net-connect.fixture.ts'],+ maxWorkers: 1,+ },+});diff --git a/test-support/no-net-connect-fixture-runner.test.ts b/test-support/no-net-connect-fixture-runner.test.tsnew file mode 100644index 000000000..b24a92a4c--- /dev/null+++ b/test-support/no-net-connect-fixture-runner.test.ts@@ -0,0 +1,313 @@+import { execFile } from 'node:child_process';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, test } from 'vitest';+import { NetConnectBlockedError } from './no-net-connect';++const PROJECT_ROOT = fileURLToPath(new URL('../', import.meta.url));+const FIXTURE_CONFIG = fileURLToPath(+ new URL('./fixtures/no-net-connect/vitest.no-net-connect-fixture.config.ts', import.meta.url),+);+const VITEST_PACKAGE_DIR = dirname(fileURLToPath(import.meta.resolve('vitest/package.json')));+const VITEST_CLI = resolve(VITEST_PACKAGE_DIR, 'vitest.mjs');+const FIXTURE_TIMEOUT_MS = 20_000;++type AssertionStatus = 'passed' | 'failed' | 'skipped' | 'pending' | 'todo';++type AssertionResult = {+ fullName: string;+ status: AssertionStatus;+ failureMessages: string[];+};++type TestFileResult = {+ status: AssertionStatus;+ message: string;+ assertionResults: AssertionResult[];+};++type VitestJsonReport = {+ success: boolean;+ testResults: TestFileResult[];+};++type FixtureResult = {+ exitCode: number | string | null;+ killed: boolean;+ signal: NodeJS.Signals | null;+ stdout: string;+ stderr: string;+};++type FixtureRun = {+ env?: Record<string, string>;+ reporter?: 'json' | 'default';+};++function runFixture(testNamePattern: string, run: FixtureRun = {}): Promise<FixtureResult> {+ return new Promise((resolveResult) => {+ execFile(+ process.execPath,+ [+ VITEST_CLI,+ 'run',+ '--config',+ FIXTURE_CONFIG,+ '--testNamePattern',+ testNamePattern,+ `--reporter=${run.reporter ?? 'json'}`,+ '--no-color',+ ],+ {+ cwd: PROJECT_ROOT,+ env: {+ ...process.env,+ FORCE_COLOR: '0',+ NO_COLOR: '1',+ OK_FIXTURE_COLLECTION_BLOCK: '',+ ...run.env,+ },+ timeout: FIXTURE_TIMEOUT_MS,+ },+ (error, stdout, stderr) => {+ resolveResult({+ exitCode: error?.code ?? 0,+ killed: error?.killed ?? false,+ signal: error?.signal ?? null,+ stdout,+ stderr,+ });+ },+ );+ });+}++function assertLaunched(+ result: FixtureResult,+): asserts result is FixtureResult & { exitCode: number } {+ if (result.killed && result.signal === 'SIGTERM') {+ throw new Error(+ `Vitest fixture exceeded the ${FIXTURE_TIMEOUT_MS} ms per-run budget and was killed; ` ++ `this is a runner budget, not a guard regression.\n${result.stderr}`,+ );+ }+ expect(result.killed, result.stderr).toBe(false);+ expect(result.signal, result.stderr).toBeNull();+ if (typeof result.exitCode !== 'number') {+ throw new Error(`Vitest fixture failed to launch: ${result.exitCode}\n${result.stderr}`);+ }+}++function parseReport(result: FixtureResult): VitestJsonReport {+ assertLaunched(result);+ try {+ return JSON.parse(result.stdout) as VitestJsonReport;+ } catch (error) {+ throw new Error(`Vitest fixture returned invalid JSON\n${result.stdout}\n${result.stderr}`, {+ cause: error,+ });+ }+}++function assertionFor(report: VitestJsonReport, fullName: string): AssertionResult {+ const assertion = report.testResults[0]?.assertionResults.find(+ (result) => result.fullName === fullName,+ );+ if (assertion === undefined) throw new Error(`Missing fixture assertion: ${fullName}`);+ return assertion;+}++function expectedBlockedFailure(hostname: string, scopeName: string): string {+ return new NetConnectBlockedError(hostname, scopeName).toString();+}++describe('no-net-connect lifecycle fixture', () => {+ test('swallowed undeclared forbidden fetch exits with its NetConnectBlockedError', async () => {+ const fullName = 'swallowed undeclared forbidden fetch fails';+ const result = await runFixture(fullName);+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(1);+ expect(report.success).toBe(false);+ const assertion = assertionFor(report, fullName);+ expect(assertion.status).toBe('failed');+ expect(assertion.failureMessages).toHaveLength(1);+ expect(assertion.failureMessages[0]).toContain(+ expectedBlockedFailure('undeclared.invalid', fullName),+ );+ });++ test('mismatched hostname reports the unexpected block and unused expectation', async () => {+ const fullName = 'mismatched hostname expectation fails';+ const result = await runFixture(fullName);+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(1);+ expect(report.success).toBe(false);+ const assertion = assertionFor(report, fullName);+ expect(assertion.status).toBe('failed');+ const failures = assertion.failureMessages.join('\n');+ expect(failures).toContain(expectedBlockedFailure('actual.invalid', fullName));+ expect(failures).toContain(+ `Error: Expected network blocks did not occur in ${fullName}: expected.invalid`,+ );+ });++ test('ordinary assertion and swallowed block both surface', async () => {+ const fullName = 'ordinary assertion and swallowed forbidden fetch both surface';+ const result = await runFixture(fullName);+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(1);+ expect(report.success).toBe(false);+ const assertion = assertionFor(report, fullName);+ expect(assertion.status).toBe('failed');+ const failures = assertion.failureMessages.join('\n');+ expect(failures).toContain(expectedBlockedFailure('combined-failure.invalid', fullName));+ expect(failures).toContain('ordinary-actual');+ expect(failures).toContain('ordinary-expected');+ });++ test('unused hostname expectation fails its owning assertion', async () => {+ const fullName = 'unused hostname expectation fails';+ const result = await runFixture(fullName);+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(1);+ expect(report.success).toBe(false);+ const assertion = assertionFor(report, fullName);+ expect(assertion.status).toBe('failed');+ expect(assertion.failureMessages).toHaveLength(1);+ expect(assertion.failureMessages[0]).toContain(+ `Expected network blocks did not occur in ${fullName}: unused.invalid`,+ );+ });++ test('suite setup swallowed block fails the suite result', async () => {+ const result = await runFixture('suite setup swallowed block fails');+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(1);+ expect(report.success).toBe(false);+ const fileResult = report.testResults[0];+ expect(fileResult?.status).toBe('failed');+ expect(fileResult?.message).toBe(+ new NetConnectBlockedError('suite-setup.invalid', '<suite hooks>').message,+ );+ expect(+ assertionFor(report, 'suite setup swallowed block fails suite body completes').status,+ ).toBe('passed');+ });++ test('a collection-time block is reported alongside a suite-hook block', async () => {+ const result = await runFixture('suite setup swallowed block fails', {+ env: { OK_FIXTURE_COLLECTION_BLOCK: '1' },+ reporter: 'default',+ });+ assertLaunched(result);+ expect(result.exitCode, result.stderr).toBe(1);+ const output = `${result.stdout}\n${result.stderr}`;+ expect(output).toContain(+ new NetConnectBlockedError('suite-setup.invalid', '<suite hooks>').message,+ );+ expect(output).toContain(+ new NetConnectBlockedError('collection-time.invalid', '<outside a test>').message,+ );+ });++ test('suite teardown swallowed block fails the suite result', async () => {+ const result = await runFixture('suite teardown swallowed block fails');+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(1);+ expect(report.success).toBe(false);+ const fileResult = report.testResults[0];+ expect(fileResult?.status).toBe('failed');+ expect(fileResult?.message).toBe(+ new NetConnectBlockedError('suite-teardown.invalid', '<suite hooks>').message,+ );+ expect(+ assertionFor(report, 'suite teardown swallowed block fails suite body completes').status,+ ).toBe('passed');+ });++ test('suite hook declaration cannot authorize a sibling suite block', async () => {+ const suiteName = 'suite hook declarations cannot authorize sibling suite blocks';+ const result = await runFixture(suiteName);+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(1);+ expect(report.success).toBe(false);+ const fileResult = report.testResults[0];+ expect(fileResult?.status).toBe('failed');+ expect(fileResult?.message).toBe(+ new NetConnectBlockedError('cross-suite.invalid', '<suite hooks>').message,+ );+ expect(+ assertionFor(report, `${suiteName} declaration sibling declaration rejection body passes`)+ .status,+ ).toBe('passed');+ expect(+ assertionFor(report, `${suiteName} blocking sibling swallowed block body passes`).status,+ ).toBe('passed');+ });++ test('a block landing after its scope drained is reported on stderr, not enforced', async () => {+ const suiteName = 'a block that lands after its scope drained is reported, not enforced';+ const result = await runFixture(suiteName);+ assertLaunched(result);+ expect(result.exitCode, result.stderr).toBe(0);+ const report = parseReport(result);+ expect(report.success).toBe(true);+ const scopeName = `${suiteName} > schedules a forbidden fetch that lands after it returns`;+ expect(result.stderr).toContain(`Blocked a request to "orphan.invalid" for "${scopeName}"`);+ expect(result.stderr).toContain('Reported, not enforced');+ const lateScope = `${suiteName} > schedules a late declaration that cannot re-open its scope`;+ expect(result.stderr).toContain(+ `Declared a block for "late-declaration.invalid" for "${lateScope}"`,+ );+ expect(result.stderr).toContain(+ `Blocked a request to "late-declaration.invalid" for "${lateScope}"`,+ );+ expect(result.stderr).not.toContain(+ new NetConnectBlockedError('orphan.invalid', scopeName).message,+ );+ });++ test.each(['declared exact hostname block passes', 'unrelated console error passes'])(+ '%s exits with a passing assertion',+ async (fullName) => {+ const result = await runFixture(fullName);+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(0);+ expect(result.stderr).not.toContain('[no-net-connect]');+ expect(report.success).toBe(true);+ expect(assertionFor(report, fullName).status).toBe('passed');+ },+ );++ test('concurrent exact hostname expectations both pass', async () => {+ const suiteName = 'concurrent siblings isolate exact hostname expectations';+ const result = await runFixture(suiteName);+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(0);+ expect(report.success).toBe(true);+ expect(assertionFor(report, `${suiteName} alpha request`).status).toBe('passed');+ expect(assertionFor(report, `${suiteName} beta request`).status).toBe('passed');+ });++ test('concurrent unexpected block fails only its owning test', async () => {+ const suiteName = 'concurrent unexpected block stays with its owning test';+ const offenderName = `${suiteName} offender swallows its unexpected block`;+ const innocentName = `${suiteName} innocent sibling passes`;+ const result = await runFixture(suiteName);+ const report = parseReport(result);+ expect(result.exitCode, result.stderr).toBe(1);+ expect(report.success).toBe(false);+ const offender = assertionFor(report, offenderName);+ expect(offender.status).toBe('failed');+ expect(offender.failureMessages).toHaveLength(1);+ expect(offender.failureMessages[0]).toContain(+ expectedBlockedFailure(+ 'concurrent-offender.invalid',+ `${suiteName} > offender swallows its unexpected block`,+ ),+ );+ const innocent = assertionFor(report, innocentName);+ expect(innocent.status).toBe('passed');+ expect(innocent.failureMessages).toEqual([]);+ });+});diff --git a/test-support/no-net-connect.test.ts b/test-support/no-net-connect.test.tsindex 5dc834ba1..471d7f2ea 100644--- a/test-support/no-net-connect.test.ts+++ b/test-support/no-net-connect.test.ts@@ -1,6 +1,13 @@-import { createServer } from 'node:http';-import { describe, expect, test, vi } from 'vitest';-import { installNoNetConnect, isLoopbackHostname, NetConnectBlockedError } from './no-net-connect';+import { createServer, type IncomingMessage, type RequestListener, type Server } from 'node:http';+import { Agent, Dispatcher, MockAgent } from 'undici';+import { describe, expect, test } from 'vitest';+import {+ type DispatcherRequestInit,+ expectBlockedNetworkRequest,+ installNoNetConnect,+ isLoopbackHostname,+ NetConnectBlockedError,+} from './no-net-connect';import {REFUSED_LOOPBACK_ORIGIN,REFUSED_LOOPBACK_ORIGIN_ALT,@@ -8,6 +15,51 @@ import {const FETCH_BLOCKED_PORT_ORIGIN = 'http://127.0.0.1:1';+type ListeningServer = {+ origin: string;+ server: Server;+ close: () => Promise<void>;+};++async function listen(handler: RequestListener): Promise<ListeningServer> {+ const server = createServer(handler);+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', () => {+ server.off('error', reject);+ resolve();+ });+ });+ const address = server.address();+ if (address === null || typeof address === 'string') throw new Error('Server has no TCP port');+ return {+ origin: `http://127.0.0.1:${address.port}`,+ server,+ close: () =>+ new Promise<void>((resolve, reject) => {+ server.close((error) => (error === undefined ? resolve() : reject(error)));+ }),+ };+}++async function readBody(request: IncomingMessage): Promise<string> {+ const chunks: Buffer[] = [];+ for await (const chunk of request) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ }+ return Buffer.concat(chunks).toString('utf8');+}++async function blockedBy(+ hostname: string,+ run: () => Promise<unknown>,+): Promise<NetConnectBlockedError> {+ expectBlockedNetworkRequest(hostname);+ const outcome = await run().catch((error: unknown) => error);+ expect(outcome).toBeInstanceOf(NetConnectBlockedError);+ return outcome as NetConnectBlockedError;+}+describe('isLoopbackHostname', () => {test.each(['localhost',@@ -34,21 +86,10 @@ describe('isLoopbackHostname', () => {])('%s is not loopback', (host) => expect(isLoopbackHostname(host)).toBe(false));});-async function blockedBy(run: () => Promise<unknown>): Promise<unknown> {- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});- try {- const outcome = await run().catch((e: unknown) => e);- expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('[no-net-connect]'));- return outcome;- } finally {- consoleError.mockRestore();- }-}-describe('the installed fetch guard', () => {test('socketless schemes are allowed through without a host check', async () => {- const res = await fetch('data:text/plain,hello');- expect(await res.text()).toBe('hello');+ const response = await fetch('data:text/plain,hello');+ expect(await response.text()).toBe('hello');});test('installing twice is a no-op because the marker rides the wrapper', () => {@@ -64,74 +105,435 @@ describe('the installed fetch guard', () => {try {installNoNetConnect();expect(globalThis.fetch).not.toBe(unmarked);- const err = await blockedBy(() => fetch('https://example.com'));- expect(err).toBeInstanceOf(NetConnectBlockedError);+ const error = await blockedBy('example.com', () => fetch('https://example.com'));+ expect(error.message).toContain('example.com');+ } finally {+ globalThis.fetch = guarded;+ }+ });++ test('passes a full Dispatcher instance to the underlying fetch', async () => {+ const guarded = globalThis.fetch;+ let captured: Dispatcher | undefined;+ const underlying: typeof globalThis.fetch = async (_input, init) => {+ captured = (init as DispatcherRequestInit).dispatcher;+ return new Response('captured');+ };+ globalThis.fetch = underlying;+ try {+ installNoNetConnect();+ const response = await fetch('http://localhost/resource');+ expect(await response.text()).toBe('captured');+ expect(captured).toBeInstanceOf(Dispatcher);+ for (const method of ['dispatch', 'compose', 'request', 'close', 'destroy'] as const) {+ expect(typeof captured?.[method]).toBe('function');+ }+ } finally {+ globalThis.fetch = guarded;+ }+ });++ test('blocks a dispatch whose origin it cannot verify', async () => {+ const guarded = globalThis.fetch;+ let captured: Dispatcher | undefined;+ const underlying: typeof globalThis.fetch = async (_input, init) => {+ captured = (init as DispatcherRequestInit).dispatcher;+ return new Response('captured');+ };+ globalThis.fetch = underlying;+ try {+ installNoNetConnect();+ await fetch('http://localhost/resource');+ expectBlockedNetworkRequest('<unverifiable-origin>');+ let rejection: unknown;+ try {+ captured?.dispatch({ path: '/resource', method: 'GET' }, {});+ } catch (error) {+ rejection = error;+ }+ expect(rejection).toBeInstanceOf(NetConnectBlockedError);+ expect((rejection as Error).message).toContain('<unverifiable-origin>');+ } finally {+ globalThis.fetch = guarded;+ }+ });++ test('blocks a relative dispatch origin even when a document base would make it loopback', async () => {+ const guarded = globalThis.fetch;+ let captured: Dispatcher | undefined;+ const underlying: typeof globalThis.fetch = async (_input, init) => {+ captured = (init as DispatcherRequestInit).dispatcher;+ return new Response('captured');+ };+ globalThis.fetch = underlying;+ const hadLocation = 'location' in globalThis;+ Object.defineProperty(globalThis, 'location', {+ value: { href: 'http://localhost/page' },+ configurable: true,+ writable: true,+ });+ try {+ installNoNetConnect();+ await fetch('http://localhost/resource');+ expectBlockedNetworkRequest('<unverifiable-origin>');+ let rejection: unknown;+ try {+ captured?.dispatch({ path: '/resource', method: 'GET', origin: 'relative-origin' }, {});+ } catch (error) {+ rejection = error;+ }+ expect(rejection).toBeInstanceOf(NetConnectBlockedError);+ expect((rejection as Error).message).toContain('<unverifiable-origin>');} finally {globalThis.fetch = guarded;+ if (!hadLocation) Reflect.deleteProperty(globalThis, 'location');+ }+ });++ test('forwards a caller dispatcher for an allowed request', async () => {+ let targetHits = 0;+ const target = await listen((_request, response) => {+ targetHits += 1;+ response.end('through dispatcher');+ });+ const targetPort = new URL(target.origin).port;+ const dispatcher = new Agent({+ connect: {+ lookup(_hostname, _options, callback) {+ callback(null, [{ address: '127.0.0.1', family: 4 }]);+ },+ },+ });+ try {+ const response = await fetch(`http://allowed.localhost:${targetPort}/destination`, {+ dispatcher,+ } as DispatcherRequestInit);+ expect(await response.text()).toBe('through dispatcher');+ expect(targetHits).toBe(1);+ } finally {+ await dispatcher.close();+ await target.close();+ }+ });++ test('preserves caller MockAgent matching and consumes its interceptor', async () => {+ const dispatcher = new MockAgent();+ dispatcher.disableNetConnect();+ dispatcher+ .get('http://mocked.localhost')+ .intercept({ method: 'GET', path: '/resource' })+ .reply(200, 'mocked response');+ try {+ const response = await fetch('http://mocked.localhost/resource', {+ dispatcher,+ } as DispatcherRequestInit);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe('mocked response');+ dispatcher.assertNoPendingInterceptors();+ } finally {+ await dispatcher.close();+ }+ });++ test('preserves caller MockAgent body matching and the body a reply callback reads', async () => {+ const dispatcher = new MockAgent();+ dispatcher.disableNetConnect();+ let observedBody: unknown;+ dispatcher+ .get('http://mocked.localhost')+ .intercept({ method: 'POST', path: '/resource', body: 'declared body' })+ .reply(200, (options: { body?: unknown }) => {+ observedBody = options.body;+ return 'matched on body';+ });+ try {+ const response = await fetch('http://mocked.localhost/resource', {+ method: 'POST',+ body: 'declared body',+ dispatcher,+ } as DispatcherRequestInit);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe('matched on body');+ expect(observedBody).toBe('declared body');+ dispatcher.assertNoPendingInterceptors();+ } finally {+ await dispatcher.close();}});+ test('declared blocked requests consume the exact hostname expectation', async () => {+ const error = await blockedBy('example.com', () => fetch('https://example.com'));+ expect(error.message).toContain('example.com');+ });+test('rejects a non-loopback request and names the offending test', async () => {- const err = (await blockedBy(() =>- fetch('https://intake.invalid-tld-for-test.invalid/api/bug-report'),- )) as Error;- expect(err).toBeInstanceOf(NetConnectBlockedError);- expect(err.message).toMatch(/intake\.invalid-tld-for-test\.invalid/);- expect(err.message).toMatch(/names the offending test/);+ const hostname = 'intake.invalid-tld-for-test.invalid';+ const error = await blockedBy(hostname, () => fetch(`https://${hostname}/api/bug-report`));+ expect(error.message).toContain(hostname);+ expect(error.message).toMatch(/names the offending test/);});- test('carries no errno-shaped `code`, so it cannot masquerade as a real transport error', async () => {- const err = await blockedBy(() => fetch('https://example.com'));- expect(err).toBeInstanceOf(NetConnectBlockedError);- expect((err as { code?: unknown }).code).toBeUndefined();- expect((err as { cause?: unknown }).cause).toBeUndefined();+ test('carries no errno-shaped code, so it cannot masquerade as a real transport error', async () => {+ const error = await blockedBy('example.com', () => fetch('https://example.com'));+ expect((error as { code?: unknown }).code).toBeUndefined();+ expect((error as { cause?: unknown }).cause).toBeUndefined();});test('lets a real loopback server through untouched', async () => {- const server = createServer((_req, res) => {- res.writeHead(200, { 'content-type': 'text/plain' });- res.end('reachable');+ const target = await listen((_request, response) => {+ response.writeHead(200, { 'content-type': 'text/plain' });+ response.end('reachable');});- await new Promise<void>((done) => server.listen(0, '127.0.0.1', () => done()));- const address = server.address();- if (address === null || typeof address === 'string') throw new Error('no port');try {- const res = await fetch(`http://127.0.0.1:${address.port}/`);- expect(await res.text()).toBe('reachable');+ const response = await fetch(target.origin);+ expect(await response.text()).toBe('reachable');} finally {- await new Promise<void>((done) => server.close(() => done()));+ await target.close();}});- test.each([- REFUSED_LOOPBACK_ORIGIN,- REFUSED_LOOPBACK_ORIGIN_ALT,- ])('%s yields a real kernel-level transport error', async (origin) => {- const err = (await fetch(`${origin}/api`).catch((e: unknown) => e)) as {+ test.each([REFUSED_LOOPBACK_ORIGIN, REFUSED_LOOPBACK_ORIGIN_ALT])(+ '%s yields a real kernel-level transport error',+ async (origin) => {+ const error = (await fetch(`${origin}/api`).catch((caught: unknown) => caught)) as {+ name?: string;+ cause?: { code?: string; syscall?: string };+ };+ expect(error).not.toBeInstanceOf(NetConnectBlockedError);+ expect(error.name).toBe('TypeError');+ expect(error.cause?.code).toBe('ECONNREFUSED');+ expect(error.cause?.syscall).toBe('connect');+ },+ );++ test.each([REFUSED_LOOPBACK_ORIGIN, REFUSED_LOOPBACK_ORIGIN_ALT])(+ '%s sits below every ephemeral range, so listen(0) cannot hand it out',+ (origin) => {+ const port = Number(new URL(origin).port);+ expect(port).toBeGreaterThan(0);+ expect(port).toBeLessThan(32768);+ },+ );++ test('a fetch-blocked port would not do because it fails with no errno at all', async () => {+ const error = (await fetch(`${FETCH_BLOCKED_PORT_ORIGIN}/api`).catch(+ (caught: unknown) => caught,+ )) as {name?: string;- cause?: { code?: string; syscall?: string };+ cause?: { code?: string };};- expect(err).not.toBeInstanceOf(NetConnectBlockedError);- expect(err.name).toBe('TypeError');- expect(err.cause?.code).toBe('ECONNREFUSED');- expect(err.cause?.syscall).toBe('connect');+ expect(error.name).toBe('TypeError');+ expect(error.cause?.code).toBeUndefined();});+});- test.each([- REFUSED_LOOPBACK_ORIGIN,- REFUSED_LOOPBACK_ORIGIN_ALT,- ])('%s sits below every ephemeral range, so listen(0) cannot hand it out', (origin) => {- const port = Number(new URL(origin).port);- expect(port).toBeGreaterThan(0);- expect(port).toBeLessThan(32768);+describe('native fetch redirect semantics', () => {+ test.each(['manual', 'error'] as const)(+ 'honors redirect mode %s from a Request input',+ async (redirect) => {+ let targetHits = 0;+ const target = await listen((_request, response) => {+ targetHits += 1;+ response.end('followed');+ });+ const source = await listen((_request, response) => {+ response.writeHead(302, { location: `${target.origin}/destination` });+ response.end();+ });+ try {+ const request = new Request(`${source.origin}/source`, { redirect });+ if (redirect === 'manual') {+ const response = await fetch(request);+ expect(response.status).toBe(302);+ expect(response.headers.get('location')).toBe(`${target.origin}/destination`);+ } else {+ const error = await fetch(request).catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(TypeError);+ }+ expect(targetHits).toBe(0);+ } finally {+ await Promise.all([source.close(), target.close()]);+ }+ },+ );++ test('follows a relative redirect and reports the final response URL', async () => {+ const target = await listen((request, response) => {+ if (request.url === '/start') {+ response.writeHead(302, { location: '/final' });+ response.end();+ return;+ }+ response.end('arrived');+ });+ try {+ const response = await fetch(`${target.origin}/start`);+ expect(await response.text()).toBe('arrived');+ expect(response.url).toBe(`${target.origin}/final`);+ expect(response.redirected).toBe(true);+ } finally {+ await target.close();+ }});- test('a fetch-blocked port would NOT do: it fails with no errno at all', async () => {- const err = (await fetch(`${FETCH_BLOCKED_PORT_ORIGIN}/api`).catch((e: unknown) => e)) as {- name?: string;- cause?: { code?: string };- };- expect(err.name).toBe('TypeError');- expect(err.cause?.code).toBeUndefined();+ test.each([302, 303])('rewrites POST to GET after a %i redirect', async (status) => {+ const received: Array<{ method: string | undefined; body: string }> = [];+ const target = await listen(async (request, response) => {+ if (request.url === '/start') {+ await readBody(request);+ response.writeHead(status, { location: '/final' });+ response.end();+ return;+ }+ received.push({ method: request.method, body: await readBody(request) });+ response.end('arrived');+ });+ try {+ const response = await fetch(`${target.origin}/start`, {+ method: 'POST',+ body: 'original-body',+ });+ expect(await response.text()).toBe('arrived');+ expect(received).toEqual([{ method: 'GET', body: '' }]);+ } finally {+ await target.close();+ }+ });++ test('preserves POST method and body after a 307 redirect', async () => {+ const received: Array<{ method: string | undefined; body: string }> = [];+ const target = await listen(async (request, response) => {+ if (request.url === '/start') {+ await readBody(request);+ response.writeHead(307, { location: '/final' });+ response.end();+ return;+ }+ received.push({ method: request.method, body: await readBody(request) });+ response.end('arrived');+ });+ try {+ const response = await fetch(`${target.origin}/start`, {+ method: 'POST',+ body: 'original-body',+ });+ expect(await response.text()).toBe('arrived');+ expect(received).toEqual([{ method: 'POST', body: 'original-body' }]);+ } finally {+ await target.close();+ }+ });++ test('strips credentials when a redirect crosses origins', async () => {+ let receivedHeaders: IncomingMessage['headers'] | undefined;+ const target = await listen((request, response) => {+ receivedHeaders = request.headers;+ response.end('arrived');+ });+ const source = await listen((_request, response) => {+ response.writeHead(302, { location: `${target.origin}/final` });+ response.end();+ });+ try {+ const response = await fetch(`${source.origin}/start`, {+ headers: {+ authorization: 'Bearer secret',+ cookie: 'session=secret',+ 'proxy-authorization': 'Basic secret',+ },+ });+ expect(await response.text()).toBe('arrived');+ expect(receivedHeaders?.authorization).toBeUndefined();+ expect(receivedHeaders?.cookie).toBeUndefined();+ expect(receivedHeaders?.['proxy-authorization']).toBeUndefined();+ } finally {+ await Promise.all([source.close(), target.close()]);+ }+ });++ test('returns a nonredirect 304 response without another request', async () => {+ let requests = 0;+ const target = await listen((request, response) => {+ requests += 1;+ if (request.url === '/destination') {+ response.end('incorrectly followed');+ return;+ }+ response.writeHead(304, { location: '/destination' });+ response.end();+ });+ try {+ const response = await fetch(target.origin);+ expect(response.status).toBe(304);+ expect(response.redirected).toBe(false);+ expect(requests).toBe(1);+ } finally {+ await target.close();+ }+ });++ test('allows twenty redirects and rejects the twenty-first', async () => {+ const hits = new Map<number, number>();+ const target = await listen((request, response) => {+ const match = /^\/(\d+)\/(\d+)$/.exec(request.url ?? '');+ if (match === null) throw new Error(`Unexpected redirect path ${request.url}`);+ const total = Number(match[1]);+ const step = Number(match[2]);+ hits.set(total, (hits.get(total) ?? 0) + 1);+ if (step < total) {+ response.writeHead(302, { location: `/${total}/${step + 1}` });+ response.end();+ return;+ }+ response.end('arrived');+ });+ try {+ const allowed = await fetch(`${target.origin}/20/0`);+ expect(await allowed.text()).toBe('arrived');+ const rejected = await fetch(`${target.origin}/21/0`).catch((caught: unknown) => caught);+ expect(rejected).toBeInstanceOf(TypeError);+ expect(hits.get(20)).toBe(21);+ expect(hits.get(21)).toBe(21);+ } finally {+ await target.close();+ }+ });++ test('blocks a redirected external hostname before its dispatcher can reach loopback', async () => {+ let targetHits = 0;+ const target = await listen((_request, response) => {+ targetHits += 1;+ response.end('guard bypassed');+ });+ const targetPort = new URL(target.origin).port;+ let sourceHits = 0;+ const source = await listen((request, response) => {+ sourceHits += 1;+ response.writeHead(302, {+ location:+ request.url === '/source'+ ? '/allowed-hop'+ : `http://blocked.invalid:${targetPort}/destination`,+ });+ response.end();+ });+ const dispatcher = new Agent({+ connect: {+ lookup(_hostname, _options, callback) {+ callback(null, [{ address: '127.0.0.1', family: 4 }]);+ },+ },+ });+ try {+ const error = await blockedBy('blocked.invalid', () =>+ fetch(`${source.origin}/source`, { dispatcher } as DispatcherRequestInit),+ );+ expect(error.message).toContain('blocked.invalid');+ expect(sourceHits).toBe(2);+ expect(targetHits).toBe(0);+ } finally {+ await dispatcher.close();+ await Promise.all([source.close(), target.close()]);+ }});});diff --git a/test-support/no-net-connect.ts b/test-support/no-net-connect.tsindex 2f820f553..8b16a3873 100644--- a/test-support/no-net-connect.ts+++ b/test-support/no-net-connect.ts@@ -1,7 +1,104 @@-import { expect } from 'vitest';+import { AsyncLocalStorage } from 'node:async_hooks';+import { type Dispatcher, getGlobalDispatcher } from 'undici';+import { aroundAll, aroundEach, type RunnerTask } from 'vitest';const INSTALLED = Symbol.for('ok.test.noNetConnect.installed');+interface BlockScope {+ kind: 'test' | 'file';+ name: string;+ expected: string[];+ unexpected: NetConnectBlockedError[];+ drained: boolean;+}++const activeScope = new AsyncLocalStorage<BlockScope>();+function newScope(kind: BlockScope['kind'], name: string): BlockScope {+ return { kind, name, expected: [], unexpected: [], drained: false };+}++const collectionScope = newScope('file', '<outside a test>');++function scopeFor(task: RunnerTask): BlockScope {+ const names = [task.name];+ for (let suite = task.suite; suite; suite = suite.suite) names.unshift(suite.name);+ return newScope('test', names.join(' > '));+}++function assertNoUnexpectedBlocks(...scopes: BlockScope[]): void {+ const errors: Error[] = [];+ for (const scope of scopes) {+ scope.drained = true;+ errors.push(...scope.unexpected.splice(0));+ const expected = scope.expected.splice(0);+ if (expected.length) {+ errors.push(+ new Error(`Expected network blocks did not occur in ${scope.name}: ${expected.join(', ')}`),+ );+ }+ }+ if (errors.length === 1) throw errors[0];+ if (errors.length > 1) {+ throw new AggregateError(+ errors,+ errors.map((error) => `${error.name}: ${error.message}`).join('\n'),+ );+ }+}++const UNVERIFIABLE_ORIGIN = '<unverifiable-origin>';++function reportAfterScope(what: string, scope: BlockScope): void {+ process.stderr.write(+ `[no-net-connect] ${what} for "${scope.name}" after that scope completed. ` ++ 'Reported, not enforced: the ledger for that scope was already drained, so nothing ' ++ 'fails. Await the work that reaches the network, or move it inside the test.\n',+ );+}++export function expectBlockedNetworkRequest(hostname: string): void {+ const scope = activeScope.getStore();+ if (scope?.kind !== 'test')+ throw new Error('Expected network blocks must be declared inside a test, not suite hooks');+ if (scope.drained) {+ reportAfterScope(`Declared a block for "${hostname}"`, scope);+ return;+ }+ scope.expected.push(hostname.toLowerCase());+}++function blockHost(hostname: string, scope: BlockScope): never {+ const blocked = new NetConnectBlockedError(hostname, scope.name);+ if (scope.drained) reportAfterScope(`Blocked a request to "${hostname}"`, scope);+ else {+ const expectedIndex = scope.expected.indexOf(hostname.toLowerCase());+ if (expectedIndex >= 0) scope.expected.splice(expectedIndex, 1);+ else scope.unexpected.push(blocked);+ }+ throw blocked;+}++function checkTarget(target: URL, scope: BlockScope): void {+ if (SOCKETLESS_PROTOCOLS.has(target.protocol) || isLoopbackHostname(target.hostname)) return;+ blockHost(target.hostname, scope);+}++function checkDispatchOrigin(origin: Dispatcher.DispatchOptions['origin'], scope: BlockScope): void {+ if (origin instanceof URL) {+ checkTarget(origin, scope);+ return;+ }+ if (typeof origin === 'string') {+ try {+ checkTarget(new URL(origin), scope);+ return;+ } catch (error) {+ if (error instanceof NetConnectBlockedError) throw error;+ }+ }+ blockHost(UNVERIFIABLE_ORIGIN, scope);+}+const IPV4_OCTET = '(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';const LOOPBACK_V4_RE = new RegExp(`^127\\.${IPV4_OCTET}\\.${IPV4_OCTET}\\.${IPV4_OCTET}$`);@@ -41,38 +138,67 @@ export class NetConnectBlockedError extends Error {constructor(hostname: string, testName: string) {super(`Blocked an outbound network request to "${hostname}" from test: ${testName}. ` +- 'Unit tests must be hermetic — only loopback hosts are reachable. Fake the ' +- 'dependency at its seam, or point it at a CLOSED loopback port when you need a ' +- 'real transport error. See test-support/no-net-connect.ts.',+ 'Unit tests must be hermetic: only loopback hosts are reachable. Fake the ' ++ 'dependency at its seam, or point it at a CLOSED loopback port for a real transport error. ' ++ 'Deliberate guard tests must call expectBlockedNetworkRequest(hostname) before the request. ' ++ 'Unexpected blocks fail the owning test even when the request error is caught.',);}}+export type FetchInit = RequestInit & { dispatcher?: Dispatcher };++export type DispatcherRequestInit = FetchInit & { dispatcher: Dispatcher };+export function installNoNetConnect(): void {const realFetch = globalThis.fetch;if (typeof realFetch !== 'function') return;if ((realFetch as { [INSTALLED]?: boolean })[INSTALLED] === true) return;- const guardedFetch = async function guardedFetch(- input: Parameters<typeof realFetch>[0],- init?: Parameters<typeof realFetch>[1],- ): ReturnType<typeof realFetch> {+ const guardedFetch = async (input: Parameters<typeof realFetch>[0], init?: FetchInit) => {+ const scope = activeScope.getStore() ?? collectionScope;const target = resolveTarget(input);- if (- target !== null &&- !SOCKETLESS_PROTOCOLS.has(target.protocol) &&- !isLoopbackHostname(target.hostname)- ) {- const testName = expect.getState().currentTestName ?? '<outside a test>';- const blocked = new NetConnectBlockedError(target.hostname, testName);- console.error(`[no-net-connect] ${blocked.message}`);- throw blocked;+ if (target !== null) checkTarget(target, scope);+ const upstream = init?.dispatcher ?? getGlobalDispatcher();+ const dispatcher = upstream.compose((dispatch) => (options, handler) => {+ checkDispatchOrigin(options.origin, scope);+ return dispatch(options, handler);+ });+ const guardedInit: FetchInit = { ...init, dispatcher };+ try {+ return await realFetch(input, guardedInit);+ } catch (error) {+ if (error instanceof Error && error.cause instanceof NetConnectBlockedError) {+ throw error.cause;+ }+ throw error;}- return realFetch(input, init);- } as typeof realFetch;+ };- (guardedFetch as { [INSTALLED]?: boolean })[INSTALLED] = true;+ Object.defineProperty(guardedFetch, INSTALLED, { value: true });globalThis.fetch = guardedFetch;}installNoNetConnect();++aroundEach(async (runTest, { task }) => {+ const scope = scopeFor(task);+ await activeScope.run(scope, async () => {+ try {+ await runTest();+ } finally {+ assertNoUnexpectedBlocks(scope);+ }+ });+});++aroundAll(async (runSuite) => {+ const scope = newScope('file', '<suite hooks>');+ await activeScope.run(scope, async () => {+ try {+ await runSuite();+ } finally {+ assertNoUnexpectedBlocks(scope, collectionScope);+ }+ });+});diff --git a/test-support/setup-files-contract.test.ts b/test-support/setup-files-contract.test.tsindex 527c3faeb..00ce476ea 100644--- a/test-support/setup-files-contract.test.ts+++ b/test-support/setup-files-contract.test.ts@@ -25,6 +25,7 @@ const KNOWN_TEST_PROJECTS = ['packages/md-conformance/md-audit/vitest.config.ts','packages/md-conformance/vitest.config.ts','packages/server/vitest.config.ts',+ 'test-support/fixtures/no-net-connect/vitest.no-net-connect-fixture.config.ts','vitest.config.ts','vitest.scripts.config.ts',];@@ -100,16 +101,17 @@ describe('vitest setupFiles contract', () => {);});- test.each(- configs.filter(isTestConfig),- )('%s resolves setupFiles containing every entry the shared base installs', async (relPath) => {- const setupFiles = await resolveSetupFiles(relPath);- const missing = okVitestBase.test.setupFiles.filter((entry) => !setupFiles.includes(entry));- expect(- missing,- `${relPath} omits ${missing.length} shared setup file(s); it resolves ` +- `[${setupFiles.join(', ')}]. Build it from okVitestBase.test.setupFiles ` +- 'rather than listing entries by hand.',- ).toEqual([]);- });+ test.each(configs.filter(isTestConfig))(+ '%s resolves setupFiles containing every entry the shared base installs',+ async (relPath) => {+ const setupFiles = await resolveSetupFiles(relPath);+ const missing = okVitestBase.test.setupFiles.filter((entry) => !setupFiles.includes(entry));+ expect(+ missing,+ `${relPath} omits ${missing.length} shared setup file(s); it resolves ` ++ `[${setupFiles.join(', ')}]. Build it from okVitestBase.test.setupFiles ` ++ 'rather than listing entries by hand.',+ ).toEqual([]);+ },+ );});diff --git a/test-support/tsconfig.no-net-connect.json b/test-support/tsconfig.no-net-connect.jsonnew file mode 100644index 000000000..5d125a40f--- /dev/null+++ b/test-support/tsconfig.no-net-connect.json@@ -0,0 +1,13 @@+{+ "extends": "../tsconfig.json",+ "compilerOptions": {+ "noEmit": true,+ "types": ["node"],+ "allowImportingTsExtensions": true+ },+ "include": [+ "no-net-connect*.ts",+ "turbo-typecheck-attachment.test.ts",+ "fixtures/no-net-connect/**/*.ts"+ ]+}diff --git a/test-support/turbo-typecheck-attachment.test.ts b/test-support/turbo-typecheck-attachment.test.tsnew file mode 100644index 000000000..f94ed3ac0--- /dev/null+++ b/test-support/turbo-typecheck-attachment.test.ts@@ -0,0 +1,104 @@+import { spawnSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { dirname, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, test } from 'vitest';++const SUBTREE_ROOT = fileURLToPath(new URL('../', import.meta.url));+const ROOT_TASK = '//#typecheck:no-net-connect';+const TSCONFIG = 'test-support/tsconfig.no-net-connect.json';++type TurboConfig = {+ tasks: Record<string, { dependsOn?: string[]; inputs?: string[] }>;+};++function turboConfig(): TurboConfig {+ return JSON.parse(readFileSync(resolve(SUBTREE_ROOT, 'turbo.json'), 'utf8')) as TurboConfig;+}++const TSC = resolve(+ SUBTREE_ROOT,+ 'node_modules/.bin',+ process.platform === 'win32' ? 'tsc.cmd' : 'tsc',+);++function programFiles(): string[] {+ const run = spawnSync(TSC, ['--noEmit', '-p', TSCONFIG, '--listFiles'], {+ cwd: SUBTREE_ROOT,+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ shell: process.platform === 'win32',+ });+ if (run.error) throw run.error;+ if (run.status !== 0) {+ throw new Error(+ `${TSC} exited ${run.status} on ${TSCONFIG}; its diagnostics (stdout) follow, and the ` ++ `typecheck cell reports the same program:\n${run.stdout}${run.stderr}`,+ );+ }+ return run.stdout+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.length > 0 && !line.includes('/node_modules/'))+ .map((absolute) => relative(SUBTREE_ROOT, absolute))+ .filter((path) => !path.startsWith('..'));+}++function matchesInput(file: string, pattern: string): boolean {+ const deep = '/**/*.ts';+ if (pattern.endsWith(deep)) {+ const prefix = pattern.slice(0, -deep.length + 1);+ return file.startsWith(prefix) && file.endsWith('.ts');+ }+ const flat = '/*.ts';+ if (pattern.endsWith(flat)) {+ const dir = pattern.slice(0, -flat.length);+ return dirname(file) === dir && file.endsWith('.ts');+ }+ return file === pattern;+}++describe('the guard typecheck task is attached and its cache key covers its program', () => {+ test('tasks.typecheck.dependsOn carries the root task', () => {+ const { tasks } = turboConfig();+ expect(+ tasks.typecheck?.dependsOn,+ `dropping ${ROOT_TASK} from tasks.typecheck.dependsOn takes the only compiler that reads ` ++ 'the network guard out of every caller of turbo run typecheck, which still exits 0',+ ).toContain(ROOT_TASK);+ });++ test('the root task declares inputs matching every file in its tsc program', () => {+ const inputs = turboConfig().tasks[ROOT_TASK]?.inputs;+ expect(inputs, `${ROOT_TASK} must declare inputs`).toBeDefined();+ const files = programFiles();+ expect(files.length, 'the tsc program resolved no first-party files').toBeGreaterThan(0);+ const uncovered = files.filter(+ (file) => !(inputs ?? []).some((pattern) => matchesInput(file, pattern)),+ );+ expect(+ uncovered,+ `${TSCONFIG} compiles these files, and they match no declared input, so editing one ` ++ `changes no hash and ${ROOT_TASK} can replay a cached pass`,+ ).toEqual([]);+ });++ test('the tsconfig the program extends is itself an input', () => {+ const inputs = turboConfig().tasks[ROOT_TASK]?.inputs ?? [];+ const program = JSON.parse(readFileSync(resolve(SUBTREE_ROOT, TSCONFIG), 'utf8')) as {+ extends?: string;+ };+ expect(+ program.extends,+ 'the program must extend a tsconfig for this assertion to mean anything',+ ).toBeDefined();+ const extended = relative(+ SUBTREE_ROOT,+ resolve(dirname(resolve(SUBTREE_ROOT, TSCONFIG)), program.extends ?? ''),+ );+ expect(+ inputs.some((pattern) => matchesInput(extended, pattern)),+ `${extended} sets the compiler options the program runs under and matches no declared input`,+ ).toBe(true);+ });+});diff --git a/turbo.json b/turbo.jsonindex d6b13c43c..ec91747b7 100644--- a/turbo.json+++ b/turbo.json@@ -41,7 +41,15 @@},"lint": {},"typecheck": {- "dependsOn": ["^build"]+ "dependsOn": ["^build", "//#typecheck:no-net-connect"]+ },+ "//#typecheck:no-net-connect": {+ "inputs": [+ "test-support/*.ts",+ "test-support/fixtures/no-net-connect/**/*.ts",+ "test-support/tsconfig.no-net-connect.json",+ "tsconfig.json"+ ]},"@inkeep/open-knowledge#check:dts": {"dependsOn": ["build"],