@kumiai/mls-rpc 0.8.0 → 0.10.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/README.md +146 -24
- package/lib/access.d.ts +17 -0
- package/lib/access.js +47 -0
- package/lib/apply-commit.d.ts +37 -0
- package/lib/apply-commit.js +105 -0
- package/lib/crypto.d.ts +19 -11
- package/lib/crypto.js +138 -58
- package/lib/index.d.ts +4 -2
- package/lib/index.js +4 -2
- package/lib/mls.d.ts +16 -9
- package/lib/mls.js +176 -81
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -17,21 +17,102 @@ depend on both.
|
|
|
17
17
|
|
|
18
18
|
## Exports
|
|
19
19
|
|
|
20
|
-
- `
|
|
21
|
-
|
|
20
|
+
- `simpleHandleAccess({ handle, adopt, persist? })` — serialised access to a live handle; the
|
|
21
|
+
`HandleAccess` type for a host that brings its own.
|
|
22
|
+
- `createGroupCrypto({ access, entryLabel?, runtime?, pending? })` — `GroupCrypto` over that access.
|
|
23
|
+
- `createGroupMLS({ access, identity, entrySlot, recoverySecret? })` — `GroupMLS` over the same
|
|
24
|
+
access.
|
|
25
|
+
- `applyCommit({ handle, commit, entrySlot, ownDID, persist?, ... })` — apply a received Commit inside the host's own
|
|
26
|
+
transaction (see below).
|
|
22
27
|
- `createLedgerEntrySlot()` — the per-commit ledger-entry resolver seam (see below).
|
|
23
|
-
- `
|
|
28
|
+
- `deriveEntryKey`, `sealEntries`, `openEntries`, `ENTRY_SEAL_LABEL` — the ledger-entry seal.
|
|
29
|
+
- `createRecoveryPending`, `deriveRecoverySecret`, `RECOVERY_LABEL` — recovery request keys and the
|
|
30
|
+
default recovery secret.
|
|
24
31
|
|
|
25
|
-
##
|
|
32
|
+
## Share one access instance
|
|
26
33
|
|
|
27
|
-
Both factories take
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
34
|
+
Both factories take the same `access` instance. The adapter reads the current handle through
|
|
35
|
+
`handle: () => GroupHandle`, because authored commits and recovery replace it wholesale. A host
|
|
36
|
+
adopts an authored commit through `access.replace(next)` after acceptance. The adapter saves before
|
|
37
|
+
publishing the replacement and publishes its synchronous epoch hint after a successful save.
|
|
31
38
|
|
|
32
39
|
For a *received* commit there is nothing to adopt: ts-mls's `processMessage` advances the handle in
|
|
33
40
|
place. A host that treated every commit as adopt-later would double-apply received ones.
|
|
34
41
|
|
|
42
|
+
Migrating from 0.9: build one adapter from the old `handle` / `adopt` / `persist` parameters and pass
|
|
43
|
+
it to both factories in their place.
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
const access = simpleHandleAccess({ handle: () => handle, adopt, persist })
|
|
47
|
+
const crypto = createGroupCrypto({ access, pending })
|
|
48
|
+
const mls = createGroupMLS({ access, identity, entrySlot })
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### A host's own `HandleAccess`
|
|
52
|
+
|
|
53
|
+
A host with its own handle store implements the port instead:
|
|
54
|
+
|
|
55
|
+
- `read(fn)` lends the handle for the callback only. `mutate(fn)` serialises with every other
|
|
56
|
+
operation and resolves after the state is stored; `fn`'s `persist` argument goes to
|
|
57
|
+
`processMessage` and `bootstrapLedger`. `replace(next)` stores before publishing. A transactional
|
|
58
|
+
host may restore a fresh handle per mutation, discard it on rollback, and publish on commit.
|
|
59
|
+
- `epoch()` is a synchronous hint. Publish it only after the outermost successful commit, and restore
|
|
60
|
+
it on rollback. No port decision reads it: every one uses an epoch read under the lock.
|
|
61
|
+
- `open(fn, persistOpened)` is the durable open. `fn` stages the open and hands its state and record
|
|
62
|
+
to the callback it is given. A host may capture them, release its lock, and then call
|
|
63
|
+
`persistOpened` to write both in one transaction guarded by the state row's revision, publishing
|
|
64
|
+
the working handle only after that commits, and only if no newer write was published meanwhile.
|
|
65
|
+
On a revision conflict it retries from a fresh handle. Faults from `persistOpened`, from the staging
|
|
66
|
+
callback the adapter hands `fn`, and from anything the adapter raises around `fn` come back as
|
|
67
|
+
`AppFrameStorageError`, which the lane retries.
|
|
68
|
+
|
|
69
|
+
## Durable logged app delivery
|
|
70
|
+
|
|
71
|
+
Pass a `pending` adapter to `createGroupCrypto` to opt in. Its `persistOpened(stagedState, record)`
|
|
72
|
+
must write the encoded post-open `ClientState` as the group's handle state **and** insert the
|
|
73
|
+
`PendingAppFrame` in one atomic transaction. `list()` returns all uncompleted records after a
|
|
74
|
+
restart, ordered by `(frame.segment, frame.position)` by this port. `complete(id)` clears one
|
|
75
|
+
record and resolves for an unknown id. Deduplicate inserts by `record.frame.id`.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
const access = simpleHandleAccess({
|
|
79
|
+
handle: () => handle,
|
|
80
|
+
adopt: (next) => { handle = next },
|
|
81
|
+
persist: (current) => store.save(current),
|
|
82
|
+
})
|
|
83
|
+
const crypto = createGroupCrypto({
|
|
84
|
+
access,
|
|
85
|
+
pending: {
|
|
86
|
+
persistOpened: async (stagedState, record) => {
|
|
87
|
+
await store.transaction(async (tx) => {
|
|
88
|
+
await tx.saveHandleState(groupID, stagedState)
|
|
89
|
+
await tx.insertPendingIfAbsent(record.frame.id, record)
|
|
90
|
+
})
|
|
91
|
+
},
|
|
92
|
+
list: () => store.listPending(groupID),
|
|
93
|
+
complete: (id) => store.completePending(id),
|
|
94
|
+
},
|
|
95
|
+
})
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The example's `saveHandleState` must also enforce the host's save ordering and same-epoch
|
|
99
|
+
monotonic version rule. Saves issued before `persistOpened` must finish before it; a delayed
|
|
100
|
+
older state at the same epoch must be rejected. `persistOpened` runs under the handle mutex and
|
|
101
|
+
the peer's commit mutex: it must not call either object. Never hold a transaction or the sole
|
|
102
|
+
database connection while awaiting a peer or handle call; a handler should commit its own
|
|
103
|
+
transaction before awaiting `commit()` or `dispatch()`. A single-connection host that reverses
|
|
104
|
+
this order can deadlock. Hosts adopting this in Kubun must first remove transaction-then-registry
|
|
105
|
+
waits on paths overlapping app opens and prove the lock order against SQLite.
|
|
106
|
+
|
|
107
|
+
With `pending`, `unwrap(bytes, { expectedAAD, frame })` calls `GroupHandle.decryptStaged` and
|
|
108
|
+
resolves only after the atomic write. A persistence failure becomes `AppFrameStorageError` for
|
|
109
|
+
the RPC lane to retry; an unopenable frame is classified dead. Without `pending`, the adapter saves
|
|
110
|
+
the post-open ratchet state without a pending record, so a crash after `unwrap` and before the
|
|
111
|
+
handler finishes loses that frame: `pending` is the at-least-once path. `frameAAD(bytes)` exposes
|
|
112
|
+
the cleartext AAD as a routing hint. The full `expectedAAD` on open authenticates it.
|
|
113
|
+
The 0.10 app AAD carries version and log intent. Older bare-topic app frames cannot interoperate
|
|
114
|
+
with 0.10 peers. See the `@kumiai/rpc` README for the delivery and retention boundary.
|
|
115
|
+
|
|
35
116
|
## `createLedgerEntrySlot` is mandatory, and must be installed where the handle is built
|
|
36
117
|
|
|
37
118
|
`GroupMLS.processCommit` is handed a `resolveLedgerEntries` scoped to **one** commit's frame — the
|
|
@@ -40,7 +121,7 @@ once, in `GroupOptions`, and offers no way to change it afterwards. So the indir
|
|
|
40
121
|
installed when the group is *built*:
|
|
41
122
|
|
|
42
123
|
```ts
|
|
43
|
-
import { createGroupCrypto, createGroupMLS, createLedgerEntrySlot } from '@kumiai/mls-rpc'
|
|
124
|
+
import { createGroupCrypto, createGroupMLS, createLedgerEntrySlot, simpleHandleAccess } from '@kumiai/mls-rpc'
|
|
44
125
|
|
|
45
126
|
const entrySlot = createLedgerEntrySlot()
|
|
46
127
|
// Every construction site: createGroup / processWelcome / restoreGroup.
|
|
@@ -49,21 +130,65 @@ const { group } = await createGroup(identity, groupID, {
|
|
|
49
130
|
})
|
|
50
131
|
|
|
51
132
|
let handle = group
|
|
52
|
-
const
|
|
53
|
-
const mls = createGroupMLS({
|
|
133
|
+
const access = simpleHandleAccess({
|
|
54
134
|
handle: () => handle,
|
|
55
|
-
adopt: (next) => {
|
|
56
|
-
|
|
57
|
-
|
|
135
|
+
adopt: (next) => { handle = next },
|
|
136
|
+
persist: (current) => store.save(current),
|
|
137
|
+
})
|
|
138
|
+
const crypto = createGroupCrypto({ access })
|
|
139
|
+
const mls = createGroupMLS({
|
|
140
|
+
access,
|
|
58
141
|
identity,
|
|
59
142
|
entrySlot,
|
|
60
|
-
persist: async (current) => await store.save(current),
|
|
61
143
|
})
|
|
62
144
|
```
|
|
63
145
|
|
|
64
146
|
Passing anything else means a commit resolves its entries against whatever resolver the handle
|
|
65
147
|
happened to be born with.
|
|
66
148
|
|
|
149
|
+
The optional adapter `persist` callback receives the tentative state after an accepted commit,
|
|
150
|
+
the bootstrapped handle, or an ordinary ratchet operation. Writes must
|
|
151
|
+
be atomic: rejection must leave storage unchanged, since the in-memory handle rolls back and no
|
|
152
|
+
control notifications fire. Received-message and bootstrap persist runs under the handle mutex;
|
|
153
|
+
it must not call back into that handle. Recovery persists the rejoined handle before adoption. If
|
|
154
|
+
adoption throws, storage already holds the new handle and a restart loads it.
|
|
155
|
+
|
|
156
|
+
## Applying a commit inside a host transaction
|
|
157
|
+
|
|
158
|
+
`processCommit` is `applyCommit` inside `access.mutate`, plus entry resolution before the lock. A host
|
|
159
|
+
that projects commits into its own tables calls `applyCommit` inside its own transaction instead, from
|
|
160
|
+
its own `GroupMLS.processCommit`, so the peer still sees each result and rotates its anchor:
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
const result = await applyCommit({
|
|
164
|
+
handle,
|
|
165
|
+
commit,
|
|
166
|
+
senderDID,
|
|
167
|
+
resolveLedgerEntries: (ids) => resolved(ids), // must not take the handle lock
|
|
168
|
+
entrySlot,
|
|
169
|
+
ownDID: identity.id,
|
|
170
|
+
persist,
|
|
171
|
+
})
|
|
172
|
+
if (result.applied) {
|
|
173
|
+
// write result.rosterAfter, result.surfacedEntries, ... and commit
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
It refuses non-Commit bytes, a frame at another epoch, and this member's own authenticated commit
|
|
178
|
+
before any resolver or mutation runs. `applied` means the handle took the commit's state; `advanced`
|
|
179
|
+
means the epoch moved. A commit removing this member is applied without advancing. The result
|
|
180
|
+
carries both rosters, the ledger length before, the committer, and the verified non-`kumiai.*`
|
|
181
|
+
entries the commit appended, repeats kept. `MissingLedgerEntriesError`, resolver faults and store
|
|
182
|
+
faults propagate: map them to a throw from `processCommit`, never to `advanced: false`, which the peer
|
|
183
|
+
steps over as a commit it will never apply.
|
|
184
|
+
|
|
185
|
+
## Recovery secret
|
|
186
|
+
|
|
187
|
+
`exportRecoverySecret` defaults to `deriveRecoverySecret`, the anchor KDF. A host whose groups
|
|
188
|
+
already rendezvous on another secret passes `recoverySecret: (handle) => ...` for every restore of
|
|
189
|
+
those groups: both the commit and the rendezvous topic follow it. A result under 16 bytes or a throw
|
|
190
|
+
is refused; the default is never tried as a fallback.
|
|
191
|
+
|
|
67
192
|
## Two seals, one exporter
|
|
68
193
|
|
|
69
194
|
`wrap`/`unwrap` carry app traffic and are ratchet-backed: each open consumes a message key and
|
|
@@ -83,15 +208,12 @@ leave a peer stepping over frames without ever classifying one and never learnin
|
|
|
83
208
|
Documented on the factories themselves; the conformance suite in `@kumiai/rpc-conformance` pins each
|
|
84
209
|
one. The ones a host is most likely to trip on:
|
|
85
210
|
|
|
86
|
-
- **`unwrap` opens
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
epoch's bytes computes every other's. This exports from the epoch's exporter secret, which a
|
|
93
|
-
removed member cannot reach forward from. That difference is the entire security property the
|
|
94
|
-
app-lane topic rests on, and it is real only here.
|
|
211
|
+
- **`unwrap` opens only at the current epoch.** A readable frame at any other epoch throws
|
|
212
|
+
`FrameEpochError` before decryption, under the handle lock. ts-mls could open a few past epochs,
|
|
213
|
+
but `GroupHandle.decrypt` resolves senders at the current epoch, so such a frame never had a
|
|
214
|
+
sender.
|
|
215
|
+
- **`exportSecret` derives from MLS exporter state.** The fake uses HMAC to model epoch separation,
|
|
216
|
+
while the real port derives from the handle's exporter secret.
|
|
95
217
|
- **`wrap` mutates.** It consumes a per-message ratchet key, so sealing the same plaintext twice
|
|
96
218
|
gives different bytes.
|
|
97
219
|
- **`exportRecoverySecret` is derived from the group's genesis anchor, which is public.** MLS has no
|
package/lib/access.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { GroupHandle } from '@kumiai/mls';
|
|
2
|
+
import type { PendingAppFrame } from '@kumiai/rpc';
|
|
3
|
+
type PersistOpened = (stagedState: Uint8Array, record: PendingAppFrame) => Promise<void>;
|
|
4
|
+
export type HandleAccess = {
|
|
5
|
+
epoch(): number;
|
|
6
|
+
read<TValue>(fn: (handle: GroupHandle) => TValue | Promise<TValue>): Promise<TValue>;
|
|
7
|
+
mutate<TValue>(fn: (handle: GroupHandle, persist: (handle: GroupHandle) => Promise<void>) => Promise<TValue>): Promise<TValue>;
|
|
8
|
+
replace(next: GroupHandle): Promise<void>;
|
|
9
|
+
open<TValue>(fn: (handle: GroupHandle, persistOpened: PersistOpened) => Promise<TValue>, persistOpened: PersistOpened): Promise<TValue>;
|
|
10
|
+
};
|
|
11
|
+
export type SimpleHandleAccessParams = {
|
|
12
|
+
handle: () => GroupHandle;
|
|
13
|
+
adopt: (next: GroupHandle) => void | Promise<void>;
|
|
14
|
+
persist?: (handle: GroupHandle) => void | Promise<void>;
|
|
15
|
+
};
|
|
16
|
+
export declare function simpleHandleAccess(params: SimpleHandleAccessParams): HandleAccess;
|
|
17
|
+
export {};
|
package/lib/access.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export function simpleHandleAccess(params) {
|
|
2
|
+
let publishedEpoch = Number(params.handle().epoch);
|
|
3
|
+
let tail = Promise.resolve();
|
|
4
|
+
const serialise = async (fn)=>{
|
|
5
|
+
const previous = tail;
|
|
6
|
+
let release = ()=>{};
|
|
7
|
+
tail = new Promise((resolve)=>{
|
|
8
|
+
release = resolve;
|
|
9
|
+
});
|
|
10
|
+
await previous;
|
|
11
|
+
try {
|
|
12
|
+
return await fn();
|
|
13
|
+
} finally{
|
|
14
|
+
release();
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
const save = async (handle)=>{
|
|
18
|
+
await params.persist?.(handle);
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
epoch: ()=>publishedEpoch,
|
|
22
|
+
read: (fn)=>serialise(async ()=>await fn(params.handle())),
|
|
23
|
+
mutate: (fn)=>serialise(async ()=>{
|
|
24
|
+
const handle = params.handle();
|
|
25
|
+
let saved = false;
|
|
26
|
+
const persist = async (current)=>{
|
|
27
|
+
await save(current);
|
|
28
|
+
saved = true;
|
|
29
|
+
};
|
|
30
|
+
const result = await fn(handle, persist);
|
|
31
|
+
if (!saved) await save(handle);
|
|
32
|
+
publishedEpoch = Number(handle.epoch);
|
|
33
|
+
return result;
|
|
34
|
+
}),
|
|
35
|
+
replace: (next)=>serialise(async ()=>{
|
|
36
|
+
await save(next);
|
|
37
|
+
await params.adopt(next);
|
|
38
|
+
publishedEpoch = Number(next.epoch);
|
|
39
|
+
}),
|
|
40
|
+
open: (fn, persistOpened)=>serialise(async ()=>{
|
|
41
|
+
const handle = params.handle();
|
|
42
|
+
const result = await fn(handle, persistOpened);
|
|
43
|
+
publishedEpoch = Number(handle.epoch);
|
|
44
|
+
return result;
|
|
45
|
+
})
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type GroupHandle, type VerifiedLedgerEntry } from '@kumiai/mls';
|
|
2
|
+
import type { CommitContext, RosterEntry } from '@kumiai/rpc';
|
|
3
|
+
import type { LedgerEntrySlot } from './mls.js';
|
|
4
|
+
export type ApplyCommitParams = CommitContext & {
|
|
5
|
+
handle: GroupHandle;
|
|
6
|
+
commit: Uint8Array;
|
|
7
|
+
entrySlot: LedgerEntrySlot;
|
|
8
|
+
/** This member's DID: its own authenticated commit is never applied as received. */
|
|
9
|
+
ownDID: string;
|
|
10
|
+
/** Runs before the handle adopts the new state. */
|
|
11
|
+
persist?: ((handle: GroupHandle) => Promise<void>) | undefined;
|
|
12
|
+
};
|
|
13
|
+
export type ApplyCommitResult = {
|
|
14
|
+
/** The handle took the commit's state. A host keeps it even when `advanced` is false. */
|
|
15
|
+
applied: boolean;
|
|
16
|
+
/** The epoch moved. A commit removing this member is applied without advancing it. */
|
|
17
|
+
advanced: boolean;
|
|
18
|
+
epochBefore: number;
|
|
19
|
+
epochAfter: number;
|
|
20
|
+
rosterBefore: Array<RosterEntry>;
|
|
21
|
+
rosterAfter: Array<RosterEntry>;
|
|
22
|
+
/** Verified non-control entries the commit appended, in log order, repeats kept. */
|
|
23
|
+
surfacedEntries: Array<VerifiedLedgerEntry>;
|
|
24
|
+
ledgerLengthBefore: number;
|
|
25
|
+
committerDID?: string;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Apply a received Commit to `handle` in place, for a caller that already holds the handle's
|
|
29
|
+
* lock and owns the surrounding transaction. `resolveLedgerEntries` runs inside that lock
|
|
30
|
+
* and must not take it again.
|
|
31
|
+
*
|
|
32
|
+
* `persist` runs before the handle adopts the new state; its failure propagates and leaves the
|
|
33
|
+
* handle where it was. `MissingLedgerEntriesError` and resolver faults propagate for the caller to
|
|
34
|
+
* classify. Any other refusal returns `applied: false`, and a throw after the handle took the
|
|
35
|
+
* commit (a callback after durable acceptance) reports it applied rather than inviting a replay.
|
|
36
|
+
*/
|
|
37
|
+
export declare function applyCommit(params: ApplyCommitParams): Promise<ApplyCommitResult>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { normalizeDID } from '@kokuin/token';
|
|
2
|
+
import { MissingLedgerEntriesError, readMessageEpoch } from '@kumiai/mls';
|
|
3
|
+
/** Reserved by `@kumiai/mls` for its own control entries; never surfaced to a host. */ const CONTROL_TYPE_PREFIX = 'kumiai.';
|
|
4
|
+
function rosterOf(handle) {
|
|
5
|
+
return handle.listMembers().map((member)=>({
|
|
6
|
+
did: member.id,
|
|
7
|
+
leafIndex: member.leafIndex,
|
|
8
|
+
longForm: member.longForm
|
|
9
|
+
}));
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Apply a received Commit to `handle` in place, for a caller that already holds the handle's
|
|
13
|
+
* lock and owns the surrounding transaction. `resolveLedgerEntries` runs inside that lock
|
|
14
|
+
* and must not take it again.
|
|
15
|
+
*
|
|
16
|
+
* `persist` runs before the handle adopts the new state; its failure propagates and leaves the
|
|
17
|
+
* handle where it was. `MissingLedgerEntriesError` and resolver faults propagate for the caller to
|
|
18
|
+
* classify. Any other refusal returns `applied: false`, and a throw after the handle took the
|
|
19
|
+
* commit (a callback after durable acceptance) reports it applied rather than inviting a replay.
|
|
20
|
+
*/ export async function applyCommit(params) {
|
|
21
|
+
const { handle, commit, entrySlot, ownDID, persist } = params;
|
|
22
|
+
const before = handle.epoch;
|
|
23
|
+
const rosterBefore = rosterOf(handle);
|
|
24
|
+
const ledgerLengthBefore = handle.ledger.length;
|
|
25
|
+
const refused = (committerDID)=>({
|
|
26
|
+
applied: false,
|
|
27
|
+
advanced: false,
|
|
28
|
+
epochBefore: Number(before),
|
|
29
|
+
epochAfter: Number(before),
|
|
30
|
+
rosterBefore,
|
|
31
|
+
rosterAfter: rosterBefore,
|
|
32
|
+
surfacedEntries: [],
|
|
33
|
+
ledgerLengthBefore,
|
|
34
|
+
...committerDID != null && {
|
|
35
|
+
committerDID
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
const surfaced = ()=>handle.ledger.slice(ledgerLengthBefore).map((entry)=>entry.verified).filter((verified)=>!verified.entry.type.startsWith(CONTROL_TYPE_PREFIX));
|
|
39
|
+
const header = await handle.readCommitHeader(commit);
|
|
40
|
+
if (header == null || readMessageEpoch(commit) !== before) return refused();
|
|
41
|
+
const committerDID = header.committerDID;
|
|
42
|
+
if (committerDID != null && normalizeDID(committerDID) === normalizeDID(ownDID)) {
|
|
43
|
+
return refused(committerDID);
|
|
44
|
+
}
|
|
45
|
+
let persistFailed = false;
|
|
46
|
+
let persisted = false;
|
|
47
|
+
let resolverFailed = false;
|
|
48
|
+
let threw = false;
|
|
49
|
+
const resolve = params.resolveLedgerEntries;
|
|
50
|
+
entrySlot.install(resolve && (async (ids)=>{
|
|
51
|
+
try {
|
|
52
|
+
return await resolve(ids);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
// A fault fetching bodies says nothing about the commit, which may apply on retry.
|
|
55
|
+
resolverFailed = true;
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}));
|
|
59
|
+
try {
|
|
60
|
+
await handle.processMessage(commit, {
|
|
61
|
+
...persist != null && {
|
|
62
|
+
persist: async (current)=>{
|
|
63
|
+
try {
|
|
64
|
+
await persist(current);
|
|
65
|
+
persisted = true;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
persistFailed = true;
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (error instanceof MissingLedgerEntriesError || persistFailed || resolverFailed) throw error;
|
|
75
|
+
threw = true;
|
|
76
|
+
} finally{
|
|
77
|
+
entrySlot.install(undefined);
|
|
78
|
+
}
|
|
79
|
+
if (handle.epoch === before) {
|
|
80
|
+
// A commit removing this member changes the tree without ratcheting the handle, and a host
|
|
81
|
+
// callback may throw after that state was stored.
|
|
82
|
+
const rosterAfter = rosterOf(handle);
|
|
83
|
+
const changed = rosterAfter.length !== rosterBefore.length || rosterAfter.some((entry, index)=>entry.did !== rosterBefore[index]?.did);
|
|
84
|
+
if (threw && !persisted && !changed) return refused(committerDID);
|
|
85
|
+
return {
|
|
86
|
+
...refused(committerDID),
|
|
87
|
+
applied: true,
|
|
88
|
+
rosterAfter,
|
|
89
|
+
surfacedEntries: surfaced()
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
applied: true,
|
|
94
|
+
advanced: true,
|
|
95
|
+
epochBefore: Number(before),
|
|
96
|
+
epochAfter: Number(handle.epoch),
|
|
97
|
+
rosterBefore,
|
|
98
|
+
rosterAfter: rosterOf(handle),
|
|
99
|
+
surfacedEntries: surfaced(),
|
|
100
|
+
ledgerLengthBefore,
|
|
101
|
+
...committerDID != null && {
|
|
102
|
+
committerDID
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
package/lib/crypto.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import type
|
|
1
|
+
import { type GroupHandle } from '@kumiai/mls';
|
|
2
|
+
import { type GroupCrypto, type PendingAppFrame, type PendingAppFrames } from '@kumiai/rpc';
|
|
3
3
|
import { type Runtime } from '@sozai/runtime';
|
|
4
|
+
import type { HandleAccess } from './access.js';
|
|
4
5
|
/**
|
|
5
6
|
* Label the ledger-entry seal key is exported under. Distinct from any label a caller passes to
|
|
6
7
|
* `exportSecret`: that names a topic secret handed to anything that derives one, while this key
|
|
@@ -9,12 +10,11 @@ import { type Runtime } from '@sozai/runtime';
|
|
|
9
10
|
* from a caller (see below).
|
|
10
11
|
*/
|
|
11
12
|
export declare const ENTRY_SEAL_LABEL = "kumiai/ledger-entries/v1";
|
|
13
|
+
export declare function deriveEntryKey(handle: GroupHandle, label?: string): Promise<Uint8Array>;
|
|
14
|
+
export declare function sealEntries(key: Uint8Array, entries: Uint8Array, runtime?: Runtime): Uint8Array;
|
|
15
|
+
export declare function openEntries(key: Uint8Array, sealed: Uint8Array): Uint8Array;
|
|
12
16
|
export type GroupCryptoParams = {
|
|
13
|
-
|
|
14
|
-
* The peer's current handle. A function, not a value: the handle is replaced when the peer
|
|
15
|
-
* adopts its own commit, and closing over a fixed handle would silently seal at a dead epoch.
|
|
16
|
-
*/
|
|
17
|
-
handle: () => GroupHandle;
|
|
17
|
+
access: HandleAccess;
|
|
18
18
|
/**
|
|
19
19
|
* Override the ledger-entry seal's exporter label. Members must agree on it, or they can't
|
|
20
20
|
* apply each other's commits.
|
|
@@ -22,16 +22,19 @@ export type GroupCryptoParams = {
|
|
|
22
22
|
entryLabel?: string;
|
|
23
23
|
/** Runtime providing platform primitives. Defaults to `createRuntime()`. */
|
|
24
24
|
runtime?: Runtime;
|
|
25
|
+
/** Atomic host store for post-open handle state and the pending record. */
|
|
26
|
+
pending?: {
|
|
27
|
+
persistOpened(stagedState: Uint8Array, record: PendingAppFrame): Promise<void>;
|
|
28
|
+
list(): Promise<Array<PendingAppFrame>>;
|
|
29
|
+
complete(id: string): Promise<void>;
|
|
30
|
+
};
|
|
25
31
|
};
|
|
26
32
|
/**
|
|
27
33
|
* {@link GroupCrypto} over a live {@link GroupHandle} — the real port, against real MLS.
|
|
28
34
|
*
|
|
29
35
|
* ## Where this diverges from the fake in `@kumiai/rpc`'s test fixtures
|
|
30
36
|
*
|
|
31
|
-
* 1. `unwrap`
|
|
32
|
-
* via ts-mls's retained key material (the fake refuses everything but its current epoch, so
|
|
33
|
-
* the fake is stricter — both are valid implementations of the port; group-rpc must not
|
|
34
|
-
* depend on the window, which is spent by epoch transitions, not time).
|
|
37
|
+
* 1. `unwrap` gates the frame epoch before ts-mls's bounded past-window decrypt.
|
|
35
38
|
*
|
|
36
39
|
* 2. `exportSecret` is one-way; the fake's is not. The fake XORs epoch and label into a fixed
|
|
37
40
|
* base, so one epoch's bytes yield every other epoch's for that label. This exports from the
|
|
@@ -46,4 +49,9 @@ export type GroupCryptoParams = {
|
|
|
46
49
|
* a sealed app frame and a commit — returning `null` (never throwing) for anything ts-mls
|
|
47
50
|
* won't decode. The fake answers only for its own two encodings.
|
|
48
51
|
*/
|
|
52
|
+
export declare function createGroupCrypto(params: GroupCryptoParams & {
|
|
53
|
+
pending: NonNullable<GroupCryptoParams['pending']>;
|
|
54
|
+
}): GroupCrypto & {
|
|
55
|
+
pending: PendingAppFrames;
|
|
56
|
+
};
|
|
49
57
|
export declare function createGroupCrypto(params: GroupCryptoParams): GroupCrypto;
|
package/lib/crypto.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { readMessageEpoch } from '@kumiai/mls';
|
|
1
|
+
import { readMessageAAD, readMessageEpoch } from '@kumiai/mls';
|
|
2
|
+
import { AppFrameStorageError, FrameEpochError, isAppFrameStorageError, sortPendingAppFrames } from '@kumiai/rpc';
|
|
2
3
|
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
|
3
4
|
import { createRuntime } from '@sozai/runtime';
|
|
4
5
|
/**
|
|
@@ -29,32 +30,33 @@ import { createRuntime } from '@sozai/runtime';
|
|
|
29
30
|
* no v1 peer can read a v2 blob regardless, but the failure reads as "unsupported version"
|
|
30
31
|
* rather than an AEAD refusal indistinguishable from a wrong epoch or a tampered frame.
|
|
31
32
|
*/ const ENTRY_VERSION = 1;
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
33
|
+
export function deriveEntryKey(handle, label) {
|
|
34
|
+
return handle.exportSecret(label ?? ENTRY_SEAL_LABEL, new Uint8Array(), SECRET_LENGTH);
|
|
35
|
+
}
|
|
36
|
+
export function sealEntries(key, entries, runtime = createRuntime()) {
|
|
37
|
+
// Random per seal: two members can frame a commit at the same epoch.
|
|
38
|
+
const nonce = runtime.getRandomValues(new Uint8Array(ENTRY_NONCE_BYTES));
|
|
39
|
+
const ciphertext = xchacha20poly1305(key, nonce).encrypt(entries);
|
|
40
|
+
const sealed = new Uint8Array(1 + nonce.length + ciphertext.length);
|
|
41
|
+
sealed[0] = ENTRY_VERSION;
|
|
42
|
+
sealed.set(nonce, 1);
|
|
43
|
+
sealed.set(ciphertext, 1 + nonce.length);
|
|
44
|
+
return sealed;
|
|
45
|
+
}
|
|
46
|
+
function assertSealedEntryBlob(sealed) {
|
|
47
|
+
if (sealed.length <= 1 + ENTRY_NONCE_BYTES) throw new Error('openEntries: not a sealed blob');
|
|
48
|
+
if (sealed[0] !== ENTRY_VERSION) {
|
|
49
|
+
throw new Error(`openEntries: unsupported blob version ${sealed[0]}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function openEntries(key, sealed) {
|
|
53
|
+
assertSealedEntryBlob(sealed);
|
|
54
|
+
return xchacha20poly1305(key, sealed.subarray(1, 1 + ENTRY_NONCE_BYTES)).decrypt(sealed.subarray(1 + ENTRY_NONCE_BYTES));
|
|
55
|
+
}
|
|
56
|
+
export function createGroupCrypto(params) {
|
|
57
|
+
const { access, entryLabel = ENTRY_SEAL_LABEL, runtime = createRuntime(), pending } = params;
|
|
56
58
|
return {
|
|
57
|
-
epoch: ()=>
|
|
59
|
+
epoch: ()=>access.epoch(),
|
|
58
60
|
// Passed straight through to the handle's exporter, except `entryLabel`: reusing it would
|
|
59
61
|
// not be an independent export — it's the exact exporter call `sealEntries`/`openEntries`
|
|
60
62
|
// make below (same context, same `SECRET_LENGTH`), so it would hand back the ledger-entry
|
|
@@ -63,55 +65,133 @@ import { createRuntime } from '@sozai/runtime';
|
|
|
63
65
|
if (label === entryLabel) {
|
|
64
66
|
throw new Error(`exportSecret: label '${label}' is reserved for the ledger-entry seal`);
|
|
65
67
|
}
|
|
66
|
-
return
|
|
68
|
+
return access.read(async (group)=>({
|
|
69
|
+
secret: await group.exportSecret(label, EXPORT_CONTEXT, length),
|
|
70
|
+
epoch: Number(group.epoch)
|
|
71
|
+
}));
|
|
67
72
|
},
|
|
68
|
-
wrap: (bytes)=>
|
|
73
|
+
wrap: (bytes, opts)=>access.mutate((group)=>group.encrypt(bytes, opts)),
|
|
69
74
|
sealEntries: async (bytes)=>{
|
|
70
|
-
const key = await
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
75
|
+
const { key, epoch } = await access.read(async (group)=>({
|
|
76
|
+
key: await deriveEntryKey(group, entryLabel),
|
|
77
|
+
epoch: Number(group.epoch)
|
|
78
|
+
}));
|
|
79
|
+
try {
|
|
80
|
+
return {
|
|
81
|
+
sealed: sealEntries(key, bytes, runtime),
|
|
82
|
+
epoch
|
|
83
|
+
};
|
|
84
|
+
} finally{
|
|
85
|
+
key.fill(0);
|
|
86
|
+
}
|
|
80
87
|
},
|
|
81
88
|
openEntries: async (sealed)=>{
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
89
|
+
assertSealedEntryBlob(sealed);
|
|
90
|
+
const key = await access.read((group)=>deriveEntryKey(group, entryLabel));
|
|
91
|
+
try {
|
|
92
|
+
return openEntries(key, sealed);
|
|
93
|
+
} finally{
|
|
94
|
+
key.fill(0);
|
|
88
95
|
}
|
|
89
|
-
// Pure: exporting is epoch-level and touches no handle state, so this may be called from
|
|
90
|
-
// inside the apply of the very commit whose blob it opens — the only place it's called from.
|
|
91
|
-
const key = await handle().exportSecret(entryLabel, EXPORT_CONTEXT, SECRET_LENGTH);
|
|
92
|
-
return xchacha20poly1305(key, sealed.subarray(1, 1 + ENTRY_NONCE_BYTES)).decrypt(sealed.subarray(1 + ENTRY_NONCE_BYTES));
|
|
93
96
|
},
|
|
94
|
-
unwrap: async (bytes)=>{
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
97
|
+
unwrap: async (bytes, opts)=>{
|
|
98
|
+
if (opts?.frame != null) {
|
|
99
|
+
if (pending == null) throw new Error('unwrap: pending store required for durable open');
|
|
100
|
+
const frame = opts.frame;
|
|
101
|
+
// Wrapped here, not inside `fn`: a transactional adapter makes the write after `fn`.
|
|
102
|
+
const persistOpened = async (state, record)=>{
|
|
103
|
+
try {
|
|
104
|
+
await pending.persistOpened(state, record);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
throw new AppFrameStorageError('failed to persist opened app frame', {
|
|
107
|
+
cause: error
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
let openError;
|
|
112
|
+
const open = async (group, persistStaged)=>{
|
|
113
|
+
const epoch = Number(group.epoch);
|
|
114
|
+
const frameEpoch = readMessageEpoch(bytes);
|
|
115
|
+
if (frameEpoch != null && Number(frameEpoch) !== epoch) {
|
|
116
|
+
throw new FrameEpochError(Number(frameEpoch), epoch);
|
|
117
|
+
}
|
|
118
|
+
const result = await group.decryptStaged(bytes, opts, async (stagedState, result)=>{
|
|
119
|
+
// The handle adopts the staged state only after this returns: a fault here leaves
|
|
120
|
+
// the key unspent, so the frame must be retried, not dropped.
|
|
121
|
+
try {
|
|
122
|
+
await persistStaged(stagedState, {
|
|
123
|
+
frame,
|
|
124
|
+
payload: result.payload,
|
|
125
|
+
senderDID: result.senderDID
|
|
126
|
+
});
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (isAppFrameStorageError(error)) throw error;
|
|
129
|
+
throw new AppFrameStorageError('failed to stage opened app frame', {
|
|
130
|
+
cause: error
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
return {
|
|
135
|
+
...result,
|
|
136
|
+
epoch
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
let opened;
|
|
140
|
+
try {
|
|
141
|
+
opened = await access.open(async (group, persistStaged)=>{
|
|
142
|
+
try {
|
|
143
|
+
return await open(group, persistStaged);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
openError = error;
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
}, persistOpened);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
// The open's own refusal says whether the frame is dead. Anything the adapter raised
|
|
151
|
+
// around it (a restore, a read) left the key unspent, so the lane must retry.
|
|
152
|
+
if (error === openError || isAppFrameStorageError(error)) throw error;
|
|
153
|
+
throw new AppFrameStorageError('handle access failed during durable open', {
|
|
154
|
+
cause: error
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
payload: opened.payload,
|
|
159
|
+
senderDID: opened.senderDID,
|
|
160
|
+
epoch: opened.epoch
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
const { payload, senderDID, epoch } = await access.mutate(async (group)=>{
|
|
164
|
+
const epoch = Number(group.epoch);
|
|
165
|
+
const frameEpoch = readMessageEpoch(bytes);
|
|
166
|
+
if (frameEpoch != null && Number(frameEpoch) !== epoch) {
|
|
167
|
+
throw new FrameEpochError(Number(frameEpoch), epoch);
|
|
168
|
+
}
|
|
169
|
+
const opened = await group.decrypt(bytes, opts);
|
|
170
|
+
return {
|
|
171
|
+
...opened,
|
|
172
|
+
epoch
|
|
173
|
+
};
|
|
174
|
+
});
|
|
103
175
|
if (senderDID == null) {
|
|
104
176
|
throw new Error('unwrap: opened frame has no authenticated sender');
|
|
105
177
|
}
|
|
106
178
|
return {
|
|
107
179
|
payload,
|
|
108
|
-
senderDID
|
|
180
|
+
senderDID,
|
|
181
|
+
epoch
|
|
109
182
|
};
|
|
110
183
|
},
|
|
111
184
|
frameEpoch: (bytes)=>{
|
|
112
185
|
// Total by contract: readMessageEpoch never throws and answers without a key.
|
|
113
186
|
const epoch = readMessageEpoch(bytes);
|
|
114
187
|
return epoch == null ? null : Number(epoch);
|
|
188
|
+
},
|
|
189
|
+
frameAAD: (bytes)=>readMessageAAD(bytes),
|
|
190
|
+
...pending == null ? {} : {
|
|
191
|
+
pending: {
|
|
192
|
+
list: async ()=>sortPendingAppFrames(await pending.list()),
|
|
193
|
+
complete: (id)=>pending.complete(id)
|
|
194
|
+
}
|
|
115
195
|
}
|
|
116
196
|
};
|
|
117
197
|
}
|
package/lib/index.d.ts
CHANGED
|
@@ -18,5 +18,7 @@
|
|
|
18
18
|
*
|
|
19
19
|
* @module mls-rpc
|
|
20
20
|
*/
|
|
21
|
-
export {
|
|
22
|
-
export {
|
|
21
|
+
export { type HandleAccess, type SimpleHandleAccessParams, simpleHandleAccess } from './access.js';
|
|
22
|
+
export { type ApplyCommitParams, type ApplyCommitResult, applyCommit } from './apply-commit.js';
|
|
23
|
+
export { createGroupCrypto, deriveEntryKey, ENTRY_SEAL_LABEL, type GroupCryptoParams, openEntries, sealEntries, } from './crypto.js';
|
|
24
|
+
export { createGroupMLS, createLedgerEntrySlot, createRecoveryPending, deriveRecoverySecret, type GroupMLSParams, type LedgerEntrySlot, RECOVERY_LABEL, type RecoveryPending, } from './mls.js';
|
package/lib/index.js
CHANGED
|
@@ -17,5 +17,7 @@
|
|
|
17
17
|
* failure mode the seam already has.
|
|
18
18
|
*
|
|
19
19
|
* @module mls-rpc
|
|
20
|
-
*/ export {
|
|
21
|
-
export {
|
|
20
|
+
*/ export { simpleHandleAccess } from './access.js';
|
|
21
|
+
export { applyCommit } from './apply-commit.js';
|
|
22
|
+
export { createGroupCrypto, deriveEntryKey, ENTRY_SEAL_LABEL, openEntries, sealEntries } from './crypto.js';
|
|
23
|
+
export { createGroupMLS, createLedgerEntrySlot, createRecoveryPending, deriveRecoverySecret, RECOVERY_LABEL } from './mls.js';
|
package/lib/mls.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { OwnIdentity } from '@kokuin/token';
|
|
2
2
|
import { type GroupHandle } from '@kumiai/mls';
|
|
3
3
|
import type { GroupMLS } from '@kumiai/rpc';
|
|
4
|
+
import type { HandleAccess } from './access.js';
|
|
4
5
|
/**
|
|
5
6
|
* The label the non-rotating recovery secret is derived under. This secret is the root of
|
|
6
7
|
* BOTH the commit topic and the rendezvous topic — everything downstream of it depends on
|
|
@@ -33,21 +34,27 @@ export type LedgerEntrySlot = {
|
|
|
33
34
|
};
|
|
34
35
|
export declare function createLedgerEntrySlot(): LedgerEntrySlot;
|
|
35
36
|
export type GroupMLSParams = {
|
|
36
|
-
|
|
37
|
-
handle: () => GroupHandle;
|
|
38
|
-
/** Replace the handle — the ONLY way the peer's MLS state is swapped wholesale. */
|
|
39
|
-
adopt: (handle: GroupHandle) => void | Promise<void>;
|
|
37
|
+
access: HandleAccess;
|
|
40
38
|
/** This member's signing identity: recovery requests and attestations are signed with it. */
|
|
41
39
|
identity: OwnIdentity;
|
|
42
40
|
/** The slot the handle was built with. See {@link LedgerEntrySlot}. */
|
|
43
41
|
entrySlot: LedgerEntrySlot;
|
|
44
42
|
/**
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
* that
|
|
43
|
+
* The group's recovery secret, read under `access.read`. Defaults to
|
|
44
|
+
* {@link deriveRecoverySecret}. A host whose groups already use another derivation passes it
|
|
45
|
+
* here for every restore of that group: the commit and rendezvous topics follow the choice.
|
|
48
46
|
*/
|
|
49
|
-
|
|
47
|
+
recoverySecret?: (handle: GroupHandle) => Promise<Uint8Array>;
|
|
50
48
|
};
|
|
49
|
+
export type RecoveryPending = {
|
|
50
|
+
get(requestID: string): Uint8Array | null;
|
|
51
|
+
put(requestID: string, ephemeralPrivateKey: Uint8Array): void;
|
|
52
|
+
delete(requestID: string): void;
|
|
53
|
+
};
|
|
54
|
+
export declare function createRecoveryPending(options?: {
|
|
55
|
+
ttlMS?: number;
|
|
56
|
+
}): RecoveryPending;
|
|
57
|
+
export declare function deriveRecoverySecret(handle: GroupHandle): Promise<Uint8Array>;
|
|
51
58
|
/**
|
|
52
59
|
* {@link GroupMLS} over a live {@link GroupHandle} — the real lifecycle port.
|
|
53
60
|
*
|
|
@@ -60,7 +67,7 @@ export type GroupMLSParams = {
|
|
|
60
67
|
* adopts it in `onAccepted`). A host that treated every commit as adopt-later would
|
|
61
68
|
* double-apply received ones.
|
|
62
69
|
*
|
|
63
|
-
* 2. **`
|
|
70
|
+
* 2. **`rosterEntries` reads the ratchet tree, so a leaf with an unparsable credential is
|
|
64
71
|
* simply absent** rather than present-with-a-placeholder. The double's roster is a set of
|
|
65
72
|
* strings it was handed.
|
|
66
73
|
*
|
package/lib/mls.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { createRecoveryRequest, encodeGroupAnchor, joinGroupExternal, MissingLedgerEntriesError, openSealedGroupInfo, openSealedLedger, sealGroupInfo, sealLedger } from '@kumiai/mls';
|
|
1
|
+
import { createRecoveryRequest, encodeGroupAnchor, joinGroupExternal, ledgerEntryDigest, MissingLedgerEntriesError, openSealedGroupInfo, openSealedLedger, readCommitEntryIDs, readMessageEpoch, sealGroupInfo, sealLedger } from '@kumiai/mls';
|
|
2
|
+
import { applyCommit } from './apply-commit.js';
|
|
2
3
|
const utf8 = new TextEncoder();
|
|
3
4
|
/**
|
|
4
5
|
* The label the non-rotating recovery secret is derived under. This secret is the root of
|
|
@@ -26,11 +27,58 @@ export function createLedgerEntrySlot() {
|
|
|
26
27
|
}
|
|
27
28
|
};
|
|
28
29
|
}
|
|
30
|
+
/** Below this a topic secret is guessable; the default derives 32 bytes. */ const MIN_RECOVERY_SECRET_BYTES = 16;
|
|
29
31
|
/**
|
|
30
32
|
* How long a minted recovery request's private half is kept. The port makes retention the
|
|
31
33
|
* implementation's problem — the lane has no release hook and drops its `requestID` on
|
|
32
34
|
* timeout without saying so — so this bounds it off the mint time.
|
|
33
35
|
*/ const REQUEST_TTL_MS = 120_000;
|
|
36
|
+
export function createRecoveryPending(options) {
|
|
37
|
+
const ttlMS = options?.ttlMS ?? REQUEST_TTL_MS;
|
|
38
|
+
const requests = new Map();
|
|
39
|
+
const remove = (requestID, request)=>{
|
|
40
|
+
clearTimeout(request.timer);
|
|
41
|
+
request.ephemeralPrivateKey.fill(0);
|
|
42
|
+
requests.delete(requestID);
|
|
43
|
+
};
|
|
44
|
+
const sweep = ()=>{
|
|
45
|
+
const cutoff = Date.now() - ttlMS;
|
|
46
|
+
for (const [id, request] of requests){
|
|
47
|
+
if (request.mintedAt <= cutoff) remove(id, request);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
get: (requestID)=>{
|
|
52
|
+
sweep();
|
|
53
|
+
return requests.get(requestID)?.ephemeralPrivateKey ?? null;
|
|
54
|
+
},
|
|
55
|
+
put: (requestID, ephemeralPrivateKey)=>{
|
|
56
|
+
sweep();
|
|
57
|
+
const previous = requests.get(requestID);
|
|
58
|
+
if (previous != null) remove(requestID, previous);
|
|
59
|
+
const timer = setTimeout(()=>{
|
|
60
|
+
const held = requests.get(requestID);
|
|
61
|
+
if (held?.ephemeralPrivateKey === ephemeralPrivateKey) remove(requestID, held);
|
|
62
|
+
}, ttlMS);
|
|
63
|
+
const nodeTimer = timer;
|
|
64
|
+
nodeTimer.unref?.();
|
|
65
|
+
requests.set(requestID, {
|
|
66
|
+
ephemeralPrivateKey,
|
|
67
|
+
mintedAt: Date.now(),
|
|
68
|
+
timer
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
delete: (requestID)=>{
|
|
72
|
+
sweep();
|
|
73
|
+
const request = requests.get(requestID);
|
|
74
|
+
if (request != null) remove(requestID, request);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
export async function deriveRecoverySecret(handle) {
|
|
79
|
+
const { cipherSuite } = handle.context;
|
|
80
|
+
return await cipherSuite.kdf.expand(await cipherSuite.kdf.extract(utf8.encode(handle.groupID), encodeGroupAnchor(handle.anchor)), utf8.encode(RECOVERY_LABEL), 32);
|
|
81
|
+
}
|
|
34
82
|
/**
|
|
35
83
|
* {@link GroupMLS} over a live {@link GroupHandle} — the real lifecycle port.
|
|
36
84
|
*
|
|
@@ -43,7 +91,7 @@ export function createLedgerEntrySlot() {
|
|
|
43
91
|
* adopts it in `onAccepted`). A host that treated every commit as adopt-later would
|
|
44
92
|
* double-apply received ones.
|
|
45
93
|
*
|
|
46
|
-
* 2. **`
|
|
94
|
+
* 2. **`rosterEntries` reads the ratchet tree, so a leaf with an unparsable credential is
|
|
47
95
|
* simply absent** rather than present-with-a-placeholder. The double's roster is a set of
|
|
48
96
|
* strings it was handed.
|
|
49
97
|
*
|
|
@@ -56,20 +104,21 @@ export function createLedgerEntrySlot() {
|
|
|
56
104
|
* topic is for (a stranded peer must be able to name it, and so must a removed one) but a
|
|
57
105
|
* host must not put anything on it that confidentiality depends on.
|
|
58
106
|
*/ export function createGroupMLS(params) {
|
|
59
|
-
const {
|
|
60
|
-
const pending =
|
|
61
|
-
const sweep = ()=>{
|
|
62
|
-
const cutoff = Date.now() - REQUEST_TTL_MS;
|
|
63
|
-
for (const [id, request] of pending){
|
|
64
|
-
if (request.mintedAt < cutoff) pending.delete(id);
|
|
65
|
-
}
|
|
66
|
-
};
|
|
107
|
+
const { access, identity, entrySlot } = params;
|
|
108
|
+
const pending = createRecoveryPending();
|
|
67
109
|
return {
|
|
68
|
-
async
|
|
69
|
-
return
|
|
110
|
+
async readEpoch () {
|
|
111
|
+
return await access.read((group)=>Number(group.epoch));
|
|
112
|
+
},
|
|
113
|
+
async rosterEntries () {
|
|
114
|
+
return await access.read((group)=>group.listMembers().map((member)=>({
|
|
115
|
+
did: member.id,
|
|
116
|
+
leafIndex: member.leafIndex,
|
|
117
|
+
longForm: member.longForm
|
|
118
|
+
})));
|
|
70
119
|
},
|
|
71
120
|
async readCommitHeader (commit) {
|
|
72
|
-
const header = await
|
|
121
|
+
const header = await access.read((group)=>group.readCommitHeader(commit));
|
|
73
122
|
if (header == null) return null;
|
|
74
123
|
return {
|
|
75
124
|
epoch: Number(header.epoch),
|
|
@@ -82,98 +131,129 @@ export function createLedgerEntrySlot() {
|
|
|
82
131
|
};
|
|
83
132
|
},
|
|
84
133
|
async processCommit (commit, context) {
|
|
85
|
-
const
|
|
86
|
-
const
|
|
87
|
-
|
|
134
|
+
const frameEpoch = readMessageEpoch(commit);
|
|
135
|
+
const eligible = await access.read(async (group)=>{
|
|
136
|
+
const header = await group.readCommitHeader(commit);
|
|
137
|
+
return {
|
|
138
|
+
eligible: header != null && frameEpoch === group.epoch,
|
|
139
|
+
epoch: Number(group.epoch)
|
|
140
|
+
};
|
|
141
|
+
});
|
|
142
|
+
if (!eligible.eligible) {
|
|
143
|
+
return {
|
|
144
|
+
advanced: false,
|
|
145
|
+
epochBefore: eligible.epoch,
|
|
146
|
+
epochAfter: eligible.epoch
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const ids = readCommitEntryIDs(commit);
|
|
150
|
+
const tokens = ids.length === 0 ? [] : await context.resolveLedgerEntries?.(ids);
|
|
151
|
+
const resolved = new Map();
|
|
152
|
+
for (const token of tokens ?? [])resolved.set(ledgerEntryDigest(token), token);
|
|
153
|
+
const ignored = Symbol('ignored commit');
|
|
154
|
+
let refusedEpoch;
|
|
88
155
|
try {
|
|
89
|
-
await
|
|
156
|
+
return await access.mutate(async (group, persist)=>{
|
|
157
|
+
if (group.epoch !== frameEpoch) {
|
|
158
|
+
// Moved while entries resolved: the caller re-classifies against the epoch it names.
|
|
159
|
+
refusedEpoch = Number(group.epoch);
|
|
160
|
+
throw ignored;
|
|
161
|
+
}
|
|
162
|
+
const result = await applyCommit({
|
|
163
|
+
...context,
|
|
164
|
+
handle: group,
|
|
165
|
+
commit,
|
|
166
|
+
resolveLedgerEntries: async (requested)=>requested.flatMap((id)=>{
|
|
167
|
+
const token = resolved.get(id);
|
|
168
|
+
return token == null ? [] : [
|
|
169
|
+
token
|
|
170
|
+
];
|
|
171
|
+
}),
|
|
172
|
+
entrySlot,
|
|
173
|
+
ownDID: identity.id,
|
|
174
|
+
persist
|
|
175
|
+
});
|
|
176
|
+
// Thrown so the adapter does not save a handle the commit left untouched.
|
|
177
|
+
if (!result.applied) {
|
|
178
|
+
refusedEpoch = result.epochBefore;
|
|
179
|
+
throw ignored;
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
advanced: result.advanced,
|
|
183
|
+
epochBefore: result.epochBefore,
|
|
184
|
+
epochAfter: result.epochAfter
|
|
185
|
+
};
|
|
186
|
+
});
|
|
90
187
|
} catch (error) {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
// position to apply would wedge it there forever.
|
|
96
|
-
if (error instanceof MissingLedgerEntriesError) throw error;
|
|
97
|
-
return {
|
|
98
|
-
advanced: false
|
|
188
|
+
if (error === ignored && refusedEpoch != null) return {
|
|
189
|
+
advanced: false,
|
|
190
|
+
epochBefore: refusedEpoch,
|
|
191
|
+
epochAfter: refusedEpoch
|
|
99
192
|
};
|
|
100
|
-
|
|
101
|
-
entrySlot.install(undefined);
|
|
193
|
+
throw error;
|
|
102
194
|
}
|
|
103
|
-
const advanced = handle().epoch !== before;
|
|
104
|
-
// Durable before it resolves: the lane advances its cursor on this answer, so a crash
|
|
105
|
-
// between applying and persisting would lose the commit and never re-read it.
|
|
106
|
-
if (advanced) await persist?.(handle());
|
|
107
|
-
return {
|
|
108
|
-
advanced
|
|
109
|
-
};
|
|
110
195
|
},
|
|
111
196
|
async createRecoveryRequest (requestID) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
pending.set(requestID, {
|
|
119
|
-
ephemeralPrivateKey,
|
|
120
|
-
mintedAt: Date.now()
|
|
121
|
-
});
|
|
197
|
+
const { request, ephemeralPrivateKey } = await access.read((group)=>createRecoveryRequest({
|
|
198
|
+
group,
|
|
199
|
+
identity,
|
|
200
|
+
requestID
|
|
201
|
+
}));
|
|
202
|
+
pending.put(requestID, ephemeralPrivateKey);
|
|
122
203
|
return utf8.encode(request);
|
|
123
204
|
},
|
|
124
205
|
async sealGroupInfo (request) {
|
|
125
206
|
// Throws for a request this member refuses — a removed requester holds no leaf in
|
|
126
207
|
// this member's tree — and the peer stays silent. Roster-intrinsic, not a check here.
|
|
127
|
-
return await sealGroupInfo({
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
208
|
+
return await access.read((group)=>sealGroupInfo({
|
|
209
|
+
group,
|
|
210
|
+
identity,
|
|
211
|
+
request: new TextDecoder().decode(request)
|
|
212
|
+
}));
|
|
132
213
|
},
|
|
133
214
|
async applyRecovery (sealed, requestID) {
|
|
134
215
|
const held = pending.get(requestID);
|
|
135
216
|
if (held == null) return null;
|
|
136
217
|
let groupInfo;
|
|
137
218
|
try {
|
|
138
|
-
groupInfo = await openSealedGroupInfo({
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
219
|
+
groupInfo = await access.read((group)=>openSealedGroupInfo({
|
|
220
|
+
group,
|
|
221
|
+
sealed,
|
|
222
|
+
requestID,
|
|
223
|
+
ephemeralPrivateKey: held
|
|
224
|
+
}));
|
|
144
225
|
} catch {
|
|
145
226
|
// Bytes this peer cannot open OR cannot trust: a forged reply that merely decrypts
|
|
146
227
|
// fails the membership attestation, and both are `null`.
|
|
147
228
|
return null;
|
|
148
229
|
}
|
|
149
|
-
const rejoined = await joinGroupExternal({
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
230
|
+
const rejoined = await access.read((group)=>joinGroupExternal({
|
|
231
|
+
identity,
|
|
232
|
+
groupInfo,
|
|
233
|
+
credential: group.credential,
|
|
234
|
+
resync: true
|
|
235
|
+
}));
|
|
155
236
|
return {
|
|
156
237
|
commit: rejoined.commitMessage,
|
|
157
238
|
// Adopted ONLY if the hub accepts the commit. A peer that adopted first would sit
|
|
158
239
|
// on a branch of its own the moment it lost the compare-and-set.
|
|
159
240
|
onAccepted: async ()=>{
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
await persist?.(rejoined.group);
|
|
241
|
+
await access.replace(rejoined.group);
|
|
242
|
+
if (pending.get(requestID) === held) pending.delete(requestID);
|
|
163
243
|
}
|
|
164
244
|
};
|
|
165
245
|
},
|
|
166
246
|
async isLedgerComplete () {
|
|
167
|
-
return await
|
|
247
|
+
return await access.read((group)=>group.isLedgerComplete());
|
|
168
248
|
},
|
|
169
249
|
async getLedger () {
|
|
170
|
-
return await
|
|
250
|
+
return await access.read((group)=>group.getLedger());
|
|
171
251
|
},
|
|
172
252
|
async sealLedger (request) {
|
|
173
|
-
return await sealLedger({
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
253
|
+
return await access.read((group)=>sealLedger({
|
|
254
|
+
group,
|
|
255
|
+
request: new TextDecoder().decode(request)
|
|
256
|
+
}));
|
|
177
257
|
},
|
|
178
258
|
async openSealedLedger (sealed, requestID) {
|
|
179
259
|
const held = pending.get(requestID);
|
|
@@ -181,12 +261,12 @@ export function createLedgerEntrySlot() {
|
|
|
181
261
|
try {
|
|
182
262
|
// The key is NOT consumed: every responder answers, and the requester must open the
|
|
183
263
|
// next reply after dropping one.
|
|
184
|
-
return await openSealedLedger({
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
264
|
+
return await access.read((group)=>openSealedLedger({
|
|
265
|
+
group,
|
|
266
|
+
sealed,
|
|
267
|
+
requestID,
|
|
268
|
+
ephemeralPrivateKey: held
|
|
269
|
+
}));
|
|
190
270
|
} catch {
|
|
191
271
|
return null;
|
|
192
272
|
}
|
|
@@ -194,16 +274,31 @@ export function createLedgerEntrySlot() {
|
|
|
194
274
|
async bootstrapLedger (tokens) {
|
|
195
275
|
// Throws for a list whose recomputed head does not match the authenticated one — a
|
|
196
276
|
// lying responder can withhold, never rewrite.
|
|
197
|
-
await
|
|
198
|
-
|
|
277
|
+
await access.mutate(async (group, persist)=>{
|
|
278
|
+
let persisted = false;
|
|
279
|
+
try {
|
|
280
|
+
await group.bootstrapLedger(tokens, {
|
|
281
|
+
persist: async (current)=>{
|
|
282
|
+
await persist(current);
|
|
283
|
+
persisted = true;
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
} catch (error) {
|
|
287
|
+
// A host callback after the write: the stored ledger is complete, so the adapter must
|
|
288
|
+
// still publish this handle.
|
|
289
|
+
if (!persisted) throw error;
|
|
290
|
+
}
|
|
291
|
+
});
|
|
199
292
|
},
|
|
200
293
|
async exportRecoverySecret () {
|
|
201
294
|
// Epoch-INDEPENDENT by construction: the genesis anchor never changes, so a peer
|
|
202
295
|
// stranded at any epoch derives the same rendezvous. See the class doc — this is not
|
|
203
296
|
// a confidential value.
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
297
|
+
const secret = await access.read(params.recoverySecret ?? deriveRecoverySecret);
|
|
298
|
+
if (!(secret instanceof Uint8Array) || secret.length < MIN_RECOVERY_SECRET_BYTES) {
|
|
299
|
+
throw new Error(`recoverySecret: expected at least ${MIN_RECOVERY_SECRET_BYTES} bytes from the host`);
|
|
300
|
+
}
|
|
301
|
+
return secret;
|
|
207
302
|
}
|
|
208
303
|
};
|
|
209
304
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kumiai/mls-rpc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "The @kumiai/rpc consumer ports (GroupCrypto, GroupMLS) implemented over @kumiai/mls",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mls",
|
|
@@ -26,15 +26,15 @@
|
|
|
26
26
|
],
|
|
27
27
|
"dependencies": {
|
|
28
28
|
"@kokuin/token": "^0.5.0",
|
|
29
|
-
"@kumiai/mls": "^0.
|
|
30
|
-
"@kumiai/rpc": "^0.
|
|
29
|
+
"@kumiai/mls": "^0.10.0",
|
|
30
|
+
"@kumiai/rpc": "^0.10.0",
|
|
31
31
|
"@noble/ciphers": "^2.4.0",
|
|
32
32
|
"@sozai/runtime": "^0.1.0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
|
-
"@kumiai/rpc-conformance": "^0.
|
|
35
|
+
"@kumiai/rpc-conformance": "^0.10.0",
|
|
36
36
|
"ts-mls": "2.0.0-rc.13",
|
|
37
|
-
"vitest": "^
|
|
37
|
+
"vitest": "^5.0.1"
|
|
38
38
|
},
|
|
39
39
|
"publishConfig": {
|
|
40
40
|
"access": "public"
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
|
|
44
44
|
"build:clean": "del lib",
|
|
45
|
-
"build:js": "swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
|
|
46
|
-
"build:types": "tsc --emitDeclarationOnly --skipLibCheck",
|
|
45
|
+
"build:js": "del 'lib/**/*.js' && swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
|
|
46
|
+
"build:types": "del 'lib/**/*.d.ts' 'lib/**/*.d.ts.map' && tsc --emitDeclarationOnly --skipLibCheck",
|
|
47
47
|
"test": "pnpm run test:types && pnpm run test:unit",
|
|
48
48
|
"test:types": "tsc --noEmit --skipLibCheck -p tsconfig.test.json",
|
|
49
49
|
"test:unit": "vitest run"
|