@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/src/cms.ts ADDED
@@ -0,0 +1,387 @@
1
+ // Spec: 0001-crypto FR-005
2
+ /**
3
+ * CMS (RFC 5652) AuthEnvelopedData (RFC 5083), the S/MIME (RFC 8551) form a message is encrypted in, on Web Crypto and the kernel's DER
4
+ * alone (commons 0001-crypto FR-005). Content is encrypted once with AES-256-GCM (RFC 5084), and its key is encrypted to each
5
+ * recipient's RSA public key with RSAES-OAEP, SHA-256 and MGF1 with SHA-256 (RFC 8017, RFC 4055), named by the issuer and serial number of
6
+ * the recipient's X.509 certificate (RFC 5280). The holder of a private key opens it again. PEM is read and written, and a certificate is
7
+ * read for what encryption needs (issuer, serial, key, addresses, validity, key usage). The content key and nonce come from the caller
8
+ * (`cmsKeys` with a source of random bytes), so the kernel has no effect. Taken from Stolos's `src/archon/export/smime.ts` (emailed
9
+ * exports); opening, PEM writing and typed errors are new, and the mail headers stay in Stolos.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { authEnveloped, cmsKeys, readCertificate, readPem } from "./cms.ts";
14
+ * const pem = readPem(certificateText, "CERTIFICATE");
15
+ * if (pem.kind === "ok") {
16
+ * const cert = readCertificate(pem.value[0] ?? new Uint8Array());
17
+ * if (cert.kind === "ok") {
18
+ * const der = await authEnveloped(content, [cert.value], cmsKeys((n) => crypto.getRandomValues(new Uint8Array(n))));
19
+ * }
20
+ * }
21
+ * ```
22
+ *
23
+ * @module
24
+ */
25
+ import { fromBase64, toBase64 } from "@intellectual-frontiers/formats/base64";
26
+ import {
27
+ algorithm,
28
+ children,
29
+ derNull,
30
+ explicit,
31
+ implicit,
32
+ integer,
33
+ octetString,
34
+ oid,
35
+ readInteger,
36
+ readOid,
37
+ readTlv,
38
+ sequence,
39
+ setOf,
40
+ TAG,
41
+ type Tlv,
42
+ } from "@intellectual-frontiers/formats/der";
43
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
44
+ import { toHex } from "@intellectual-frontiers/formats/hex";
45
+
46
+ /** The object identifiers used. */
47
+ export const OID = {
48
+ data: "1.2.840.113549.1.7.1",
49
+ authEnvelopedData: "1.2.840.113549.1.9.16.1.23",
50
+ aes256gcm: "2.16.840.1.101.3.4.1.46",
51
+ rsaEncryption: "1.2.840.113549.1.1.1",
52
+ rsaesOaep: "1.2.840.113549.1.1.7",
53
+ mgf1: "1.2.840.113549.1.1.8",
54
+ sha256: "2.16.840.1.101.3.4.2.1",
55
+ commonName: "2.5.4.3",
56
+ emailAddress: "1.2.840.113549.1.9.1",
57
+ subjectAltName: "2.5.29.17",
58
+ keyUsage: "2.5.29.15",
59
+ } as const;
60
+
61
+ /** Why CMS or a certificate could not be read, written or opened. */
62
+ export type CmsError =
63
+ | { readonly kind: "pem"; readonly message: string }
64
+ | { readonly kind: "certificate"; readonly message: string }
65
+ | { readonly kind: "unsupported"; readonly message: string }
66
+ | { readonly kind: "structure"; readonly message: string }
67
+ | { readonly kind: "no-recipient"; readonly message: string }
68
+ | { readonly kind: "decrypt"; readonly message: string };
69
+
70
+ /** A CMS error as one sentence. */
71
+ export function formatCmsError(e: CmsError): string {
72
+ return `${e.kind}: ${e.message}`;
73
+ }
74
+
75
+ const fail = (kind: CmsError["kind"], message: string): Result<never, CmsError> => err({ kind, message });
76
+
77
+ /** Every PEM block of a label (`CERTIFICATE`, `PRIVATE KEY`) in a text, as DER; none found, or a block that is not base64, is an error. */
78
+ export function readPem(text: string, label: string): Result<readonly Uint8Array[], CmsError> {
79
+ const out: Uint8Array[] = [];
80
+ const re = new RegExp(`-----BEGIN ${label}-----([\\s\\S]*?)-----END ${label}-----`, "g");
81
+ for (const m of text.matchAll(re)) {
82
+ const der = fromBase64(m[1] ?? "");
83
+ if (der.kind === "err") return fail("pem", `a ${label} block that is not base64`);
84
+ out.push(der.value);
85
+ }
86
+ return out.length === 0 ? fail("pem", `no -----BEGIN ${label}----- block`) : ok(out);
87
+ }
88
+
89
+ /** DER as a PEM block of a label, base64 in 64-column lines. */
90
+ export function toPem(der: Uint8Array, label: string): string {
91
+ const lines = toBase64(der).match(/.{1,64}/g) ?? [];
92
+ return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`;
93
+ }
94
+
95
+ /** What encryption and a person need from a recipient's X.509 certificate. */
96
+ export type Certificate = {
97
+ /** The issuer's Name, its DER exactly as in the certificate. */
98
+ readonly issuer: Uint8Array;
99
+ /** The serial number's INTEGER element, exactly as in the certificate. */
100
+ readonly serial: Uint8Array;
101
+ /** The serial number in hexadecimal. */
102
+ readonly serialHex: string;
103
+ /** The SubjectPublicKeyInfo, DER. */
104
+ readonly spki: Uint8Array;
105
+ /** The public key's algorithm, as an OID. */
106
+ readonly keyAlgorithm: string;
107
+ /** The subject's common name, where it has one. */
108
+ readonly commonName: string | undefined;
109
+ /** The addresses it names (subjectAltName rfc822Name and the subject's emailAddress), in lower case. */
110
+ readonly emails: readonly string[];
111
+ /** When it starts being valid, where its time can be read. */
112
+ readonly notBefore: Date | undefined;
113
+ /** When it stops being valid, where its time can be read. */
114
+ readonly notAfter: Date | undefined;
115
+ /** Whether it may encrypt keys: true where it has no keyUsage extension, else its keyEncipherment bit. */
116
+ readonly keyEncipherment: boolean;
117
+ };
118
+
119
+ const text = (t: Tlv): string => new TextDecoder().decode(t.content);
120
+
121
+ function readTime(t: Tlv): Date | undefined {
122
+ const s = text(t);
123
+ const m =
124
+ t.tag === TAG.utcTime
125
+ ? /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s)
126
+ : t.tag === TAG.generalizedTime
127
+ ? /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s)
128
+ : null;
129
+ if (m === null) return undefined;
130
+ let y = Number(m[1]);
131
+ if (t.tag === TAG.utcTime) y += y >= 50 ? 1900 : 2000;
132
+ return new Date(Date.UTC(y, Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])));
133
+ }
134
+
135
+ /** The children of an element, or a `structure` error naming what was being read. */
136
+ function kids(t: Tlv | undefined, what: string): Result<readonly Tlv[], CmsError> {
137
+ if (t === undefined) return fail("structure", `no ${what}`);
138
+ const c = children(t.content);
139
+ return c.kind === "ok" ? c : fail("structure", `${what}: ${c.error.message} at byte ${c.error.at}`);
140
+ }
141
+
142
+ function oidOf(t: Tlv | undefined): string | undefined {
143
+ if (t === undefined || t.tag !== TAG.oid) return undefined;
144
+ const r = readOid(t.content);
145
+ return r.kind === "ok" ? r.value : undefined;
146
+ }
147
+
148
+ /** The values of an attribute type in a Name (a SEQUENCE OF SET OF AttributeTypeAndValue). */
149
+ function nameValues(name: Tlv, type: string): readonly string[] {
150
+ const out: string[] = [];
151
+ const rdns = kids(name, "a name");
152
+ if (rdns.kind === "err") return out;
153
+ for (const rdn of rdns.value) {
154
+ const atvs = kids(rdn, "a relative name");
155
+ if (atvs.kind === "err") continue;
156
+ for (const atv of atvs.value) {
157
+ const pair = kids(atv, "an attribute");
158
+ if (pair.kind === "err") continue;
159
+ const [t, v] = pair.value;
160
+ if (v !== undefined && oidOf(t) === type) out.push(text(v));
161
+ }
162
+ }
163
+ return out;
164
+ }
165
+
166
+ /** An X.509 certificate read for what encryption needs, or why it is not one this reader takes. */
167
+ export function readCertificate(der: Uint8Array): Result<Certificate, CmsError> {
168
+ const cert = readTlv(der);
169
+ if (cert.kind === "err" || cert.value.tag !== TAG.sequence) return fail("certificate", "not a DER certificate");
170
+ const top = kids(cert.value, "a certificate");
171
+ if (top.kind === "err") return top;
172
+ const tbs = top.value[0];
173
+ if (tbs?.tag !== TAG.sequence) return fail("certificate", "no TBSCertificate");
174
+ const f = kids(tbs, "the TBSCertificate");
175
+ if (f.kind === "err") return f;
176
+ let i = f.value[0]?.tag === 0xa0 ? 1 : 0;
177
+ const serial = f.value[i++];
178
+ i++;
179
+ const issuer = f.value[i++];
180
+ const validity = f.value[i++];
181
+ const subject = f.value[i++];
182
+ const spki = f.value[i++];
183
+ if (serial?.tag !== TAG.integer || issuer === undefined || validity === undefined || subject === undefined || spki === undefined) {
184
+ return fail("certificate", "its fields are not where RFC 5280 puts them");
185
+ }
186
+ const alg = kids(spki, "the public key");
187
+ if (alg.kind === "err") return alg;
188
+ const algId = kids(alg.value[0], "the key's algorithm");
189
+ if (algId.kind === "err") return algId;
190
+ const keyAlgorithm = oidOf(algId.value[0]);
191
+ if (keyAlgorithm === undefined) return fail("certificate", "no key algorithm");
192
+ const emails = [...nameValues(subject, OID.emailAddress)];
193
+ let keyEncipherment = true;
194
+ const ext = f.value.slice(i).find((x) => x.tag === 0xa3);
195
+ if (ext !== undefined) {
196
+ const list = kids(ext, "the extensions");
197
+ if (list.kind === "err") return list;
198
+ const items = kids(list.value[0], "the extensions");
199
+ if (items.kind === "err") return items;
200
+ for (const e of items.value) {
201
+ const parts = kids(e, "an extension");
202
+ if (parts.kind === "err") return parts;
203
+ const id = oidOf(parts.value[0]);
204
+ const value = parts.value.at(-1);
205
+ if (value === undefined) continue;
206
+ const inner = readTlv(value.content);
207
+ if (inner.kind === "err") continue;
208
+ if (id === OID.subjectAltName) {
209
+ const names = kids(inner.value, "subjectAltName");
210
+ if (names.kind === "ok") for (const gn of names.value) if (gn.tag === 0x81) emails.push(text(gn));
211
+ } else if (id === OID.keyUsage) {
212
+ keyEncipherment = ((inner.value.content[1] ?? 0) & 0x20) !== 0;
213
+ }
214
+ }
215
+ }
216
+ const times = kids(validity, "the validity");
217
+ const [from, to] = times.kind === "ok" ? times.value : [];
218
+ return ok({
219
+ issuer: issuer.raw,
220
+ serial: serial.raw,
221
+ serialHex: toHex(serial.content),
222
+ spki: spki.raw,
223
+ keyAlgorithm,
224
+ commonName: nameValues(subject, OID.commonName)[0],
225
+ emails: [...new Set(emails.map((e) => e.toLowerCase()))],
226
+ notBefore: from === undefined ? undefined : readTime(from),
227
+ notAfter: to === undefined ? undefined : readTime(to),
228
+ keyEncipherment,
229
+ });
230
+ }
231
+
232
+ /** Why a certificate cannot encrypt to an address now. */
233
+ export type CertificateProblem =
234
+ | { readonly kind: "not-rsa"; readonly algorithm: string }
235
+ | { readonly kind: "not-yet-valid"; readonly from: Date }
236
+ | { readonly kind: "expired"; readonly on: Date }
237
+ | { readonly kind: "signing-only" }
238
+ | { readonly kind: "other-address"; readonly names: readonly string[] };
239
+
240
+ /** Why a certificate cannot be used to encrypt to `address` at `now`, or undefined where it can. */
241
+ export function certificateProblem(c: Certificate, address: string, now: Date): CertificateProblem | undefined {
242
+ if (c.keyAlgorithm !== OID.rsaEncryption) return { kind: "not-rsa", algorithm: c.keyAlgorithm };
243
+ if (c.notBefore !== undefined && c.notBefore.getTime() > now.getTime()) return { kind: "not-yet-valid", from: c.notBefore };
244
+ if (c.notAfter !== undefined && c.notAfter.getTime() < now.getTime()) return { kind: "expired", on: c.notAfter };
245
+ if (!c.keyEncipherment) return { kind: "signing-only" };
246
+ if (c.emails.length > 0 && !c.emails.includes(address.toLowerCase())) return { kind: "other-address", names: c.emails };
247
+ return undefined;
248
+ }
249
+
250
+ /** RSAES-OAEP with SHA-256 and MGF1 with SHA-256, as an AlgorithmIdentifier (RFC 4055 §4.1). */
251
+ export function oaepSha256(): Uint8Array {
252
+ const sha256 = algorithm(OID.sha256, derNull());
253
+ return algorithm(OID.rsaesOaep, sequence(explicit(0, sha256), explicit(1, algorithm(OID.mgf1, sha256))));
254
+ }
255
+
256
+ /** The fresh secrets of one message: a 32-byte AES-256 content key and a 12-byte GCM nonce. */
257
+ export type CmsKeys = { readonly contentKey: Uint8Array; readonly nonce: Uint8Array };
258
+
259
+ /** Fresh secrets from a source of random bytes, such as `(n) => crypto.getRandomValues(new Uint8Array(n))`. */
260
+ export function cmsKeys(random: (length: number) => Uint8Array): CmsKeys {
261
+ return { contentKey: random(32), nonce: random(12) };
262
+ }
263
+
264
+ /**
265
+ * A CMS ContentInfo holding AuthEnvelopedData, as DER: `content` encrypted with AES-256-GCM, its key encrypted to every recipient with
266
+ * RSA-OAEP SHA-256. No recipient, a recipient whose key is not RSA, or keys of the wrong size are errors.
267
+ */
268
+ export async function authEnveloped(
269
+ content: Uint8Array,
270
+ recipients: readonly Certificate[],
271
+ keys: CmsKeys,
272
+ ): Promise<Result<Uint8Array, CmsError>> {
273
+ if (recipients.length === 0) return fail("no-recipient", "no recipient to encrypt to");
274
+ if (keys.contentKey.length !== 32 || keys.nonce.length !== 12) return fail("unsupported", "a content key of 32 bytes and a nonce of 12");
275
+ const notRsa = recipients.find((r) => r.keyAlgorithm !== OID.rsaEncryption);
276
+ if (notRsa !== undefined) return fail("unsupported", `the key of certificate ${notRsa.serialHex} is not RSA (${notRsa.keyAlgorithm})`);
277
+ const aes = await crypto.subtle.importKey("raw", new Uint8Array(keys.contentKey), "AES-GCM", false, ["encrypt"]);
278
+ const sealed = new Uint8Array(
279
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(keys.nonce), tagLength: 128 }, aes, new Uint8Array(content)),
280
+ );
281
+ const infos: Uint8Array[] = [];
282
+ for (const r of recipients) {
283
+ const pub = await crypto.subtle.importKey("spki", new Uint8Array(r.spki), { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
284
+ const ek = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, pub, new Uint8Array(keys.contentKey)));
285
+ infos.push(sequence(integer(0), sequence(r.issuer, r.serial), oaepSha256(), octetString(ek)));
286
+ }
287
+ const eci = sequence(
288
+ oid(OID.data),
289
+ algorithm(OID.aes256gcm, sequence(octetString(keys.nonce), integer(16))),
290
+ implicit(0, sealed.subarray(0, sealed.length - 16), false),
291
+ );
292
+ const aed = sequence(integer(0), setOf(...infos), eci, octetString(sealed.subarray(sealed.length - 16)));
293
+ return ok(sequence(oid(OID.authEnvelopedData), explicit(0, aed)));
294
+ }
295
+
296
+ /** Whether an AlgorithmIdentifier names SHA-256, its parameters NULL or absent (both are accepted, RFC 4055 §2.1, RFC 5754 §2). */
297
+ function isSha256(t: Tlv | undefined): boolean {
298
+ const parts = t === undefined ? undefined : children(t.content);
299
+ if (parts?.kind !== "ok" || oidOf(parts.value[0]) !== OID.sha256) return false;
300
+ const params = parts.value[1];
301
+ return parts.value.length === 1 || (parts.value.length === 2 && params?.tag === TAG.null && params.content.length === 0);
302
+ }
303
+
304
+ /** Whether an AlgorithmIdentifier is RSAES-OAEP with SHA-256, MGF1 with SHA-256 and the default label, however its NULLs are written. */
305
+ export function isOaepSha256(t: Tlv): boolean {
306
+ const parts = children(t.content);
307
+ if (parts.kind === "err" || oidOf(parts.value[0]) !== OID.rsaesOaep) return false;
308
+ const params = kids(parts.value[1], "the OAEP parameters");
309
+ if (params.kind === "err") return false;
310
+ const hash = params.value.find((p) => p.tag === 0xa0);
311
+ const mgf = params.value.find((p) => p.tag === 0xa1);
312
+ if (params.value.some((p) => p.tag !== 0xa0 && p.tag !== 0xa1) || hash === undefined || mgf === undefined) return false;
313
+ const h = readTlv(hash.content);
314
+ const m = readTlv(mgf.content);
315
+ if (h.kind === "err" || m.kind === "err" || !isSha256(h.value)) return false;
316
+ const mgfParts = children(m.value.content);
317
+ return mgfParts.kind === "ok" && oidOf(mgfParts.value[0]) === OID.mgf1 && isSha256(mgfParts.value[1]);
318
+ }
319
+
320
+ const same = (a: Uint8Array, b: Uint8Array): boolean => a.length === b.length && a.every((x, k) => x === b[k]);
321
+
322
+ /**
323
+ * The content of an AuthEnvelopedData, opened by the recipient whose certificate is `cert` with its RSA-OAEP SHA-256 private key; or why
324
+ * it cannot be: not this structure, no RecipientInfo for this certificate, or a key or tag that does not decrypt (the content was changed).
325
+ */
326
+ export async function openAuthEnveloped(der: Uint8Array, cert: Certificate, privateKey: CryptoKey): Promise<Result<Uint8Array, CmsError>> {
327
+ const info = readTlv(der);
328
+ if (info.kind === "err") return fail("structure", "not DER");
329
+ const ci = kids(info.value, "the ContentInfo");
330
+ if (ci.kind === "err") return ci;
331
+ if (oidOf(ci.value[0]) !== OID.authEnvelopedData) return fail("structure", "not AuthEnvelopedData");
332
+ const wrapped = kids(ci.value[1], "the content");
333
+ if (wrapped.kind === "err") return wrapped;
334
+ const aed = kids(wrapped.value[0], "the AuthEnvelopedData");
335
+ if (aed.kind === "err") return aed;
336
+ const [version, recipientSet, eci, mac] = aed.value;
337
+ if (version?.tag !== TAG.integer || recipientSet?.tag !== TAG.set || eci === undefined || mac?.tag !== TAG.octetString) {
338
+ return fail("structure", "an AuthEnvelopedData without its four fields (attributes are not read)");
339
+ }
340
+ const v = readInteger(version.content);
341
+ if (v.kind === "err" || v.value !== 0n) return fail("unsupported", "an AuthEnvelopedData of version 0");
342
+ const infos = kids(recipientSet, "the RecipientInfos");
343
+ if (infos.kind === "err") return infos;
344
+ let encryptedKey: Uint8Array | undefined;
345
+ for (const r of infos.value) {
346
+ const parts = kids(r, "a RecipientInfo");
347
+ if (parts.kind === "err") return parts;
348
+ const [, rid, alg, ek] = parts.value;
349
+ const ids = kids(rid, "an IssuerAndSerialNumber");
350
+ if (ids.kind === "err" || ek === undefined || alg === undefined) continue;
351
+ const [issuer, serial] = ids.value;
352
+ if (issuer !== undefined && serial !== undefined && same(issuer.raw, cert.issuer) && same(serial.raw, cert.serial)) {
353
+ if (!isOaepSha256(alg)) return fail("unsupported", "a key encrypted with RSA-OAEP, SHA-256 and MGF1 with SHA-256");
354
+ encryptedKey = ek.content;
355
+ }
356
+ }
357
+ if (encryptedKey === undefined) return fail("no-recipient", `no RecipientInfo for certificate ${cert.serialHex}`);
358
+ const ec = kids(eci, "the EncryptedContentInfo");
359
+ if (ec.kind === "err") return ec;
360
+ const [type, cipher, body] = ec.value;
361
+ const cipherParts = kids(cipher, "the content's algorithm");
362
+ if (cipherParts.kind === "err") return cipherParts;
363
+ if (oidOf(type) !== OID.data || oidOf(cipherParts.value[0]) !== OID.aes256gcm || body?.tag !== 0x80) {
364
+ return fail("unsupported", "id-data content encrypted with AES-256-GCM");
365
+ }
366
+ const params = kids(cipherParts.value[1], "the GCM parameters");
367
+ if (params.kind === "err") return params;
368
+ const nonce = params.value[0];
369
+ if (nonce?.tag !== TAG.octetString) return fail("structure", "no GCM nonce");
370
+ let rawKey: Uint8Array;
371
+ try {
372
+ rawKey = new Uint8Array(await crypto.subtle.decrypt({ name: "RSA-OAEP" }, privateKey, new Uint8Array(encryptedKey)));
373
+ } catch {
374
+ return fail("decrypt", "the content key does not decrypt with this private key");
375
+ }
376
+ try {
377
+ const aes = await crypto.subtle.importKey("raw", new Uint8Array(rawKey), "AES-GCM", false, ["decrypt"]);
378
+ const sealed = new Uint8Array(body.content.length + mac.content.length);
379
+ sealed.set(body.content);
380
+ sealed.set(mac.content, body.content.length);
381
+ return ok(
382
+ new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(nonce.content), tagLength: 128 }, aes, sealed)),
383
+ );
384
+ } catch {
385
+ return fail("decrypt", "the content does not decrypt: it was changed, or the key is not its own");
386
+ }
387
+ }
package/src/cose.ts ADDED
@@ -0,0 +1,199 @@
1
+ // Spec: 0001-crypto FR-008
2
+ /**
3
+ * COSE keys and signatures (RFC 9052, RFC 9053) as WebAuthn uses them (commons 0014-webauthn FR-002): a credential's public key read from
4
+ * its CBOR `COSE_Key`, checked for one of the two algorithms commons accepts (ES256, `-7`: ECDSA on P-256 with SHA-256; EdDSA, `-8`: Ed25519),
5
+ * imported into Web Crypto, and a signature verified with it, an ECDSA signature turned from the DER `Ecdsa-Sig-Value` an authenticator
6
+ * gives into the raw `r || s` Web Crypto takes. A `COSE_Key` can also be made from a public JSON Web Key, which is how a test (or a
7
+ * migration from stored JWKs) writes one.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { coseKeyFromJwk, parseCoseKey, verifyCose } from "./cose.ts";
12
+ * const pair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]);
13
+ * const cose = coseKeyFromJwk(await crypto.subtle.exportKey("jwk", pair.publicKey));
14
+ * const data = new TextEncoder().encode("signed");
15
+ * const sig = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, pair.privateKey, data));
16
+ * if (cose.kind === "ok") {
17
+ * const key = parseCoseKey(cose.value);
18
+ * if (key.kind === "ok") await verifyCose(key.value, sig, data); // { kind: "ok", value: true }
19
+ * }
20
+ * ```
21
+ *
22
+ * @limits
23
+ * Only ES256 on P-256 and EdDSA on Ed25519: RS256 and the other algorithms an authenticator may offer are refused, as commons never offers
24
+ * them.
25
+ *
26
+ * @module
27
+ */
28
+ import { fromBase64Url, toBase64Url } from "@intellectual-frontiers/formats/base64";
29
+ import { type CborKey, type CborValue, decodeCbor, encodeCbor, formatCborError, isMap } from "@intellectual-frontiers/formats/cbor";
30
+ import { children, readTlv, TAG } from "@intellectual-frontiers/formats/der";
31
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
32
+
33
+ /** COSE's identifier of ES256: ECDSA on P-256 with SHA-256. */
34
+ export const ES256 = -7;
35
+ /** COSE's identifier of EdDSA (here always Ed25519). */
36
+ export const EDDSA = -8;
37
+ /** The algorithms commons accepts, in order of preference. */
38
+ export const ALGORITHMS: readonly number[] = [EDDSA, ES256];
39
+
40
+ /** A public key read from a `COSE_Key`: an EC2 key on P-256 for ES256, or an OKP key on Ed25519 for EdDSA. */
41
+ export type CoseKey =
42
+ | { readonly kty: "EC2"; readonly alg: typeof ES256; readonly crv: "P-256"; readonly x: Uint8Array; readonly y: Uint8Array }
43
+ | { readonly kty: "OKP"; readonly alg: typeof EDDSA; readonly crv: "Ed25519"; readonly x: Uint8Array };
44
+
45
+ function bytesAt(m: ReadonlyMap<CborKey, CborValue>, label: number, name: string, size: number): Result<Uint8Array, string> {
46
+ const v = m.get(label);
47
+ if (!(v instanceof Uint8Array)) return err(`the COSE key has no ${name} as bytes`);
48
+ if (v.length !== size) return err(`the COSE key's ${name} is ${v.length} bytes, not ${size}`);
49
+ return ok(v);
50
+ }
51
+
52
+ /** A `COSE_Key` read from its CBOR: a map with `kty` (1), `alg` (3), `crv` (-1), `x` (-2) and, for EC2, `y` (-3); anything else refused. */
53
+ export function parseCoseKey(bytes: Uint8Array): Result<CoseKey, string> {
54
+ const d = decodeCbor(bytes);
55
+ if (d.kind === "err") return err(`the COSE key is not CBOR (${formatCborError(d.error)})`);
56
+ const m = d.value;
57
+ if (!isMap(m)) return err("the COSE key is not a CBOR map");
58
+ const kty = m.get(1);
59
+ const alg = m.get(3);
60
+ const crv = m.get(-1);
61
+ if (alg === ES256) {
62
+ if (kty !== 2) return err("an ES256 COSE key whose kty is not EC2 (2)");
63
+ if (crv !== 1) return err("an ES256 COSE key whose curve is not P-256 (1)");
64
+ const x = bytesAt(m, -2, "x", 32);
65
+ if (x.kind === "err") return x;
66
+ const y = bytesAt(m, -3, "y", 32);
67
+ if (y.kind === "err") return y;
68
+ return ok({ kty: "EC2", alg: ES256, crv: "P-256", x: x.value, y: y.value });
69
+ }
70
+ if (alg === EDDSA) {
71
+ if (kty !== 1) return err("an EdDSA COSE key whose kty is not OKP (1)");
72
+ if (crv !== 6) return err("an EdDSA COSE key whose curve is not Ed25519 (6)");
73
+ const x = bytesAt(m, -2, "x", 32);
74
+ if (x.kind === "err") return x;
75
+ return ok({ kty: "OKP", alg: EDDSA, crv: "Ed25519", x: x.value });
76
+ }
77
+ return err(
78
+ `the COSE key's algorithm ${typeof alg === "number" || typeof alg === "bigint" ? String(alg) : "(none)"} is not accepted (only ES256, -7, and EdDSA, -8)`,
79
+ );
80
+ }
81
+
82
+ /** The CBOR `COSE_Key` of a key (deterministic: its labels sorted). */
83
+ export function encodeCoseKey(key: CoseKey): Uint8Array {
84
+ const m = new Map<CborKey, CborValue>(
85
+ key.kty === "EC2"
86
+ ? [
87
+ [1, 2],
88
+ [3, ES256],
89
+ [-1, 1],
90
+ [-2, key.x],
91
+ [-3, key.y],
92
+ ]
93
+ : [
94
+ [1, 1],
95
+ [3, EDDSA],
96
+ [-1, 6],
97
+ [-2, key.x],
98
+ ],
99
+ );
100
+ return encodeCbor(m);
101
+ }
102
+
103
+ /** The `COSE_Key` of a public JSON Web Key: EC on P-256 (as ES256) or OKP on Ed25519 (as EdDSA); any other key refused. */
104
+ export function coseKeyFromJwk(jwk: JsonWebKey): Result<Uint8Array, string> {
105
+ const b = (v: string | undefined, name: string): Result<Uint8Array, string> => {
106
+ if (v === undefined) return err(`the JWK has no ${name}`);
107
+ const r = fromBase64Url(v);
108
+ return r.kind === "ok" && r.value.length === 32 ? r : err(`the JWK's ${name} is not 32 bytes of base64url`);
109
+ };
110
+ if (jwk.kty === "EC" && jwk.crv === "P-256") {
111
+ const x = b(jwk.x, "x");
112
+ if (x.kind === "err") return x;
113
+ const y = b(jwk.y, "y");
114
+ if (y.kind === "err") return y;
115
+ return ok(encodeCoseKey({ kty: "EC2", alg: ES256, crv: "P-256", x: x.value, y: y.value }));
116
+ }
117
+ if (jwk.kty === "OKP" && jwk.crv === "Ed25519") {
118
+ const x = b(jwk.x, "x");
119
+ if (x.kind === "err") return x;
120
+ return ok(encodeCoseKey({ kty: "OKP", alg: EDDSA, crv: "Ed25519", x: x.value }));
121
+ }
122
+ return err(`a JWK of type ${String(jwk.kty)} on ${String(jwk.crv)} (only EC on P-256 and OKP on Ed25519)`);
123
+ }
124
+
125
+ /** The public JSON Web Key of a COSE key. */
126
+ export function jwkOfCoseKey(key: CoseKey): JsonWebKey {
127
+ return key.kty === "EC2"
128
+ ? { kty: "EC", crv: "P-256", x: toBase64Url(key.x), y: toBase64Url(key.y) }
129
+ : { kty: "OKP", crv: "Ed25519", x: toBase64Url(key.x) };
130
+ }
131
+
132
+ /** Bytes Web Crypto takes as a `BufferSource` (a copy on its own `ArrayBuffer`). */
133
+ function own(b: Uint8Array): Uint8Array<ArrayBuffer> {
134
+ return new Uint8Array(b);
135
+ }
136
+
137
+ /** The key imported into Web Crypto for verifying; a point not on its curve is refused. */
138
+ export async function importCoseKey(key: CoseKey): Promise<Result<CryptoKey, string>> {
139
+ try {
140
+ if (key.kty === "EC2") {
141
+ const raw = new Uint8Array(65);
142
+ raw[0] = 4;
143
+ raw.set(key.x, 1);
144
+ raw.set(key.y, 33);
145
+ return ok(await crypto.subtle.importKey("raw", raw, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]));
146
+ }
147
+ return ok(await crypto.subtle.importKey("raw", own(key.x), { name: "Ed25519" }, false, ["verify"]));
148
+ } catch (e) {
149
+ return err(`the public key cannot be used (${e instanceof Error ? e.message : String(e)})`);
150
+ }
151
+ }
152
+
153
+ /** An integer of a DER signature as exactly `size` unsigned big-endian bytes, or undefined where it does not fit or is negative. */
154
+ function fixed(content: Uint8Array, size: number): Uint8Array | undefined {
155
+ if (content.length === 0 || ((content[0] ?? 0) & 0x80) !== 0) return undefined;
156
+ let start = 0;
157
+ while (start < content.length - 1 && content[start] === 0) start++;
158
+ const magnitude = content.subarray(start);
159
+ if (magnitude.length > size) return undefined;
160
+ const out = new Uint8Array(size);
161
+ out.set(magnitude, size - magnitude.length);
162
+ return out;
163
+ }
164
+
165
+ /** An ECDSA signature as DER (`Ecdsa-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER }`) turned into raw `r || s` of `size` bytes each. */
166
+ export function ecdsaDerToRaw(der: Uint8Array, size = 32): Result<Uint8Array, string> {
167
+ const seq = readTlv(der);
168
+ if (seq.kind === "err" || seq.value.tag !== TAG.sequence || seq.value.raw.length !== der.length)
169
+ return err("the ECDSA signature is not a DER sequence");
170
+ const parts = children(seq.value.content);
171
+ if (parts.kind === "err" || parts.value.length !== 2) return err("the ECDSA signature is not two integers");
172
+ const [r, s] = parts.value;
173
+ if (r === undefined || s === undefined || r.tag !== TAG.integer || s.tag !== TAG.integer)
174
+ return err("the ECDSA signature is not two integers");
175
+ const rr = fixed(r.content, size);
176
+ const ss = fixed(s.content, size);
177
+ if (rr === undefined || ss === undefined) return err(`the ECDSA signature's integers do not fit ${size} bytes`);
178
+ const out = new Uint8Array(size * 2);
179
+ out.set(rr, 0);
180
+ out.set(ss, size);
181
+ return ok(out);
182
+ }
183
+
184
+ /** Whether `signature` is the key's signature of `data` (ES256: DER as WebAuthn gives it; EdDSA: 64 raw bytes); an unusable key or a malformed signature is an error. */
185
+ export async function verifyCose(key: CoseKey, signature: Uint8Array, data: Uint8Array): Promise<Result<boolean, string>> {
186
+ const k = await importCoseKey(key);
187
+ if (k.kind === "err") return k;
188
+ try {
189
+ if (key.kty === "EC2") {
190
+ const raw = ecdsaDerToRaw(signature);
191
+ if (raw.kind === "err") return raw;
192
+ return ok(await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, k.value, own(raw.value), own(data)));
193
+ }
194
+ if (signature.length !== 64) return err(`the Ed25519 signature is ${signature.length} bytes, not 64`);
195
+ return ok(await crypto.subtle.verify({ name: "Ed25519" }, k.value, own(signature), own(data)));
196
+ } catch (e) {
197
+ return err(`the signature cannot be checked (${e instanceof Error ? e.message : String(e)})`);
198
+ }
199
+ }