eust-w 0ef99b1e6d style: add Prettier and EditorConfig, format the codebase
Adds prettier 3.9.8 (exact) with a shared config (single quotes,
120 columns, trailing commas), .prettierignore, .editorconfig and the
`format` / `format:check` scripts, then formats all TypeScript,
JavaScript, CSS, JSON and YAML sources.

Purely mechanical: no behaviour change. Typecheck passes, the vitest
suite and the 74 IDE node tests produce the same results as before
(socket-binding tests still cannot run inside this sandbox).
Previously the longest source line was ~3000 characters; reviewing the
following semantic changes now produces readable diffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:32:43 +08:00

472 lines
17 KiB
JavaScript

import http from 'node:http';
import https from 'node:https';
import { createPrivateKey } from 'node:crypto';
import { bodySha256, signPreviewProof } from './proof.mjs';
const ID = /^[A-Za-z0-9_-]{1,128}$/;
const CAP = /^[A-Za-z0-9_-]{43}$/;
const CHALLENGE = /^[A-Za-z0-9_-]{32,128}$/;
const HOP = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'te',
'trailer',
'transfer-encoding',
'upgrade',
]);
class Failure extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
export function createPreviewGateway(config) {
const publicUrl = new URL(config.publicOrigin),
upstream = new URL(config.upstreamOrigin),
api = new URL(config.apiOrigin);
for (const value of [publicUrl, upstream, api])
if (
!['http:', 'https:'].includes(value.protocol) ||
value.username ||
value.password ||
value.pathname !== '/' ||
value.search ||
value.hash
)
throw new Error('Explicit credential-free origins required');
if (config.production !== false && (publicUrl.protocol !== 'https:' || api.protocol !== 'https:'))
throw new Error('Production public and API origins require HTTPS');
if (
config.production === false &&
publicUrl.protocol === 'http:' &&
!['127.0.0.1', 'localhost', '[::1]'].includes(publicUrl.hostname)
)
throw new Error('Development plaintext preview is loopback only');
if (
publicUrl.origin === upstream.origin ||
publicUrl.hostname === api.hostname ||
!ID.test(config.tenantId) ||
!ID.test(config.environmentId) ||
!ID.test(config.projectId) ||
typeof config.serviceToken !== 'string' ||
config.serviceToken.length < 32 ||
createPrivateKey(config.proofPrivateKey).asymmetricKeyType !== 'ed25519'
)
throw new Error('Scoped preview configuration and independent Ed25519 key required');
const fetcher = config.fetchImpl ?? fetch,
secure = publicUrl.protocol === 'https:',
cookieName = secure ? '__Host-WF_PREVIEW_SESSION' : 'WF_PREVIEW_SESSION';
const pollMs = Math.max(20, Math.min(config.reauthorizeMs ?? 3000, 5000)),
active = new Set(),
sockets = new Set();
function host(req) {
if (req.headers.host !== publicUrl.host) throw new Failure(421, 'Unknown preview host');
}
function origin(req, required = false) {
if ((required && !req.headers.origin) || (req.headers.origin && req.headers.origin !== publicUrl.origin))
throw new Failure(403, 'Preview origin denied');
}
function route(req) {
if (!req.url?.startsWith('/') || req.url.startsWith('//') || req.url.includes('\\'))
throw new Failure(400, 'Invalid preview path');
const url = new URL(req.url, publicUrl);
if (url.origin !== publicUrl.origin) throw new Failure(400, 'Invalid preview path');
return url;
}
function credential(req) {
const values = (req.headers.cookie ?? '')
.split(';')
.map(value => value.trim())
.filter(value => value.startsWith(`${cookieName}=`));
if (values.length !== 1) throw new Failure(401, 'Private preview authentication required');
const value = values[0].slice(cookieName.length + 1);
if (!CAP.test(value)) throw new Failure(401, 'Private preview authentication required');
return value;
}
async function authorize(kind, value, method, path, challenge) {
if (!CAP.test(value ?? '')) throw new Failure(401, 'Private preview authentication required');
let response;
try {
response = await fetcher(`${api.origin}/preview-control/authorize`, {
method: 'POST',
headers: { authorization: `Bearer ${config.serviceToken}`, 'content-type': 'application/json' },
body: JSON.stringify({
tenantId: config.tenantId,
environmentId: config.environmentId,
kind,
credential: value,
method,
path,
...(kind === 'probe' ? { challenge } : {}),
}),
redirect: 'error',
signal: AbortSignal.timeout(3000),
});
} catch {
throw new Failure(503, 'Preview authorization unavailable');
}
if (!response.ok)
throw new Failure(
[401, 403, 404].includes(response.status) ? response.status : 503,
'Private preview authorization denied',
);
const payload = await response.json(),
grant = payload.data ?? payload;
if (
grant.tenantId !== config.tenantId ||
grant.environmentId !== config.environmentId ||
grant.projectId !== config.projectId ||
grant.publicOrigin !== publicUrl.origin ||
!grant.releaseId ||
!grant.bindingDigest ||
!Number.isFinite(Date.parse(grant.expiresAt)) ||
Date.parse(grant.expiresAt) <= Date.now() ||
(kind === 'probe' && grant.role !== 'probe') ||
(kind !== 'probe' && !['owner', 'admin', 'developer', 'deployer', 'viewer'].includes(grant.role))
)
throw new Failure(403, 'Preview grant mismatch');
let destination;
try {
destination = new URL(grant.applicationUrl);
} catch {
throw new Failure(403, 'Preview application URL missing');
}
if (
destination.origin !== publicUrl.origin ||
destination.username ||
destination.password ||
destination.pathname.startsWith('/_wishforge/')
)
throw new Failure(403, 'Preview application URL mismatch');
if (grant.role === 'viewer' && !['GET', 'HEAD'].includes(method))
throw new Failure(403, 'Viewer access is read-only');
return grant;
}
function baseHeaders() {
return {
'cache-control': 'no-store',
'referrer-policy': 'no-referrer',
'x-content-type-options': 'nosniff',
'origin-agent-cluster': '?1',
'cross-origin-opener-policy': 'same-origin',
};
}
function proof(req, grant, decision, status, body) {
const challenge = req.headers['x-wishforge-preview-challenge'];
if (!CHALLENGE.test(challenge ?? '')) return undefined;
const issuedAt = Date.now();
return signPreviewProof(config.proofPrivateKey, {
schemaVersion: 1,
tenantId: config.tenantId,
environmentId: config.environmentId,
publicOrigin: publicUrl.origin,
releaseId: grant?.releaseId ?? null,
bindingDigest: grant?.bindingDigest ?? null,
policyDigest: grant?.policyDigest ?? null,
capabilitySha256: decision === 'authorized' ? bodySha256(req.headers['x-wishforge-preview-capability']) : null,
challenge,
decision,
method: req.method,
path: req.url,
status,
bodySha256: bodySha256(body),
issuedAt,
expiresAt: issuedAt + 120000,
});
}
function fail(req, res, error, anonymous = false) {
if (res.headersSent) {
res.destroy();
return;
}
const status = error.status ?? 502,
body = Buffer.from(
JSON.stringify({
error:
status === 401
? 'Private preview authentication required'
: error.status
? error.message
: 'Preview unavailable',
}),
),
headers = { ...baseHeaders(), 'content-type': 'application/json', 'content-length': String(body.length) };
if (anonymous && status === 401) {
const signed = proof(req, undefined, 'anonymous_denied', status, body);
if (signed) headers['x-wishforge-preview-proof'] = signed;
}
res.writeHead(status, headers);
res.end(body);
}
function proxyHeaders(req, websocket = false) {
const headers = { ...req.headers },
connectionFields = String(headers.connection ?? '')
.split(',')
.map(value => value.trim().toLowerCase());
for (const key of Object.keys(headers))
if (
HOP.has(key) ||
connectionFields.includes(key) ||
['authorization', 'host', 'origin', 'referer'].includes(key) ||
key.startsWith('x-forwarded-') ||
key.startsWith('x-wishforge-')
)
delete headers[key];
const appCookies = (req.headers.cookie ?? '')
.split(';')
.map(value => value.trim())
.filter(value => value && !value.startsWith(`${cookieName}=`) && !/^(__Host-)?WF_/i.test(value));
if (appCookies.length) headers.cookie = appCookies.join('; ');
else delete headers.cookie;
headers.host = upstream.host;
headers.origin = upstream.origin;
if (websocket) {
headers.connection = 'Upgrade';
headers.upgrade = 'websocket';
}
return headers;
}
function responseHeaders(raw) {
const headers = {};
for (const [key, value] of Object.entries(raw)) {
if (
value === undefined ||
HOP.has(key) ||
key.startsWith('x-wishforge-') ||
key.startsWith('access-control-') ||
[
'server',
'x-powered-by',
'content-location',
'refresh',
'link',
'access-control-allow-origin',
'access-control-allow-credentials',
].includes(key)
)
continue;
if (key === 'set-cookie') {
headers[key] = (Array.isArray(value) ? value : [value])
.filter(item => !/^\s*(?:__Host-)?WF_/i.test(item))
.map(
item =>
item.replace(/;\s*domain=[^;]*/gi, '') + (secure && !/;\s*secure(?:;|$)/i.test(item) ? '; Secure' : ''),
);
continue;
}
if (key === 'location') {
const location = new URL(String(value), upstream);
if (location.origin !== upstream.origin)
throw new Failure(502, 'External application redirect is not permitted');
headers.location = `${publicUrl.origin}${location.pathname}${location.search}${location.hash}`;
continue;
}
headers[key] = value;
}
return { ...headers, ...baseHeaders() };
}
function watch(kind, value, method, path, stop) {
let busy = false,
closed = false;
const timer = setInterval(async () => {
if (busy || closed) return;
busy = true;
try {
await authorize(kind, value, method, path);
} catch {
stop();
} finally {
busy = false;
}
}, pollMs);
timer.unref();
const close = () => {
closed = true;
clearInterval(timer);
active.delete(close);
};
active.add(close);
return close;
}
const server = http.createServer(async (req, res) => {
let anonymous = false;
try {
host(req);
const url = route(req);
if (url.pathname === '/_wishforge/session' && req.method === 'GET') {
const grant = await authorize('launch', url.searchParams.get('code'), 'GET', '/');
if (!CAP.test(grant.sessionToken ?? '')) throw new Failure(502, 'Invalid preview session');
res.writeHead(303, {
...baseHeaders(),
location: new URL(grant.applicationUrl).href,
'set-cookie': `${cookieName}=${grant.sessionToken}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${Math.max(0, Math.min(900, Math.floor((Date.parse(grant.expiresAt) - Date.now()) / 1000)))}${secure ? '; Secure' : ''}`,
});
res.end();
return;
}
if (url.pathname.startsWith('/_wishforge/')) throw new Failure(404, 'Reserved preview path');
const isProbe = typeof req.headers['x-wishforge-preview-capability'] === 'string';
let value;
if (isProbe) {
value = req.headers['x-wishforge-preview-capability'];
if (!CHALLENGE.test(req.headers['x-wishforge-preview-challenge'] ?? ''))
throw new Failure(400, 'Release probe challenge required');
if (!['GET', 'HEAD'].includes(req.method)) throw new Failure(403, 'Read-only release probe required');
} else {
try {
value = credential(req);
} catch (error) {
anonymous = true;
throw error;
}
origin(req, !['GET', 'HEAD'].includes(req.method));
}
const kind = isProbe ? 'probe' : 'session',
grant = await authorize(kind, value, req.method, req.url, req.headers['x-wishforge-preview-challenge']);
if (
req.headers['content-length'] !== undefined &&
(!/^\d+$/.test(req.headers['content-length']) || Number(req.headers['content-length']) > 8 * 1024 * 1024)
)
throw new Failure(413, 'Preview request exceeds 8 MiB');
const target = new URL(req.url, upstream);
if (isProbe) {
const response = await fetcher(target, {
method: req.method,
headers: { accept: '*/*', 'accept-encoding': 'identity' },
redirect: 'manual',
signal: AbortSignal.timeout(15000),
});
const chunks = [];
let size = 0;
if (response.body)
for await (const chunk of response.body) {
size += chunk.length;
if (size > 4 * 1024 * 1024) throw new Failure(502, 'Preview probe exceeds body limit');
chunks.push(chunk);
}
const body = Buffer.concat(chunks);
await authorize(kind, value, req.method, req.url, req.headers['x-wishforge-preview-challenge']);
const signed = proof(req, grant, 'authorized', response.status, body),
headers = responseHeaders(Object.fromEntries(response.headers));
delete headers['content-encoding'];
headers['content-length'] = String(body.length);
headers['x-wishforge-preview-proof'] = signed;
res.writeHead(response.status, headers);
res.end(req.method === 'HEAD' ? undefined : body);
return;
}
const transport = target.protocol === 'https:' ? https : http;
const forward = transport.request(target, { method: req.method, headers: proxyHeaders(req) }, response => {
try {
res.writeHead(response.statusCode ?? 502, responseHeaders(response.headers));
response.pipe(res);
} catch (error) {
response.destroy();
fail(req, res, error);
}
});
forward.setTimeout(60000, () => forward.destroy());
forward.on('error', () => fail(req, res, new Failure(502, 'Preview upstream unavailable')));
const endWatch = watch(kind, value, req.method, req.url, () => {
forward.destroy();
res.destroy();
});
res.on('close', () => {
endWatch();
forward.destroy();
});
req.on('aborted', () => forward.destroy());
let received = 0;
req.on('data', chunk => {
received += chunk.length;
if (received > 8 * 1024 * 1024) {
req.unpipe(forward);
forward.destroy();
fail(req, res, new Failure(413, 'Preview request exceeds 8 MiB'));
}
});
req.pipe(forward);
} catch (error) {
fail(req, res, error, anonymous);
}
});
server.on('connection', socket => {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
});
server.on('upgrade', async (req, socket, head) => {
try {
host(req);
origin(req, true);
const url = route(req);
if (url.pathname.startsWith('/_wishforge/')) throw new Failure(404, 'Reserved preview path');
const value = credential(req);
await authorize('session', value, 'WS', req.url);
const target = new URL(req.url, upstream),
transport = target.protocol === 'https:' ? https : http;
const forward = transport.request(target, { method: 'GET', headers: proxyHeaders(req, true) });
forward.setTimeout(10000, () => forward.destroy());
forward.on('upgrade', (response, peer, peerHead) => {
if (response.statusCode !== 101) {
peer.destroy();
socket.destroy();
return;
}
let headers;
try {
headers = responseHeaders(response.headers);
} catch {
peer.destroy();
socket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n');
return;
}
headers.connection = 'Upgrade';
headers.upgrade = 'websocket';
socket.write(
`HTTP/1.1 101 Switching Protocols\r\n${Object.entries(headers)
.flatMap(([key, value]) => (Array.isArray(value) ? value : [value]).map(item => `${key}: ${item}`))
.join('\r\n')}\r\n\r\n`,
);
if (head.length) peer.write(head);
if (peerHead.length) socket.write(peerHead);
socket.pipe(peer);
peer.pipe(socket);
const endWatch = watch('session', value, 'WS', req.url, () => {
peer.destroy();
socket.destroy();
});
socket.on('close', () => {
endWatch();
peer.destroy();
});
peer.on('close', () => {
endWatch();
socket.destroy();
});
peer.on('error', () => socket.destroy());
socket.on('error', () => peer.destroy());
});
forward.on('response', response => {
response.resume();
socket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n');
});
forward.on('error', () => socket.destroy());
socket.on('close', () => forward.destroy());
forward.end();
} catch (error) {
socket.end(`HTTP/1.1 ${error.status ?? 502} Access Denied\r\nConnection: close\r\n\r\n`);
}
});
return {
server,
cookieName,
async close() {
for (const end of active) end();
for (const socket of sockets) socket.destroy();
if (server.listening) await new Promise(resolve => server.close(resolve));
},
};
}