@kumiai/rpc 0.1.0 → 0.2.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/lib/crypto.d.ts CHANGED
@@ -45,9 +45,18 @@ export type GroupMLS = {
45
45
  processCommit(commit: Uint8Array, context: CommitContext): Promise<{
46
46
  advanced: boolean;
47
47
  }>;
48
- /** Export current group state for a recovery responder to send a stranded peer. */
49
- exportGroupInfo(): Promise<Uint8Array>;
50
- /** Re-sync from a recovery reply, returning whether the epoch advanced. */
48
+ /**
49
+ * Export current group state for a recovery responder, sealed to the
50
+ * requesting member's MLS leaf so only that requester (not the hub, not other
51
+ * members) can open it.
52
+ */
53
+ exportGroupInfo(requesterDID: string): Promise<Uint8Array>;
54
+ /**
55
+ * Re-sync from a sealed recovery reply, returning whether the epoch advanced.
56
+ * The bytes may be hub-injected or sealed to a different member; implementations
57
+ * SHOULD return `{ advanced: false }` for input they cannot open. A throw is also
58
+ * tolerated — the caller treats it as no advance — but returning is preferred.
59
+ */
51
60
  applyRecovery(groupInfo: Uint8Array): Promise<{
52
61
  advanced: boolean;
53
62
  }>;
@@ -0,0 +1,17 @@
1
+ import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
2
+ import type { HubLike } from '@kumiai/hub-tunnel';
3
+ export type SealDirectedHubParams = {
4
+ hub: HubLike;
5
+ wrap: ByteTransform;
6
+ unwrap: Unwrap;
7
+ /** When set, inbound frames whose recovered senderDID != this are dropped. */
8
+ expectedSenderDID?: string;
9
+ };
10
+ /**
11
+ * Wrap a HubLike so directed frames are sealed with `wrap` on publish and opened
12
+ * with `unwrap` on receive. The recovered MLS `senderDID` replaces the
13
+ * hub-asserted one (a lying hub cannot forge it); frames that fail to open,
14
+ * that unwrap without a recovered sender, or whose recovered sender !=
15
+ * `expectedSenderDID`, are dropped.
16
+ */
17
+ export declare function sealDirectedHub(params: SealDirectedHubParams): HubLike;
@@ -0,0 +1,80 @@
1
+ function normalizeUnwrap(result) {
2
+ return result instanceof Uint8Array ? {
3
+ payload: result
4
+ } : result;
5
+ }
6
+ /**
7
+ * Wrap a HubLike so directed frames are sealed with `wrap` on publish and opened
8
+ * with `unwrap` on receive. The recovered MLS `senderDID` replaces the
9
+ * hub-asserted one (a lying hub cannot forge it); frames that fail to open,
10
+ * that unwrap without a recovered sender, or whose recovered sender !=
11
+ * `expectedSenderDID`, are dropped.
12
+ */ export function sealDirectedHub(params) {
13
+ const { hub, wrap, unwrap, expectedSenderDID } = params;
14
+ return {
15
+ async publish (publishParams) {
16
+ const sealed = await wrap(publishParams.payload);
17
+ return hub.publish({
18
+ senderDID: publishParams.senderDID,
19
+ topicID: publishParams.topicID,
20
+ payload: sealed
21
+ });
22
+ },
23
+ subscribe: (subscriberDID, topicID)=>hub.subscribe(subscriberDID, topicID),
24
+ unsubscribe: (subscriberDID, topicID)=>hub.unsubscribe?.(subscriberDID, topicID),
25
+ receive (subscriberDID) {
26
+ const inner = hub.receive(subscriberDID);
27
+ const innerIterator = inner[Symbol.asyncIterator]();
28
+ const iterator = {
29
+ async next () {
30
+ while(true){
31
+ const result = await innerIterator.next();
32
+ if (result.done) {
33
+ return {
34
+ value: undefined,
35
+ done: true
36
+ };
37
+ }
38
+ const message = result.value;
39
+ let opened;
40
+ try {
41
+ opened = normalizeUnwrap(await unwrap(message.payload));
42
+ } catch {
43
+ continue; // un-openable (garbage / another lane) — drop
44
+ }
45
+ if (opened.senderDID == null) {
46
+ continue; // no authenticated sender — never fall back to the hub-asserted one
47
+ }
48
+ if (expectedSenderDID != null && opened.senderDID !== expectedSenderDID) {
49
+ continue;
50
+ }
51
+ return {
52
+ value: {
53
+ sequenceID: message.sequenceID,
54
+ senderDID: opened.senderDID,
55
+ topicID: message.topicID,
56
+ payload: opened.payload
57
+ },
58
+ done: false
59
+ };
60
+ }
61
+ },
62
+ return () {
63
+ innerIterator.return?.();
64
+ return Promise.resolve({
65
+ value: undefined,
66
+ done: true
67
+ });
68
+ }
69
+ };
70
+ return {
71
+ [Symbol.asyncIterator] () {
72
+ return iterator;
73
+ },
74
+ return () {
75
+ inner.return?.();
76
+ }
77
+ };
78
+ }
79
+ };
80
+ }
package/lib/directed.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Client } from '@enkaku/client';
2
2
  import type { ProtocolDefinition } from '@enkaku/protocol';
