import { createHash, sign, verify } from 'node:crypto'

export const payloadDigest = (payload) => createHash('sha256').update(payload).digest('hex')
export const signManifest = (payload, privateKeyPem, keyId) => { if (!privateKeyPem || !keyId?.trim()) throw new Error('An Ed25519 private key and key id are required.'); const signature = sign(null, Buffer.from(payload), privateKeyPem).toString('base64'); return { status: 'signed', algorithm: 'Ed25519', keyId: keyId.trim(), payloadSha256: payloadDigest(payload), signature } }
export const verifyManifestSignature = (payload, signature, publicKeyPem) => { if (!signature || signature.status !== 'signed' || signature.algorithm !== 'Ed25519' || !/^[0-9a-f]{64}$/.test(signature.payloadSha256 || '') || payloadDigest(payload) !== signature.payloadSha256) return false; try { return verify(null, Buffer.from(payload), publicKeyPem, Buffer.from(signature.signature, 'base64')) } catch { return false } }
