import crypto from "node:crypto"; import { hexToBytes, utf8ToBytes, bytesToHex } from "@noble/hashes/utils"; import { encrypt as eciesEncrypt, decrypt as eciesDecrypt } from "eciesjs"; import { SCOPE, defaultExpiration } from "./constants.js"; import type { JWTHeader, JWTPayload, JWTOptions } from "./types.js"; import { InvalidTokenError, InvalidScopeError } from "./errors/index.js"; /* * Decode JSON Web Token */ export function decode(token: string): { headers: JWTHeader; payload: JWTPayload; } { const jwtParts = token.split("."); let headers: JWTHeader; let payload: JWTPayload; try { headers = JSON.parse( Buffer.from(jwtParts[0]!, "base64").toString(), ) as JWTHeader; payload = JSON.parse( Buffer.from(jwtParts[1]!, "base64").toString(), ) as JWTPayload; } catch (error) { throw new InvalidTokenError( `The token can not be parsed: ${(error as Error).message || ""}`, ); } return { headers, payload }; } /* * Function to check that headers are in accordance with EBSI standards */ export function checkHeaders(headers: JWTHeader): boolean { const algorithm = "ES256K"; if (headers.alg !== algorithm) { throw new InvalidTokenError( `The token algorithm must be '${algorithm}'. Received '${ headers.alg || "" }'`, ); } if (headers.typ !== "JWT") { throw new InvalidTokenError("assertion has not typ=JWT in the header"); } return true; } /* * Function to check that token payload have attributes required in accordance with EBSI standards */ function checkPayloadAttributes(payload: JWTPayload): boolean { if ( !payload.aud || !payload.iss || !payload.exp || !payload.sub || !payload["nonce"] || !payload.iat ) return false; return true; } /* * Function to check that assertion token payload is in accordance with EBSI standards */ export function checkAssertionTokenPayload(payload: JWTPayload): boolean { if (!checkPayloadAttributes(payload) || !payload.jti) { throw new InvalidTokenError( "Assertion token requires aud, iss, exp, sub, jti, nonce and iat in the payload", ); } const { iat, exp } = payload; if (!exp || !iat || exp - iat > defaultExpiration.requestToken) { throw new InvalidTokenError( `The expiration time can not exceed ${defaultExpiration.requestToken} seconds`, ); } return true; } /* * Function to check that access token payload is in accordance with EBSI standards */ export function checkAccessTokenPayload( payload: JWTPayload, opts: JWTOptions = {}, ): boolean { const { scope, audience } = opts; let { expiration } = opts; if (!expiration) { expiration = defaultExpiration; } if (!checkPayloadAttributes(payload) || !payload["atHash"]) { throw new InvalidTokenError( "Access token requires aud, iss, exp, sub, atHash, nonce and iat in the payload", ); } const { iat, exp } = payload; const expirationTime = expiration.accessToken ? expiration.accessToken : defaultExpiration.accessToken; const now = Math.floor(new Date().getTime() / 1000); if (!exp || !iat || exp - iat > expirationTime) { throw new InvalidTokenError( `The expiration time can not exceed ${expirationTime} seconds`, ); } if (iat > now) throw new InvalidTokenError(`iat cannot be later than present`); if (now > exp) throw new InvalidTokenError(`Access token is expired`); if (audience && payload.aud !== audience) { throw new InvalidTokenError(`The aud in the token must be ${audience}`); } if (scope && scope !== SCOPE) { throw new InvalidScopeError(`Invalid scope '${scope}'`); } return true; } /* * Function to check that headers and payload are in accordance with EBSI standards */ export function checkHeadersPayload( token: string, options?: JWTOptions, ): { headers: JWTHeader; payload: JWTPayload; scope?: string; } { const { headers, payload } = decode(token); checkHeaders(headers); if (!options) { // Assertion (access request) token checkAssertionTokenPayload(payload); return { headers, payload }; } // Access token const opts = { ...options }; if (!opts.scope) { opts.scope = SCOPE; } checkAccessTokenPayload(payload, opts); return { headers, payload, scope: opts.scope }; } export function encrypt( payload: { [x: string]: unknown }, publicKeyHex: string, ): string { const encrypted = eciesEncrypt( publicKeyHex, utf8ToBytes(JSON.stringify(payload)), ); return bytesToHex(encrypted); } export function decrypt(privateKey: string, encrypted: string): string { const decrypted = eciesDecrypt(privateKey, hexToBytes(encrypted)); return new TextDecoder().decode(decrypted); } export function computeHash(payload: string): Buffer { const cryptoHash = crypto.createHash("sha256"); cryptoHash.update(payload); return cryptoHash.digest(); }