3
3
  import { type ProcedureHandlers } from '@enkaku/server';
4
+ import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
4
5
  import type { HubMux } from './hub-mux.js';
5
6
  export type DirectedClientParams = {
6
7
  mux: HubMux;
@@ -8,6 +9,8 @@ export type DirectedClientParams = {
8
9
  memberDID: string;
9
10
  secret: Uint8Array;
10
11
  epoch: number;
12
+ wrap: ByteTransform;
13
+ unwrap: Unwrap;
11
14
  getRandomID?: () => string;
12
15
  };
13
16
  /**
@@ -22,15 +25,20 @@ export type InboxAcceptorParams<Protocol extends ProtocolDefinition> = {
22
25
  mux: HubMux;
23
26
  localDID: string;
24
27
  selfInboxTopic: string;
25
- /** Map an inbound senderDID to the topic we send replies on (their inbox). */
28
+ /** Map an authenticated senderDID to the topic we send replies on (their inbox). */
26
29
  resolveSendTopic: (senderDID: string) => string;
27
30
  protocol: Protocol;
28
31
  handlers: ProcedureHandlers<Protocol>;
32
+ wrap: ByteTransform;
33
+ unwrap: Unwrap;
29
34
  };
30
35
  /**
31
- * Accept directed RPC: one shared inbox `Server` plus a lazily-created
32
- * server-side hub-tunnel per inbound session. Relies on the mux delivering the
33
- * triggering frame to the new tunnel's sink (onInbound fires before sinks).
36
+ * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each
37
+ * inbound frame with `unwrap`, binds every session to the MLS-authenticated
38
+ * sender recovered from the ciphertext, and feeds decrypted frame bytes into a
39
+ * per-session in-memory transport whose replies are sealed with `wrap`. Frames
40
+ * whose recovered sender does not match the session binding are dropped, so a
41
+ * malicious hub can neither read the lane nor forge/splice a sender.
34
42
  */
