167 lines
11 KiB
TypeScript
167 lines
11 KiB
TypeScript
/** Bounded private terminal-history representation. This module neither claims
|
|
* work nor refunds a quota. Only the locked source owner may publish its result. */
|
|
import { createHash } from "node:crypto"
|
|
import { gzipSync, gunzipSync } from "node:zlib"
|
|
import { z } from "zod"
|
|
import type { ServerPollHistoryRows } from "./server-poll-history-verification.js"
|
|
|
|
export const SERVER_POLL_ARCHIVE_MAX_BYTES = 131072
|
|
export const SERVER_POLL_ARCHIVE_MAX_DECODED_BYTES = 16 * 1024 * 1024
|
|
const MAX_COMPRESSED_BYTES = 96 * 1024 - 256
|
|
const sha = (value: string | Buffer) => createHash("sha256").update(value).digest("hex")
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/), uuid = z.string().uuid()
|
|
const positive = z.number().int().positive().safe()
|
|
const owner = z.string().min(1).max(200).refine(value => value.trim() === value && !/[\x00-\x1f\x7f]/.test(value))
|
|
export class ServerPollArchiveRefused extends Error {
|
|
readonly automaticReplay = false
|
|
constructor() { super("Terminal poll history cannot be authenticated"); this.name = "ServerPollArchiveRefused" }
|
|
}
|
|
const refuse = (): never => { throw new ServerPollArchiveRefused() }
|
|
|
|
/** UTC, retaining all six PostgreSQL fractional digits. A JS Date alone would
|
|
* silently discard microseconds and weaken the original activity binding. */
|
|
export function canonicalPollArchiveTimestamp(raw: unknown): string {
|
|
if (typeof raw !== "string") return refuse()
|
|
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(raw)
|
|
if (!match) return refuse()
|
|
const millis = Date.parse(raw)
|
|
if (!Number.isFinite(millis) || millis < 0 || new Date(millis).toISOString().slice(0, 19) !== match[1]) return refuse()
|
|
return match[1] + "." + (match[2] ?? "").padEnd(6, "0") + "Z"
|
|
}
|
|
const timestamp = z.string().transform(canonicalPollArchiveTimestamp)
|
|
const metadataSchema = z.object({
|
|
version: z.literal(1), receipt_id: uuid, execution_id: uuid, connection_id: uuid, owner_id: owner,
|
|
binding_proof: hash, context_proof: hash, source_digest: hash, source_sha256: hash, terminal_digest: hash,
|
|
original_activity_at: timestamp, original_expires_at: timestamp,
|
|
retention_days: z.number().int().min(1).max(365), safety_ms: z.literal(60000),
|
|
decoded_bytes: positive.max(SERVER_POLL_ARCHIVE_MAX_DECODED_BYTES), compressed_bytes: positive.max(MAX_COMPRESSED_BYTES),
|
|
ciphertext_bytes: positive.max(SERVER_POLL_ARCHIVE_MAX_BYTES), ciphertext_sha256: hash,
|
|
})
|
|
export type ServerPollArchiveMetadata = z.infer<typeof metadataSchema>
|
|
export type ServerPollTerminalArchive = ServerPollArchiveMetadata & { ciphertext: string; archive_proof: string }
|
|
export interface ServerPollArchiveSource {
|
|
admission: Record<string, unknown>
|
|
journal: ServerPollHistoryRows
|
|
terminal: { operation: Record<string, unknown>; plan: Record<string, unknown>; step: Record<string, unknown> }
|
|
}
|
|
export interface ServerPollArchiveSourceMetadata {
|
|
receiptId: string; executionId: string; connectionId: string; ownerId: string
|
|
bindingProof: string; contextProof: string; originalActivityAt: string; originalExpiresAt: string
|
|
retentionDays: number; safetyMs: number; terminalDigest: string
|
|
}
|
|
export interface ServerPollArchiveDependencies {
|
|
encrypt(value: Buffer): Promise<Buffer>
|
|
decrypt(value: Buffer): Promise<Buffer>
|
|
proof(purpose: string, value: unknown): Promise<string>
|
|
/** Test-only composition. Production always calls both fixed source verifiers. */
|
|
verifySource(source: ServerPollArchiveSource, now: number): Promise<ServerPollArchiveSourceMetadata>
|
|
}
|
|
const sourceSchema = z.object({ admission: z.record(z.string(), z.unknown()),
|
|
journal: z.object({ execution: z.record(z.string(), z.unknown()), intents: z.array(z.record(z.string(), z.unknown())).max(2008),
|
|
acks: z.array(z.record(z.string(), z.unknown())).max(2008), receipt: z.record(z.string(), z.unknown()),
|
|
quarantines: z.array(z.record(z.string(), z.unknown())).max(1) }).strict(),
|
|
terminal: z.object({ operation: z.record(z.string(), z.unknown()), plan: z.record(z.string(), z.unknown()),
|
|
step: z.record(z.string(), z.unknown()) }).strict(),
|
|
}).strict()
|
|
const production: ServerPollArchiveDependencies = {
|
|
async encrypt(value) { return (await import("../modules/mcp/security.js")).encryptBinary(value) },
|
|
async decrypt(value) { return (await import("../modules/mcp/security.js")).decryptBinary(value) },
|
|
async proof(purpose, value) {
|
|
const security = await import("../modules/mcp/security.js")
|
|
return security.privateSecretFingerprint(security.fingerprint(value), purpose)
|
|
},
|
|
async verifySource(source, now) {
|
|
const history = await (await import("./server-poll-history-verification.js")).verifyServerPollHistory(source.journal)
|
|
return (await import("./server-poll-terminal-source.js")).verifyServerPollTerminalSource(source, history, now)
|
|
},
|
|
}
|
|
const RECORD_PURPOSE = "server-poll-terminal-archive-record-v1"
|
|
const SOURCE_PURPOSE = "server-poll-terminal-archive-source-v1"
|
|
|
|
function codec(raw: ServerPollArchiveDependencies) {
|
|
const deps = Object.freeze({ ...raw })
|
|
const source = (text: string): ServerPollArchiveSource => {
|
|
if (typeof text !== "string" || !text.length || Buffer.byteLength(text) > SERVER_POLL_ARCHIVE_MAX_DECODED_BYTES) return refuse()
|
|
try { return sourceSchema.parse(JSON.parse(text)) } catch { return refuse() }
|
|
}
|
|
const metadata = (verified: ServerPollArchiveSourceMetadata) => ({ version: 1 as const, receipt_id: verified.receiptId,
|
|
execution_id: verified.executionId, connection_id: verified.connectionId, owner_id: verified.ownerId,
|
|
binding_proof: verified.bindingProof, context_proof: verified.contextProof, terminal_digest: verified.terminalDigest,
|
|
original_activity_at: canonicalPollArchiveTimestamp(verified.originalActivityAt),
|
|
original_expires_at: canonicalPollArchiveTimestamp(verified.originalExpiresAt), retention_days: verified.retentionDays, safety_ms: verified.safetyMs })
|
|
const proof = async (purpose: string, value: unknown) => hash.parse(await deps.proof(purpose, value))
|
|
const readMetadata = async (row: unknown) => {
|
|
try {
|
|
const parsed = metadataSchema.parse(row), archiveProof = hash.parse((row as Record<string, unknown>).archive_proof)
|
|
if (archiveProof !== await proof(RECORD_PURPOSE, { ...parsed, identity_kind: "mcp", storage_state: "compacted", admission_bytes: 32768, charged_rows: 2 })) return refuse()
|
|
return parsed
|
|
} catch { return refuse() }
|
|
}
|
|
return Object.freeze({
|
|
/** Undefined means too large; the caller MUST keep the complete full charge.
|
|
* Invalid source is an error, never a compactable partial history. */
|
|
async create(sourceText: string, now: number): Promise<ServerPollTerminalArchive | undefined> {
|
|
try {
|
|
if (!Number.isSafeInteger(now) || now < 0) return refuse()
|
|
const parsed = source(sourceText), verified = await deps.verifySource(parsed, now)
|
|
let compressed: Buffer
|
|
try { compressed = gzipSync(Buffer.from(sourceText), { level: 6, maxOutputLength: MAX_COMPRESSED_BYTES }) }
|
|
catch (error) {
|
|
if ((error as { code?: string }).code === "ERR_BUFFER_TOO_LARGE") return undefined
|
|
return refuse()
|
|
}
|
|
const encrypted = await deps.encrypt(compressed), ciphertext = encrypted.toString("base64")
|
|
if (Buffer.byteLength(ciphertext) > SERVER_POLL_ARCHIVE_MAX_BYTES) return undefined
|
|
const sourceSha = sha(sourceText)
|
|
const unsigned = metadataSchema.parse({ ...metadata(verified), source_sha256: sourceSha,
|
|
source_digest: await proof(SOURCE_PURPOSE, sourceSha), decoded_bytes: Buffer.byteLength(sourceText),
|
|
compressed_bytes: compressed.length, ciphertext_bytes: Buffer.byteLength(ciphertext), ciphertext_sha256: sha(ciphertext) })
|
|
const archive_proof = await proof(RECORD_PURPOSE, { ...unsigned, identity_kind: "mcp", storage_state: "compacted", admission_bytes: 32768, charged_rows: 2 })
|
|
return { ...unsigned, ciphertext, archive_proof }
|
|
} catch { return refuse() }
|
|
},
|
|
/** SQL must supply ACTUAL ciphertext digest/length, not stored assertions.
|
|
* This bounded metadata verifier does not decrypt or hydrate all archives. */
|
|
async verifyCharge(row: unknown): Promise<{ bytes: number; rows: 2; metadata: ServerPollArchiveMetadata }> {
|
|
const parsed = await readMetadata(row)
|
|
return { bytes: parsed.ciphertext_bytes + 32768, rows: 2, metadata: parsed }
|
|
},
|
|
async open(row: unknown, now: number): Promise<{ sourceText: string; source: ServerPollArchiveSource; metadata: ServerPollArchiveMetadata }> {
|
|
if (!Number.isSafeInteger(now) || now < 0) return refuse()
|
|
const parsed = await readMetadata(row), ciphertext = (row as Record<string, unknown>).ciphertext
|
|
if (typeof ciphertext !== "string" || Buffer.byteLength(ciphertext) !== parsed.ciphertext_bytes || sha(ciphertext) !== parsed.ciphertext_sha256 ||
|
|
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(ciphertext)) return refuse()
|
|
try {
|
|
const binary = Buffer.from(ciphertext, "base64")
|
|
if (binary.toString("base64") !== ciphertext) return refuse()
|
|
const compressed = await deps.decrypt(binary)
|
|
if (compressed.length !== parsed.compressed_bytes) return refuse()
|
|
const decoded = gunzipSync(compressed, { maxOutputLength: SERVER_POLL_ARCHIVE_MAX_DECODED_BYTES })
|
|
if (decoded.length !== parsed.decoded_bytes) return refuse()
|
|
const text = decoded.toString("utf8")
|
|
if (!Buffer.from(text).equals(decoded) || sha(text) !== parsed.source_sha256 || await proof(SOURCE_PURPOSE, parsed.source_sha256) !== parsed.source_digest) return refuse()
|
|
const original = source(text), verified = await deps.verifySource(original, now)
|
|
const authenticated = metadataSchema.parse({ ...parsed, ...metadata(verified) })
|
|
if (JSON.stringify(authenticated) !== JSON.stringify(parsed)) return refuse()
|
|
return { sourceText: text, source: original, metadata: parsed }
|
|
} catch { return refuse() }
|
|
},
|
|
})
|
|
}
|
|
const productionCodec = codec(production)
|
|
export const createServerPollTerminalArchive = productionCodec.create
|
|
export const openServerPollTerminalArchive = productionCodec.open
|
|
export const verifyServerPollArchiveCharge = productionCodec.verifyCharge
|
|
/** Derive the existing fixed verification purpose once for one bounded SQL
|
|
* pass. This caches no row, accounting total, permission or admission result. */
|
|
export async function createServerPollArchiveChargeVerifier() {
|
|
const security = await import("../modules/mcp/security.js")
|
|
const signer = await security.privateFingerprinterExisting(RECORD_PURPOSE)
|
|
return codec({ ...production, proof: async (purpose, value) => {
|
|
if (purpose !== RECORD_PURPOSE) return refuse()
|
|
return signer(security.fingerprint(value))
|
|
} }).verifyCharge
|
|
}
|
|
/** Explicit deterministic component composition, never accepted from an API. */
|
|
export const createServerPollTerminalArchiveForTests = (dependencies: ServerPollArchiveDependencies) => codec(dependencies)
|