/** * Shared editor-session registry format: entry shape, guards, path, * liveness-filtered reads, served-project parsing and pending launches. * The server’s session-registry module owns writes to this format. * * The registry is also the CREDENTIAL FILE for the owner's own processes: each entry carries its session's * connection token, and `sessionFetch` is how a process on this machine reaches a session with it, as a Code-OSS * client reads its server's `--connection-token-file` (`src/vs/server/node/serverConnectionToken.ts:62-79` in the * `volter-ai/code-oss` fork). The file is the user's alone (0600, written by the session). */ import { mkdirSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, } from 'node:fs'; import { homedir } from 'node:os'; import { join, resolve } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; /** One registry entry, exactly as the server's write half records it. */ export interface EditorSessionEntry { /** Canonical project root currently open, or null when none. */ project: string | null; port: number; /** PID of the dev-server process. */ pid: number; /** ISO timestamp of server start. */ startedAt: string; sessionId: string | null; /** The session's connection token, which every request to it carries (`sessionFetch`). Never returned by a * session route; it is in this user-private file and in the page's cookie. */ connectionToken?: string | null; repositoryId: string | null; worktreeId: string | null; worktreeRoot: string | null; projectRelativePath: string | null; branch: string | null; headCommit: string | null; baseCommit: string | null; } export const EDITOR_SESSIONS_REGISTRY_FILE = join(homedir(), '.volter', 'editor-sessions.json'); export function isEditorSessionEntry(v: unknown): v is EditorSessionEntry { if (typeof v !== 'object' || v === null) return false; const s = v as Record; const optionalIdentity = (value: unknown) => value === undefined || value === null || typeof value === 'string'; return ( (typeof s['project'] === 'string' || s['project'] === null) && typeof s['port'] === 'number' && typeof s['pid'] === 'number' && typeof s['startedAt'] === 'string' && optionalIdentity(s['sessionId']) && optionalIdentity(s['connectionToken']) && optionalIdentity(s['repositoryId']) && optionalIdentity(s['worktreeId']) && optionalIdentity(s['worktreeRoot']) && optionalIdentity(s['projectRelativePath']) && optionalIdentity(s['branch']) && optionalIdentity(s['headCommit']) && optionalIdentity(s['baseCommit']) ); } export function normalizeEditorSessionEntry(session: EditorSessionEntry): EditorSessionEntry { return { ...session, sessionId: session.sessionId ?? null, connectionToken: session.connectionToken ?? null, repositoryId: session.repositoryId ?? null, worktreeId: session.worktreeId ?? null, worktreeRoot: session.worktreeRoot ?? null, projectRelativePath: session.projectRelativePath ?? null, branch: session.branch ?? null, headCommit: session.headCommit ?? null, baseCommit: session.baseCommit ?? null, }; } /** Whether pid exists. Signal 0's EPERM means it exists but this caller cannot signal it. */ export function pidAlive(pid: number): boolean { try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } } /** The registry's live entries — shape-validated and PID-liveness-filtered. */ export function readLiveRegisteredSessions(): EditorSessionEntry[] { try { const raw: unknown = JSON.parse(readFileSync(EDITOR_SESSIONS_REGISTRY_FILE, 'utf8')); return Array.isArray(raw) ? raw .filter(isEditorSessionEntry) .map(normalizeEditorSessionEntry) .filter((s) => pidAlive(s.pid)) : []; } catch { return []; } } /** * The cookie the session reads its connection token from: Code-OSS's own (`connectionTokenCookieName`, * `src/vs/base/common/network.ts:187`). The page's Code-OSS server sets it on the page's host from the address's * `?tkn=` (`src/vs/server/node/webClientServer.ts:313-336`), and the session's routes share that host through its * proxy and the token through the project's token file, so one cookie carries both. */ export const CONNECTION_TOKEN_COOKIE = 'vscode-tkn'; /** The connection token of the live session listening on `port` of this machine, from its entry; null when no live * session there registered one. */ export function registeredConnectionToken(port: number): string | null { return readLiveRegisteredSessions().find((session) => session.port === port)?.connectionToken ?? null; } const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']); /** The port of a session `url` names on this machine, or null for any other address. */ function loopbackSessionPort(url: string | URL): number | null { const target = new URL(url); return target.protocol === 'http:' && LOOPBACK_HOSTS.has(target.hostname) && target.port !== '' ? Number(target.port) : null; } /** `init` with the connection token of the session `url` names, as the cookie the session reads. Only a loopback * address gets one, and only a registered session's: the token never leaves this machine. */ export function withSessionToken(url: string | URL, init: RequestInit = {}): RequestInit { const port = loopbackSessionPort(url); const token = port === null ? null : registeredConnectionToken(port); if (token === null) return init; const headers = new Headers(init.headers); headers.set('cookie', `${CONNECTION_TOKEN_COOKIE}=${token}`); return { ...init, headers }; } /** * Say why a session on this machine refused (403) a request this process could send it no token with: its registry * entry, the one place the owner's processes read the token from, is missing or carries none. Throws that; returns * when the refusal is something else (a token was sent, or the address is not a local session's). */ export function refuseWithoutRegisteredToken(url: string | URL, status: number): void { if (status !== 403) return; const port = loopbackSessionPort(url); if (port === null || registeredConnectionToken(port) !== null) return; throw new Error( `The editor session on port ${port} refused this request: its connection token could not be read, because the ` + `session registry ${EDITOR_SESSIONS_REGISTRY_FILE} has no live entry for port ${port} carrying one. The session ` + "says why its entry could not be written in its terminal and on its console, and writes it again every minute.", ); } /** `fetch` to a session on this machine, carrying its connection token (`withSessionToken`). Every request a process * of the owner's makes to a session goes through here or through `EditorClient`, which does the same, and a refusal * for want of the token says so (`refuseWithoutRegisteredToken`). */ export async function sessionFetch(url: string | URL, init?: RequestInit): Promise { const response = await fetch(url, withSessionToken(url, init)); refuseWithoutRegisteredToken(url, response.status); return response; } /** Announce a launch before the server can register. Each launcher owns its file. */ export function announceEditorLaunch(project: string): () => void { const directory = join(project, '.volter', 'editor-launches'); mkdirSync(directory, { recursive: true }); const file = join(directory, `${process.pid}.json`); writeFileSync(file, JSON.stringify({ pid: process.pid })); const clear = () => { process.removeListener('exit', clear); try { unlinkSync(file); } catch { // Already cleared when the server became ready. } }; process.once('exit', clear); return clear; } function hasPendingEditorLaunch(project: string): boolean { const directory = join(project, '.volter', 'editor-launches'); try { return readdirSync(directory).some((name) => { if (!/^\d+\.json$/.test(name)) return false; const pid = Number(name.slice(0, -5)); return pid !== process.pid && pidAlive(pid); }); } catch { return false; } } /** Wait only for an observed live launcher, never for a missing editor. */ export async function waitForPendingEditorLaunch(project: string): Promise { const canon = canonicalizeProjectPath(project); const ready = () => readLiveRegisteredSessions().some( (session) => session.project !== null && canonicalizeProjectPath(session.project) === canon, ); if (ready() || !hasPendingEditorLaunch(canon)) return; const deadline = Date.now() + 180_000; while (!ready()) { if (!hasPendingEditorLaunch(canon)) { // The launcher clears its announcement only after registration. if (ready()) return; throw new Error(`The editor launch for ${canon} ended before registering a session.`); } if (Date.now() >= deadline) { throw new Error( `The editor launch for ${canon} is still running but has not registered within 180s.`, ); } await delay(100); } } /** Read the project identity reported by /__editor/project. A serving path * identifies an open project even when its manifest cannot be parsed or * validated; project: null alone denotes no described project. */ export function servedProjectAnswer(body: unknown): { path: string | null; manifestError: string | null; } { const b = body as { project?: { path?: string } | null; serving?: { path?: string; error?: string } | null; }; return { path: b.project?.path ?? b.serving?.path ?? null, manifestError: b.project ? null : (b.serving?.error ?? null), }; } /** Canonical (realpathed when possible) absolute form of a project path. */ function canonicalizeProjectPath(p: string): string { const absolute = resolve(p); try { return realpathSync(absolute); } catch { return absolute; } }