import { CompactEncrypt } from '../jwe/compact/encrypt.js'; import { JWTClaimsBuilder } from '../lib/jwt_claims_set.js'; export class EncryptJWT { #cek; #iv; #keyManagementParameters; #protectedHeader; #replicateIssuerAsHeader; #replicateSubjectAsHeader; #replicateAudienceAsHeader; #jwt; constructor(payload = {}) { this.#jwt = new JWTClaimsBuilder(payload); } setIssuer(issuer) { this.#jwt.iss = issuer; return this; } setSubject(subject) { this.#jwt.sub = subject; return this; } setAudience(audience) { this.#jwt.aud = audience; return this; } setJti(jwtId) { this.#jwt.jti = jwtId; return this; } setNotBefore(input) { this.#jwt.nbf = input; return this; } setExpirationTime(input) { this.#jwt.exp = input; return this; } setIssuedAt(input) { this.#jwt.iat = input; return this; } setProtectedHeader(protectedHeader) { if (this.#protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this.#protectedHeader = protectedHeader; return this; } setKeyManagementParameters(parameters) { if (this.#keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once'); } this.#keyManagementParameters = parameters; return this; } setContentEncryptionKey(cek) { if (this.#cek) { throw new TypeError('setContentEncryptionKey can only be called once'); } this.#cek = cek; return this; } setInitializationVector(iv) { if (this.#iv) { throw new TypeError('setInitializationVector can only be called once'); } this.#iv = iv; return this; } replicateIssuerAsHeader() { this.#replicateIssuerAsHeader = true; return this; } replicateSubjectAsHeader() { this.#replicateSubjectAsHeader = true; return this; } replicateAudienceAsHeader() { this.#replicateAudienceAsHeader = true; return this; } async encrypt(key, options) { const enc = new CompactEncrypt(this.#jwt.data()); if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) { this.#protectedHeader = { ...this.#protectedHeader, iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : undefined, sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : undefined, aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : undefined, }; } enc.setProtectedHeader(this.#protectedHeader); if (this.#iv) { enc.setInitializationVector(this.#iv); } if (this.#cek) { enc.setContentEncryptionKey(this.#cek); } if (this.#keyManagementParameters) { enc.setKeyManagementParameters(this.#keyManagementParameters); } return enc.encrypt(key, options); } }