@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
239 lines • 11.3 kB
JavaScript
import { generateKeyPairSync, sign } from "node:crypto";
import { isRecord } from "../../core/extensions/builtin/mcp/modern/form-schema.js";
import { boundedClaim, presenterKeyThumbprint } from "./mcp-presenter-attestation.js";
import { secretRequestTranscript } from "./secret-sealed.js";
/**
* Host tokens of the sealed secret route (D11 secret phase, section 3). One in-memory Ed25519 host key per host
* instance, never persisted; one issuer token per `(hostInstance, durableSessionId)` while a current grant on that
* session negotiated `secret_input_v1`, re-minted at two thirds of its lifetime and dropped with the last such grant.
* A request reads the cache synchronously, so secret routing never awaits the issuer.
*/
const HOST_TOKEN_AUDIENCE = "omo-secret-host";
const HOST_TOKEN_TYPE = "secret_host";
/** The issuer's lifetime ceiling and clock skew for a host token (3.2). */
const MAX_LIFETIME_S = 900;
const SKEW_S = 60;
const MAX_TOKEN_CHARS = 8192;
/** A mint that has not settled by then counts as failed; its late result is ignored. */
const MINT_TIMEOUT_MS = 30_000;
/** After a failed mint, while a holder remains: retry within this, sooner when a cached token expires first. */
const RETRY_MAX_MS = 60_000;
const RETRY_MIN_MS = 5_000;
/** A retry is armed at least this far before the cached token's `exp`, so it lands before the token does. */
const RETRY_BEFORE_EXP_MS = 1_000;
/**
* A retry never fires sooner than this after a failure. Without a floor, a near-expiry failure armed the next
* retry at 0 ms and a failing issuer got back-to-back mint calls until `exp` (senpi#5919 review). 250 ms is the
* low end of the suggested 250-500 ms range: a retry armed with over 1.25 s left still lands at least 1 s
* before `exp`, while the burst in the final second is bounded to a handful of attempts.
*/
const RETRY_MIN_WAIT_MS = 250;
function sealedRouteAuthority(authority) {
return typeof authority?.mintSecretHostToken === "function" && typeof authority.verifySecretAnswer === "function";
}
function claimsOf(token) {
const parts = token.split(".");
if (parts.length !== 3)
return undefined;
try {
const claims = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
return isRecord(claims) ? claims : undefined;
}
catch {
return undefined;
}
}
export class SecretHostTokens {
/** `undefined` unless the authority can both mint host tokens and verify step-up tokens: then no key exists. */
static create(hostInstance, authority) {
return sealedRouteAuthority(authority) ? new SecretHostTokens(hostInstance, authority) : undefined;
}
constructor(hostInstance, authority) {
this.entries = new Map();
this.listeners = new Set();
this.disposed = false;
this.hostInstance = hostInstance;
this.authority = authority;
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
this.privateKey = privateKey;
this.spki = publicKey.export({ type: "spki", format: "der" });
const jkt = presenterKeyThumbprint(this.spki);
if (jkt === undefined)
throw new Error("secret_host_key_unavailable");
this.hostJkt = jkt;
this.hostPk = this.spki.subarray(12).toString("base64url");
}
/**
* A grant with `secret_input_v1` was acquired on `binding`. Mints the session's token unless a valid one is held;
* `held` reports whether a current account-principal grant on the binding still negotiates the feature.
*/
want(durableSessionId, binding, held) {
if (this.disposed || !binding.subscribe || !held())
return;
let entry = this.entries.get(durableSessionId);
if (entry && entry.binding !== binding) {
this.drop(durableSessionId, entry);
entry = undefined;
}
if (!entry) {
const created = { binding, held, minting: false };
created.unsubscribe = binding.subscribe(() => {
if (!held())
this.drop(durableSessionId, created);
});
this.entries.set(durableSessionId, created);
entry = created;
}
if (!entry.minting && (entry.refresh === undefined || !this.valid(entry.token)))
void this.mint(durableSessionId, entry);
}
/** The session's token while it is valid now and still names the signed-in account; read synchronously. */
current(durableSessionId) {
const token = this.entries.get(durableSessionId)?.token;
return this.valid(token) ? token : undefined;
}
valid(token) {
return token !== undefined && Date.now() < token.exp * 1000 && token.acc === this.authority.hostAccount();
}
/**
* The host key's signature over a request binding, as 128 lowercase hex characters (0022 3.5). It signs only a `B`
* naming this host instance and this key, so the key signs nothing outside the request domain for another host.
*/
signRequest(binding) {
if (binding[1] !== this.hostInstance || binding[2] !== this.hostJkt)
throw new Error("secret_request_foreign");
return sign(null, Buffer.from(secretRequestTranscript(binding)), this.privateKey).toString("hex");
}
/** Fires after every successful mint or re-mint, so pending sealed requests can carry the new token (3.2). */
onToken(listener) {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
dispose() {
this.listeners.clear();
this.disposed = true;
for (const [durableSessionId, entry] of [...this.entries])
this.drop(durableSessionId, entry);
}
async mint(durableSessionId, entry) {
clearTimeout(entry.refresh);
entry.refresh = undefined;
entry.minting = true;
let open = true;
const proof = (input) => {
const { issuer, nonce } = input;
if (!open ||
typeof issuer !== "string" ||
typeof nonce !== "string" ||
!boundedClaim(issuer) ||
!boundedClaim(nonce))
throw new Error("secret_host_proof_refused");
const transcript = [
"omo-secret-host-proof/v1",
issuer,
HOST_TOKEN_AUDIENCE,
this.hostJkt,
nonce,
this.hostInstance,
durableSessionId,
].join("\n");
return sign(null, Buffer.from(transcript), this.privateKey).toString("base64url");
};
let minted;
let deadline;
try {
if (this.authority.hostAccount() !== undefined) {
const call = (async () => this.authority.mintSecretHostToken({
hostInstance: this.hostInstance,
durableSessionId,
hostKeySpki: new Uint8Array(this.spki),
sign: proof,
}))();
const timedOut = new Promise((resolve) => {
deadline = setTimeout(() => resolve(undefined), MINT_TIMEOUT_MS);
deadline.unref();
});
// An issuer or authority fault leaves the raiser route only; the key and the session are unaffected.
minted = await Promise.race([call.catch(() => undefined), timedOut]);
}
}
finally {
clearTimeout(deadline);
open = false;
entry.minting = false;
}
if (this.disposed || this.entries.get(durableSessionId) !== entry)
return;
const token = typeof minted === "string" ? this.accept(minted, durableSessionId) : undefined;
if (token) {
entry.token = token;
for (const listener of [...this.listeners])
listener(durableSessionId, token);
this.arm(durableSessionId, entry, ((token.exp * 1000 - Date.now()) * 2) / 3);
return;
}
// While a holder remains, a failure is retried; a still-valid token is kept until its own `exp` (3.2).
// The retry must land before that `exp`: with under ~5 s left the 5 s floor alone would push the
// attempt past it, so the wait is capped at 1 s before `exp` (senpi#5919). The cap keeps a small
// minimum wait (`RETRY_MIN_WAIT_MS`) so a failure in the last second cannot arm the next retry at
// 0 ms and hammer a failing issuer back-to-back until `exp`. Without a valid token the retry stays
// at the 60 s bound.
if (!entry.held())
return;
const remainingMs = this.valid(entry.token) ? entry.token.exp * 1000 - Date.now() : undefined;
const left = remainingMs === undefined ? RETRY_MAX_MS : remainingMs / 3;
let delay = Math.min(RETRY_MAX_MS, Math.max(RETRY_MIN_MS, left));
if (remainingMs !== undefined)
delay = Math.min(delay, Math.max(RETRY_MIN_WAIT_MS, remainingMs - RETRY_BEFORE_EXP_MS));
this.arm(durableSessionId, entry, delay);
}
/** The claims the engine relies on, checked against what it asked for; anything else is not this session's token. */
accept(token, durableSessionId) {
if (token.length === 0 || token.length > MAX_TOKEN_CHARS)
return undefined;
const claims = claimsOf(token);
if (!claims || !isRecord(claims.cnf))
return undefined;
const { aud, typ, acc, dev, iat, exp, hin, sid } = claims;
const nowS = Math.floor(Date.now() / 1000);
if (aud !== HOST_TOKEN_AUDIENCE ||
typ !== HOST_TOKEN_TYPE ||
hin !== this.hostInstance ||
sid !== durableSessionId ||
claims.cnf.jkt !== this.hostJkt ||
typeof acc !== "string" ||
acc !== this.authority.hostAccount() ||
typeof dev !== "string" ||
!boundedClaim(dev) ||
typeof iat !== "number" ||
typeof exp !== "number" ||
!Number.isSafeInteger(iat) ||
!Number.isSafeInteger(exp) ||
exp <= iat ||
exp - iat > MAX_LIFETIME_S ||
iat > nowS + SKEW_S ||
nowS >= exp)
return undefined;
return Object.freeze({ token, acc, dev, iat, exp });
}
/** Re-mints after `delayMs`, measured on the local clock so issuer clock skew cannot shorten it. */
arm(durableSessionId, entry, delayMs) {
clearTimeout(entry.refresh);
entry.refresh = setTimeout(() => {
entry.refresh = undefined;
if (!this.disposed && this.entries.get(durableSessionId) === entry && !entry.minting)
void this.mint(durableSessionId, entry);
}, Math.max(0, delayMs));
// The host's own lifetime decides when it exits; a pending refresh never holds the process.
entry.refresh.unref();
}
drop(durableSessionId, entry) {
clearTimeout(entry.refresh);
entry.refresh = undefined;
entry.token = undefined;
entry.unsubscribe?.();
if (this.entries.get(durableSessionId) === entry)
this.entries.delete(durableSessionId);
}
}
//# sourceMappingURL=secret-host-token.js.map