@openlfcp/crypto 0.0.0-stage → 0.1.0-rc.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @openlfcp/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
+ The cryptography of LFCP on audited primitives: SHA-256, Ed25519 signatures (strict verification), X25519, HKDF, ChaCha20-Poly1305 and HPKE for Key Packages, Resource DEKs and their commitments. It is the only package that uses `@noble/*` and `hpke` directly.
4
+
5
+ ```sh
6
+ npm install @openlfcp/crypto@next
7
+ ```
8
+
9
+ ESM only; Node.js 24 or later (browsers and Electron for every package except `@openlfcp/storage-node`).
10
+
11
+ ## Scope
12
+
13
+ Part of the OpenLFCP TypeScript SDK, which implements the OpenLFCP MVP 0.1
14
+ subset of [LFCP-WIRE-01](https://github.com/openlfcp/spec/blob/main/wire/LFCP-WIRE-01.md)
15
+ at `mvp-0.1-baseline.8`, not every deferred WIRE-01 feature. It does not
16
+ claim full LFCP-WIRE-01 conformance. This is a release candidate
17
+ (`0.1.0-rc.1`, npm dist-tag `next`): APIs may still change.
18
+
19
+ ## Links
20
+
21
+ - Specification: [openlfcp/spec](https://github.com/openlfcp/spec)
22
+ - Source and the other SDK packages: [openlfcp/sdk-ts](https://github.com/openlfcp/sdk-ts)
23
+ - Issues: [openlfcp/sdk-ts/issues](https://github.com/openlfcp/sdk-ts/issues)
24
+
25
+ ## License
26
+
27
+ Apache-2.0. See [LICENSE](LICENSE).
package/dist/aead.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { type ActorSequence } from "@openlfcp/core";
2
+ import { ActorDataKey, SnapshotKey } from "./epoch.js";
3
+ /** ciphertext || 16-byte tag of `plaintext` under the actor key, the sequence nonce and `aad` (§26). */
4
+ export declare function encryptDataUnit(key: ActorDataKey, seq: ActorSequence, aad: Uint8Array, plaintext: Uint8Array): Uint8Array;
5
+ /**
6
+ * The plaintext of `ciphertext` (ciphertext || tag). Any authentication
7
+ * failure (wrong key, sequence, AAD or tampered bytes) is
8
+ * AEAD_AUTHENTICATION_FAILED: client-local, no wire code (§26.3, ADR 0001 N3).
9
+ */
10
+ export declare function decryptDataUnit(key: ActorDataKey, seq: ActorSequence, aad: Uint8Array, ciphertext: Uint8Array): Uint8Array;
11
+ /**
12
+ * ciphertext || 16-byte tag of a Snapshot plaintext under the publisher's
13
+ * Snapshot key, the sequence nonce and `aad` (§29.1.4). The sequence must
14
+ * never be reused for one (resource, epoch, publisher) (§29.1.2).
15
+ */
16
+ export declare function encryptSnapshot(key: SnapshotKey, seq: bigint, aad: Uint8Array, plaintext: Uint8Array): Uint8Array;
17
+ /** The Snapshot plaintext, or AEAD_AUTHENTICATION_FAILED: client-local, no wire code (§29.1.4). */
18
+ export declare function decryptSnapshot(key: SnapshotKey, seq: bigint, aad: Uint8Array, ciphertext: Uint8Array): Uint8Array;
19
+ //# sourceMappingURL=aead.d.ts.map
package/dist/aead.js ADDED
@@ -0,0 +1,104 @@
1
+ import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
2
+ import { LfcpError } from "@openlfcp/core";
3
+ import { ActorDataKey, dataUnitNonce, SnapshotKey, snapshotNonce, symmetricSecretBytes, } from "./epoch.js";
4
+ /**
5
+ * ChaCha20-Poly1305 for Data Units (LFCP-WIRE-01 §9, §12, §26) and
6
+ * Snapshots (§29.1), from @noble/ciphers. The functions take the
7
+ * ActorDataKey or SnapshotKey itself, so the key bytes never leave this
8
+ * package, and derive the nonce from the actor or Snapshot sequence
9
+ * (0x00000000 || uint64_be(seq), §12, §29.1.2): there is no random nonce
10
+ * and no way to pass another one.
11
+ *
12
+ * The sequence must come from the writer's ActorSequenceReservation
13
+ * (@openlfcp/storage, §8): a sequence used twice under one actor key reuses
14
+ * a nonce. Use createDataUnit (@openlfcp/client) rather than these
15
+ * building blocks.
16
+ *
17
+ * Errors never include key, plaintext or ciphertext bytes.
18
+ */
19
+ const TAG_LENGTH = 16;
20
+ function keyBytes(key) {
21
+ if (!(key instanceof ActorDataKey))
22
+ throw new LfcpError("CRYPTO_FAILURE", "expected an ActorDataKey");
23
+ return symmetricSecretBytes(key);
24
+ }
25
+ /** ciphertext || 16-byte tag of `plaintext` under the actor key, the sequence nonce and `aad` (§26). */
26
+ export function encryptDataUnit(key, seq, aad, plaintext) {
27
+ const nonce = dataUnitNonce(seq);
28
+ const k = Uint8Array.from(keyBytes(key));
29
+ try {
30
+ return chacha20poly1305(k, nonce, aad).encrypt(plaintext);
31
+ }
32
+ catch {
33
+ throw new LfcpError("CRYPTO_FAILURE", "ChaCha20-Poly1305 encryption failed");
34
+ }
35
+ finally {
36
+ k.fill(0);
37
+ }
38
+ }
39
+ /**
40
+ * The plaintext of `ciphertext` (ciphertext || tag). Any authentication
41
+ * failure (wrong key, sequence, AAD or tampered bytes) is
42
+ * AEAD_AUTHENTICATION_FAILED: client-local, no wire code (§26.3, ADR 0001 N3).
43
+ */
44
+ export function decryptDataUnit(key, seq, aad, ciphertext) {
45
+ const nonce = dataUnitNonce(seq);
46
+ if (!(ciphertext instanceof Uint8Array) || ciphertext.length < TAG_LENGTH)
47
+ throw new LfcpError("AEAD_AUTHENTICATION_FAILED", "the ciphertext is shorter than the tag");
48
+ const k = Uint8Array.from(keyBytes(key));
49
+ try {
50
+ return chacha20poly1305(k, nonce, aad).decrypt(ciphertext);
51
+ }
52
+ catch {
53
+ throw new LfcpError("AEAD_AUTHENTICATION_FAILED", "the Data Unit does not authenticate under this key, sequence and AAD");
54
+ }
55
+ finally {
56
+ k.fill(0);
57
+ }
58
+ }
59
+ function snapshotKeyBytes(key) {
60
+ if (!(key instanceof SnapshotKey))
61
+ throw new LfcpError("CRYPTO_FAILURE", "expected a SnapshotKey");
62
+ return symmetricSecretBytes(key);
63
+ }
64
+ /** §29: Snapshot Sequences begin at 1 and fit in uint64. */
65
+ function snapshotSequenceNonce(seq) {
66
+ if (typeof seq !== "bigint" || seq < 1n)
67
+ throw new LfcpError("OUT_OF_RANGE", "a Snapshot Sequence starts at 1 (§29)");
68
+ return snapshotNonce(seq);
69
+ }
70
+ /**
71
+ * ciphertext || 16-byte tag of a Snapshot plaintext under the publisher's
72
+ * Snapshot key, the sequence nonce and `aad` (§29.1.4). The sequence must
73
+ * never be reused for one (resource, epoch, publisher) (§29.1.2).
74
+ */
75
+ export function encryptSnapshot(key, seq, aad, plaintext) {
76
+ const nonce = snapshotSequenceNonce(seq);
77
+ const k = Uint8Array.from(snapshotKeyBytes(key));
78
+ try {
79
+ return chacha20poly1305(k, nonce, aad).encrypt(plaintext);
80
+ }
81
+ catch {
82
+ throw new LfcpError("CRYPTO_FAILURE", "ChaCha20-Poly1305 encryption failed");
83
+ }
84
+ finally {
85
+ k.fill(0);
86
+ }
87
+ }
88
+ /** The Snapshot plaintext, or AEAD_AUTHENTICATION_FAILED: client-local, no wire code (§29.1.4). */
89
+ export function decryptSnapshot(key, seq, aad, ciphertext) {
90
+ const nonce = snapshotSequenceNonce(seq);
91
+ if (!(ciphertext instanceof Uint8Array) || ciphertext.length < TAG_LENGTH)
92
+ throw new LfcpError("AEAD_AUTHENTICATION_FAILED", "the ciphertext is shorter than the tag");
93
+ const k = Uint8Array.from(snapshotKeyBytes(key));
94
+ try {
95
+ return chacha20poly1305(k, nonce, aad).decrypt(ciphertext);
96
+ }
97
+ catch {
98
+ throw new LfcpError("AEAD_AUTHENTICATION_FAILED", "the Snapshot does not authenticate under this key, sequence and AAD");
99
+ }
100
+ finally {
101
+ k.fill(0);
102
+ }
103
+ }
104
+ //# sourceMappingURL=aead.js.map
@@ -0,0 +1,54 @@
1
+ import { type ActorSequence, type DataEpoch, type Hash32, type PrincipalId, type ResourceId } from "@openlfcp/core";
2
+ declare const INSPECT: unique symbol;
3
+ /** 32 secret bytes with redacted diagnostics. */
4
+ declare abstract class SymmetricSecret {
5
+ #private;
6
+ protected constructor(kind: string, bytes: Uint8Array);
7
+ toJSON(): string;
8
+ toString(): string;
9
+ [INSPECT](): string;
10
+ }
11
+ /** A Resource Data Encryption Key for one Data Epoch (§11). */
12
+ export declare class ResourceDEK extends SymmetricSecret {
13
+ readonly kind = "ResourceDEK";
14
+ private constructor();
15
+ }
16
+ /** A writer's ChaCha20-Poly1305 key for one (Resource, Data Epoch) (§12). */
17
+ export declare class ActorDataKey extends SymmetricSecret {
18
+ readonly kind = "ActorDataKey";
19
+ private constructor();
20
+ }
21
+ /** A Snapshot publisher's ChaCha20-Poly1305 key for one (Resource, Data Epoch) (§29.1.1). */
22
+ export declare class SnapshotKey extends SymmetricSecret {
23
+ readonly kind = "SnapshotKey";
24
+ private constructor();
25
+ }
26
+ /** True for the symmetric secrets of this module. */
27
+ export declare const isSymmetricSecret: (value: unknown) => value is SymmetricSecret;
28
+ /** The secret bytes (for exportSecretKeyBytes only). */
29
+ export declare const symmetricSecretBytes: (secret: SymmetricSecret) => Uint8Array;
30
+ /** A fresh DEK: 32 bytes from the platform CSPRNG (§11 "MUST be generated randomly"). */
31
+ export declare function generateResourceDEK(): ResourceDEK;
32
+ /** Restores a DEK from its 32 bytes (a received Key Package, local secret storage). The input is copied. */
33
+ export declare function importResourceDEK(bytes: Uint8Array): ResourceDEK;
34
+ /** dek_commitment = SHA-256(ASCII("LFCP-DEK-v1") || resource_id || uint64_be(E) || DEK) (§11). */
35
+ export declare function dekCommitment(resource: ResourceId, epoch: DataEpoch, dek: ResourceDEK): Hash32;
36
+ /**
37
+ * actor_key = HKDF-Expand(HKDF-Extract(R || uint64_be(E), DEK),
38
+ * ASCII("LFCP-DATA-KEY-v1") || A, 32) (§12)
39
+ */
40
+ export declare function deriveActorDataKey(dek: ResourceDEK, resource: ResourceId, epoch: DataEpoch, actor: PrincipalId): ActorDataKey;
41
+ /**
42
+ * snapshot_key = HKDF-Expand(HKDF-Extract(resource_id || uint64_be(E), DEK),
43
+ * ASCII("LFCP-SNAPSHOT-KEY-v1") || publisher, 32) (§29.1.1)
44
+ */
45
+ export declare function deriveSnapshotKey(dek: ResourceDEK, resource: ResourceId, epoch: DataEpoch, publisher: PrincipalId): SnapshotKey;
46
+ /** nonce = 0x00000000 || uint64_be(seq), 12 bytes, for actor sequence 1..2^64-1 (§8, §12). */
47
+ export declare function dataUnitNonce(seq: ActorSequence): Uint8Array;
48
+ /**
49
+ * snapshot_nonce = 0x00000000 || uint64_be(snapshot_sequence), 12 bytes
50
+ * (§29.1.2). The sequence must fit in uint64; §29 sets no lower bound.
51
+ */
52
+ export declare function snapshotNonce(snapshotSequence: bigint): Uint8Array;
53
+ export {};
54
+ //# sourceMappingURL=epoch.d.ts.map
package/dist/epoch.js ADDED
@@ -0,0 +1,176 @@
1
+ import { randomBytes } from "@noble/hashes/utils.js";
2
+ import { actorSequence, dataEpoch, hash32, ID32_LENGTH, LfcpError, uint64BE, } from "@openlfcp/core";
3
+ import { sha256 } from "./hash.js";
4
+ import { hkdfExpand, hkdfExtract } from "./hkdf.js";
5
+ /**
6
+ * Data Epoch key material (LFCP-WIRE-01 §11, §12, §29.1.1, §29.1.2).
7
+ *
8
+ * - The Resource DEK is 32 random bytes per (Resource, Data Epoch), from the
9
+ * platform CSPRNG; it is never derived from IDs, identities or time.
10
+ * - Its public commitment is SHA-256("LFCP-DEK-v1" || R || uint64_be(E) || DEK).
11
+ * - Each writer encrypts with its own actor key,
12
+ * HKDF-Expand(HKDF-Extract(R || uint64_be(E), DEK), "LFCP-DATA-KEY-v1" || A, 32),
13
+ * and nonce 0x00000000 || uint64_be(seq). The same sequence is safe for
14
+ * different Principals because their keys differ; reusing a sequence for
15
+ * one (Resource, Principal) is forbidden (§8, §12), across epochs too.
16
+ * - A Snapshot publisher uses the same construction with the label
17
+ * "LFCP-SNAPSHOT-KEY-v1" and its Snapshot Sequence.
18
+ *
19
+ * All IDs are the raw 32 bytes, never text forms. Secrets (ResourceDEK,
20
+ * ActorDataKey, SnapshotKey) keep their bytes in a private field and print
21
+ * as "[redacted]" through toJSON, toString and inspect; the only way out is
22
+ * `exportSecretKeyBytes`. Errors never include key bytes.
23
+ */
24
+ const REDACTED = "[redacted]";
25
+ const INSPECT = Symbol.for("nodejs.util.inspect.custom");
26
+ const KEY_LENGTH = 32;
27
+ const ascii = (text) => Uint8Array.from(text, (c) => c.charCodeAt(0));
28
+ const DEK_LABEL = ascii("LFCP-DEK-v1");
29
+ const DATA_KEY_LABEL = ascii("LFCP-DATA-KEY-v1");
30
+ const SNAPSHOT_KEY_LABEL = ascii("LFCP-SNAPSHOT-KEY-v1");
31
+ const NONCE_PREFIX = new Uint8Array(4);
32
+ let readSecret;
33
+ /** 32 secret bytes with redacted diagnostics. */
34
+ class SymmetricSecret {
35
+ #bytes;
36
+ static {
37
+ readSecret = (secret) => secret.#bytes;
38
+ }
39
+ constructor(kind, bytes) {
40
+ if (!(bytes instanceof Uint8Array) || bytes.length !== KEY_LENGTH)
41
+ throw new LfcpError("INVALID_LENGTH", `${kind} must be exactly ${KEY_LENGTH} bytes`);
42
+ this.#bytes = Uint8Array.from(bytes);
43
+ }
44
+ toJSON() {
45
+ return REDACTED;
46
+ }
47
+ toString() {
48
+ return REDACTED;
49
+ }
50
+ [INSPECT]() {
51
+ return REDACTED;
52
+ }
53
+ }
54
+ let makeDek;
55
+ let makeActorKey;
56
+ let makeSnapshotKey;
57
+ /** A Resource Data Encryption Key for one Data Epoch (§11). */
58
+ export class ResourceDEK extends SymmetricSecret {
59
+ kind = "ResourceDEK";
60
+ static {
61
+ makeDek = (bytes) => new ResourceDEK(bytes);
62
+ }
63
+ constructor(bytes) {
64
+ super("a Resource DEK", bytes);
65
+ }
66
+ }
67
+ /** A writer's ChaCha20-Poly1305 key for one (Resource, Data Epoch) (§12). */
68
+ export class ActorDataKey extends SymmetricSecret {
69
+ kind = "ActorDataKey";
70
+ static {
71
+ makeActorKey = (bytes) => new ActorDataKey(bytes);
72
+ }
73
+ constructor(bytes) {
74
+ super("an actor data key", bytes);
75
+ }
76
+ }
77
+ /** A Snapshot publisher's ChaCha20-Poly1305 key for one (Resource, Data Epoch) (§29.1.1). */
78
+ export class SnapshotKey extends SymmetricSecret {
79
+ kind = "SnapshotKey";
80
+ static {
81
+ makeSnapshotKey = (bytes) => new SnapshotKey(bytes);
82
+ }
83
+ constructor(bytes) {
84
+ super("a Snapshot key", bytes);
85
+ }
86
+ }
87
+ /** True for the symmetric secrets of this module. */
88
+ export const isSymmetricSecret = (value) => value instanceof SymmetricSecret;
89
+ /** The secret bytes (for exportSecretKeyBytes only). */
90
+ export const symmetricSecretBytes = (secret) => readSecret(secret);
91
+ function id32(what, id) {
92
+ if (!(id instanceof Uint8Array) || id.length !== ID32_LENGTH)
93
+ throw new LfcpError("INVALID_LENGTH", `${what} must be the raw ${ID32_LENGTH}-byte ID`);
94
+ return id;
95
+ }
96
+ function concat(...parts) {
97
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
98
+ let at = 0;
99
+ for (const p of parts) {
100
+ out.set(p, at);
101
+ at += p.length;
102
+ }
103
+ return out;
104
+ }
105
+ function dekOf(dek) {
106
+ if (!(dek instanceof ResourceDEK))
107
+ throw new LfcpError("CRYPTO_FAILURE", "expected a ResourceDEK");
108
+ return readSecret(dek);
109
+ }
110
+ /** A fresh DEK: 32 bytes from the platform CSPRNG (§11 "MUST be generated randomly"). */
111
+ export function generateResourceDEK() {
112
+ let bytes;
113
+ try {
114
+ bytes = randomBytes(KEY_LENGTH);
115
+ }
116
+ catch {
117
+ throw new LfcpError("NO_SECURE_RANDOM", "no CSPRNG (crypto.getRandomValues) is available");
118
+ }
119
+ return makeDek(bytes);
120
+ }
121
+ /** Restores a DEK from its 32 bytes (a received Key Package, local secret storage). The input is copied. */
122
+ export function importResourceDEK(bytes) {
123
+ return makeDek(bytes);
124
+ }
125
+ /** dek_commitment = SHA-256(ASCII("LFCP-DEK-v1") || resource_id || uint64_be(E) || DEK) (§11). */
126
+ export function dekCommitment(resource, epoch, dek) {
127
+ return hash32(sha256(concat(DEK_LABEL, id32("the Resource ID", resource), uint64BE(dataEpoch(epoch)), dekOf(dek))));
128
+ }
129
+ function epochKey(dek, resource, epoch, label, principal) {
130
+ const salt = concat(id32("the Resource ID", resource), uint64BE(dataEpoch(epoch)));
131
+ const prk = hkdfExtract(salt, dekOf(dek));
132
+ try {
133
+ return hkdfExpand(prk, concat(label, id32("the Principal ID", principal)), KEY_LENGTH);
134
+ }
135
+ finally {
136
+ prk.fill(0);
137
+ }
138
+ }
139
+ /**
140
+ * actor_key = HKDF-Expand(HKDF-Extract(R || uint64_be(E), DEK),
141
+ * ASCII("LFCP-DATA-KEY-v1") || A, 32) (§12)
142
+ */
143
+ export function deriveActorDataKey(dek, resource, epoch, actor) {
144
+ const bytes = epochKey(dek, resource, epoch, DATA_KEY_LABEL, actor);
145
+ try {
146
+ return makeActorKey(bytes);
147
+ }
148
+ finally {
149
+ bytes.fill(0);
150
+ }
151
+ }
152
+ /**
153
+ * snapshot_key = HKDF-Expand(HKDF-Extract(resource_id || uint64_be(E), DEK),
154
+ * ASCII("LFCP-SNAPSHOT-KEY-v1") || publisher, 32) (§29.1.1)
155
+ */
156
+ export function deriveSnapshotKey(dek, resource, epoch, publisher) {
157
+ const bytes = epochKey(dek, resource, epoch, SNAPSHOT_KEY_LABEL, publisher);
158
+ try {
159
+ return makeSnapshotKey(bytes);
160
+ }
161
+ finally {
162
+ bytes.fill(0);
163
+ }
164
+ }
165
+ /** nonce = 0x00000000 || uint64_be(seq), 12 bytes, for actor sequence 1..2^64-1 (§8, §12). */
166
+ export function dataUnitNonce(seq) {
167
+ return concat(NONCE_PREFIX, uint64BE(actorSequence(seq)));
168
+ }
169
+ /**
170
+ * snapshot_nonce = 0x00000000 || uint64_be(snapshot_sequence), 12 bytes
171
+ * (§29.1.2). The sequence must fit in uint64; §29 sets no lower bound.
172
+ */
173
+ export function snapshotNonce(snapshotSequence) {
174
+ return concat(NONCE_PREFIX, uint64BE(snapshotSequence));
175
+ }
176
+ //# sourceMappingURL=epoch.js.map
package/dist/hash.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** SHA-256 (FIPS 180-4), the `hash32` function of LFCP-WIRE-01 §5.3. */
2
+ export declare function sha256(data: Uint8Array): Uint8Array;
3
+ //# sourceMappingURL=hash.d.ts.map
package/dist/hash.js ADDED
@@ -0,0 +1,6 @@
1
+ import { sha256 as nobleSha256 } from "@noble/hashes/sha2.js";
2
+ /** SHA-256 (FIPS 180-4), the `hash32` function of LFCP-WIRE-01 §5.3. */
3
+ export function sha256(data) {
4
+ return nobleSha256(data);
5
+ }
6
+ //# sourceMappingURL=hash.js.map
package/dist/hkdf.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /** HKDF-Extract(salt, IKM) with SHA-256: the 32-byte PRK. The result is secret material. */
2
+ export declare function hkdfExtract(salt: Uint8Array, ikm: Uint8Array): Uint8Array;
3
+ /** HKDF-Expand(PRK, info, L) with SHA-256. The result is secret material. */
4
+ export declare function hkdfExpand(prk: Uint8Array, info: Uint8Array, length: number): Uint8Array;
5
+ //# sourceMappingURL=hkdf.d.ts.map
package/dist/hkdf.js ADDED
@@ -0,0 +1,20 @@
1
+ import { expand, extract } from "@noble/hashes/hkdf.js";
2
+ import { sha256 as nobleSha256 } from "@noble/hashes/sha2.js";
3
+ import { LfcpError } from "@openlfcp/core";
4
+ // HKDF-SHA256 (RFC 5869), the KDF of the LFCP crypto profile (LFCP-WIRE-01 §9).
5
+ const MAX_OUTPUT = 255 * 32;
6
+ /** HKDF-Extract(salt, IKM) with SHA-256: the 32-byte PRK. The result is secret material. */
7
+ export function hkdfExtract(salt, ikm) {
8
+ if (!(salt instanceof Uint8Array) || !(ikm instanceof Uint8Array))
9
+ throw new LfcpError("INVALID_LENGTH", "HKDF-Extract takes byte strings");
10
+ return extract(nobleSha256, ikm, salt);
11
+ }
12
+ /** HKDF-Expand(PRK, info, L) with SHA-256. The result is secret material. */
13
+ export function hkdfExpand(prk, info, length) {
14
+ if (!(prk instanceof Uint8Array) || prk.length < 32 || !(info instanceof Uint8Array))
15
+ throw new LfcpError("INVALID_LENGTH", "HKDF-Expand takes a PRK of at least 32 bytes and info bytes");
16
+ if (!Number.isSafeInteger(length) || length < 1 || length > MAX_OUTPUT)
17
+ throw new LfcpError("OUT_OF_RANGE", `HKDF-Expand length must be in 1..${MAX_OUTPUT}`);
18
+ return expand(nobleSha256, prk, info, length);
19
+ }
20
+ //# sourceMappingURL=hkdf.js.map
package/dist/hpke.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { type ResourceDEK } from "./epoch.js";
2
+ import { type AgreementKeyPair } from "./keys.js";
3
+ /** HPKE output: the encapsulated key (enc) and the ciphertext of the DEK. */
4
+ export interface SealedDek {
5
+ readonly enc: Uint8Array;
6
+ readonly ciphertext: Uint8Array;
7
+ }
8
+ /** Seals `dek` to the recipient's X25519 public key with `info` and `aad` (§25.1). */
9
+ export declare function sealDek(recipientPublicKey: Uint8Array, dek: ResourceDEK, info: Uint8Array, aad: Uint8Array): Promise<SealedDek>;
10
+ /**
11
+ * Opens an HPKE-sealed DEK with the recipient's X25519 key pair. An HPKE
12
+ * failure (wrong key, tampered enc, ciphertext, info or AAD) is
13
+ * KEY_PACKAGE_OPEN_FAILED. A plaintext that is not 32 bytes is
14
+ * DEK_COMMITMENT_MISMATCH (LFCP-WIRE-01 §25.2: "A decrypted plaintext that
15
+ * is not exactly 32 bytes long is a DEK that does not match the
16
+ * commitment"). Both are client-local (ADR 0001 N5).
17
+ */
18
+ export declare function openDek(recipient: AgreementKeyPair, enc: Uint8Array, ciphertext: Uint8Array, info: Uint8Array, aad: Uint8Array): Promise<ResourceDEK>;
19
+ //# sourceMappingURL=hpke.d.ts.map
package/dist/hpke.js ADDED
@@ -0,0 +1,62 @@
1
+ import { LfcpError } from "@openlfcp/core";
2
+ import { AEAD_ChaCha20Poly1305, KDF_HKDF_SHA256, KEM_DHKEM_X25519_HKDF_SHA256, } from "@panva/hpke-noble";
3
+ import { CipherSuite } from "hpke";
4
+ import { importResourceDEK, symmetricSecretBytes } from "./epoch.js";
5
+ import { agreementSecretBytes } from "./keys.js";
6
+ /**
7
+ * RFC 9180 HPKE for LFCP Key Packages (LFCP-WIRE-01 §9, §25): Base mode
8
+ * with DHKEM(X25519, HKDF-SHA256) 0x0020, HKDF-SHA256 0x0001 and
9
+ * ChaCha20-Poly1305 0x0003. The protocol is the `hpke` library's; the
10
+ * primitives are the audited noble packages through @panva/hpke-noble.
11
+ *
12
+ * The plaintext is exactly the 32-byte DEK. Sealing always draws a fresh
13
+ * ephemeral key from the platform CSPRNG; there is no way to pass one in.
14
+ * Secrets (the DEK, the recipient key, the ephemeral key, the shared
15
+ * secret) never appear in errors.
16
+ */
17
+ const SUITE = new CipherSuite(KEM_DHKEM_X25519_HKDF_SHA256, KDF_HKDF_SHA256, AEAD_ChaCha20Poly1305);
18
+ const KEY_LENGTH = 32;
19
+ /** Seals `dek` to the recipient's X25519 public key with `info` and `aad` (§25.1). */
20
+ export async function sealDek(recipientPublicKey, dek, info, aad) {
21
+ if (!(recipientPublicKey instanceof Uint8Array) || recipientPublicKey.length !== KEY_LENGTH)
22
+ throw new LfcpError("INVALID_LENGTH", "an X25519 public key must be exactly 32 bytes");
23
+ const plaintext = Uint8Array.from(symmetricSecretBytes(dek));
24
+ try {
25
+ const pk = await SUITE.DeserializePublicKey(Uint8Array.from(recipientPublicKey));
26
+ const sealed = await SUITE.Seal(pk, plaintext, { info, aad });
27
+ return Object.freeze({ enc: sealed.encapsulatedSecret, ciphertext: sealed.ciphertext });
28
+ }
29
+ catch {
30
+ throw new LfcpError("CRYPTO_FAILURE", "HPKE seal failed");
31
+ }
32
+ finally {
33
+ plaintext.fill(0);
34
+ }
35
+ }
36
+ /**
37
+ * Opens an HPKE-sealed DEK with the recipient's X25519 key pair. An HPKE
38
+ * failure (wrong key, tampered enc, ciphertext, info or AAD) is
39
+ * KEY_PACKAGE_OPEN_FAILED. A plaintext that is not 32 bytes is
40
+ * DEK_COMMITMENT_MISMATCH (LFCP-WIRE-01 §25.2: "A decrypted plaintext that
41
+ * is not exactly 32 bytes long is a DEK that does not match the
42
+ * commitment"). Both are client-local (ADR 0001 N5).
43
+ */
44
+ export async function openDek(recipient, enc, ciphertext, info, aad) {
45
+ let plaintext;
46
+ try {
47
+ const sk = await SUITE.DeserializePrivateKey(Uint8Array.from(agreementSecretBytes(recipient)), false);
48
+ plaintext = await SUITE.Open(sk, enc, ciphertext, { info, aad });
49
+ }
50
+ catch {
51
+ throw new LfcpError("KEY_PACKAGE_OPEN_FAILED", "the Key Package does not open with this recipient key");
52
+ }
53
+ try {
54
+ if (plaintext.length !== KEY_LENGTH)
55
+ throw new LfcpError("DEK_COMMITMENT_MISMATCH", "the Key Package plaintext is not a 32-byte DEK, so it matches no commitment");
56
+ return importResourceDEK(plaintext);
57
+ }
58
+ finally {
59
+ plaintext.fill(0);
60
+ }
61
+ }
62
+ //# sourceMappingURL=hpke.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Cryptographic primitives for LFCP, as a thin wrapper over the audited
3
+ * @noble libraries. No other package imports @noble directly.
4
+ */
5
+ export declare const PACKAGE = "@openlfcp/crypto";
6
+ export { decryptDataUnit, decryptSnapshot, encryptDataUnit, encryptSnapshot } from "./aead.js";
7
+ export { ActorDataKey, dataUnitNonce, dekCommitment, deriveActorDataKey, deriveSnapshotKey, generateResourceDEK, importResourceDEK, ResourceDEK, SnapshotKey, snapshotNonce, } from "./epoch.js";
8
+ export { sha256 } from "./hash.js";
9
+ export { hkdfExpand, hkdfExtract } from "./hkdf.js";
10
+ export { openDek, type SealedDek, sealDek } from "./hpke.js";
11
+ export { InvitationSecret } from "./invitation.js";
12
+ export { AgreementKeyPair, exportSecretKeyBytes, generateAgreementKeyPair, generateSigningKeyPair, importAgreementKey, importSigningKey, isValidEd25519PublicKey, SigningKeyPair, verifyEd25519, } from "./keys.js";
13
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Cryptographic primitives for LFCP, as a thin wrapper over the audited
3
+ * @noble libraries. No other package imports @noble directly.
4
+ */
5
+ export const PACKAGE = "@openlfcp/crypto";
6
+ export { decryptDataUnit, decryptSnapshot, encryptDataUnit, encryptSnapshot } from "./aead.js";
7
+ export { ActorDataKey, dataUnitNonce, dekCommitment, deriveActorDataKey, deriveSnapshotKey, generateResourceDEK, importResourceDEK, ResourceDEK, SnapshotKey, snapshotNonce, } from "./epoch.js";
8
+ export { sha256 } from "./hash.js";
9
+ export { hkdfExpand, hkdfExtract } from "./hkdf.js";
10
+ export { openDek, sealDek } from "./hpke.js";
11
+ export { InvitationSecret } from "./invitation.js";
12
+ export { AgreementKeyPair, exportSecretKeyBytes, generateAgreementKeyPair, generateSigningKeyPair, importAgreementKey, importSigningKey, isValidEd25519PublicKey, SigningKeyPair, verifyEd25519, } from "./keys.js";
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,29 @@
1
+ import { type AgreementKeyPair, type SigningKeyPair } from "./keys.js";
2
+ /**
3
+ * The key material of an Invitation Principal (LFCP-WIRE-01 §18, §18.2):
4
+ * the ephemeral Principal an inviter creates for one invitation, whose
5
+ * private keys travel in the `#secret=` fragment of a bearer invitation
6
+ * URI.
7
+ *
8
+ * Like every key in this package, it is redacted: `toJSON`, `toString`
9
+ * and Node's inspect hook print "[redacted]", and the two key pairs it
10
+ * holds are redacted themselves. The secret is encoded only by the
11
+ * invitation codec of @openlfcp/wire, for the URI fragment. §18.2: it MUST
12
+ * NOT be logged, placed in analytics or transmitted to a synchronization
13
+ * server.
14
+ */
15
+ export declare class InvitationSecret {
16
+ #private;
17
+ private constructor();
18
+ /** A fresh Invitation Principal: independent Ed25519 and X25519 keys from the platform CSPRNG. */
19
+ static generate(): InvitationSecret;
20
+ /** An Invitation Principal from its key pairs (for example, decoded from a URI fragment). */
21
+ static fromKeys(signing: SigningKeyPair, agreement: AgreementKeyPair): InvitationSecret;
22
+ /** The Ed25519 key pair: signs the CAPABILITY_CLAIM record (§18.1). */
23
+ get signingKey(): SigningKeyPair;
24
+ /** The X25519 key pair: opens the Key Package sealed to the Invitation Principal (§18, §25). */
25
+ get agreementKey(): AgreementKeyPair;
26
+ toJSON(): string;
27
+ toString(): string;
28
+ }
29
+ //# sourceMappingURL=invitation.d.ts.map
@@ -0,0 +1,48 @@
1
+ import { generateAgreementKeyPair, generateSigningKeyPair, } from "./keys.js";
2
+ /**
3
+ * The key material of an Invitation Principal (LFCP-WIRE-01 §18, §18.2):
4
+ * the ephemeral Principal an inviter creates for one invitation, whose
5
+ * private keys travel in the `#secret=` fragment of a bearer invitation
6
+ * URI.
7
+ *
8
+ * Like every key in this package, it is redacted: `toJSON`, `toString`
9
+ * and Node's inspect hook print "[redacted]", and the two key pairs it
10
+ * holds are redacted themselves. The secret is encoded only by the
11
+ * invitation codec of @openlfcp/wire, for the URI fragment. §18.2: it MUST
12
+ * NOT be logged, placed in analytics or transmitted to a synchronization
13
+ * server.
14
+ */
15
+ export class InvitationSecret {
16
+ #signing;
17
+ #agreement;
18
+ constructor(signing, agreement) {
19
+ this.#signing = signing;
20
+ this.#agreement = agreement;
21
+ }
22
+ /** A fresh Invitation Principal: independent Ed25519 and X25519 keys from the platform CSPRNG. */
23
+ static generate() {
24
+ return new InvitationSecret(generateSigningKeyPair(), generateAgreementKeyPair());
25
+ }
26
+ /** An Invitation Principal from its key pairs (for example, decoded from a URI fragment). */
27
+ static fromKeys(signing, agreement) {
28
+ return new InvitationSecret(signing, agreement);
29
+ }
30
+ /** The Ed25519 key pair: signs the CAPABILITY_CLAIM record (§18.1). */
31
+ get signingKey() {
32
+ return this.#signing;
33
+ }
34
+ /** The X25519 key pair: opens the Key Package sealed to the Invitation Principal (§18, §25). */
35
+ get agreementKey() {
36
+ return this.#agreement;
37
+ }
38
+ toJSON() {
39
+ return "[redacted]";
40
+ }
41
+ toString() {
42
+ return "[redacted]";
43
+ }
44
+ [Symbol.for("nodejs.util.inspect.custom")]() {
45
+ return "[redacted]";
46
+ }
47
+ }
48
+ //# sourceMappingURL=invitation.js.map
package/dist/keys.d.ts ADDED
@@ -0,0 +1,76 @@
1
+ import { type ActorDataKey, type ResourceDEK, type SnapshotKey } from "./epoch.js";
2
+ declare const INSPECT: unique symbol;
3
+ /** An Ed25519 key pair. The secret is the 32-byte RFC 8032 seed. */
4
+ export declare class SigningKeyPair {
5
+ #private;
6
+ /** The 32-byte Ed25519 public key. */
7
+ readonly publicKey: Uint8Array;
8
+ private constructor();
9
+ /** Ed25519 signature (64 bytes) over `message`. */
10
+ sign(message: Uint8Array): Uint8Array;
11
+ toJSON(): string;
12
+ toString(): string;
13
+ [INSPECT](): string;
14
+ }
15
+ /** An X25519 key pair. The secret is the 32-byte RFC 7748 scalar. */
16
+ export declare class AgreementKeyPair {
17
+ #private;
18
+ /** The 32-byte X25519 public key. */
19
+ readonly publicKey: Uint8Array;
20
+ private constructor();
21
+ /**
22
+ * X25519 shared secret with `peerPublicKey` (RFC 7748). The result is
23
+ * secret material: treat it like a private key.
24
+ */
25
+ sharedSecret(peerPublicKey: Uint8Array): Uint8Array;
26
+ toJSON(): string;
27
+ toString(): string;
28
+ [INSPECT](): string;
29
+ }
30
+ /** A fresh Ed25519 key pair from the platform CSPRNG. */
31
+ export declare function generateSigningKeyPair(): SigningKeyPair;
32
+ /** A fresh X25519 key pair from the platform CSPRNG, independent of any signing key. */
33
+ export declare function generateAgreementKeyPair(): AgreementKeyPair;
34
+ /** Restores an Ed25519 key pair from its 32-byte seed. The input is copied. */
35
+ export declare function importSigningKey(secret: Uint8Array): SigningKeyPair;
36
+ /** Restores an X25519 key pair from its 32-byte secret scalar. The input is copied. */
37
+ export declare function importAgreementKey(secret: Uint8Array): AgreementKeyPair;
38
+ /**
39
+ * Returns a copy of the secret bytes of a key pair or a Data Epoch key, for
40
+ * persistence (or, for a DEK, HPKE delivery to a recipient) only.
41
+ *
42
+ * WARNING: the result is secret. Never log it, put it in errors or
43
+ * diagnostics, or send it anywhere except an encrypted local secret store.
44
+ */
45
+ export declare function exportSecretKeyBytes(key: SigningKeyPair | AgreementKeyPair | ResourceDEK | ActorDataKey | SnapshotKey): Uint8Array;
46
+ /**
47
+ * The X25519 secret of a key pair, for this package's HPKE module only. It
48
+ * is not re-exported from the package index.
49
+ */
50
+ export declare const agreementSecretBytes: (key: AgreementKeyPair) => Uint8Array;
51
+ /**
52
+ * Whether `publicKey` is a canonical Ed25519 point encoding that is not of
53
+ * small order (LFCP-WIRE-01 §7, §10.5.1 rules 2 and 3), as required of every
54
+ * descriptor's Ed25519 key at receipt.
55
+ */
56
+ export declare function isValidEd25519PublicKey(publicKey: Uint8Array): boolean;
57
+ /**
58
+ * Strict Ed25519 verification, LFCP-WIRE-01 §10.5.1. Returns false (never
59
+ * throws) for any malformed or invalid input. The checks run in this order:
60
+ *
61
+ * 1. decode: A and R are canonical point encodings (y < p; x = 0 with the
62
+ * sign bit set is refused) — rule 2;
63
+ * 2. S < L — rule 1;
64
+ * 3. neither A nor R is of small order — rule 3;
65
+ * 4. the cofactorless equation [S]B = R + [k]A, where k = SHA-512 of the
66
+ * exact received R bytes, the exact A bytes and M, reduced mod L — rule 4.
67
+ *
68
+ * noble's `ed25519.verify` is not used: it checks the cofactored equation
69
+ * ([8][S]B = [8]R + [8][k]A) and does not refuse a small-order R, so it
70
+ * accepts signatures §10.5.1 rejects (a mixed-order A or R, a small-order
71
+ * R). The rules are composed here from noble's point decoding and
72
+ * arithmetic, and R and A are never re-encoded.
73
+ */
74
+ export declare function verifyEd25519(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): boolean;
75
+ export {};
76
+ //# sourceMappingURL=keys.d.ts.map
package/dist/keys.js ADDED
@@ -0,0 +1,206 @@
1
+ import { ed25519, x25519 } from "@noble/curves/ed25519.js";
2
+ import { bytesToNumberLE, concatBytes } from "@noble/curves/utils.js";
3
+ import { sha512 } from "@noble/hashes/sha2.js";
4
+ import { LfcpError } from "@openlfcp/core";
5
+ import { isSymmetricSecret, symmetricSecretBytes, } from "./epoch.js";
6
+ /**
7
+ * Key material for an LFCP Principal (LFCP-WIRE-01 §7): an Ed25519 signing
8
+ * key and an independent X25519 key-agreement key. Neither is derived from
9
+ * the other.
10
+ *
11
+ * Private bytes live only in a private class field. `toJSON`, `toString`
12
+ * and Node's inspect hook all print "[redacted]", no enumerable property
13
+ * holds secret bytes, and errors never include key bytes. The only way to
14
+ * read the bytes is `exportSecretKeyBytes`.
15
+ */
16
+ const REDACTED = "[redacted]";
17
+ const INSPECT = Symbol.for("nodejs.util.inspect.custom");
18
+ const KEY_LENGTH = 32;
19
+ function requireKeyBytes(kind, bytes) {
20
+ if (!(bytes instanceof Uint8Array) || bytes.length !== KEY_LENGTH) {
21
+ throw new LfcpError("INVALID_LENGTH", `${kind} must be exactly ${KEY_LENGTH} bytes`);
22
+ }
23
+ return Uint8Array.from(bytes);
24
+ }
25
+ /** Runs a primitive and replaces any error with one that cannot carry key material. */
26
+ function guarded(what, fn) {
27
+ try {
28
+ return fn();
29
+ }
30
+ catch {
31
+ throw new LfcpError("CRYPTO_FAILURE", `${what} failed`);
32
+ }
33
+ }
34
+ // Module-private access, assigned in the class static blocks, so the only
35
+ // public ways in and out are the import/export functions below.
36
+ let makeSigningKeyPair;
37
+ let readSigningSecret;
38
+ let makeAgreementKeyPair;
39
+ let readAgreementSecret;
40
+ /** An Ed25519 key pair. The secret is the 32-byte RFC 8032 seed. */
41
+ export class SigningKeyPair {
42
+ #secret;
43
+ /** The 32-byte Ed25519 public key. */
44
+ publicKey;
45
+ static {
46
+ makeSigningKeyPair = (secret) => new SigningKeyPair(requireKeyBytes("an Ed25519 secret key", secret));
47
+ readSigningSecret = (key) => key.#secret;
48
+ }
49
+ constructor(secret) {
50
+ this.#secret = secret;
51
+ this.publicKey = guarded("Ed25519 public key derivation", () => ed25519.getPublicKey(secret));
52
+ }
53
+ /** Ed25519 signature (64 bytes) over `message`. */
54
+ sign(message) {
55
+ return guarded("Ed25519 signing", () => ed25519.sign(message, this.#secret));
56
+ }
57
+ toJSON() {
58
+ return REDACTED;
59
+ }
60
+ toString() {
61
+ return REDACTED;
62
+ }
63
+ [INSPECT]() {
64
+ return REDACTED;
65
+ }
66
+ }
67
+ /** An X25519 key pair. The secret is the 32-byte RFC 7748 scalar. */
68
+ export class AgreementKeyPair {
69
+ #secret;
70
+ /** The 32-byte X25519 public key. */
71
+ publicKey;
72
+ static {
73
+ makeAgreementKeyPair = (secret) => new AgreementKeyPair(requireKeyBytes("an X25519 secret key", secret));
74
+ readAgreementSecret = (key) => key.#secret;
75
+ }
76
+ constructor(secret) {
77
+ this.#secret = secret;
78
+ this.publicKey = guarded("X25519 public key derivation", () => x25519.getPublicKey(secret));
79
+ }
80
+ /**
81
+ * X25519 shared secret with `peerPublicKey` (RFC 7748). The result is
82
+ * secret material: treat it like a private key.
83
+ */
84
+ sharedSecret(peerPublicKey) {
85
+ if (!(peerPublicKey instanceof Uint8Array) || peerPublicKey.length !== KEY_LENGTH) {
86
+ throw new LfcpError("INVALID_LENGTH", `an X25519 public key must be exactly ${KEY_LENGTH} bytes`);
87
+ }
88
+ return guarded("X25519 agreement", () => x25519.getSharedSecret(this.#secret, peerPublicKey));
89
+ }
90
+ toJSON() {
91
+ return REDACTED;
92
+ }
93
+ toString() {
94
+ return REDACTED;
95
+ }
96
+ [INSPECT]() {
97
+ return REDACTED;
98
+ }
99
+ }
100
+ /** A fresh Ed25519 key pair from the platform CSPRNG. */
101
+ export function generateSigningKeyPair() {
102
+ return makeSigningKeyPair(guarded("Ed25519 key generation", () => ed25519.utils.randomSecretKey()));
103
+ }
104
+ /** A fresh X25519 key pair from the platform CSPRNG, independent of any signing key. */
105
+ export function generateAgreementKeyPair() {
106
+ return makeAgreementKeyPair(guarded("X25519 key generation", () => x25519.utils.randomSecretKey()));
107
+ }
108
+ /** Restores an Ed25519 key pair from its 32-byte seed. The input is copied. */
109
+ export function importSigningKey(secret) {
110
+ return makeSigningKeyPair(secret);
111
+ }
112
+ /** Restores an X25519 key pair from its 32-byte secret scalar. The input is copied. */
113
+ export function importAgreementKey(secret) {
114
+ return makeAgreementKeyPair(secret);
115
+ }
116
+ /**
117
+ * Returns a copy of the secret bytes of a key pair or a Data Epoch key, for
118
+ * persistence (or, for a DEK, HPKE delivery to a recipient) only.
119
+ *
120
+ * WARNING: the result is secret. Never log it, put it in errors or
121
+ * diagnostics, or send it anywhere except an encrypted local secret store.
122
+ */
123
+ export function exportSecretKeyBytes(key) {
124
+ if (key instanceof SigningKeyPair)
125
+ return Uint8Array.from(readSigningSecret(key));
126
+ if (key instanceof AgreementKeyPair)
127
+ return Uint8Array.from(readAgreementSecret(key));
128
+ if (isSymmetricSecret(key))
129
+ return Uint8Array.from(symmetricSecretBytes(key));
130
+ throw new LfcpError("CRYPTO_FAILURE", "not a secret key of this package");
131
+ }
132
+ /**
133
+ * The X25519 secret of a key pair, for this package's HPKE module only. It
134
+ * is not re-exported from the package index.
135
+ */
136
+ export const agreementSecretBytes = (key) => readAgreementSecret(key);
137
+ const POINT = ed25519.Point;
138
+ /** The Ed25519 group order L. */
139
+ const L = POINT.Fn.ORDER;
140
+ /**
141
+ * Decodes an Ed25519 point under §10.5.1 rule 2: y < p, and x = 0 with the
142
+ * sign bit set is refused. Returns undefined for a non-canonical or
143
+ * off-curve encoding.
144
+ */
145
+ function decodePoint(bytes) {
146
+ try {
147
+ return POINT.fromBytes(bytes, false);
148
+ }
149
+ catch {
150
+ return undefined;
151
+ }
152
+ }
153
+ /**
154
+ * Whether `publicKey` is a canonical Ed25519 point encoding that is not of
155
+ * small order (LFCP-WIRE-01 §7, §10.5.1 rules 2 and 3), as required of every
156
+ * descriptor's Ed25519 key at receipt.
157
+ */
158
+ export function isValidEd25519PublicKey(publicKey) {
159
+ if (!(publicKey instanceof Uint8Array) || publicKey.length !== KEY_LENGTH)
160
+ return false;
161
+ const a = decodePoint(publicKey);
162
+ return a !== undefined && !a.isSmallOrder();
163
+ }
164
+ /**
165
+ * Strict Ed25519 verification, LFCP-WIRE-01 §10.5.1. Returns false (never
166
+ * throws) for any malformed or invalid input. The checks run in this order:
167
+ *
168
+ * 1. decode: A and R are canonical point encodings (y < p; x = 0 with the
169
+ * sign bit set is refused) — rule 2;
170
+ * 2. S < L — rule 1;
171
+ * 3. neither A nor R is of small order — rule 3;
172
+ * 4. the cofactorless equation [S]B = R + [k]A, where k = SHA-512 of the
173
+ * exact received R bytes, the exact A bytes and M, reduced mod L — rule 4.
174
+ *
175
+ * noble's `ed25519.verify` is not used: it checks the cofactored equation
176
+ * ([8][S]B = [8]R + [8][k]A) and does not refuse a small-order R, so it
177
+ * accepts signatures §10.5.1 rejects (a mixed-order A or R, a small-order
178
+ * R). The rules are composed here from noble's point decoding and
179
+ * arithmetic, and R and A are never re-encoded.
180
+ */
181
+ export function verifyEd25519(publicKey, message, signature) {
182
+ try {
183
+ if (!(publicKey instanceof Uint8Array) ||
184
+ !(message instanceof Uint8Array) ||
185
+ !(signature instanceof Uint8Array) ||
186
+ publicKey.length !== KEY_LENGTH ||
187
+ signature.length !== 2 * KEY_LENGTH)
188
+ return false;
189
+ const rBytes = signature.subarray(0, KEY_LENGTH);
190
+ const a = decodePoint(publicKey);
191
+ const r = decodePoint(rBytes);
192
+ if (a === undefined || r === undefined)
193
+ return false;
194
+ const s = bytesToNumberLE(signature.subarray(KEY_LENGTH));
195
+ if (s >= L)
196
+ return false;
197
+ if (a.isSmallOrder() || r.isSmallOrder())
198
+ return false;
199
+ const k = bytesToNumberLE(sha512(concatBytes(rBytes, publicKey, message))) % L;
200
+ return POINT.BASE.multiplyUnsafe(s).equals(r.add(a.multiplyUnsafe(k)));
201
+ }
202
+ catch {
203
+ return false;
204
+ }
205
+ }
206
+ //# sourceMappingURL=keys.js.map
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@openlfcp/crypto",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-rc.1",
4
+ "description": "The cryptography of LFCP (SHA-256, Ed25519, X25519, HKDF, ChaCha20-Poly1305, HPKE) on audited primitives (@noble, hpke).",
5
+ "keywords": [
6
+ "openlfcp",
7
+ "lfcp",
8
+ "local-first",
9
+ "end-to-end-encryption",
10
+ "ed25519",
11
+ "x25519",
12
+ "hpke",
13
+ "chacha20-poly1305",
14
+ "cryptography"
15
+ ],
16
+ "license": "Apache-2.0",
17
+ "homepage": "https://github.com/openlfcp/sdk-ts/tree/main/packages/crypto#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/openlfcp/sdk-ts/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/openlfcp/sdk-ts.git",
24
+ "directory": "packages/crypto"
25
+ },
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=24"
30
+ },
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "!dist/**/*.map",
40
+ "!dist/**/*.tsbuildinfo"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "tag": "next"
45
+ },
46
+ "dependencies": {
47
+ "@noble/ciphers": "^2.4.0",
48
+ "@noble/curves": "^2.4.0",
49
+ "@noble/hashes": "^2.4.0",
50
+ "@panva/hpke-noble": "^1.1.7",
51
+ "hpke": "^1.1.7",
52
+ "@openlfcp/core": "^0.1.0-rc.1"
53
+ }
6
54
  }