Suite of AT Protocol TypeScript libraries built on web standards
1import { equals, fromString } from "@atp/bytes";
2import { BASE58_MULTIBASE_PREFIX, DID_KEY_PREFIX } from "./const.ts";
3
4/**
5 * Extracts the multikey from a `did:key` string.
6 * @param did - The `did:key` string to extract the multikey from.
7 * @throws Error if the input doesn't start with `did:key:`.
8 */
9export const extractMultikey = (did: string): string => {
10 if (!did.startsWith(DID_KEY_PREFIX)) {
11 throw new Error(`Incorrect prefix for did:key: ${did}`);
12 }
13 return did.slice(DID_KEY_PREFIX.length);
14};
15
16/**
17 * Extracts the bytes from a multikey string using base58btc encoding.
18 * @param multikey - The multikey string to extract the bytes from.
19 * @throws Error if the input doesn't start with `z`.
20 */
21export const extractPrefixedBytes = (multikey: string): Uint8Array => {
22 if (!multikey.startsWith(BASE58_MULTIBASE_PREFIX)) {
23 throw new Error(`Incorrect prefix for multikey: ${multikey}`);
24 }
25 return fromString(
26 multikey.slice(BASE58_MULTIBASE_PREFIX.length),
27 "base58btc",
28 );
29};
30
31/**
32 * Checks if the given bytes have the specified prefix.
33 * @param bytes - The bytes to check.
34 * @param prefix - The prefix to check for.
35 * @returns True if the bytes have the specified prefix, false otherwise.
36 */
37export const hasPrefix = (bytes: Uint8Array, prefix: Uint8Array): boolean => {
38 return equals(prefix, bytes.subarray(0, prefix.byteLength));
39};
40
41/**
42 * Detects the signature format of the given bytes.
43 * @param sig - The signature bytes to detect the format of.
44 * @returns The signature format, either "compact" or "der".
45 */
46export function detectSigFormat(sig: Uint8Array): "compact" | "der" {
47 if (sig.length === 65) {
48 throw new Error(
49 "Recoverable signatures (65 bytes) not supported; strip recovery id.",
50 );
51 }
52 if (sig.length === 64) return "compact";
53 if (sig.length >= 70 && sig[0] === 0x30) return "der"; // ASN.1 SEQUENCE
54 throw new Error("Unknown signature format: expected 64-byte compact or DER.");
55}