@kumiai/rpc 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ # @kumiai/rpc
2
+
3
+ High-level, MLS-aware group RPC for Enkaku. Wraps the pub/sub hub and the
4
+ broadcast primitives so a group is a first-class messaging substrate: address
5
+ the whole group (events), a subgroup, anycast a request, gather replies, or run
6
+ directed 1:1 RPC (request/stream/channel) to a single member — all over
7
+ epoch-rotating opaque topics, with an authenticated sender on every surface.
@@ -0,0 +1,21 @@
1
+ import type { TransportType } from '@enkaku/transport';
2
+ import { type BroadcastHandler, type BroadcastMessage, type SuppressibleHandler } from '@kumiai/broadcast';
3
+ export type GroupBusServerParams = {
4
+ transport: TransportType<BroadcastMessage, BroadcastMessage>;
5
+ from: string;
6
+ /** Fire-and-forget event procedures: prc -> handler(data, senderDID). */
7
+ eventHandlers: Record<string, (data: unknown, senderDID?: string) => void | Promise<void>>;
8
+ /** Anycast request procedures: prc -> handler(param, { senderDID }) -> result. */
9
+ requestHandlers: Record<string, BroadcastHandler | SuppressibleHandler>;
10
+ sleep?: (ms: number) => Promise<void>;
11
+ getJitterMs?: (maxMs: number) => number;
12
+ };
13
+ /**
14
+ * Bus-side server for a single protocol topic: dispatches plain events to
15
+ * `eventHandlers` and anycast requests to `requestHandlers` (with the same
16
+ * jitter + observe-and-suppress storm-collapse as `createBroadcastResponder`),
17
+ * forwarding the unwrap-recovered `senderDID` to both.
18
+ */
19
+ export declare function createGroupBusServer(params: GroupBusServerParams): {
20
+ dispose: () => Promise<void>;
21
+ };
@@ -0,0 +1,87 @@
1
+ import { defaultJitter, defaultSleep, isSuppressible } from '@kumiai/broadcast';
2
+ const DEFAULT_JITTER_MS = 250;
3
+ const DEFAULT_SUPPRESS_TTL_MS = 30_000;
4
+ /**
5
+ * Bus-side server for a single protocol topic: dispatches plain events to
6
+ * `eventHandlers` and anycast requests to `requestHandlers` (with the same
7
+ * jitter + observe-and-suppress storm-collapse as `createBroadcastResponder`),
8
+ * forwarding the unwrap-recovered `senderDID` to both.
9
+ */ export function createGroupBusServer(params) {
10
+ const { transport, from, eventHandlers, requestHandlers } = params;
11
+ const sleep = params.sleep ?? defaultSleep;
12
+ const getJitterMs = params.getJitterMs ?? defaultJitter;
13
+ const suppressTimers = new Map();
14
+ let running = true;
15
+ const markReplied = (rid, ttlMs)=>{
16
+ if (suppressTimers.has(rid)) return;
17
+ const timer = setTimeout(()=>suppressTimers.delete(rid), ttlMs);
18
+ suppressTimers.set(rid, timer);
19
+ };
20
+ const handleRequest = async (prc, request, handler, senderDID)=>{
21
+ const isGather = request.gather === true;
22
+ if (!isGather && isSuppressible(handler)) {
23
+ const { jitterMs = DEFAULT_JITTER_MS } = handler.suppress;
24
+ await sleep(getJitterMs(jitterMs));
25
+ if (suppressTimers.has(request.rid)) return;
26
+ }
27
+ let reply;
28
+ try {
29
+ const ok = await handler(request.prm, {
30
+ senderDID
31
+ });
32
+ reply = {
33
+ kind: 'res',
34
+ rid: request.rid,
35
+ from,
36
+ ok
37
+ };
38
+ } catch (error) {
39
+ reply = {
40
+ kind: 'res',
41
+ rid: request.rid,
42
+ from,
43
+ err: error instanceof Error ? error.message : String(error)
44
+ };
45
+ }
46
+ const ttlMs = isSuppressible(handler) ? handler.suppress.suppressTtlMs ?? DEFAULT_SUPPRESS_TTL_MS : DEFAULT_SUPPRESS_TTL_MS;
47
+ if (!isGather) markReplied(request.rid, ttlMs);
48
+ await transport.write({
49
+ payload: {
50
+ typ: 'event',
51
+ prc,
52
+ data: reply
53
+ }
54
+ }).catch(()=>{});
55
+ };
56
+ void (async ()=>{
57
+ for await (const msg of transport){
58
+ if (!running) break;
59
+ const payload = msg?.payload;
60
+ if (payload?.typ !== 'event' || typeof payload.prc !== 'string') continue;
61
+ const data = payload.data;
62
+ if (data?.kind === 'res' && typeof data.rid === 'string') {
63
+ markReplied(data.rid, DEFAULT_SUPPRESS_TTL_MS);
64
+ continue;
65
+ }
66
+ if (data?.kind === 'req' && typeof data.rid === 'string') {
67
+ const handler = requestHandlers[payload.prc];
68
+ if (handler != null) {
69
+ void handleRequest(payload.prc, data, handler, msg.senderDID);
70
+ }
71
+ continue;
72
+ }
73
+ const eventHandler = eventHandlers[payload.prc];
74
+ if (eventHandler != null) {
75
+ void Promise.resolve(eventHandler(payload.data, msg.senderDID)).catch(()=>{});
76
+ }
77
+ }
78
+ })().catch(()=>{});
79
+ return {
80
+ dispose: async ()=>{
81
+ running = false;
82
+ for (const timer of suppressTimers.values())clearTimeout(timer);
83
+ suppressTimers.clear();
84
+ await transport.dispose();
85
+ }
86
+ };
87
+ }
@@ -0,0 +1,60 @@
1
+ import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
2
+ /**
3
+ * Consumer-supplied MLS crypto port. The consumer adapts its live MLS group into
4
+ * this shape (epoch number, an epoch-bound topic-derivation secret, byte-level
5
+ * encrypt via `wrap`, and decrypt-plus-recover-sender via `unwrap`). group-rpc
6
+ * never imports MLS.
7
+ *
8
+ * `epoch()` and `exportSecret()` are read on init and on every
9
+ * {@link "peer".GroupPeer.resync}. `wrap`/`unwrap` close over the live group, so
10
+ * they always use current epoch state. `unwrap` returns the authenticated
11
+ * sender (`senderDID`) recovered from the ciphertext.
12
+ */
13
+ export type GroupCrypto = {
14
+ epoch(): number;
15
+ exportSecret(): Uint8Array | Promise<Uint8Array>;
16
+ wrap: ByteTransform;
17
+ unwrap: Unwrap;
18
+ };
19
+ /** Context delivered alongside a received Commit on the raw handshake lane. */
20
+ export type CommitContext = {
21
+ /**
22
+ * The hub-authenticated publisher of the frame. This is the transport sender,
23
+ * NOT the MLS-cryptographic committer (the Commit authenticates its committer
24
+ * internally) — auxiliary information (logging, rate-limiting), not an
25
+ * authorization boundary.
26
+ */
27
+ senderDID?: string;
28
+ };
29
+ /**
30
+ * Consumer-supplied MLS lifecycle port. Sibling to {@link GroupCrypto}: where
31
+ * `GroupCrypto` adapts application encrypt/decrypt, this drives the handshake
32
+ * lane — applying Commits to advance the epoch and re-syncing a stranded peer.
33
+ * group-rpc owns the transport + orchestration (subscribe the non-rotating
34
+ * handshake topic, run these methods, resync when the epoch advances); the
35
+ * consumer owns the MLS state and any storage/atomicity, entirely below this
36
+ * interface.
37
+ */
38
+ export type GroupMLS = {
39
+ /**
40
+ * Apply a received Commit to the MLS state and durably persist the result,
41
+ * returning whether the epoch advanced (the signal to resync the app lane).
42
+ * Implementations make this atomic; the orchestration only requires that the
43
+ * write is durable before it resolves.
44
+ */
45
+ processCommit(commit: Uint8Array, context: CommitContext): Promise<{
46
+ advanced: boolean;
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. */
51
+ applyRecovery(groupInfo: Uint8Array): Promise<{
52
+ advanced: boolean;
53
+ }>;
54
+ /**
55
+ * The epoch-independent secret for the non-rotating handshake/recovery topic.
56
+ * Stable for the group's whole life so a stranded peer on any epoch can always
57
+ * derive the rendezvous.
58
+ */
59
+ exportRecoverySecret(): Uint8Array | Promise<Uint8Array>;
60
+ };
package/lib/crypto.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Consumer-supplied MLS lifecycle port. Sibling to {@link GroupCrypto}: where
3
+ * `GroupCrypto` adapts application encrypt/decrypt, this drives the handshake
4
+ * lane — applying Commits to advance the epoch and re-syncing a stranded peer.
5
+ * group-rpc owns the transport + orchestration (subscribe the non-rotating
6
+ * handshake topic, run these methods, resync when the epoch advances); the
7
+ * consumer owns the MLS state and any storage/atomicity, entirely below this
8
+ * interface.
9
+ */ export { };
@@ -0,0 +1,37 @@
1
+ import { Client } from '@enkaku/client';
2
+ import type { ProtocolDefinition } from '@enkaku/protocol';
3
+ import { type ProcedureHandlers } from '@enkaku/server';
4
+ import type { HubMux } from './hub-mux.js';
5
+ export type DirectedClientParams = {
6
+ mux: HubMux;
7
+ localDID: string;
8
+ memberDID: string;
9
+ secret: Uint8Array;
10
+ epoch: number;
11
+ getRandomID?: () => string;
12
+ };
13
+ /**
14
+ * Directed 1:1 RPC client to a single member, over a hub-tunnel transport whose
15
+ * send/receive topics are the two members' inbox topics for the current epoch.
16
+ */
17
+ export declare function createDirectedClient<Protocol extends ProtocolDefinition>(params: DirectedClientParams): {
18
+ client: Client<Protocol>;
19
+ dispose: () => Promise<void>;
20
+ };
21
+ export type InboxAcceptorParams<Protocol extends ProtocolDefinition> = {
22
+ mux: HubMux;
23
+ localDID: string;
24
+ selfInboxTopic: string;
25
+ /** Map an inbound senderDID to the topic we send replies on (their inbox). */
26
+ resolveSendTopic: (senderDID: string) => string;
27
+ protocol: Protocol;
28
+ handlers: ProcedureHandlers<Protocol>;
29
+ };
30
+ /**
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).
34
+ */
35
+ export declare function createInboxAcceptor<Protocol extends ProtocolDefinition>(params: InboxAcceptorParams<Protocol>): {
36
+ dispose: () => Promise<void>;
37
+ };
@@ -0,0 +1,80 @@
1
+ import { Client } from '@enkaku/client';
2
+ import { Server } from '@enkaku/server';
3
+ import { defaultRandomID } from '@kumiai/broadcast';
4
+ import { createHubTunnelTransport, decodeFrame } from '@kumiai/hub-tunnel';
5
+ import { inboxTopic } from './topic.js';
6
+ /**
7
+ * Directed 1:1 RPC client to a single member, over a hub-tunnel transport whose
8
+ * send/receive topics are the two members' inbox topics for the current epoch.
9
+ */ export function createDirectedClient(params) {
10
+ const { mux, localDID, memberDID, secret, epoch } = params;
11
+ const getRandomID = params.getRandomID ?? defaultRandomID;
12
+ const transport = createHubTunnelTransport({
13
+ hub: mux.hubLike,
14
+ sessionID: getRandomID(),
15
+ localDID,
16
+ sendTopicID: inboxTopic(secret, epoch, memberDID),
17
+ receiveTopicID: inboxTopic(secret, epoch, localDID)
18
+ });
19
+ const client = new Client({
20
+ transport,
21
+ serverID: memberDID
22
+ });
23
+ return {
24
+ client,
25
+ dispose: async ()=>{
26
+ await client.dispose();
27
+ }
28
+ };
29
+ }
30
+ /**
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).
34
+ */ export function createInboxAcceptor(params) {
35
+ const { mux, localDID, selfInboxTopic, resolveSendTopic, protocol, handlers } = params;
36
+ const server = new Server({
37
+ protocol,
38
+ handlers,
39
+ requireAuth: false
40
+ });
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;
54
+ }
55
+ if (frame.kind !== 'message') return;
56
+ } catch {
57
+ return;
58
+ }
59
+ if (tunnels.has(sessionID)) return;
60
+ const tunnel = createHubTunnelTransport({
61
+ hub: mux.hubLike,
62
+ sessionID: {
63
+ auto: true
64
+ },
65
+ localDID,
66
+ sendTopicID: resolveSendTopic(message.senderDID),
67
+ receiveTopicID: selfInboxTopic
68
+ });
69
+ tunnels.set(sessionID, tunnel);
70
+ void server.handle(tunnel);
71
+ });
72
+ return {
73
+ dispose: async ()=>{
74
+ unsubscribe();
75
+ for (const tunnel of tunnels.values())void tunnel.dispose();
76
+ tunnels.clear();
77
+ await server.dispose();
78
+ }
79
+ };
80
+ }
@@ -0,0 +1,14 @@
1
+ import type { ProtocolDefinition } from '@enkaku/protocol';
2
+ import { type BroadcastHandler, type SuppressConfig } from '@kumiai/broadcast';
3
+ export type BusHandlerMaps = {
4
+ eventHandlers: Record<string, (data: unknown, senderDID?: string) => void | Promise<void>>;
5
+ requestHandlers: Record<string, BroadcastHandler>;
6
+ };
7
+ /**
8
+ * Adapt native `@enkaku/server` handlers into bus event/request handler maps.
9
+ * `event` procedures become fire-and-forget event handlers; `request` procedures
10
+ * become anycast request handlers (wrapped `suppressible`). `stream`/`channel`
11
+ * and procedures without a handler are omitted — reachable only on the directed
12
+ * inbox server. The authenticated sender is exposed at `ctx.message.payload.iss`.
13
+ */
14
+ export declare function adaptBusHandlers(protocol: ProtocolDefinition, handlers: Record<string, unknown>, suppress?: SuppressConfig): BusHandlerMaps;
@@ -0,0 +1,42 @@
1
+ import { suppressible } from '@kumiai/broadcast';
2
+ /** Minimal bus-path context message: authenticated sender at `payload.iss`. */ function busMessage(senderDID) {
3
+ return {
4
+ payload: {
5
+ iss: senderDID
6
+ }
7
+ };
8
+ }
9
+ /**
10
+ * Adapt native `@enkaku/server` handlers into bus event/request handler maps.
11
+ * `event` procedures become fire-and-forget event handlers; `request` procedures
12
+ * become anycast request handlers (wrapped `suppressible`). `stream`/`channel`
13
+ * and procedures without a handler are omitted — reachable only on the directed
14
+ * inbox server. The authenticated sender is exposed at `ctx.message.payload.iss`.
15
+ */ export function adaptBusHandlers(protocol, handlers, suppress = {}) {
16
+ const eventHandlers = {};
17
+ const requestHandlers = {};
18
+ for (const [prc, definition] of Object.entries(protocol)){
19
+ const handler = handlers[prc];
20
+ if (handler == null) continue;
21
+ if (definition.type === 'event') {
22
+ eventHandlers[prc] = (data, senderDID)=>handler({
23
+ data,
24
+ message: busMessage(senderDID)
25
+ });
26
+ } else if (definition.type === 'request') {
27
+ const fn = (param, context)=>{
28
+ const controller = new AbortController();
29
+ return handler({
30
+ param,
31
+ signal: controller.signal,
32
+ message: busMessage(context?.senderDID)
33
+ });
34
+ };
35
+ requestHandlers[prc] = Object.keys(suppress).length > 0 ? suppressible(fn, suppress) : fn;
36
+ }
37
+ }
38
+ return {
39
+ eventHandlers,
40
+ requestHandlers
41
+ };
42
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Framing for the raw MLS-handshake lane. Unlike application protocols, this
3
+ * lane carries un-`wrap`ped bytes on a single non-rotating topic and multiplexes
4
+ * three message kinds. Each frame is self-identifying:
5
+ *
6
+ * [ MAGIC(2) | VERSION(1) | KIND(1) | payload... ]
7
+ *
8
+ * The magic marks the bytes as a handshake frame (fail-fast on garbage or a
9
+ * mis-routed payload); the version allows the wire format to evolve without an
10
+ * ambiguous unversioned migration; the kind discriminates the three messages.
11
+ */
12
+ /** Leading marker identifying a handshake frame ("EK"). */
13
+ export declare const HANDSHAKE_MAGIC: Uint8Array<ArrayBuffer>;
14
+ /** Current handshake wire-format version. */
15
+ export declare const HANDSHAKE_VERSION = 1;
16
+ /** The message kinds carried on the handshake lane. */
17
+ export declare const HANDSHAKE_KIND: {
18
+ /** An MLS Commit fanned out to advance every member's epoch. */
19
+ readonly commit: 0;
20
+ /** A stranded peer asking the group for current state. */
21
+ readonly recoveryRequest: 1;
22
+ /** A member's reply carrying the state needed to re-sync. */
23
+ readonly recoveryReply: 2;
24
+ };
25
+ export type HandshakeKind = (typeof HANDSHAKE_KIND)[keyof typeof HANDSHAKE_KIND];
26
+ /** Wrap a payload with the magic + version + kind header. */
27
+ export declare function encodeHandshakeFrame(kind: HandshakeKind, payload: Uint8Array): Uint8Array;
28
+ /**
29
+ * Validate the header and split a frame into its kind and payload. Throws on a
30
+ * short frame, a bad magic, an unsupported version, or an unknown kind.
31
+ */
32
+ export declare function decodeHandshakeFrame(frame: Uint8Array): {
33
+ kind: HandshakeKind;
34
+ payload: Uint8Array;
35
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Framing for the raw MLS-handshake lane. Unlike application protocols, this
3
+ * lane carries un-`wrap`ped bytes on a single non-rotating topic and multiplexes
4
+ * three message kinds. Each frame is self-identifying:
5
+ *
6
+ * [ MAGIC(2) | VERSION(1) | KIND(1) | payload... ]
7
+ *
8
+ * The magic marks the bytes as a handshake frame (fail-fast on garbage or a
9
+ * mis-routed payload); the version allows the wire format to evolve without an
10
+ * ambiguous unversioned migration; the kind discriminates the three messages.
11
+ */ /** Leading marker identifying a handshake frame ("EK"). */ export const HANDSHAKE_MAGIC = Uint8Array.from([
12
+ 0x45,
13
+ 0x4b
14
+ ]);
15
+ /** Current handshake wire-format version. */ export const HANDSHAKE_VERSION = 1;
16
+ const HEADER_LENGTH = HANDSHAKE_MAGIC.length + 2;
17
+ /** The message kinds carried on the handshake lane. */ export const HANDSHAKE_KIND = {
18
+ /** An MLS Commit fanned out to advance every member's epoch. */ commit: 0,
19
+ /** A stranded peer asking the group for current state. */ recoveryRequest: 1,
20
+ /** A member's reply carrying the state needed to re-sync. */ recoveryReply: 2
21
+ };
22
+ const KINDS = new Set(Object.values(HANDSHAKE_KIND));
23
+ function isHandshakeKind(value) {
24
+ return KINDS.has(value);
25
+ }
26
+ /** Wrap a payload with the magic + version + kind header. */ export function encodeHandshakeFrame(kind, payload) {
27
+ const frame = new Uint8Array(HEADER_LENGTH + payload.length);
28
+ frame.set(HANDSHAKE_MAGIC, 0);
29
+ frame[HANDSHAKE_MAGIC.length] = HANDSHAKE_VERSION;
30
+ frame[HANDSHAKE_MAGIC.length + 1] = kind;
31
+ frame.set(payload, HEADER_LENGTH);
32
+ return frame;
33
+ }
34
+ /**
35
+ * Validate the header and split a frame into its kind and payload. Throws on a
36
+ * short frame, a bad magic, an unsupported version, or an unknown kind.
37
+ */ export function decodeHandshakeFrame(frame) {
38
+ if (frame.length < HEADER_LENGTH) {
39
+ throw new Error('handshake frame is too short');
40
+ }
41
+ if (frame[0] !== HANDSHAKE_MAGIC[0] || frame[1] !== HANDSHAKE_MAGIC[1]) {
42
+ throw new Error('handshake frame has a bad magic');
43
+ }
44
+ const version = frame[HANDSHAKE_MAGIC.length];
45
+ if (version !== HANDSHAKE_VERSION) {
46
+ throw new Error(`unsupported handshake version: ${version}`);
47
+ }
48
+ const kind = frame[HANDSHAKE_MAGIC.length + 1];
49
+ if (!isHandshakeKind(kind)) {
50
+ throw new Error(`unknown handshake kind: ${kind}`);
51
+ }
52
+ return {
53
+ kind,
54
+ payload: frame.subarray(HEADER_LENGTH)
55
+ };
56
+ }
@@ -0,0 +1,32 @@
1
+ import type { BroadcastBus } from '@kumiai/broadcast';
2
+ import type { StoredMessage } from '@kumiai/hub-protocol';
3
+ import type { HubLike } from '@kumiai/hub-tunnel';
4
+ export type HubMuxParams = {
5
+ hub: HubLike;
6
+ /** Authenticated DID used to drain `hub.receive` and stamp bus publishes. */
7
+ localDID: string;
8
+ };
9
+ /**
10
+ * An onInbound listener. `ack` marks the message durably handled so a durable
11
+ * hub stops redelivering it; a listener that does not need the durability gate
12
+ * (e.g. an idempotent app consumer) may ignore it.
13
+ */
14
+ export type InboundListener = (message: StoredMessage, ack: () => void) => void;
15
+ export type HubMux = {
16
+ readonly bus: BroadcastBus;
17
+ readonly hubLike: HubLike;
18
+ onInbound: (topicID: string, listener: InboundListener) => () => void;
19
+ dispose: () => Promise<void>;
20
+ };
21
+ /**
22
+ * Multiplex a single hub `receive` drain into a BroadcastBus view, a HubLike
23
+ * view (for directed tunnels), and an onInbound hook (for lazy directed-server
24
+ * accept).
25
+ *
26
+ * Per inbound message, in order: (1) fire `onInbound` listeners for the topic,
27
+ * then (2) push to every `hubLike.receive` sink — so a listener may create a
28
+ * directed tunnel synchronously and still receive the triggering frame. Topics
29
+ * are refcounted across all three views: the first registration subscribes on
30
+ * the hub, the last removal unsubscribes.
31
+ */
32
+ export declare function createHubMux(params: HubMuxParams): HubMux;
package/lib/hub-mux.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Multiplex a single hub `receive` drain into a BroadcastBus view, a HubLike
3
+ * view (for directed tunnels), and an onInbound hook (for lazy directed-server
4
+ * accept).
5
+ *
6
+ * Per inbound message, in order: (1) fire `onInbound` listeners for the topic,
7
+ * then (2) push to every `hubLike.receive` sink — so a listener may create a
8
+ * directed tunnel synchronously and still receive the triggering frame. Topics
9
+ * are refcounted across all three views: the first registration subscribes on
10
+ * the hub, the last removal unsubscribes.
11
+ */ export function createHubMux(params) {
12
+ const { hub, localDID } = params;
13
+ const listeners = new Map();
14
+ const refcount = new Map();
15
+ const sinks = new Set();
16
+ let disposed = false;
17
+ const retain = (topicID)=>{
18
+ const next = (refcount.get(topicID) ?? 0) + 1;
19
+ refcount.set(topicID, next);
20
+ if (next === 1) void Promise.resolve(hub.subscribe(localDID, topicID)).catch(()=>{});
21
+ };
22
+ const release = (topicID)=>{
23
+ const current = refcount.get(topicID) ?? 0;
24
+ if (current <= 0) return;
25
+ const next = current - 1;
26
+ if (next === 0) {
27
+ refcount.delete(topicID);
28
+ void Promise.resolve(hub.unsubscribe?.(localDID, topicID)).catch(()=>{});
29
+ } else {
30
+ refcount.set(topicID, next);
31
+ }
32
+ };
33
+ const onInbound = (topicID, listener)=>{
34
+ let set = listeners.get(topicID);
35
+ if (set == null) {
36
+ set = new Set();
37
+ listeners.set(topicID, set);
38
+ }
39
+ set.add(listener);
40
+ retain(topicID);
41
+ let removed = false;
42
+ return ()=>{
43
+ if (removed) return;
44
+ removed = true;
45
+ const current = listeners.get(topicID);
46
+ current?.delete(listener);
47
+ if (current != null && current.size === 0) listeners.delete(topicID);
48
+ release(topicID);
49
+ };
50
+ };
51
+ const subscription = hub.receive(localDID);
52
+ const iterator = subscription[Symbol.asyncIterator]();
53
+ void (async ()=>{
54
+ while(true){
55
+ let result;
56
+ try {
57
+ result = await iterator.next();
58
+ } catch {
59
+ return;
60
+ }
61
+ if (disposed || result.done) return;
62
+ const message = result.value;
63
+ const ack = ()=>{
64
+ void Promise.resolve(subscription.ack?.(message.sequenceID)).catch(()=>{});
65
+ };
66
+ for (const listener of listeners.get(message.topicID) ?? []){
67
+ try {
68
+ listener(message, ack);
69
+ } catch {
70
+ // listener errors must not kill the drain
71
+ }
72
+ }
73
+ for (const sink of [
74
+ ...sinks
75
+ ])sink.push(message);
76
+ }
77
+ })();
78
+ const bus = {
79
+ publish: (topicID, payload)=>Promise.resolve(hub.publish({
80
+ senderDID: localDID,
81
+ topicID,
82
+ payload
83
+ })).then(()=>{}),
84
+ subscribe: (topicID, onMessage)=>onInbound(topicID, (message)=>onMessage(message.payload))
85
+ };
86
+ const hubLike = {
87
+ publish: (publishParams)=>hub.publish(publishParams),
88
+ subscribe: (_subscriberDID, topicID)=>{
89
+ retain(topicID);
90
+ },
91
+ unsubscribe: (_subscriberDID, topicID)=>{
92
+ release(topicID);
93
+ },
94
+ receive: (_subscriberDID)=>{
95
+ const queue = [];
96
+ let resolveNext;
97
+ let closed = false;
98
+ const sink = {
99
+ push: (message)=>{
100
+ if (closed) return;
101
+ if (resolveNext != null) {
102
+ const resolve = resolveNext;
103
+ resolveNext = undefined;
104
+ resolve({
105
+ value: message,
106
+ done: false
107
+ });
108
+ } else {
109
+ queue.push(message);
110
+ }
111
+ },
112
+ close: ()=>{
113
+ closed = true;
114
+ if (resolveNext != null) {
115
+ const resolve = resolveNext;
116
+ resolveNext = undefined;
117
+ resolve({
118
+ value: undefined,
119
+ done: true
120
+ });
121
+ }
122
+ }
123
+ };
124
+ sinks.add(sink);
125
+ const remove = ()=>{
126
+ sink.close();
127
+ sinks.delete(sink);
128
+ };
129
+ const iter = {
130
+ next: ()=>{
131
+ if (queue.length > 0) {
132
+ return Promise.resolve({
133
+ value: queue.shift(),
134
+ done: false
135
+ });
136
+ }
137
+ if (closed) {
138
+ return Promise.resolve({
139
+ value: undefined,
140
+ done: true
141
+ });
142
+ }
143
+ return new Promise((resolve)=>{
144
+ resolveNext = resolve;
145
+ });
146
+ },
147
+ return: ()=>{
148
+ remove();
149
+ return Promise.resolve({
150
+ value: undefined,
151
+ done: true
152
+ });
153
+ }
154
+ };
155
+ return {
156
+ [Symbol.asyncIterator]: ()=>iter,
157
+ return: remove
158
+ };
159
+ }
160
+ };
161
+ return {
162
+ bus,
163
+ hubLike,
164
+ onInbound,
165
+ dispose: async ()=>{
166
+ if (disposed) return;
167
+ disposed = true;
168
+ for (const sink of [
169
+ ...sinks
170
+ ])sink.close();
171
+ sinks.clear();
172
+ for (const topicID of [
173
+ ...refcount.keys()
174
+ ]){
175
+ void Promise.resolve(hub.unsubscribe?.(localDID, topicID)).catch(()=>{});
176
+ }
177
+ refcount.clear();
178
+ listeners.clear();
179
+ iterator.return?.();
180
+ }
181
+ };
182
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * High-level MLS-aware group RPC for Enkaku.
3
+ *
4
+ * @module rpc
5
+ */
6
+ export { defineGroupProtocol, type GroupProtocolDefinition } from '@kumiai/broadcast';
7
+ export type { CommitContext, GroupCrypto, GroupMLS } from './crypto.js';
8
+ export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION, type HandshakeKind, } from './handshake.js';
9
+ export { createMemoryGroupMLS, type MemoryGroupMLS, type MemoryGroupMLSOptions, } from './memory-group-mls.js';
10
+ export { createGroupPeer, type GroupPeer, type GroupPeerParams, type ProtocolSurface, } from './peer.js';
11
+ export { decodeRecoveryReply, decodeRecoveryRequest, encodeRecoveryReply, encodeRecoveryRequest, } from './recovery.js';
12
+ export { discoveryTopic, HANDSHAKE_LABEL, handshakeTopic, INBOX_LABEL, inboxTopic, protocolTopic, } from './topic.js';
package/lib/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * High-level MLS-aware group RPC for Enkaku.
3
+ *
4
+ * @module rpc
5
+ */ export { defineGroupProtocol } from '@kumiai/broadcast';
6
+ export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION } from './handshake.js';
7
+ export { createMemoryGroupMLS } from './memory-group-mls.js';
8
+ export { createGroupPeer } from './peer.js';
9
+ export { decodeRecoveryReply, decodeRecoveryRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
10
+ export { discoveryTopic, HANDSHAKE_LABEL, handshakeTopic, INBOX_LABEL, inboxTopic, protocolTopic } from './topic.js';
@@ -0,0 +1,21 @@
1
+ import type { GroupMLS } from './crypto.js';
2
+ export type MemoryGroupMLS = GroupMLS & {
3
+ epoch: () => number;
4
+ commits: () => number;
5
+ lastSender: () => string | undefined;
6
+ };
7
+ export type MemoryGroupMLSOptions = {
8
+ recoverySecret?: Uint8Array;
9
+ epoch?: number;
10
+ /** Called whenever the modelled epoch advances (e.g. to keep a GroupCrypto in step). */
11
+ onAdvance?: (epoch: number) => void;
12
+ };
13
+ /**
14
+ * In-memory {@link GroupMLS} for exercising peer orchestration WITHOUT real MLS —
15
+ * the group-rpc analogue of `createMemoryBus`. It models a single epoch counter:
16
+ * a non-empty Commit advances it; GroupInfo carries the epoch so a stranded peer
17
+ * can jump forward. The recovery secret is fixed for the instance's life
18
+ * (epoch-independent). NOT real cryptography — a test double for wiring, not a
19
+ * production implementation (a real port adapts a live MLS group).
20
+ */
21
+ export declare function createMemoryGroupMLS(options?: MemoryGroupMLSOptions): MemoryGroupMLS;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * In-memory {@link GroupMLS} for exercising peer orchestration WITHOUT real MLS —
3
+ * the group-rpc analogue of `createMemoryBus`. It models a single epoch counter:
4
+ * a non-empty Commit advances it; GroupInfo carries the epoch so a stranded peer
5
+ * can jump forward. The recovery secret is fixed for the instance's life
6
+ * (epoch-independent). NOT real cryptography — a test double for wiring, not a
7
+ * production implementation (a real port adapts a live MLS group).
8
+ */ export function createMemoryGroupMLS(options = {}) {
9
+ const recoverySecret = options.recoverySecret ?? new Uint8Array(32).fill(0x33);
10
+ let epoch = options.epoch ?? 0;
11
+ let commits = 0;
12
+ let lastSender;
13
+ const advance = (to)=>{
14
+ epoch = to;
15
+ options.onAdvance?.(epoch);
16
+ };
17
+ return {
18
+ epoch: ()=>epoch,
19
+ commits: ()=>commits,
20
+ lastSender: ()=>lastSender,
21
+ async processCommit (commit, context) {
22
+ lastSender = context.senderDID;
23
+ if (commit.length === 0) {
24
+ return {
25
+ advanced: false
26
+ };
27
+ }
28
+ commits += 1;
29
+ advance(epoch + 1);
30
+ return {
31
+ advanced: true
32
+ };
33
+ },
34
+ async exportGroupInfo () {
35
+ return Uint8Array.from([
36
+ epoch
37
+ ]);
38
+ },
39
+ async applyRecovery (groupInfo) {
40
+ const target = groupInfo[0] ?? epoch;
41
+ if (target <= epoch) {
42
+ return {
43
+ advanced: false
44
+ };
45
+ }
46
+ advance(target);
47
+ return {
48
+ advanced: true
49
+ };
50
+ },
51
+ exportRecoverySecret () {
52
+ return recoverySecret;
53
+ }
54
+ };
55
+ }
package/lib/peer.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import type { Client } from '@enkaku/client';
2
+ import type { ProtocolDefinition } from '@enkaku/protocol';
3
+ import type { ProcedureHandlers } from '@enkaku/server';
4
+ import { type GatheredReply, type GatherOptions, type RequestOptions, type SuppressConfig } from '@kumiai/broadcast';
5
+ import type { HubLike } from '@kumiai/hub-tunnel';
6
+ import type { GroupCrypto, GroupMLS } from './crypto.js';
7
+ export type GroupPeerParams<Protocols extends Record<string, ProtocolDefinition>> = {
8
+ hub: HubLike;
9
+ crypto: GroupCrypto;
10
+ /** MLS lifecycle port. When provided, the peer runs the handshake lane. */
11
+ mls?: GroupMLS;
12
+ localDID: string;
13
+ protocols: Protocols;
14
+ handlers: {
15
+ [K in keyof Protocols]: ProcedureHandlers<Protocols[K]>;
16
+ };
17
+ suppress?: SuppressConfig;
18
+ getRandomID?: () => string;
19
+ /** Recovery rendezvous tuning. `getDelayMs` is the responder reply jitter. */
20
+ recovery?: {
21
+ timeoutMs?: number;
22
+ getDelayMs?: () => number;
23
+ };
24
+ };
25
+ export type ProtocolSurface<Protocol extends ProtocolDefinition> = {
26
+ dispatch: (prc: string, data?: Record<string, unknown>) => Promise<void>;
27
+ request: (prc: string, prm?: unknown, options?: RequestOptions) => Promise<unknown>;
28
+ gather: (prc: string, prm?: unknown, options?: GatherOptions) => Promise<Array<GatheredReply>>;
29
+ to: (memberDID: string) => Client<Protocol>;
30
+ };
31
+ export type GroupPeer<Protocols extends Record<string, ProtocolDefinition>> = {
32
+ protocol: <K extends keyof Protocols>(name: K) => ProtocolSurface<Protocols[K]>;
33
+ /**
34
+ * Announce a Commit the consumer just produced (and already applied locally):
35
+ * fan it out on the handshake topic and rebuild this peer's app topics to the
36
+ * now-current epoch. No-op when the peer has no MLS port.
37
+ */
38
+ localCommitted: (commit: Uint8Array) => Promise<void>;
39
+ /**
40
+ * Deep recovery for a peer stranded past the handshake backlog: request current
41
+ * state on the handshake topic, apply the first reply, and resync. Returns
42
+ * whether the epoch advanced. No-op (`advanced:false`) without an MLS port or
43
+ * if no reply arrives before the timeout.
44
+ */
45
+ recover: () => Promise<{
46
+ advanced: boolean;
47
+ }>;
48
+ resync: () => Promise<void>;
49
+ dispose: () => Promise<void>;
50
+ };
51
+ export declare function createGroupPeer<Protocols extends Record<string, ProtocolDefinition>>(params: GroupPeerParams<Protocols>): GroupPeer<Protocols>;
package/lib/peer.js ADDED
@@ -0,0 +1,301 @@
1
+ import { BroadcastClient, createBroadcastTransport, defaultJitter, defaultRandomID } from '@kumiai/broadcast';
2
+ import { createGroupBusServer } from './bus-server.js';
3
+ import { createDirectedClient, createInboxAcceptor } from './directed.js';
4
+ import { adaptBusHandlers } from './handlers.js';
5
+ import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND } from './handshake.js';
6
+ import { createHubMux } from './hub-mux.js';
7
+ import { decodeRecoveryReply, decodeRecoveryRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
8
+ import { handshakeTopic, inboxTopic, protocolTopic } from './topic.js';
9
+ const DEFAULT_RECOVERY_TIMEOUT_MS = 5000;
10
+ const DEFAULT_RECOVERY_JITTER_MS = 250;
11
+ export function createGroupPeer(params) {
12
+ const { hub, crypto, mls, localDID, protocols, handlers, suppress } = params;
13
+ const getRandomID = params.getRandomID;
14
+ const recoveryTimeoutMs = params.recovery?.timeoutMs ?? DEFAULT_RECOVERY_TIMEOUT_MS;
15
+ const getReplyDelayMs = params.recovery?.getDelayMs ?? (()=>defaultJitter(DEFAULT_RECOVERY_JITTER_MS));
16
+ const mux = createHubMux({
17
+ hub,
18
+ localDID
19
+ });
20
+ let runtimes = new Map();
21
+ let secret = new Uint8Array();
22
+ let epoch = 0;
23
+ const buildEpoch = async ()=>{
24
+ secret = await crypto.exportSecret();
25
+ epoch = crypto.epoch();
26
+ const next = new Map();
27
+ for (const [name, protocol] of Object.entries(protocols)){
28
+ const topicID = protocolTopic(secret, epoch, name);
29
+ const client = new BroadcastClient({
30
+ transport: createBroadcastTransport({
31
+ topicID,
32
+ bus: mux.bus,
33
+ wrap: crypto.wrap,
34
+ unwrap: crypto.unwrap
35
+ }),
36
+ ...getRandomID != null ? {
37
+ getRandomID
38
+ } : {}
39
+ });
40
+ const { eventHandlers, requestHandlers } = adaptBusHandlers(protocol, handlers[name], suppress);
41
+ const busServer = createGroupBusServer({
42
+ transport: createBroadcastTransport({
43
+ topicID,
44
+ bus: mux.bus,
45
+ wrap: crypto.wrap,
46
+ unwrap: crypto.unwrap
47
+ }),
48
+ from: localDID,
49
+ eventHandlers,
50
+ requestHandlers
51
+ });
52
+ const acceptor = createInboxAcceptor({
53
+ mux,
54
+ localDID,
55
+ selfInboxTopic: inboxTopic(secret, epoch, localDID),
56
+ resolveSendTopic: (senderDID)=>inboxTopic(secret, epoch, senderDID),
57
+ protocol: protocol,
58
+ handlers: handlers[name]
59
+ });
60
+ next.set(name, {
61
+ client,
62
+ busServer,
63
+ acceptor,
64
+ directed: new Map()
65
+ });
66
+ }
67
+ runtimes = next;
68
+ };
69
+ const teardownEpoch = async ()=>{
70
+ // Disposal order is independent across runtimes and within a runtime, so tear
71
+ // everything down concurrently and surface every failure rather than dying
72
+ // on the first.
73
+ const disposals = [];
74
+ for (const runtime of runtimes.values()){
75
+ for (const directed of runtime.directed.values())disposals.push(directed.dispose());
76
+ runtime.directed.clear();
77
+ disposals.push(runtime.busServer.dispose());
78
+ disposals.push(runtime.acceptor.dispose());
79
+ disposals.push(runtime.client.dispose());
80
+ }
81
+ runtimes = new Map();
82
+ const results = await Promise.allSettled(disposals);
83
+ const reasons = results.flatMap((r)=>r.status === 'rejected' ? [
84
+ r.reason
85
+ ] : []);
86
+ if (reasons.length > 0) {
87
+ throw new AggregateError(reasons, 'Group epoch teardown failed');
88
+ }
89
+ };
90
+ const surfaceFor = (name)=>{
91
+ const runtime = runtimes.get(name);
92
+ if (runtime == null) throw new Error(`Unknown protocol: ${name}`);
93
+ return {
94
+ dispatch: (prc, data)=>runtime.client.dispatch(prc, data),
95
+ request: (prc, prm, options)=>runtime.client.request(prc, prm, options),
96
+ gather: (prc, prm, options)=>runtime.client.gather(prc, prm, options),
97
+ to: (memberDID)=>{
98
+ const cached = runtime.directed.get(memberDID);
99
+ if (cached != null) return cached.client;
100
+ const created = createDirectedClient({
101
+ mux,
102
+ localDID,
103
+ memberDID,
104
+ secret,
105
+ epoch,
106
+ ...getRandomID != null ? {
107
+ getRandomID
108
+ } : {}
109
+ });
110
+ runtime.directed.set(memberDID, created);
111
+ return created.client;
112
+ }
113
+ };
114
+ };
115
+ const rebuildEpoch = async ()=>{
116
+ await teardownEpoch();
117
+ await buildEpoch();
118
+ };
119
+ let handshakeUnsubscribe;
120
+ let handshakeTopicID;
121
+ let handshakeTail = Promise.resolve();
122
+ // Recovery rendezvous state, keyed by requestID.
123
+ const recoveryWaiters = new Map();
124
+ const recoveryTimers = new Map();
125
+ const pendingReplies = new Map();
126
+ const suppressedRequests = new Set();
127
+ // Responder: after a jitter delay, answer a recovery request with current
128
+ // GroupInfo — unless another responder's reply has already been observed
129
+ // (storm-collapse), in which case the scheduled reply is cancelled.
130
+ const handleRecoveryRequest = (requestID)=>{
131
+ if (mls == null || handshakeTopicID == null) return;
132
+ if (suppressedRequests.has(requestID) || pendingReplies.has(requestID)) return;
133
+ const port = mls;
134
+ const topicID = handshakeTopicID;
135
+ const timer = setTimeout(()=>{
136
+ pendingReplies.delete(requestID);
137
+ void (async ()=>{
138
+ try {
139
+ const groupInfo = await port.exportGroupInfo();
140
+ await mux.bus.publish(topicID, encodeHandshakeFrame(HANDSHAKE_KIND.recoveryReply, encodeRecoveryReply(requestID, groupInfo)));
141
+ } catch {
142
+ // a failed reply just means another responder (or a retry) covers it
143
+ }
144
+ })();
145
+ }, getReplyDelayMs());
146
+ pendingReplies.set(requestID, timer);
147
+ };
148
+ // Requester + storm-collapse: a reply resolves the local waiter (if any) and
149
+ // suppresses this peer's own pending reply for the same request.
150
+ const handleRecoveryReply = (reply)=>{
151
+ suppressedRequests.add(reply.requestID);
152
+ const replyTimer = pendingReplies.get(reply.requestID);
153
+ if (replyTimer != null) {
154
+ clearTimeout(replyTimer);
155
+ pendingReplies.delete(reply.requestID);
156
+ }
157
+ const waiter = recoveryWaiters.get(reply.requestID);
158
+ if (waiter != null) {
159
+ recoveryWaiters.delete(reply.requestID);
160
+ const timer = recoveryTimers.get(reply.requestID);
161
+ if (timer != null) {
162
+ clearTimeout(timer);
163
+ recoveryTimers.delete(reply.requestID);
164
+ }
165
+ waiter(reply.groupInfo);
166
+ }
167
+ };
168
+ // Serialize inbound handshake processing: Commits must apply in MLS order, and
169
+ // both processCommit and the epoch rebuild are async. Each op waits for init to
170
+ // finish, then runs to completion before the next begins.
171
+ const onHandshakeMessage = (message, ack)=>{
172
+ handshakeTail = handshakeTail.then(async ()=>{
173
+ await ready;
174
+ if (mls == null) {
175
+ ack();
176
+ return;
177
+ }
178
+ let frame;
179
+ try {
180
+ frame = decodeHandshakeFrame(message.payload);
181
+ } catch {
182
+ ack(); // drop malformed frames; acking stops poison redelivery
183
+ return;
184
+ }
185
+ if (frame.kind === HANDSHAKE_KIND.commit) {
186
+ const { advanced } = await mls.processCommit(frame.payload, {
187
+ senderDID: message.senderDID
188
+ });
189
+ if (advanced) await rebuildEpoch();
190
+ ack(); // durably handled
191
+ return;
192
+ }
193
+ if (frame.kind === HANDSHAKE_KIND.recoveryRequest) {
194
+ handleRecoveryRequest(decodeRecoveryRequest(frame.payload));
195
+ ack();
196
+ return;
197
+ }
198
+ if (frame.kind === HANDSHAKE_KIND.recoveryReply) {
199
+ handleRecoveryReply(decodeRecoveryReply(frame.payload));
200
+ ack();
201
+ return;
202
+ }
203
+ ack();
204
+ }).catch(()=>{
205
+ // processing failed (e.g. processCommit threw) — do NOT ack, so the hub
206
+ // redelivers and we retry.
207
+ });
208
+ };
209
+ const initHandshake = async ()=>{
210
+ if (mls == null) return;
211
+ const recoverySecret = await mls.exportRecoverySecret();
212
+ const topicID = handshakeTopic(recoverySecret);
213
+ handshakeTopicID = topicID;
214
+ // Subscribed once for the peer's whole life — deliberately NOT rebuilt on
215
+ // resync, so a peer stranded on a stale epoch always shares this rendezvous
216
+ // with the live group. Released only on dispose.
217
+ handshakeUnsubscribe = mux.onInbound(topicID, onHandshakeMessage);
218
+ };
219
+ // Fan out a locally-produced Commit and rebuild this peer's app topics. The
220
+ // publish + rebuild ride the same serial tail as inbound processing so they
221
+ // never interleave with a concurrently-received Commit.
222
+ const localCommitted = async (commit)=>{
223
+ await ready;
224
+ if (mls == null || handshakeTopicID == null) return;
225
+ const topicID = handshakeTopicID;
226
+ const frame = encodeHandshakeFrame(HANDSHAKE_KIND.commit, commit);
227
+ const op = handshakeTail.then(async ()=>{
228
+ await mux.bus.publish(topicID, frame);
229
+ await rebuildEpoch();
230
+ });
231
+ handshakeTail = op.catch(()=>{});
232
+ await op;
233
+ };
234
+ const recover = async ()=>{
235
+ await ready;
236
+ if (mls == null || handshakeTopicID == null) return {
237
+ advanced: false
238
+ };
239
+ const port = mls;
240
+ const topicID = handshakeTopicID;
241
+ const requestID = (getRandomID ?? defaultRandomID)();
242
+ const groupInfo = await new Promise((resolve)=>{
243
+ recoveryWaiters.set(requestID, resolve);
244
+ recoveryTimers.set(requestID, setTimeout(()=>{
245
+ recoveryTimers.delete(requestID);
246
+ if (recoveryWaiters.delete(requestID)) resolve(null);
247
+ }, recoveryTimeoutMs));
248
+ void Promise.resolve(mux.bus.publish(topicID, encodeHandshakeFrame(HANDSHAKE_KIND.recoveryRequest, encodeRecoveryRequest(requestID)))).catch(()=>{});
249
+ });
250
+ if (groupInfo == null) return {
251
+ advanced: false
252
+ };
253
+ let result = {
254
+ advanced: false
255
+ };
256
+ const op = handshakeTail.then(async ()=>{
257
+ const r = await port.applyRecovery(groupInfo);
258
+ if (r.advanced) await rebuildEpoch();
259
+ result = r;
260
+ });
261
+ handshakeTail = op.catch(()=>{});
262
+ await op;
263
+ return result;
264
+ };
265
+ const ready = (async ()=>{
266
+ await initHandshake();
267
+ await buildEpoch();
268
+ })();
269
+ const withReady = async (fn)=>{
270
+ await ready;
271
+ return fn();
272
+ };
273
+ return {
274
+ protocol: (name)=>{
275
+ const key = String(name);
276
+ return {
277
+ dispatch: (prc, data)=>withReady(()=>surfaceFor(key).dispatch(prc, data)),
278
+ request: (prc, prm, options)=>withReady(()=>surfaceFor(key).request(prc, prm, options)),
279
+ gather: (prc, prm, options)=>withReady(()=>surfaceFor(key).gather(prc, prm, options)),
280
+ to: (memberDID)=>surfaceFor(key).to(memberDID)
281
+ };
282
+ },
283
+ localCommitted,
284
+ recover,
285
+ resync: async ()=>{
286
+ await ready;
287
+ await rebuildEpoch();
288
+ },
289
+ dispose: async ()=>{
290
+ await ready;
291
+ handshakeUnsubscribe?.();
292
+ for (const timer of recoveryTimers.values())clearTimeout(timer);
293
+ for (const timer of pendingReplies.values())clearTimeout(timer);
294
+ recoveryTimers.clear();
295
+ pendingReplies.clear();
296
+ suppressedRequests.clear();
297
+ await teardownEpoch();
298
+ await mux.dispose();
299
+ }
300
+ };
301
+ }
@@ -0,0 +1,12 @@
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;
8
+ export declare function encodeRecoveryReply(requestID: string, groupInfo: Uint8Array): Uint8Array;
9
+ export declare function decodeRecoveryReply(payload: Uint8Array): {
10
+ requestID: string;
11
+ groupInfo: Uint8Array;
12
+ };
@@ -0,0 +1,35 @@
1
+ import { fromUTF, toUTF } from '@sozai/codec';
2
+ /**
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);
8
+ }
9
+ export function decodeRecoveryRequest(payload) {
10
+ return toUTF(payload);
11
+ }
12
+ export function encodeRecoveryReply(requestID, groupInfo) {
13
+ const rid = fromUTF(requestID);
14
+ if (rid.length > 0xffff) {
15
+ throw new Error('recovery reply requestID is too long');
16
+ }
17
+ const out = new Uint8Array(2 + rid.length + groupInfo.length);
18
+ new DataView(out.buffer).setUint16(0, rid.length, true);
19
+ out.set(rid, 2);
20
+ out.set(groupInfo, 2 + rid.length);
21
+ return out;
22
+ }
23
+ export function decodeRecoveryReply(payload) {
24
+ if (payload.length < 2) {
25
+ throw new Error('recovery reply is too short');
26
+ }
27
+ const ridLen = new DataView(payload.buffer, payload.byteOffset, payload.byteLength).getUint16(0, true);
28
+ if (payload.length < 2 + ridLen) {
29
+ throw new Error('recovery reply is truncated');
30
+ }
31
+ return {
32
+ requestID: toUTF(payload.subarray(2, 2 + ridLen)),
33
+ groupInfo: payload.subarray(2 + ridLen)
34
+ };
35
+ }
package/lib/topic.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** Reserved label for per-member unicast inbox topics. */
2
+ export declare const INBOX_LABEL = "enkaku/inbox/v1";
3
+ /** Reserved label for the non-rotating MLS-handshake/recovery topic. */
4
+ export declare const HANDSHAKE_LABEL = "enkaku/handshake/v1";
5
+ /**
6
+ * Group-scoped broadcast/multicast topic for an application protocol. Opaque to
7
+ * the hub; derivable only by members holding the epoch secret. `scope`
8
+ * discriminates a subgroup (e.g. an ephemeral room) sharing the protocol.
9
+ */
10
+ export declare function protocolTopic(secret: Uint8Array, epoch: number, protocol: string, scope?: string): string;
11
+ /**
12
+ * Group-scoped personal inbox topic for unicast/directed RPC to `memberDID`.
13
+ * Opaque; derivable only by fellow members. Uses the reserved {@link INBOX_LABEL}
14
+ * so it never collides with an application protocol of the same name.
15
+ */
16
+ export declare function inboxTopic(secret: Uint8Array, epoch: number, memberDID: string): string;
17
+ /**
18
+ * The non-rotating MLS-handshake/recovery topic, derived from the
19
+ * epoch-independent recovery secret (epoch fixed at `0`). Stable for the group's
20
+ * whole life so every member — including one stranded on a stale epoch — can
21
+ * always derive the rendezvous. Opaque to the hub.
22
+ */
23
+ export declare function handshakeTopic(recoverySecret: Uint8Array): string;
24
+ /**
25
+ * Public, secretless pre-group rendezvous topic (invite / keypackage / Welcome).
26
+ * `b64url(SHA-256(DISCOVERY_PREFIX ‖ SEP ‖ memberDID))` — intentionally
27
+ * enumerable from the DID alone; the published domain-separation tag makes it
28
+ * nothing-up-my-sleeve.
29
+ */
30
+ export declare function discoveryTopic(memberDID: string): string;
package/lib/topic.js ADDED
@@ -0,0 +1,37 @@
1
+ import { deriveTopicID } from '@kumiai/broadcast';
2
+ import { sha256 } from '@noble/hashes/sha2.js';
3
+ import { fromUTF, toB64U } from '@sozai/codec';
4
+ /** Reserved label for per-member unicast inbox topics. */ export const INBOX_LABEL = 'enkaku/inbox/v1';
5
+ /** Reserved label for the non-rotating MLS-handshake/recovery topic. */ export const HANDSHAKE_LABEL = 'enkaku/handshake/v1';
6
+ const DISCOVERY_PREFIX = 'enkaku/discovery/v1';
7
+ const SEP = '\0';
8
+ /**
9
+ * Group-scoped broadcast/multicast topic for an application protocol. Opaque to
10
+ * the hub; derivable only by members holding the epoch secret. `scope`
11
+ * discriminates a subgroup (e.g. an ephemeral room) sharing the protocol.
12
+ */ export function protocolTopic(secret, epoch, protocol, scope = '') {
13
+ return deriveTopicID(secret, epoch, protocol, scope);
14
+ }
15
+ /**
16
+ * Group-scoped personal inbox topic for unicast/directed RPC to `memberDID`.
17
+ * Opaque; derivable only by fellow members. Uses the reserved {@link INBOX_LABEL}
18
+ * so it never collides with an application protocol of the same name.
19
+ */ export function inboxTopic(secret, epoch, memberDID) {
20
+ return deriveTopicID(secret, epoch, INBOX_LABEL, memberDID);
21
+ }
22
+ /**
23
+ * The non-rotating MLS-handshake/recovery topic, derived from the
24
+ * epoch-independent recovery secret (epoch fixed at `0`). Stable for the group's
25
+ * whole life so every member — including one stranded on a stale epoch — can
26
+ * always derive the rendezvous. Opaque to the hub.
27
+ */ export function handshakeTopic(recoverySecret) {
28
+ return deriveTopicID(recoverySecret, 0, HANDSHAKE_LABEL);
29
+ }
30
+ /**
31
+ * Public, secretless pre-group rendezvous topic (invite / keypackage / Welcome).
32
+ * `b64url(SHA-256(DISCOVERY_PREFIX ‖ SEP ‖ memberDID))` — intentionally
33
+ * enumerable from the DID alone; the published domain-separation tag makes it
34
+ * nothing-up-my-sleeve.
35
+ */ export function discoveryTopic(memberDID) {
36
+ return toB64U(sha256(fromUTF(`${DISCOVERY_PREFIX}${SEP}${memberDID}`)));
37
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@kumiai/rpc",
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "High-level MLS-aware group RPC for Enkaku: bus broadcast/anycast/gather plus directed RPC over the pub/sub hub",
6
+ "keywords": [
7
+ "rpc",
8
+ "group",
9
+ "mls",
10
+ "pubsub",
11
+ "broadcast"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/TairuFramework/kumiai",
16
+ "directory": "packages/rpc"
17
+ },
18
+ "type": "module",
19
+ "main": "lib/index.js",
20
+ "types": "lib/index.d.ts",
21
+ "exports": {
22
+ ".": "./lib/index.js"
23
+ },
24
+ "files": [
25
+ "lib/*"
26
+ ],
27
+ "sideEffects": false,
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",
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"
38
+ },
39
+ "devDependencies": {
40
+ "vitest": "^4.1.9"
41
+ },
42
+ "scripts": {
43
+ "build:clean": "del lib",
44
+ "build:js": "swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
45
+ "build:types": "tsc --emitDeclarationOnly --skipLibCheck",
46
+ "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
47
+ "test:types": "tsc --noEmit --skipLibCheck -p tsconfig.test.json",
48
+ "test:unit": "vitest run",
49
+ "test": "pnpm run test:types && pnpm run test:unit"
50
+ }
51
+ }