import { createRemoteJWKSet, jwtVerify, } from 'jose';
import { exportJWK, generateKeyPair } from 'jose';
export async function createJwkPair() {
    const { publicKey, privateKey } = await generateKeyPair('PS256');
    const privateJwk = await exportJWK(privateKey);
    const publicJwk = await exportJWK(publicKey);
    privateJwk.kid = 'key-2024-001';
    privateJwk.use = 'sig';
    privateJwk.alg = 'PS256';
    publicJwk.kid = privateJwk.kid;
    publicJwk.use = privateJwk.use;
    publicJwk.alg = privateJwk.alg;
    return { privateJwk, publicJwk };
}
let remoteKeyset;
function getRemoteKeyset(jwksUrl) {
    if (remoteKeyset === undefined) {
        remoteKeyset = createRemoteJWKSet(new URL(jwksUrl));
    }
    return remoteKeyset;
}
export const tokenConfigOptions = (config) => {
    const tokenOptions = ['jwk', 'secret', 'jwksUrl'].filter(key => config[key] !== undefined);
    return tokenOptions;
};
export async function verifyToken(config, token, verifyOptions) {
    if (config.jwk !== undefined) {
        return verifyTokenImpl(token, loadJwk(config.jwk), verifyOptions);
    }
    if (config.secret !== undefined) {
        return verifyTokenImpl(token, loadSecret(config.secret), verifyOptions);
    }
    if (config.jwksUrl !== undefined) {
        const remoteKeyset = getRemoteKeyset(config.jwksUrl);
        return (await jwtVerify(token, remoteKeyset, verifyOptions)).payload;
    }
    throw new Error('verifyToken was called but no auth options (one of: jwk, secret, jwksUrl) were configured.');
}
function loadJwk(jwkString) {
    return JSON.parse(jwkString);
}
function loadSecret(secret) {
    return new TextEncoder().encode(secret);
}
async function verifyTokenImpl(token, verifyKey, verifyOptions) {
    const { payload } = await jwtVerify(token, verifyKey, verifyOptions);
    return payload;
}
//# sourceMappingURL=jwt.js.map