feat: W1 batch — config, protocol, ring-buffer, origin, mock-pty (TDD)

Parallel module-builder subagents, disjoint file ownership, shared tree:
- T4 src/config.ts        — loadConfig+M1 origins (32 tests)
- T5 src/protocol.ts      — parse/serialize+SESSION_ID_RE+M7 (60 tests)
- T6 src/session/ring-buffer.ts — byte-accurate, no UTF-8/ANSI split+M2 (15 tests)
- T7 src/http/origin.ts   — host+port match, undefined rejected (12 tests)
- T3 test/helpers/mock-pty.ts — IPty double w/ emitData/emitExit (9 tests)

Verified by orchestrator: tsc --noEmit clean; full suite 128 tests pass.
This commit is contained in:
Yaojia Wang
2026-06-16 08:09:40 +02:00
parent 0e10dc21c3
commit 0fa0b69ce9
15 changed files with 1579 additions and 0 deletions

View File

157
src/config.ts Normal file
View File

@@ -0,0 +1,157 @@
/**
* src/config.ts — T4: environment config loader
*
* Reads env vars once at startup, validates them, derives allowedOrigins from
* local NIC IPs (M1 — NOT from bindHost; 0.0.0.0 is never a valid Origin),
* and returns a frozen Config object.
*/
import os from 'node:os'
import type { Config, EnvLike } from './types.js'
// ── constants ─────────────────────────────────────────────────────────────────
const DEFAULT_PORT = 3000
const DEFAULT_BIND_HOST = '0.0.0.0'
const DEFAULT_IDLE_TTL_SEC = 24 * 60 * 60 // 24 hours in seconds
const DEFAULT_SCROLLBACK_BYTES = 2 * 1024 * 1024 // 2 MB
const DEFAULT_MAX_PAYLOAD_BYTES = 1 * 1024 * 1024 // 1 MB
const DEFAULT_WS_PATH = '/term'
// ── helpers ───────────────────────────────────────────────────────────────────
function parsePositiveInt(
raw: string | undefined,
label: string,
fallback: number,
): number {
if (raw === undefined) return fallback
const n = Number(raw)
if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) {
throw new Error(
`Invalid config: ${label}=${JSON.stringify(raw)} — must be a non-negative integer`,
)
}
return n
}
function parsePort(raw: string | undefined): number {
if (raw === undefined) return DEFAULT_PORT
const n = Number(raw)
if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 65535) {
throw new Error(
`Invalid config: PORT=${JSON.stringify(raw)} — must be an integer 165535`,
)
}
return n
}
function parseIdleTtl(raw: string | undefined): number {
if (raw === undefined) return DEFAULT_IDLE_TTL_SEC * 1000
const n = Number(raw)
if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) {
throw new Error(
`Invalid config: IDLE_TTL=${JSON.stringify(raw)} — must be a non-negative integer (seconds)`,
)
}
return n * 1000
}
/**
* Derive allowedOrigins from host NIC IPs (M1).
*
* Rules:
* - Enumerate os.networkInterfaces(), pick IPv4 entries.
* - Skip internal (loopback) entries — 127.0.0.1 / localhost are added explicitly.
* - For every qualifying address, produce both http:// and https:// origins.
* - Append ALLOWED_ORIGINS env-var items (comma-separated).
* - Deduplicate.
* - Never include 0.0.0.0 (wildcard listen address, never a browser Origin).
*/
function deriveAllowedOrigins(port: number, extraEnv: string | undefined): readonly string[] {
const set = new Set<string>()
// 1. Always include localhost / loopback
const loopbackHosts = ['localhost', '127.0.0.1']
for (const host of loopbackHosts) {
set.add(`http://${host}:${port}`)
set.add(`https://${host}:${port}`)
}
// 2. Enumerate NIC IPv4 addresses — skip internal (loopback already handled above)
const ifaces = os.networkInterfaces()
for (const ifaceList of Object.values(ifaces)) {
if (!ifaceList) continue
for (const entry of ifaceList) {
// Only IPv4, non-internal entries; never 0.0.0.0
if (
entry.family === 'IPv4' &&
!entry.internal &&
entry.address !== '0.0.0.0'
) {
set.add(`http://${entry.address}:${port}`)
set.add(`https://${entry.address}:${port}`)
}
}
}
// 3. Merge ALLOWED_ORIGINS env var (comma-separated list of origin strings)
if (extraEnv) {
for (const raw of extraEnv.split(',')) {
const trimmed = raw.trim()
if (trimmed) set.add(trimmed)
}
}
return Object.freeze([...set])
}
// ── loadConfig ────────────────────────────────────────────────────────────────
/**
* Read and validate environment variables; fill in defaults for missing keys.
* Invalid values (port out of range, TTL non-integer, etc.) throw immediately
* so the server never starts in a misconfigured state (fail-fast).
*
* The returned Config is Object.freeze'd — immutable after construction.
*/
export function loadConfig(env: EnvLike): Config {
const port = parsePort(env['PORT'])
const bindHost = env['BIND_HOST'] ?? DEFAULT_BIND_HOST
const shellPath =
env['SHELL_PATH'] ?? (process.env['SHELL'] as string | undefined) ?? '/bin/zsh'
const homeDir = os.homedir()
const idleTtlMs = parseIdleTtl(env['IDLE_TTL'])
const scrollbackBytes = parsePositiveInt(
env['SCROLLBACK_BYTES'],
'SCROLLBACK_BYTES',
DEFAULT_SCROLLBACK_BYTES,
)
const maxPayloadBytes = parsePositiveInt(
env['MAX_PAYLOAD_BYTES'],
'MAX_PAYLOAD_BYTES',
DEFAULT_MAX_PAYLOAD_BYTES,
)
const wsPath = env['WS_PATH'] ?? DEFAULT_WS_PATH
const allowedOrigins = deriveAllowedOrigins(port, env['ALLOWED_ORIGINS'])
return Object.freeze({
port,
bindHost,
shellPath,
homeDir,
idleTtlMs,
scrollbackBytes,
maxPayloadBytes,
wsPath,
allowedOrigins,
} satisfies Config)
}

