diff --git a/packages/code/src/checkpoint-stage.test.ts b/packages/code/src/checkpoint-stage.test.ts new file mode 100644 index 00000000..3bd15cd0 --- /dev/null +++ b/packages/code/src/checkpoint-stage.test.ts @@ -0,0 +1,134 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { constants } from 'node:fs'; +import { + chmod, + link, + mkdir, + mkdtemp, + open, + readdir, + rename, + rm, + stat, + symlink, + unlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import type { TestContext } from 'node:test'; + +import { CheckpointStage } from './checkpoint-stage.js'; + +const skip = process.platform !== 'linux'; +const flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; + +async function fixture(t: TestContext) { + const dir = await mkdtemp(join(tmpdir(), 'checkpoint-stage-')); + const path = join(dir, 'stage'); + await mkdir(path, { mode: 0o700 }); + const root = await open(path, flags); + t.after(async () => { + await root.close(); + await rm(dir, { recursive: true, force: true }); + }); + return { dir, path, store: new CheckpointStage(root) }; +} + +test( + 'reopens intact staged bytes after the writer is killed', + { skip }, + async t => { + const { path, store } = await fixture(t); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { open } from 'node:fs/promises'; + import { writeSync } from 'node:fs'; + import { CheckpointStage } from ${JSON.stringify( + new URL('./checkpoint-stage.js', import.meta.url).href + )}; + const root = await open(process.argv[1], ${flags}); + const digest = await new CheckpointStage(root).stage(Buffer.from('fixture')); + writeSync(1, digest); + process.kill(process.pid, 'SIGKILL'); + `, + path, + ], + { encoding: 'utf8', timeout: 10000 } + ); + assert.equal(result.signal, 'SIGKILL', result.stderr); + const digest = result.stdout; + assert.match(digest, /^[a-f0-9]{64}$/); + assert.deepEqual(await readdir(path), [digest]); + assert.equal((await stat(join(path, digest))).mode & 0o777, 0o600); + assert.deepEqual(await store.read(digest), Buffer.from('fixture')); + assert.notEqual(await store.stage(Buffer.from('fixture')), digest); + } +); + +test( + 'remains pinned when the directory name is replaced', + { skip }, + async t => { + const { dir, path, store } = await fixture(t); + const saved = join(dir, 'saved'); + await rename(path, saved); + await mkdir(path, { mode: 0o700 }); + const digest = await store.stage(Buffer.from('fixture')); + assert.deepEqual(await readdir(saved), [digest]); + assert.deepEqual(await readdir(path), []); + assert.deepEqual(await store.read(digest), Buffer.from('fixture')); + } +); + +test( + 'rejects malformed IDs, private-mode violations, altered bytes and non-regular entries', + { skip }, + async t => { + const { path, store } = await fixture(t); + const digest = await store.stage(Buffer.from('fixture')); + const file = join(path, digest); + await assert.rejects(store.read('../outside')); + await chmod(file, 0o640); + await assert.rejects(store.read(digest)); + await chmod(file, 0o600); + await link(file, join(path, 'alias')); + await assert.rejects(store.read(digest)); + await unlink(join(path, 'alias')); + await writeFile(file, Buffer.alloc(39)); + await assert.rejects(store.read(digest)); + await unlink(file); + await symlink('/dev/null', file); + await assert.rejects(store.read(digest)); + await unlink(file); + execFileSync('mkfifo', ['-m', '600', file]); + await assert.rejects(store.read(digest)); + await chmod(path, 0o750); + await assert.rejects(store.stage(Buffer.from('fixture'))); + } +); + +test( + 'bounds payload and staging entries without displacing intact bytes', + { skip }, + async t => { + const { path, store } = await fixture(t); + await assert.rejects(store.stage(Buffer.alloc(16 * 1024 * 1024 + 1))); + const first = store.stage(Buffer.from('fixture')); + await assert.rejects(store.stage(Buffer.from('concurrent'))); + const digest = await first; + for (let index = 0; index < 31; index++) { + await writeFile(join(path, `.orphan-${index}`), '', { + mode: 0o600, + }); + } + await assert.rejects(store.stage(Buffer.from('over capacity'))); + assert.deepEqual(await store.read(digest), Buffer.from('fixture')); + } +); diff --git a/packages/code/src/checkpoint-stage.ts b/packages/code/src/checkpoint-stage.ts new file mode 100644 index 00000000..064175dc --- /dev/null +++ b/packages/code/src/checkpoint-stage.ts @@ -0,0 +1,119 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { constants } from 'node:fs'; +import { link, open, opendir, unlink } from 'node:fs/promises'; +import type { FileHandle } from 'node:fs/promises'; + +const maxBytes = 16 * 1024 * 1024; +const maxEntries = 32; +const key = /^[a-f0-9]{64}$/; +const domain = 'librechat/checkpoint-stage/v1\0'; + +function unavailable(): never { + throw new Error('Checkpoint staging unavailable'); +} + +function commitment(bytes: Buffer): string { + return createHash('sha256').update(domain).update(bytes).digest('hex'); +} + +/** + * Internal storage only, not proof of settlement, eligibility, or publication. + * The caller must supply an exclusively leased, pinned Linux directory on a + * supported durable local filesystem, already excluded from ALL sandbox and + * host-side tool access. The caller owns that handle and its lifetime. + */ +export class CheckpointStage { + private busy = false; + + constructor(private readonly root: FileHandle) {} + + private async directory(): Promise { + const info = await this.root.stat(); + if ( + process.platform !== 'linux' || + !info.isDirectory() || + info.uid !== process.getuid?.() || + (info.mode & 0o7777) !== 0o700 + ) + unavailable(); + return `/proc/self/fd/${this.root.fd}`; + } + + /** Bytes encode the caller's immutable manifest and payload together. */ + async stage(payload: Buffer): Promise { + if (this.busy || !payload.length || payload.length > maxBytes) + unavailable(); + this.busy = true; + try { + // Snapshot caller bytes before yielding; the private nonce prevents a digest oracle. + const bytes = Buffer.concat([randomBytes(32), payload]); + const digest = commitment(bytes); + const directory = await this.directory(); + const entries = await opendir(directory); + let count = 0; + for await (const _ of entries) + if (++count >= maxEntries) unavailable(); + + const temporary = `${directory}/.stage-${digest}`; + const final = `${directory}/${digest}`; + const file = await open(temporary, 'wx', 0o600); + try { + await file.writeFile(bytes); + await file.sync(); + await file.close(); + // No replacement, even if the name already exists. Both names are in one directory. + await link(temporary, final); + } finally { + try { + await file.close(); + } finally { + await unlink(temporary); + } + } + await this.root.sync(); + return digest; + } finally { + this.busy = false; + } + } + + /** Only returns intact staged bytes; a caller must separately consume fresh bridge proof. */ + async read(digest: string): Promise { + if (!key.test(digest)) unavailable(); + const directory = await this.directory(); + const file = await open( + `${directory}/${digest}`, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK + ); + try { + const info = await file.stat(); + if ( + !info.isFile() || + info.uid !== process.getuid?.() || + (info.mode & 0o7777) !== 0o600 || + info.nlink !== 1 || + info.size <= 32 || + info.size > maxBytes + 32 + ) + unavailable(); + const bytes = Buffer.alloc(info.size + 1); + let offset = 0; + while (offset < bytes.length) { + const { bytesRead } = await file.read( + bytes, + offset, + bytes.length - offset, + offset + ); + if (!bytesRead) break; + offset += bytesRead; + } + const content = bytes.subarray(0, offset); + if (offset !== info.size || commitment(content) !== digest) + unavailable(); + return content.subarray(32); + } finally { + await file.close(); + } + } +}