summaryrefslogtreecommitdiffhomepage
path: root/packages/server/src/helpers/matchExpectedRPID.ts
blob: 35ce4a3c2d8256f02aece06142c9bfaa08ca771a (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
43
44
45
46
47
48
49
50
51
import { toHash } from './toHash.ts';
import { isoUint8Array } from './iso/index.ts';

/**
 * Go through each expected RP ID and try to find one that matches. Returns the unhashed RP ID
 * that matched the hash in the response.
 *
 * Raises an `UnexpectedRPIDHash` error if no match is found
 */
export async function matchExpectedRPID(
  rpIDHash: Uint8Array,
  expectedRPIDs: string[],
): Promise<string> {
  try {
    const matchedRPID = await Promise.any<string>(
      expectedRPIDs.map((expected) => {
        return new Promise((resolve, reject) => {
          toHash(isoUint8Array.fromASCIIString(expected)).then(
            (expectedRPIDHash) => {
              if (isoUint8Array.areEqual(rpIDHash, expectedRPIDHash)) {
                resolve(expected);
              } else {
                reject();
              }
            },
          );
        });
      }),
    );

    return matchedRPID;
  } catch (err) {
    const _err = err as Error;

    // This means no matches were found
    if (_err.name === 'AggregateError') {
      throw new UnexpectedRPIDHash();
    }

    // An unexpected error occurred
    throw err;
  }
}

class UnexpectedRPIDHash extends Error {
  constructor() {
    const message = 'Unexpected RP ID hash';
    super(message);
    this.name = 'UnexpectedRPIDHash';
  }
}