@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/dist/dsse.js ADDED
@@ -0,0 +1,243 @@
1
+ // Spec: 0001-crypto FR-006
2
+ /**
3
+ * in-toto Statements v1 and DSSE envelopes (commons 0001-crypto FR-006): a statement says that a predicate of some type holds
4
+ * of its subjects, each named and identified by its digests; DSSE signs a payload of a stated type, by the pre-authentication encoding
5
+ * (PAE) of the two, and carries it in a JSON envelope with its signatures. Signing and verifying use Web Crypto (`crypto.subtle`) on keys
6
+ * the caller has imported as `CryptoKey`s, so the module has no effect beyond the computation: Ed25519, ECDSA on P-256, P-384 and P-521
7
+ * (with SHA-256, SHA-384 and SHA-512, the signature in ASN.1 DER as sigstore and in-toto's own tools write it), and RSA-PSS and
8
+ * RSASSA-PKCS1-v1_5 with the key's hash. Verification returns the payload, or an error that says why it was refused: an envelope that is
9
+ * malformed, a payload type not the one expected, a key not usable, or too few valid signatures.
10
+ *
11
+ * Taken from Stolos's `src/archon/export/intoto.ts`, which built a statement and an envelope for a signature callback but never verified
12
+ * one. What changed: the statement is generic in its predicate; the subject's digest is any map of algorithms; signing takes keys rather
13
+ * than a callback; verification, the envelope's decoder and the ECDSA signature form are new. Stolos's evidence bundle predicate (its
14
+ * predicate type, the manifest's summary and the subject list of a bundle's items) is Stolos's own domain and stays there.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { pae, signStatement, statement, subject, verifyStatement } from "./dsse.ts";
19
+ * import { unknownValue } from "@intellectual-frontiers/core";
20
+ * new TextDecoder().decode(pae("http://example.com/HelloWorld", new TextEncoder().encode("hello world")));
21
+ * // "DSSEv1 29 http://example.com/HelloWorld 11 hello world"
22
+ * const keys = await crypto.subtle.generateKey({ name: "Ed25519" }, false, ["sign", "verify"]);
23
+ * const s = statement([await subject("a.txt", new TextEncoder().encode("a"))], "https://example.com/Note/v1", { note: "hi" });
24
+ * const signed = await signStatement(s, [{ key: keys.privateKey, keyid: "me" }]);
25
+ * if (signed.kind === "ok") await verifyStatement(signed.value, [{ key: keys.publicKey, keyid: "me" }], unknownValue); // { kind: "ok", ... }
26
+ * ```
27
+ *
28
+ * @module
29
+ */
30
+ import { absurd, array, describe, formatDecodeError, json, object, record, string, unknownValue, err, ok, } from "@intellectual-frontiers/core";
31
+ import { fromBase64, toBase64 } from "@intellectual-frontiers/formats/base64";
32
+ import { children, integer, readTlv, sequence, TAG } from "@intellectual-frontiers/formats/der";
33
+ import { sha256 } from "./sha256.js";
34
+ /** The `_type` of an in-toto Statement v1. */
35
+ export const STATEMENT_TYPE = "https://in-toto.io/Statement/v1";
36
+ /** The DSSE payload type of an in-toto statement. */
37
+ export const INTOTO_PAYLOAD_TYPE = "application/vnd.in-toto+json";
38
+ const utf8 = new TextEncoder();
39
+ /** A subject: the name, and the SHA-256 of the bytes; `more` adds a URI, a media type or annotations. */
40
+ export async function subject(name, bytes, more = {}) {
41
+ return { name, digest: { sha256: await sha256(bytes) }, ...more };
42
+ }
43
+ /** A statement of the predicate about the subjects. */
44
+ export function statement(subjects, predicateType, predicate) {
45
+ return { _type: STATEMENT_TYPE, subject: subjects, predicateType, predicate };
46
+ }
47
+ const lowerHex = (input, path = "$") => typeof input === "string" && /^(?:[0-9a-f]{2})+$/.test(input)
48
+ ? ok(input)
49
+ : err({ kind: "decode", path, expected: "lower-case hexadecimal", found: describe(input) });
50
+ const statementType = (input, path = "$") => input === STATEMENT_TYPE ? ok(STATEMENT_TYPE) : err({ kind: "decode", path, expected: STATEMENT_TYPE, found: describe(input) });
51
+ /** The decoder of a ResourceDescriptor with a name and digests. */
52
+ export const resourceDescriptorDecoder = object({ name: string, digest: record(lowerHex) }, { uri: string, mediaType: string, annotations: record(unknownValue) });
53
+ /** The decoder of an in-toto Statement v1 whose predicate `predicate` decodes. */
54
+ export function statementDecoder(predicate) {
55
+ return object({ _type: statementType, subject: array(resourceDescriptorDecoder), predicateType: string, predicate });
56
+ }
57
+ const base64Text = (input, path = "$") => typeof input === "string" && fromBase64(input).kind === "ok"
58
+ ? ok(input)
59
+ : err({ kind: "decode", path, expected: "standard base64", found: describe(input) });
60
+ /** The decoder of a DSSE envelope: its fields present, and the payload and signatures in base64. */
61
+ export const envelopeDecoder = object({
62
+ payload: base64Text,
63
+ payloadType: string,
64
+ signatures: array(object({ sig: base64Text }, { keyid: string })),
65
+ });
66
+ /** A DSSE envelope read from JSON text, or why it is not one. */
67
+ export function parseEnvelope(text) {
68
+ const r = json(text, envelopeDecoder);
69
+ return r.kind === "ok" ? r : err({ kind: "malformed", reason: formatDecodeError(r.error) });
70
+ }
71
+ /** DSSE's pre-authentication encoding: `DSSEv1 <len(type)> <type> <len(payload)> <payload>`, the lengths in bytes as ASCII decimal. */
72
+ export function pae(payloadType, payload) {
73
+ const type = utf8.encode(payloadType);
74
+ const head = utf8.encode(`DSSEv1 ${type.length} ${payloadType} ${payload.length} `);
75
+ const out = new Uint8Array(head.length + payload.length);
76
+ out.set(head);
77
+ out.set(payload, head.length);
78
+ return out;
79
+ }
80
+ const HASHES = ["SHA-256", "SHA-384", "SHA-512"];
81
+ const CURVES = ["P-256", "P-384", "P-521"];
82
+ function hashOf(algorithm) {
83
+ const hash = "hash" in algorithm ? algorithm.hash : undefined;
84
+ const name = typeof hash === "object" && hash !== null && "name" in hash ? hash.name : undefined;
85
+ return HASHES.find((h) => h === name);
86
+ }
87
+ /** The signature algorithm of a key, or the reason it is not one this module uses. */
88
+ export function signatureAlgorithm(key) {
89
+ const a = key.algorithm;
90
+ switch (a.name) {
91
+ case "Ed25519":
92
+ return ok({ kind: "ed25519" });
93
+ case "ECDSA": {
94
+ const named = "namedCurve" in a ? a.namedCurve : undefined;
95
+ const curve = CURVES.find((c) => c === named);
96
+ return curve === undefined ? err(`the curve ${String(named)} is not one of ${CURVES.join(", ")}`) : ok({ kind: "ecdsa", curve });
97
+ }
98
+ case "RSA-PSS":
99
+ case "RSASSA-PKCS1-v1_5": {
100
+ const hash = hashOf(a);
101
+ if (hash === undefined)
102
+ return err(`the key's hash is not one of ${HASHES.join(", ")}`);
103
+ return ok(a.name === "RSA-PSS" ? { kind: "rsa-pss", hash } : { kind: "rsassa-pkcs1-v1_5", hash });
104
+ }
105
+ default:
106
+ return err(`${a.name} is not a signature algorithm DSSE is used with here`);
107
+ }
108
+ }
109
+ const CURVE_BYTES = { "P-256": 32, "P-384": 48, "P-521": 66 };
110
+ const CURVE_HASH = { "P-256": "SHA-256", "P-384": "SHA-384", "P-521": "SHA-512" };
111
+ const HASH_BYTES = { "SHA-256": 32, "SHA-384": 48, "SHA-512": 64 };
112
+ function webCryptoParams(a) {
113
+ switch (a.kind) {
114
+ case "ed25519":
115
+ return { name: "Ed25519" };
116
+ case "ecdsa":
117
+ return { name: "ECDSA", hash: CURVE_HASH[a.curve] };
118
+ case "rsa-pss":
119
+ return { name: "RSA-PSS", saltLength: HASH_BYTES[a.hash] };
120
+ case "rsassa-pkcs1-v1_5":
121
+ return { name: "RSASSA-PKCS1-v1_5" };
122
+ default:
123
+ return absurd(a);
124
+ }
125
+ }
126
+ /** Web Crypto's ECDSA signature (r and s, each `n` bytes) as an ASN.1 DER SEQUENCE of two INTEGERs. */
127
+ function ecdsaToDer(raw, n) {
128
+ return sequence(integer(raw.subarray(0, n)), integer(raw.subarray(n, 2 * n)));
129
+ }
130
+ /** An ASN.1 DER ECDSA signature as Web Crypto's r and s of `n` bytes each, or undefined where it is not one. */
131
+ function ecdsaFromDer(der, n) {
132
+ const t = readTlv(der);
133
+ if (t.kind === "err" || t.value.tag !== TAG.sequence || t.value.raw.length !== der.length)
134
+ return undefined;
135
+ const parts = children(t.value.content);
136
+ if (parts.kind === "err" || parts.value.length !== 2)
137
+ return undefined;
138
+ const out = new Uint8Array(2 * n);
139
+ for (const [i, part] of parts.value.entries()) {
140
+ if (part.tag !== TAG.integer || ((part.content[0] ?? 0x80) & 0x80) !== 0)
141
+ return undefined;
142
+ const magnitude = part.content[0] === 0 ? part.content.subarray(1) : part.content;
143
+ if (magnitude.length > n)
144
+ return undefined;
145
+ out.set(magnitude, (i + 1) * n - magnitude.length);
146
+ }
147
+ return out;
148
+ }
149
+ /** The payload of the type signed by every key given (private keys), in an envelope; or the first key that cannot sign. */
150
+ export async function signEnvelope(payloadType, payload, keys) {
151
+ const message = pae(payloadType, payload);
152
+ const signatures = [];
153
+ for (const [index, k] of keys.entries()) {
154
+ const a = signatureAlgorithm(k.key);
155
+ if (a.kind === "err")
156
+ return err({ kind: "key", index, reason: a.error });
157
+ let raw;
158
+ try {
159
+ raw = new Uint8Array(await crypto.subtle.sign(webCryptoParams(a.value), k.key, message));
160
+ }
161
+ catch (e) {
162
+ return err({ kind: "key", index, reason: e instanceof Error ? e.message : String(e) });
163
+ }
164
+ const sig = a.value.kind === "ecdsa" ? ecdsaToDer(raw, CURVE_BYTES[a.value.curve]) : raw;
165
+ signatures.push(k.keyid === undefined ? { sig: toBase64(sig) } : { keyid: k.keyid, sig: toBase64(sig) });
166
+ }
167
+ return ok({ payload: toBase64(payload), payloadType, signatures });
168
+ }
169
+ /**
170
+ * The payload of an envelope whose type is `payloadType` and which at least `threshold` of the keys given (public keys, 1 by default)
171
+ * each verify a signature of. A signature that names a key id is tried only with the keys of that id or of none.
172
+ */
173
+ export async function verifyEnvelope(envelope, payloadType, keys, threshold = 1) {
174
+ if (envelope.payloadType !== payloadType)
175
+ return err({ kind: "payload-type", expected: payloadType, found: envelope.payloadType });
176
+ const payload = fromBase64(envelope.payload);
177
+ if (payload.kind === "err")
178
+ return err({ kind: "malformed", reason: `the payload: ${payload.error}` });
179
+ const signatures = [];
180
+ for (const [i, s] of envelope.signatures.entries()) {
181
+ const sig = fromBase64(s.sig);
182
+ if (sig.kind === "err")
183
+ return err({ kind: "malformed", reason: `signature ${i}: ${sig.error}` });
184
+ signatures.push(sig.value);
185
+ }
186
+ const algorithms = [];
187
+ for (const [index, k] of keys.entries()) {
188
+ const a = signatureAlgorithm(k.key);
189
+ if (a.kind === "err")
190
+ return err({ kind: "key", index, reason: a.error });
191
+ algorithms.push(a.value);
192
+ }
193
+ const message = pae(envelope.payloadType, payload.value);
194
+ const verifiedBy = [];
195
+ for (const [index, k] of keys.entries()) {
196
+ const a = algorithms[index];
197
+ if (a === undefined)
198
+ continue;
199
+ for (const [i, s] of envelope.signatures.entries()) {
200
+ const bytes = signatures[i];
201
+ if (bytes === undefined || (s.keyid !== undefined && k.keyid !== undefined && s.keyid !== k.keyid))
202
+ continue;
203
+ const sig = a.kind === "ecdsa" ? ecdsaFromDer(bytes, CURVE_BYTES[a.curve]) : new Uint8Array(bytes);
204
+ if (sig === undefined)
205
+ continue;
206
+ let valid;
207
+ try {
208
+ valid = await crypto.subtle.verify(webCryptoParams(a), k.key, sig, message);
209
+ }
210
+ catch (e) {
211
+ return err({ kind: "key", index, reason: e instanceof Error ? e.message : String(e) });
212
+ }
213
+ if (valid) {
214
+ verifiedBy.push(k);
215
+ break;
216
+ }
217
+ }
218
+ }
219
+ const needed = Math.max(1, threshold);
220
+ if (verifiedBy.length < needed) {
221
+ return err({ kind: "no-valid-signature", signatures: envelope.signatures.length, verified: verifiedBy.length, threshold: needed });
222
+ }
223
+ return ok({ payloadType: envelope.payloadType, payload: payload.value, keys: verifiedBy });
224
+ }
225
+ /** A statement as JSON, signed by every key given, in an envelope of type `application/vnd.in-toto+json`. */
226
+ export function signStatement(s, keys) {
227
+ return signEnvelope(INTOTO_PAYLOAD_TYPE, utf8.encode(JSON.stringify(s)), keys);
228
+ }
229
+ /** The statement an envelope of type `application/vnd.in-toto+json` carries, verified as `verifyEnvelope` does, its predicate decoded by `predicate`. */
230
+ export async function verifyStatement(envelope, keys, predicate, threshold = 1) {
231
+ const v = await verifyEnvelope(envelope, INTOTO_PAYLOAD_TYPE, keys, threshold);
232
+ if (v.kind === "err")
233
+ return v;
234
+ let text;
235
+ try {
236
+ text = new TextDecoder("utf-8", { fatal: true }).decode(v.value.payload);
237
+ }
238
+ catch {
239
+ return err({ kind: "statement", error: { kind: "decode", path: "$", expected: "UTF-8 text", found: "bytes that are not" } });
240
+ }
241
+ const s = json(text, statementDecoder(predicate));
242
+ return s.kind === "ok" ? s : err({ kind: "statement", error: s.error });
243
+ }
package/dist/md5.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * An MD5 digest computed a piece at a time: `update` with each piece of the bytes in order (text is taken as UTF-8), then `digest` or
3
+ * `hex`. After the digest is taken, the object takes no more bytes. Not for security (see the module's documentation).
4
+ */
5
+ export declare class Md5 {
6
+ #private;
7
+ /** Takes the next piece of the bytes; throws where the digest was already taken. */
8
+ update(data: Uint8Array | string): this;
9
+ /** The 16 bytes of the digest of every piece taken; the same each time it is asked. */
10
+ digest(): Uint8Array;
11
+ /** The digest as 32 lower-case hexadecimal digits. */
12
+ hex(): string;
13
+ }
14
+ /** The 16 bytes of the MD5 of bytes, or of text as UTF-8. Not for security. */
15
+ export declare function md5(data: Uint8Array | string): Uint8Array;
16
+ /** The MD5 of bytes, or of text as UTF-8, as 32 lower-case hexadecimal digits (`md5("")` is `d41d8cd98f00b204e9800998ecf8427e`). */
17
+ export declare function md5Hex(data: Uint8Array | string): string;
18
+ /** The 16 bytes of the MD5 of every byte of a stream, read a chunk at a time, so the whole is never held. Not for security. */
19
+ export declare function md5Stream(stream: ReadableStream<Uint8Array>): Promise<Uint8Array>;
package/dist/md5.js ADDED
@@ -0,0 +1,146 @@
1
+ // Spec: 0001-crypto FR-002
2
+ /**
3
+ * MD5 (RFC 1321), which Web Crypto does not give, for the protocols that still ask for it: S3's `Content-MD5` header (the digest in
4
+ * base64), the ETag of an S3 object put in one part, and old checksum files (commons 0001-crypto FR-002).
5
+ *
6
+ * MD5 is NOT for security: collisions are made in seconds, so it MUST NOT check that bytes are the ones expected against anyone who
7
+ * could choose them, sign, or hash a password. Use SHA-256 (`./sha256.ts`) for that; MD5 here only answers a protocol that names it.
8
+ *
9
+ * The digest is given whole (`md5`, `md5Hex`) or a piece at a time (`Md5`, and `md5Stream` for a `ReadableStream`), so a file larger
10
+ * than memory is digested as it is read.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { Md5, md5Hex } from "./md5.ts";
15
+ * md5Hex("abc"); // "900150983cd24fb0d6963f7d28e17f72"
16
+ * new Md5().update("a").update("bc").hex(); // the same
17
+ * ```
18
+ *
19
+ * @module
20
+ */
21
+ import { toHex } from "@intellectual-frontiers/formats/hex";
22
+ /** The per-round left rotations of RFC 1321 §3.4. */
23
+ const SHIFTS = [
24
+ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11,
25
+ 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
26
+ ];
27
+ /** T[i] = floor(2^32 * |sin(i + 1)|), the table of RFC 1321 §3.4. */
28
+ const T = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000) >>> 0);
29
+ const bytesOf = (data) => (typeof data === "string" ? new TextEncoder().encode(data) : data);
30
+ /**
31
+ * An MD5 digest computed a piece at a time: `update` with each piece of the bytes in order (text is taken as UTF-8), then `digest` or
32
+ * `hex`. After the digest is taken, the object takes no more bytes. Not for security (see the module's documentation).
33
+ */
34
+ export class Md5 {
35
+ #state = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]);
36
+ #block = new Uint8Array(64);
37
+ #words = new Uint32Array(16);
38
+ #filled = 0;
39
+ #length = 0;
40
+ #done;
41
+ /** Takes the next piece of the bytes; throws where the digest was already taken. */
42
+ update(data) {
43
+ if (this.#done !== undefined)
44
+ throw new Error("the MD5 digest was already taken; start a new Md5");
45
+ const bytes = bytesOf(data);
46
+ this.#length += bytes.length;
47
+ let at = 0;
48
+ while (at < bytes.length) {
49
+ const n = Math.min(64 - this.#filled, bytes.length - at);
50
+ this.#block.set(bytes.subarray(at, at + n), this.#filled);
51
+ this.#filled += n;
52
+ at += n;
53
+ if (this.#filled === 64) {
54
+ this.#compress();
55
+ this.#filled = 0;
56
+ }
57
+ }
58
+ return this;
59
+ }
60
+ /** The 16 bytes of the digest of every piece taken; the same each time it is asked. */
61
+ digest() {
62
+ if (this.#done !== undefined)
63
+ return this.#done.slice();
64
+ const bits = this.#length * 8;
65
+ const pad = new Uint8Array((this.#filled < 56 ? 56 : 120) - this.#filled + 8);
66
+ pad[0] = 0x80;
67
+ const view = new DataView(pad.buffer);
68
+ view.setUint32(pad.length - 8, bits >>> 0, true);
69
+ view.setUint32(pad.length - 4, Math.floor(bits / 0x100000000) >>> 0, true);
70
+ this.update(pad);
71
+ const out = new Uint8Array(16);
72
+ const outView = new DataView(out.buffer);
73
+ this.#state.forEach((w, i) => outView.setUint32(i * 4, w, true));
74
+ this.#done = out;
75
+ return out.slice();
76
+ }
77
+ /** The digest as 32 lower-case hexadecimal digits. */
78
+ hex() {
79
+ return toHex(this.digest());
80
+ }
81
+ #compress() {
82
+ const x = this.#words;
83
+ const b64 = this.#block;
84
+ for (let i = 0; i < 16; i++)
85
+ x[i] = ((b64[i * 4] ?? 0) | ((b64[i * 4 + 1] ?? 0) << 8) | ((b64[i * 4 + 2] ?? 0) << 16) | ((b64[i * 4 + 3] ?? 0) << 24)) >>> 0;
86
+ const s = this.#state;
87
+ let a = s[0] ?? 0;
88
+ let b = s[1] ?? 0;
89
+ let c = s[2] ?? 0;
90
+ let d = s[3] ?? 0;
91
+ for (let i = 0; i < 64; i++) {
92
+ let f;
93
+ let g;
94
+ if (i < 16) {
95
+ f = (b & c) | (~b & d);
96
+ g = i;
97
+ }
98
+ else if (i < 32) {
99
+ f = (d & b) | (~d & c);
100
+ g = (5 * i + 1) % 16;
101
+ }
102
+ else if (i < 48) {
103
+ f = b ^ c ^ d;
104
+ g = (3 * i + 5) % 16;
105
+ }
106
+ else {
107
+ f = c ^ (b | ~d);
108
+ g = (7 * i) % 16;
109
+ }
110
+ const sum = (a + f + (T[i] ?? 0) + (x[g] ?? 0)) >>> 0;
111
+ const r = SHIFTS[i] ?? 0;
112
+ a = d;
113
+ d = c;
114
+ c = b;
115
+ b = (b + ((sum << r) | (sum >>> (32 - r)))) >>> 0;
116
+ }
117
+ s[0] = ((s[0] ?? 0) + a) >>> 0;
118
+ s[1] = ((s[1] ?? 0) + b) >>> 0;
119
+ s[2] = ((s[2] ?? 0) + c) >>> 0;
120
+ s[3] = ((s[3] ?? 0) + d) >>> 0;
121
+ }
122
+ }
123
+ /** The 16 bytes of the MD5 of bytes, or of text as UTF-8. Not for security. */
124
+ export function md5(data) {
125
+ return new Md5().update(data).digest();
126
+ }
127
+ /** The MD5 of bytes, or of text as UTF-8, as 32 lower-case hexadecimal digits (`md5("")` is `d41d8cd98f00b204e9800998ecf8427e`). */
128
+ export function md5Hex(data) {
129
+ return toHex(md5(data));
130
+ }
131
+ /** The 16 bytes of the MD5 of every byte of a stream, read a chunk at a time, so the whole is never held. Not for security. */
132
+ export async function md5Stream(stream) {
133
+ const h = new Md5();
134
+ const reader = stream.getReader();
135
+ try {
136
+ for (;;) {
137
+ const { done, value } = await reader.read();
138
+ if (done)
139
+ return h.digest();
140
+ h.update(value);
141
+ }
142
+ }
143
+ finally {
144
+ reader.releaseLock();
145
+ }
146
+ }
package/dist/mod.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Crypto, the digests, signatures and envelopes of Intellectual Frontiers Commons, in pure code on Web Crypto with no outside package (its specification 0001-crypto): SHA-256 as a branded `Sha256`, MD5
3
+ * for the protocols that still ask for it (as `md5`), SHA-512 crypt, UUIDs (as `uuid`), AWS Signature Version 4 (as `sigv4`), CMS encrypted content (as `cms`), in-toto statements in DSSE envelopes
4
+ * (as `dsse`), COSE keys (as `cose`) and WebAuthn for a relying party (as `webauthn`). It depends on `core` and `formats`, names no host global and runs wherever ECMAScript and Web Crypto do: Bun, Node 26, a
5
+ * browser, a Worker.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { sha256 } from "@intellectual-frontiers/crypto";
10
+ * const sum = await sha256("abc");
11
+ * sum; // "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+ export * as cms from "./cms.js";
17
+ export * as cose from "./cose.js";
18
+ export { CRYPT_ROUNDS, cryptSalt, sha512Crypt, verifySha512Crypt } from "./crypt.js";
19
+ export * as dsse from "./dsse.js";
20
+ export * as md5 from "./md5.js";
21
+ export { parseSha256Sums, sameSha256, sha256, sha256Of } from "./sha256.js";
22
+ export type { Sha256 } from "./sha256.js";
23
+ export * as sigv4 from "./sigv4.js";
24
+ export * as uuid from "./uuid.js";
25
+ export * as webauthn from "./webauthn.js";
package/dist/mod.js ADDED
@@ -0,0 +1,25 @@
1
+ // Spec: 0001-crypto FR-009
2
+ /**
3
+ * Crypto, the digests, signatures and envelopes of Intellectual Frontiers Commons, in pure code on Web Crypto with no outside package (its specification 0001-crypto): SHA-256 as a branded `Sha256`, MD5
4
+ * for the protocols that still ask for it (as `md5`), SHA-512 crypt, UUIDs (as `uuid`), AWS Signature Version 4 (as `sigv4`), CMS encrypted content (as `cms`), in-toto statements in DSSE envelopes
5
+ * (as `dsse`), COSE keys (as `cose`) and WebAuthn for a relying party (as `webauthn`). It depends on `core` and `formats`, names no host global and runs wherever ECMAScript and Web Crypto do: Bun, Node 26, a
6
+ * browser, a Worker.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { sha256 } from "@intellectual-frontiers/crypto";
11
+ * const sum = await sha256("abc");
12
+ * sum; // "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
13
+ * ```
14
+ *
15
+ * @module
16
+ */
17
+ export * as cms from "./cms.js";
18
+ export * as cose from "./cose.js";
19
+ export { CRYPT_ROUNDS, cryptSalt, sha512Crypt, verifySha512Crypt } from "./crypt.js";
20
+ export * as dsse from "./dsse.js";
21
+ export * as md5 from "./md5.js";
22
+ export { parseSha256Sums, sameSha256, sha256, sha256Of } from "./sha256.js";
23
+ export * as sigv4 from "./sigv4.js";
24
+ export * as uuid from "./uuid.js";
25
+ export * as webauthn from "./webauthn.js";
@@ -0,0 +1,25 @@
1
+ /**
2
+ * SHA-256 through Web Crypto (`crypto.subtle`, in every runtime and browser), and a typed `Sha256`: 64 lower-case hexadecimal digits that
3
+ * the compiler keeps apart from any other string, so a checksum is never confused with a version or a path (commons 0005-typescript-runtime
4
+ * 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.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { sha256, sha256Of } from "./sha256.js";
9
+ * const sum = await sha256(new TextEncoder().encode("abc"));
10
+ * sum === sha256Of("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); // true
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ import type { Brand } from "@intellectual-frontiers/core";
16
+ /** 64 lower-case hexadecimal digits: a SHA-256 checksum. */
17
+ export type Sha256 = Brand<string, "Sha256">;
18
+ /** The text as a checksum where it is one (upper-case digits are lowered), else undefined. */
19
+ export declare function sha256Of(text: string): Sha256 | undefined;
20
+ /** The SHA-256 of bytes, or of text as UTF-8. */
21
+ export declare function sha256(data: Uint8Array | string): Promise<Sha256>;
22
+ /** Whether two checksums are the same, compared in constant time for their length. */
23
+ export declare function sameSha256(a: Sha256, b: Sha256): boolean;
24
+ /** 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. */
25
+ export declare function parseSha256Sums(text: string): ReadonlyMap<string, Sha256>;
package/dist/sha256.js ADDED
@@ -0,0 +1,34 @@
1
+ import { toHex } from "@intellectual-frontiers/formats/hex";
2
+ const SHA256 = /^[0-9a-f]{64}$/;
3
+ /** The text as a checksum where it is one (upper-case digits are lowered), else undefined. */
4
+ export function sha256Of(text) {
5
+ const t = text.trim().toLowerCase();
6
+ return SHA256.test(t) ? t : undefined;
7
+ }
8
+ /** The SHA-256 of bytes, or of text as UTF-8. */
9
+ export async function sha256(data) {
10
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
11
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
12
+ return toHex(new Uint8Array(digest));
13
+ }
14
+ /** Whether two checksums are the same, compared in constant time for their length. */
15
+ export function sameSha256(a, b) {
16
+ if (a.length !== b.length)
17
+ return false;
18
+ let d = 0;
19
+ for (let i = 0; i < a.length; i++)
20
+ d |= a.charCodeAt(i) ^ b.charCodeAt(i);
21
+ return d === 0;
22
+ }
23
+ /** 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. */
24
+ export function parseSha256Sums(text) {
25
+ const out = new Map();
26
+ for (const line of text.split(/\r?\n/)) {
27
+ const m = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line.trim());
28
+ const sum = m?.[1] === undefined ? undefined : sha256Of(m[1]);
29
+ const name = m?.[2];
30
+ if (sum !== undefined && name !== undefined)
31
+ out.set(name, sum);
32
+ }
33
+ return out;
34
+ }
@@ -0,0 +1,67 @@
1
+ /** An access key: its id, its secret, and a session token where the key is temporary. */
2
+ export type AwsCredentials = {
3
+ readonly accessKeyId: string;
4
+ readonly secretAccessKey: string;
5
+ readonly sessionToken?: string;
6
+ };
7
+ /** How to sign. */
8
+ export type SigV4Options = {
9
+ readonly credentials: AwsCredentials;
10
+ /** The region of the credential scope (`us-east-1`). */
11
+ readonly region: string;
12
+ /** The service of the credential scope (`iam`, `sts`, `s3`, `ec2`). */
13
+ readonly service: string;
14
+ /** The time of signing, which becomes `x-amz-date` (the kernel reads no clock). */
15
+ readonly date: Date;
16
+ /** Sign `UNSIGNED-PAYLOAD` instead of the body's SHA-256 (S3 allows it). */
17
+ readonly unsignedPayload?: boolean;
18
+ /** Also send the payload's hash as `x-amz-content-sha256` (always for S3, which requires it). */
19
+ readonly contentSha256Header?: boolean;
20
+ };
21
+ /** A request to sign, by its parts. */
22
+ export type SigV4Request = {
23
+ readonly method: string;
24
+ /** The whole URL, as text (its path is signed as written there, before any normalization a URL parser would make). */
25
+ readonly url: string;
26
+ /** The headers to send; each is signed, but for those a transport may change (`user-agent`, `traceparent`, ...). */
27
+ readonly headers: Readonly<Record<string, string>>;
28
+ readonly body?: string | Uint8Array;
29
+ };
30
+ /** A signed request: the headers to send and, for whoever must check them, what was signed. */
31
+ export type Signed = {
32
+ /**
33
+ * The request's headers with `x-amz-date`, `x-amz-security-token` and `x-amz-content-sha256` where they apply, and `authorization`;
34
+ * never `host`, which the transport sets from the URL.
35
+ */
36
+ readonly headers: Readonly<Record<string, string>>;
37
+ readonly canonicalRequest: string;
38
+ readonly stringToSign: string;
39
+ /** The signature, 64 lower-case hexadecimal digits. */
40
+ readonly signature: string;
41
+ /** The value of the `Authorization` header. */
42
+ readonly authorization: string;
43
+ };
44
+ /** The algorithm's name, as the string to sign and the `Authorization` header begin. */
45
+ export declare const ALGORITHM = "AWS4-HMAC-SHA256";
46
+ /** What is signed in place of a body's hash where the payload is not signed. */
47
+ export declare const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
48
+ /** RFC 3986 percent-encoding, as SigV4 wants it: everything but `A-Z a-z 0-9 - _ . ~` encoded, in upper-case hexadecimal. */
49
+ export declare function uriEncode(text: string): string;
50
+ /** `20150830T123600Z`: the time as `x-amz-date` writes it. */
51
+ export declare function amzDate(date: Date): string;
52
+ /**
53
+ * The path as SigV4 signs it. For a service other than S3: `.` and `..` segments resolved and empty segments dropped, each segment
54
+ * decoded and encoded twice (RFC 3986). For S3: the path as given, each segment decoded and encoded once.
55
+ */
56
+ export declare function canonicalPath(path: string, service: string): string;
57
+ /** The query as SigV4 signs it: each name and value decoded and encoded by RFC 3986, a name without `=` given an empty value, sorted. */
58
+ export declare function canonicalQuery(query: string): string;
59
+ /** The signing key: HMAC-SHA256 of `AWS4` and the secret through the day (`YYYYMMDD`), the region, the service and `aws4_request`. */
60
+ export declare function signingKey(secretAccessKey: string, day: string, region: string, service: string): Promise<Uint8Array>;
61
+ /** A request signed by Signature Version 4 (FR-068): the headers to send, and the canonical request, string to sign and signature. */
62
+ export declare function sign(request: SigV4Request, options: SigV4Options): Promise<Signed>;
63
+ /**
64
+ * 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
65
+ * 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.
66
+ */
67
+ export declare function signRequest(request: Request, options: SigV4Options): Promise<Request>;