Introduce spawner app with sandboxing support and client protocol implementation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
571f43457d
commit
7b1df2607e
26 files changed
+2438
-5
No files matched your search
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "@homepage/protocol",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": "./src/index.ts"
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { connect, type Socket } from 'node:net';
|
||||
import { readLine } from './lines.ts';
|
||||
import type { ManagedContainer, SpawnerRequest, SpawnerResponse } from './spawner.ts';
|
||||
|
||||
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
||||
|
||||
export class SpawnerError extends Error {}
|
||||
|
||||
// noinspection ExceptionCaughtLocallyJS
|
||||
export class SpawnerClient
|
||||
{
|
||||
readonly socketPath: string;
|
||||
|
||||
constructor(socketPath: string) { this.socketPath = socketPath; }
|
||||
|
||||
async spawn(sessionId: string, expiresAt: number): Promise<string> {
|
||||
const response = await this.request({ op: 'spawn', sessionId, expiresAt });
|
||||
return response.containerId!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a raw duplex stream to the container's terminal. The container
|
||||
* is started by the first attach, and the stream starts paused, so no early
|
||||
* output gets lost before the caller pipes or resumes it.
|
||||
*/
|
||||
async attach(containerId: string): Promise<Socket> {
|
||||
const { socket } = await this.open({ op: 'attach', containerId });
|
||||
return socket;
|
||||
}
|
||||
|
||||
async resize(containerId: string, cols: number, rows: number): Promise<void> {
|
||||
await this.request({ op: 'resize', containerId, cols, rows });
|
||||
}
|
||||
|
||||
async kill(containerId: string): Promise<void> {
|
||||
await this.request({ op: 'kill', containerId });
|
||||
}
|
||||
|
||||
async list(): Promise<ManagedContainer[]> {
|
||||
const response = await this.request({ op: 'list' });
|
||||
return response.containers ?? [];
|
||||
}
|
||||
|
||||
private async request(request: SpawnerRequest): Promise<SpawnerResponse & { ok: true }> {
|
||||
const { socket, response } = await this.open(request);
|
||||
socket.destroy();
|
||||
return response;
|
||||
}
|
||||
|
||||
private open(request: SpawnerRequest): Promise<{ socket: Socket; response: SpawnerResponse & { ok: true } }>
|
||||
{
|
||||
return new Promise((resolve, reject) =>
|
||||
{
|
||||
const socket = connect(this.socketPath);
|
||||
socket.once('error', reject);
|
||||
socket.once('connect', async () =>
|
||||
{
|
||||
socket.off('error', reject);
|
||||
try
|
||||
{
|
||||
socket.write(`${JSON.stringify(request)}\n`);
|
||||
const { line, rest } = await readLine(socket, MAX_RESPONSE_BYTES, 30_000);
|
||||
const response = JSON.parse(line) as SpawnerResponse;
|
||||
|
||||
if (!response.ok) throw new SpawnerError(response.error);
|
||||
if (rest.length > 0) socket.unshift(rest);
|
||||
|
||||
resolve({ socket, response });
|
||||
}
|
||||
catch (error)
|
||||
{
|
||||
socket.destroy();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './spawner.ts';
|
||||
export * from './lines.ts';
|
||||
export * from './client.ts';
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { Socket } from 'node:net';
|
||||
|
||||
export type Line = {
|
||||
line: string;
|
||||
/** Bytes received after the newline, which belong to the following stream. */
|
||||
rest: Buffer;
|
||||
};
|
||||
|
||||
export function readLine(socket: Socket, maxBytes: number, timeoutMs = 5000): Promise<Line> {
|
||||
return new Promise((resolve, reject) =>
|
||||
{
|
||||
let buffered = Buffer.alloc(0);
|
||||
|
||||
const finish = (error: Error | null, result?: Line) =>
|
||||
{
|
||||
clearTimeout(timer);
|
||||
|
||||
socket.off('data', onData);
|
||||
socket.off('end', onEnd);
|
||||
socket.off('error', onError);
|
||||
|
||||
if (error) reject(error);
|
||||
else resolve(result!);
|
||||
};
|
||||
|
||||
const onData = (chunk: Buffer) =>
|
||||
{
|
||||
buffered = Buffer.concat([buffered, chunk]);
|
||||
|
||||
const newline = buffered.indexOf(0x0a);
|
||||
if (newline === -1) {
|
||||
if (buffered.length > maxBytes) finish(new Error('line too long'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (newline > maxBytes) {
|
||||
finish(new Error('line too long'));
|
||||
return;
|
||||
}
|
||||
|
||||
socket.pause();
|
||||
finish(null, { line: buffered.subarray(0, newline).toString('utf8'), rest: buffered.subarray(newline + 1) });
|
||||
};
|
||||
|
||||
const onEnd = () => finish(new Error('connection closed before a full line arrived'));
|
||||
const onError = (error: Error) => finish(error);
|
||||
const timer = setTimeout(() => finish(new Error('timed out waiting for a line')), timeoutMs);
|
||||
|
||||
socket.on('data', onData);
|
||||
socket.once('end', onEnd);
|
||||
socket.once('error', onError);
|
||||
socket.resume();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { InvalidRequestError, MAX_SESSION_SECONDS, parseRequest } from './spawner.ts';
|
||||
|
||||
const now = 1_800_000_000;
|
||||
const parse = (value: unknown) => parseRequest(JSON.stringify(value), now);
|
||||
|
||||
describe('parseRequest', () => {
|
||||
it('accepts a valid spawn', () => {
|
||||
expect(parse({ op: 'spawn', sessionId: 'abcdEFGH_-12', expiresAt: now + 1200 })).toEqual({
|
||||
op: 'spawn',
|
||||
sessionId: 'abcdEFGH_-12',
|
||||
expiresAt: now + 1200,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['short id', { op: 'spawn', sessionId: 'abc', expiresAt: now + 60 }],
|
||||
['id with shell characters', { op: 'spawn', sessionId: 'abcdefgh;rm', expiresAt: now + 60 }],
|
||||
['expiry in the past', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now }],
|
||||
['expiry too far ahead', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + MAX_SESSION_SECONDS + 1 }],
|
||||
['fractional expiry', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + 1.5 }],
|
||||
['uppercase container id', { op: 'kill', containerId: 'ABCDEF123456' }],
|
||||
['container id with path', { op: 'attach', containerId: '../../info' }],
|
||||
['unknown op', { op: 'exec', containerId: 'abcdef123456' }],
|
||||
['array', [{ op: 'list' }]],
|
||||
['null', null],
|
||||
])('rejects %s', (_name, value) => {
|
||||
expect(() => parse(value)).toThrow(InvalidRequestError);
|
||||
});
|
||||
|
||||
it('rejects malformed json', () => {
|
||||
expect(() => parseRequest('{"op":', now)).toThrow(InvalidRequestError);
|
||||
});
|
||||
|
||||
it('ignores inherited properties', () => {
|
||||
expect(() => parseRequest('{"__proto__":{"op":"list"}}', now)).toThrow(InvalidRequestError);
|
||||
});
|
||||
|
||||
it('clamps the terminal size', () => {
|
||||
expect(parse({ op: 'resize', containerId: 'abcdef123456', cols: 9999, rows: 0 })).toEqual({
|
||||
op: 'resize',
|
||||
containerId: 'abcdef123456',
|
||||
cols: 500,
|
||||
rows: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a non integer terminal size', () => {
|
||||
expect(() => parse({ op: 'resize', containerId: 'abcdef123456', cols: '80', rows: 24 })).toThrow(
|
||||
InvalidRequestError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
export const SANDBOX_LABEL = 'org.security-command.sandbox';
|
||||
export const SESSION_LABEL = 'org.security-command.session';
|
||||
|
||||
export const MAX_REQUEST_BYTES = 4096;
|
||||
export const MAX_SESSION_SECONDS = 6 * 60 * 60;
|
||||
export const MAX_TERMINAL_SIZE = 500;
|
||||
|
||||
export type SpawnerRequest =
|
||||
| { op: 'spawn'; sessionId: string; expiresAt: number }
|
||||
| { op: 'attach'; containerId: string }
|
||||
| { op: 'resize'; containerId: string; cols: number; rows: number }
|
||||
| { op: 'kill'; containerId: string }
|
||||
| { op: 'list' };
|
||||
|
||||
export type ManagedContainer = {
|
||||
containerId: string;
|
||||
sessionId: string;
|
||||
running: boolean;
|
||||
};
|
||||
|
||||
export type SpawnerResponse =
|
||||
| { ok: true; containerId?: string; containers?: ManagedContainer[] }
|
||||
| { ok: false; error: string };
|
||||
|
||||
const SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
||||
const CONTAINER_ID = /^[0-9a-f]{12,64}$/;
|
||||
|
||||
export class InvalidRequestError extends Error {}
|
||||
|
||||
function invalid(message: string): never {
|
||||
throw new InvalidRequestError(message);
|
||||
}
|
||||
|
||||
function field(input: Record<string, unknown>, name: string): unknown {
|
||||
return Object.hasOwn(input, name) ? input[name] : undefined;
|
||||
}
|
||||
|
||||
function sessionId(value: unknown): string {
|
||||
return typeof value === 'string' && SESSION_ID.test(value) ? value : invalid('invalid session id');
|
||||
}
|
||||
|
||||
function containerId(value: unknown): string {
|
||||
return typeof value === 'string' && CONTAINER_ID.test(value) ? value : invalid('invalid container id');
|
||||
}
|
||||
|
||||
function terminalSize(value: unknown): number {
|
||||
if (typeof value !== 'number' || !Number.isInteger(value)) invalid('invalid terminal size');
|
||||
return Math.min(Math.max(value, 1), MAX_TERMINAL_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses one request line. Everything the backend sends is treated as
|
||||
* untrusted, because the backend faces the internet and may be compromised.
|
||||
*/
|
||||
export function parseRequest(line: string, nowSeconds = Math.floor(Date.now() / 1000)): SpawnerRequest
|
||||
{
|
||||
let input: unknown;
|
||||
try { input = JSON.parse(line); }
|
||||
catch { invalid('malformed json'); }
|
||||
|
||||
if (typeof input !== 'object' || input === null || Array.isArray(input)) invalid('request must be an object');
|
||||
|
||||
const request = input as Record<string, unknown>;
|
||||
switch (field(request, 'op'))
|
||||
{
|
||||
case 'spawn': {
|
||||
const expiresAt = field(request, 'expiresAt');
|
||||
|
||||
if (
|
||||
typeof expiresAt !== 'number' ||
|
||||
!Number.isInteger(expiresAt) ||
|
||||
expiresAt <= nowSeconds ||
|
||||
expiresAt > nowSeconds + MAX_SESSION_SECONDS
|
||||
) { invalid('invalid expiry'); }
|
||||
|
||||
return { op: 'spawn', sessionId: sessionId(field(request, 'sessionId')), expiresAt };
|
||||
}
|
||||
|
||||
case 'attach':
|
||||
return { op: 'attach', containerId: containerId(field(request, 'containerId')) };
|
||||
|
||||
case 'resize':
|
||||
return {
|
||||
op: 'resize',
|
||||
containerId: containerId(field(request, 'containerId')),
|
||||
cols: terminalSize(field(request, 'cols')),
|
||||
rows: terminalSize(field(request, 'rows')),
|
||||
};
|
||||
|
||||
case 'kill':
|
||||
return { op: 'kill', containerId: containerId(field(request, 'containerId')) };
|
||||
|
||||
case 'list':
|
||||
return { op: 'list' };
|
||||
|
||||
default:
|
||||
return invalid('unknown op');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user