@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Intellectual Frontiers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @intellectual-frontiers/crypto
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Crypto: SHA-256, MD5, SHA-512 crypt, UUIDs, AWS Signature Version 4, CMS, DSSE, COSE and WebAuthn, in pure code on Web Crypto, with core and formats as its dependencies.
4
+
5
+ ```sh
6
+ bun add @intellectual-frontiers/crypto # or: npm install @intellectual-frontiers/crypto
7
+ ```
8
+
9
+ Sources and specifications: https://github.com/intellectual-frontiers/.github/tree/main/commons/crypto
package/dist/cms.d.ts ADDED
@@ -0,0 +1,106 @@
1
+ import { type Tlv } from "@intellectual-frontiers/formats/der";
2
+ import { type Result } from "@intellectual-frontiers/core";
3
+ /** The object identifiers used. */
4
+ export declare const OID: {
5
+ readonly data: "1.2.840.113549.1.7.1";
6
+ readonly authEnvelopedData: "1.2.840.113549.1.9.16.1.23";
7
+ readonly aes256gcm: "2.16.840.1.101.3.4.1.46";
8
+ readonly rsaEncryption: "1.2.840.113549.1.1.1";
9
+ readonly rsaesOaep: "1.2.840.113549.1.1.7";
10
+ readonly mgf1: "1.2.840.113549.1.1.8";
11
+ readonly sha256: "2.16.840.1.101.3.4.2.1";
12
+ readonly commonName: "2.5.4.3";
13
+ readonly emailAddress: "1.2.840.113549.1.9.1";
14
+ readonly subjectAltName: "2.5.29.17";
15
+ readonly keyUsage: "2.5.29.15";
16
+ };
17
+ /** Why CMS or a certificate could not be read, written or opened. */
18
+ export type CmsError = {
19
+ readonly kind: "pem";
20
+ readonly message: string;
21
+ } | {
22
+ readonly kind: "certificate";
23
+ readonly message: string;
24
+ } | {
25
+ readonly kind: "unsupported";
26
+ readonly message: string;
27
+ } | {
28
+ readonly kind: "structure";
29
+ readonly message: string;
30
+ } | {
31
+ readonly kind: "no-recipient";
32
+ readonly message: string;
33
+ } | {
34
+ readonly kind: "decrypt";
35
+ readonly message: string;
36
+ };
37
+ /** A CMS error as one sentence. */
38
+ export declare function formatCmsError(e: CmsError): string;
39
+ /** 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. */
40
+ export declare function readPem(text: string, label: string): Result<readonly Uint8Array[], CmsError>;
41
+ /** DER as a PEM block of a label, base64 in 64-column lines. */
42
+ export declare function toPem(der: Uint8Array, label: string): string;
43
+ /** What encryption and a person need from a recipient's X.509 certificate. */
44
+ export type Certificate = {
45
+ /** The issuer's Name, its DER exactly as in the certificate. */
46
+ readonly issuer: Uint8Array;
47
+ /** The serial number's INTEGER element, exactly as in the certificate. */
48
+ readonly serial: Uint8Array;
49
+ /** The serial number in hexadecimal. */
50
+ readonly serialHex: string;
51
+ /** The SubjectPublicKeyInfo, DER. */
52
+ readonly spki: Uint8Array;
53
+ /** The public key's algorithm, as an OID. */
54
+ readonly keyAlgorithm: string;
55
+ /** The subject's common name, where it has one. */
56
+ readonly commonName: string | undefined;
57
+ /** The addresses it names (subjectAltName rfc822Name and the subject's emailAddress), in lower case. */
58
+ readonly emails: readonly string[];
59
+ /** When it starts being valid, where its time can be read. */
60
+ readonly notBefore: Date | undefined;
61
+ /** When it stops being valid, where its time can be read. */
62
+ readonly notAfter: Date | undefined;
63
+ /** Whether it may encrypt keys: true where it has no keyUsage extension, else its keyEncipherment bit. */
64
+ readonly keyEncipherment: boolean;
65
+ };
66
+ /** An X.509 certificate read for what encryption needs, or why it is not one this reader takes. */
67
+ export declare function readCertificate(der: Uint8Array): Result<Certificate, CmsError>;
68
+ /** Why a certificate cannot encrypt to an address now. */
69
+ export type CertificateProblem = {
70
+ readonly kind: "not-rsa";
71
+ readonly algorithm: string;
72
+ } | {
73
+ readonly kind: "not-yet-valid";
74
+ readonly from: Date;
75
+ } | {
76
+ readonly kind: "expired";
77
+ readonly on: Date;
78
+ } | {
79
+ readonly kind: "signing-only";
80
+ } | {
81
+ readonly kind: "other-address";
82
+ readonly names: readonly string[];
83
+ };
84
+ /** Why a certificate cannot be used to encrypt to `address` at `now`, or undefined where it can. */
85
+ export declare function certificateProblem(c: Certificate, address: string, now: Date): CertificateProblem | undefined;
86
+ /** RSAES-OAEP with SHA-256 and MGF1 with SHA-256, as an AlgorithmIdentifier (RFC 4055 §4.1). */
87
+ export declare function oaepSha256(): Uint8Array;
88
+ /** The fresh secrets of one message: a 32-byte AES-256 content key and a 12-byte GCM nonce. */
89
+ export type CmsKeys = {
90
+ readonly contentKey: Uint8Array;
91
+ readonly nonce: Uint8Array;
92
+ };
93
+ /** Fresh secrets from a source of random bytes, such as `(n) => crypto.getRandomValues(new Uint8Array(n))`. */
94
+ export declare function cmsKeys(random: (length: number) => Uint8Array): CmsKeys;
95
+ /**
96
+ * A CMS ContentInfo holding AuthEnvelopedData, as DER: `content` encrypted with AES-256-GCM, its key encrypted to every recipient with
97
+ * RSA-OAEP SHA-256. No recipient, a recipient whose key is not RSA, or keys of the wrong size are errors.
98
+ */
99
+ export declare function authEnveloped(content: Uint8Array, recipients: readonly Certificate[], keys: CmsKeys): Promise<Result<Uint8Array, CmsError>>;
100
+ /** Whether an AlgorithmIdentifier is RSAES-OAEP with SHA-256, MGF1 with SHA-256 and the default label, however its NULLs are written. */
101
+ export declare function isOaepSha256(t: Tlv): boolean;
102
+ /**
103
+ * The content of an AuthEnvelopedData, opened by the recipient whose certificate is `cert` with its RSA-OAEP SHA-256 private key; or why
104
+ * it cannot be: not this structure, no RecipientInfo for this certificate, or a key or tag that does not decrypt (the content was changed).
105
+ */
106
+ export declare function openAuthEnveloped(der: Uint8Array, cert: Certificate, privateKey: CryptoKey): Promise<Result<Uint8Array, CmsError>>;
package/dist/cms.js ADDED
@@ -0,0 +1,350 @@
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 { algorithm, children, derNull, explicit, implicit, integer, octetString, oid, readInteger, readOid, readTlv, sequence, setOf, TAG, } from "@intellectual-frontiers/formats/der";
27
+ import { err, ok } from "@intellectual-frontiers/core";
28
+ import { toHex } from "@intellectual-frontiers/formats/hex";
29
+ /** The object identifiers used. */
30
+ export const OID = {
31
+ data: "1.2.840.113549.1.7.1",
32
+ authEnvelopedData: "1.2.840.113549.1.9.16.1.23",
33
+ aes256gcm: "2.16.840.1.101.3.4.1.46",
34
+ rsaEncryption: "1.2.840.113549.1.1.1",
35
+ rsaesOaep: "1.2.840.113549.1.1.7",
36
+ mgf1: "1.2.840.113549.1.1.8",
37
+ sha256: "2.16.840.1.101.3.4.2.1",
38
+ commonName: "2.5.4.3",
39
+ emailAddress: "1.2.840.113549.1.9.1",
40
+ subjectAltName: "2.5.29.17",
41
+ keyUsage: "2.5.29.15",
42
+ };
43
+ /** A CMS error as one sentence. */
44
+ export function formatCmsError(e) {
45
+ return `${e.kind}: ${e.message}`;
46
+ }
47
+ const fail = (kind, message) => err({ kind, message });
48
+ /** 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. */
49
+ export function readPem(text, label) {
50
+ const out = [];
51
+ const re = new RegExp(`-----BEGIN ${label}-----([\\s\\S]*?)-----END ${label}-----`, "g");
52
+ for (const m of text.matchAll(re)) {
53
+ const der = fromBase64(m[1] ?? "");
54
+ if (der.kind === "err")
55
+ return fail("pem", `a ${label} block that is not base64`);
56
+ out.push(der.value);
57
+ }
58
+ return out.length === 0 ? fail("pem", `no -----BEGIN ${label}----- block`) : ok(out);
59
+ }
60
+ /** DER as a PEM block of a label, base64 in 64-column lines. */
61
+ export function toPem(der, label) {
62
+ const lines = toBase64(der).match(/.{1,64}/g) ?? [];
63
+ return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`;
64
+ }
65
+ const text = (t) => new TextDecoder().decode(t.content);
66
+ function readTime(t) {
67
+ const s = text(t);
68
+ const m = t.tag === TAG.utcTime
69
+ ? /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s)
70
+ : t.tag === TAG.generalizedTime
71
+ ? /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s)
72
+ : null;
73
+ if (m === null)
74
+ return undefined;
75
+ let y = Number(m[1]);
76
+ if (t.tag === TAG.utcTime)
77
+ y += y >= 50 ? 1900 : 2000;
78
+ return new Date(Date.UTC(y, Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])));
79
+ }
80
+ /** The children of an element, or a `structure` error naming what was being read. */
81
+ function kids(t, what) {
82
+ if (t === undefined)
83
+ return fail("structure", `no ${what}`);
84
+ const c = children(t.content);
85
+ return c.kind === "ok" ? c : fail("structure", `${what}: ${c.error.message} at byte ${c.error.at}`);
86
+ }
87
+ function oidOf(t) {
88
+ if (t === undefined || t.tag !== TAG.oid)
89
+ return undefined;
90
+ const r = readOid(t.content);
91
+ return r.kind === "ok" ? r.value : undefined;
92
+ }
93
+ /** The values of an attribute type in a Name (a SEQUENCE OF SET OF AttributeTypeAndValue). */
94
+ function nameValues(name, type) {
95
+ const out = [];
96
+ const rdns = kids(name, "a name");
97
+ if (rdns.kind === "err")
98
+ return out;
99
+ for (const rdn of rdns.value) {
100
+ const atvs = kids(rdn, "a relative name");
101
+ if (atvs.kind === "err")
102
+ continue;
103
+ for (const atv of atvs.value) {
104
+ const pair = kids(atv, "an attribute");
105
+ if (pair.kind === "err")
106
+ continue;
107
+ const [t, v] = pair.value;
108
+ if (v !== undefined && oidOf(t) === type)
109
+ out.push(text(v));
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+ /** An X.509 certificate read for what encryption needs, or why it is not one this reader takes. */
115
+ export function readCertificate(der) {
116
+ const cert = readTlv(der);
117
+ if (cert.kind === "err" || cert.value.tag !== TAG.sequence)
118
+ return fail("certificate", "not a DER certificate");
119
+ const top = kids(cert.value, "a certificate");
120
+ if (top.kind === "err")
121
+ return top;
122
+ const tbs = top.value[0];
123
+ if (tbs?.tag !== TAG.sequence)
124
+ return fail("certificate", "no TBSCertificate");
125
+ const f = kids(tbs, "the TBSCertificate");
126
+ if (f.kind === "err")
127
+ return f;
128
+ let i = f.value[0]?.tag === 0xa0 ? 1 : 0;
129
+ const serial = f.value[i++];
130
+ i++;
131
+ const issuer = f.value[i++];
132
+ const validity = f.value[i++];
133
+ const subject = f.value[i++];
134
+ const spki = f.value[i++];
135
+ if (serial?.tag !== TAG.integer || issuer === undefined || validity === undefined || subject === undefined || spki === undefined) {
136
+ return fail("certificate", "its fields are not where RFC 5280 puts them");
137
+ }
138
+ const alg = kids(spki, "the public key");
139
+ if (alg.kind === "err")
140
+ return alg;
141
+ const algId = kids(alg.value[0], "the key's algorithm");
142
+ if (algId.kind === "err")
143
+ return algId;
144
+ const keyAlgorithm = oidOf(algId.value[0]);
145
+ if (keyAlgorithm === undefined)
146
+ return fail("certificate", "no key algorithm");
147
+ const emails = [...nameValues(subject, OID.emailAddress)];
148
+ let keyEncipherment = true;
149
+ const ext = f.value.slice(i).find((x) => x.tag === 0xa3);
150
+ if (ext !== undefined) {
151
+ const list = kids(ext, "the extensions");
152
+ if (list.kind === "err")
153
+ return list;
154
+ const items = kids(list.value[0], "the extensions");
155
+ if (items.kind === "err")
156
+ return items;
157
+ for (const e of items.value) {
158
+ const parts = kids(e, "an extension");
159
+ if (parts.kind === "err")
160
+ return parts;
161
+ const id = oidOf(parts.value[0]);
162
+ const value = parts.value.at(-1);
163
+ if (value === undefined)
164
+ continue;
165
+ const inner = readTlv(value.content);
166
+ if (inner.kind === "err")
167
+ continue;
168
+ if (id === OID.subjectAltName) {
169
+ const names = kids(inner.value, "subjectAltName");
170
+ if (names.kind === "ok")
171
+ for (const gn of names.value)
172
+ if (gn.tag === 0x81)
173
+ emails.push(text(gn));
174
+ }
175
+ else if (id === OID.keyUsage) {
176
+ keyEncipherment = ((inner.value.content[1] ?? 0) & 0x20) !== 0;
177
+ }
178
+ }
179
+ }
180
+ const times = kids(validity, "the validity");
181
+ const [from, to] = times.kind === "ok" ? times.value : [];
182
+ return ok({
183
+ issuer: issuer.raw,
184
+ serial: serial.raw,
185
+ serialHex: toHex(serial.content),
186
+ spki: spki.raw,
187
+ keyAlgorithm,
188
+ commonName: nameValues(subject, OID.commonName)[0],
189
+ emails: [...new Set(emails.map((e) => e.toLowerCase()))],
190
+ notBefore: from === undefined ? undefined : readTime(from),
191
+ notAfter: to === undefined ? undefined : readTime(to),
192
+ keyEncipherment,
193
+ });
194
+ }
195
+ /** Why a certificate cannot be used to encrypt to `address` at `now`, or undefined where it can. */
196
+ export function certificateProblem(c, address, now) {
197
+ if (c.keyAlgorithm !== OID.rsaEncryption)
198
+ return { kind: "not-rsa", algorithm: c.keyAlgorithm };
199
+ if (c.notBefore !== undefined && c.notBefore.getTime() > now.getTime())
200
+ return { kind: "not-yet-valid", from: c.notBefore };
201
+ if (c.notAfter !== undefined && c.notAfter.getTime() < now.getTime())
202
+ return { kind: "expired", on: c.notAfter };
203
+ if (!c.keyEncipherment)
204
+ return { kind: "signing-only" };
205
+ if (c.emails.length > 0 && !c.emails.includes(address.toLowerCase()))
206
+ return { kind: "other-address", names: c.emails };
207
+ return undefined;
208
+ }
209
+ /** RSAES-OAEP with SHA-256 and MGF1 with SHA-256, as an AlgorithmIdentifier (RFC 4055 §4.1). */
210
+ export function oaepSha256() {
211
+ const sha256 = algorithm(OID.sha256, derNull());
212
+ return algorithm(OID.rsaesOaep, sequence(explicit(0, sha256), explicit(1, algorithm(OID.mgf1, sha256))));
213
+ }
214
+ /** Fresh secrets from a source of random bytes, such as `(n) => crypto.getRandomValues(new Uint8Array(n))`. */
215
+ export function cmsKeys(random) {
216
+ return { contentKey: random(32), nonce: random(12) };
217
+ }
218
+ /**
219
+ * A CMS ContentInfo holding AuthEnvelopedData, as DER: `content` encrypted with AES-256-GCM, its key encrypted to every recipient with
220
+ * RSA-OAEP SHA-256. No recipient, a recipient whose key is not RSA, or keys of the wrong size are errors.
221
+ */
222
+ export async function authEnveloped(content, recipients, keys) {
223
+ if (recipients.length === 0)
224
+ return fail("no-recipient", "no recipient to encrypt to");
225
+ if (keys.contentKey.length !== 32 || keys.nonce.length !== 12)
226
+ return fail("unsupported", "a content key of 32 bytes and a nonce of 12");
227
+ const notRsa = recipients.find((r) => r.keyAlgorithm !== OID.rsaEncryption);
228
+ if (notRsa !== undefined)
229
+ return fail("unsupported", `the key of certificate ${notRsa.serialHex} is not RSA (${notRsa.keyAlgorithm})`);
230
+ const aes = await crypto.subtle.importKey("raw", new Uint8Array(keys.contentKey), "AES-GCM", false, ["encrypt"]);
231
+ const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(keys.nonce), tagLength: 128 }, aes, new Uint8Array(content)));
232
+ const infos = [];
233
+ for (const r of recipients) {
234
+ const pub = await crypto.subtle.importKey("spki", new Uint8Array(r.spki), { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
235
+ const ek = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, pub, new Uint8Array(keys.contentKey)));
236
+ infos.push(sequence(integer(0), sequence(r.issuer, r.serial), oaepSha256(), octetString(ek)));
237
+ }
238
+ const eci = sequence(oid(OID.data), algorithm(OID.aes256gcm, sequence(octetString(keys.nonce), integer(16))), implicit(0, sealed.subarray(0, sealed.length - 16), false));
239
+ const aed = sequence(integer(0), setOf(...infos), eci, octetString(sealed.subarray(sealed.length - 16)));
240
+ return ok(sequence(oid(OID.authEnvelopedData), explicit(0, aed)));
241
+ }
242
+ /** Whether an AlgorithmIdentifier names SHA-256, its parameters NULL or absent (both are accepted, RFC 4055 §2.1, RFC 5754 §2). */
243
+ function isSha256(t) {
244
+ const parts = t === undefined ? undefined : children(t.content);
245
+ if (parts?.kind !== "ok" || oidOf(parts.value[0]) !== OID.sha256)
246
+ return false;
247
+ const params = parts.value[1];
248
+ return parts.value.length === 1 || (parts.value.length === 2 && params?.tag === TAG.null && params.content.length === 0);
249
+ }
250
+ /** Whether an AlgorithmIdentifier is RSAES-OAEP with SHA-256, MGF1 with SHA-256 and the default label, however its NULLs are written. */
251
+ export function isOaepSha256(t) {
252
+ const parts = children(t.content);
253
+ if (parts.kind === "err" || oidOf(parts.value[0]) !== OID.rsaesOaep)
254
+ return false;
255
+ const params = kids(parts.value[1], "the OAEP parameters");
256
+ if (params.kind === "err")
257
+ return false;
258
+ const hash = params.value.find((p) => p.tag === 0xa0);
259
+ const mgf = params.value.find((p) => p.tag === 0xa1);
260
+ if (params.value.some((p) => p.tag !== 0xa0 && p.tag !== 0xa1) || hash === undefined || mgf === undefined)
261
+ return false;
262
+ const h = readTlv(hash.content);
263
+ const m = readTlv(mgf.content);
264
+ if (h.kind === "err" || m.kind === "err" || !isSha256(h.value))
265
+ return false;
266
+ const mgfParts = children(m.value.content);
267
+ return mgfParts.kind === "ok" && oidOf(mgfParts.value[0]) === OID.mgf1 && isSha256(mgfParts.value[1]);
268
+ }
269
+ const same = (a, b) => a.length === b.length && a.every((x, k) => x === b[k]);
270
+ /**
271
+ * The content of an AuthEnvelopedData, opened by the recipient whose certificate is `cert` with its RSA-OAEP SHA-256 private key; or why
272
+ * it cannot be: not this structure, no RecipientInfo for this certificate, or a key or tag that does not decrypt (the content was changed).
273
+ */
274
+ export async function openAuthEnveloped(der, cert, privateKey) {
275
+ const info = readTlv(der);
276
+ if (info.kind === "err")
277
+ return fail("structure", "not DER");
278
+ const ci = kids(info.value, "the ContentInfo");
279
+ if (ci.kind === "err")
280
+ return ci;
281
+ if (oidOf(ci.value[0]) !== OID.authEnvelopedData)
282
+ return fail("structure", "not AuthEnvelopedData");
283
+ const wrapped = kids(ci.value[1], "the content");
284
+ if (wrapped.kind === "err")
285
+ return wrapped;
286
+ const aed = kids(wrapped.value[0], "the AuthEnvelopedData");
287
+ if (aed.kind === "err")
288
+ return aed;
289
+ const [version, recipientSet, eci, mac] = aed.value;
290
+ if (version?.tag !== TAG.integer || recipientSet?.tag !== TAG.set || eci === undefined || mac?.tag !== TAG.octetString) {
291
+ return fail("structure", "an AuthEnvelopedData without its four fields (attributes are not read)");
292
+ }
293
+ const v = readInteger(version.content);
294
+ if (v.kind === "err" || v.value !== 0n)
295
+ return fail("unsupported", "an AuthEnvelopedData of version 0");
296
+ const infos = kids(recipientSet, "the RecipientInfos");
297
+ if (infos.kind === "err")
298
+ return infos;
299
+ let encryptedKey;
300
+ for (const r of infos.value) {
301
+ const parts = kids(r, "a RecipientInfo");
302
+ if (parts.kind === "err")
303
+ return parts;
304
+ const [, rid, alg, ek] = parts.value;
305
+ const ids = kids(rid, "an IssuerAndSerialNumber");
306
+ if (ids.kind === "err" || ek === undefined || alg === undefined)
307
+ continue;
308
+ const [issuer, serial] = ids.value;
309
+ if (issuer !== undefined && serial !== undefined && same(issuer.raw, cert.issuer) && same(serial.raw, cert.serial)) {
310
+ if (!isOaepSha256(alg))
311
+ return fail("unsupported", "a key encrypted with RSA-OAEP, SHA-256 and MGF1 with SHA-256");
312
+ encryptedKey = ek.content;
313
+ }
314
+ }
315
+ if (encryptedKey === undefined)
316
+ return fail("no-recipient", `no RecipientInfo for certificate ${cert.serialHex}`);
317
+ const ec = kids(eci, "the EncryptedContentInfo");
318
+ if (ec.kind === "err")
319
+ return ec;
320
+ const [type, cipher, body] = ec.value;
321
+ const cipherParts = kids(cipher, "the content's algorithm");
322
+ if (cipherParts.kind === "err")
323
+ return cipherParts;
324
+ if (oidOf(type) !== OID.data || oidOf(cipherParts.value[0]) !== OID.aes256gcm || body?.tag !== 0x80) {
325
+ return fail("unsupported", "id-data content encrypted with AES-256-GCM");
326
+ }
327
+ const params = kids(cipherParts.value[1], "the GCM parameters");
328
+ if (params.kind === "err")
329
+ return params;
330
+ const nonce = params.value[0];
331
+ if (nonce?.tag !== TAG.octetString)
332
+ return fail("structure", "no GCM nonce");
333
+ let rawKey;
334
+ try {
335
+ rawKey = new Uint8Array(await crypto.subtle.decrypt({ name: "RSA-OAEP" }, privateKey, new Uint8Array(encryptedKey)));
336
+ }
337
+ catch {
338
+ return fail("decrypt", "the content key does not decrypt with this private key");
339
+ }
340
+ try {
341
+ const aes = await crypto.subtle.importKey("raw", new Uint8Array(rawKey), "AES-GCM", false, ["decrypt"]);
342
+ const sealed = new Uint8Array(body.content.length + mac.content.length);
343
+ sealed.set(body.content);
344
+ sealed.set(mac.content, body.content.length);
345
+ return ok(new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(nonce.content), tagLength: 128 }, aes, sealed)));
346
+ }
347
+ catch {
348
+ return fail("decrypt", "the content does not decrypt: it was changed, or the key is not its own");
349
+ }
350
+ }
package/dist/cose.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { type Result } from "@intellectual-frontiers/core";
2
+ /** COSE's identifier of ES256: ECDSA on P-256 with SHA-256. */
3
+ export declare const ES256 = -7;
4
+ /** COSE's identifier of EdDSA (here always Ed25519). */
5
+ export declare const EDDSA = -8;
6
+ /** The algorithms commons accepts, in order of preference. */
7
+ export declare const ALGORITHMS: readonly number[];
8
+ /** A public key read from a `COSE_Key`: an EC2 key on P-256 for ES256, or an OKP key on Ed25519 for EdDSA. */
9
+ export type CoseKey = {
10
+ readonly kty: "EC2";
11
+ readonly alg: typeof ES256;
12
+ readonly crv: "P-256";
13
+ readonly x: Uint8Array;
14
+ readonly y: Uint8Array;
15
+ } | {
16
+ readonly kty: "OKP";
17
+ readonly alg: typeof EDDSA;
18
+ readonly crv: "Ed25519";
19
+ readonly x: Uint8Array;
20
+ };
21
+ /** 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. */
22
+ export declare function parseCoseKey(bytes: Uint8Array): Result<CoseKey, string>;
23
+ /** The CBOR `COSE_Key` of a key (deterministic: its labels sorted). */
24
+ export declare function encodeCoseKey(key: CoseKey): Uint8Array;
25
+ /** 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. */
26
+ export declare function coseKeyFromJwk(jwk: JsonWebKey): Result<Uint8Array, string>;
27
+ /** The public JSON Web Key of a COSE key. */
28
+ export declare function jwkOfCoseKey(key: CoseKey): JsonWebKey;
29
+ /** The key imported into Web Crypto for verifying; a point not on its curve is refused. */
30
+ export declare function importCoseKey(key: CoseKey): Promise<Result<CryptoKey, string>>;
31
+ /** An ECDSA signature as DER (`Ecdsa-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER }`) turned into raw `r || s` of `size` bytes each. */
32
+ export declare function ecdsaDerToRaw(der: Uint8Array, size?: number): Result<Uint8Array, string>;
33
+ /** 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. */
34
+ export declare function verifyCose(key: CoseKey, signature: Uint8Array, data: Uint8Array): Promise<Result<boolean, string>>;