import { ok } from "../is.js";
import { subtle } from "crypto";
import JsonWebToken from "jsonwebtoken";
export async function verifyTokenWithKeys(req) {
    const { keys } = req;
    for (const key of keys) {
        if (await verifyTokenWithKey(req, key)) {
            return true;
        }
    }
    return false;
}
export async function verifyTokenWithKey(req, key) {
    try {
        const verified = JsonWebToken.verify(req.token, key, {
            issuer: req.issuer,
            subject: req.subject
        });
        ok(isPayloadStringRecordLike(verified));
        const { body } = verified;
        if (typeof body === "string") {
            ok(typeof req.body === "string");
            const expectedHash = Buffer.from(body, "base64url");
            const bodyHash = Buffer.from(await subtle.digest("SHA-256", Buffer.from(req.body)));
            ok(expectedHash.equals(bodyHash));
        }
        return true;
    }
    catch {
        return false;
    }
}
function isPayloadStringRecordLike(value) {
    return !!(typeof value !== "string" && value);
}
//# sourceMappingURL=token-signature.js.map