Skip to content

Commit

Permalink
fix(clerk-sdk-node): Properly import key from jwk
Browse files Browse the repository at this point in the history
  • Loading branch information
chanioxaris committed Jan 18, 2022
1 parent 88b4897 commit e982fd0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
15 changes: 5 additions & 10 deletions packages/sdk-node/src/Clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,10 @@ export type RequireSessionClaimsProp<T> = T & { sessionClaims: JwtPayload };

import { Base } from '@clerk/backend-core';
import { Crypto, CryptoKey } from '@peculiar/webcrypto';
import { decodeBase64, toSPKIDer } from './utils/crypto';

const crypto = new Crypto();

const decodeBase64 = (base64: string) =>
Buffer.from(base64, 'base64').toString('binary');

const importKey = async (jwk: JsonWebKey, algorithm: Algorithm) => {
return await crypto.subtle.importKey('jwk', jwk, algorithm, true, ['verify']);
};
Expand Down Expand Up @@ -123,15 +121,12 @@ export default class Clerk extends ClerkBackendAPI {
cacheMaxAge: jwksCacheMaxAge,
});

const encoder = new TextEncoder();
const signingKey = await jwksClient.getSigningKey(decoded.header.kid)
const pubKey = signingKey.getPublicKey()

return await crypto.subtle.importKey(
'raw',
encoder.encode(
(
await jwksClient.getSigningKey(decoded.header.kid)
).getPublicKey() as string
),
'spki',
toSPKIDer(pubKey),
{
name: 'RSASSA-PKCS1-v1_5',
hash: 'SHA-256',
Expand Down
21 changes: 21 additions & 0 deletions packages/sdk-node/src/utils/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export const decodeBase64 = (base64: string) =>
Buffer.from(base64, 'base64').toString('binary');

// toSPKIDer converts a PEM encoded Public Key to DER encoded
export function toSPKIDer(pem: string): ArrayBuffer {
const pemHeader = "-----BEGIN PUBLIC KEY-----";
const pemFooter = "-----END PUBLIC KEY-----";
const pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length);
const binaryDerString = decodeBase64(pemContents)
return str2ab(binaryDerString);
}

// https://stackoverflow.com/a/11058858
function str2ab(input: string): ArrayBuffer {
const buf = new ArrayBuffer(input.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = input.length; i < strLen; i++) {
bufView[i] = input.charCodeAt(i);
}
return buf;
}

0 comments on commit e982fd0

Please sign in to comment.