Produce bug-compatible version of JWT Sign using jose instead of jsonwebtoken

This commit is contained in:
GCHQDeveloper581 2026-05-29 14:50:03 +00:00
parent 01ab7855fa
commit 3b9914f8e2
No known key found for this signature in database
GPG Key ID: 6222E059A3DF595C

View File

@ -4,7 +4,8 @@
* @license Apache-2.0 * @license Apache-2.0
*/ */
import Operation from "../Operation.mjs"; 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 OperationError from "../errors/OperationError.mjs";
import {JWT_ALGORITHMS} from "../lib/JWT.mjs"; import {JWT_ALGORITHMS} from "../lib/JWT.mjs";
@ -50,21 +51,47 @@ class JWTSign extends Operation {
* @param {Object[]} args * @param {Object[]} args
* @returns {string} * @returns {string}
*/ */
run(input, args) { async run(input, args) {
const [key, algorithm, header] = args; const [key, algorithm, header] = args;
let secret;
try { try {
return jwt.sign(input, key, { if (key.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
algorithm: algorithm === "None" ? "none" : algorithm, secret = await createPrivateKey(key);
header: JSON.parse(header || "{}") } else if (key.startsWith("-----BEGIN PRIVATE KEY-----")) {
}); secret = await importPKCS8(key, algorithm);
} else {
secret = new TextEncoder().encode(key);
}
} catch (err) { } 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. 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}`); ${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; export default JWTSign;