Public
Script
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
52
53
54
55
56
57
58
59
60
61
62
63
// SPDX-License-Identifier: 0BSD
import { computeThumbprint } from "https://esm.town/v/vladimyr/libjwk";
import { shake128, shake256 } from "npm:@noble/hashes/sha3";
import * as jose from "npm:jose";
import ky, { HTTPError } from "npm:ky";
import { base16 } from "npm:multiformats/bases/base16";
export { HTTPError as HTTPError };
export type HashAlgorithm = "shake128" | "shake256";
const reLegacyAspeURI = /^aspe:(?:\/\/)?(?:(?<hostname>[^\s\/:]+)(?:\/|:))?(?<keyId>[A-Za-z0-9]{26})$/;
const reAspeURI = /^aspe:(?:\/\/(?<hostname>[^\s\/]+)\/)?(?<fingerprint>[A-Fa-f0-9]{40})$/;
export type AspeURI = ReturnType<typeof parseAspeURI>;
export function parseAspeURI(input: string) {
const match = input.match(reAspeURI);
if (!match) return null;
const { hostname, fingerprint } = match.groups;
return { hostname, fingerprint: fingerprint.toUpperCase() };
}
export type LegacyAspeURI = ReturnType<typeof parseLegacyAspeURI>;
export function parseLegacyAspeURI(input: string) {
const match = input.match(reLegacyAspeURI);
if (!match) return null;
const { hostname, keyId } = match.groups;
return { hostname, keyId: keyId.toUpperCase() };
}
export function getKeyId(fingerprint: string) {
return formatFingerprint(fingerprint)
.split(" ")
.slice(0, 4)
.join(" ");
}
export function formatFingerprint(fingerprint: string) {
return fingerprint
.toUpperCase()
.split(/([0-9A-F]{4})/g)
.filter(Boolean)
.join(" ");
}
export function calculateFingerprint(asp: string, alg: HashAlgorithm = "shake128", d: number = 160) {
const { jwk } = jose.decodeProtectedHeader(asp);
if (!["shake128", "shake256"].includes(alg)) {
throw new Error("error: unsupported algorithm");
}
const thumbprint = computeThumbprint(jwk, alg, d);
return base16.baseEncode(thumbprint);
}
export function fetchASP(id: string, server = "keyoxide.org") {
const url = new URL(`https://keyoxide.org/.well-known/aspe/id/${id}`);
url.hostname = server;
return ky.get(url, {
headers: {
Accept: "application/asp+jwt",
},
}).text();
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
March 6, 2024