@openlfcp/core 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 ADDED
@@ -0,0 +1,27 @@
1
+ # @openlfcp/core
2
+
3
+ Identifiers, shared protocol types, errors and byte helpers used by every other `@openlfcp/*` package: Resource, Principal, Control Record and Data Unit IDs, uint64 sequences and epochs, `LfcpError` with the LFCP wire codes, hex and base64url helpers.
4
+
5
+ ```sh
6
+ npm install @openlfcp/core@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).
@@ -0,0 +1,18 @@
1
+ /** Lowercase hexadecimal, two digits per byte. */
2
+ export declare function toHex(bytes: Uint8Array): string;
3
+ /**
4
+ * Parses lowercase, even-length hexadecimal. Upper case, a `0x` prefix and
5
+ * odd lengths are rejected with `INVALID_HEX`.
6
+ */
7
+ export declare function fromHex(hex: string): Uint8Array;
8
+ /** Unpadded base64url (RFC 4648 §5), the encoding LFCP uses in URIs and references. */
9
+ export declare function toBase64url(bytes: Uint8Array): string;
10
+ /**
11
+ * Parses canonical unpadded base64url. Rejects padding, characters outside
12
+ * the URL-safe alphabet, a length of 1 modulo 4 and non-zero trailing bits,
13
+ * so every byte string has exactly one accepted encoding.
14
+ */
15
+ export declare function fromBase64url(text: string): Uint8Array;
16
+ /** Byte-for-byte equality. Not constant-time: do not use it to compare secrets. */
17
+ export declare function bytesEqual(a: Uint8Array, b: Uint8Array): boolean;
18
+ //# sourceMappingURL=bytes.d.ts.map
package/dist/bytes.js ADDED
@@ -0,0 +1,99 @@
1
+ import { LfcpError } from "./errors.js";
2
+ const HEX = "0123456789abcdef";
3
+ const B64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
4
+ const B64URL_VALUE = new Map([...B64URL].map((c, i) => [c, i]));
5
+ /** Lowercase hexadecimal, two digits per byte. */
6
+ export function toHex(bytes) {
7
+ let out = "";
8
+ for (const b of bytes)
9
+ out += HEX.charAt(b >> 4) + HEX.charAt(b & 0x0f);
10
+ return out;
11
+ }
12
+ /**
13
+ * Parses lowercase, even-length hexadecimal. Upper case, a `0x` prefix and
14
+ * odd lengths are rejected with `INVALID_HEX`.
15
+ */
16
+ export function fromHex(hex) {
17
+ if (!/^(?:[0-9a-f]{2})*$/.test(hex)) {
18
+ throw new LfcpError("INVALID_HEX", "expected lowercase hexadecimal with an even number of digits");
19
+ }
20
+ const out = new Uint8Array(hex.length / 2);
21
+ for (let i = 0; i < out.length; i += 1)
22
+ out[i] = Number.parseInt(hex.slice(2 * i, 2 * i + 2), 16);
23
+ return out;
24
+ }
25
+ /** Unpadded base64url (RFC 4648 §5), the encoding LFCP uses in URIs and references. */
26
+ export function toBase64url(bytes) {
27
+ let out = "";
28
+ let i = 0;
29
+ for (; i + 3 <= bytes.length; i += 3) {
30
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
31
+ out +=
32
+ B64URL.charAt(n >> 18) +
33
+ B64URL.charAt((n >> 12) & 63) +
34
+ B64URL.charAt((n >> 6) & 63) +
35
+ B64URL.charAt(n & 63);
36
+ }
37
+ const rest = bytes.length - i;
38
+ if (rest === 1) {
39
+ const n = bytes[i] << 16;
40
+ out += B64URL.charAt(n >> 18) + B64URL.charAt((n >> 12) & 63);
41
+ }
42
+ else if (rest === 2) {
43
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
44
+ out += B64URL.charAt(n >> 18) + B64URL.charAt((n >> 12) & 63) + B64URL.charAt((n >> 6) & 63);
45
+ }
46
+ return out;
47
+ }
48
+ /**
49
+ * Parses canonical unpadded base64url. Rejects padding, characters outside
50
+ * the URL-safe alphabet, a length of 1 modulo 4 and non-zero trailing bits,
51
+ * so every byte string has exactly one accepted encoding.
52
+ */
53
+ export function fromBase64url(text) {
54
+ const fail = (why) => {
55
+ throw new LfcpError("INVALID_BASE64URL", `not canonical unpadded base64url: ${why}`);
56
+ };
57
+ const rem = text.length % 4;
58
+ if (rem === 1)
59
+ fail("length is 1 modulo 4");
60
+ const values = [];
61
+ // The input may be a secret (a stored key, an invitation fragment): an
62
+ // error names the position of a bad character, never the character.
63
+ let i = 0;
64
+ for (const c of text) {
65
+ const v = B64URL_VALUE.get(c);
66
+ if (v === undefined)
67
+ fail(c === "=" ? "padding is not allowed" : `a character outside the alphabet at ${i}`);
68
+ values.push(v);
69
+ i += 1;
70
+ }
71
+ // The last character of a 2- or 3-character group carries 4 or 2 bits that
72
+ // are not part of any byte; they must be zero (RFC 4648 §3.5).
73
+ const last = values[values.length - 1] ?? 0;
74
+ if ((rem === 2 && (last & 0x0f) !== 0) || (rem === 3 && (last & 0x03) !== 0))
75
+ fail("non-zero trailing bits");
76
+ const out = new Uint8Array((values.length * 6) >> 3);
77
+ let acc = 0;
78
+ let bits = 0;
79
+ let o = 0;
80
+ for (const v of values) {
81
+ acc = ((acc << 6) | v) & 0xffff;
82
+ bits += 6;
83
+ if (bits >= 8) {
84
+ bits -= 8;
85
+ out[o++] = (acc >> bits) & 0xff;
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+ /** Byte-for-byte equality. Not constant-time: do not use it to compare secrets. */
91
+ export function bytesEqual(a, b) {
92
+ if (a.length !== b.length)
93
+ return false;
94
+ for (let i = 0; i < a.length; i += 1)
95
+ if (a[i] !== b[i])
96
+ return false;
97
+ return true;
98
+ }
99
+ //# sourceMappingURL=bytes.js.map
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Validation codes raised by the SDK while checking local input.
3
+ *
4
+ * These are SDK-internal codes, not the LFCP-WIRE-01 §62 wire error codes
5
+ * that are sent in NACK and ERROR messages. At the wire boundary, every
6
+ * `CBOR_*` failure of a received persistent object surfaces as
7
+ * `MALFORMED_MESSAGE` (LFCP-WIRE-01 §5.2).
8
+ */
9
+ export type LfcpErrorCode = "INVALID_LENGTH" | "INVALID_HEX" | "INVALID_BASE64URL" | "INVALID_UUIDV7" | "NO_SECURE_RANDOM"
10
+ /** Valid CBOR, but not the deterministic encoding (non-shortest head, unsorted map keys). */
11
+ | "CBOR_NON_CANONICAL"
12
+ /** A map contains the same key twice. */
13
+ | "CBOR_DUPLICATE_KEY"
14
+ /** An indefinite-length item or a break code. */
15
+ | "CBOR_INDEFINITE_LENGTH"
16
+ /** A type LFCP does not use: tags, floats, undefined, other simple values, reserved encodings, unsupported JS values. */
17
+ | "CBOR_UNSUPPORTED_TYPE"
18
+ /** An integer outside the CBOR range -2^64 .. 2^64-1, or an unsafe JS number. */
19
+ | "CBOR_OUT_OF_RANGE"
20
+ /** The input ends inside an item. */
21
+ | "CBOR_TRUNCATED"
22
+ /** Bytes remain after the single top-level item. */
23
+ | "CBOR_TRAILING_BYTES"
24
+ /** A text string that is not well-formed UTF-8 (or a JS string with lone surrogates). */
25
+ | "CBOR_INVALID_UTF8"
26
+ /** Nesting deeper than the SDK's safety limit. */
27
+ | "CBOR_TOO_DEEP"
28
+ /** A cryptographic operation failed (e.g. a low-order X25519 public key). Never carries key bytes. */
29
+ | "CRYPTO_FAILURE"
30
+ /** A Principal Descriptor has the wrong shape, field set, key lengths or encoding (LFCP-WIRE-01 §7). */
31
+ | "INVALID_PRINCIPAL_DESCRIPTOR"
32
+ /** A Principal Descriptor's ID is not the §7 hash of its public keys. */
33
+ | "PRINCIPAL_ID_MISMATCH"
34
+ /**
35
+ * A signed object is not the canonical LFCP COSE_Sign1 shape (LFCP-WIRE-01 §10):
36
+ * tagged, wrong arity, extra or missing protected parameters, non-empty
37
+ * unprotected header, detached payload or a non-64-byte signature. Surfaces
38
+ * on the wire as MALFORMED_MESSAGE.
39
+ */
40
+ | "COSE_MALFORMED"
41
+ /** The signing key does not belong to the Principal Descriptor it is used with. */
42
+ | "COSE_SIGNER_MISMATCH"
43
+ /**
44
+ * Deterministic CBOR that does not have the structure a Wire rule requires:
45
+ * wrong field set, field type or byte-string length, or a broken structural
46
+ * rule (actor sequence 0 §8, a non-canonical actor-have or frontier §28.1,
47
+ * §28.2, Genesis not at control_seq 0 with a null link §13.1). Surfaces on
48
+ * the wire as MALFORMED_MESSAGE.
49
+ */
50
+ | "INVALID_STRUCTURE"
51
+ /**
52
+ * A well-formed value that LFCP reserves but this version does not define:
53
+ * a core Control Record type 9–31. §14: "Unknown core Control Record types
54
+ * MUST cause validation failure, with INVALID_CONTROL_CHAIN."
55
+ */
56
+ | "UNSUPPORTED_VALUE"
57
+ /**
58
+ * An integer outside the range a construction requires: a Data Epoch or
59
+ * uint64 value outside 0..2^64-1, an actor sequence outside 1..2^64-1, or
60
+ * a number that is not a safe integer. Values are never truncated.
61
+ * SDK-local; decoded wire values are range-checked by the decoders.
62
+ */
63
+ | "OUT_OF_RANGE"
64
+ /**
65
+ * A local attempt to use an actor sequence twice for one (Resource,
66
+ * Principal) (LFCP-WIRE-01 §8, §12: nonce reuse). SDK-local; never sent.
67
+ */
68
+ | "SEQUENCE_REUSE"
69
+ /**
70
+ * A local transaction that would produce a Shared Objects change over the
71
+ * change expansion limits (SHARED-OBJECTS-PROFILE-01 §11.1). Nothing was
72
+ * written; the application splits the transaction (§12). SDK-local.
73
+ */
74
+ | "CHANGE_TOO_LARGE"
75
+ /**
76
+ * A Control Chain that is not one valid linear chain (LFCP-WIRE-01 §13,
77
+ * §13.1): no Genesis, a sequence that is not previous + 1, a link that is
78
+ * not the previous record ID, a different Resource, or a record that
79
+ * links to nothing. INVALID_CONTROL_CHAIN on the wire (§13.1).
80
+ */
81
+ | "INVALID_CONTROL_CHAIN"
82
+ /**
83
+ * A record whose issuer cannot be resolved to a Principal Descriptor, or
84
+ * an object that references a Control Head the receiver does not have.
85
+ * MISSING_DEPENDENCY on the wire (§13.1); the receiver may fetch and retry.
86
+ */
87
+ | "MISSING_DEPENDENCY"
88
+ /**
89
+ * Something this implementation does not support by scope: a Control
90
+ * Chain containing a Coordinator Recovery (7) or Resource Tombstone (8)
91
+ * record (MVP-0.1-PROTOCOL-SCOPE §4, DV1). PROTOCOL_UNSUPPORTED on the wire.
92
+ */
93
+ | "PROTOCOL_UNSUPPORTED"
94
+ /** A signed object whose kid or signature is wrong for its expected signer (G1/N2). INVALID_SIGNATURE on the wire. */
95
+ | "INVALID_SIGNATURE"
96
+ /** A record the authorization policy (LFCP-021) refuses. AUTHORIZATION_FAILED on the wire. */
97
+ | "AUTHORIZATION_FAILED"
98
+ /**
99
+ * Shared Objects state that violates SHARED-OBJECTS-PROFILE-01 (§74.1):
100
+ * reported with one §74.1 diagnostic per failure. A profile-level code,
101
+ * never an LFCP Wire error code.
102
+ */
103
+ | "PROFILE_INVALID"
104
+ /**
105
+ * A Resource whose Data Profile this client does not implement (§27):
106
+ * its plaintext is never applied. PROFILE_UNSUPPORTED on the wire (§62).
107
+ */
108
+ | "PROFILE_UNSUPPORTED"
109
+ /**
110
+ * Two concurrent Shared Objects under one Object ID (SHARED-OBJECTS-
111
+ * PROFILE-01 §21). A profile error of its own, not PROFILE_INVALID.
112
+ */
113
+ | "OBJECT_ID_COLLISION"
114
+ /**
115
+ * A received second, different change or unit for one (resource, actor,
116
+ * sequence) (§26.2). ACTOR_EQUIVOCATION on the wire (§62). A local attempt
117
+ * to reuse a sequence is SEQUENCE_REUSE instead.
118
+ */
119
+ | "ACTOR_EQUIVOCATION"
120
+ /**
121
+ * The keys given to open a Key Package are not those of the Principal it
122
+ * names (§25: recipient binding). Client-local, no wire code (ADR 0001 N5).
123
+ */
124
+ | "KEY_PACKAGE_RECIPIENT_MISMATCH"
125
+ /** An LFCP message above the size limit in force (§31). MESSAGE_TOO_LARGE on the wire. */
126
+ | "MESSAGE_TOO_LARGE"
127
+ /** A Data Profile codec used with a Resource of another data_profile (§15, §27). SDK-local misuse. */
128
+ | "DATA_PROFILE_MISMATCH"
129
+ /**
130
+ * A Data Unit that fails ChaCha20-Poly1305 authentication (§26.3). Only a
131
+ * client holding the DEK detects it; client-local, no wire code (ADR 0001 N3).
132
+ */
133
+ | "AEAD_AUTHENTICATION_FAILED"
134
+ /** A Key Package does not open (HPKE failure). Client-local, no wire code (N5). */
135
+ | "KEY_PACKAGE_OPEN_FAILED"
136
+ /**
137
+ * An opened DEK does not match the epoch's DEK commitment, or the
138
+ * plaintext is not 32 bytes (§25.2). Client-local, no wire code (N5).
139
+ */
140
+ | "DEK_COMMITMENT_MISMATCH"
141
+ /**
142
+ * An invitation URI or invitation secret that is not the §18.2 form, or
143
+ * a secret whose recomputed Invitation Principal is not the subject of
144
+ * the referenced invitation grant. Client-local, never sent.
145
+ */
146
+ | "INVALID_INVITATION";
147
+ /** Error with a stable machine-readable `code`; the message is for humans only. */
148
+ export declare class LfcpError extends Error {
149
+ readonly code: LfcpErrorCode;
150
+ constructor(code: LfcpErrorCode, message: string);
151
+ }
152
+ //# sourceMappingURL=errors.d.ts.map
package/dist/errors.js ADDED
@@ -0,0 +1,10 @@
1
+ /** Error with a stable machine-readable `code`; the message is for humans only. */
2
+ export class LfcpError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = "LfcpError";
7
+ this.code = code;
8
+ }
9
+ }
10
+ //# sourceMappingURL=errors.js.map
package/dist/ids.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 32-byte LFCP identifiers, as raw bytes.
3
+ *
4
+ * Each kind is a distinct branded Uint8Array, so one kind cannot be passed
5
+ * where another is expected. The constructors check the length and copy the
6
+ * input, so later writes to the caller's buffer cannot change a validated
7
+ * identifier. The returned array is still a Uint8Array: treat it as
8
+ * read-only.
9
+ */
10
+ declare const brand: unique symbol;
11
+ type Id32<Kind extends string> = Uint8Array & {
12
+ readonly [brand]: Kind;
13
+ };
14
+ /** LFCP-WIRE-01 §6: 32 random bytes. */
15
+ export type ResourceId = Id32<"ResourceId">;
16
+ /** LFCP-WIRE-01 §7: SHA-256 over the Principal's public keys (derivation is LFCP-014). */
17
+ export type PrincipalId = Id32<"PrincipalId">;
18
+ /** LFCP-WIRE-01 §5.3: a SHA-256 value encoded as 32 bytes. */
19
+ export type Hash32 = Id32<"Hash32">;
20
+ /** LFCP-WIRE-01 §13, §10.6: SHA-256 of a Control Record's exact COSE_Sign1 bytes. */
21
+ export type ControlRecordId = Id32<"ControlRecordId">;
22
+ /** LFCP-WIRE-01 §26, §10.6: SHA-256 of a Data Unit's exact COSE_Sign1 bytes. */
23
+ export type DataUnitId = Id32<"DataUnitId">;
24
+ export declare const ID32_LENGTH = 32;
25
+ export declare const resourceId: (bytes: Uint8Array) => ResourceId;
26
+ /**
27
+ * A new Resource ID: 32 bytes from the platform CSPRNG (LFCP-WIRE-01 §6).
28
+ * It never encodes a hostname, owner, account, path or time, and nothing
29
+ * derives it from Genesis content.
30
+ */
31
+ export declare const generateResourceId: () => ResourceId;
32
+ export declare const principalId: (bytes: Uint8Array) => PrincipalId;
33
+ export declare const hash32: (bytes: Uint8Array) => Hash32;
34
+ export declare const controlRecordId: (bytes: Uint8Array) => ControlRecordId;
35
+ export declare const dataUnitId: (bytes: Uint8Array) => DataUnitId;
36
+ /** Equality of two identifiers of the same kind. */
37
+ export declare function idEquals<T extends Id32<string>>(a: T, b: T): boolean;
38
+ /**
39
+ * Orders Principal IDs by their raw bytes, compared as unsigned bytes, as
40
+ * LFCP-WIRE-01 §28.2 requires for canonical frontier entries. This is byte
41
+ * order only; it carries no meaning of time, causality or precedence.
42
+ * Returns a negative number, zero or a positive number like Array.sort expects.
43
+ */
44
+ export declare function compareCanonicalFrontierOrder(a: PrincipalId, b: PrincipalId): number;
45
+ export {};
46
+ //# sourceMappingURL=ids.d.ts.map
package/dist/ids.js ADDED
@@ -0,0 +1,41 @@
1
+ import { bytesEqual } from "./bytes.js";
2
+ import { LfcpError } from "./errors.js";
3
+ import { secureRandom } from "./random.js";
4
+ export const ID32_LENGTH = 32;
5
+ function id32(kind, bytes) {
6
+ if (!(bytes instanceof Uint8Array) || bytes.length !== ID32_LENGTH) {
7
+ const got = bytes instanceof Uint8Array ? `${bytes.length} bytes` : typeof bytes;
8
+ throw new LfcpError("INVALID_LENGTH", `${kind} must be exactly ${ID32_LENGTH} bytes, got ${got}`);
9
+ }
10
+ return Uint8Array.from(bytes);
11
+ }
12
+ export const resourceId = (bytes) => id32("ResourceId", bytes);
13
+ /**
14
+ * A new Resource ID: 32 bytes from the platform CSPRNG (LFCP-WIRE-01 §6).
15
+ * It never encodes a hostname, owner, account, path or time, and nothing
16
+ * derives it from Genesis content.
17
+ */
18
+ export const generateResourceId = () => resourceId(secureRandom(ID32_LENGTH));
19
+ export const principalId = (bytes) => id32("PrincipalId", bytes);
20
+ export const hash32 = (bytes) => id32("Hash32", bytes);
21
+ export const controlRecordId = (bytes) => id32("ControlRecordId", bytes);
22
+ export const dataUnitId = (bytes) => id32("DataUnitId", bytes);
23
+ /** Equality of two identifiers of the same kind. */
24
+ export function idEquals(a, b) {
25
+ return bytesEqual(a, b);
26
+ }
27
+ /**
28
+ * Orders Principal IDs by their raw bytes, compared as unsigned bytes, as
29
+ * LFCP-WIRE-01 §28.2 requires for canonical frontier entries. This is byte
30
+ * order only; it carries no meaning of time, causality or precedence.
31
+ * Returns a negative number, zero or a positive number like Array.sort expects.
32
+ */
33
+ export function compareCanonicalFrontierOrder(a, b) {
34
+ for (let i = 0; i < ID32_LENGTH; i += 1) {
35
+ const d = a[i] - b[i];
36
+ if (d !== 0)
37
+ return d;
38
+ }
39
+ return 0;
40
+ }
41
+ //# sourceMappingURL=ids.js.map
@@ -0,0 +1,9 @@
1
+ /** Name of this package. */
2
+ export declare const PACKAGE = "@openlfcp/core";
3
+ export { bytesEqual, fromBase64url, fromHex, toBase64url, toHex } from "./bytes.js";
4
+ export { LfcpError, type LfcpErrorCode } from "./errors.js";
5
+ export { type ControlRecordId, compareCanonicalFrontierOrder, controlRecordId, type DataUnitId, dataUnitId, generateResourceId, type Hash32, hash32, ID32_LENGTH, idEquals, type PrincipalId, principalId, type ResourceId, resourceId, } from "./ids.js";
6
+ export { formatObjectId, type GenerateObjectIdOptions, generateObjectId, isObjectId, type ObjectId, parseObjectId, } from "./object-id.js";
7
+ export { secureRandom } from "./random.js";
8
+ export { type ActorSequence, actorSequence, type DataEpoch, dataEpoch, UINT64_MAX, uint64BE, } from "./uint64.js";
9
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /** Name of this package. */
2
+ export const PACKAGE = "@openlfcp/core";
3
+ export { bytesEqual, fromBase64url, fromHex, toBase64url, toHex } from "./bytes.js";
4
+ export { LfcpError } from "./errors.js";
5
+ export { compareCanonicalFrontierOrder, controlRecordId, dataUnitId, generateResourceId, hash32, ID32_LENGTH, idEquals, principalId, resourceId, } from "./ids.js";
6
+ export { formatObjectId, generateObjectId, isObjectId, parseObjectId, } from "./object-id.js";
7
+ export { secureRandom } from "./random.js";
8
+ export { actorSequence, dataEpoch, UINT64_MAX, uint64BE, } from "./uint64.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Shared Object ID (SHARED-OBJECTS-PROFILE-01 §19): a UUIDv7 (RFC 9562) in its
3
+ * canonical lowercase hyphenated string form.
4
+ *
5
+ * Object IDs identify objects; they do not order them. The UUIDv7 timestamp
6
+ * and lexical order are NOT LFCP causality, conflict precedence or
7
+ * authorization order, so this module deliberately offers no comparison,
8
+ * sorting or timestamp extraction.
9
+ */
10
+ declare const brand: unique symbol;
11
+ export type ObjectId = string & {
12
+ readonly [brand]: "ObjectId";
13
+ };
14
+ /** True when `text` is a canonical UUIDv7 Object ID. */
15
+ export declare function isObjectId(text: string): text is ObjectId;
16
+ /** Returns `text` as an ObjectId, or throws `INVALID_UUIDV7`. Non-canonical forms (e.g. upper case) are rejected, not normalized. */
17
+ export declare function parseObjectId(text: string): ObjectId;
18
+ /** The canonical string form (Object IDs are stored canonically, so this is the value itself). */
19
+ export declare function formatObjectId(id: ObjectId): string;
20
+ export interface GenerateObjectIdOptions {
21
+ /** Unix time in milliseconds for the 48-bit timestamp; defaults to Date.now(). */
22
+ readonly now?: number;
23
+ /** Source of 10 random bytes; defaults to globalThis.crypto.getRandomValues. */
24
+ readonly random?: (length: number) => Uint8Array;
25
+ }
26
+ /**
27
+ * Generates a new UUIDv7 Object ID (RFC 9562 §5.7): 48-bit Unix millisecond
28
+ * timestamp, version 7, 12 random bits, variant 10, 62 random bits. No
29
+ * within-millisecond counter is kept.
30
+ */
31
+ export declare function generateObjectId(options?: GenerateObjectIdOptions): ObjectId;
32
+ export {};
33
+ //# sourceMappingURL=object-id.d.ts.map
@@ -0,0 +1,44 @@
1
+ import { LfcpError } from "./errors.js";
2
+ import { secureRandom } from "./random.js";
3
+ // Lowercase, standard hyphen positions, version 7, variant bits 10.
4
+ const UUIDV7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
5
+ /** True when `text` is a canonical UUIDv7 Object ID. */
6
+ export function isObjectId(text) {
7
+ return UUIDV7.test(text);
8
+ }
9
+ /** Returns `text` as an ObjectId, or throws `INVALID_UUIDV7`. Non-canonical forms (e.g. upper case) are rejected, not normalized. */
10
+ export function parseObjectId(text) {
11
+ if (!isObjectId(text))
12
+ throw new LfcpError("INVALID_UUIDV7", "not a canonical lowercase UUIDv7");
13
+ return text;
14
+ }
15
+ /** The canonical string form (Object IDs are stored canonically, so this is the value itself). */
16
+ export function formatObjectId(id) {
17
+ return id;
18
+ }
19
+ /**
20
+ * Generates a new UUIDv7 Object ID (RFC 9562 §5.7): 48-bit Unix millisecond
21
+ * timestamp, version 7, 12 random bits, variant 10, 62 random bits. No
22
+ * within-millisecond counter is kept.
23
+ */
24
+ export function generateObjectId(options = {}) {
25
+ const now = options.now ?? Date.now();
26
+ if (!Number.isSafeInteger(now) || now < 0 || now > 0xffff_ffff_ffff) {
27
+ throw new LfcpError("INVALID_UUIDV7", "timestamp must be an integer in [0, 2^48)");
28
+ }
29
+ const rnd = (options.random ?? secureRandom)(10);
30
+ if (rnd.length !== 10)
31
+ throw new LfcpError("INVALID_LENGTH", "random source must return 10 bytes");
32
+ const b = new Uint8Array(16);
33
+ let t = now;
34
+ for (let i = 5; i >= 0; i -= 1) {
35
+ b[i] = t % 256;
36
+ t = Math.floor(t / 256);
37
+ }
38
+ b.set(rnd, 6);
39
+ b[6] = 0x70 | (b[6] & 0x0f);
40
+ b[8] = 0x80 | (b[8] & 0x3f);
41
+ const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
42
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
43
+ }
44
+ //# sourceMappingURL=object-id.js.map
@@ -0,0 +1,3 @@
1
+ /** `length` bytes from the platform CSPRNG (globalThis.crypto.getRandomValues), or NO_SECURE_RANDOM. */
2
+ export declare function secureRandom(length: number): Uint8Array;
3
+ //# sourceMappingURL=random.d.ts.map
package/dist/random.js ADDED
@@ -0,0 +1,10 @@
1
+ import { LfcpError } from "./errors.js";
2
+ /** `length` bytes from the platform CSPRNG (globalThis.crypto.getRandomValues), or NO_SECURE_RANDOM. */
3
+ export function secureRandom(length) {
4
+ const c = globalThis.crypto;
5
+ if (typeof c?.getRandomValues !== "function") {
6
+ throw new LfcpError("NO_SECURE_RANDOM", "globalThis.crypto.getRandomValues is not available");
7
+ }
8
+ return c.getRandomValues(new Uint8Array(length));
9
+ }
10
+ //# sourceMappingURL=random.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Unsigned 64-bit values of LFCP-WIRE-01 as branded bigints.
3
+ *
4
+ * Constructions such as `uint64_be(epoch)` (§11, §12) need the full uint64
5
+ * range, which a JavaScript number cannot hold exactly above 2^53. The
6
+ * constructors accept a bigint or a safe-integer number and reject anything
7
+ * out of range with OUT_OF_RANGE; a value is never truncated or wrapped.
8
+ */
9
+ declare const brand: unique symbol;
10
+ /** A Data Epoch (§11, §19): 0 <= epoch <= 2^64 - 1. */
11
+ export type DataEpoch = bigint & {
12
+ readonly [brand]: "DataEpoch";
13
+ };
14
+ /** A per-(Resource, Principal) actor sequence (§8): 1 <= seq <= 2^64 - 1. */
15
+ export type ActorSequence = bigint & {
16
+ readonly [brand]: "ActorSequence";
17
+ };
18
+ export declare const UINT64_MAX: bigint;
19
+ export declare const dataEpoch: (value: bigint | number) => DataEpoch;
20
+ export declare const actorSequence: (value: bigint | number) => ActorSequence;
21
+ /** `uint64_be(value)`: 8 big-endian bytes; OUT_OF_RANGE outside 0..2^64-1. */
22
+ export declare function uint64BE(value: bigint | number): Uint8Array;
23
+ export {};
24
+ //# sourceMappingURL=uint64.d.ts.map
package/dist/uint64.js ADDED
@@ -0,0 +1,27 @@
1
+ import { LfcpError } from "./errors.js";
2
+ export const UINT64_MAX = 2n ** 64n - 1n;
3
+ function uint(what, value, min) {
4
+ let n;
5
+ if (typeof value === "bigint")
6
+ n = value;
7
+ else if (typeof value === "number" && Number.isSafeInteger(value))
8
+ n = BigInt(value);
9
+ else
10
+ throw new LfcpError("OUT_OF_RANGE", `${what} must be a bigint or a safe integer, got ${typeof value === "number" ? String(value) : typeof value}`);
11
+ if (n < min || n > UINT64_MAX)
12
+ throw new LfcpError("OUT_OF_RANGE", `${what} must be in ${min}..2^64-1, got ${n}`);
13
+ return n;
14
+ }
15
+ export const dataEpoch = (value) => uint("a Data Epoch", value, 0n);
16
+ export const actorSequence = (value) => uint("an actor sequence", value, 1n);
17
+ /** `uint64_be(value)`: 8 big-endian bytes; OUT_OF_RANGE outside 0..2^64-1. */
18
+ export function uint64BE(value) {
19
+ let n = uint("a uint64 value", value, 0n);
20
+ const out = new Uint8Array(8);
21
+ for (let i = 7; i >= 0; i -= 1) {
22
+ out[i] = Number(n & 0xffn);
23
+ n >>= 8n;
24
+ }
25
+ return out;
26
+ }
27
+ //# sourceMappingURL=uint64.js.map
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@openlfcp/core",
3
+ "version": "0.1.0-rc.1",
4
+ "description": "Identifiers, shared protocol types, errors and byte helpers for LFCP.",
5
+ "keywords": [
6
+ "openlfcp",
7
+ "lfcp",
8
+ "local-first",
9
+ "end-to-end-encryption",
10
+ "identifiers",
11
+ "errors",
12
+ "bytes"
13
+ ],
14
+ "license": "Apache-2.0",
15
+ "homepage": "https://github.com/openlfcp/sdk-ts/tree/main/packages/core#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/openlfcp/sdk-ts/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/openlfcp/sdk-ts.git",
22
+ "directory": "packages/core"
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "engines": {
27
+ "node": ">=24"
28
+ },
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "!dist/**/*.map",
38
+ "!dist/**/*.tsbuildinfo"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public",
42
+ "tag": "next"
43
+ }
44
+ }