35
43
  export declare function createInboxAcceptor<Protocol extends ProtocolDefinition>(params: InboxAcceptorParams<Protocol>): {
36
44
  dispose: () => Promise<void>;
package/lib/directed.js CHANGED
@@ -2,15 +2,24 @@ import { Client } from '@enkaku/client';
2
2
  import { Server } from '@enkaku/server';
3
3
  import { defaultRandomID } from '@kumiai/broadcast';
4
4
  import { createHubTunnelTransport, decodeFrame } from '@kumiai/hub-tunnel';
5
+ import { sealDirectedHub } from './directed-crypto.js';
5
6
  import { inboxTopic } from './topic.js';
6
7
  /**
7
8
  * Directed 1:1 RPC client to a single member, over a hub-tunnel transport whose
8
9
  * send/receive topics are the two members' inbox topics for the current epoch.
9
10
  */ export function createDirectedClient(params) {
10
- const { mux, localDID, memberDID, secret, epoch } = params;
11
+ const { mux, localDID, memberDID, secret, epoch, wrap, unwrap } = params;
11
12
  const getRandomID = params.getRandomID ?? defaultRandomID;
12
- const transport = createHubTunnelTransport({
13
+ // Replies are authored by `memberDID`; drop anything a lying hub injects under
14
+ // a different MLS sender.
15
+ const sealedHub = sealDirectedHub({
13
16
  hub: mux.hubLike,
17
+ wrap,
18
+ unwrap,
19
+ expectedSenderDID: memberDID
20
+ });
21
+ const transport = createHubTunnelTransport({
22
+ hub: sealedHub,
14
23
  sessionID: getRandomID(),
15
24
  localDID,
16
25
  sendTopicID: inboxTopic(secret, epoch, memberDID),
@@ -27,53 +36,186 @@ import { inboxTopic } from './topic.js';
27
36
  }
28
37
  };
29
38
  }
39
+ function normalizeUnwrap(result) {
40
+ return result instanceof Uint8Array ? {
41
+ payload: result
42
+ } : result;
43
+ }
30
44
  /**
31
- * Accept directed RPC: one shared inbox `Server` plus a lazily-created
32
- * server-side hub-tunnel per inbound session. Relies on the mux delivering the
33
- * triggering frame to the new tunnel's sink (onInbound fires before sinks).
45
+ * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each
46
+ * inbound frame with `unwrap`, binds every session to the MLS-authenticated
47
+ * sender recovered from the ciphertext, and feeds decrypted frame bytes into a
48
+ * per-session in-memory transport whose replies are sealed with `wrap`. Frames
49
+ * whose recovered sender does not match the session binding are dropped, so a
50
+ * malicious hub can neither read the lane nor forge/splice a sender.
34
51
  */ export function createInboxAcceptor(params) {
35
- const { mux, localDID, selfInboxTopic, resolveSendTopic, protocol, handlers } = params;
52
+ const { mux, localDID, selfInboxTopic, resolveSendTopic, protocol, handlers, wrap, unwrap } = params;
36
53
  const server = new Server({
37
54
  protocol,
38
55
  handlers,
39
56
  requireAuth: false
40
57
  });
41
- const tunnels = new Map();
42
- const unsubscribe = mux.onInbound(selfInboxTopic, (message)=>{
43
- let sessionID;
44
- try {
45
- const frame = decodeFrame(message.payload);
46
- sessionID = frame.sessionID;
47
- if (frame.kind === 'session-end') {
48
- const existing = tunnels.get(sessionID);
49
- if (existing != null) {
50
- tunnels.delete(sessionID);
51
- void existing.dispose();
52
- }
53
- return;
58
+ const sessions = new Map();
59
+ const createSession = (senderDID)=>{
60
+ const queue = [];
61
+ let resolveNext;
62
+ let closed = false;
63
+ const sessionHub = {
64
+ async publish (publishParams) {
65
+ const sealed = await wrap(publishParams.payload);
66
+ return mux.hubLike.publish({
67
+ senderDID: publishParams.senderDID,
68
+ topicID: publishParams.topicID,
69
+ payload: sealed
70
+ });
71
+ },
72
+ subscribe () {},
73
+ unsubscribe () {},
74
+ receive () {
75
+ const iter = {
76
+ next () {
77
+ if (queue.length > 0) {
78
+ return Promise.resolve({
79
+ value: queue.shift(),
80
+ done: false
81
+ });
82
+ }
83
+ if (closed) {
84
+ return Promise.resolve({
85
+ value: undefined,
86
+ done: true
87
+ });
88
+ }
89
+ return new Promise((resolve)=>{
90
+ resolveNext = resolve;
91
+ });
92
+ },
93
+ return () {
94
+ closed = true;
95
+ if (resolveNext != null) {
96
+ const resolve = resolveNext;
97
+ resolveNext = undefined;
98
+ resolve({
99
+ value: undefined,
100
+ done: true
101
+ });
102
+ }
103
+ return Promise.resolve({
104
+ value: undefined,
105
+ done: true
106
+ });
107
+ }
108
+ };
109
+ return {
110
+ [Symbol.asyncIterator]: ()=>iter,
111
+ return () {
112
+ closed = true;
113
+ if (resolveNext != null) {
114
+ const resolve = resolveNext;
115
+ resolveNext = undefined;
116
+ resolve({
117
+ value: undefined,
118
+ done: true
119
+ });
120
+ }
121
+ }
122
+ };
54
123
  }
55
- if (frame.kind !== 'message') return;
56
- } catch {
57
- return;
58
- }
59
- if (tunnels.has(sessionID)) return;
124
+ };
60
125
  const tunnel = createHubTunnelTransport({
61
- hub: mux.hubLike,
126
+ hub: sessionHub,
62
127
  sessionID: {
63
128
  auto: true
64
129
  },
65
130
  localDID,
66
- sendTopicID: resolveSendTopic(message.senderDID),
131
+ sendTopicID: resolveSendTopic(senderDID),
67
132
  receiveTopicID: selfInboxTopic
68
133
  });
69
- tunnels.set(sessionID, tunnel);
70
134
  void server.handle(tunnel);
135
+ return {
136
+ senderDID,
137
+ feed: (frameBytes)=>{
138
+ const message = {
139
+ sequenceID: '',
140
+ senderDID,
141
+ topicID: selfInboxTopic,
142
+ payload: frameBytes
143
+ };
144
+ if (resolveNext != null) {
145
+ const resolve = resolveNext;
146
+ resolveNext = undefined;
147
+ resolve({
148
+ value: message,
149
+ done: false
150
+ });
151
+ } else {
152
+ queue.push(message);
153
+ }
154
+ },
155
+ dispose: async ()=>{
156
+ closed = true;
157
+ if (resolveNext != null) {
158
+ const resolve = resolveNext;
159
+ resolveNext = undefined;
160
+ resolve({
161
+ value: undefined,
162
+ done: true
163
+ });
164
+ }
165
+ await tunnel.dispose();
166
+ }
167
+ };
168
+ };
169
+ // Serialize inbound processing: `unwrap` is async (real MLS decrypt has
170
+ // variable latency), so independent concurrent tasks could resolve out of
171
+ // dispatch order — racing to double-create a session, or feeding frames to a
172
+ // tunnel out of wire order (which drops them as stale seq). Chaining each
173
+ // message onto a running tail keeps processing in arrival order.
174
+ let inboundTail = Promise.resolve();
175
+ const unsubscribe = mux.onInbound(selfInboxTopic, (message)=>{
176
+ inboundTail = inboundTail.then(async ()=>{
177
+ let opened;
178
+ try {
179
+ opened = normalizeUnwrap(await unwrap(message.payload));
180
+ } catch {
181
+ return; // un-openable — drop
182
+ }
183
+ const senderDID = opened.senderDID;
184
+ if (senderDID == null) return; // no authenticated sender — drop
185
+ let frame;
186
+ try {
187
+ frame = decodeFrame(opened.payload);
188
+ } catch {
189
+ return;
190
+ }
191
+ const existing = sessions.get(frame.sessionID);
192
+ if (frame.kind === 'session-end') {
193
+ if (existing != null && existing.senderDID === senderDID) {
194
+ sessions.delete(frame.sessionID);
195
+ void existing.dispose();
196
+ }
197
+ return;
198
+ }
199
+ if (frame.kind !== 'message') return;
200
+ if (existing != null) {
201
+ if (existing.senderDID === senderDID) existing.feed(opened.payload);
202
+ return; // sender mismatch on an established session — splice attempt, drop
203
+ }
204
+ const session = createSession(senderDID);
205
+ sessions.set(frame.sessionID, session);
206
+ session.feed(opened.payload);
207
+ }).catch(()=>{
208
+ // a single message's processing failure must not break the chain
209
+ });
71
210
  });
72
211
  return {
73
212
  dispose: async ()=>{
74
213
  unsubscribe();
75
- for (const tunnel of tunnels.values())void tunnel.dispose();
76
- tunnels.clear();
214
+ const pending = [
215
+ ...sessions.values()
216
+ ].map((session)=>session.dispose());
217
+ sessions.clear();
218
+ await Promise.allSettled(pending);
77
219
  await server.dispose();
78
220
  }
79
221
  };
@@ -7,6 +7,8 @@ export type MemoryGroupMLS = GroupMLS & {
7
7
  export type MemoryGroupMLSOptions = {
8
8
  recoverySecret?: Uint8Array;
9
9
  epoch?: number;
10
+ /** This member's DID — modelled recipient of GroupInfo sealed to its leaf. */
11
+ localDID?: string;
10
12
  /** Called whenever the modelled epoch advances (e.g. to keep a GroupCrypto in step). */
11
13
  onAdvance?: (epoch: number) => void;
12
14
  };
@@ -1,3 +1,4 @@
1
+ import { fromUTF, toUTF } from '@sozai/codec';
1
2
  /**
2
3
  * In-memory {@link GroupMLS} for exercising peer orchestration WITHOUT real MLS —
3
4
  * the group-rpc analogue of `createMemoryBus`. It models a single epoch counter:
@@ -7,6 +8,7 @@
7
8
  * production implementation (a real port adapts a live MLS group).
8
9
  */ export function createMemoryGroupMLS(options = {}) {
9
10
  const recoverySecret = options.recoverySecret ?? new Uint8Array(32).fill(0x33);
11
+ const localDID = options.localDID;
10
12
  let epoch = options.epoch ?? 0;
11
13
  let commits = 0;
12
14
  let lastSender;
@@ -14,6 +16,26 @@
14
16
  epoch = to;
15
17
  options.onAdvance?.(epoch);
16
18
  };
19
+ // Seal = [didLen(2)][requesterDID][epoch(1)]. NOT real crypto — a test double
20
+ // that models "only the sealed-to member can open it".
21
+ const seal = (requesterDID, epochByte)=>{
22
+ const did = fromUTF(requesterDID);
23
+ const out = new Uint8Array(2 + did.length + 1);
24
+ new DataView(out.buffer).setUint16(0, did.length, true);
25
+ out.set(did, 2);
26
+ out[2 + did.length] = epochByte;
27
+ return out;
28
+ };
29
+ const open = (sealed)=>{
30
+ if (sealed.length < 3) return undefined;
31
+ const didLen = new DataView(sealed.buffer, sealed.byteOffset, sealed.byteLength).getUint16(0, true);
32
+ if (sealed.length < 2 + didLen + 1) return undefined;
33
+ const sealedTo = toUTF(sealed.subarray(2, 2 + didLen));
34
+ // A member with a set localDID can open only bytes sealed to it. When unset,
35
+ // the double is permissive (used by wiring tests that don't assert sealing).
36
+ if (localDID != null && sealedTo !== localDID) return undefined;
37
+ return sealed[2 + didLen];
38
+ };
17
39
  return {
18
40
  epoch: ()=>epoch,
19
41
  commits: ()=>commits,
@@ -31,14 +53,12 @@
31
53
  advanced: true
32
54
  };
33
55
  },
34
- async exportGroupInfo () {
35
- return Uint8Array.from([
36
- epoch
37
- ]);
56
+ async exportGroupInfo (requesterDID) {
57
+ return seal(requesterDID, epoch);
38
58
  },
39
59
  async applyRecovery (groupInfo) {
40
- const target = groupInfo[0] ?? epoch;
41
- if (target <= epoch) {
60
+ const target = open(groupInfo);
61
+ if (target == null || target <= epoch) {
42
62
  return {
43
63
  advanced: false
44
64
  };
package/lib/peer.js CHANGED
@@ -55,7 +55,9 @@ export function createGroupPeer(params) {
55
55
  selfInboxTopic: inboxTopic(secret, epoch, localDID),
56
56
  resolveSendTopic: (senderDID)=>inboxTopic(secret, epoch, senderDID),
57
57
  protocol: protocol,
58
- handlers: handlers[name]
58
+ handlers: handlers[name],
59
+ wrap: crypto.wrap,
60
+ unwrap: crypto.unwrap
59
61
  });
60
62
  next.set(name, {
61
63
  client,
@@ -103,6 +105,8 @@ export function createGroupPeer(params) {
103
105
  memberDID,
104
106
  secret,
105
107
  epoch,
108
+ wrap: crypto.wrap,
109
+ unwrap: crypto.unwrap,
106
110
  ...getRandomID != null ? {
107
111
  getRandomID
108
112
  } : {}
@@ -127,7 +131,8 @@ export function createGroupPeer(params) {
127
131
  // Responder: after a jitter delay, answer a recovery request with current
128
132
  // GroupInfo — unless another responder's reply has already been observed
129
133
  // (storm-collapse), in which case the scheduled reply is cancelled.
130
- const handleRecoveryRequest = (requestID)=>{
134
+ const handleRecoveryRequest = (request)=>{
135
+ const { requestID, requesterDID } = request;
131
136
  if (mls == null || handshakeTopicID == null) return;
132
137
  if (suppressedRequests.has(requestID) || pendingReplies.has(requestID)) return;
133
138
  const port = mls;
@@ -136,7 +141,7 @@ export function createGroupPeer(params) {
136
141
  pendingReplies.delete(requestID);
137
142
  void (async ()=>{
138
143
  try {
139
- const groupInfo = await port.exportGroupInfo();
144
+ const groupInfo = await port.exportGroupInfo(requesterDID);
140
145
  await mux.bus.publish(topicID, encodeHandshakeFrame(HANDSHAKE_KIND.recoveryReply, encodeRecoveryReply(requestID, groupInfo)));
141
146
  } catch {
142
147
  // a failed reply just means another responder (or a retry) covers it
@@ -245,7 +250,7 @@ export function createGroupPeer(params) {
245
250
  recoveryTimers.delete(requestID);
246
251
  if (recoveryWaiters.delete(requestID)) resolve(null);
247
252
  }, recoveryTimeoutMs));
248
- void Promise.resolve(mux.bus.publish(topicID, encodeHandshakeFrame(HANDSHAKE_KIND.recoveryRequest, encodeRecoveryRequest(requestID)))).catch(()=>{});
253
+ void Promise.resolve(mux.bus.publish(topicID, encodeHandshakeFrame(HANDSHAKE_KIND.recoveryRequest, encodeRecoveryRequest(requestID, localDID)))).catch(()=>{});
249
254
  });
250
255
  if (groupInfo == null) return {
251
256
  advanced: false
@@ -254,7 +259,14 @@ export function createGroupPeer(params) {
254
259
  advanced: false
255
260
  };
256
261
  const op = handshakeTail.then(async ()=>{
257
- const r = await port.applyRecovery(groupInfo);
262
+ let r;
263
+ try {
264
+ r = await port.applyRecovery(groupInfo);
265
+ } catch {
266
+ // A hub-injected or wrong-leaf reply fails to open; treat as no recovery
267
+ // rather than rejecting the public recover() call.
268
+ return;
269
+ }
258
270
  if (r.advanced) await rebuildEpoch();
259
271
  result = r;
260
272
  });
package/lib/recovery.d.ts CHANGED
@@ -1,10 +1,8 @@
1
- /**
2
- * Payload codecs for the recovery rendezvous carried on the handshake lane. A
3
- * request names a `requestID` so replies correlate and redundant responders can
4
- * observe-and-suppress; a reply echoes the `requestID` and carries the GroupInfo.
5
- */
6
- export declare function encodeRecoveryRequest(requestID: string): Uint8Array;
7
- export declare function decodeRecoveryRequest(payload: Uint8Array): string;
1
+ export declare function encodeRecoveryRequest(requestID: string, requesterDID: string): Uint8Array;
2
+ export declare function decodeRecoveryRequest(payload: Uint8Array): {
3
+ requestID: string;
4
+ requesterDID: string;
5
+ };
8
6
  export declare function encodeRecoveryReply(requestID: string, groupInfo: Uint8Array): Uint8Array;
9
7
  export declare function decodeRecoveryReply(payload: Uint8Array): {
10
8
  requestID: string;
package/lib/recovery.js CHANGED
@@ -1,17 +1,57 @@
1
1
  import { fromUTF, toUTF } from '@sozai/codec';
2
2
  /**
3
3
  * Payload codecs for the recovery rendezvous carried on the handshake lane. A
4
- * request names a `requestID` so replies correlate and redundant responders can
5
- * observe-and-suppress; a reply echoes the `requestID` and carries the GroupInfo.
6
- */ export function encodeRecoveryRequest(requestID) {
7
- return fromUTF(requestID);
4
+ * request names a `requestID` (so replies correlate and redundant responders can
5
+ * observe-and-suppress) and the `requesterDID` the responder seals its reply to;
6
+ * a reply echoes the `requestID` and carries the sealed GroupInfo.
7
+ */ /** Cap on decoded ID lengths — these become attacker-controlled map keys. */ const MAX_REQUEST_ID_BYTES = 128;
8
+ const MAX_REQUESTER_DID_BYTES = 512;
9
+ export function encodeRecoveryRequest(requestID, requesterDID) {
10
+ const rid = fromUTF(requestID);
11
+ const did = fromUTF(requesterDID);
12
+ if (rid.length > MAX_REQUEST_ID_BYTES) {
13
+ throw new Error('recovery request requestID is too long');
14
+ }
15
+ if (did.length > MAX_REQUESTER_DID_BYTES) {
16
+ throw new Error('recovery request requesterDID is too long');
17
+ }
18
+ const out = new Uint8Array(2 + rid.length + 2 + did.length);
19
+ const view = new DataView(out.buffer);
20
+ view.setUint16(0, rid.length, true);
21
+ out.set(rid, 2);
22
+ view.setUint16(2 + rid.length, did.length, true);
23
+ out.set(did, 2 + rid.length + 2);
24
+ return out;
8
25
  }
9
26
  export function decodeRecoveryRequest(payload) {
10
- return toUTF(payload);
27
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
28
+ if (payload.length < 2) {
29
+ throw new Error('recovery request is too short');
30
+ }
31
+ const ridLen = view.getUint16(0, true);
32
+ if (ridLen > MAX_REQUEST_ID_BYTES) {
33
+ throw new Error('recovery request requestID is too long');
34
+ }
35
+ if (payload.length < 2 + ridLen + 2) {
36
+ throw new Error('recovery request is truncated');
37
+ }
38
+ const requestID = toUTF(payload.subarray(2, 2 + ridLen));
39
+ const didLen = view.getUint16(2 + ridLen, true);
40
+ if (didLen > MAX_REQUESTER_DID_BYTES) {
41
+ throw new Error('recovery request requesterDID is too long');
42
+ }
43
+ if (payload.length < 2 + ridLen + 2 + didLen) {
44
+ throw new Error('recovery request is truncated');
45
+ }
46
+ const requesterDID = toUTF(payload.subarray(2 + ridLen + 2, 2 + ridLen + 2 + didLen));
47
+ return {
48
+ requestID,
49
+ requesterDID
50
+ };
11
51
  }
12
52
  export function encodeRecoveryReply(requestID, groupInfo) {
13
53
  const rid = fromUTF(requestID);
14
- if (rid.length > 0xffff) {
54
+ if (rid.length > MAX_REQUEST_ID_BYTES) {
15
55
  throw new Error('recovery reply requestID is too long');
16
56
  }
17
57
  const out = new Uint8Array(2 + rid.length + groupInfo.length);
@@ -25,6 +65,9 @@ export function decodeRecoveryReply(payload) {
25
65
  throw new Error('recovery reply is too short');
26
66
  }
27
67
  const ridLen = new DataView(payload.buffer, payload.byteOffset, payload.byteLength).getUint16(0, true);
68
+ if (ridLen > MAX_REQUEST_ID_BYTES) {
69
+ throw new Error('recovery reply requestID is too long');
70
+ }
28
71
  if (payload.length < 2 + ridLen) {
29
72
  throw new Error('recovery reply is truncated');
30
73
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/rpc",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "license": "MIT",
5
5
  "description": "High-level MLS-aware group RPC for Enkaku: bus broadcast/anycast/gather plus directed RPC over the pub/sub hub",
6
6
  "keywords": [
@@ -26,18 +26,18 @@
26
26
  ],
27
27
  "sideEffects": false,
28
28
  "dependencies": {
29
- "@enkaku/client": "^0.18.0",
30
- "@sozai/codec": "^0.1.0",
31
- "@enkaku/protocol": "^0.18.0",
32
- "@enkaku/server": "^0.18.0",
33
- "@enkaku/transport": "^0.18.0",
29
+ "@enkaku/client": "^0.19.0",
30
+ "@sozai/codec": "^0.2.0",
31
+ "@enkaku/protocol": "^0.19.0",
32
+ "@enkaku/server": "^0.19.0",
33
+ "@enkaku/transport": "^0.19.1",
34
34
  "@noble/hashes": "^2.0.0",
35
- "@kumiai/broadcast": "^0.1.0",
36
- "@kumiai/hub-tunnel": "^0.1.0",
37
- "@kumiai/hub-protocol": "^0.1.0"
35
+ "@kumiai/hub-protocol": "^0.2.0",
36
+ "@kumiai/broadcast": "^0.2.0",
37
+ "@kumiai/hub-tunnel": "^0.2.0"
38
38
  },
39
39
  "devDependencies": {
40
- "vitest": "^4.1.9"
40
+ "vitest": "^4.1.10"
41
41
  },
42
42
  "scripts": {
43
43
  "build:clean": "del lib",