Repository Public
1// SP Vault Connect + Agents: workload identities, scoped grants, approvals, leases, kill switch, brokered operations.2// Values live in the separate managed-secrets process; this module never sees them except while relaying a3// "read" delivery that a human approved. Not zero-knowledge — the UI and docs say so everywhere.4import crypto from "node:crypto";5import fs from "node:fs";6import type { FastifyInstance, FastifyRequest } from "fastify";7import { z } from "zod";8import { ctx, unb64u } from "../../../packages/protocol/src/bytes.ts";9import { verify as ecdsaVerify } from "../../../packages/protocol/src/primitives.ts";10import { audit, bad, HttpError, need, needStrong, notFound, publish, rateLimit, sql } from "./core.ts";11import { parse, uuid } from "./auth.ts";1213const managedUrl = process.env.SPV_MANAGED_URL ?? "";14const managedToken = () => fs.readFileSync(process.env.SPV_MANAGED_TOKEN_FILE!, "utf8").trim();15async function managed(method: string, path: string, body: object): Promise<any> {16 if (!managedUrl) throw new HttpError(503, "managed_unavailable", "The managed-secrets service is not enabled on this server");17 const r = await fetch(managedUrl + path, { method, headers: { "content-type": "application/json", "x-spv-managed": managedToken() }, body: JSON.stringify(body), signal: AbortSignal.timeout(20000) }).catch(() => null);18 if (!r) throw new HttpError(503, "managed_unavailable");19 const j: any = await r.json().catch(() => ({}));20 if (!r.ok) throw new HttpError(r.status === 401 ? 503 : r.status, "managed_error", j.message ?? "managed-secrets error");21 return j;22}2324// ── policy engine (pure) ─────────────────────────────────────────────────────────────────────────────────────25export interface PolicyInput {26 now: number; killed: boolean; identityRevoked: boolean; secretDeleted: boolean; secretExpiresAt: number | null;27 grant: { mode: "operate" | "read"; approval: "never" | "lease" | "each"; expiresAt: number; revoked: boolean; maxUses: number | null; uses: number; constraints: { methods?: string[]; pathPrefix?: string } };28 op: { kind: "http" | "sign" | "read"; method?: string; path?: string };29 secretKind: string; activeLease: boolean;30}31export type Decision = { decision: "allow" } | { decision: "approval" } | { decision: "deny"; reason: string };3233export function evaluate(i: PolicyInput): Decision {34 const deny = (reason: string): Decision => ({ decision: "deny", reason });35 if (i.killed) return deny("kill switch engaged: all agent access is suspended");36 if (i.identityRevoked) return deny("identity revoked");37 if (i.grant.revoked) return deny("grant revoked");38 if (i.secretDeleted) return deny("secret deleted");39 if (i.grant.expiresAt <= i.now) return deny("grant expired");40 if (i.secretExpiresAt !== null && i.secretExpiresAt <= i.now) return deny("secret expired");41 if (i.grant.maxUses !== null && i.grant.uses >= i.grant.maxUses) return deny("usage limit reached");42 if (i.op.kind === "read" && i.grant.mode !== "read") return deny("this grant allows brokered operations only, not reading the secret");43 if (i.op.kind === "sign" && i.secretKind !== "hmac") return deny("this secret cannot sign");44 if (i.op.kind === "http" && !i.secretKind.startsWith("http-")) return deny("this secret cannot be used for HTTP calls");45 if (i.op.kind === "http") {46 const c = i.grant.constraints;47 if (c.methods && !c.methods.includes(String(i.op.method).toUpperCase())) return deny("method not permitted by the grant");48 if (c.pathPrefix && !String(i.op.path ?? "").startsWith(c.pathPrefix)) return deny("path not permitted by the grant");49 }50 // Delivering a raw secret is always a high-risk operation: a human approves every single time.51 if (i.op.kind === "read") return { decision: "approval" };52 if (i.grant.approval === "never") return { decision: "allow" };53 if (i.grant.approval === "lease" && i.activeLease) return { decision: "allow" };54 return { decision: "approval" };55}5657// ── workload identity: every request is signed with the identity's P-256 key (no bearer secret to steal from logs) ──58const nonces = new Map<string, number>();59setInterval(() => { const t = Date.now(); for (const [k, v] of nonces) if (v < t) nonces.delete(k); }, 60_000).unref();6061declare module "fastify" { interface FastifyRequest { rawBody?: string } }6263async function agentIdentity(req: FastifyRequest) {64 const id = String(req.headers["x-spv-agent"] ?? ""), ts = String(req.headers["x-spv-ts"] ?? ""), nonce = String(req.headers["x-spv-nonce"] ?? ""), sig = String(req.headers["x-spv-sig"] ?? "");65 const unauth = () => new HttpError(401, "unauthenticated");66 if (!/^[0-9a-f-]{36}$/.test(id) || !/^\d{10}$/.test(ts) || !/^[A-Za-z0-9_-]{16,44}$/.test(nonce) || !/^[A-Za-z0-9_-]{86}$/.test(sig)) throw unauth();67 if (Math.abs(Date.now() / 1000 - Number(ts)) > 120) throw new HttpError(401, "unauthenticated", "clock skew too large");68 const [sa] = await sql`select s.*, a.agents_killed_at from service_accounts s join accounts a on a.id = s.account_id where s.id = ${id}`;69 if (!sa) throw unauth();70 const bodyHash = crypto.createHash("sha256").update(req.rawBody ?? "").digest("base64url");71 const pathOnly = req.url.split("?")[0]!;72 if (!(await ecdsaVerify(unb64u(sa.pub), ctx("agent-request", id, req.method, pathOnly, ts, nonce, bodyHash), unb64u(sig)).catch(() => false))) throw unauth();73 const nk = `${id}:${nonce}`;74 if (nonces.has(nk)) throw new HttpError(401, "replay", "request replayed");75 nonces.set(nk, Date.now() + 300_000);76 rateLimit(`agent:${id}`, 120, 60);77 sql`update service_accounts set last_used_at = now() where id = ${id}`.catch(() => {});78 return sa;79}8081const summarize = (s: string, n: number) => s.replace(/[\u0000-\u001f\u007f-\u009f--]/g, " ").slice(0, n);8283export function connectRoutes(app: FastifyInstance) {84 // ════ human side (authenticated device session) ═══════════════════════════════════════════════════════════85 app.get("/api/v1/connect", async (req) => {86 const s = await need(req, "device");87 const [a] = await sql`select agents_killed_at from accounts where id = ${s.accountId}`;88 const [identities, secrets, grants, approvals] = await Promise.all([89 sql`select id, name, kind, created_at, revoked_at, last_used_at from service_accounts where account_id = ${s.accountId} order by created_at`,90 sql`select id, name, kind, config, version, created_at, rotated_at, rotate_every_days, expires_at from managed_secrets where account_id = ${s.accountId} and deleted_at is null order by created_at`,91 sql`select * from agent_grants where account_id = ${s.accountId} order by created_at desc limit 500`,92 sql`select * from agent_approvals where account_id = ${s.accountId} and (status = 'pending' and expires_at > now() or created_at > now() - interval '7 days') order by created_at desc limit 100`,93 ]);94 return {95 enabled: !!managedUrl, killed: !!a.agents_killed_at,96 identities: identities.map((i) => ({ id: i.id, name: i.name, kind: i.kind, createdAt: i.created_at, revoked: !!i.revoked_at, lastUsedAt: i.last_used_at })),97 secrets: secrets.map((x) => ({ id: x.id, name: x.name, kind: x.kind, config: x.config, version: x.version, createdAt: x.created_at, rotatedAt: x.rotated_at, rotateEveryDays: x.rotate_every_days, expiresAt: x.expires_at })),98 grants: grants.map((g) => ({ id: g.id, identityId: g.service_account_id, secretId: g.secret_id, mode: g.mode, approval: g.approval, leaseTtlSec: g.lease_ttl_sec, maxUses: g.max_uses, uses: g.uses, constraints: g.constraints, expiresAt: g.expires_at, revoked: !!g.revoked_at })),99 approvals: approvals.map((p) => ({ id: p.id, grantId: p.grant_id, summary: p.summary, status: p.status === "pending" && p.expires_at < new Date() ? "expired" : p.status, createdAt: p.created_at, expiresAt: p.expires_at })),100 };101 });102103 app.post("/api/v1/connect/identities", async (req) => {104 const s = await needStrong(req);105 const b = parse(z.object({ id: uuid, name: z.string().min(1).max(64), kind: z.enum(["service", "agent"]), pub: z.string().regex(/^[A-Za-z0-9_-]{87}$/) }).strict(), req.body);106 await sql.begin(async (tx) => {107 await tx`insert into service_accounts (id, account_id, name, kind, pub) values (${b.id}, ${s.accountId}, ${b.name}, ${b.kind}, ${b.pub})`;108 await audit(tx, s.accountId, "connect.identity_created", { identity: b.id, kind: b.kind }, s.deviceId);109 });110 return { ok: true };111 });112 app.delete("/api/v1/connect/identities/:id", async (req) => {113 const s = await need(req, "device");114 const id = parse(uuid, (req.params as any).id);115 await sql.begin(async (tx) => {116 if (!(await tx`update service_accounts set revoked_at = now() where id = ${id} and account_id = ${s.accountId} and revoked_at is null returning 1`).length) throw notFound();117 await tx`update agent_grants set revoked_at = now() where service_account_id = ${id} and revoked_at is null`;118 await tx`update agent_leases set revoked_at = now() where grant_id in (select id from agent_grants where service_account_id = ${id}) and revoked_at is null`;119 await audit(tx, s.accountId, "connect.identity_revoked", { identity: id }, s.deviceId);120 });121 return { ok: true };122 });123124 const secretConfig = z.object({125 allowedHosts: z.array(z.string().regex(/^(\*\.)?[a-z0-9.-]{1,253}$/i)).max(20).default([]), allowedMethods: z.array(z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"])).max(5).default(["GET", "POST"]),126 header: z.string().regex(/^[A-Za-z0-9-]{1,64}$/).optional(), prefix: z.string().max(32).optional(), username: z.string().max(128).optional(),127 }).strict();128129 app.post("/api/v1/connect/secrets", async (req) => {130 const s = await needStrong(req);131 const b = parse(z.object({ id: uuid, name: z.string().min(1).max(80), kind: z.enum(["http-bearer", "http-header", "http-basic", "hmac", "raw"]), config: secretConfig, value: z.string().min(1).max(65536),132 rotateEveryDays: z.number().int().min(1).max(3650).optional(), expiresAt: z.string().datetime().optional() }).strict(), req.body);133 if (b.kind.startsWith("http-") && !b.config.allowedHosts.length) throw bad("invalid_request", "an HTTP secret needs at least one allowed host");134 if (b.kind === "http-header" && !b.config.header) throw bad("invalid_request", "header name required");135 await sql`insert into managed_secrets (id, account_id, name, kind, config, rotate_every_days, expires_at) values (${b.id}, ${s.accountId}, ${b.name}, ${b.kind}, ${sql.json(b.config)}, ${b.rotateEveryDays ?? null}, ${b.expiresAt ?? null})`;136 try { await managed("PUT", `/secrets/${b.id}`, { accountId: s.accountId, version: 1, value: b.value }); }137 catch (e) { await sql`delete from managed_secrets where id = ${b.id}`; throw e; }138 await sql.begin((tx) => audit(tx, s.accountId, "connect.secret_created", { secret: b.id, kind: b.kind }, s.deviceId));139 return { ok: true };140 });141 /** Rotation: new value, version bump, every lease on the secret ends. */142 app.put("/api/v1/connect/secrets/:id/value", async (req) => {143 const s = await needStrong(req);144 const id = parse(uuid, (req.params as any).id);145 const b = parse(z.object({ value: z.string().min(1).max(65536) }).strict(), req.body);146 const [m] = await sql`update managed_secrets set version = version + 1, rotated_at = now() where id = ${id} and account_id = ${s.accountId} and deleted_at is null returning version`;147 if (!m) throw notFound();148 await managed("PUT", `/secrets/${id}`, { accountId: s.accountId, version: m.version, value: b.value });149 await sql.begin(async (tx) => {150 await tx`update agent_leases set revoked_at = now() where grant_id in (select id from agent_grants where secret_id = ${id}) and revoked_at is null`;151 await audit(tx, s.accountId, "connect.secret_rotated", { secret: id, version: m.version }, s.deviceId);152 });153 return { ok: true, version: m.version };154 });155 app.delete("/api/v1/connect/secrets/:id", async (req) => {156 const s = await needStrong(req);157 const id = parse(uuid, (req.params as any).id);158 if (!(await sql`update managed_secrets set deleted_at = now() where id = ${id} and account_id = ${s.accountId} and deleted_at is null returning 1`).length) throw notFound();159 await managed("DELETE", `/secrets/${id}`, { accountId: s.accountId });160 await sql.begin(async (tx) => {161 await tx`update agent_grants set revoked_at = now() where secret_id = ${id} and revoked_at is null`;162 await audit(tx, s.accountId, "connect.secret_deleted", { secret: id }, s.deviceId);163 });164 return { ok: true };165 });166167 app.post("/api/v1/connect/grants", async (req) => {168 const s = await needStrong(req);169 const b = parse(z.object({ id: uuid, identityId: uuid, secretId: uuid, mode: z.enum(["operate", "read"]), approval: z.enum(["never", "lease", "each"]), leaseTtlSec: z.number().int().min(30).max(3600).default(300),170 maxUses: z.number().int().min(1).max(1_000_000).optional(), expiresInSec: z.number().int().min(60).max(365 * 86400),171 constraints: z.object({ methods: z.array(z.string().regex(/^[A-Z]{3,7}$/)).max(5).optional(), pathPrefix: z.string().regex(/^\/[^\s]{0,200}$/).optional() }).strict().default({}) }).strict(), req.body);172 const [ok] = await sql`select (select kind from service_accounts where id = ${b.identityId} and account_id = ${s.accountId} and revoked_at is null) as ik, (select 1 from managed_secrets where id = ${b.secretId} and account_id = ${s.accountId} and deleted_at is null) as sk`;173 if (!ok.ik || !ok.sk) throw notFound();174 // an autonomous agent never gets unattended access: approval "never" is reserved for service accounts175 if (ok.ik === "agent" && b.approval === "never") throw bad("invalid_request", "agents require human approval (per lease or per use)");176 await sql.begin(async (tx) => {177 await tx`insert into agent_grants (id, account_id, service_account_id, secret_id, mode, approval, lease_ttl_sec, max_uses, constraints, expires_at) values (${b.id}, ${s.accountId}, ${b.identityId}, ${b.secretId}, ${b.mode}, ${b.approval}, ${b.leaseTtlSec}, ${b.maxUses ?? null}, ${tx.json(b.constraints)}, now() + ${b.expiresInSec} * interval '1 second')`;178 await audit(tx, s.accountId, "connect.grant_created", { grant: b.id, identity: b.identityId, secret: b.secretId, mode: b.mode, approval: b.approval }, s.deviceId);179 });180 return { ok: true };181 });182 app.delete("/api/v1/connect/grants/:id", async (req) => {183 const s = await need(req, "device");184 const id = parse(uuid, (req.params as any).id);185 await sql.begin(async (tx) => {186 if (!(await tx`update agent_grants set revoked_at = now() where id = ${id} and account_id = ${s.accountId} and revoked_at is null returning 1`).length) throw notFound();187 await tx`update agent_leases set revoked_at = now() where grant_id = ${id} and revoked_at is null`;188 await audit(tx, s.accountId, "connect.grant_revoked", { grant: id }, s.deviceId);189 });190 return { ok: true };191 });192193 app.post("/api/v1/connect/approvals/:id", async (req) => {194 const s = await needStrong(req); // a human, freshly authenticated, on a certified device195 const id = parse(uuid, (req.params as any).id);196 const b = parse(z.object({ approve: z.boolean() }).strict(), req.body);197 await sql.begin(async (tx) => {198 const [p] = await tx`update agent_approvals set status = ${b.approve ? "approved" : "denied"}, decided_at = now(), decided_by = ${s.deviceId} where id = ${id} and account_id = ${s.accountId} and status = 'pending' and expires_at > now() returning grant_id`;199 if (!p) throw notFound();200 const [g] = await tx`select approval, lease_ttl_sec, mode from agent_grants where id = ${p.grant_id}`;201 if (b.approve && g.approval === "lease") await tx`insert into agent_leases (id, grant_id, approval_id, expires_at) values (${crypto.randomUUID()}, ${p.grant_id}, ${id}, now() + ${g.lease_ttl_sec} * interval '1 second')`;202 await audit(tx, s.accountId, b.approve ? "connect.approved" : "connect.denied", { approval: id, grant: p.grant_id }, s.deviceId);203 });204 return { ok: true };205 });206207 /** Kill switch: suspends every agent and service identity of the account at once and ends all leases. Easy to engage (no step-up); releasing needs one. */208 app.post("/api/v1/connect/kill", async (req) => {209 const b = parse(z.object({ engaged: z.boolean() }).strict(), req.body);210 const s = b.engaged ? await need(req, "device") : await needStrong(req);211 await sql.begin(async (tx) => {212 await tx`update accounts set agents_killed_at = ${b.engaged ? tx`now()` : null} where id = ${s.accountId}`;213 if (b.engaged) {214 await tx`update agent_leases set revoked_at = now() where revoked_at is null and grant_id in (select id from agent_grants where account_id = ${s.accountId})`;215 await tx`update agent_approvals set status = 'denied', decided_at = now() where account_id = ${s.accountId} and status = 'pending'`;216 }217 await audit(tx, s.accountId, b.engaged ? "connect.kill_engaged" : "connect.kill_released", {}, s.deviceId);218 });219 return { ok: true };220 });221222 // ════ workload side (signed requests) ════════════════════════════════════════════════════════════════════223 app.get("/api/v1/agent/grants", async (req) => {224 const sa = await agentIdentity(req);225 const rows = await sql`select g.id, g.mode, g.approval, g.expires_at, g.max_uses, g.uses, g.constraints, m.name, m.kind, m.config from agent_grants g join managed_secrets m on m.id = g.secret_id where g.service_account_id = ${sa.id} and g.revoked_at is null and g.expires_at > now() and m.deleted_at is null`;226 return { suspended: !!sa.agents_killed_at || !!sa.revoked_at, grants: rows.map((g) => ({ grantId: g.id, secretName: g.name, secretKind: g.kind, mode: g.mode, approval: g.approval, expiresAt: g.expires_at, usesLeft: g.max_uses === null ? null : g.max_uses - g.uses, allowedHosts: g.config.allowedHosts ?? [], constraints: g.constraints })) };227 });228229 app.get("/api/v1/agent/approvals/:id", async (req) => {230 const sa = await agentIdentity(req);231 const [p] = await sql`select p.status, p.expires_at from agent_approvals p join agent_grants g on g.id = p.grant_id where p.id = ${parse(uuid, (req.params as any).id)} and g.service_account_id = ${sa.id}`;232 if (!p) throw notFound();233 return { status: p.status === "pending" && p.expires_at < new Date() ? "expired" : p.status };234 });235236 const opBody = z.object({237 grantId: uuid, reason: z.string().max(300).default(""), approvalId: uuid.optional(),238 http: z.object({ method: z.string().regex(/^[A-Za-z]{3,7}$/), url: z.string().url().max(2048), headers: z.record(z.string().max(64), z.string().max(4096)).default({}), body: z.string().max(1024 * 1024).optional() }).strict().optional(),239 sign: z.object({ payload: z.string().regex(/^[A-Za-z0-9_-]*$/).max(1_400_000) }).strict().optional(),240 read: z.literal(true).optional(),241 }).strict();242243 /** One entry point for every use of a secret; the policy engine decides allow / needs-approval / deny. */244 app.post("/api/v1/agent/use", async (req, reply) => {245 const sa = await agentIdentity(req);246 const b = parse(opBody, req.body);247 const kinds = [b.http && "http", b.sign && "sign", b.read && "read"].filter(Boolean) as ("http" | "sign" | "read")[];248 if (kinds.length !== 1) throw bad("invalid_request", "exactly one of http, sign, read");249 const kind = kinds[0]!;250 const url = b.http ? new URL(b.http.url) : null;251252 const outcome = await sql.begin(async (tx) => {253 const [g] = await tx`select g.*, m.kind as secret_kind, m.config, m.name as secret_name, m.deleted_at, m.expires_at as secret_expires_at from agent_grants g join managed_secrets m on m.id = g.secret_id where g.id = ${b.grantId} and g.service_account_id = ${sa.id} for update of g`;254 if (!g) throw notFound();255 const [lease] = await tx`select id from agent_leases where grant_id = ${g.id} and revoked_at is null and expires_at > now() limit 1`;256 let decision = evaluate({257 now: Date.now(), killed: !!sa.agents_killed_at, identityRevoked: !!sa.revoked_at, secretDeleted: !!g.deleted_at, secretExpiresAt: g.secret_expires_at ? g.secret_expires_at.getTime() : null,258 grant: { mode: g.mode, approval: g.approval, expiresAt: g.expires_at.getTime(), revoked: !!g.revoked_at, maxUses: g.max_uses, uses: g.uses, constraints: g.constraints },259 op: { kind, method: b.http?.method, path: url?.pathname }, secretKind: g.secret_kind, activeLease: !!lease,260 });261 if (decision.decision === "approval" && b.approvalId) {262 // single-use approval (approval "each", and every raw read)263 const used = await tx`update agent_approvals set status = 'used' where id = ${b.approvalId} and grant_id = ${g.id} and status = 'approved' and decided_at > now() - interval '10 minutes' and summary->>'fingerprint' = ${fingerprint(kind, b)} returning 1`;264 if (used.length) decision = { decision: "allow" };265 }266 if (decision.decision === "deny") {267 await audit(tx, sa.account_id, "agent.denied", { identity: sa.id, grant: g.id, op: kind, reason: decision.reason }, null, `agent:${sa.id}`);268 return { status: 403, body: { error: "denied", message: decision.reason } };269 }270 if (decision.decision === "approval") {271 const [open] = await tx`select id from agent_approvals where grant_id = ${g.id} and status = 'pending' and expires_at > now() and summary->>'fingerprint' = ${fingerprint(kind, b)} limit 1`;272 const id = open?.id ?? crypto.randomUUID();273 if (!open) {274 // The human sees structured facts taken from the request itself. The agent's free text is truncated, stripped of275 // control / bidi characters and labelled as untrusted in every client.276 const summary = { fingerprint: fingerprint(kind, b), op: kind, identity: sa.name, identityKind: sa.kind, secret: g.secret_name, mode: g.mode,277 ...(url ? { method: b.http!.method.toUpperCase(), host: url.hostname, path: summarize(url.pathname, 200), bodyBytes: b.http!.body?.length ?? 0 } : {}), ...(b.sign ? { payloadBytes: unb64u(b.sign.payload).length } : {}),278 untrustedReason: summarize(b.reason, 300) };279 await tx`insert into agent_approvals (id, account_id, grant_id, summary, expires_at) values (${id}, ${sa.account_id}, ${g.id}, ${tx.json(summary)}, now() + interval '10 minutes')`;280 await audit(tx, sa.account_id, "agent.approval_requested", { identity: sa.id, grant: g.id, op: kind, approval: id }, null, `agent:${sa.id}`);281 }282 return { status: 202, body: { status: "approval_required", approvalId: id }, notify: sa.account_id as string };283 }284 rateLimit(`grant:${g.id}`, g.rate_per_min, 60);285 await tx`update agent_grants set uses = uses + 1 where id = ${g.id}`;286 await audit(tx, sa.account_id, kind === "read" ? "agent.secret_delivered" : "agent.operation", { identity: sa.id, grant: g.id, op: kind, ...(url ? { host: url.hostname, method: b.http!.method.toUpperCase() } : {}) }, null, `agent:${sa.id}`);287 return { status: 200, exec: { secretId: g.secret_id as string, secretKind: g.secret_kind as string, config: g.config, accountId: sa.account_id as string } };288 });289290 if ("notify" in outcome && outcome.notify) publish([outcome.notify], { type: "approval" });291 if (!("exec" in outcome) || !outcome.exec) return reply.code(outcome.status).send(outcome.body);292 const e = outcome.exec;293 if (kind === "http") return managed("POST", `/secrets/${e.secretId}/http`, { accountId: e.accountId, kind: e.secretKind, config: e.config, request: { ...b.http!, method: b.http!.method.toUpperCase() } });294 if (kind === "sign") return managed("POST", `/secrets/${e.secretId}/hmac`, { accountId: e.accountId, payload: b.sign!.payload });295 const r = await managed("POST", `/secrets/${e.secretId}/reveal`, { accountId: e.accountId });296 return { value: r.value, warning: "Raw secret delivered. Whoever holds it can disclose it; revocation cannot take it back. Rotate it when the task is done." };297 });298}299300/** Binds an approval to the exact operation that was shown to the human. */301function fingerprint(kind: string, b: any): string {302 const core = kind === "http" ? [b.http.method.toUpperCase(), b.http.url, b.http.body ?? ""] : kind === "sign" ? [b.sign.payload] : ["read"];303 return crypto.createHash("sha256").update(JSON.stringify([kind, b.grantId, ...core])).digest("base64url");304}305