@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
233 lines • 10.7 kB
JavaScript
/**
* This device's own key-check records (`LocalKeyVerification`) and service-entry validity (custody design
* 2.2 / 3.1).
*
* One JSON file under `<agentDir>/state/custody/verified-keys.json`, shared by relayd and the CLI/hand
* process. A record binds the checked KEYS (SPKI hashes, ARNs, template version, account), not only their
* ids, so an attacker entry that copies the ids of a checked key never matches. A record only ever grants
* validity, so the read side fails closed: a file that exists but cannot be parsed reads as `unknown`, and a
* record without the `verifierKeyId` that vouched for its facts counts as absent (the device checks again).
*/
import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { getAgentDir } from "../../config.js";
import { lockWithLossHandling } from "../file-lock.js";
import { decodeBase64 } from "./ecdsa-p256.js";
import { rosterViewAt, verifyServiceSig, } from "./roster-entries.js";
import { isVouchRevoked } from "./verifier-revocations.js";
const REQUIRED_STRINGS = ["accountId", "sigKeyId", "sigPkSha256"];
const OPTIONAL_STRINGS = ["kemKeyId", "kemPkSha256", "supersedes"];
const RECORD_KEYS = [
"kind",
"generation",
"kmsKeyArns",
"templateVersion",
"verifierKeyId",
"vouchedAt",
"checkedAt",
...REQUIRED_STRINGS,
...OPTIONAL_STRINGS,
];
export function verifiedKeysPath(agentDir = getAgentDir()) {
return join(agentDir, "state", "custody", "verified-keys.json");
}
const isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
const isText = (value) => typeof value === "string" && value.length > 0;
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
/** `"absent"` for a record without `verifierKeyId`; `undefined` for a malformed one. */
function parseRecord(value) {
if (!isRecord(value))
return undefined;
const raw = value;
if (!Object.keys(raw).every((key) => RECORD_KEYS.some((known) => known === key)))
return undefined;
const { kind, accountId, generation, sigKeyId, sigPkSha256, kemKeyId, kemPkSha256, kmsKeyArns, templateVersion, verifierKeyId, vouchedAt, supersedes, checkedAt, } = raw;
if (kind !== "custody" && kind !== "placement-registry")
return undefined;
if (verifierKeyId === undefined)
return "absent";
if (!isText(verifierKeyId) || !isCount(vouchedAt))
return undefined;
if (!isText(accountId) || !isText(sigKeyId) || !isText(sigPkSha256))
return undefined;
if (!isCount(generation) || !isCount(templateVersion) || !isCount(checkedAt))
return undefined;
if (!Array.isArray(kmsKeyArns) || !kmsKeyArns.every(isText))
return undefined;
if ([kemKeyId, kemPkSha256, supersedes].some((optional) => optional !== undefined && !isText(optional)))
return undefined;
return {
kind,
accountId,
generation,
sigKeyId,
sigPkSha256,
...(isText(kemKeyId) ? { kemKeyId } : {}),
...(isText(kemPkSha256) ? { kemPkSha256 } : {}),
kmsKeyArns: [...kmsKeyArns],
templateVersion,
verifierKeyId,
vouchedAt,
...(isText(supersedes) ? { supersedes } : {}),
checkedAt,
};
}
function parseFile(text) {
let value;
try {
value = JSON.parse(text);
}
catch {
return undefined;
}
if (!isRecord(value))
return undefined;
const file = value;
if (file.v !== 2 || !Array.isArray(file.records))
return undefined;
const records = [];
for (const raw of file.records) {
const record = parseRecord(raw);
if (!record)
return undefined;
if (record !== "absent")
records.push(record);
}
return records;
}
export async function readVerifiedKeys(path) {
let text;
try {
text = await readFile(path, "utf8");
}
catch (error) {
const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
return missing ? { state: "ok", records: [] } : { state: "unknown" };
}
const records = parseFile(text);
return records ? { state: "ok", records } : { state: "unknown" };
}
async function spkiSha256(spkiBase64) {
const bytes = decodeBase64(spkiBase64);
if (!bytes)
return undefined;
return Buffer.from(await crypto.subtle.digest("SHA-256", bytes)).toString("base64");
}
/**
* The record this device stores after `checkServiceKey` returned `ok` for `entry`. `undefined` when the
* entry belongs to another account or its self-signature does not verify: such an entry can never be recorded.
*/
export async function verificationFor(entry, accountId, checkedAt, vouch) {
if (entry.accountId !== accountId || !(await verifyServiceSig(entry)))
return undefined;
const sigPkSha256 = await spkiSha256(entry.sigPk);
const kemPkSha256 = entry.kemPk === undefined ? undefined : await spkiSha256(entry.kemPk);
if (!sigPkSha256 || (entry.kemPk !== undefined && !kemPkSha256))
return undefined;
return {
kind: entry.kind,
accountId: entry.accountId,
generation: entry.generation,
sigKeyId: entry.sigKeyId,
sigPkSha256,
...(entry.kemKeyId === undefined ? {} : { kemKeyId: entry.kemKeyId }),
...(kemPkSha256 === undefined ? {} : { kemPkSha256 }),
kmsKeyArns: [...entry.kmsKeyArns],
templateVersion: entry.templateVersion,
verifierKeyId: vouch.verifierKeyId,
vouchedAt: vouch.vouchedAt,
...(entry.supersedes === undefined ? {} : { supersedes: entry.supersedes }),
checkedAt,
};
}
/**
* The checked keys match. `supersedes` is not part of the binding: a revocation stays sticky on the record
* (`recordVerification`) and a disagreement between published entries is the twin rule's to judge (15.11, gate r8 M-4).
*/
function sameBinding(a, b) {
return (a.kind === b.kind &&
a.accountId === b.accountId &&
a.generation === b.generation &&
a.sigKeyId === b.sigKeyId &&
a.sigPkSha256 === b.sigPkSha256 &&
a.kemKeyId === b.kemKeyId &&
a.kemPkSha256 === b.kemPkSha256 &&
a.templateVersion === b.templateVersion &&
a.kmsKeyArns.length === b.kmsKeyArns.length &&
a.kmsKeyArns.every((arn, index) => arn === b.kmsKeyArns[index]));
}
export async function findVerification(records, entry) {
const expected = await verificationFor(entry, entry.accountId, 0, { verifierKeyId: "", vouchedAt: 0 });
return expected && records.find((record) => sameBinding(record, expected));
}
/**
* Validity of a service entry FOR THIS DEVICE in `accountId`. Only this device's own records count; other
* devices' attestations and revocations never do. Two validly signed entries for one (kind, account,
* generation) that differ in key, or share the key but disagree on `supersedes`, make the entry `unknown`. Supersession comes from this device's records only
* (a checked entry of the same kind and account, strictly higher generation, naming this `sigKeyId`), so it
* cannot be undone by an entry disappearing from a later roster. The roster view must be fresh (15.15 H-1), and a
* record vouched by a revoked verifier key (15.10) never makes an entry `valid`; it still supersedes, because a
* revocation only ever removes trust.
*/
export async function serviceEntryValidity(entry, accountId, records, roster, context) {
const view = rosterViewAt(roster, context.now, context.nowMono);
if (view.state === "unknown")
return "unknown";
if (entry.accountId !== accountId || !(await verifyServiceSig(entry)))
return "invalid";
for (const other of view.serviceEntries) {
if (other.kind !== entry.kind || other.accountId !== entry.accountId || other.generation !== entry.generation)
continue;
const sameKey = other.sigKeyId === entry.sigKeyId && other.sigPk === entry.sigPk && other.kemPk === entry.kemPk;
const twin = !sameKey || other.supersedes !== entry.supersedes;
if (twin && (await verifyServiceSig(other)))
return "unknown";
}
const revoked = records.some((record) => record.kind === entry.kind &&
record.accountId === entry.accountId &&
record.generation > entry.generation &&
record.supersedes === entry.sigKeyId);
if (revoked)
return "superseded";
const vouched = records.filter((record) => !isVouchRevoked(context.revocations, record.verifierKeyId, record.vouchedAt));
return (await findVerification(vouched, entry)) ? "valid" : "pending";
}
export async function recordVerification(path, record) {
const dir = dirname(path);
await mkdir(dir, { recursive: true, mode: 0o700 });
const stop = new AbortController();
const lock = await lockWithLossHandling(dir, {
realpath: false,
lockfilePath: `${path}.lock`,
retries: { retries: 50, minTimeout: 20, maxTimeout: 200 },
// A lost lock aborts the temp-file write, so nothing more is written after the loss.
onLost: (error) => stop.abort(error),
});
try {
const current = await readVerifiedKeys(path);
// An unreadable file is replaced: dropping records only forces re-checks, never grants trust.
const kept = current.state === "ok" ? current.records : [];
const replaced = (existing) => existing.kind === record.kind &&
existing.accountId === record.accountId &&
existing.generation === record.generation &&
existing.sigKeyId === record.sigKeyId;
// A revocation is sticky: re-checking the same key never clears the `supersedes` an earlier record carried, even when
// its signer later publishes the entry without it (15.11, gate round 6 M-5).
const revoked = kept.find((existing) => replaced(existing) && existing.supersedes !== undefined)?.supersedes;
const merged = revoked === undefined ? record : { ...record, supersedes: revoked };
const next = { v: 2, records: [...kept.filter((existing) => !replaced(existing)), merged] };
const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
await writeFile(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, signal: stop.signal });
await chmod(tmp, 0o600);
lock.assertHeld();
await rename(tmp, path);
}
catch (error) {
lock.assertHeld();
throw error;
}
finally {
await lock.release();
}
}
//# sourceMappingURL=verified-keys.js.map