View File

53
src/http/origin.ts Normal file
View File

@@ -0,0 +1,53 @@
/**
* src/http/origin.ts — Origin whitelist check (T7)
*
* Pure function, no side effects. Security-critical:
* this is the CSWSH (Cross-Site WebSocket Hijacking) defence described in
* TECH_DOC §7 and ARCHITECTURE §3.3.
*
* Strategy:
* - Parse the incoming Origin as a URL.
* - Compare scheme + hostname + port against every entry in the allowed list.
* - Both host AND port must match (ARCHITECTURE §3.3: "host+port 双匹配").
* - undefined Origin (non-browser clients: curl, scripts) → reject by default.
* This is the single central policy point — no scattered `if` checks elsewhere.
*/
/**
* Returns true iff `origin` exactly matches one of the `allowed` origins.
*
* Matching is scheme + hostname + port (all three must agree).
* `undefined` → false (non-browser client; default-deny, no scattered if-chains).
*/
export function isOriginAllowed(
origin: string | undefined,
allowed: readonly string[],
): boolean {
// Central policy: undefined Origin is rejected. No other code path handles this.
if (origin === undefined || origin === '') {
return false
}
let incomingUrl: URL
try {
incomingUrl = new URL(origin)
} catch {
// Malformed Origin value → reject.
return false
}
return allowed.some((entry) => {
let allowedUrl: URL
try {
allowedUrl = new URL(entry)
} catch {
return false
}
return (
incomingUrl.protocol === allowedUrl.protocol &&
incomingUrl.hostname === allowedUrl.hostname &&
incomingUrl.port === allowedUrl.port
)
})
}

158
src/protocol.ts Normal file
View File

