import { decodeJWT } from "did-jwt"; import { getGenericName, getApp, checkAuthorization, encode, } from "@cef-ebsi/siop-auth"; import { KeyEncoder } from "@cef-ebsi/key-encoder"; import { bases, bytes } from "multiformats/basics"; import { importJWK, jwtVerify, type JWTVerifyResult, type KeyLike } from "jose"; export interface JwtTarVerifyResult extends JWTVerifyResult { publicKeyHex: string; publicKey: KeyLike | Uint8Array; } const { base64 } = bases; const keyEncoder = new KeyEncoder("secp256k1"); export async function verifyJwtTar( jwt: string, opts: { trustedAppsRegistry: string; op?: string; timeout?: number; }, ): Promise { const { header, payload } = decodeJWT(jwt); const { kid } = header as unknown as { kid: string }; if (!kid || !kid.startsWith(opts.trustedAppsRegistry)) { throw new Error( `JWT with invalid kid. It should be hosted at ${opts.trustedAppsRegistry}`, ); } if (typeof payload.iss !== "string") { throw new Error("JWT with invalid iss. It must be a string"); } if (opts.op && opts.op !== getGenericName(payload.iss)) { throw new Error( `Invalid OpenID Provider. Received ${payload.iss}. Expected ${opts.op}`, ); } const tApp = await getApp(kid, { ...(opts.timeout && { timeout: opts.timeout }), }); if (!tApp.name || tApp.name !== payload.iss) { throw new Error( `kid resolves the app '${ tApp.name ?? "" }' but the iss field in the jwt refers to the app '${payload.iss ?? ""}'`, ); } const validations = await Promise.all( tApp.publicKeys.map(async (publicKeyPemBase64: string) => { try { const publicKeyPem = bytes.toString( base64.baseDecode(publicKeyPemBase64), ); const publicKeyHex = keyEncoder.encodePublic( publicKeyPem, "pem", "raw", ); const publicKeyJwk = encode.publicKey.fromHexToJWK(publicKeyHex); const publicKey = await importJWK(publicKeyJwk, header.alg); const verifyResult = await jwtVerify(jwt, publicKey); return { valid: true, result: { ...verifyResult, publicKeyHex, publicKey, }, }; } catch (error) { return { valid: false, error, }; } }), ); const [valid] = validations.filter((v) => v.valid); if (!valid) { throw new Error( `JWT could not be validated with the public keys of '${ tApp.name }'. Errors: ${JSON.stringify( validations.map((v) => (v.error as Error).message), )}`, ); } const aud = payload.aud as string; const sub = payload.sub as string; // verify that the apps exist and are not revoked await getApp(`${opts.trustedAppsRegistry}/${aud}`, { ...(opts.timeout && { timeout: opts.timeout }), }); if (sub !== tApp.name) { await getApp(`${opts.trustedAppsRegistry}/${sub}`, { ...(opts.timeout && { timeout: opts.timeout }), }); } await checkAuthorization(aud, sub, opts); return valid.result as JwtTarVerifyResult; }