@koralabs/handle-chat-sdk 0.0.13 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +6 -0
- package/README.md +97 -0
- package/assets/libsignal_bg.wasm +0 -0
- package/examples/guardian-flow.mjs +88 -0
- package/examples/quickstart.mjs +74 -0
- package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.d.ts +187 -0
- package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.js +860 -0
- package/lib/src/chat/ChatService.d.ts +113 -0
- package/lib/src/chat/ChatService.js +643 -0
- package/lib/src/chat/anchor.d.ts +17 -0
- package/lib/src/chat/anchor.js +43 -0
- package/lib/src/chat/blob.d.ts +41 -0
- package/lib/src/chat/blob.js +146 -0
- package/lib/src/chat/chainDirectory.d.ts +29 -0
- package/lib/src/chat/chainDirectory.js +51 -0
- package/lib/src/chat/directory.d.ts +14 -0
- package/lib/src/chat/directory.js +14 -0
- package/lib/src/chat/guardian.d.ts +73 -0
- package/lib/src/chat/guardian.js +55 -0
- package/lib/src/chat/identity.d.ts +28 -0
- package/lib/src/chat/identity.js +55 -0
- package/lib/src/chat/invite.d.ts +12 -0
- package/lib/src/chat/invite.js +55 -0
- package/lib/src/chat/mesh/b2b.d.ts +17 -0
- package/lib/src/chat/mesh/b2b.js +50 -0
- package/lib/src/chat/mesh/client.d.ts +25 -0
- package/lib/src/chat/mesh/client.js +133 -0
- package/lib/src/chat/mesh/node.d.ts +12 -0
- package/lib/src/chat/mesh/node.js +46 -0
- package/lib/src/chat/mesh/presenceAuth.d.ts +19 -0
- package/lib/src/chat/mesh/presenceAuth.js +46 -0
- package/lib/src/chat/mesh/protocol.d.ts +57 -0
- package/lib/src/chat/mesh/protocol.js +8 -0
- package/lib/src/chat/mesh/webrtcAddr.d.ts +3 -0
- package/lib/src/chat/mesh/webrtcAddr.js +14 -0
- package/lib/src/chat/mesh/wire.d.ts +5 -0
- package/lib/src/chat/mesh/wire.js +36 -0
- package/lib/src/chat/message.d.ts +28 -0
- package/lib/src/chat/message.js +92 -0
- package/lib/src/chat/publish.d.ts +6 -0
- package/lib/src/chat/publish.js +22 -0
- package/lib/src/chat/qr.d.ts +9 -0
- package/lib/src/chat/qr.js +25 -0
- package/lib/src/chat/receipt.d.ts +17 -0
- package/lib/src/chat/receipt.js +22 -0
- package/lib/src/chat/sessionStore.d.ts +65 -0
- package/lib/src/chat/sessionStore.js +138 -0
- package/lib/src/chat/transport.d.ts +51 -0
- package/lib/src/chat/transport.js +79 -0
- package/lib/src/index.d.ts +19 -0
- package/lib/src/index.js +18 -0
- package/lib/src/memory.d.ts +18 -0
- package/lib/src/memory.js +44 -0
- package/lib/src/signal/SignalEngine.d.ts +68 -0
- package/lib/src/signal/SignalEngine.js +121 -0
- package/package.json +43 -19
- package/index.d.ts +0 -8
- package/index.js +0 -8
- package/interfaces/Chat.d.ts +0 -33
- package/interfaces/Chat.js +0 -1
- package/interfaces/Directory.d.ts +0 -27
- package/interfaces/Directory.js +0 -1
- package/interfaces/SessionMessage.d.ts +0 -15
- package/interfaces/SessionMessage.js +0 -1
- package/interfaces/Store.d.ts +0 -29
- package/interfaces/Store.js +0 -1
- package/lib/SignalDirectory.d.ts +0 -23
- package/lib/SignalDirectory.js +0 -157
- package/lib/SignalProtocolStore.d.ts +0 -46
- package/lib/SignalProtocolStore.js +0 -195
- package/lib/helper.d.ts +0 -2
- package/lib/helper.js +0 -17
- package/lib/helper.test.d.ts +0 -1
- package/lib/helper.test.js +0 -10
- package/lib/message-helper.d.ts +0 -20
- package/lib/message-helper.js +0 -53
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { multiaddr } from "@multiformats/multiaddr";
|
|
2
|
+
import { readFrame, sendFrame } from "./wire.js";
|
|
3
|
+
import { waitForWebrtcAddr } from "./webrtcAddr.js";
|
|
4
|
+
/**
|
|
5
|
+
* The device-mesh primitive: two browsers connect **directly** over WebRTC. A circuit-relay superpeer
|
|
6
|
+
* only brokers the handshake (it carries no conversation); after that the data channel is peer-to-peer.
|
|
7
|
+
* Self-contained (own module) so its WebRTC deps load only when direct delivery is used — not in the
|
|
8
|
+
* mailbox mesh chunk. Ported from `poc/src/browser/b2b.ts`.
|
|
9
|
+
*/
|
|
10
|
+
export const B2B_PROTOCOL = "/handle-chat/b2b/1.0.0";
|
|
11
|
+
/** A browser node that can be dialed directly over WebRTC, reachable for the handshake via a relay. */
|
|
12
|
+
export async function createWebrtcNode() {
|
|
13
|
+
// Loaded here, not at module top, so importing B2B_PROTOCOL/dialDirect never pulls in the WebRTC stack.
|
|
14
|
+
const [{ createLibp2p }, { webSockets }, { webRTC }, { circuitRelayTransport }, { noise }, { yamux }, { identify }] = await Promise.all([
|
|
15
|
+
import("libp2p"),
|
|
16
|
+
import("@libp2p/websockets"),
|
|
17
|
+
import("@libp2p/webrtc"),
|
|
18
|
+
import("@libp2p/circuit-relay-v2"),
|
|
19
|
+
import("@chainsafe/libp2p-noise"),
|
|
20
|
+
import("@chainsafe/libp2p-yamux"),
|
|
21
|
+
import("@libp2p/identify"),
|
|
22
|
+
]);
|
|
23
|
+
return createLibp2p({
|
|
24
|
+
addresses: { listen: ["/p2p-circuit", "/webrtc"] },
|
|
25
|
+
transports: [webSockets(), webRTC(), circuitRelayTransport()],
|
|
26
|
+
connectionEncrypters: [noise()],
|
|
27
|
+
streamMuxers: [yamux()],
|
|
28
|
+
services: { identify: identify() },
|
|
29
|
+
connectionGater: { denyDialMultiaddr: () => false },
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** Reserve a relay slot, accept direct messages, and return our dialable /webrtc address. */
|
|
33
|
+
export async function startDirectListener(relayAddr, onMessage) {
|
|
34
|
+
const node = await createWebrtcNode();
|
|
35
|
+
await node.handle(B2B_PROTOCOL, (stream) => {
|
|
36
|
+
void (async () => {
|
|
37
|
+
onMessage(new TextDecoder().decode(await readFrame(stream)));
|
|
38
|
+
await stream.close().catch(() => { });
|
|
39
|
+
})();
|
|
40
|
+
});
|
|
41
|
+
await node.dial(multiaddr(relayAddr)); // reserve a relay slot so we're reachable for the handshake
|
|
42
|
+
return { node, addr: await waitForWebrtcAddr(node) };
|
|
43
|
+
}
|
|
44
|
+
/** Connect to a peer's /webrtc address (handshake brokered by the relay) and send directly. */
|
|
45
|
+
export async function dialDirect(node, targetAddr, text) {
|
|
46
|
+
const stream = await node.dialProtocol(multiaddr(targetAddr), B2B_PROTOCOL);
|
|
47
|
+
sendFrame(stream, new TextEncoder().encode(text));
|
|
48
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
49
|
+
await stream.close().catch(() => { });
|
|
50
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type WireEnvelope } from "./protocol";
|
|
2
|
+
import type { RegistrationSigner } from "../transport";
|
|
3
|
+
/**
|
|
4
|
+
* The mesh client: one WebRTC-capable node that registers its presence with the helper, receives direct
|
|
5
|
+
* (peer-to-peer) envelopes AND polls the mailbox, and sends DIRECT-FIRST — dialing the recipient
|
|
6
|
+
* peer-to-peer when they're online (helper only brokers the handshake), falling back to the helper's
|
|
7
|
+
* store-and-forward mailbox when they're not. The helper becomes optional for live chat.
|
|
8
|
+
*/
|
|
9
|
+
export declare class MeshClient {
|
|
10
|
+
private readonly node;
|
|
11
|
+
private readonly helperAddr;
|
|
12
|
+
private readonly ref;
|
|
13
|
+
private readonly refresh;
|
|
14
|
+
private readonly poll;
|
|
15
|
+
private readonly reRegister;
|
|
16
|
+
private constructor();
|
|
17
|
+
static start(helperAddr: string, keys: string[], onEnvelope: (e: WireEnvelope) => void, pollMs?: number, signer?: RegistrationSigner): Promise<MeshClient>;
|
|
18
|
+
/** Replace the active label set (called on a topic-rotation rollover) and register the new labels now. The
|
|
19
|
+
* signer authenticates the public-slot labels among them (Tier 2 Stage 3). */
|
|
20
|
+
setKeys(keys: string[], signer?: RegistrationSigner): void;
|
|
21
|
+
/** Send DIRECT-FIRST: dial the recipient peer-to-peer if present, else store in the mailbox. Resolves
|
|
22
|
+
* `true` if delivered/stored, `false` if neither path could take it (helper unreachable → caller queues). */
|
|
23
|
+
send(env: WireEnvelope): Promise<boolean>;
|
|
24
|
+
stop(): Promise<void>;
|
|
25
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { multiaddr } from "@multiformats/multiaddr";
|
|
2
|
+
import { createWebrtcNode } from "./b2b.js";
|
|
3
|
+
import { request } from "./node.js";
|
|
4
|
+
import { readFrame, sendFrame } from "./wire.js";
|
|
5
|
+
import { waitForWebrtcAddr } from "./webrtcAddr.js";
|
|
6
|
+
import { MAILBOX_PROTOCOL, PRESENCE_PROTOCOL, DIRECT_PROTOCOL, } from "./protocol.js";
|
|
7
|
+
const enc = new TextEncoder();
|
|
8
|
+
const dec = new TextDecoder();
|
|
9
|
+
const b64 = (b) => {
|
|
10
|
+
let s = "";
|
|
11
|
+
for (const x of b)
|
|
12
|
+
s += String.fromCharCode(x);
|
|
13
|
+
return btoa(s);
|
|
14
|
+
};
|
|
15
|
+
/** Build a presence registration for one routing label: an AUTHENTICATED public-slot registration if the
|
|
16
|
+
* signer vouches for it (Tier 2 Stage 3), else an unauthenticated pairwise one. */
|
|
17
|
+
const registration = (key, addr, signer) => {
|
|
18
|
+
const auth = signer(key, addr);
|
|
19
|
+
return auth
|
|
20
|
+
? { op: "register", key, addr, slot: "public", epoch: auth.epoch, pub: b64(auth.pub), sig: b64(auth.sig) }
|
|
21
|
+
: { op: "register", key, addr, slot: "pairwise" };
|
|
22
|
+
};
|
|
23
|
+
async function jsonReq(node, addr, protocol, req) {
|
|
24
|
+
const bytes = await request(node, addr, protocol, enc.encode(JSON.stringify(req)));
|
|
25
|
+
return JSON.parse(dec.decode(bytes));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The mesh client: one WebRTC-capable node that registers its presence with the helper, receives direct
|
|
29
|
+
* (peer-to-peer) envelopes AND polls the mailbox, and sends DIRECT-FIRST — dialing the recipient
|
|
30
|
+
* peer-to-peer when they're online (helper only brokers the handshake), falling back to the helper's
|
|
31
|
+
* store-and-forward mailbox when they're not. The helper becomes optional for live chat.
|
|
32
|
+
*/
|
|
33
|
+
export class MeshClient {
|
|
34
|
+
node;
|
|
35
|
+
helperAddr;
|
|
36
|
+
ref;
|
|
37
|
+
refresh;
|
|
38
|
+
poll;
|
|
39
|
+
reRegister;
|
|
40
|
+
constructor(node, helperAddr, ref, refresh, poll, reRegister) {
|
|
41
|
+
this.node = node;
|
|
42
|
+
this.helperAddr = helperAddr;
|
|
43
|
+
this.ref = ref;
|
|
44
|
+
this.refresh = refresh;
|
|
45
|
+
this.poll = poll;
|
|
46
|
+
this.reRegister = reRegister;
|
|
47
|
+
}
|
|
48
|
+
static async start(helperAddr, keys, onEnvelope, pollMs = 1500, signer = () => null) {
|
|
49
|
+
const node = await createWebrtcNode();
|
|
50
|
+
// A failed start must not leak the running libp2p node (its listeners keep the process alive).
|
|
51
|
+
try {
|
|
52
|
+
// Receive direct, peer-to-peer envelopes.
|
|
53
|
+
await node.handle(DIRECT_PROTOCOL, (stream) => {
|
|
54
|
+
void (async () => {
|
|
55
|
+
try {
|
|
56
|
+
onEnvelope(JSON.parse(dec.decode(await readFrame(stream))));
|
|
57
|
+
await stream.close().catch(() => { });
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
stream.abort(new Error("bad direct envelope"));
|
|
61
|
+
}
|
|
62
|
+
})();
|
|
63
|
+
});
|
|
64
|
+
// Reach the helper (relay + presence + mailbox) and learn our dialable /webrtc address.
|
|
65
|
+
await node.dial(multiaddr(helperAddr));
|
|
66
|
+
const myAddr = await waitForWebrtcAddr(node);
|
|
67
|
+
// Our rotating label set (updatable via setKeys). Register presence + poll the mailbox under EACH.
|
|
68
|
+
const ref = { keys: [...keys], signer, myAddr };
|
|
69
|
+
const register = async () => {
|
|
70
|
+
for (const key of ref.keys)
|
|
71
|
+
await jsonReq(node, helperAddr, PRESENCE_PROTOCOL, registration(key, ref.myAddr, ref.signer)).catch(() => { });
|
|
72
|
+
};
|
|
73
|
+
await register();
|
|
74
|
+
const reRegister = setInterval(() => void register(), 30_000); // refresh before the helper's TTL
|
|
75
|
+
const drain = async () => {
|
|
76
|
+
for (const key of ref.keys) {
|
|
77
|
+
const res = await jsonReq(node, helperAddr, MAILBOX_PROTOCOL, { op: "fetch", to: key }).catch(() => null);
|
|
78
|
+
if (res && "envelopes" in res)
|
|
79
|
+
for (const env of res.envelopes)
|
|
80
|
+
onEnvelope(env);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
void drain().catch(() => { });
|
|
84
|
+
const poll = setInterval(() => void drain().catch(() => { }), pollMs);
|
|
85
|
+
return new MeshClient(node, helperAddr, ref, () => void register(), poll, reRegister);
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
await Promise.resolve(node.stop()).catch(() => { });
|
|
89
|
+
throw err;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Replace the active label set (called on a topic-rotation rollover) and register the new labels now. The
|
|
93
|
+
* signer authenticates the public-slot labels among them (Tier 2 Stage 3). */
|
|
94
|
+
setKeys(keys, signer = this.ref.signer) {
|
|
95
|
+
this.ref.keys = [...keys];
|
|
96
|
+
this.ref.signer = signer;
|
|
97
|
+
this.refresh();
|
|
98
|
+
}
|
|
99
|
+
/** Send DIRECT-FIRST: dial the recipient peer-to-peer if present, else store in the mailbox. Resolves
|
|
100
|
+
* `true` if delivered/stored, `false` if neither path could take it (helper unreachable → caller queues). */
|
|
101
|
+
async send(env) {
|
|
102
|
+
const res = await jsonReq(this.node, this.helperAddr, PRESENCE_PROTOCOL, {
|
|
103
|
+
op: "lookup",
|
|
104
|
+
key: env.to,
|
|
105
|
+
slot: env.slot ?? "pairwise",
|
|
106
|
+
}).catch(() => ({ addr: null }));
|
|
107
|
+
const addr = "addr" in res ? res.addr : null;
|
|
108
|
+
if (addr) {
|
|
109
|
+
try {
|
|
110
|
+
const stream = await this.node.dialProtocol(multiaddr(addr), DIRECT_PROTOCOL);
|
|
111
|
+
sendFrame(stream, enc.encode(JSON.stringify(env)));
|
|
112
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
113
|
+
await stream.close().catch(() => { });
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
// present but unreachable (NAT etc.) — fall through to the mailbox
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const r = await jsonReq(this.node, this.helperAddr, MAILBOX_PROTOCOL, { op: "store", envelope: env });
|
|
122
|
+
return "ok" in r && r.ok === true;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async stop() {
|
|
129
|
+
clearInterval(this.poll);
|
|
130
|
+
clearInterval(this.reRegister);
|
|
131
|
+
await this.node.stop();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Libp2p } from "@libp2p/interface";
|
|
2
|
+
/**
|
|
3
|
+
* A WebSocket-only libp2p node — dial-only in the browser, or listening for the helper (pass `listen`).
|
|
4
|
+
* esbuild's `platform: browser` resolves @libp2p/websockets to its dial-only browser build, so this same
|
|
5
|
+
* module bundles for the app and runs (listening) under node for the helper.
|
|
6
|
+
*/
|
|
7
|
+
export declare function createNode(listen?: string[]): Promise<Libp2p>;
|
|
8
|
+
export type RequestHandler = (req: Uint8Array) => Promise<Uint8Array>;
|
|
9
|
+
/** Register a one-shot framed request/response handler for a protocol (helper side). */
|
|
10
|
+
export declare function handleRequests(node: Libp2p, protocol: string, handler: RequestHandler): Promise<void>;
|
|
11
|
+
/** Dial a peer, send one request frame, await one response frame (client side). */
|
|
12
|
+
export declare function request(node: Libp2p, addr: string, protocol: string, req: Uint8Array): Promise<Uint8Array>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createLibp2p } from "libp2p";
|
|
2
|
+
import { webSockets } from "@libp2p/websockets";
|
|
3
|
+
import { noise } from "@chainsafe/libp2p-noise";
|
|
4
|
+
import { yamux } from "@chainsafe/libp2p-yamux";
|
|
5
|
+
import { multiaddr } from "@multiformats/multiaddr";
|
|
6
|
+
import { readFrame, sendFrame } from "./wire.js";
|
|
7
|
+
/**
|
|
8
|
+
* A WebSocket-only libp2p node — dial-only in the browser, or listening for the helper (pass `listen`).
|
|
9
|
+
* esbuild's `platform: browser` resolves @libp2p/websockets to its dial-only browser build, so this same
|
|
10
|
+
* module bundles for the app and runs (listening) under node for the helper.
|
|
11
|
+
*/
|
|
12
|
+
export async function createNode(listen) {
|
|
13
|
+
return createLibp2p({
|
|
14
|
+
...(listen ? { addresses: { listen } } : {}),
|
|
15
|
+
transports: [webSockets()],
|
|
16
|
+
connectionEncrypters: [noise()],
|
|
17
|
+
streamMuxers: [yamux()],
|
|
18
|
+
connectionGater: { denyDialMultiaddr: () => false },
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
/** Register a one-shot framed request/response handler for a protocol (helper side). */
|
|
22
|
+
export async function handleRequests(node, protocol, handler) {
|
|
23
|
+
await node.handle(protocol, (stream) => {
|
|
24
|
+
void (async () => {
|
|
25
|
+
try {
|
|
26
|
+
const req = await readFrame(stream);
|
|
27
|
+
sendFrame(stream, await handler(req));
|
|
28
|
+
await stream.close();
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
stream.abort(err instanceof Error ? err : new Error(String(err)));
|
|
32
|
+
}
|
|
33
|
+
})();
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/** Dial a peer, send one request frame, await one response frame (client side). */
|
|
37
|
+
export async function request(node, addr, protocol, req) {
|
|
38
|
+
const stream = await node.dialProtocol(multiaddr(addr), protocol);
|
|
39
|
+
try {
|
|
40
|
+
sendFrame(stream, req);
|
|
41
|
+
return await readFrame(stream);
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
await stream.close().catch(() => { });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tier 2 Stage 3 — authenticated presence for the public first-contact slot (audit J).
|
|
3
|
+
*
|
|
4
|
+
* The public slot is `topic = HKDF(presence_auth_pub, epoch)` — a per-identity standard-Ed25519 key published
|
|
5
|
+
* in the bundle. A registrant proves ownership by signing `topic ‖ addr ‖ epoch` with the matching private
|
|
6
|
+
* key. This module is the VERIFIER (run by the mesh-helper): it recomputes the topic binding and checks the
|
|
7
|
+
* Ed25519 signature with WebCrypto — so an attacker who knows a victim's (public) presence-auth key can derive
|
|
8
|
+
* the victim's public topic but cannot register it. Must match `libsignal-wasm/src/lib.rs` derive_topic +
|
|
9
|
+
* signPresence byte-for-byte.
|
|
10
|
+
*/
|
|
11
|
+
export declare const presenceEpoch: (now: number) => number;
|
|
12
|
+
/** `topic ‖ addr ‖ epoch_le` — the exact bytes `signPresence` signs in the WASM. */
|
|
13
|
+
export declare function presenceMessage(topic: Uint8Array, addr: string, epoch: number): Uint8Array;
|
|
14
|
+
/** The public first-contact slot label for a presence-auth public key at an epoch: HKDF-SHA256(salt=TOPIC_SALT,
|
|
15
|
+
* ikm=pub, info=`topic:{epoch}`) → 32 bytes. Matches the Rust `derive_topic`. */
|
|
16
|
+
export declare function publicSlotTopic(pub: Uint8Array, epoch: number): Promise<Uint8Array>;
|
|
17
|
+
/** Verify a public-slot presence registration: the topic MUST be this key's slot for `epoch` (binding), and
|
|
18
|
+
* the signature MUST be valid Ed25519 by `pub`. Either failing → reject (the registrant doesn't own the slot). */
|
|
19
|
+
export declare function verifyPresence(pub: Uint8Array, topic: Uint8Array, addr: string, epoch: number, sig: Uint8Array): Promise<boolean>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tier 2 Stage 3 — authenticated presence for the public first-contact slot (audit J).
|
|
3
|
+
*
|
|
4
|
+
* The public slot is `topic = HKDF(presence_auth_pub, epoch)` — a per-identity standard-Ed25519 key published
|
|
5
|
+
* in the bundle. A registrant proves ownership by signing `topic ‖ addr ‖ epoch` with the matching private
|
|
6
|
+
* key. This module is the VERIFIER (run by the mesh-helper): it recomputes the topic binding and checks the
|
|
7
|
+
* Ed25519 signature with WebCrypto — so an attacker who knows a victim's (public) presence-auth key can derive
|
|
8
|
+
* the victim's public topic but cannot register it. Must match `libsignal-wasm/src/lib.rs` derive_topic +
|
|
9
|
+
* signPresence byte-for-byte.
|
|
10
|
+
*/
|
|
11
|
+
// Mirror of the Rust constants/derivation (TOPIC_SALT, derive_topic, TOPIC_ROTATION_MS).
|
|
12
|
+
const TOPIC_SALT = new TextEncoder().encode("koralabs:handle-chat:topic:v1");
|
|
13
|
+
const TOPIC_ROTATION_MS = 24 * 60 * 60 * 1000;
|
|
14
|
+
export const presenceEpoch = (now) => Math.floor(now / TOPIC_ROTATION_MS);
|
|
15
|
+
/** `topic ‖ addr ‖ epoch_le` — the exact bytes `signPresence` signs in the WASM. */
|
|
16
|
+
export function presenceMessage(topic, addr, epoch) {
|
|
17
|
+
const a = new TextEncoder().encode(addr);
|
|
18
|
+
const out = new Uint8Array(topic.length + a.length + 4);
|
|
19
|
+
out.set(topic, 0);
|
|
20
|
+
out.set(a, topic.length);
|
|
21
|
+
new DataView(out.buffer).setUint32(topic.length + a.length, epoch >>> 0, true); // u32 little-endian
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
/** The public first-contact slot label for a presence-auth public key at an epoch: HKDF-SHA256(salt=TOPIC_SALT,
|
|
25
|
+
* ikm=pub, info=`topic:{epoch}`) → 32 bytes. Matches the Rust `derive_topic`. */
|
|
26
|
+
export async function publicSlotTopic(pub, epoch) {
|
|
27
|
+
const key = await crypto.subtle.importKey("raw", buf(pub), "HKDF", false, ["deriveBits"]);
|
|
28
|
+
const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: TOPIC_SALT, info: new TextEncoder().encode(`topic:${epoch}`) }, key, 256);
|
|
29
|
+
return new Uint8Array(bits);
|
|
30
|
+
}
|
|
31
|
+
/** Verify a public-slot presence registration: the topic MUST be this key's slot for `epoch` (binding), and
|
|
32
|
+
* the signature MUST be valid Ed25519 by `pub`. Either failing → reject (the registrant doesn't own the slot). */
|
|
33
|
+
export async function verifyPresence(pub, topic, addr, epoch, sig) {
|
|
34
|
+
const expected = await publicSlotTopic(pub, epoch);
|
|
35
|
+
if (!bytesEqual(expected, topic))
|
|
36
|
+
return false; // the key doesn't bind to this topic → not the owner's slot
|
|
37
|
+
const key = await crypto.subtle.importKey("raw", buf(pub), { name: "Ed25519" }, false, ["verify"]);
|
|
38
|
+
return crypto.subtle.verify({ name: "Ed25519" }, key, buf(sig), buf(presenceMessage(topic, addr, epoch)));
|
|
39
|
+
}
|
|
40
|
+
const bytesEqual = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
41
|
+
// Fresh ArrayBuffer copy — WASM-memory-backed views can't be passed to crypto.subtle directly.
|
|
42
|
+
const buf = (x) => {
|
|
43
|
+
const out = new Uint8Array(x.byteLength);
|
|
44
|
+
out.set(x);
|
|
45
|
+
return out;
|
|
46
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** The store-and-forward mailbox protocol — the helper's one job. */
|
|
2
|
+
export declare const MAILBOX_PROTOCOL = "/handle-chat/mailbox/1.0.0";
|
|
3
|
+
/** An envelope on the wire (JSON-safe): the ciphertext `body` is base64. With sealed sender there is NO
|
|
4
|
+
* sender field, and `to` is a scrambled TOPIC, not a handle — so the helper sees only an opaque routing
|
|
5
|
+
* label + opaque ciphertext: neither who sent it, who receives it, nor any plaintext. */
|
|
6
|
+
export interface WireEnvelope {
|
|
7
|
+
to: string;
|
|
8
|
+
body: string;
|
|
9
|
+
ts: number;
|
|
10
|
+
slot?: "public" | "pairwise";
|
|
11
|
+
}
|
|
12
|
+
export type MailboxRequest = {
|
|
13
|
+
op: "store";
|
|
14
|
+
envelope: WireEnvelope;
|
|
15
|
+
} | {
|
|
16
|
+
op: "fetch";
|
|
17
|
+
to: string;
|
|
18
|
+
};
|
|
19
|
+
export type MailboxResponse = {
|
|
20
|
+
ok: true;
|
|
21
|
+
} | {
|
|
22
|
+
envelopes: WireEnvelope[];
|
|
23
|
+
} | {
|
|
24
|
+
error: string;
|
|
25
|
+
};
|
|
26
|
+
/** Presence: an online peer registers its direct (/webrtc) address under its routing key, so a sender
|
|
27
|
+
* can find it and connect PEER-TO-PEER. The helper learns only the opaque routing key + a multiaddr —
|
|
28
|
+
* it never carries the conversation. (Expires by TTL; refreshed while online.) */
|
|
29
|
+
export declare const PRESENCE_PROTOCOL = "/handle-chat/presence/1.0.0";
|
|
30
|
+
/** Presence lives in TWO tables (Tier 2 Stage 3). `public` = the first-contact slot `HKDF(presence_auth_pub,
|
|
31
|
+
* epoch)`: registration is AUTHENTICATED (the helper verifies the Ed25519 `sig` over `key‖addr‖epoch` against
|
|
32
|
+
* `pub`, and that `key == HKDF(pub, epoch)`) so a peer can't blackhole a victim's first-contact slot (audit
|
|
33
|
+
* J). `pairwise` = a per-conversation slot, unguessable without the shared secret, so it needs no auth. A
|
|
34
|
+
* sender looks up the table matching the slot it addressed. `pub`/`sig` are base64. */
|
|
35
|
+
export type PresenceSlot = "public" | "pairwise";
|
|
36
|
+
export type PresenceRequest = {
|
|
37
|
+
op: "register";
|
|
38
|
+
key: string;
|
|
39
|
+
addr: string;
|
|
40
|
+
slot: PresenceSlot;
|
|
41
|
+
epoch?: number;
|
|
42
|
+
pub?: string;
|
|
43
|
+
sig?: string;
|
|
44
|
+
} | {
|
|
45
|
+
op: "lookup";
|
|
46
|
+
key: string;
|
|
47
|
+
slot: PresenceSlot;
|
|
48
|
+
};
|
|
49
|
+
export type PresenceResponse = {
|
|
50
|
+
ok: true;
|
|
51
|
+
} | {
|
|
52
|
+
addr: string | null;
|
|
53
|
+
} | {
|
|
54
|
+
error: string;
|
|
55
|
+
};
|
|
56
|
+
/** Direct peer-to-peer envelope delivery over the WebRTC data channel — bypasses the helper entirely. */
|
|
57
|
+
export declare const DIRECT_PROTOCOL = "/handle-chat/direct/1.0.0";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The store-and-forward mailbox protocol — the helper's one job. */
|
|
2
|
+
export const MAILBOX_PROTOCOL = "/handle-chat/mailbox/1.0.0";
|
|
3
|
+
/** Presence: an online peer registers its direct (/webrtc) address under its routing key, so a sender
|
|
4
|
+
* can find it and connect PEER-TO-PEER. The helper learns only the opaque routing key + a multiaddr —
|
|
5
|
+
* it never carries the conversation. (Expires by TTL; refreshed while online.) */
|
|
6
|
+
export const PRESENCE_PROTOCOL = "/handle-chat/presence/1.0.0";
|
|
7
|
+
/** Direct peer-to-peer envelope delivery over the WebRTC data channel — bypasses the helper entirely. */
|
|
8
|
+
export const DIRECT_PROTOCOL = "/handle-chat/direct/1.0.0";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Poll until the node reports a dialable /webrtc address (learned after reaching the relay/helper). */
|
|
2
|
+
export const waitForWebrtcAddr = (node, timeoutMs = 15_000) => new Promise((resolve, reject) => {
|
|
3
|
+
const deadline = Date.now() + timeoutMs;
|
|
4
|
+
const check = () => {
|
|
5
|
+
const addr = node.getMultiaddrs().map((m) => m.toString()).find((m) => m.includes("/webrtc"));
|
|
6
|
+
if (addr)
|
|
7
|
+
resolve(addr);
|
|
8
|
+
else if (Date.now() > deadline)
|
|
9
|
+
reject(new Error("no /webrtc address obtained"));
|
|
10
|
+
else
|
|
11
|
+
setTimeout(check, 200);
|
|
12
|
+
};
|
|
13
|
+
check();
|
|
14
|
+
});
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Stream } from "@libp2p/interface";
|
|
2
|
+
/** Write one length-prefixed frame. */
|
|
3
|
+
export declare const sendFrame: (stream: Stream, payload: Uint8Array) => void;
|
|
4
|
+
/** Read exactly one length-prefixed frame, reassembling across chunks. */
|
|
5
|
+
export declare const readFrame: (stream: Stream) => Promise<Uint8Array>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Length-prefixed framing over a libp2p v3 message stream (4-byte big-endian length + payload). The
|
|
3
|
+
* stream is an AsyncIterable of byte chunks; a frame may arrive split across chunks, so we reassemble.
|
|
4
|
+
* Ported from `poc/src/mesh/wire.ts` — pure, no node/browser deps.
|
|
5
|
+
*/
|
|
6
|
+
const concat = (a, b) => {
|
|
7
|
+
const out = new Uint8Array(a.length + b.length);
|
|
8
|
+
out.set(a);
|
|
9
|
+
out.set(b, a.length);
|
|
10
|
+
return out;
|
|
11
|
+
};
|
|
12
|
+
const readUint32BE = (b) => ((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]) >>> 0;
|
|
13
|
+
const toBytes = (chunk) => chunk instanceof Uint8Array ? chunk : chunk.subarray();
|
|
14
|
+
/** Write one length-prefixed frame. */
|
|
15
|
+
export const sendFrame = (stream, payload) => {
|
|
16
|
+
const header = new Uint8Array(4);
|
|
17
|
+
header[0] = (payload.length >>> 24) & 0xff;
|
|
18
|
+
header[1] = (payload.length >>> 16) & 0xff;
|
|
19
|
+
header[2] = (payload.length >>> 8) & 0xff;
|
|
20
|
+
header[3] = payload.length & 0xff;
|
|
21
|
+
stream.send(header);
|
|
22
|
+
stream.send(payload);
|
|
23
|
+
};
|
|
24
|
+
/** Read exactly one length-prefixed frame, reassembling across chunks. */
|
|
25
|
+
export const readFrame = async (stream) => {
|
|
26
|
+
let buf = new Uint8Array(0);
|
|
27
|
+
let need = -1;
|
|
28
|
+
for await (const chunk of stream) {
|
|
29
|
+
buf = concat(buf, toBytes(chunk));
|
|
30
|
+
if (need < 0 && buf.length >= 4)
|
|
31
|
+
need = readUint32BE(buf);
|
|
32
|
+
if (need >= 0 && buf.length >= 4 + need)
|
|
33
|
+
return buf.subarray(4, 4 + need);
|
|
34
|
+
}
|
|
35
|
+
throw new Error("stream ended before a full frame arrived");
|
|
36
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export declare const HANDLE_VENDOR_PREFIX = "application/vnd.handle.";
|
|
2
|
+
export declare const TEXT_MIME = "text/plain";
|
|
3
|
+
/** MIME for an app-defined JSON payload, e.g. `jsonMime("guardian-invite")`. */
|
|
4
|
+
export declare const jsonMime: (kind: string) => string;
|
|
5
|
+
export interface ContentMessage {
|
|
6
|
+
/** IANA MIME type — e.g. "text/plain", "image/png", "application/vnd.handle.guardian-invite+json". */
|
|
7
|
+
mime: string;
|
|
8
|
+
/** Raw content bytes (UTF-8 for text, file bytes for media, JSON/CBOR bytes for structured payloads). */
|
|
9
|
+
body: Uint8Array;
|
|
10
|
+
/** Optional descriptors: name, size, width, height, durationMs, … (all stringified). */
|
|
11
|
+
meta?: Record<string, string>;
|
|
12
|
+
}
|
|
13
|
+
export declare function encodeMessage(m: ContentMessage): Uint8Array;
|
|
14
|
+
export declare function decodeMessage(bytes: Uint8Array): ContentMessage;
|
|
15
|
+
export declare const textMessage: (text: string) => ContentMessage;
|
|
16
|
+
export declare const mediaMessage: (mime: string, bytes: Uint8Array, meta?: Record<string, string>) => ContentMessage;
|
|
17
|
+
export declare const jsonMessage: (kind: string, value: unknown, meta?: Record<string, string>) => ContentMessage;
|
|
18
|
+
export declare const isText: (m: ContentMessage) => boolean;
|
|
19
|
+
export declare const isJson: (m: ContentMessage) => boolean;
|
|
20
|
+
export declare const topType: (m: ContentMessage) => string;
|
|
21
|
+
/** Decoded text for a text message (else ""). */
|
|
22
|
+
export declare const messageText: (m: ContentMessage) => string;
|
|
23
|
+
/** Parsed object for a JSON payload (else null). */
|
|
24
|
+
export declare const messageJson: (m: ContentMessage) => unknown;
|
|
25
|
+
/** A short human label for a non-text message (conversation-list preview, fallback render). */
|
|
26
|
+
export declare function mediaLabel(m: ContentMessage): string;
|
|
27
|
+
/** One-line preview for the conversation list. */
|
|
28
|
+
export declare const previewText: (m: ContentMessage) => string;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed message content. A chat message is `{ mime, body, meta }` — the IANA MIME type is the backbone,
|
|
3
|
+
* so text, images, audio, video, and app-defined payloads all share one model and the UI dispatches on
|
|
4
|
+
* the type. App-specific/structured payloads use the vendor tree + structured suffix
|
|
5
|
+
* (`application/vnd.handle.<kind>+json`); opaque custom data uses `application/octet-stream`.
|
|
6
|
+
*
|
|
7
|
+
* This is the INNER plaintext that travels through Signal sealed-sender (so it's E2E-encrypted for free),
|
|
8
|
+
* distinct from the transport `Envelope`. Encoded as a compact binary frame so media bytes ride raw — no
|
|
9
|
+
* base64 bloat. Small payloads are inlined in `body`; a content-addressed `ref` for large blobs can be
|
|
10
|
+
* added later (a bumped version) without breaking this format.
|
|
11
|
+
*/
|
|
12
|
+
const enc = new TextEncoder();
|
|
13
|
+
const dec = new TextDecoder();
|
|
14
|
+
const VERSION = 1;
|
|
15
|
+
export const HANDLE_VENDOR_PREFIX = "application/vnd.handle.";
|
|
16
|
+
export const TEXT_MIME = "text/plain";
|
|
17
|
+
/** MIME for an app-defined JSON payload, e.g. `jsonMime("guardian-invite")`. */
|
|
18
|
+
export const jsonMime = (kind) => `${HANDLE_VENDOR_PREFIX}${kind}+json`;
|
|
19
|
+
// Frame: [version u8][mimeLen u16][mime][metaLen u16][meta-json][bodyLen u32][body]
|
|
20
|
+
export function encodeMessage(m) {
|
|
21
|
+
const mime = enc.encode(m.mime);
|
|
22
|
+
const meta = enc.encode(m.meta && Object.keys(m.meta).length ? JSON.stringify(m.meta) : "");
|
|
23
|
+
const out = new Uint8Array(1 + 2 + mime.length + 2 + meta.length + 4 + m.body.length);
|
|
24
|
+
const dv = new DataView(out.buffer);
|
|
25
|
+
let o = 0;
|
|
26
|
+
out[o++] = VERSION;
|
|
27
|
+
dv.setUint16(o, mime.length);
|
|
28
|
+
o += 2;
|
|
29
|
+
out.set(mime, o);
|
|
30
|
+
o += mime.length;
|
|
31
|
+
dv.setUint16(o, meta.length);
|
|
32
|
+
o += 2;
|
|
33
|
+
out.set(meta, o);
|
|
34
|
+
o += meta.length;
|
|
35
|
+
dv.setUint32(o, m.body.length);
|
|
36
|
+
o += 4;
|
|
37
|
+
out.set(m.body, o);
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
export function decodeMessage(bytes) {
|
|
41
|
+
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
42
|
+
let o = 0;
|
|
43
|
+
const version = bytes[o++];
|
|
44
|
+
if (version !== VERSION)
|
|
45
|
+
throw new Error(`unsupported message version ${version}`);
|
|
46
|
+
const mimeLen = dv.getUint16(o);
|
|
47
|
+
o += 2;
|
|
48
|
+
const mime = dec.decode(bytes.subarray(o, o + mimeLen));
|
|
49
|
+
o += mimeLen;
|
|
50
|
+
const metaLen = dv.getUint16(o);
|
|
51
|
+
o += 2;
|
|
52
|
+
const metaStr = dec.decode(bytes.subarray(o, o + metaLen));
|
|
53
|
+
o += metaLen;
|
|
54
|
+
const bodyLen = dv.getUint32(o);
|
|
55
|
+
o += 4;
|
|
56
|
+
const body = bytes.slice(o, o + bodyLen);
|
|
57
|
+
return { mime, body, meta: metaStr ? JSON.parse(metaStr) : undefined };
|
|
58
|
+
}
|
|
59
|
+
// ---- constructors ----
|
|
60
|
+
export const textMessage = (text) => ({ mime: TEXT_MIME, body: enc.encode(text) });
|
|
61
|
+
export const mediaMessage = (mime, bytes, meta) => ({ mime, body: bytes, meta });
|
|
62
|
+
export const jsonMessage = (kind, value, meta) => ({
|
|
63
|
+
mime: jsonMime(kind),
|
|
64
|
+
body: enc.encode(JSON.stringify(value)),
|
|
65
|
+
meta,
|
|
66
|
+
});
|
|
67
|
+
// ---- inspection ----
|
|
68
|
+
export const isText = (m) => m.mime === TEXT_MIME || m.mime.startsWith("text/");
|
|
69
|
+
export const isJson = (m) => m.mime.endsWith("+json") || m.mime === "application/json";
|
|
70
|
+
export const topType = (m) => m.mime.split("/")[0];
|
|
71
|
+
/** Decoded text for a text message (else ""). */
|
|
72
|
+
export const messageText = (m) => (isText(m) ? dec.decode(m.body) : "");
|
|
73
|
+
/** Parsed object for a JSON payload (else null). */
|
|
74
|
+
export const messageJson = (m) => (isJson(m) ? JSON.parse(dec.decode(m.body)) : null);
|
|
75
|
+
/** A short human label for a non-text message (conversation-list preview, fallback render). */
|
|
76
|
+
export function mediaLabel(m) {
|
|
77
|
+
const name = m.meta?.name;
|
|
78
|
+
switch (topType(m)) {
|
|
79
|
+
case "image":
|
|
80
|
+
return "📷 Image";
|
|
81
|
+
case "audio":
|
|
82
|
+
return "🎤 Audio";
|
|
83
|
+
case "video":
|
|
84
|
+
return "🎬 Video";
|
|
85
|
+
default:
|
|
86
|
+
if (isJson(m))
|
|
87
|
+
return `⚙︎ ${m.mime.slice(HANDLE_VENDOR_PREFIX.length).replace(/\+json$/, "") || "payload"}`;
|
|
88
|
+
return name ? `📎 ${name}` : "📎 File";
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** One-line preview for the conversation list. */
|
|
92
|
+
export const previewText = (m) => (isText(m) ? messageText(m) : mediaLabel(m));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export interface PublishDeps {
|
|
2
|
+
bffUrl: string;
|
|
3
|
+
signTx: (txCbor: string, partialSign?: boolean) => Promise<string>;
|
|
4
|
+
submitTx: (signedTxCbor: string) => Promise<string>;
|
|
5
|
+
}
|
|
6
|
+
export declare function publishAnchor(handle: string, bundle: Uint8Array, address: string, deps: PublishDeps): Promise<string>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Publish a handle's Signal key-bundle as an on-chain anchor (the cold-discovery path). The app is a
|
|
3
|
+
* thin relay — no @cardano-sdk in the bundle: the BFF builds + assembles the tx, the wallet signs +
|
|
4
|
+
* submits. Returns the submitted tx hash.
|
|
5
|
+
*/
|
|
6
|
+
const toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
7
|
+
async function postJson(url, body) {
|
|
8
|
+
const res = await fetch(url, {
|
|
9
|
+
method: "POST",
|
|
10
|
+
headers: { "content-type": "application/json" },
|
|
11
|
+
body: JSON.stringify(body),
|
|
12
|
+
});
|
|
13
|
+
if (!res.ok)
|
|
14
|
+
throw new Error(`${url} → ${res.status}`);
|
|
15
|
+
return (await res.json());
|
|
16
|
+
}
|
|
17
|
+
export async function publishAnchor(handle, bundle, address, deps) {
|
|
18
|
+
const { unsigned } = await postJson(`${deps.bffUrl}/anchor/build`, { handle, bundle: toHex(bundle), address });
|
|
19
|
+
const witness = await deps.signTx(unsigned, true);
|
|
20
|
+
const { signed } = await postJson(`${deps.bffUrl}/anchor/assemble`, { unsigned, witness });
|
|
21
|
+
return deps.submitTx(signed);
|
|
22
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Render `text` as a crisp SVG QR code (a string you can drop into innerHTML). Low error-correction
|
|
3
|
+
* for maximum capacity — invites are big (the post-quantum bundle), so they make a dense QR; the link
|
|
4
|
+
* always works as a fallback. Throws if the text exceeds QR capacity (~2.9 KB).
|
|
5
|
+
*/
|
|
6
|
+
export declare function qrSvg(text: string, opts?: {
|
|
7
|
+
size?: number;
|
|
8
|
+
margin?: number;
|
|
9
|
+
}): string;
|