@@ -0,0 +1,158 @@
/**
* src/protocol.ts — WebSocket message codec + validation (T5, pure functions)
*
* Invariant #3 (ARCHITECTURE §8): parseClientMessage NEVER throws.
* All invalid input flows through ParseResult.ok=false.
*
* Imports only from src/types.ts (frozen shared contract, T2).
*/
import type { ClientMessage, ServerMessage, ParseResult } from './types.js'
// ─── SESSION_ID_RE (M7) ───────────────────────────────────────────────────────
/**
* UUID v4 pattern.
* - 8-4-4-4-12 hex groups
* - version nibble must be '4'
* - variant nibble must be 8, 9, a, or b (10xx in binary)
*
* M7: strings like "abc123" must be rejected; crypto.randomUUID() values must pass.
*/
export const SESSION_ID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
// ─── Type whitelist ───────────────────────────────────────────────────────────
const ALLOWED_TYPES = new Set<string>(['attach', 'input', 'resize'])
// ─── parseClientMessage ───────────────────────────────────────────────────────
/**
* Parse and validate a raw WS text frame as a ClientMessage.
*
* Steps (ARCHITECTURE §3.2 / TECH_DOC §5.3):
* 1. JSON.parse — bad JSON → ok=false
* 2. Must be a plain object (not null, array, etc.)
* 3. type must be in whitelist {'attach','input','resize'}
* 4. Per-type field validation:
* - resize: cols and rows are integers in [1, 1000]
* - input: data is a string (passed through verbatim, invariant #9)
* - attach: sessionId is null OR a string matching SESSION_ID_RE (M7)
*
* NEVER throws — all errors return { ok: false, error: <message> }.
*/
export function parseClientMessage(raw: string): ParseResult {
// Step 1: JSON parse
let parsed: unknown
try {
parsed = JSON.parse(raw)
} catch {
return { ok: false, error: 'invalid JSON' }
}
// Step 2: Must be a plain object
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
return { ok: false, error: 'message must be a JSON object' }
}
const obj = parsed as Record<string, unknown>
// Step 3: type whitelist
const type = obj['type']
if (typeof type !== 'string' || !ALLOWED_TYPES.has(type)) {
return { ok: false, error: `unknown or missing type: ${String(type)}` }
}
// Step 4: per-type validation
if (type === 'resize') {
return validateResize(obj)
}
if (type === 'input') {
return validateInput(obj)
}
// type === 'attach'
return validateAttach(obj)
}
// ─── Per-type validators ──────────────────────────────────────────────────────
function validateResize(obj: Record<string, unknown>): ParseResult {
const { cols, rows } = obj
if (!isValidDimension(cols)) {
return {
ok: false,
error: `resize.cols must be an integer in [1, 1000], got ${String(cols)}`,
}
}
if (!isValidDimension(rows)) {
return {
ok: false,
error: `resize.rows must be an integer in [1, 1000], got ${String(rows)}`,
}
}
return {
ok: true,
message: { type: 'resize', cols: cols as number, rows: rows as number },
}
}
function isValidDimension(value: unknown): value is number {
return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 1000
}
function validateInput(obj: Record<string, unknown>): ParseResult {
const { data } = obj
if (typeof data !== 'string') {
return { ok: false, error: `input.data must be a string, got ${typeof data}` }
}
// Invariant #9: data passed through verbatim, no content filtering
return { ok: true, message: { type: 'input', data } }
}
function validateAttach(obj: Record<string, unknown>): ParseResult {
const { sessionId } = obj
// sessionId must be explicitly present as null or a UUID v4 string (M7)
if (!Object.prototype.hasOwnProperty.call(obj, 'sessionId')) {
return { ok: false, error: 'attach.sessionId field is required' }
}
if (sessionId === null) {
return { ok: true, message: { type: 'attach', sessionId: null } }
}
if (typeof sessionId !== 'string') {
return {
ok: false,
error: `attach.sessionId must be null or a UUID v4 string, got ${typeof sessionId}`,
}
}
if (!SESSION_ID_RE.test(sessionId)) {
return {
ok: false,
error: `attach.sessionId is not a valid UUID v4: ${sessionId}`,
}
}
return { ok: true, message: { type: 'attach', sessionId } }
}
// ─── serialize ────────────────────────────────────────────────────────────────
/**
* Serialize a ServerMessage to a JSON text frame.
*
* Internal trusted data — JSON.stringify directly (ARCHITECTURE §3.2).
*/
export function serialize(msg: ServerMessage): string {
return JSON.stringify(msg)
}

View File

View File

@@ -0,0 +1,65 @@
/**
* src/session/ring-buffer.ts (T6) — output scrollback for reconnect replay.
*
* M2 (the easy-to-get-wrong part). PTY output is an opaque ANSI byte stream; we
* must NEVER cut a multi-byte UTF-8 codepoint or an ANSI escape sequence in half,
* or the first screen on reconnect renders as garbage — exactly the vibe-coding
* "refresh and the Claude TUI is still there" path. So:
*
* - capacity is measured in REAL UTF-8 bytes (Buffer.byteLength), because
* `string.length` counts UTF-16 code units, not bytes;
* - eviction happens on whole append-chunk boundaries (drop the oldest chunk),
* so no chunk is ever sliced (the trade-off is the live size floats a little
* above/below maxBytes);
* - snapshot() prepends a soft-reset `\x1b[0m` so that even if the oldest
* surviving chunk started mid-attribute, the terminal is reset first.
*
* Implements the frozen `RingBuffer` contract in src/types.ts (read-only import).
*/
import type { RingBuffer } from '../types.js';
const SOFT_RESET = '\x1b[0m';
interface Chunk {
readonly text: string;
readonly bytes: number;
}
/**
* Create a ring buffer holding at most ~`maxBytes` UTF-8 bytes of recent output.
*
* @param maxBytes capacity in real UTF-8 bytes (e.g. `cfg.scrollbackBytes`).
*/
export function createRingBuffer(maxBytes: number): RingBuffer {
// Immutable-update style: each append produces a new chunk list / total rather
// than mutating shared state in place (per coding-style immutability rule).
let chunks: readonly Chunk[] = [];
let totalBytes = 0;
function append(chunk: string): void {
if (chunk.length === 0) return; // nothing to store; keeps accounting clean
const bytes = Buffer.byteLength(chunk, 'utf8');
let nextChunks: Chunk[] = [...chunks, { text: chunk, bytes }];
let nextTotal = totalBytes + bytes;
// Evict whole oldest chunks until we fit — but never drop the only remaining
// chunk, so a lone chunk larger than capacity is kept intact (cannot split).
while (nextTotal > maxBytes && nextChunks.length > 1) {
const oldest = nextChunks[0]!;
nextChunks = nextChunks.slice(1);
nextTotal -= oldest.bytes;
}
chunks = nextChunks;
totalBytes = nextTotal;
}
function snapshot(): string {
// Soft-reset first (M2 safety net), then the current buffer verbatim.
return SOFT_RESET + chunks.map((c) => c.text).join('');
}
return { append, snapshot };
}