import { createJWT, ES256KSigner, type JWTHeader } from "did-jwt"; import { bases, bytes } from "multiformats/basics"; import { v4 as uuidv4 } from "uuid"; import { defaultExpiration, GRANT_TYPE, SCOPE } from "./constants.js"; import type { Ake1SigPayload, BodyRequest } from "./types.js"; import { checkHeadersPayload, computeHash, encrypt } from "./utils.js"; import type { JwtTarVerifyResult } from "./verifier.js"; const { base64url } = bases; export class RP { #privateKey: string; name: string; trustedAppsRegistry: string; kid: string; expiration: { requestToken: number; accessToken: number; }; constructor(opts: { privateKey: string; name: string; trustedAppsRegistry: string; expiration?: { requestToken: number; accessToken: number }; }) { this.#privateKey = opts.privateKey; this.name = opts.name; this.trustedAppsRegistry = opts.trustedAppsRegistry; this.kid = `${this.trustedAppsRegistry}/${this.name}`; this.expiration = opts?.expiration ?? defaultExpiration; } async createAccessToken( body: BodyRequest, resultVerification: JwtTarVerifyResult, payloadToken?: { [x: string]: unknown }, ) { if (body.grantType !== GRANT_TYPE) { throw new Error(`grantType must be '${GRANT_TYPE}'`); } if (!body.clientAssertion) { throw new Error("No assertion present in the body"); } if (body.scope && body.scope !== SCOPE) { throw new Error(`Invalid scope '${body.scope}'`); } checkHeadersPayload(body.clientAssertion); const { payload: verifPayload, protectedHeader: verifHeader, publicKeyHex, } = resultVerification; const jwtOpts = { issuer: this.name, signer: ES256KSigner( Buffer.from(this.#privateKey.replace(/^0x/, ""), "hex"), ), expiresIn: this.expiration.accessToken, }; const headerOpts = { typ: "JWT", alg: "ES256K", kid: this.kid, } as const satisfies JWTHeader; const accessToken = await createJWT( { ...(verifPayload.iss && { sub: verifPayload.iss }), ...(verifPayload.aud && { aud: verifPayload.aud }), atHash: base64url.baseEncode(computeHash(body.clientAssertion)), nonce: uuidv4(), ...payloadToken, }, jwtOpts, headerOpts, ); const encryptedAccessToken = encrypt( { access_token: accessToken, kid: this.kid, nonce: verifPayload["nonce"], }, publicKeyHex, ); const ake1Sig = await createJWT( { ake1_nonce: verifPayload["nonce"], ake1_enc_payload: encryptedAccessToken, kid: verifHeader.kid, }, jwtOpts, headerOpts, ); const ake1SigPayloadBase64url = ake1Sig.split(".")[1]!; const ake1SigPayload = JSON.parse( bytes.toString(base64url.baseDecode(ake1SigPayloadBase64url)), ) as Ake1SigPayload; const ake1JwsDetached = ake1Sig.replace(ake1SigPayloadBase64url, ""); return { ake1_enc_payload: encryptedAccessToken, ake1_sig_payload: ake1SigPayload, ake1_jws_detached: ake1JwsDetached, kid: this.kid, }; } }