@intellectual-frontiers/crypto 0.0.0-stage → 0.1.1

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/dist/sigv4.js ADDED
@@ -0,0 +1,169 @@
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.js";
25
+ /** The algorithm's name, as the string to sign and the `Authorization` header begin. */
26
+ export const ALGORITHM = "AWS4-HMAC-SHA256";
27
+ /** What is signed in place of a body's hash where the payload is not signed. */
28
+ export const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
29
+ // Headers a transport, a proxy or a tracer may add or change after signing: never signed, so that changing them breaks no signature.
30
+ const UNSIGNED_HEADERS = new Set(["authorization", "connection", "expect", "user-agent", "x-amzn-trace-id", "traceparent", "tracestate"]);
31
+ const encoder = new TextEncoder();
32
+ /** RFC 3986 percent-encoding, as SigV4 wants it: everything but `A-Z a-z 0-9 - _ . ~` encoded, in upper-case hexadecimal. */
33
+ export function uriEncode(text) {
34
+ return encodeURIComponent(text).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
35
+ }
36
+ function decoded(text) {
37
+ try {
38
+ return decodeURIComponent(text);
39
+ }
40
+ catch {
41
+ return text;
42
+ }
43
+ }
44
+ /** `20150830T123600Z`: the time as `x-amz-date` writes it. */
45
+ export function amzDate(date) {
46
+ return date
47
+ .toISOString()
48
+ .replace(/[-:]/g, "")
49
+ .replace(/\.\d{3}Z$/, "Z");
50
+ }
51
+ /** The authority, path and query of a URL as written, without parsing (and so without normalizing) its path. */
52
+ function urlParts(url) {
53
+ const m = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#]*)([^?#]*)(?:\?([^#]*))?/.exec(url);
54
+ if (m === null)
55
+ return { host: "", path: "/", query: "" };
56
+ const authority = m[1] ?? "";
57
+ const host = authority.slice(authority.lastIndexOf("@") + 1);
58
+ return { host, path: m[2] === undefined || m[2] === "" ? "/" : m[2], query: m[3] ?? "" };
59
+ }
60
+ /**
61
+ * The path as SigV4 signs it. For a service other than S3: `.` and `..` segments resolved and empty segments dropped, each segment
62
+ * decoded and encoded twice (RFC 3986). For S3: the path as given, each segment decoded and encoded once.
63
+ */
64
+ export function canonicalPath(path, service) {
65
+ const absolute = path.startsWith("/");
66
+ const raw = path.split("/");
67
+ if (service === "s3")
68
+ return raw.map((s) => uriEncode(decoded(s))).join("/") || "/";
69
+ const segments = [];
70
+ for (const s of raw) {
71
+ if (s === "" || s === ".")
72
+ continue;
73
+ if (s === "..")
74
+ segments.pop();
75
+ else
76
+ segments.push(s);
77
+ }
78
+ const trailing = segments.length > 0 && path.endsWith("/") ? "/" : "";
79
+ const joined = segments.map((s) => uriEncode(uriEncode(decoded(s)))).join("/");
80
+ return `${absolute ? "/" : ""}${joined}${trailing}` || "/";
81
+ }
82
+ /** The query as SigV4 signs it: each name and value decoded and encoded by RFC 3986, a name without `=` given an empty value, sorted. */
83
+ export function canonicalQuery(query) {
84
+ if (query === "")
85
+ return "";
86
+ const pairs = query
87
+ .split("&")
88
+ .filter((p) => p !== "")
89
+ .map((p) => {
90
+ const eq = p.indexOf("=");
91
+ const name = eq < 0 ? p : p.slice(0, eq);
92
+ const value = eq < 0 ? "" : p.slice(eq + 1);
93
+ return [uriEncode(decoded(name)), uriEncode(decoded(value))];
94
+ });
95
+ pairs.sort(([a, x], [b, y]) => (a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0));
96
+ return pairs.map(([k, v]) => `${k}=${v}`).join("&");
97
+ }
98
+ async function hmac(key, data) {
99
+ const k = await crypto.subtle.importKey("raw", new Uint8Array(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
100
+ return new Uint8Array(await crypto.subtle.sign("HMAC", k, encoder.encode(data)));
101
+ }
102
+ /** The signing key: HMAC-SHA256 of `AWS4` and the secret through the day (`YYYYMMDD`), the region, the service and `aws4_request`. */
103
+ export async function signingKey(secretAccessKey, day, region, service) {
104
+ let k = await hmac(encoder.encode(`AWS4${secretAccessKey}`), day);
105
+ for (const part of [region, service, "aws4_request"])
106
+ k = await hmac(k, part);
107
+ return k;
108
+ }
109
+ /** A request signed by Signature Version 4 (FR-068): the headers to send, and the canonical request, string to sign and signature. */
110
+ export async function sign(request, options) {
111
+ const { credentials, region, service } = options;
112
+ const when = amzDate(options.date);
113
+ const day = when.slice(0, 8);
114
+ const url = urlParts(request.url);
115
+ const body = request.body ?? "";
116
+ const payload = options.unsignedPayload === true ? UNSIGNED_PAYLOAD : await sha256(body);
117
+ const send = new Map();
118
+ for (const [name, value] of Object.entries(request.headers)) {
119
+ const lower = name.toLowerCase();
120
+ const before = send.get(lower);
121
+ send.set(lower, { name, value: before === undefined ? value : `${before.value},${value}` });
122
+ }
123
+ const put = (name, value) => void send.set(name, { name, value });
124
+ put("x-amz-date", when);
125
+ if (credentials.sessionToken !== undefined)
126
+ put("x-amz-security-token", credentials.sessionToken);
127
+ if (options.contentSha256Header === true || service === "s3")
128
+ put("x-amz-content-sha256", payload);
129
+ const host = send.get("host")?.value ?? url.host;
130
+ const signedValues = new Map([["host", host]]);
131
+ for (const [lower, { value }] of send)
132
+ if (!UNSIGNED_HEADERS.has(lower) && lower !== "host")
133
+ signedValues.set(lower, value);
134
+ const names = [...signedValues.keys()].sort();
135
+ const canonicalHeaders = names.map((n) => `${n}:${(signedValues.get(n) ?? "").trim().replace(/\s+/g, " ")}\n`).join("");
136
+ const signedHeaders = names.join(";");
137
+ const canonicalRequest = [
138
+ request.method.toUpperCase(),
139
+ canonicalPath(url.path, service),
140
+ canonicalQuery(url.query),
141
+ canonicalHeaders,
142
+ signedHeaders,
143
+ payload,
144
+ ].join("\n");
145
+ const scope = `${day}/${region}/${service}/aws4_request`;
146
+ const stringToSign = [ALGORITHM, when, scope, await sha256(canonicalRequest)].join("\n");
147
+ const signature = toHex(await hmac(await signingKey(credentials.secretAccessKey, day, region, service), stringToSign));
148
+ const authorization = `${ALGORITHM} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
149
+ const headers = {};
150
+ for (const [lower, { name, value }] of send)
151
+ if (lower !== "host" && lower !== "authorization")
152
+ headers[name] = value;
153
+ headers["authorization"] = authorization;
154
+ return { headers, canonicalRequest, stringToSign, signature, authorization };
155
+ }
156
+ /**
157
+ * 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
158
+ * 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.
159
+ */
160
+ export async function signRequest(request, options) {
161
+ const hasBody = request.method !== "GET" && request.method !== "HEAD" && request.body !== null;
162
+ const body = hasBody ? new Uint8Array(await request.clone().arrayBuffer()) : undefined;
163
+ const headers = {};
164
+ request.headers.forEach((value, name) => {
165
+ headers[name] = value;
166
+ });
167
+ const signed = await sign({ method: request.method, url: request.url, headers, ...(body === undefined ? {} : { body }) }, options);
168
+ return new Request(request.url, { method: request.method, headers: signed.headers, ...(body === undefined ? {} : { body }) });
169
+ }
package/dist/uuid.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * 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
3
+ * 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
4
+ * runtime, so the standard formats name what they describe by it and the same input gives the same document (commons 0007-grc FR-017,
5
+ * 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
6
+ * to protect.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { NAMESPACE_DNS, uuidV5 } from "./uuid.js";
11
+ * await uuidV5(NAMESPACE_DNS, "www.example.com"); // "2ed6657d-e927-568b-95e1-2665a8aea6a2"
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+ import { type Decoder } from "@intellectual-frontiers/core";
17
+ import type { Brand } from "@intellectual-frontiers/core";
18
+ /** A UUID in RFC 9562's text form, lower-case: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`; made only by `uuidOf`, `uuidFromBytes` and `uuidV5`. */
19
+ export type Uuid = Brand<string, "Uuid">;
20
+ /** Text as a `Uuid` (any case, with or without a `urn:uuid:` prefix), lower-cased; undefined where it is not one. */
21
+ export declare function uuidOf(text: string): Uuid | undefined;
22
+ /** Sixteen bytes as a `Uuid`, or undefined where there are not sixteen. */
23
+ export declare function uuidFromBytes(bytes: Uint8Array): Uuid | undefined;
24
+ /** A UUID's sixteen bytes. */
25
+ export declare function uuidBytes(u: Uuid): Uint8Array;
26
+ /** A UUID's version, the high four bits of its seventh byte (5 for a name-based UUID with SHA-1). */
27
+ export declare function uuidVersion(u: Uuid): number;
28
+ /** A UUID as a URN, `urn:uuid:...` (RFC 9562 Section 4). */
29
+ export declare function uuidUrn(u: Uuid): `urn:uuid:${string}`;
30
+ /** The Nil UUID, all zeros (RFC 9562 Section 5.9). */
31
+ export declare const NIL_UUID: Uuid;
32
+ /** The namespace of fully qualified domain names (RFC 9562 Section 6.6). */
33
+ export declare const NAMESPACE_DNS: Uuid;
34
+ /** The namespace of URLs (RFC 9562 Section 6.6). */
35
+ export declare const NAMESPACE_URL: Uuid;
36
+ /** The namespace of ISO object identifiers (RFC 9562 Section 6.6). */
37
+ export declare const NAMESPACE_OID: Uuid;
38
+ /** The namespace of X.500 distinguished names, in DER or text (RFC 9562 Section 6.6). */
39
+ export declare const NAMESPACE_X500: Uuid;
40
+ /**
41
+ * 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
42
+ * the name's (a string is taken as UTF-8), with the version (5) and the variant (`10`) set.
43
+ */
44
+ export declare function uuidV5(namespace: Uuid, name: string | Uint8Array): Promise<Uuid>;
45
+ /**
46
+ * 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
47
+ * `["a", "b"]` stay apart).
48
+ */
49
+ export declare function nameOf(parts: readonly string[]): string;
50
+ /** The version 5 UUID of a name made of parts (`nameOf`) in a namespace. */
51
+ export declare function uuidV5Of(namespace: Uuid, parts: readonly string[]): Promise<Uuid>;
52
+ /** The decoder of a UUID in text (any case, or a `urn:uuid:` URN). */
53
+ export declare const uuidDecoder: Decoder<Uuid>;
package/dist/uuid.js ADDED
@@ -0,0 +1,92 @@
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 { describe, err, ok } from "@intellectual-frontiers/core";
18
+ import { fromHex, toHex } from "@intellectual-frontiers/formats/hex";
19
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
20
+ /** Text as a `Uuid` (any case, with or without a `urn:uuid:` prefix), lower-cased; undefined where it is not one. */
21
+ export function uuidOf(text) {
22
+ const t = text.trim().toLowerCase();
23
+ const bare = t.startsWith("urn:uuid:") ? t.slice("urn:uuid:".length) : t;
24
+ return UUID.test(bare) ? bare : undefined; // checked against the text form just above
25
+ }
26
+ /** Sixteen bytes as a `Uuid`, or undefined where there are not sixteen. */
27
+ export function uuidFromBytes(bytes) {
28
+ if (bytes.length !== 16)
29
+ return undefined;
30
+ const x = toHex(bytes);
31
+ return uuidOf(`${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`);
32
+ }
33
+ /** A UUID's sixteen bytes. */
34
+ export function uuidBytes(u) {
35
+ return fromHex(u.replaceAll("-", "")) ?? new Uint8Array(16);
36
+ }
37
+ /** A UUID's version, the high four bits of its seventh byte (5 for a name-based UUID with SHA-1). */
38
+ export function uuidVersion(u) {
39
+ return Number.parseInt(u.charAt(14), 16);
40
+ }
41
+ /** A UUID as a URN, `urn:uuid:...` (RFC 9562 Section 4). */
42
+ export function uuidUrn(u) {
43
+ return `urn:uuid:${u}`;
44
+ }
45
+ function constant(text) {
46
+ const u = uuidOf(text);
47
+ if (u === undefined)
48
+ throw new Error(`not a UUID: ${text}`);
49
+ return u;
50
+ }
51
+ /** The Nil UUID, all zeros (RFC 9562 Section 5.9). */
52
+ export const NIL_UUID = constant("00000000-0000-0000-0000-000000000000");
53
+ /** The namespace of fully qualified domain names (RFC 9562 Section 6.6). */
54
+ export const NAMESPACE_DNS = constant("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
55
+ /** The namespace of URLs (RFC 9562 Section 6.6). */
56
+ export const NAMESPACE_URL = constant("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
57
+ /** The namespace of ISO object identifiers (RFC 9562 Section 6.6). */
58
+ export const NAMESPACE_OID = constant("6ba7b812-9dad-11d1-80b4-00c04fd430c8");
59
+ /** The namespace of X.500 distinguished names, in DER or text (RFC 9562 Section 6.6). */
60
+ export const NAMESPACE_X500 = constant("6ba7b814-9dad-11d1-80b4-00c04fd430c8");
61
+ const utf8 = new TextEncoder();
62
+ /**
63
+ * 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
64
+ * the name's (a string is taken as UTF-8), with the version (5) and the variant (`10`) set.
65
+ */
66
+ export async function uuidV5(namespace, name) {
67
+ const ns = uuidBytes(namespace);
68
+ const n = typeof name === "string" ? utf8.encode(name) : name;
69
+ const input = new Uint8Array(ns.length + n.length);
70
+ input.set(ns);
71
+ input.set(n, ns.length);
72
+ const hash = new Uint8Array(await crypto.subtle.digest("SHA-1", input)).slice(0, 16);
73
+ hash[6] = ((hash[6] ?? 0) & 0x0f) | 0x50;
74
+ hash[8] = ((hash[8] ?? 0) & 0x3f) | 0x80;
75
+ return uuidFromBytes(hash) ?? NIL_UUID;
76
+ }
77
+ /**
78
+ * 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
79
+ * `["a", "b"]` stay apart).
80
+ */
81
+ export function nameOf(parts) {
82
+ return JSON.stringify(parts);
83
+ }
84
+ /** The version 5 UUID of a name made of parts (`nameOf`) in a namespace. */
85
+ export function uuidV5Of(namespace, parts) {
86
+ return uuidV5(namespace, nameOf(parts));
87
+ }
88
+ /** The decoder of a UUID in text (any case, or a `urn:uuid:` URN). */
89
+ export const uuidDecoder = (input, path = "$") => {
90
+ const u = typeof input === "string" ? uuidOf(input) : undefined;
91
+ return u === undefined ? err({ kind: "decode", path, expected: "a UUID", found: describe(input) }) : ok(u);
92
+ };
@@ -0,0 +1,212 @@
1
+ import { type CborKey, type CborValue } from "@intellectual-frontiers/formats/cbor";
2
+ import { type Result } from "@intellectual-frontiers/core";
3
+ /** A relying party as the options name it. */
4
+ export type PublicKeyCredentialRpEntity = {
5
+ readonly id?: string;
6
+ readonly name: string;
7
+ };
8
+ /** A user account as the options name it (`id` base64url, at most 64 bytes). */
9
+ export type PublicKeyCredentialUserEntityJSON = {
10
+ readonly id: string;
11
+ readonly name: string;
12
+ readonly displayName: string;
13
+ };
14
+ /** An algorithm offered for a new credential. */
15
+ export type PublicKeyCredentialParameters = {
16
+ readonly type: "public-key";
17
+ readonly alg: number;
18
+ };
19
+ /** A credential named by its id (base64url). */
20
+ export type PublicKeyCredentialDescriptorJSON = {
21
+ readonly type: "public-key";
22
+ readonly id: string;
23
+ readonly transports?: readonly string[];
24
+ };
25
+ /** What kind of authenticator is wanted. */
26
+ export type AuthenticatorSelectionCriteria = {
27
+ readonly authenticatorAttachment?: "platform" | "cross-platform";
28
+ readonly residentKey?: "discouraged" | "preferred" | "required";
29
+ readonly requireResidentKey?: boolean;
30
+ readonly userVerification?: "required" | "preferred" | "discouraged";
31
+ };
32
+ /** The options of `navigator.credentials.create({ publicKey })` as JSON (`PublicKeyCredential.parseCreationOptionsFromJSON` takes it). */
33
+ export type PublicKeyCredentialCreationOptionsJSON = {
34
+ readonly rp: PublicKeyCredentialRpEntity;
35
+ readonly user: PublicKeyCredentialUserEntityJSON;
36
+ readonly challenge: string;
37
+ readonly pubKeyCredParams: readonly PublicKeyCredentialParameters[];
38
+ readonly timeout?: number;
39
+ readonly excludeCredentials?: readonly PublicKeyCredentialDescriptorJSON[];
40
+ readonly authenticatorSelection?: AuthenticatorSelectionCriteria;
41
+ readonly hints?: readonly string[];
42
+ readonly attestation?: "none" | "indirect" | "direct" | "enterprise";
43
+ readonly attestationFormats?: readonly string[];
44
+ readonly extensions?: Readonly<Record<string, unknown>>;
45
+ };
46
+ /** The options of `navigator.credentials.get({ publicKey })` as JSON (`PublicKeyCredential.parseRequestOptionsFromJSON` takes it). */
47
+ export type PublicKeyCredentialRequestOptionsJSON = {
48
+ readonly challenge: string;
49
+ readonly timeout?: number;
50
+ readonly rpId?: string;
51
+ readonly allowCredentials?: readonly PublicKeyCredentialDescriptorJSON[];
52
+ readonly userVerification?: "required" | "preferred" | "discouraged";
53
+ readonly hints?: readonly string[];
54
+ readonly extensions?: Readonly<Record<string, unknown>>;
55
+ };
56
+ /** An authenticator's answer to `create()`, as `AuthenticatorAttestationResponse.toJSON()` gives it. */
57
+ export type AuthenticatorAttestationResponseJSON = {
58
+ readonly clientDataJSON: string;
59
+ readonly attestationObject: string;
60
+ readonly authenticatorData?: string;
61
+ readonly transports?: readonly string[];
62
+ readonly publicKey?: string;
63
+ readonly publicKeyAlgorithm?: number;
64
+ };
65
+ /** A new credential, as `PublicKeyCredential.toJSON()` gives it after `create()`. */
66
+ export type RegistrationResponseJSON = {
67
+ readonly id: string;
68
+ readonly rawId: string;
69
+ readonly response: AuthenticatorAttestationResponseJSON;
70
+ readonly authenticatorAttachment?: string | null;
71
+ readonly clientExtensionResults: Readonly<Record<string, unknown>>;
72
+ readonly type: "public-key";
73
+ };
74
+ /** An authenticator's answer to `get()`, as `AuthenticatorAssertionResponse.toJSON()` gives it. */
75
+ export type AuthenticatorAssertionResponseJSON = {
76
+ readonly clientDataJSON: string;
77
+ readonly authenticatorData: string;
78
+ readonly signature: string;
79
+ readonly userHandle?: string | null;
80
+ };
81
+ /** An assertion, as `PublicKeyCredential.toJSON()` gives it after `get()`. */
82
+ export type AuthenticationResponseJSON = {
83
+ readonly id: string;
84
+ readonly rawId: string;
85
+ readonly response: AuthenticatorAssertionResponseJSON;
86
+ readonly authenticatorAttachment?: string | null;
87
+ readonly clientExtensionResults: Readonly<Record<string, unknown>>;
88
+ readonly type: "public-key";
89
+ };
90
+ /** A credential as the relying party keeps it: its id and COSE public key (base64url), its algorithm and its last signature counter. */
91
+ export type StoredCredential = {
92
+ readonly id: string;
93
+ readonly publicKey: string;
94
+ readonly alg: number;
95
+ readonly signCount: number;
96
+ };
97
+ /** What a verified registration gives the relying party to keep. */
98
+ export type VerifiedRegistration = {
99
+ /** The credential's id, base64url. */
100
+ readonly credentialId: string;
101
+ /** The credential's public key as its CBOR `COSE_Key`, base64url. */
102
+ readonly publicKey: string;
103
+ /** Its COSE algorithm: -7 (ES256) or -8 (EdDSA). */
104
+ readonly alg: number;
105
+ readonly signCount: number;
106
+ readonly userVerified: boolean;
107
+ /** Whether the credential is backed up (synced, a passkey): the BS flag. */
108
+ readonly backedUp: boolean;
109
+ /** Whether it may be backed up: the BE flag. */
110
+ readonly backupEligible: boolean;
111
+ /** The authenticator's AAGUID, as a UUID (all zeros under attestation `none`). */
112
+ readonly aaguid: string;
113
+ /** The attestation format the authenticator used (`none` or `packed`). */
114
+ readonly fmt: string;
115
+ readonly transports?: string[];
116
+ };
117
+ /** What a verified authentication gives: the counter to keep, and the flags. */
118
+ export type VerifiedAuthentication = {
119
+ readonly signCount: number;
120
+ readonly userVerified: boolean;
121
+ readonly backedUp: boolean;
122
+ };
123
+ /** The default time a ceremony may take: five minutes, within what Level 3 recommends where user verification is required. */
124
+ export declare const DEFAULT_TIMEOUT_MS = 300000;
125
+ /**
126
+ * The options for registering a credential: ES256 and EdDSA offered, a discoverable credential preferred, user verification required, no
127
+ * attestation asked for, and the credentials the user already has excluded. A challenge shorter than 16 bytes or a user id longer than 64
128
+ * is a programming error and throws a `RangeError`.
129
+ */
130
+ export declare function registrationOptions(o: {
131
+ readonly rpId: string;
132
+ readonly rpName: string;
133
+ readonly user: {
134
+ readonly id: string;
135
+ readonly name: string;
136
+ readonly displayName: string;
137
+ };
138
+ readonly challenge: string;
139
+ readonly excludeCredentials?: readonly string[];
140
+ readonly timeoutMs?: number;
141
+ }): PublicKeyCredentialCreationOptionsJSON;
142
+ /** The options for authenticating: user verification required, and the credentials allowed where the user is known (none for a passkey's discoverable sign-in). */
143
+ export declare function authenticationOptions(o: {
144
+ readonly rpId: string;
145
+ readonly challenge: string;
146
+ readonly allowCredentials?: readonly string[];
147
+ readonly timeoutMs?: number;
148
+ }): PublicKeyCredentialRequestOptionsJSON;
149
+ /** The flags of authenticator data (WebAuthn §6.1). */
150
+ export declare const FLAGS: {
151
+ readonly up: 1;
152
+ readonly uv: 4;
153
+ readonly be: 8;
154
+ readonly bs: 16;
155
+ readonly at: 64;
156
+ readonly ed: 128;
157
+ };
158
+ /** Authenticator data as read (WebAuthn §6.1). */
159
+ export type AuthenticatorData = {
160
+ readonly rpIdHash: Uint8Array;
161
+ readonly flags: number;
162
+ readonly userPresent: boolean;
163
+ readonly userVerified: boolean;
164
+ readonly backupEligible: boolean;
165
+ readonly backedUp: boolean;
166
+ readonly signCount: number;
167
+ /** The attested credential data, where the AT flag says it is there. */
168
+ readonly attested?: {
169
+ readonly aaguid: Uint8Array;
170
+ readonly credentialId: Uint8Array;
171
+ readonly publicKey: Uint8Array;
172
+ };
173
+ /** The extension outputs, where the ED flag says they are there. */
174
+ readonly extensions?: ReadonlyMap<CborKey, CborValue>;
175
+ };
176
+ /** Authenticator data read: the RP ID hash, the flags, the counter, the attested credential (its COSE key's bytes as given) and extensions; every byte accounted for. */
177
+ export declare function parseAuthenticatorData(bytes: Uint8Array): Result<AuthenticatorData, string>;
178
+ /** Client data as read (WebAuthn §5.8.1). */
179
+ export type ClientData = {
180
+ readonly type: string;
181
+ readonly challenge: string;
182
+ readonly origin: string;
183
+ readonly crossOrigin?: boolean;
184
+ readonly topOrigin?: string;
185
+ };
186
+ /** Client data JSON (its bytes, UTF-8) read. */
187
+ export declare function parseClientData(bytes: Uint8Array): Result<ClientData, string>;
188
+ /**
189
+ * A registration verified (WebAuthn §7.1): the client data, the attestation object, the authenticator data and the credential's key; what
190
+ * to keep, or why it is refused.
191
+ */
192
+ export declare function verifyRegistration(o: {
193
+ readonly response: RegistrationResponseJSON;
194
+ readonly expectedChallenge: string;
195
+ readonly expectedOrigin: string | readonly string[];
196
+ readonly rpId: string;
197
+ }): Promise<Result<VerifiedRegistration, string>>;
198
+ /**
199
+ * An authentication verified (WebAuthn §7.2) against the credential kept at registration: the client data, the authenticator data, the
200
+ * signature and the counter; the counter and flags to keep, or why it is refused.
201
+ */
202
+ export declare function verifyAuthentication(o: {
203
+ readonly response: AuthenticationResponseJSON;
204
+ readonly expectedChallenge: string;
205
+ readonly expectedOrigin: string | readonly string[];
206
+ readonly rpId: string;
207
+ readonly credential: StoredCredential;
208
+ }): Promise<Result<VerifiedAuthentication, string>>;
209
+ /** JSON from a browser read as a `RegistrationResponseJSON`, or why it is not one: the boundary before `verifyRegistration`. */
210
+ export declare function parseRegistrationResponse(input: unknown): Result<RegistrationResponseJSON, string>;
211
+ /** JSON from a browser read as an `AuthenticationResponseJSON`, or why it is not one: the boundary before `verifyAuthentication`. */
212
+ export declare function parseAuthenticationResponse(input: unknown): Result<AuthenticationResponseJSON, string>;