summaryrefslogtreecommitdiffhomepage
path: root/packages/server/src/metadata/verifyJWT.ts
blob: 4c10eb3099d150df4abedc0370790523f89df968 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { convertX509PublicKeyToCOSE } from '../helpers/convertX509PublicKeyToCOSE.ts';
import { isoBase64URL, isoUint8Array } from '../helpers/iso/index.ts';
import { COSEALG, COSEKEYS, isCOSEPublicKeyEC2, isCOSEPublicKeyRSA } from '../helpers/cose.ts';
import { verifyEC2 } from '../helpers/iso/isoCrypto/verifyEC2.ts';
import { verifyRSA } from '../helpers/iso/isoCrypto/verifyRSA.ts';

/**
 * Lightweight verification for FIDO MDS JWTs. Supports use of EC2 and RSA.
 *
 * If this ever needs to support more JWS algorithms, here's the list of them:
 *
 * https://www.rfc-editor.org/rfc/rfc7518.html#section-3.1
 *
 * (Pulled from https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1)
 */
export function verifyJWT(jwt: string, leafCert: Uint8Array): Promise<boolean> {
  const [header, payload, signature] = jwt.split('.');

  const certCOSE = convertX509PublicKeyToCOSE(leafCert);
  const data = isoUint8Array.fromUTF8String(`${header}.${payload}`);
  const signatureBytes = isoBase64URL.toBuffer(signature);

  if (isCOSEPublicKeyEC2(certCOSE)) {
    return verifyEC2({
      data,
      signature: signatureBytes,
      cosePublicKey: certCOSE,
      shaHashOverride: COSEALG.ES256,
    });
  } else if (isCOSEPublicKeyRSA(certCOSE)) {
    return verifyRSA({
      data,
      signature: signatureBytes,
      cosePublicKey: certCOSE,
    });
  }

  const kty = certCOSE.get(COSEKEYS.kty);
  throw new Error(
    `JWT verification with public key of kty ${kty} is not supported by this method`,
  );
}