import { describe, expect, it } from 'vitest';
import {
applyPreviewPassthroughRequestHeaders,
applyPreviewPassthroughResponseHeaders,
classifyPreviewNavigation,
classifyPreviewResourceError,
createPreviewProxyRuntime,
normalizeProxyTargetUrl,
PREVIEW_TARGET_ERROR_HEADER,
rewritePreviewBody,
rewritePreviewCspHeader,
rewritePreviewRedirectLocation,
} from './proxy-runtime.js';
const createResponse = () => {
const headers = new Map();
return {
body: null,
statusCode: 200,
headers,
setHeader(name, value) {
headers.set(name.toLowerCase(), value);
},
removeHeader(name) {
headers.delete(name.toLowerCase());
},
status(code) {
this.statusCode = code;
return this;
},
json(body) {
this.body = body;
return body;
},
};
};
const createAttachedPreviewRuntime = () => {
let proxyOptions;
const postRoutes = new Map();
const useRoutes = new Map();
let randomByte = 0;
const runtime = createPreviewProxyRuntime({
crypto: {
randomBytes(size) {
randomByte += 1;
return Buffer.alloc(size, randomByte);
},
},
URL,
createProxyMiddleware(options) {
proxyOptions = options;
const middleware = () => {};
middleware.upgrade = () => {};
return middleware;
},
responseInterceptor: (handler) => handler,
});
const app = {
post(path, ...handlers) {
postRoutes.set(path, handlers);
},
use(path, ...handlers) {
useRoutes.set(path, handlers);
},
};
runtime.attach(app, {
server: { on() {} },
express: { json: () => (_req, _res, next) => next() },
uiAuthController: null,
isRequestOriginAllowed: async () => true,
rejectWebSocketUpgrade() {},
});
return { postRoutes, proxyOptions: () => proxyOptions, useRoutes };
};
const rewrite = (bodyText, kind) => rewritePreviewBody({
bodyText,
kind,
proxyBasePath: '/api/preview/proxy/abc123',
targetOrigin: 'http://127.0.0.1:3000',
});
describe('preview target failure signaling', () => {
it('marks missing and expired targets instead of relying on the HTTP status alone', () => {
const { useRoutes } = createAttachedPreviewRuntime();
const [guard] = useRoutes.get('/api/preview/proxy');
for (const [originalUrl, code, error] of [
['/api/preview/proxy/', 'missing', 'Preview target not found'],
[`/api/preview/proxy/${'a'.repeat(32)}/`, 'expired', 'Preview target expired'],
]) {
const response = createResponse();
guard({ originalUrl, headers: {} }, response, () => {});
expect(response.statusCode).toBe(404);
expect(response.headers.get(PREVIEW_TARGET_ERROR_HEADER)).toBe(code);
expect(response.body).toEqual({ error });
}
});
it('marks invalid target tokens and accepts a registered target token', async () => {
const { postRoutes, useRoutes } = createAttachedPreviewRuntime();
const [, registerTarget] = postRoutes.get('/api/preview/targets');
const [guard] = useRoutes.get('/api/preview/proxy');
const registrationResponse = createResponse();
await registerTarget({ body: { url: 'http://127.0.0.1:4323/' }, secure: false }, registrationResponse);
const { id, previewToken } = registrationResponse.body;
const invalidResponse = createResponse();
guard({ originalUrl: `/api/preview/proxy/${id}/`, headers: {} }, invalidResponse, () => {});
expect(invalidResponse.statusCode).toBe(403);
expect(invalidResponse.headers.get(PREVIEW_TARGET_ERROR_HEADER)).toBe('invalid-token');
const validResponse = createResponse();
let continued = false;
guard({
originalUrl: `/api/preview/proxy/${id}/?oc_preview_token=${previewToken}`,
headers: {},
}, validResponse, () => {
continued = true;
});
expect(continued).toBe(true);
expect(validResponse.headers.has(PREVIEW_TARGET_ERROR_HEADER)).toBe(false);
});
it('removes the reserved target-error marker from upstream responses', async () => {
const { postRoutes, proxyOptions, useRoutes } = createAttachedPreviewRuntime();
const [, registerTarget] = postRoutes.get('/api/preview/targets');
const registrationResponse = createResponse();
await registerTarget({ body: { url: 'http://127.0.0.1:4323/' }, secure: false }, registrationResponse);
const { id, previewToken } = registrationResponse.body;
const request = {
originalUrl: `/api/preview/proxy/${id}/missing?oc_preview_token=${previewToken}`,
headers: {},
};
const response = createResponse();
response.setHeader(PREVIEW_TARGET_ERROR_HEADER, 'expired');
await proxyOptions().on.proxyRes(
Buffer.from('{"error":"upstream missing"}'),
{ headers: { 'content-type': 'application/json' } },
request,
response,
);
expect(response.headers.has(PREVIEW_TARGET_ERROR_HEADER)).toBe(false);
const [guard] = useRoutes.get('/api/preview/proxy');
let continued = false;
guard(request, createResponse(), () => {
continued = true;
});
expect(continued).toBe(true);
});
});
describe('preview Inertia header passthrough', () => {
it('forwards Inertia request headers to the preview target', () => {
const forwarded = new Map();
const proxyReq = {
setHeader: (name, value) => forwarded.set(name, value),
};
applyPreviewPassthroughRequestHeaders({
headers: {
'x-inertia': 'true',
'x-inertia-version': 'asset-hash',
'x-unrelated': 'ignored',
},
}, proxyReq);
expect(forwarded.get('x-inertia')).toBe('true');
expect(forwarded.get('x-inertia-version')).toBe('asset-hash');
expect(forwarded.has('x-unrelated')).toBe(false);
});
it('forwards Inertia response headers back to the preview client', () => {
const forwarded = new Map();
const res = {
headersSent: false,
setHeader: (name, value) => forwarded.set(name, value),
};
applyPreviewPassthroughResponseHeaders({
headers: {
'x-inertia': 'true',
'x-inertia-location': 'http://127.0.0.1:8000/login',
'x-unrelated': 'ignored',
},
}, res);
expect(forwarded.get('x-inertia')).toBe('true');
expect(forwarded.get('x-inertia-location')).toBe('http://127.0.0.1:8000/login');
expect(forwarded.has('x-unrelated')).toBe(false);
});
});
describe('preview resource error classification', () => {
it('suppresses Astro/Vite stylesheet modules reported as failed scripts', () => {
expect(classifyPreviewResourceError({
tagName: 'script',
url: 'http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc/src/styles/global.css',
})).toBe('suppress');
expect(classifyPreviewResourceError({
tagName: 'script',
url: 'http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc/src/pages/support.astro?astro&type=style&index=0&lang.css',
})).toBe('suppress');
});
it('suppresses framework virtual modules reported by dev servers', () => {
expect(classifyPreviewResourceError({
tagName: 'script',
url: 'http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc/src/layouts/BaseLayout.astro?astro&type=script&index=0&lang.ts',
})).toBe('suppress');
expect(classifyPreviewResourceError({
tagName: 'script',
url: 'http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc/@vite/client',
})).toBe('suppress');
expect(classifyPreviewResourceError({
tagName: 'link',
url: 'http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc/@id/astro:scripts/page.js',
})).toBe('suppress');
});
it('suppresses conservative ecosystem dev-runtime resources', () => {
const noisyResources = [
'/_next/static/chunks/webpack.js',
'/_next/static/chunks/react-refresh.js',
'/.svelte-kit/generated/client/app.js',
'/@id/__x00__virtual:sveltekit:browser',
'/@remix-run/dev/dist/browser.js',
'/__hmr?runtime=remix',
'/_nuxt/@vite/client',
'/_nuxt/@id/virtual:nuxt:%2FUsers%2Fapp',
'/webpack-dev-server/client/index.js',
'/webpack/hot/dev-server.js',
'/__webpack_hmr',
];
for (const resource of noisyResources) {
expect(classifyPreviewResourceError({
tagName: 'script',
url: `http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc${resource}`,
})).toBe('suppress');
}
});
it('keeps ordinary application resource failures visible', () => {
expect(classifyPreviewResourceError({
tagName: 'script',
url: 'http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc/assets/app.js',
})).toBe('report');
expect(classifyPreviewResourceError({
tagName: 'img',
url: 'http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc/missing.png',
})).toBe('report');
expect(classifyPreviewResourceError({
tagName: 'link',
url: 'http://127.0.0.1:57123/api/preview/proxy/f4af70b4261d77706743959516f9cecc/styles/missing.css',
})).toBe('report');
});
});
describe('preview body URL rewriting', () => {
it('rewrites only HTML resource attributes in HTML responses', () => {
const input = '
Docs';
const output = rewrite(input, 'html');
expect(output).toContain('src="/api/preview/proxy/abc123/logo.png"');
expect(output).toContain('href="/api/preview/proxy/abc123/docs"');
expect(output).toContain('const url = "/api/data";');
});
it('rewrites inline module imports in HTML responses', () => {
const input = [
'',
'',
'',
'',
'',
].join('');
const output = rewrite(input, 'html');
expect(output).toContain('from "/api/preview/proxy/abc123/@react-refresh"');
expect(output).toContain('import { injectIntoGlobalHook } from "/api/preview/proxy/abc123/@react-refresh";');
expect(output).toContain('import value from "/api/preview/proxy/abc123/module.js";');
expect(output).toContain('const url = "/api/data";');
expect(output).toContain('import "/api/preview/proxy/abc123/entry.js";');
expect(output).toContain('import "/not-rewritten.js";');
expect(output).toContain('window.__vite_plugin_react_preamble_installed__ = true;');
expect(output).toContain('const refreshUrl = "/@react-refresh";');
});
it('removes CSP meta tags that block the preview bridge', () => {
const input = '