@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
70 lines (69 loc) • 3.24 kB
JavaScript
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { link, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import { ciDigest, CI_FAILURE_SCOPE, ciSubmissionSchema } from "./ci-failure-contract.js";
import { BridgeError, bridgeRoot, targetSchema } from "./protocol.js";
const ORIGIN_TTL = 7 * 86_400_000;
export const CI_REPORTER_HEADER = "x-phren-ci-reporter";
export const CI_PROOF_HEADER = "x-phren-ci-proof";
const originSchema = z.object({
submission: ciSubmissionSchema, target: targetSchema, terminal: z.string().min(1).max(200),
issuedAt: z.number().int(), nonce: z.string().uuid(),
}).strict();
async function key(create = false) {
const root = bridgeRoot(), file = path.join(root, "ci-handoff.key");
try {
const bytes = await readFile(file);
if (bytes.length !== 32)
throw new Error("Invalid CI hand-off key.");
return bytes;
}
catch (error) {
if (!create || error.code !== "ENOENT")
throw error;
}
await mkdir(root, { recursive: true, mode: 0o700 });
const scratch = `${file}.${randomBytes(16).toString("hex")}.tmp`;
try {
await writeFile(scratch, randomBytes(32), { mode: 0o600, flag: "wx" });
// Publish a complete key exactly once, even when two jobs are submitted together.
await link(scratch, file).catch(error => { if (error.code !== "EEXIST")
throw error; });
}
finally {
await unlink(scratch).catch(() => undefined);
}
return key();
}
const mac = (secret, ...parts) => createHmac("sha256", secret).update(JSON.stringify(parts)).digest("hex");
function validMac(actual, expected) {
const checked = ciDigest.safeParse(actual);
return checked.success && timingSafeEqual(Buffer.from(checked.data, "hex"), Buffer.from(expected, "hex"));
}
export async function issueCiOrigin(origin) {
const encoded = Buffer.from(JSON.stringify(originSchema.parse(origin))).toString("base64url");
return `${encoded}.${mac(await key(true), "origin-v1", encoded)}`;
}
export async function verifyCiOrigin(token) {
const [encoded, signature] = token.split(".");
const secret = await key();
if (validMac(signature, mac(secret, "origin-v1", encoded))) {
const origin = originSchema.parse(JSON.parse(Buffer.from(encoded, "base64url").toString()));
const age = Date.now() - origin.issuedAt;
if (age >= 0 && age <= ORIGIN_TTL)
return origin;
}
throw new BridgeError(403, "The submitted CI origin is invalid or expired.", { code: "ci-origin-invalid" });
}
export async function signCiIngress(reporter, bodyDigest) {
return mac(await key(), CI_FAILURE_SCOPE, reporter, bodyDigest);
}
export async function authenticatedCiReporter(reporter, proof, bodyDigest) {
if (ciDigest.safeParse(reporter).success && ciDigest.safeParse(proof).success) {
const expected = await signCiIngress(String(reporter), bodyDigest).catch(() => undefined);
if (expected && validMac(proof, expected))
return String(reporter);
}
throw new BridgeError(403, "An authenticated CI reporting key is required.");
}