Add proof-of-work challenge, session hub support, and status metrics across backend and frontend apps.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b841c2d1f6
commit
9647ac8c50
29 files changed
+1492
-292
No files matched your search
@@ -2,3 +2,4 @@ export * from './spawner.ts';
|
||||
export * from './lines.ts';
|
||||
export * from './client.ts';
|
||||
export * from './terminal.ts';
|
||||
export * from './proof.ts';
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sha256, solveProof, verifyProof } from './proof.ts';
|
||||
|
||||
const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
|
||||
|
||||
describe('sha256', () => {
|
||||
it.each(['', 'abc', 'challenge:12345', 'x'.repeat(55), 'x'.repeat(56), 'y'.repeat(64), 'z'.repeat(200)])(
|
||||
'matches node for a message of %#',
|
||||
(message) => {
|
||||
expect(hex(sha256(Buffer.from(message)))).toBe(createHash('sha256').update(message).digest('hex'));
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('proof of work', () => {
|
||||
it('finds a nonce the verifier accepts', () => {
|
||||
const nonce = solveProof('AAAAAAAAAAAAAAAAAAAAAA', 12)!;
|
||||
|
||||
expect(verifyProof('AAAAAAAAAAAAAAAAAAAAAA', nonce, 12)).toBe(true);
|
||||
expect(verifyProof('BAAAAAAAAAAAAAAAAAAAAA', nonce, 12)).toBe(false);
|
||||
});
|
||||
|
||||
it('agrees with node about the leading zero bits', () => {
|
||||
const nonce = solveProof('challenge', 10)!;
|
||||
const digest = createHash('sha256').update(`challenge:${nonce}`).digest();
|
||||
|
||||
expect(digest[0]).toBe(0);
|
||||
expect(digest[1]! >> 6).toBe(0);
|
||||
});
|
||||
|
||||
it('stops after the given number of attempts', () => {
|
||||
expect(solveProof('challenge', 32, 0, 100)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Proof of work for new sandboxes: find a nonce so that SHA-256 of
|
||||
* "challenge:nonce" starts with a number of zero bits. Browser and backend
|
||||
* share this file, so both compute exactly the same hash. Free of Node imports.
|
||||
*/
|
||||
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
]);
|
||||
|
||||
const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
|
||||
|
||||
const rotate = (value: number, bits: number) => (value >>> bits) | (value << (32 - bits));
|
||||
|
||||
/** Processes one 64 byte block. The first 16 words of w hold the block; w has room for 64. */
|
||||
function compress(state: Uint32Array, w: Uint32Array): void
|
||||
{
|
||||
for (let i = 16; i < 64; i++)
|
||||
{
|
||||
const s0 = rotate(w[i - 15]!, 7) ^ rotate(w[i - 15]!, 18) ^ (w[i - 15]! >>> 3);
|
||||
const s1 = rotate(w[i - 2]!, 17) ^ rotate(w[i - 2]!, 19) ^ (w[i - 2]! >>> 10);
|
||||
w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) | 0;
|
||||
}
|
||||
|
||||
let [a, b, c, d, e, f, g, h] = state as unknown as number[];
|
||||
for (let i = 0; i < 64; i++)
|
||||
{
|
||||
const t1 = (h! + (rotate(e!, 6) ^ rotate(e!, 11) ^ rotate(e!, 25)) + ((e! & f!) ^ (~e! & g!)) + K[i]! + w[i]!) | 0;
|
||||
const t2 = ((rotate(a!, 2) ^ rotate(a!, 13) ^ rotate(a!, 22)) + ((a! & b!) ^ (a! & c!) ^ (b! & c!))) | 0;
|
||||
h = g; g = f; f = e; e = (d! + t1) | 0;
|
||||
d = c; c = b; b = a; a = (t1 + t2) | 0;
|
||||
}
|
||||
|
||||
state[0] = (state[0]! + a!) | 0; state[1] = (state[1]! + b!) | 0;
|
||||
state[2] = (state[2]! + c!) | 0; state[3] = (state[3]! + d!) | 0;
|
||||
state[4] = (state[4]! + e!) | 0; state[5] = (state[5]! + f!) | 0;
|
||||
state[6] = (state[6]! + g!) | 0; state[7] = (state[7]! + h!) | 0;
|
||||
}
|
||||
|
||||
export function sha256(message: Uint8Array): Uint8Array
|
||||
{
|
||||
const blocks = Math.ceil((message.length + 9) / 64);
|
||||
const padded = new Uint8Array(blocks * 64);
|
||||
padded.set(message);
|
||||
padded[message.length] = 0x80;
|
||||
|
||||
const view = new DataView(padded.buffer);
|
||||
view.setUint32(padded.length - 8, Math.floor(message.length / 0x20000000));
|
||||
view.setUint32(padded.length - 4, (message.length * 8) >>> 0);
|
||||
|
||||
const state = Uint32Array.from(INITIAL);
|
||||
const w = new Uint32Array(64);
|
||||
for (let block = 0; block < blocks; block++)
|
||||
{
|
||||
for (let i = 0; i < 16; i++) w[i] = view.getUint32(block * 64 + i * 4);
|
||||
compress(state, w);
|
||||
}
|
||||
|
||||
const digest = new Uint8Array(32);
|
||||
const output = new DataView(digest.buffer);
|
||||
state.forEach((word, i) => output.setUint32(i * 4, word));
|
||||
return digest;
|
||||
}
|
||||
|
||||
function leadingZeroBits(words: ArrayLike<number>): number
|
||||
{
|
||||
let bits = 0;
|
||||
for (let i = 0; i < words.length; i++)
|
||||
{
|
||||
const zeros = Math.clz32(words[i]!);
|
||||
bits += zeros;
|
||||
if (zeros < 32) break;
|
||||
}
|
||||
return bits;
|
||||
}
|
||||
|
||||
function encode(text: string): Uint8Array {
|
||||
return Uint8Array.from(text, (character) => character.charCodeAt(0) & 0xff);
|
||||
}
|
||||
|
||||
export function verifyProof(challenge: string, nonce: number, difficulty: number): boolean
|
||||
{
|
||||
const digest = sha256(encode(`${challenge}:${nonce}`));
|
||||
const view = new DataView(digest.buffer);
|
||||
const words = Array.from({ length: 8 }, (_, i) => view.getUint32(i * 4));
|
||||
return leadingZeroBits(words) >= difficulty;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches nonces from start for at most count attempts. Challenge and nonce
|
||||
* fit into one block, so the block is rebuilt in place without allocations.
|
||||
*/
|
||||
export function solveProof(challenge: string, difficulty: number, start = 0, count = Number.MAX_SAFE_INTEGER): number | undefined
|
||||
{
|
||||
const prefix = encode(`${challenge}:`);
|
||||
if (prefix.length + 16 > 55) throw new Error('challenge too long for a single block');
|
||||
|
||||
const block = new Uint8Array(64);
|
||||
const view = new DataView(block.buffer);
|
||||
const state = new Uint32Array(8);
|
||||
const w = new Uint32Array(64);
|
||||
block.set(prefix);
|
||||
|
||||
for (let nonce = start; nonce < start + count; nonce++)
|
||||
{
|
||||
const digits = String(nonce);
|
||||
const length = prefix.length + digits.length;
|
||||
|
||||
for (let i = 0; i < digits.length; i++) block[prefix.length + i] = digits.charCodeAt(i);
|
||||
block[length] = 0x80;
|
||||
block.fill(0, length + 1, 60);
|
||||
view.setUint32(60, length * 8);
|
||||
|
||||
for (let i = 0; i < 16; i++) w[i] = view.getUint32(i * 4);
|
||||
state.set(INITIAL);
|
||||
compress(state, w);
|
||||
|
||||
if (leadingZeroBits(state) >= difficulty) return nonce;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { InvalidMessageError, parseClientMessage } from './terminal.ts';
|
||||
|
||||
const TOKEN = 'A'.repeat(21) + '_';
|
||||
const parse = (value: unknown) => parseClientMessage(JSON.stringify(value));
|
||||
|
||||
describe('parseClientMessage', () => {
|
||||
it('accepts hello, resize and resume', () => {
|
||||
expect(parse({ type: 'hello', nonce: 7, cols: 80, rows: 24 })).toEqual({ type: 'hello', nonce: 7, cols: 80, rows: 24 });
|
||||
expect(parse({ type: 'resize', cols: 0, rows: 9999 })).toEqual({ type: 'resize', cols: 1, rows: 500 });
|
||||
expect(parse({ type: 'resume', token: TOKEN, cols: 80, rows: 24 })).toEqual({
|
||||
type: 'resume',
|
||||
token: TOKEN,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['unknown type', { type: 'exec', cols: 80, rows: 24 }],
|
||||
['missing size', { type: 'hello', nonce: 1 }],
|
||||
['missing nonce', { type: 'hello', cols: 80, rows: 24 }],
|
||||
['negative nonce', { type: 'hello', nonce: -1, cols: 80, rows: 24 }],
|
||||
['fractional nonce', { type: 'hello', nonce: 1.5, cols: 80, rows: 24 }],
|
||||
['short token', { type: 'resume', token: 'abc', cols: 80, rows: 24 }],
|
||||
['token with symbols', { type: 'resume', token: 'A'.repeat(21) + '/', cols: 80, rows: 24 }],
|
||||
['inherited type', JSON.parse('{"__proto__":{"type":"hello"},"nonce":1,"cols":80,"rows":24}')],
|
||||
])('rejects %s', (_name, value) => {
|
||||
expect(() => parse(value)).toThrow(InvalidMessageError);
|
||||
});
|
||||
|
||||
it('rejects oversized messages', () => {
|
||||
expect(() => parseClientMessage(' '.repeat(2000))).toThrow(InvalidMessageError);
|
||||
});
|
||||
});
|
||||
@@ -8,17 +8,30 @@ export const TERMINAL_PATH = '/ws';
|
||||
export const MAX_CONTROL_BYTES = 1024;
|
||||
export const MAX_TERMINAL_SIZE = 500;
|
||||
|
||||
/** Reconnect tokens are 16 random bytes in base64url. */
|
||||
const TOKEN = /^[A-Za-z0-9_-]{22}$/;
|
||||
|
||||
export type TerminalSize = { cols: number; rows: number };
|
||||
|
||||
/** A new sandbox needs a nonce that solves the connection's challenge, see proof.ts. */
|
||||
export type ClientMessage =
|
||||
| ({ type: 'hello' } & TerminalSize)
|
||||
| ({ type: 'hello'; nonce: number } & TerminalSize)
|
||||
| ({ type: 'resume'; token: string } & TerminalSize)
|
||||
| ({ type: 'resize' } & TerminalSize);
|
||||
|
||||
export type ExitReason = 'closed' | 'expired' | 'error';
|
||||
/** Why the server ended a session. "gone" answers a resume whose session no longer exists. */
|
||||
export type ExitReason = 'closed' | 'expired' | 'idle' | 'error' | 'gone';
|
||||
|
||||
/** Why the server did not start a session. */
|
||||
export type RefusalReason = 'busy';
|
||||
|
||||
export type ServerMessage =
|
||||
| { type: 'ready' }
|
||||
| { type: 'exit'; reason: ExitReason };
|
||||
| { type: 'challenge'; challenge: string; difficulty: number }
|
||||
| { type: 'queued'; position: number }
|
||||
| { type: 'ready'; token: string; expiresAt: number; resumed: boolean }
|
||||
| { type: 'idle'; secondsLeft: number }
|
||||
| { type: 'exit'; reason: ExitReason }
|
||||
| { type: 'refused'; reason: RefusalReason };
|
||||
|
||||
export class InvalidMessageError extends Error {}
|
||||
|
||||
@@ -43,9 +56,29 @@ export function parseClientMessage(text: string): ClientMessage
|
||||
|
||||
if (typeof input !== 'object' || input === null || Array.isArray(input)) invalid('message must be an object');
|
||||
|
||||
const message = input as Record<string, unknown>;
|
||||
const type = Object.hasOwn(message, 'type') ? message.type : undefined;
|
||||
if (type !== 'hello' && type !== 'resize') invalid('unknown message type');
|
||||
const message = input as Record<string, unknown>;
|
||||
const field = (name: string) => (Object.hasOwn(message, name) ? message[name] : undefined);
|
||||
const type = field('type');
|
||||
const terminal = { cols: size(field('cols')), rows: size(field('rows')) };
|
||||
|
||||
return { type, cols: size(message.cols), rows: size(message.rows) };
|
||||
switch (type)
|
||||
{
|
||||
case 'hello': {
|
||||
const nonce = field('nonce');
|
||||
if (typeof nonce !== 'number' || !Number.isSafeInteger(nonce) || nonce < 0) invalid('invalid nonce');
|
||||
return { type, nonce, ...terminal };
|
||||
}
|
||||
|
||||
case 'resize':
|
||||
return { type, ...terminal };
|
||||
|
||||
case 'resume': {
|
||||
const token = field('token');
|
||||
if (typeof token !== 'string' || !TOKEN.test(token)) invalid('invalid token');
|
||||
return { type, token, ...terminal };
|
||||
}
|
||||
|
||||
default:
|
||||
return invalid('unknown message type');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user