From 3b9914f8e21614de9ebff6c7a0898c919fba4064 Mon Sep 17 00:00:00 2001 From: GCHQDeveloper581 <63102987+GCHQDeveloper581@users.noreply.github.com> Date: Fri, 29 May 2026 14:50:03 +0000 Subject: [PATCH] Produce bug-compatible version of JWT Sign using jose instead of jsonwebtoken --- src/core/operations/JWTSign.mjs | 41 +++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/src/core/operations/JWTSign.mjs b/src/core/operations/JWTSign.mjs index 66831efa..bd0ac662 100644 --- a/src/core/operations/JWTSign.mjs +++ b/src/core/operations/JWTSign.mjs @@ -4,7 +4,8 @@ * @license Apache-2.0 */ import Operation from "../Operation.mjs"; -import jwt from "jsonwebtoken"; +import { SignJWT, importPKCS8 } from "jose"; +import { createPrivateKey } from "crypto"; import OperationError from "../errors/OperationError.mjs"; import {JWT_ALGORITHMS} from "../lib/JWT.mjs"; @@ -50,21 +51,47 @@ class JWTSign extends Operation { * @param {Object[]} args * @returns {string} */ - run(input, args) { + async run(input, args) { const [key, algorithm, header] = args; + let secret; try { - return jwt.sign(input, key, { - algorithm: algorithm === "None" ? "none" : algorithm, - header: JSON.parse(header || "{}") - }); + if (key.startsWith("-----BEGIN RSA PRIVATE KEY-----")) { + secret = await createPrivateKey(key); + } else if (key.startsWith("-----BEGIN PRIVATE KEY-----")) { + secret = await importPKCS8(key, algorithm); + } else { + secret = new TextEncoder().encode(key); + } } catch (err) { throw new OperationError(`Error: Have you entered the key correctly? The key should be either the secret for HMAC algorithms or the PEM-encoded private key for RSA and ECDSA. ${err}`); } - } + const fullHeader = { alg: algorithm, typ: "JWT" }; + try { + if (header !== "{}") { + Object.assign(fullHeader, JSON.parse(header)); + } + } catch (err) { + throw new OperationError(`Header must be a valid (or empty) json object. + +${err}`); + } + + try { + const token = await new SignJWT(input) + .setProtectedHeader(fullHeader) + .sign(secret); + + return token; + } catch (err) { + throw new OperationError(`Error: Have you entered the key correctly? The key should be either the secret for HMAC algorithms or the PEM-encoded private key for RSA and ECDSA. + +${err}`); + } + }; } export default JWTSign;