import { v4 as uuidv4 } from "uuid"; import { createJWT, ES256KSigner } from "did-jwt"; import { base64url } from "multiformats/bases/base64"; import { jwtVerify } from "jose"; import { InvalidTokenError } from "./errors/index.js"; import type { AkeResponse } from "./types.js"; import { CLIENT_ASSERTION_TYPE, GRANT_TYPE, SCOPE, defaultExpiration, } from "./constants.js"; import { decrypt } from "./utils.js"; import { verifyJwtTar } from "./verifier.js"; export class Agent { #privateKey: string; trustedAppsRegistry: string; name: 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.expiration = opts.expiration ?? defaultExpiration; this.kid = `${this.trustedAppsRegistry}/${this.name}`; } /* * Create an OAuth2 authentication request. */ async createRequest( resourceApp: string, payload: { [x: string]: unknown } = {}, ): Promise<{ grantType: string; clientAssertionType: string; clientAssertion: string; scope: string; }> { return { grantType: GRANT_TYPE, clientAssertionType: CLIENT_ASSERTION_TYPE, scope: SCOPE, clientAssertion: await createJWT( { jti: uuidv4(), aud: resourceApp, sub: this.name, ...payload, }, { issuer: this.name, signer: ES256KSigner( Buffer.from(this.#privateKey.replace(/^0x/, ""), "hex"), ), expiresIn: this.expiration.requestToken, }, { typ: "JWT", alg: "ES256K", kid: this.kid, }, ), }; } /* * Validate an OAuth2 Authentication response using the AKE protocol including the Access Token in the response and returns the decrypted Access Token. */ async verifyAkeResponse( response: AkeResponse, opts: { nonce: string; op?: string; timeout?: number; }, ): Promise { const { ake1_enc_payload: ake1EncPayload, ake1_sig_payload: ake1SigPayload, ake1_jws_detached: ake1JwsDetached, } = response; const ake1DecPayload = JSON.parse( decrypt(this.#privateKey, ake1EncPayload), ) as { kid: string; access_token: string; nonce: string; }; const { kid, nonce, access_token: accessToken } = ake1DecPayload; if ( typeof kid !== "string" || typeof accessToken !== "string" || typeof nonce !== "string" ) { throw new Error( `invalid decrypted payload. Received: ${JSON.stringify( ake1DecPayload, )}`, ); } if (nonce !== opts.nonce) { throw new Error(`Expected nonce ${opts.nonce}. Received ${nonce}`); } const verification = await verifyJwtTar(accessToken, { trustedAppsRegistry: this.trustedAppsRegistry, ...(opts.op && { op: opts.op }), ...(opts.timeout && { timeout: opts.timeout }), }); // check ake1JwsDetached const ake1SignPayload = ake1JwsDetached.replace( "..", `.${base64url.baseEncode(Buffer.from(JSON.stringify(ake1SigPayload)))}.`, ); try { await jwtVerify(ake1SignPayload, verification.publicKey); } catch (error) { throw new InvalidTokenError( `invalid detached signature: ${(error as Error).message}`, ); } return accessToken; } }