summaryrefslogtreecommitdiff
path: root/src/lib/pgp/user.ts
blob: 334fbde048b8aa26de1739c9f3bdcbf9a9182577 (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
import { PublicKey, type Subkey, UserIDPacket } from "openpgp";
import type { Signature } from "./sign.ts";
import { defined, get } from "../../utils/anonymous.ts";

export function getUserIDsFromKey(
  signature: Signature | undefined,
  key: PublicKey | Subkey,
): UserIDPacket[] {
  const packet = signature?.getPackets?.()?.[0];
  const userID = packet?.signersUserID;

  if (userID) {
    return [UserIDPacket.fromObject(parseUserID(userID))];
  }

  key = key instanceof PublicKey ? key : key.mainKey;
  return key.users.map(get("userID")).filter(defined);
}

function parseUserID(input: string) {
  const regex = /^(.*?)\s*(?:\((.*?)\))?\s*(?:<(.+?)>)?$/;
  const match = input.match(regex);

  if (!match) return {};

  const [, name, comment, email] = match;

  return {
    name: name?.trim() || undefined,
    comment: comment?.trim() || undefined,
    email: email?.trim() || undefined,
  };
}