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>
461 lines
19 KiB
JavaScript
461 lines
19 KiB
JavaScript
import http from 'node:http';
|
|
import https from 'node:https';
|
|
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
import { WebSocket, WebSocketServer } from 'ws';
|
|
import assertions from '../security/assertions.cjs';
|
|
|
|
const COOKIE = 'WF_IDE_SESSION';
|
|
const ID = /^[a-zA-Z0-9_-]{1,128}$/;
|
|
const EDIT_ROLES = new Set(['owner', 'admin', 'maintainer', 'developer', 'editor']);
|
|
class HttpError extends Error {
|
|
constructor(status, message) {
|
|
super(message);
|
|
this.status = status;
|
|
}
|
|
}
|
|
const random = () => randomBytes(32).toString('base64url');
|
|
|
|
export function createGateway(config) {
|
|
const publicUrl = new URL(config.publicUrl);
|
|
if (
|
|
!['http:', 'https:'].includes(publicUrl.protocol) ||
|
|
publicUrl.pathname !== '/' ||
|
|
publicUrl.search ||
|
|
publicUrl.username ||
|
|
publicUrl.password
|
|
)
|
|
throw new Error('publicUrl must be an HTTP(S) origin');
|
|
if (!ID.test(config.tenantId) || !config.serviceToken)
|
|
throw new Error('A fixed tenantId and gateway serviceToken are required');
|
|
const upstreamOrigins = new Set(config.allowedUpstreamOrigins);
|
|
const collaborationOrigins = new Set(config.allowedCollaborationOrigins ?? []);
|
|
const serviceNamespace = config.allowedServiceNamespace;
|
|
if (serviceNamespace && (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(serviceNamespace) || serviceNamespace.length > 63))
|
|
throw new Error('Invalid service namespace');
|
|
if (!upstreamOrigins.size && !serviceNamespace) throw new Error('Explicit upstream allowlist required');
|
|
const fetchImpl = config.fetchImpl ?? fetch;
|
|
const sessions = new Map();
|
|
const launches = new Map();
|
|
// Theia's own process token is distinct from the caller's authentication.
|
|
// Keep it server-side, scoped to an allowed upstream, never in browser cookies.
|
|
const upstreamTokens = new Map();
|
|
const sockets = new Set();
|
|
const workspaceSockets = new Map();
|
|
const rawSockets = new Set();
|
|
const sessionTtl = Math.min(config.sessionTtlMs ?? 900000, 900000);
|
|
const pollMs = Math.min(config.reauthorizeMs ?? 1000, 1000);
|
|
const now = () => Date.now();
|
|
const purge = () => {
|
|
for (const map of [sessions, launches])
|
|
for (const [key, value] of map) if (value.expiresAt <= now()) map.delete(key);
|
|
};
|
|
const timer = setInterval(purge, 5000);
|
|
timer.unref();
|
|
const wss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024, perMessageDeflate: false });
|
|
|
|
async function authorize(workspaceId, userToken, operation, collaboration = false) {
|
|
if (!ID.test(workspaceId) || !userToken || userToken.length > 16384)
|
|
throw new HttpError(401, 'Authentication required');
|
|
let response;
|
|
try {
|
|
response = await fetchImpl(
|
|
`${config.apiOrigin}/internal/workspaces/${encodeURIComponent(workspaceId)}/authorize`,
|
|
{
|
|
method: 'POST',
|
|
headers: {
|
|
authorization: `Bearer ${config.serviceToken}`,
|
|
'content-type': 'application/json',
|
|
'X-WishForge-Tenant': config.tenantId,
|
|
},
|
|
body: JSON.stringify({ userToken, operation }),
|
|
signal: AbortSignal.timeout(3000),
|
|
redirect: 'error',
|
|
},
|
|
);
|
|
} catch {
|
|
throw new HttpError(503, 'Workspace authorization unavailable');
|
|
}
|
|
if (!response.ok)
|
|
throw new HttpError([401, 403, 404].includes(response.status) ? response.status : 503, 'Workspace access denied');
|
|
const payload = await response.json();
|
|
const grant = payload.data ?? payload;
|
|
if (
|
|
grant.tenantId !== config.tenantId ||
|
|
grant.workspaceId !== workspaceId ||
|
|
!grant.projectId ||
|
|
!EDIT_ROLES.has(grant.role)
|
|
)
|
|
throw new HttpError(403, 'Workspace grant mismatch');
|
|
let upstream;
|
|
try {
|
|
upstream = new URL(collaboration ? grant.collaborationUpstreamUrl : grant.upstreamUrl);
|
|
} catch {
|
|
throw new HttpError(502, 'Invalid workspace upstream');
|
|
}
|
|
const origins = collaboration ? collaborationOrigins : upstreamOrigins;
|
|
const serviceAllowed =
|
|
serviceNamespace &&
|
|
upstream.protocol === 'http:' &&
|
|
upstream.port === (collaboration ? '8100' : '3000') &&
|
|
new RegExp(`^wf-ide-[a-f0-9]{24}\\.${serviceNamespace}\\.svc(?:\\.cluster\\.local)?$`).test(upstream.hostname);
|
|
if (
|
|
(!origins.has(upstream.origin) && !serviceAllowed) ||
|
|
!['http:', 'https:'].includes(upstream.protocol) ||
|
|
upstream.username ||
|
|
upstream.password ||
|
|
upstream.search ||
|
|
upstream.hash
|
|
)
|
|
throw new HttpError(502, 'Workspace upstream is not permitted');
|
|
return { ...grant, upstream };
|
|
}
|
|
function tokenFor(req, workspaceId) {
|
|
const authorization = req.headers.authorization;
|
|
if (authorization?.startsWith('Bearer '))
|
|
return { userToken: authorization.slice(7), expiresAt: Number.MAX_SAFE_INTEGER };
|
|
const opaque = req.headers.cookie
|
|
?.split(';')
|
|
.map(v => v.trim())
|
|
.find(v => v.startsWith(`${COOKIE}=`))
|
|
?.slice(COOKIE.length + 1);
|
|
const session = opaque && sessions.get(opaque);
|
|
if (!session || session.expiresAt <= now() || session.workspaceId !== workspaceId)
|
|
throw new HttpError(401, 'Launch an authenticated IDE session');
|
|
return session;
|
|
}
|
|
function originCheck(req, required = false) {
|
|
if ((required && !req.headers.origin) || (req.headers.origin && req.headers.origin !== publicUrl.origin))
|
|
throw new HttpError(403, 'Origin not allowed');
|
|
}
|
|
function route(req) {
|
|
const parsed = new URL(req.url, publicUrl);
|
|
const match = parsed.pathname.match(/^\/workspaces\/([a-zA-Z0-9_-]{1,128})(\/.*)?$/);
|
|
if (!match) throw new HttpError(404, 'Workspace route not found');
|
|
let suffix = match[2] ?? '/';
|
|
const collaboration = suffix === '/collaboration' || suffix.startsWith('/collaboration/');
|
|
if (collaboration) suffix = suffix.slice('/collaboration'.length) || '/';
|
|
// Multiplexed Theia services need edit permission. Callers cannot downgrade
|
|
// this to preview by supplying a query parameter or header.
|
|
const operation = collaboration
|
|
? 'edit'
|
|
: /\/terminals?(?:\/|$)/.test(suffix)
|
|
? 'terminal'
|
|
: /\/debug(?:\/|$)/.test(suffix)
|
|
? 'debug'
|
|
: 'edit';
|
|
return { workspaceId: match[1], suffix, query: parsed.search, operation, collaboration };
|
|
}
|
|
function targetFor(grant, routing) {
|
|
const target = new URL(grant.upstream);
|
|
target.pathname = `${target.pathname.replace(/\/$/, '')}${routing.suffix}`;
|
|
target.search = routing.query;
|
|
return target;
|
|
}
|
|
function proxyHeaders(req, target, grant) {
|
|
const headers = { ...req.headers };
|
|
for (const key of Object.keys(headers))
|
|
if (
|
|
[
|
|
'authorization',
|
|
'cookie',
|
|
'connection',
|
|
'upgrade',
|
|
'proxy-authorization',
|
|
'proxy-authenticate',
|
|
'te',
|
|
'trailer',
|
|
'transfer-encoding',
|
|
].includes(key) ||
|
|
key.startsWith('x-forwarded-') ||
|
|
key.startsWith('x-wishforge-') ||
|
|
key.startsWith('sec-websocket-')
|
|
)
|
|
delete headers[key];
|
|
headers.host = target.host;
|
|
headers.origin = target.origin;
|
|
headers['x-forwarded-host'] = publicUrl.host;
|
|
headers['x-forwarded-proto'] = publicUrl.protocol.slice(0, -1);
|
|
headers['x-wishforge-tenant'] = grant.tenantId;
|
|
headers['x-wishforge-workspace'] = grant.workspaceId;
|
|
if (config.assertionPrivateKey)
|
|
headers['x-wishforge-actor-assertion'] = assertions.signAssertion(config.assertionPrivateKey, grant);
|
|
const token = upstreamTokens.get(grant.upstream.href);
|
|
if (token) headers.cookie = `theia-connection-token=${token}`;
|
|
return headers;
|
|
}
|
|
function fail(res, error) {
|
|
if (res.headersSent) {
|
|
res.destroy();
|
|
return;
|
|
}
|
|
res.writeHead(error.status ?? 500, {
|
|
'content-type': 'application/json',
|
|
'cache-control': 'no-store',
|
|
'referrer-policy': 'no-referrer',
|
|
});
|
|
res.end(JSON.stringify({ error: error.status ? error.message : 'Gateway error' }));
|
|
}
|
|
async function readJson(req) {
|
|
let body = '';
|
|
for await (const chunk of req) {
|
|
body += chunk;
|
|
if (body.length > 2048) throw new HttpError(413, 'Request too large');
|
|
}
|
|
try {
|
|
return JSON.parse(body);
|
|
} catch {
|
|
throw new HttpError(400, 'Invalid JSON');
|
|
}
|
|
}
|
|
const server = http.createServer(async (req, res) => {
|
|
try {
|
|
const url = new URL(req.url, publicUrl);
|
|
if (url.pathname === '/healthz' && req.method === 'GET') {
|
|
res.writeHead(200);
|
|
res.end('ok');
|
|
return;
|
|
}
|
|
if (
|
|
['/internal/integration-state', '/internal/lifecycle-state'].includes(url.pathname) &&
|
|
req.method === 'POST'
|
|
) {
|
|
const lifecycle = url.pathname === '/internal/lifecycle-state';
|
|
const supplied = req.headers.authorization?.startsWith('Bearer ') ? req.headers.authorization.slice(7) : '';
|
|
const expected = Buffer.from(config.serviceToken),
|
|
actual = Buffer.from(supplied);
|
|
if (actual.length !== expected.length || !timingSafeEqual(actual, expected) || !config.assertionPrivateKey)
|
|
throw new HttpError(401, 'Integration service authentication required');
|
|
const body = await readJson(req);
|
|
if (
|
|
body.tenantId !== config.tenantId ||
|
|
!ID.test(body.workspaceId ?? '') ||
|
|
(!lifecycle && !ID.test(body.runId ?? ''))
|
|
)
|
|
throw new HttpError(400, 'Invalid integration scope');
|
|
const authorized = await fetchImpl(
|
|
`${config.apiOrigin}/internal/workspaces/${body.workspaceId}/${lifecycle ? 'lifecycle-authorize' : 'integration-authorize'}`,
|
|
{
|
|
method: 'POST',
|
|
headers: {
|
|
authorization: `Bearer ${config.serviceToken}`,
|
|
'content-type': 'application/json',
|
|
'X-WishForge-Tenant': config.tenantId,
|
|
},
|
|
body: JSON.stringify(
|
|
lifecycle ? {} : { runId: body.runId, generation: body.generation, revision: body.revision },
|
|
),
|
|
redirect: 'error',
|
|
signal: AbortSignal.timeout(3000),
|
|
},
|
|
);
|
|
if (!authorized.ok) throw new HttpError(403, 'Integration scope denied');
|
|
const payload = await authorized.json();
|
|
const grant = payload.data ?? payload;
|
|
if (
|
|
grant.tenantId !== config.tenantId ||
|
|
grant.workspaceId !== body.workspaceId ||
|
|
grant.purpose !== (lifecycle ? 'workspace-lifecycle' : 'integration-state')
|
|
)
|
|
throw new HttpError(403, 'Integration grant mismatch');
|
|
const target = new URL(grant.upstreamUrl);
|
|
const managed =
|
|
serviceNamespace &&
|
|
target.protocol === 'http:' &&
|
|
target.port === '3000' &&
|
|
new RegExp(`^wf-ide-[a-f0-9]{24}\\.${serviceNamespace}\\.svc(?:\\.cluster\\.local)?$`).test(target.hostname);
|
|
if (
|
|
(!upstreamOrigins.has(target.origin) && !managed) ||
|
|
target.username ||
|
|
target.password ||
|
|
target.search ||
|
|
target.hash
|
|
)
|
|
throw new HttpError(502, 'Integration upstream denied');
|
|
const response = await fetchImpl(
|
|
new URL(lifecycle ? '/_wishforge/lifecycle/state' : '/_wishforge/integration/state', target),
|
|
{
|
|
headers: { 'x-wishforge-actor-assertion': assertions.signAssertion(config.assertionPrivateKey, grant) },
|
|
redirect: 'error',
|
|
signal: AbortSignal.timeout(10000),
|
|
},
|
|
);
|
|
if (!response.ok) throw new HttpError(503, 'Workspace input state unavailable');
|
|
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
const receipt = await response.json();
|
|
res.end(
|
|
JSON.stringify(
|
|
lifecycle ? { ...receipt, gatewayConnections: workspaceSockets.get(body.workspaceId)?.size ?? 0 } : receipt,
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
if (url.pathname === '/launch' && req.method === 'POST') {
|
|
originCheck(req);
|
|
const userToken = req.headers.authorization?.startsWith('Bearer ')
|
|
? req.headers.authorization.slice(7)
|
|
: undefined;
|
|
const body = await readJson(req);
|
|
if (!body || Object.keys(body).some(key => key !== 'workspaceId') || !ID.test(body.workspaceId ?? ''))
|
|
throw new HttpError(400, 'workspaceId is required');
|
|
await authorize(body.workspaceId, userToken, 'edit');
|
|
purge();
|
|
if (launches.size >= 1000 || sessions.size >= 1000) throw new HttpError(429, 'Session capacity reached');
|
|
const code = random();
|
|
launches.set(code, { workspaceId: body.workspaceId, userToken, expiresAt: now() + 30000 });
|
|
res.writeHead(200, {
|
|
'content-type': 'application/json',
|
|
'cache-control': 'no-store',
|
|
'referrer-policy': 'no-referrer',
|
|
});
|
|
res.end(
|
|
JSON.stringify({ launchUrl: `${publicUrl.origin}/session?code=${encodeURIComponent(code)}`, expiresIn: 30 }),
|
|
);
|
|
return;
|
|
}
|
|
if (url.pathname === '/session' && req.method === 'GET') {
|
|
const code = url.searchParams.get('code');
|
|
const launch = launches.get(code);
|
|
launches.delete(code);
|
|
if (!launch || launch.expiresAt <= now()) throw new HttpError(401, 'Launch code is invalid or expired');
|
|
await authorize(launch.workspaceId, launch.userToken, 'edit');
|
|
const opaque = random();
|
|
sessions.set(opaque, { ...launch, expiresAt: now() + sessionTtl });
|
|
res.writeHead(303, {
|
|
location: `/workspaces/${launch.workspaceId}/`,
|
|
'set-cookie': `${COOKIE}=${opaque}; HttpOnly; SameSite=Strict; Path=/workspaces/${launch.workspaceId}/; Max-Age=${Math.floor(sessionTtl / 1000)}${publicUrl.protocol === 'https:' ? '; Secure' : ''}`,
|
|
'cache-control': 'no-store',
|
|
'referrer-policy': 'no-referrer',
|
|
});
|
|
res.end();
|
|
return;
|
|
}
|
|
originCheck(req);
|
|
const routing = route(req);
|
|
const session = tokenFor(req, routing.workspaceId);
|
|
const grant = await authorize(routing.workspaceId, session.userToken, routing.operation, routing.collaboration);
|
|
const target = targetFor(grant, routing);
|
|
const proxy = (target.protocol === 'https:' ? https : http).request(
|
|
target,
|
|
{ method: req.method, headers: proxyHeaders(req, target, grant) },
|
|
upstream => {
|
|
const headers = { ...upstream.headers, 'referrer-policy': 'no-referrer', 'cache-control': 'no-store' };
|
|
for (const cookie of upstream.headers['set-cookie'] ?? []) {
|
|
const token = /^theia-connection-token=([^;\s]{1,512})(?:;|$)/.exec(cookie)?.[1];
|
|
if (token) upstreamTokens.set(grant.upstream.href, token);
|
|
}
|
|
delete headers['set-cookie'];
|
|
if (headers.location) {
|
|
const location = new URL(headers.location, target);
|
|
if (location.origin === target.origin)
|
|
headers.location = `/workspaces/${routing.workspaceId}${routing.collaboration ? '/collaboration' : ''}${location.pathname}${location.search}${location.hash}`;
|
|
}
|
|
res.writeHead(upstream.statusCode ?? 502, headers);
|
|
upstream.pipe(res);
|
|
},
|
|
);
|
|
proxy.on('error', () => fail(res, new HttpError(502, 'Workspace upstream unavailable')));
|
|
proxy.setTimeout(30000, () => proxy.destroy());
|
|
req.on('aborted', () => proxy.destroy());
|
|
res.on('close', () => proxy.destroy());
|
|
req.pipe(proxy);
|
|
} catch (error) {
|
|
fail(res, error);
|
|
}
|
|
});
|
|
server.on('connection', socket => {
|
|
rawSockets.add(socket);
|
|
socket.once('close', () => rawSockets.delete(socket));
|
|
});
|
|
server.on('upgrade', async (req, socket, head) => {
|
|
socket.on('error', () => {});
|
|
try {
|
|
originCheck(req, !req.headers.authorization);
|
|
const routing = route(req);
|
|
const session = tokenFor(req, routing.workspaceId);
|
|
const grant = await authorize(routing.workspaceId, session.userToken, routing.operation, routing.collaboration);
|
|
const target = targetFor(grant, routing);
|
|
target.protocol = target.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
const protocols = req.headers['sec-websocket-protocol']
|
|
?.split(',')
|
|
.map(p => p.trim())
|
|
.filter(Boolean);
|
|
const upstream = new WebSocket(target, protocols, {
|
|
headers: proxyHeaders(req, grant.upstream, grant),
|
|
maxPayload: 16 * 1024 * 1024,
|
|
handshakeTimeout: 5000,
|
|
perMessageDeflate: false,
|
|
});
|
|
let accepted = false;
|
|
upstream.once('error', () => {
|
|
if (!accepted) socket.destroy();
|
|
});
|
|
socket.once('close', () => {
|
|
if (!accepted) upstream.terminate();
|
|
});
|
|
upstream.once('open', () =>
|
|
wss.handleUpgrade(req, socket, head, client => {
|
|
accepted = true;
|
|
sockets.add(client);
|
|
const workspaceSet = workspaceSockets.get(routing.workspaceId) ?? new Set();
|
|
workspaceSockets.set(routing.workspaceId, workspaceSet);
|
|
workspaceSet.add(client);
|
|
const close = () => {
|
|
clearInterval(poll);
|
|
sockets.delete(client);
|
|
workspaceSet.delete(client);
|
|
if (!workspaceSet.size) workspaceSockets.delete(routing.workspaceId);
|
|
client.terminate();
|
|
upstream.terminate();
|
|
};
|
|
client.on('message', (data, binary) => {
|
|
if (upstream.readyState === WebSocket.OPEN) upstream.send(data, { binary });
|
|
});
|
|
upstream.on('message', (data, binary) => {
|
|
if (client.readyState === WebSocket.OPEN) client.send(data, { binary });
|
|
});
|
|
client.on('close', close);
|
|
upstream.on('close', close);
|
|
client.on('error', close);
|
|
upstream.on('error', close);
|
|
let checking = false;
|
|
const poll = setInterval(async () => {
|
|
if (checking) return;
|
|
checking = true;
|
|
try {
|
|
if (session.expiresAt <= now()) throw new Error('Session expired');
|
|
const fresh = await authorize(
|
|
routing.workspaceId,
|
|
session.userToken,
|
|
routing.operation,
|
|
routing.collaboration,
|
|
);
|
|
if (fresh.upstream.href !== grant.upstream.href) throw new Error('Workspace moved');
|
|
} catch {
|
|
close();
|
|
} finally {
|
|
checking = false;
|
|
}
|
|
}, pollMs);
|
|
poll.unref();
|
|
}),
|
|
);
|
|
} catch (error) {
|
|
socket.end(`HTTP/1.1 ${error.status ?? 500} Access Denied\r\nConnection: close\r\n\r\n`);
|
|
}
|
|
});
|
|
server.on('close', () => {
|
|
clearInterval(timer);
|
|
for (const client of sockets) client.terminate();
|
|
wss.close();
|
|
});
|
|
return {
|
|
server,
|
|
close: async () => {
|
|
for (const client of sockets) client.terminate();
|
|
for (const socket of rawSockets) socket.destroy();
|
|
await new Promise(resolve => server.close(resolve));
|
|
},
|
|
sessionCount: () => sessions.size,
|
|
};
|
|
}
|