@intellectual-frontiers/crypto 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/cms.d.ts +106 -0
- package/dist/cms.js +350 -0
- package/dist/cose.d.ts +34 -0
- package/dist/cose.js +204 -0
- package/dist/crypt.d.ts +30 -0
- package/dist/crypt.js +117 -0
- package/dist/dsse.d.ts +137 -0
- package/dist/dsse.js +243 -0
- package/dist/md5.d.ts +19 -0
- package/dist/md5.js +146 -0
- package/dist/mod.d.ts +25 -0
- package/dist/mod.js +25 -0
- package/dist/sha256.d.ts +25 -0
- package/dist/sha256.js +34 -0
- package/dist/sigv4.d.ts +67 -0
- package/dist/sigv4.js +169 -0
- package/dist/uuid.d.ts +53 -0
- package/dist/uuid.js +92 -0
- package/dist/webauthn.d.ts +212 -0
- package/dist/webauthn.js +381 -0
- package/package.json +84 -4
- package/src/cms.ts +387 -0
- package/src/cose.ts +199 -0
- package/src/crypt.ts +117 -0
- package/src/dsse.ts +339 -0
- package/src/md5.ts +150 -0
- package/src/mod.ts +26 -0
- package/src/sha256.ts +55 -0
- package/src/sigv4.ts +216 -0
- package/src/uuid.ts +111 -0
- package/src/webauthn.ts +548 -0
package/src/sha256.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Spec: 0001-crypto FR-001
|
|
2
|
+
/**
|
|
3
|
+
* SHA-256 through Web Crypto (`crypto.subtle`, in every runtime and browser), and a typed `Sha256`: 64 lower-case hexadecimal digits that
|
|
4
|
+
* the compiler keeps apart from any other string, so a checksum is never confused with a version or a path (commons 0005-typescript-runtime
|
|
5
|
+
* FR-008). Taken from the machine setup's `result.ts` and `net.ts`, and the many call sites that write the hex loop by hand.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { sha256, sha256Of } from "./sha256.ts";
|
|
10
|
+
* const sum = await sha256(new TextEncoder().encode("abc"));
|
|
11
|
+
* sum === sha256Of("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); // true
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
import type { Brand } from "@intellectual-frontiers/core";
|
|
17
|
+
import { toHex } from "@intellectual-frontiers/formats/hex";
|
|
18
|
+
|
|
19
|
+
/** 64 lower-case hexadecimal digits: a SHA-256 checksum. */
|
|
20
|
+
export type Sha256 = Brand<string, "Sha256">;
|
|
21
|
+
|
|
22
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
23
|
+
|
|
24
|
+
/** The text as a checksum where it is one (upper-case digits are lowered), else undefined. */
|
|
25
|
+
export function sha256Of(text: string): Sha256 | undefined {
|
|
26
|
+
const t = text.trim().toLowerCase();
|
|
27
|
+
return SHA256.test(t) ? (t as Sha256) : undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The SHA-256 of bytes, or of text as UTF-8. */
|
|
31
|
+
export async function sha256(data: Uint8Array | string): Promise<Sha256> {
|
|
32
|
+
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
33
|
+
const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
|
|
34
|
+
return toHex(new Uint8Array(digest)) as Sha256;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Whether two checksums are the same, compared in constant time for their length. */
|
|
38
|
+
export function sameSha256(a: Sha256, b: Sha256): boolean {
|
|
39
|
+
if (a.length !== b.length) return false;
|
|
40
|
+
let d = 0;
|
|
41
|
+
for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
42
|
+
return d === 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The lines of a `sha256sum` or `SHASUMS256.txt` file, as file name to checksum; lines that are not a checksum and a name are skipped. */
|
|
46
|
+
export function parseSha256Sums(text: string): ReadonlyMap<string, Sha256> {
|
|
47
|
+
const out = new Map<string, Sha256>();
|
|
48
|
+
for (const line of text.split(/\r?\n/)) {
|
|
49
|
+
const m = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line.trim());
|
|
50
|
+
const sum = m?.[1] === undefined ? undefined : sha256Of(m[1]);
|
|
51
|
+
const name = m?.[2];
|
|
52
|
+
if (sum !== undefined && name !== undefined) out.set(name, sum);
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
package/src/sigv4.ts
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// Spec: 0001-crypto FR-004
|
|
2
|
+
/**
|
|
3
|
+
* AWS Signature Version 4 (commons 0001-crypto FR-004): an HTTP request signed with `AWS4-HMAC-SHA256`, by HMAC-SHA256 on
|
|
4
|
+
* Web Crypto, from its parts or from a web `Request`. The canonical request (the method; the path normalized and encoded twice, except for
|
|
5
|
+
* S3, which signs it as given, encoded once; the query sorted and encoded by RFC 3986; the headers in lower case, trimmed, sorted and
|
|
6
|
+
* signed with `host` and `x-amz-date`; the payload's SHA-256), the string to sign over the credential scope, the key derived from the
|
|
7
|
+
* secret through the day, region, service and `aws4_request`, and the `Authorization` header. The time is the caller's: the kernel reads
|
|
8
|
+
* no clock. Taken from Stolos's `src/archon/connect/aws.ts`; checked against AWS's published examples.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { sign } from "./sigv4.ts";
|
|
13
|
+
* const credentials = { accessKeyId: "AKIDEXAMPLE", secretAccessKey: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" }; // AWS's example key
|
|
14
|
+
* const signed = await sign(
|
|
15
|
+
* { method: "GET", url: "https://iam.amazonaws.com/?Action=ListUsers&Version=2010-05-08", headers: {} },
|
|
16
|
+
* { credentials, region: "us-east-1", service: "iam", date: new Date() },
|
|
17
|
+
* );
|
|
18
|
+
* signed.headers; // the request's headers with x-amz-date and authorization added, never host
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @module
|
|
22
|
+
*/
|
|
23
|
+
import { toHex } from "@intellectual-frontiers/formats/hex";
|
|
24
|
+
import { sha256 } from "./sha256.ts";
|
|
25
|
+
|
|
26
|
+
/** An access key: its id, its secret, and a session token where the key is temporary. */
|
|
27
|
+
export type AwsCredentials = {
|
|
28
|
+
readonly accessKeyId: string;
|
|
29
|
+
readonly secretAccessKey: string;
|
|
30
|
+
readonly sessionToken?: string;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** How to sign. */
|
|
34
|
+
export type SigV4Options = {
|
|
35
|
+
readonly credentials: AwsCredentials;
|
|
36
|
+
/** The region of the credential scope (`us-east-1`). */
|
|
37
|
+
readonly region: string;
|
|
38
|
+
/** The service of the credential scope (`iam`, `sts`, `s3`, `ec2`). */
|
|
39
|
+
readonly service: string;
|
|
40
|
+
/** The time of signing, which becomes `x-amz-date` (the kernel reads no clock). */
|
|
41
|
+
readonly date: Date;
|
|
42
|
+
/** Sign `UNSIGNED-PAYLOAD` instead of the body's SHA-256 (S3 allows it). */
|
|
43
|
+
readonly unsignedPayload?: boolean;
|
|
44
|
+
/** Also send the payload's hash as `x-amz-content-sha256` (always for S3, which requires it). */
|
|
45
|
+
readonly contentSha256Header?: boolean;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** A request to sign, by its parts. */
|
|
49
|
+
export type SigV4Request = {
|
|
50
|
+
readonly method: string;
|
|
51
|
+
/** The whole URL, as text (its path is signed as written there, before any normalization a URL parser would make). */
|
|
52
|
+
readonly url: string;
|
|
53
|
+
/** The headers to send; each is signed, but for those a transport may change (`user-agent`, `traceparent`, ...). */
|
|
54
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
55
|
+
readonly body?: string | Uint8Array;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** A signed request: the headers to send and, for whoever must check them, what was signed. */
|
|
59
|
+
export type Signed = {
|
|
60
|
+
/**
|
|
61
|
+
* The request's headers with `x-amz-date`, `x-amz-security-token` and `x-amz-content-sha256` where they apply, and `authorization`;
|
|
62
|
+
* never `host`, which the transport sets from the URL.
|
|
63
|
+
*/
|
|
64
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
65
|
+
readonly canonicalRequest: string;
|
|
66
|
+
readonly stringToSign: string;
|
|
67
|
+
/** The signature, 64 lower-case hexadecimal digits. */
|
|
68
|
+
readonly signature: string;
|
|
69
|
+
/** The value of the `Authorization` header. */
|
|
70
|
+
readonly authorization: string;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** The algorithm's name, as the string to sign and the `Authorization` header begin. */
|
|
74
|
+
export const ALGORITHM = "AWS4-HMAC-SHA256";
|
|
75
|
+
|
|
76
|
+
/** What is signed in place of a body's hash where the payload is not signed. */
|
|
77
|
+
export const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
|
|
78
|
+
|
|
79
|
+
// Headers a transport, a proxy or a tracer may add or change after signing: never signed, so that changing them breaks no signature.
|
|
80
|
+
const UNSIGNED_HEADERS = new Set(["authorization", "connection", "expect", "user-agent", "x-amzn-trace-id", "traceparent", "tracestate"]);
|
|
81
|
+
|
|
82
|
+
const encoder = new TextEncoder();
|
|
83
|
+
|
|
84
|
+
/** RFC 3986 percent-encoding, as SigV4 wants it: everything but `A-Z a-z 0-9 - _ . ~` encoded, in upper-case hexadecimal. */
|
|
85
|
+
export function uriEncode(text: string): string {
|
|
86
|
+
return encodeURIComponent(text).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function decoded(text: string): string {
|
|
90
|
+
try {
|
|
91
|
+
return decodeURIComponent(text);
|
|
92
|
+
} catch {
|
|
93
|
+
return text;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** `20150830T123600Z`: the time as `x-amz-date` writes it. */
|
|
98
|
+
export function amzDate(date: Date): string {
|
|
99
|
+
return date
|
|
100
|
+
.toISOString()
|
|
101
|
+
.replace(/[-:]/g, "")
|
|
102
|
+
.replace(/\.\d{3}Z$/, "Z");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The authority, path and query of a URL as written, without parsing (and so without normalizing) its path. */
|
|
106
|
+
function urlParts(url: string): { readonly host: string; readonly path: string; readonly query: string } {
|
|
107
|
+
const m = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#]*)([^?#]*)(?:\?([^#]*))?/.exec(url);
|
|
108
|
+
if (m === null) return { host: "", path: "/", query: "" };
|
|
109
|
+
const authority = m[1] ?? "";
|
|
110
|
+
const host = authority.slice(authority.lastIndexOf("@") + 1);
|
|
111
|
+
return { host, path: m[2] === undefined || m[2] === "" ? "/" : m[2], query: m[3] ?? "" };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The path as SigV4 signs it. For a service other than S3: `.` and `..` segments resolved and empty segments dropped, each segment
|
|
116
|
+
* decoded and encoded twice (RFC 3986). For S3: the path as given, each segment decoded and encoded once.
|
|
117
|
+
*/
|
|
118
|
+
export function canonicalPath(path: string, service: string): string {
|
|
119
|
+
const absolute = path.startsWith("/");
|
|
120
|
+
const raw = path.split("/");
|
|
121
|
+
if (service === "s3") return raw.map((s) => uriEncode(decoded(s))).join("/") || "/";
|
|
122
|
+
const segments: string[] = [];
|
|
123
|
+
for (const s of raw) {
|
|
124
|
+
if (s === "" || s === ".") continue;
|
|
125
|
+
if (s === "..") segments.pop();
|
|
126
|
+
else segments.push(s);
|
|
127
|
+
}
|
|
128
|
+
const trailing = segments.length > 0 && path.endsWith("/") ? "/" : "";
|
|
129
|
+
const joined = segments.map((s) => uriEncode(uriEncode(decoded(s)))).join("/");
|
|
130
|
+
return `${absolute ? "/" : ""}${joined}${trailing}` || "/";
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The query as SigV4 signs it: each name and value decoded and encoded by RFC 3986, a name without `=` given an empty value, sorted. */
|
|
134
|
+
export function canonicalQuery(query: string): string {
|
|
135
|
+
if (query === "") return "";
|
|
136
|
+
const pairs = query
|
|
137
|
+
.split("&")
|
|
138
|
+
.filter((p) => p !== "")
|
|
139
|
+
.map((p): readonly [string, string] => {
|
|
140
|
+
const eq = p.indexOf("=");
|
|
141
|
+
const name = eq < 0 ? p : p.slice(0, eq);
|
|
142
|
+
const value = eq < 0 ? "" : p.slice(eq + 1);
|
|
143
|
+
return [uriEncode(decoded(name)), uriEncode(decoded(value))];
|
|
144
|
+
});
|
|
145
|
+
pairs.sort(([a, x], [b, y]) => (a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0));
|
|
146
|
+
return pairs.map(([k, v]) => `${k}=${v}`).join("&");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function hmac(key: Uint8Array, data: string): Promise<Uint8Array> {
|
|
150
|
+
const k = await crypto.subtle.importKey("raw", new Uint8Array(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
151
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", k, encoder.encode(data)));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The signing key: HMAC-SHA256 of `AWS4` and the secret through the day (`YYYYMMDD`), the region, the service and `aws4_request`. */
|
|
155
|
+
export async function signingKey(secretAccessKey: string, day: string, region: string, service: string): Promise<Uint8Array> {
|
|
156
|
+
let k = await hmac(encoder.encode(`AWS4${secretAccessKey}`), day);
|
|
157
|
+
for (const part of [region, service, "aws4_request"]) k = await hmac(k, part);
|
|
158
|
+
return k;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A request signed by Signature Version 4 (FR-068): the headers to send, and the canonical request, string to sign and signature. */
|
|
162
|
+
export async function sign(request: SigV4Request, options: SigV4Options): Promise<Signed> {
|
|
163
|
+
const { credentials, region, service } = options;
|
|
164
|
+
const when = amzDate(options.date);
|
|
165
|
+
const day = when.slice(0, 8);
|
|
166
|
+
const url = urlParts(request.url);
|
|
167
|
+
const body = request.body ?? "";
|
|
168
|
+
const payload = options.unsignedPayload === true ? UNSIGNED_PAYLOAD : await sha256(body);
|
|
169
|
+
const send = new Map<string, { readonly name: string; readonly value: string }>();
|
|
170
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
171
|
+
const lower = name.toLowerCase();
|
|
172
|
+
const before = send.get(lower);
|
|
173
|
+
send.set(lower, { name, value: before === undefined ? value : `${before.value},${value}` });
|
|
174
|
+
}
|
|
175
|
+
const put = (name: string, value: string): void => void send.set(name, { name, value });
|
|
176
|
+
put("x-amz-date", when);
|
|
177
|
+
if (credentials.sessionToken !== undefined) put("x-amz-security-token", credentials.sessionToken);
|
|
178
|
+
if (options.contentSha256Header === true || service === "s3") put("x-amz-content-sha256", payload);
|
|
179
|
+
const host = send.get("host")?.value ?? url.host;
|
|
180
|
+
const signedValues = new Map<string, string>([["host", host]]);
|
|
181
|
+
for (const [lower, { value }] of send) if (!UNSIGNED_HEADERS.has(lower) && lower !== "host") signedValues.set(lower, value);
|
|
182
|
+
const names = [...signedValues.keys()].sort();
|
|
183
|
+
const canonicalHeaders = names.map((n) => `${n}:${(signedValues.get(n) ?? "").trim().replace(/\s+/g, " ")}\n`).join("");
|
|
184
|
+
const signedHeaders = names.join(";");
|
|
185
|
+
const canonicalRequest = [
|
|
186
|
+
request.method.toUpperCase(),
|
|
187
|
+
canonicalPath(url.path, service),
|
|
188
|
+
canonicalQuery(url.query),
|
|
189
|
+
canonicalHeaders,
|
|
190
|
+
signedHeaders,
|
|
191
|
+
payload,
|
|
192
|
+
].join("\n");
|
|
193
|
+
const scope = `${day}/${region}/${service}/aws4_request`;
|
|
194
|
+
const stringToSign = [ALGORITHM, when, scope, await sha256(canonicalRequest)].join("\n");
|
|
195
|
+
const signature = toHex(await hmac(await signingKey(credentials.secretAccessKey, day, region, service), stringToSign));
|
|
196
|
+
const authorization = `${ALGORITHM} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
|
|
197
|
+
const headers: Record<string, string> = {};
|
|
198
|
+
for (const [lower, { name, value }] of send) if (lower !== "host" && lower !== "authorization") headers[name] = value;
|
|
199
|
+
headers["authorization"] = authorization;
|
|
200
|
+
return { headers, canonicalRequest, stringToSign, signature, authorization };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* A web `Request` signed by Signature Version 4 (FR-068): a new `Request` with the same method, URL and body and the signed headers. Its
|
|
205
|
+
* body is read once (from a clone) to be hashed. The URL is the one the `Request` holds, which a URL parser has already normalized.
|
|
206
|
+
*/
|
|
207
|
+
export async function signRequest(request: Request, options: SigV4Options): Promise<Request> {
|
|
208
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD" && request.body !== null;
|
|
209
|
+
const body = hasBody ? new Uint8Array(await request.clone().arrayBuffer()) : undefined;
|
|
210
|
+
const headers: Record<string, string> = {};
|
|
211
|
+
request.headers.forEach((value, name) => {
|
|
212
|
+
headers[name] = value;
|
|
213
|
+
});
|
|
214
|
+
const signed = await sign({ method: request.method, url: request.url, headers, ...(body === undefined ? {} : { body }) }, options);
|
|
215
|
+
return new Request(request.url, { method: request.method, headers: signed.headers, ...(body === undefined ? {} : { body }) });
|
|
216
|
+
}
|
package/src/uuid.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Spec: 0001-crypto FR-007
|
|
2
|
+
/**
|
|
3
|
+
* UUIDs (RFC 9562): the branded `Uuid`, its text form read and written, the name-based version 5 (SHA-1 of a namespace and a name) and the
|
|
4
|
+
* namespaces RFC 9562 defines (Appendix A.4: DNS, URL, OID, X.500). A version 5 UUID is the same for the same namespace and name on every
|
|
5
|
+
* runtime, so the standard formats name what they describe by it and the same input gives the same document (commons 0007-grc FR-017,
|
|
6
|
+
* FR-018). SHA-1 is Web Crypto's (`crypto.subtle.digest`), so `uuidV5` is asynchronous; it is used here as RFC 9562 uses it, to name, not
|
|
7
|
+
* to protect.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { NAMESPACE_DNS, uuidV5 } from "./uuid.ts";
|
|
12
|
+
* await uuidV5(NAMESPACE_DNS, "www.example.com"); // "2ed6657d-e927-568b-95e1-2665a8aea6a2"
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
import { type Decoder, describe, err, ok } from "@intellectual-frontiers/core";
|
|
18
|
+
import type { Brand } from "@intellectual-frontiers/core";
|
|
19
|
+
import { fromHex, toHex } from "@intellectual-frontiers/formats/hex";
|
|
20
|
+
|
|
21
|
+
/** A UUID in RFC 9562's text form, lower-case: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`; made only by `uuidOf`, `uuidFromBytes` and `uuidV5`. */
|
|
22
|
+
export type Uuid = Brand<string, "Uuid">;
|
|
23
|
+
|
|
24
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
25
|
+
|
|
26
|
+
/** Text as a `Uuid` (any case, with or without a `urn:uuid:` prefix), lower-cased; undefined where it is not one. */
|
|
27
|
+
export function uuidOf(text: string): Uuid | undefined {
|
|
28
|
+
const t = text.trim().toLowerCase();
|
|
29
|
+
const bare = t.startsWith("urn:uuid:") ? t.slice("urn:uuid:".length) : t;
|
|
30
|
+
return UUID.test(bare) ? (bare as Uuid) : undefined; // checked against the text form just above
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Sixteen bytes as a `Uuid`, or undefined where there are not sixteen. */
|
|
34
|
+
export function uuidFromBytes(bytes: Uint8Array): Uuid | undefined {
|
|
35
|
+
if (bytes.length !== 16) return undefined;
|
|
36
|
+
const x = toHex(bytes);
|
|
37
|
+
return uuidOf(`${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A UUID's sixteen bytes. */
|
|
41
|
+
export function uuidBytes(u: Uuid): Uint8Array {
|
|
42
|
+
return fromHex(u.replaceAll("-", "")) ?? new Uint8Array(16);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A UUID's version, the high four bits of its seventh byte (5 for a name-based UUID with SHA-1). */
|
|
46
|
+
export function uuidVersion(u: Uuid): number {
|
|
47
|
+
return Number.parseInt(u.charAt(14), 16);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A UUID as a URN, `urn:uuid:...` (RFC 9562 Section 4). */
|
|
51
|
+
export function uuidUrn(u: Uuid): `urn:uuid:${string}` {
|
|
52
|
+
return `urn:uuid:${u}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function constant(text: string): Uuid {
|
|
56
|
+
const u = uuidOf(text);
|
|
57
|
+
if (u === undefined) throw new Error(`not a UUID: ${text}`);
|
|
58
|
+
return u;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The Nil UUID, all zeros (RFC 9562 Section 5.9). */
|
|
62
|
+
export const NIL_UUID: Uuid = constant("00000000-0000-0000-0000-000000000000");
|
|
63
|
+
|
|
64
|
+
/** The namespace of fully qualified domain names (RFC 9562 Section 6.6). */
|
|
65
|
+
export const NAMESPACE_DNS: Uuid = constant("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
|
|
66
|
+
|
|
67
|
+
/** The namespace of URLs (RFC 9562 Section 6.6). */
|
|
68
|
+
export const NAMESPACE_URL: Uuid = constant("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
|
|
69
|
+
|
|
70
|
+
/** The namespace of ISO object identifiers (RFC 9562 Section 6.6). */
|
|
71
|
+
export const NAMESPACE_OID: Uuid = constant("6ba7b812-9dad-11d1-80b4-00c04fd430c8");
|
|
72
|
+
|
|
73
|
+
/** The namespace of X.500 distinguished names, in DER or text (RFC 9562 Section 6.6). */
|
|
74
|
+
export const NAMESPACE_X500: Uuid = constant("6ba7b814-9dad-11d1-80b4-00c04fd430c8");
|
|
75
|
+
|
|
76
|
+
const utf8 = new TextEncoder();
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The version 5 UUID of a name in a namespace (RFC 9562 Section 5.5): the first sixteen bytes of SHA-1 over the namespace's bytes and then
|
|
80
|
+
* the name's (a string is taken as UTF-8), with the version (5) and the variant (`10`) set.
|
|
81
|
+
*/
|
|
82
|
+
export async function uuidV5(namespace: Uuid, name: string | Uint8Array): Promise<Uuid> {
|
|
83
|
+
const ns = uuidBytes(namespace);
|
|
84
|
+
const n = typeof name === "string" ? utf8.encode(name) : name;
|
|
85
|
+
const input = new Uint8Array(ns.length + n.length);
|
|
86
|
+
input.set(ns);
|
|
87
|
+
input.set(n, ns.length);
|
|
88
|
+
const hash = new Uint8Array(await crypto.subtle.digest("SHA-1", input)).slice(0, 16);
|
|
89
|
+
hash[6] = ((hash[6] ?? 0) & 0x0f) | 0x50;
|
|
90
|
+
hash[8] = ((hash[8] ?? 0) & 0x3f) | 0x80;
|
|
91
|
+
return uuidFromBytes(hash) ?? NIL_UUID;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A stable name made of parts, for `uuidV5`: the parts as a JSON array, so that no two lists of parts give the same name (`["a/b"]` and
|
|
96
|
+
* `["a", "b"]` stay apart).
|
|
97
|
+
*/
|
|
98
|
+
export function nameOf(parts: readonly string[]): string {
|
|
99
|
+
return JSON.stringify(parts);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The version 5 UUID of a name made of parts (`nameOf`) in a namespace. */
|
|
103
|
+
export function uuidV5Of(namespace: Uuid, parts: readonly string[]): Promise<Uuid> {
|
|
104
|
+
return uuidV5(namespace, nameOf(parts));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The decoder of a UUID in text (any case, or a `urn:uuid:` URN). */
|
|
108
|
+
export const uuidDecoder: Decoder<Uuid> = (input, path = "$") => {
|
|
109
|
+
const u = typeof input === "string" ? uuidOf(input) : undefined;
|
|
110
|
+
return u === undefined ? err({ kind: "decode", path, expected: "a UUID", found: describe(input) }) : ok(u);
|
|
111
|
+
};
|