eust-w a2a02f2978 🔒 Cap IDE launch codes and sessions per person
The gateway refused new launches once 1000 codes or sessions existed in
total, so one member could crowd everyone else out for as long as the
sessions lived. Each person now holds at most 20 of each; beyond that
their own oldest ends, and its open connections close at their next
check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 22:22:11 +08:00

484 lines
20 KiB
JavaScript

import http from 'node:http';
import https from 'node:https';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { WebSocket, WebSocketServer } from 'ws';
import { createGitCredentials, CREDENTIAL_PATH } from './git-credentials.mjs';
const COOKIE = 'WF_IDE_SESSION';
const ID = /^[a-zA-Z0-9_-]{1,128}$/;
// The roles defined by @wishforge/contracts that may edit, use terminals and debug.
const EDIT_ROLES = new Set(['owner', 'admin', 'developer']);
class HttpError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
const random = () => randomBytes(32).toString('base64url');
/** The commit identity the control plane derived from the person's sign-in, if it is usable. */
function validAuthor(author) {
const text = value =>
typeof value === 'string' && value.length > 0 && value.length <= 200 && !/[\u0000-\u001f\u007f<>]/.test(value);
return author && text(author.name) && text(author.email) && /^[^\s@]+@[^\s@]+$/.test(author.email)
? { name: author.name, email: author.email }
: undefined;
}
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();
// A session ends after 15 idle minutes; while it is used it is renewed, for at most 12 hours.
const sessionTtl = Math.min(config.sessionTtlMs ?? 900000, 900000);
const sessionMaxMs = Math.min(config.sessionMaxMs ?? 12 * 3600_000, 12 * 3600_000);
const pollMs = Math.min(config.reauthorizeMs ?? 1000, 1000);
// An upstream that stays silent this long is given up. OCT holds each login poll open for 30 s
// before answering, so collaboration requests get longer than that.
const upstreamTimeoutMs = config.upstreamTimeoutMs ?? 30_000;
const collaborationTimeoutMs = Math.max(upstreamTimeoutMs, 65_000);
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();
// One person cannot use up the capacity everyone shares: beyond these, their own oldest
// launch code or session ends. An ended session's open connections close at their next check.
const LAUNCHES_PER_USER = 20,
SESSIONS_PER_USER = 20;
const keepNewest = (map, userId, limit, age) => {
const own = [...map].filter(([, value]) => value.userId === userId).sort(([, a], [, b]) => age(a) - age(b));
for (const [key, value] of own.slice(0, Math.max(0, own.length - limit))) {
value.expiresAt = 0;
map.delete(key);
}
};
const wss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024, perMessageDeflate: false });
const gitCredentials = createGitCredentials({
apiOrigin: config.apiOrigin,
tenantId: config.tenantId,
serviceToken: config.serviceToken,
fetchImpl,
now,
connectionToken: href => upstreamTokens.get(href),
setConnectionToken: (href, token) => upstreamTokens.set(href, token),
});
/**
* `credential` is the user's access token for a new session, or the user id an established
* session was granted to: the API still checks the current membership and role each time.
*/
async function authorize(workspaceId, credential, operation, collaboration = false) {
const { userToken, userId } = credential;
if (!ID.test(workspaceId) || (!userToken && !userId) || (userToken?.length ?? 0) > 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(userId ? { userId, operation } : { 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 };
}
/** Checks access for a request or socket, and renews a cookie session that is in use. */
async function authorizeSession(session, workspaceId, operation, collaboration) {
const grant = await authorize(
workspaceId,
session.userId ? { userId: session.userId } : { userToken: session.userToken },
operation,
collaboration,
);
if (session.createdAt !== undefined) {
if (session.userId === undefined) session.userId = grant.userId;
else if (session.userId !== grant.userId) throw new HttpError(403, 'Workspace grant mismatch');
session.expiresAt = Math.min(now() + sessionTtl, session.createdAt + sessionMaxMs);
}
return grant;
}
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] ?? '/';
// Only the gateway itself delivers Git credentials to the workspace backend. Theia's
// Express routes ignore case, so this check does too.
const internal = suffix.toLowerCase();
if (
internal === CREDENTIAL_PATH ||
internal === '/wishforge-internal' ||
internal.startsWith('/wishforge-internal/')
)
throw new HttpError(404, 'Workspace route not found');
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;
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;
}
// The control plane asks whether a workspace is idle before pausing it automatically.
// Only this gateway knows how many browser connections are open.
if (url.pathname === '/internal/lifecycle-state' && req.method === 'POST') {
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))
throw new HttpError(401, 'Service authentication required');
const body = await readJson(req);
if (body.tenantId !== config.tenantId || !ID.test(body.workspaceId ?? ''))
throw new HttpError(400, 'Invalid workspace scope');
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
res.end(
JSON.stringify({
workspaceId: body.workspaceId,
known: true,
gatewayConnections: workspaceSockets.get(body.workspaceId)?.size ?? 0,
}),
);
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');
const { userId } = await authorize(body.workspaceId, { userToken }, 'edit');
purge();
keepNewest(launches, userId, LAUNCHES_PER_USER - 1, launch => launch.expiresAt);
if (launches.size >= 1000 || sessions.size >= 1000) throw new HttpError(429, 'Session capacity reached');
const code = random();
launches.set(code, { workspaceId: body.workspaceId, userToken, userId, 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');
const grant = await authorize(launch.workspaceId, { userToken: launch.userToken }, 'edit');
if (typeof grant.userId !== 'string' || !grant.userId) throw new HttpError(403, 'Workspace grant mismatch');
const opaque = random();
// The token was just checked; the session keeps only the person it was granted to.
const session = {
workspaceId: launch.workspaceId,
userId: grant.userId,
author: validAuthor(grant.author),
createdAt: now(),
expiresAt: now() + sessionTtl,
};
sessions.set(opaque, session);
keepNewest(sessions, session.userId, SESSIONS_PER_USER, value => value.createdAt);
void gitCredentials.opened(session, grant.upstream);
res.writeHead(303, {
location: `/workspaces/${launch.workspaceId}/`,
'set-cookie': `${COOKIE}=${opaque}; HttpOnly; SameSite=Strict; Path=/workspaces/${launch.workspaceId}/; Max-Age=${Math.floor(sessionMaxMs / 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 authorizeSession(session, routing.workspaceId, 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(routing.collaboration ? collaborationTimeoutMs : upstreamTimeoutMs, () => 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 authorizeSession(session, routing.workspaceId, 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 });
});
if (!routing.collaboration) void gitCredentials.due(session, grant.upstream);
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 authorizeSession(
session,
routing.workspaceId,
routing.operation,
routing.collaboration,
);
if (fresh.upstream.href !== grant.upstream.href) throw new Error('Workspace moved');
if (!routing.collaboration) void gitCredentials.due(session, fresh.upstream);
} 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,
};
}