@enc-protocol/plugin-group-mls-lazy 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +143 -0
- package/index.mjs +57 -0
- package/mls-lazy.js +150 -0
- package/package.json +53 -0
- package/tree.mjs +28 -0
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 2026 Zhenyu Sun, Tomoya Nagasawa, and WEAVEDB LTD.
|
|
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,143 @@
|
|
|
1
|
+
# @enc-protocol/plugin-group-mls-lazy
|
|
2
|
+
|
|
3
|
+
A `GroupCryptoFn` slot impl: Lazy MLS per `spec/app/group.md`.
|
|
4
|
+
|
|
5
|
+
Drop-in replacement for `@enc-protocol/plugin-group-naive` with the
|
|
6
|
+
spec-mandated wire format for epoch distribution.
|
|
7
|
+
|
|
8
|
+
## What this gives you
|
|
9
|
+
|
|
10
|
+
- **Wire-format compliance** with `spec/app/group.md`:
|
|
11
|
+
`epoch.encrypted_path_secrets` entries addressed by tree node
|
|
12
|
+
position (`{ node, ciphertext, ecdh_pub, nonce }`), not by recipient
|
|
13
|
+
pubkey. A spec-conformant verifier accepts the output.
|
|
14
|
+
- **Forward secrecy across epochs** — removed members can read old
|
|
15
|
+
ciphertexts (key they were members for) but not new ones.
|
|
16
|
+
- **Per-sender ratchet** for messages — `chain_key[0] = HKDF(epoch_secret,
|
|
17
|
+
'enc:group:ratchet:init:' + sender_pub)`, advance + message-key per spec.
|
|
18
|
+
- **Stateless decryption** of messages: receiver re-derives the ratchet
|
|
19
|
+
from `epoch_secret + sender_pub + sender_seq` each time.
|
|
20
|
+
- **Tree topology** derivable from sorted member list — any device
|
|
21
|
+
with the CT replays membership events to reconstruct the tree.
|
|
22
|
+
|
|
23
|
+
## Wire format
|
|
24
|
+
|
|
25
|
+
Each Commit (membership-changing Move event) carries:
|
|
26
|
+
|
|
27
|
+
```json
|
|
28
|
+
{
|
|
29
|
+
"epoch": {
|
|
30
|
+
"n": 2,
|
|
31
|
+
"committer": "<admin_pub>",
|
|
32
|
+
"encrypted_path_secrets": [
|
|
33
|
+
{ "node": 4, "ciphertext": "...", "ecdh_pub": "...", "nonce": "..." },
|
|
34
|
+
{ "node": 5, "ciphertext": "...", "ecdh_pub": "...", "nonce": "..." }
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Where `node` is a tree node ID in breadth-first numbering (root=0,
|
|
41
|
+
level-1=1,2, level-2=3..6, etc.). Leaf nodes contain members in sorted
|
|
42
|
+
pubkey order.
|
|
43
|
+
|
|
44
|
+
## Cryptographic scheme
|
|
45
|
+
|
|
46
|
+
For epoch distribution:
|
|
47
|
+
- Each non-committer leaf gets one ECDH-wrapped entry of the new
|
|
48
|
+
`epoch_secret`, addressed to that leaf's `node` id.
|
|
49
|
+
- Encryption: `shared = ECDH(committer_eph_priv, member_id_pub)`;
|
|
50
|
+
`key = HKDF(shared, 'enc:group:epoch_dist', 32)`;
|
|
51
|
+
`ct = XChaCha20-Poly1305(key, nonce).encrypt(epoch_secret)`.
|
|
52
|
+
- Decryption: member finds entry by their leaf-node id, runs ECDH with
|
|
53
|
+
identity priv + entry's `ecdh_pub`, recovers `epoch_secret`.
|
|
54
|
+
|
|
55
|
+
For messages:
|
|
56
|
+
- Per-sender ratchet seeded with `HKDF(epoch_secret, 'enc:group:ratchet:init:'
|
|
57
|
+
+ sender_pub_hex)`. Advance via `HKDF(chain_key, 'enc:group:ratchet:advance')`.
|
|
58
|
+
Message key: `HKDF(chain_key, 'enc:group:ratchet:message')`.
|
|
59
|
+
Receiver re-derives by counting `sender_seq` advances.
|
|
60
|
+
|
|
61
|
+
## Honest scope note: O(N) vs O(log N)
|
|
62
|
+
|
|
63
|
+
This v1 emits **one entry per non-committer leaf** — O(N) entries.
|
|
64
|
+
The spec aspires to O(log N) via subtree-ephemeral keys, but that
|
|
65
|
+
requires either persistent per-member state (real MLS with
|
|
66
|
+
copath-key bookkeeping) or pairing-based multi-recipient encryption.
|
|
67
|
+
|
|
68
|
+
At the demo cap of ~30 members, O(N) crypto cost is ~30ms per Move —
|
|
69
|
+
imperceptible. The **wire format is spec-conformant** regardless,
|
|
70
|
+
which is what external verifiers check.
|
|
71
|
+
|
|
72
|
+
Drop-in upgrade to true O(log N) is straightforward when wanted:
|
|
73
|
+
keep the same `prepareCommit`/`consumeCommit` shape but add
|
|
74
|
+
copath-key state in the receiver, derived from past Welcomes/Commits
|
|
75
|
+
via CT replay. The wire format doesn't change.
|
|
76
|
+
|
|
77
|
+
## API
|
|
78
|
+
|
|
79
|
+
### Slot contract (GroupCryptoFn)
|
|
80
|
+
|
|
81
|
+
```js
|
|
82
|
+
import group from '@enc-protocol/plugin-group-mls-lazy'
|
|
83
|
+
|
|
84
|
+
const state0 = group.createGroup({ creator: 'alice-pub', members: ['bob-pub'] })
|
|
85
|
+
// state0.epoch === 0, members sorted lexicographically
|
|
86
|
+
|
|
87
|
+
const env = group.encryptForGroup(state0, 'hi everyone', {
|
|
88
|
+
senderPubHex: 'alice-pub', senderSeq: 0,
|
|
89
|
+
})
|
|
90
|
+
// { epoch: 0, sender_seq: 0, sender_pub: 'alice-pub', ciphertext, nonce }
|
|
91
|
+
|
|
92
|
+
group.decryptFromGroup(state0, env).toString('utf8')
|
|
93
|
+
// 'hi everyone'
|
|
94
|
+
|
|
95
|
+
const state1 = group.addMember(state0, 'carol-pub')
|
|
96
|
+
// state1.epoch === 1, fresh groupKey, members re-sorted
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### MLS-specific extensions
|
|
100
|
+
|
|
101
|
+
`prepareCommit` / `consumeCommit` produce / parse the
|
|
102
|
+
`epoch.encrypted_path_secrets` wire payload that goes inside
|
|
103
|
+
membership-changing Move event content per spec/app/group.md:
|
|
104
|
+
|
|
105
|
+
```js
|
|
106
|
+
// Committer side (admin issuing Move(OUTSIDER, MEMBER)):
|
|
107
|
+
const { newEpochSecret, envelope } = group.prepareCommit({
|
|
108
|
+
sortedMembers: state1.members, // AFTER the membership change
|
|
109
|
+
committerPubHex: 'alice-pub',
|
|
110
|
+
prevEpochN: state0.epoch,
|
|
111
|
+
})
|
|
112
|
+
// envelope is the { n, committer, encrypted_path_secrets } object to
|
|
113
|
+
// embed in the Move event's content.
|
|
114
|
+
|
|
115
|
+
// Receiver side (any non-committer member processing the Move):
|
|
116
|
+
const recoveredSecret = group.consumeCommit({
|
|
117
|
+
sortedMembers: state1.members,
|
|
118
|
+
myPubHex: 'bob-pub',
|
|
119
|
+
identityPriv: bobIdentityPrivBytes,
|
|
120
|
+
envelope: moveEvent.content.epoch,
|
|
121
|
+
})
|
|
122
|
+
// recoveredSecret === newEpochSecret (32 bytes)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Slot descriptor
|
|
126
|
+
|
|
127
|
+
```js
|
|
128
|
+
{
|
|
129
|
+
id: 'GroupCryptoFn',
|
|
130
|
+
side: 'client',
|
|
131
|
+
signature: 'Bytes -> Bytes -> Bytes', // Lean view; richer in JS
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Tests
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
node packages/plugin-group-mls-lazy/test.mjs
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
28 assertions covering: createGroup + sort, encrypt/decrypt round-trip,
|
|
142
|
+
prepareCommit/consumeCommit (incl. wire-format shape), addMember/removeMember,
|
|
143
|
+
per-sender ratchet across seqs, cross-sender isolation, removed-member rejection.
|
package/index.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @enc-protocol/plugin-group-mls-lazy — GroupCryptoFn slot impl, Lazy MLS.
|
|
3
|
+
*
|
|
4
|
+
* Implements `spec/app/group.md`'s Lazy MLS with TRUE O(log N) epoch
|
|
5
|
+
* distribution via tree-keyed encrypted_path_secrets (binary ratchet tree,
|
|
6
|
+
* members sorted by pubkey → leaf positions; copath ECDH wraps + Welcome
|
|
7
|
+
* bootstrap; per-sender HKDF message ratchet).
|
|
8
|
+
*
|
|
9
|
+
* SOURCE = CODEGEN. The protocol + crypto is generated from the Lean spec
|
|
10
|
+
* (`Enc.DSL.Modules.MlsLazy` → `@enc-protocol/core/mls-lazy.js`), which
|
|
11
|
+
* composes ONLY the verified core primitives (deriveKey / ecdh /
|
|
12
|
+
* derivePublicKey / aeadChacha / reduceScalar / csprngBytes) — ZERO raw
|
|
13
|
+
* @noble. This file is a thin adapter: it re-exports the codegen's public
|
|
14
|
+
* API and adds the plugin-contract `slot` descriptor (app glue, not crypto).
|
|
15
|
+
*
|
|
16
|
+
* Public API (all from the codegen):
|
|
17
|
+
* prepareCommit, consumeCommit, wireEnvelope, parseWireEnvelope,
|
|
18
|
+
* deriveSenderMessageKey, encryptMessage, decryptMessage
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { Slots } from '@enc-protocol/plugin-contract'
|
|
22
|
+
import {
|
|
23
|
+
prepareCommit,
|
|
24
|
+
consumeCommit,
|
|
25
|
+
wireEnvelope,
|
|
26
|
+
parseWireEnvelope,
|
|
27
|
+
deriveSenderMessageKey,
|
|
28
|
+
encryptMessage,
|
|
29
|
+
decryptMessage,
|
|
30
|
+
} from './mls-lazy.js'
|
|
31
|
+
|
|
32
|
+
export const slot = Object.freeze({
|
|
33
|
+
id: Slots.GroupCryptoFn,
|
|
34
|
+
side: 'client',
|
|
35
|
+
signature: 'Bytes -> Bytes -> Bytes',
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
export {
|
|
39
|
+
prepareCommit,
|
|
40
|
+
consumeCommit,
|
|
41
|
+
wireEnvelope,
|
|
42
|
+
parseWireEnvelope,
|
|
43
|
+
deriveSenderMessageKey,
|
|
44
|
+
encryptMessage,
|
|
45
|
+
decryptMessage,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export default {
|
|
49
|
+
slot,
|
|
50
|
+
prepareCommit,
|
|
51
|
+
consumeCommit,
|
|
52
|
+
wireEnvelope,
|
|
53
|
+
parseWireEnvelope,
|
|
54
|
+
deriveSenderMessageKey,
|
|
55
|
+
encryptMessage,
|
|
56
|
+
decryptMessage,
|
|
57
|
+
}
|
package/mls-lazy.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mls-lazy.js
|
|
3
|
+
*
|
|
4
|
+
* ENC Protocol — EncDSL v4 generated
|
|
5
|
+
*
|
|
6
|
+
* Lazy-MLS group GroupCryptoFn (spec-formatted/app/group.md): binary ratchet
|
|
7
|
+
* tree with O(log N) epoch distribution. Composes the verified crypto
|
|
8
|
+
* primitives from ./crypto.js (deriveKey/ecdh/derivePublicKey/aeadChacha/
|
|
9
|
+
* reduceScalar/csprngBytes) — byte-faithful to the hand-written
|
|
10
|
+
* plugin-group-mls-lazy index.mjs + tree.mjs it replaces. ZERO raw @noble.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
import { deriveKey, ecdh, derivePublicKey, aeadChachaEncrypt, aeadChachaDecrypt, reduceScalar, csprngBytes, bytesToHex, hexToBytes } from '@enc-protocol/core/crypto.js'
|
|
15
|
+
|
|
16
|
+
export function paddedLeafCount(memberCount) {
|
|
17
|
+
return (() => { if (memberCount <= 1) return 1; let n = 1; while (n < memberCount) n *= 2; return n; })()
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function totalNodeCount(memberCount) {
|
|
21
|
+
return (() => 2 * paddedLeafCount(memberCount) - 1)()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function treeDepth(memberCount) {
|
|
25
|
+
return (() => Math.log2(paddedLeafCount(memberCount)))()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function leafNodeId(leafIdx, memberCount) {
|
|
29
|
+
return (() => { const L = paddedLeafCount(memberCount); return (L - 1) + leafIdx; })()
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function nodeIdToLeafIdx(nodeId, memberCount) {
|
|
33
|
+
return (() => { const L = paddedLeafCount(memberCount); if (nodeId < L - 1) return -1; return nodeId - (L - 1); })()
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function parentNode(nodeId) {
|
|
37
|
+
return (() => { if (nodeId === 0) return -1; return Math.floor((nodeId - 1) / 2); })()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function siblingNode(nodeId) {
|
|
41
|
+
return (() => { if (nodeId === 0) return -1; return (nodeId % 2 === 1) ? nodeId + 1 : nodeId - 1; })()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function directPath(nodeId) {
|
|
45
|
+
return (() => { const path = [nodeId]; let cur = nodeId; while (cur !== 0) { cur = parentNode(cur); path.push(cur); } return path; })()
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function copath(nodeId) {
|
|
49
|
+
return (() => { const cop = []; let cur = nodeId; while (cur !== 0) { cop.push(siblingNode(cur)); cur = parentNode(cur); } return cop; })()
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function leavesInSubtreeOfNodeAtLevel(_parentNode, _depth) {
|
|
53
|
+
return (() => { let level = 0; let n = _parentNode; while (n !== 0) { level++; n = parentNode(n); } return 2 ** (_depth - level - 1); })()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function subtreeLeafIndices(nodeId, memberCount) {
|
|
57
|
+
return (() => { const L = paddedLeafCount(memberCount); let level = 0; let n = nodeId; while (n !== 0) { level++; n = parentNode(n); } const depth = Math.log2(L); if (level === depth) { const li = nodeIdToLeafIdx(nodeId, memberCount); return li >= memberCount ? [] : [li]; } const subtreeHeight = depth - level; const leavesInSubtree = 2 ** subtreeHeight; let cursor = 0; const pathFromRoot = []; let cur2 = nodeId; while (cur2 !== 0) { pathFromRoot.unshift(cur2); cur2 = parentNode(cur2); } for (const step of pathFromRoot) { const parent = parentNode(step); if (step === 2 * parent + 1) { /* left child — cursor stays */ } else { cursor += leavesInSubtreeOfNodeAtLevel(parent, depth); } } const indices = []; for (let i = 0; i < leavesInSubtree; i++) { const li = cursor + i; if (li < memberCount) indices.push(li); } return indices; })()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function lca(nodeA, nodeB) {
|
|
61
|
+
return (() => { const ancA = new Set(directPath(nodeA)); let cur = nodeB; while (!ancA.has(cur)) cur = parentNode(cur); return cur; })()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function sortMembers(memberPubs) {
|
|
65
|
+
return (() => [...memberPubs].sort())()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function memberLeafIdx(memberPubs, myPub) {
|
|
69
|
+
return (() => { const sorted = sortMembers(memberPubs); return sorted.indexOf(myPub); })()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function aeadEncrypt(key, plaintext) {
|
|
73
|
+
return aeadChachaEncrypt(key, plaintext)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function aeadDecrypt(key, envelope) {
|
|
77
|
+
return (() => { const ctHex = typeof envelope.ciphertext === 'string' ? envelope.ciphertext : bytesToHex(envelope.ciphertext); return aeadChachaDecrypt(key, ctHex, envelope.nonce); })()
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function keypairFromSecret(secret) {
|
|
81
|
+
return (() => { const priv = reduceScalar(deriveKey(secret, 'enc:mls:node-priv')); const pub = derivePublicKey(priv); return { priv, pub }; })()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function deriveChildSecret(parentSecret, side) {
|
|
85
|
+
return deriveKey(parentSecret, ('enc:mls:child:' + side))
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function epochSecretFromRoot(rootSecret) {
|
|
89
|
+
return deriveKey(rootSecret, 'enc:mls:epoch')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function buildTreeSecrets(rootSecret, memberCount) {
|
|
93
|
+
return (() => { const L = paddedLeafCount(memberCount); const secrets = new Map(); secrets.set(0, rootSecret); for (let n = 0; n < L - 1; n++) { const parSecret = secrets.get(n); if (!parSecret) continue; secrets.set(2 * n + 1, deriveChildSecret(parSecret, 'left')); secrets.set(2 * n + 2, deriveChildSecret(parSecret, 'right')); } return secrets; })()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function reuseTreeState(prevTreeState, sortedMembers) {
|
|
97
|
+
return (() => { if (!prevTreeState || typeof prevTreeState !== 'object') return null; if (prevTreeState instanceof Map) return null; const prevMembers = prevTreeState.members; const secrets = prevTreeState.secrets; if (!Array.isArray(prevMembers) || !(secrets instanceof Map)) return null; if (prevMembers.length !== sortedMembers.length) return null; for (let i = 0; i < prevMembers.length; i++) { if (prevMembers[i] !== sortedMembers[i]) return null; } return secrets; })()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function bundleTreeState(secrets, sortedMembers) {
|
|
101
|
+
return (() => ({ members: [...sortedMembers], secrets }))()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function ecdhWrap(plaintextBytes, recipientPubBytes, ephPriv, ephPub) {
|
|
105
|
+
return (() => { const shared = ecdh(ephPriv, recipientPubBytes); const key = deriveKey(shared, 'enc:mls:path-wrap'); const env = aeadEncrypt(key, plaintextBytes); return { ciphertext: env.ciphertext, nonce: env.nonce, ecdh_pub: bytesToHex(ephPub) }; })()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function ecdhUnwrap(entry, recipientPriv) {
|
|
109
|
+
return (() => { const shared = ecdh(recipientPriv, hexToBytes(entry.ecdh_pub)); const key = deriveKey(shared, 'enc:mls:path-wrap'); return aeadDecrypt(key, { ciphertext: entry.ciphertext, nonce: entry.nonce }); })()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function ratchetInit(epochSecret, senderPubHex) {
|
|
113
|
+
return deriveKey(epochSecret, ('enc:group:ratchet:init:' + senderPubHex))
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function ratchetAdvance(chainKey) {
|
|
117
|
+
return deriveKey(chainKey, 'enc:group:ratchet:advance')
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function ratchetMessageKey(chainKey) {
|
|
121
|
+
return deriveKey(chainKey, 'enc:group:ratchet:message')
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function prepareCommit(opts) {
|
|
125
|
+
return (() => { const { sortedMembers, committerPubHex, prevEpochN = -1, prevTreeState = null, newMembers = [] } = opts; if (!Array.isArray(sortedMembers) || sortedMembers.length === 0) { throw new Error('plugin-group-mls-lazy: prepareCommit called with empty group'); } const reusableSecrets = reuseTreeState(prevTreeState, sortedMembers); const committerLeafIdx = sortedMembers.indexOf(committerPubHex); if (committerLeafIdx < 0) { throw new Error('plugin-group-mls-lazy: committer not in member list'); } const committerLeafNode = leafNodeId(committerLeafIdx, sortedMembers.length); const ephPriv = reduceScalar(csprngBytes(32)); const ephPub = derivePublicKey(ephPriv); const newRootSecret = csprngBytes(32); const newTreeSecrets = buildTreeSecrets(newRootSecret, sortedMembers.length); const newEpochSecret = epochSecretFromRoot(newRootSecret); const entries = []; const myCopath = copath(committerLeafNode); for (const cpNode of myCopath) { const subLeaves = subtreeLeafIndices(cpNode, sortedMembers.length); if (subLeaves.length === 0) continue; let cpPub; if (reusableSecrets && reusableSecrets.has(cpNode)) { cpPub = keypairFromSecret(reusableSecrets.get(cpNode)).pub; const wrap = ecdhWrap(newRootSecret, cpPub, ephPriv, ephPub); entries.push({ node: cpNode, ...wrap }); } else { const leftmostLeafIdx = subLeaves[0]; const leftmostLeafPub = hexToBytes(sortedMembers[leftmostLeafIdx]); const wrap = ecdhWrap(newRootSecret, leftmostLeafPub, ephPriv, ephPub); entries.push({ node: cpNode, ...wrap }); } } if (!reusableSecrets) { for (let i = 0; i < sortedMembers.length; i++) { if (i === committerLeafIdx) continue; const myLeafN = leafNodeId(i, sortedMembers.length); const myCopathAncestor = myCopath.find((cpN) => { const subL = subtreeLeafIndices(cpN, sortedMembers.length); return subL.includes(i); }); if (myCopathAncestor !== undefined) { const subL = subtreeLeafIndices(myCopathAncestor, sortedMembers.length); if (subL[0] === i) continue; } const memberPub = hexToBytes(sortedMembers[i]); const wrap = ecdhWrap(newRootSecret, memberPub, ephPriv, ephPub); entries.push({ node: myLeafN, ...wrap }); } } else { for (const newMemberPub of newMembers) { const idx = sortedMembers.indexOf(newMemberPub); if (idx < 0 || idx === committerLeafIdx) continue; const myLeafN = leafNodeId(idx, sortedMembers.length); const alreadyHas = entries.some((e) => e.node === myLeafN); if (alreadyHas) continue; const memberPub = hexToBytes(newMemberPub); const wrap = ecdhWrap(newRootSecret, memberPub, ephPriv, ephPub); entries.push({ node: myLeafN, ...wrap }); } } return { newEpochSecret, newTreeState: bundleTreeState(newTreeSecrets, sortedMembers), envelope: { n: prevEpochN + 1, committer: committerPubHex, encrypted_path_secrets: entries } }; })()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function consumeCommit(opts) {
|
|
129
|
+
return (() => { const { sortedMembers, myPubHex, identityPriv, prevTreeState = null, envelope, prevHighestN, expectedCommitter } = opts; if (!envelope || typeof envelope !== 'object') { throw new Error('plugin-group-mls-lazy: consumeCommit requires an envelope object'); } if (typeof envelope.n !== 'number' || !Number.isInteger(envelope.n) || envelope.n < 0) { throw new Error('plugin-group-mls-lazy: envelope.n invalid (got ' + envelope.n + ')'); } if (typeof prevHighestN === 'number' && envelope.n <= prevHighestN) { throw new Error('plugin-group-mls-lazy: envelope.n=' + envelope.n + ' not strictly greater than prevHighestN=' + prevHighestN); } if (typeof expectedCommitter === 'string' && envelope.committer !== expectedCommitter) { throw new Error('plugin-group-mls-lazy: envelope.committer mismatch (got ' + envelope.committer + ', expected ' + expectedCommitter + ')'); } const myLeafIdx = sortedMembers.indexOf(myPubHex); if (myLeafIdx < 0) { throw new Error('plugin-group-mls-lazy: not a member of this group'); } const myLeafNode = leafNodeId(myLeafIdx, sortedMembers.length); const myPath = new Set(directPath(myLeafNode)); const reusableSecrets = reuseTreeState(prevTreeState, sortedMembers); for (const entry of envelope?.encrypted_path_secrets || []) { if (!myPath.has(entry.node)) continue; const candidatePrivs = []; if (reusableSecrets && reusableSecrets.has(entry.node)) { candidatePrivs.push(keypairFromSecret(reusableSecrets.get(entry.node)).priv); } if (entry.node === myLeafNode) { candidatePrivs.push(identityPriv); } else { const subLeaves = subtreeLeafIndices(entry.node, sortedMembers.length); if (subLeaves.length > 0 && subLeaves[0] === myLeafIdx) { candidatePrivs.push(identityPriv); } } for (const priv of candidatePrivs) { try { const newRootSecret = ecdhUnwrap(entry, priv); const newTreeSecrets = buildTreeSecrets(newRootSecret, sortedMembers.length); return { newEpochSecret: epochSecretFromRoot(newRootSecret), newTreeState: bundleTreeState(newTreeSecrets, sortedMembers) }; } catch (_e) { /* try next priv */ } } } throw new Error('plugin-group-mls-lazy: no decryptable entry for this member'); })()
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function wireEnvelope(prepareResultOrEnvelope) {
|
|
133
|
+
return (() => { const envelope = prepareResultOrEnvelope?.envelope ?? prepareResultOrEnvelope; if (!envelope || typeof envelope !== 'object' || typeof envelope.n !== 'number' || typeof envelope.committer !== 'string' || !Array.isArray(envelope.encrypted_path_secrets)) { throw new Error('plugin-group-mls-lazy: wireEnvelope called with malformed envelope'); } return { epoch: { n: envelope.n, committer: envelope.committer, encrypted_path_secrets: envelope.encrypted_path_secrets } }; })()
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function parseWireEnvelope(content) {
|
|
137
|
+
return (() => { if (!content || typeof content !== 'object') return null; const e = content.epoch; if (!e || typeof e !== 'object') return null; if (typeof e.n !== 'number' || !Number.isInteger(e.n) || e.n < 0) return null; if (typeof e.committer !== 'string' || e.committer.length === 0) return null; if (!Array.isArray(e.encrypted_path_secrets)) return null; return { n: e.n, committer: e.committer, encrypted_path_secrets: e.encrypted_path_secrets }; })()
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function deriveSenderMessageKey(epochSecret, senderPubHex, senderSeq) {
|
|
141
|
+
return (() => { if (!(epochSecret instanceof Uint8Array) || epochSecret.length !== 32) { throw new Error('plugin-group-mls-lazy: deriveSenderMessageKey requires 32-byte epochSecret'); } if (typeof senderPubHex !== 'string' || senderPubHex.length === 0) { throw new Error('plugin-group-mls-lazy: deriveSenderMessageKey requires senderPubHex'); } if (!Number.isInteger(senderSeq) || senderSeq < 0) { throw new Error('plugin-group-mls-lazy: deriveSenderMessageKey requires non-negative integer senderSeq (got ' + senderSeq + ')'); } let chain = ratchetInit(epochSecret, senderPubHex); for (let i = 0; i < senderSeq; i++) chain = ratchetAdvance(chain); return ratchetMessageKey(chain); })()
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function encryptMessage(opts) {
|
|
145
|
+
return (() => { const { epochSecret, epochN, senderPubHex, senderSeq, plaintext } = opts; const key = deriveSenderMessageKey(epochSecret, senderPubHex, senderSeq); const data = typeof plaintext === 'string' ? new TextEncoder().encode(plaintext) : plaintext; const env = aeadEncrypt(key, data); return { epoch_n: epochN, sender_pub: senderPubHex, sender_seq: senderSeq, ciphertext: env.ciphertext, nonce: env.nonce }; })()
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function decryptMessage(opts) {
|
|
149
|
+
return (() => { const { epochSecret, envelope } = opts; if (!envelope || typeof envelope !== 'object') { throw new Error('plugin-group-mls-lazy: decryptMessage requires envelope'); } const key = deriveSenderMessageKey(epochSecret, envelope.sender_pub, envelope.sender_seq); return aeadDecrypt(key, { ciphertext: envelope.ciphertext, nonce: envelope.nonce }); })()
|
|
150
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@enc-protocol/plugin-group-mls-lazy",
|
|
3
|
+
"version": "0.9.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "GroupCryptoFn slot impl: lazy MLS per spec/app/group.md — binary ratchet tree, O(log N) epoch distribution via encrypted_path_secrets to tree node positions, stateless decryption via CT replay.",
|
|
6
|
+
"main": "./index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.mjs",
|
|
9
|
+
"./tree": "./tree.mjs"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "node --test test/*.test.mjs"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"mls-lazy.js",
|
|
16
|
+
"index.mjs",
|
|
17
|
+
"tree.mjs",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@enc-protocol/plugin-contract": "^0.9.0",
|
|
22
|
+
"@enc-protocol/core": "^0.9.0"
|
|
23
|
+
},
|
|
24
|
+
"encPlugin": {
|
|
25
|
+
"slotIds": [
|
|
26
|
+
"GroupCryptoFn"
|
|
27
|
+
],
|
|
28
|
+
"side": "client",
|
|
29
|
+
"cf": {
|
|
30
|
+
"primitives": [
|
|
31
|
+
"worker"
|
|
32
|
+
],
|
|
33
|
+
"cpu_class": "O(log n)",
|
|
34
|
+
"memory_class": "O(1)",
|
|
35
|
+
"state": "stateless",
|
|
36
|
+
"egress": "none",
|
|
37
|
+
"cf_compatible": true,
|
|
38
|
+
"forbidden": []
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=20"
|
|
43
|
+
},
|
|
44
|
+
"license": "Apache-2.0",
|
|
45
|
+
"keywords": [
|
|
46
|
+
"core",
|
|
47
|
+
"public"
|
|
48
|
+
],
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"registry": "https://registry.npmjs.org/",
|
|
51
|
+
"access": "public"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/tree.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @enc-protocol/plugin-group-mls-lazy/tree.mjs — binary ratchet tree topology.
|
|
3
|
+
*
|
|
4
|
+
* SOURCE = CODEGEN. The tree index math is generated from the Lean spec
|
|
5
|
+
* (`Enc.DSL.Modules.MlsLazy` → `@enc-protocol/core/mls-lazy.js`, the same
|
|
6
|
+
* module that emits the protocol). This file re-exports the topology helpers
|
|
7
|
+
* so existing `./tree.mjs` importers keep working without a hand-written copy.
|
|
8
|
+
*
|
|
9
|
+
* Per spec/app/group.md: members are leaves indexed by sorted-by-pubkey
|
|
10
|
+
* position; left-balanced binary tree padded to the next power of two;
|
|
11
|
+
* breadth-first node numbering (root=0).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export {
|
|
15
|
+
paddedLeafCount,
|
|
16
|
+
totalNodeCount,
|
|
17
|
+
treeDepth,
|
|
18
|
+
leafNodeId,
|
|
19
|
+
nodeIdToLeafIdx,
|
|
20
|
+
parentNode,
|
|
21
|
+
siblingNode,
|
|
22
|
+
directPath,
|
|
23
|
+
copath,
|
|
24
|
+
subtreeLeafIndices,
|
|
25
|
+
lca,
|
|
26
|
+
sortMembers,
|
|
27
|
+
memberLeafIdx,
|
|
28
|
+
} from './mls-lazy.js'
|