|
| 1 | +import crypto, { createHash } from "node:crypto"; |
| 2 | +import { canonicalJson } from "../hash/canonicalJson.js"; |
| 3 | +import type { PolicyGrantLike } from "../verifier/types.js"; |
| 4 | + |
| 5 | +export interface SignedPolicyGrant { |
| 6 | + grant: PolicyGrantLike; |
| 7 | + issuer?: string; |
| 8 | + issuerKeyId: string; |
| 9 | + signature: string; |
| 10 | +} |
| 11 | + |
| 12 | +function getExpectedKeyId(): string { |
| 13 | + return process.env.MPCP_POLICY_GRANT_SIGNING_KEY_ID || "mpcp-policy-grant-signing-key-1"; |
| 14 | +} |
| 15 | + |
| 16 | +function hashGrant(grant: PolicyGrantLike): Buffer { |
| 17 | + return createHash("sha256").update("MPCP:PolicyGrant:1.0:" + canonicalJson(grant)).digest(); |
| 18 | +} |
| 19 | + |
| 20 | +function parseSigningPrivateKey(): crypto.KeyObject | null { |
| 21 | + const pem = process.env.MPCP_POLICY_GRANT_SIGNING_PRIVATE_KEY_PEM; |
| 22 | + if (!pem) return null; |
| 23 | + try { |
| 24 | + return crypto.createPrivateKey(pem); |
| 25 | + } catch { |
| 26 | + return null; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +function parseVerificationPublicKey(): crypto.KeyObject | null { |
| 31 | + const pem = process.env.MPCP_POLICY_GRANT_SIGNING_PUBLIC_KEY_PEM; |
| 32 | + if (!pem) return null; |
| 33 | + try { |
| 34 | + return crypto.createPublicKey(pem); |
| 35 | + } catch { |
| 36 | + return null; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +export function createSignedPolicyGrant( |
| 41 | + grant: PolicyGrantLike, |
| 42 | + options?: { issuer?: string; keyId?: string }, |
| 43 | +): SignedPolicyGrant | null { |
| 44 | + const privateKey = parseSigningPrivateKey(); |
| 45 | + if (!privateKey) return null; |
| 46 | + |
| 47 | + const issuerKeyId = options?.keyId ?? getExpectedKeyId(); |
| 48 | + const signature = crypto.sign(null, hashGrant(grant), privateKey).toString("base64"); |
| 49 | + const result: SignedPolicyGrant = { grant, issuerKeyId, signature }; |
| 50 | + if (options?.issuer) result.issuer = options.issuer; |
| 51 | + return result; |
| 52 | +} |
| 53 | + |
| 54 | +export function verifyPolicyGrantSignature( |
| 55 | + envelope: SignedPolicyGrant, |
| 56 | +): { ok: true } | { ok: false; reason: "invalid_signature" } { |
| 57 | + if (envelope.issuerKeyId !== getExpectedKeyId()) return { ok: false, reason: "invalid_signature" }; |
| 58 | + |
| 59 | + const publicKey = parseVerificationPublicKey(); |
| 60 | + if (!publicKey) return { ok: false, reason: "invalid_signature" }; |
| 61 | + |
| 62 | + const isValid = crypto.verify( |
| 63 | + null, |
| 64 | + hashGrant(envelope.grant), |
| 65 | + publicKey, |
| 66 | + Buffer.from(envelope.signature, "base64"), |
| 67 | + ); |
| 68 | + if (!isValid) return { ok: false, reason: "invalid_signature" }; |
| 69 | + return { ok: true }; |
| 70 | +} |
0 commit comments