@koralabs/handle-chat-sdk 0.0.13 → 1.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.
Files changed (82) hide show
  1. package/LICENSE +6 -0
  2. package/README.md +97 -0
  3. package/assets/libsignal_bg.wasm +0 -0
  4. package/examples/guardian-flow.mjs +88 -0
  5. package/examples/quickstart.mjs +74 -0
  6. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.d.ts +207 -0
  7. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.js +945 -0
  8. package/lib/src/chat/ChatService.d.ts +117 -0
  9. package/lib/src/chat/ChatService.js +922 -0
  10. package/lib/src/chat/anchor.d.ts +17 -0
  11. package/lib/src/chat/anchor.js +43 -0
  12. package/lib/src/chat/blob.d.ts +55 -0
  13. package/lib/src/chat/blob.js +247 -0
  14. package/lib/src/chat/chainDirectory.d.ts +24 -0
  15. package/lib/src/chat/chainDirectory.js +93 -0
  16. package/lib/src/chat/demeter.d.ts +3 -0
  17. package/lib/src/chat/demeter.js +8 -0
  18. package/lib/src/chat/directory.d.ts +24 -0
  19. package/lib/src/chat/directory.js +37 -0
  20. package/lib/src/chat/guardian.d.ts +75 -0
  21. package/lib/src/chat/guardian.js +67 -0
  22. package/lib/src/chat/guardianHistory.d.ts +3 -0
  23. package/lib/src/chat/guardianHistory.js +36 -0
  24. package/lib/src/chat/httpRateLimit.d.ts +5 -0
  25. package/lib/src/chat/httpRateLimit.js +54 -0
  26. package/lib/src/chat/identity.d.ts +28 -0
  27. package/lib/src/chat/identity.js +61 -0
  28. package/lib/src/chat/invite.d.ts +19 -0
  29. package/lib/src/chat/invite.js +73 -0
  30. package/lib/src/chat/mesh/b2b.d.ts +17 -0
  31. package/lib/src/chat/mesh/b2b.js +50 -0
  32. package/lib/src/chat/mesh/client.d.ts +28 -0
  33. package/lib/src/chat/mesh/client.js +209 -0
  34. package/lib/src/chat/mesh/node.d.ts +12 -0
  35. package/lib/src/chat/mesh/node.js +46 -0
  36. package/lib/src/chat/mesh/presenceAuth.d.ts +19 -0
  37. package/lib/src/chat/mesh/presenceAuth.js +46 -0
  38. package/lib/src/chat/mesh/protocol.d.ts +92 -0
  39. package/lib/src/chat/mesh/protocol.js +19 -0
  40. package/lib/src/chat/mesh/webrtcAddr.d.ts +3 -0
  41. package/lib/src/chat/mesh/webrtcAddr.js +14 -0
  42. package/lib/src/chat/mesh/wire.d.ts +5 -0
  43. package/lib/src/chat/mesh/wire.js +36 -0
  44. package/lib/src/chat/message.d.ts +28 -0
  45. package/lib/src/chat/message.js +92 -0
  46. package/lib/src/chat/publish.d.ts +6 -0
  47. package/lib/src/chat/publish.js +33 -0
  48. package/lib/src/chat/qr.d.ts +9 -0
  49. package/lib/src/chat/qr.js +25 -0
  50. package/lib/src/chat/receipt.d.ts +17 -0
  51. package/lib/src/chat/receipt.js +22 -0
  52. package/lib/src/chat/sessionStore.d.ts +74 -0
  53. package/lib/src/chat/sessionStore.js +183 -0
  54. package/lib/src/chat/transport.d.ts +51 -0
  55. package/lib/src/chat/transport.js +139 -0
  56. package/lib/src/index.d.ts +19 -0
  57. package/lib/src/index.js +18 -0
  58. package/lib/src/memory.d.ts +18 -0
  59. package/lib/src/memory.js +44 -0
  60. package/lib/src/signal/SignalEngine.d.ts +73 -0
  61. package/lib/src/signal/SignalEngine.js +131 -0
  62. package/package.json +44 -19
  63. package/index.d.ts +0 -8
  64. package/index.js +0 -8
  65. package/interfaces/Chat.d.ts +0 -33
  66. package/interfaces/Chat.js +0 -1
  67. package/interfaces/Directory.d.ts +0 -27
  68. package/interfaces/Directory.js +0 -1
  69. package/interfaces/SessionMessage.d.ts +0 -15
  70. package/interfaces/SessionMessage.js +0 -1
  71. package/interfaces/Store.d.ts +0 -29
  72. package/interfaces/Store.js +0 -1
  73. package/lib/SignalDirectory.d.ts +0 -23
  74. package/lib/SignalDirectory.js +0 -157
  75. package/lib/SignalProtocolStore.d.ts +0 -46
  76. package/lib/SignalProtocolStore.js +0 -195
  77. package/lib/helper.d.ts +0 -2
  78. package/lib/helper.js +0 -17
  79. package/lib/helper.test.d.ts +0 -1
  80. package/lib/helper.test.js +0 -10
  81. package/lib/message-helper.d.ts +0 -20
  82. package/lib/message-helper.js +0 -53
@@ -0,0 +1,33 @@
1
+ import { providerFetch } from "./httpRateLimit.js";
2
+ /**
3
+ * Publish a handle's Signal key-bundle as an on-chain anchor (the cold-discovery path). The app is a
4
+ * thin relay — no @cardano-sdk in the bundle: the BFF builds + assembles the tx, the wallet signs +
5
+ * submits. Returns the submitted tx hash.
6
+ */
7
+ const toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
8
+ async function postJson(url, body) {
9
+ const absolute = new URL(url, globalThis.location?.origin).href;
10
+ const res = await providerFetch(fetch, absolute, {
11
+ method: "POST",
12
+ headers: { "content-type": "application/json" },
13
+ body: JSON.stringify(body),
14
+ });
15
+ if (!res.ok) {
16
+ if (res.status === 400) {
17
+ const body = await res.json().catch(() => null);
18
+ const reason = body && typeof body === "object" && "error" in body ? body.error : null;
19
+ if (reason === "address is not the current handle owner")
20
+ throw new Error("The selected wallet address does not own this handle.");
21
+ if (typeof reason === "string" && reason.startsWith("no pure-ADA UTxO"))
22
+ throw new Error("The handle address needs a pure-ADA UTxO to publish.");
23
+ }
24
+ throw new Error(`${url} → ${res.status}`);
25
+ }
26
+ return (await res.json());
27
+ }
28
+ export async function publishAnchor(handle, bundle, address, deps) {
29
+ const { unsigned } = await postJson(`${deps.bffUrl}/anchor/build`, { handle, bundle: toHex(bundle), address });
30
+ const witness = await deps.signTx(unsigned, true);
31
+ const { signed } = await postJson(`${deps.bffUrl}/anchor/assemble`, { unsigned, witness });
32
+ return deps.submitTx(signed);
33
+ }
@@ -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;
@@ -0,0 +1,25 @@
1
+ import qrcode from "qrcode-generator";
2
+ /**
3
+ * Render `text` as a crisp SVG QR code (a string you can drop into innerHTML). Low error-correction
4
+ * for maximum capacity — invites are big (the post-quantum bundle), so they make a dense QR; the link
5
+ * always works as a fallback. Throws if the text exceeds QR capacity (~2.9 KB).
6
+ */
7
+ export function qrSvg(text, opts = {}) {
8
+ const qr = qrcode(0, "L"); // 0 = smallest version that fits; L = low EC = max data
9
+ qr.addData(text, "Byte");
10
+ qr.make();
11
+ const count = qr.getModuleCount();
12
+ const margin = opts.margin ?? 2;
13
+ const dim = count + margin * 2;
14
+ const size = opts.size ?? 220;
15
+ let path = "";
16
+ for (let r = 0; r < count; r++) {
17
+ for (let c = 0; c < count; c++) {
18
+ if (qr.isDark(r, c))
19
+ path += `M${c + margin},${r + margin}h1v1h-1z`;
20
+ }
21
+ }
22
+ return (`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" ` +
23
+ `viewBox="0 0 ${dim} ${dim}" shape-rendering="crispEdges">` +
24
+ `<rect width="${dim}" height="${dim}" fill="#fff"/><path fill="#000" d="${path}"/></svg>`);
25
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Delivery + read receipts — control messages that ride the same typed-message channel (so they're E2E
3
+ * for free) but are NEVER surfaced as conversation content. A receipt references a message `id` (stamped
4
+ * into outgoing messages' `meta.id`) and reports its state: `delivered` (arrived at the peer) or `read`
5
+ * (the peer viewed the conversation). The sender uses them to show ✓ / ✓✓ / ✓✓-read indicators.
6
+ */
7
+ import { type ContentMessage } from "./message";
8
+ export declare const RECEIPT_KIND = "receipt";
9
+ export declare const RECEIPT_MIME: string;
10
+ export type ReceiptState = "delivered" | "read";
11
+ export interface Receipt {
12
+ ref: string;
13
+ state: ReceiptState;
14
+ }
15
+ export declare const receiptMessage: (ref: string, state: ReceiptState) => ContentMessage;
16
+ export declare const isReceipt: (c: ContentMessage) => boolean;
17
+ export declare function parseReceipt(c: ContentMessage): Receipt | null;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Delivery + read receipts — control messages that ride the same typed-message channel (so they're E2E
3
+ * for free) but are NEVER surfaced as conversation content. A receipt references a message `id` (stamped
4
+ * into outgoing messages' `meta.id`) and reports its state: `delivered` (arrived at the peer) or `read`
5
+ * (the peer viewed the conversation). The sender uses them to show ✓ / ✓✓ / ✓✓-read indicators.
6
+ */
7
+ import { jsonMime, jsonMessage, messageJson } from "./message.js";
8
+ export const RECEIPT_KIND = "receipt";
9
+ export const RECEIPT_MIME = jsonMime(RECEIPT_KIND);
10
+ export const receiptMessage = (ref, state) => jsonMessage(RECEIPT_KIND, { ref, state });
11
+ export const isReceipt = (c) => c.mime === RECEIPT_MIME;
12
+ export function parseReceipt(c) {
13
+ if (!isReceipt(c))
14
+ return null;
15
+ const v = messageJson(c);
16
+ if (!v || typeof v !== "object")
17
+ return null;
18
+ const { ref, state } = v;
19
+ if (typeof ref !== "string" || (state !== "delivered" && state !== "read"))
20
+ return null;
21
+ return { ref, state };
22
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Per-device session persistence. The Double-Ratchet state is sensitive — it holds keys that decrypt
3
+ * messages — so it is **encrypted at rest** under a key derived from the wallet seed (HKDF, distinct
4
+ * salt from the identity key). Reopening a tab still needs the wallet to re-derive that key; a stolen
5
+ * IndexedDB blob is useless on its own. State is inherently per-device (the ratchet mutates on every
6
+ * message and can't be shared without desync), so this is local-only, scoped to the handle.
7
+ */
8
+ import type { BlobAssemblySnapshot } from "./blob";
9
+ /** What we persist for one handle on this device. The identity key pair is NOT here — it's re-derived
10
+ * from the wallet at sign-in, never stored. */
11
+ export interface SessionSnapshot {
12
+ state: Uint8Array;
13
+ bundle: Uint8Array;
14
+ contacts: string[];
15
+ peerPA?: Record<string, string>;
16
+ inbox?: {
17
+ receipts: [string, number][];
18
+ peerReceipts?: [string, "delivered" | "read"][];
19
+ blobs?: BlobAssemblySnapshot;
20
+ };
21
+ }
22
+ /** One persisted (decrypted) message in a conversation's local history. Typed content: `mime` is the
23
+ * IANA type and `body` is the raw content base64-encoded (JSON-safe at rest); `meta` is optional. */
24
+ export interface StoredMessage {
25
+ from: string;
26
+ mime: string;
27
+ body: string;
28
+ meta?: Record<string, string>;
29
+ ts: number;
30
+ }
31
+ /** An outbound envelope queued while offline — already sealed (ciphertext base64), retried on reconnect. */
32
+ export interface QueuedEnvelope {
33
+ id: string;
34
+ remote: string;
35
+ to: string;
36
+ body: string;
37
+ ts: number;
38
+ track?: boolean;
39
+ }
40
+ export interface SessionVault {
41
+ load(handle: string): Promise<SessionSnapshot | null>;
42
+ save(handle: string, snap: SessionSnapshot): Promise<void>;
43
+ /** Atomically checkpoint inbound ratchet, deduplication and affected histories. */
44
+ commitInbound?(handle: string, snap: SessionSnapshot, histories: ReadonlyMap<string, StoredMessage[]>): Promise<void>;
45
+ /** Outbound queue persisted while offline (survives a reload), retried on reconnect. */
46
+ loadQueue(handle: string): Promise<QueuedEnvelope[] | null>;
47
+ saveQueue(handle: string, queue: QueuedEnvelope[]): Promise<void>;
48
+ /** Per-conversation decrypted message history, encrypted at rest under the same wallet-derived key.
49
+ * Plaintext history is stored because Signal's forward secrecy makes old wire ciphertext
50
+ * undecryptable once the ratchet advances — so "history" must be the decrypted text, re-sealed here. */
51
+ loadHistory(handle: string, remote: string): Promise<StoredMessage[] | null>;
52
+ saveHistory(handle: string, remote: string, messages: StoredMessage[]): Promise<void>;
53
+ }
54
+ export declare function encodeSnapshot(s: SessionSnapshot): Uint8Array;
55
+ export declare function decodeSnapshot(b: Uint8Array): SessionSnapshot;
56
+ /** The standard browser vault: AES-GCM over the snapshot, persisted in IndexedDB keyed by handle. */
57
+ export declare class EncryptedIdbVault implements SessionVault {
58
+ private readonly db;
59
+ private readonly key;
60
+ private constructor();
61
+ static create(seed: Uint8Array): Promise<EncryptedIdbVault>;
62
+ /** AES-GCM seal: [random 12-byte IV][ciphertext]. A fresh IV per write makes one key safe for every blob. */
63
+ private seal;
64
+ private open;
65
+ private get;
66
+ save(handle: string, snap: SessionSnapshot): Promise<void>;
67
+ commitInbound(handle: string, snap: SessionSnapshot, histories: ReadonlyMap<string, StoredMessage[]>): Promise<void>;
68
+ private putRows;
69
+ load(handle: string): Promise<SessionSnapshot | null>;
70
+ saveHistory(handle: string, remote: string, messages: StoredMessage[]): Promise<void>;
71
+ loadHistory(handle: string, remote: string): Promise<StoredMessage[] | null>;
72
+ saveQueue(handle: string, queue: QueuedEnvelope[]): Promise<void>;
73
+ loadQueue(handle: string): Promise<QueuedEnvelope[] | null>;
74
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Per-device session persistence. The Double-Ratchet state is sensitive — it holds keys that decrypt
3
+ * messages — so it is **encrypted at rest** under a key derived from the wallet seed (HKDF, distinct
4
+ * salt from the identity key). Reopening a tab still needs the wallet to re-derive that key; a stolen
5
+ * IndexedDB blob is useless on its own. State is inherently per-device (the ratchet mutates on every
6
+ * message and can't be shared without desync), so this is local-only, scoped to the handle.
7
+ */
8
+ const enc = new TextEncoder();
9
+ const dec = new TextDecoder();
10
+ const AT_REST_SALT = enc.encode("koralabs:handle-chat:session-at-rest:v1");
11
+ const DB_NAME = "handle-chat";
12
+ const STORE = "sessions";
13
+ const u32 = (n) => {
14
+ const b = new Uint8Array(4);
15
+ new DataView(b.buffer).setUint32(0, n);
16
+ return b;
17
+ };
18
+ const concat = (parts) => {
19
+ const total = parts.reduce((n, p) => n + p.length, 0);
20
+ const out = new Uint8Array(total);
21
+ let i = 0;
22
+ for (const p of parts) {
23
+ out.set(p, i);
24
+ i += p.length;
25
+ }
26
+ return out;
27
+ };
28
+ export function encodeSnapshot(s) {
29
+ const parts = [u32(s.state.length), s.state, u32(s.bundle.length), s.bundle, u32(s.contacts.length)];
30
+ for (const c of s.contacts) {
31
+ const cb = enc.encode(c);
32
+ parts.push(u32(cb.length), cb);
33
+ }
34
+ const pa = enc.encode(JSON.stringify(s.peerPA ?? {}));
35
+ parts.push(u32(pa.length), pa);
36
+ if (s.inbox !== undefined) {
37
+ const inbox = enc.encode(JSON.stringify(s.inbox));
38
+ parts.push(u32(inbox.length), inbox);
39
+ }
40
+ return concat(parts);
41
+ }
42
+ export function decodeSnapshot(b) {
43
+ const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
44
+ let i = 0;
45
+ const len = () => {
46
+ const v = dv.getUint32(i);
47
+ i += 4;
48
+ return v;
49
+ };
50
+ const slice = () => {
51
+ const n = len();
52
+ if (n > b.length - i)
53
+ throw new Error("invalid session snapshot length");
54
+ const s = b.subarray(i, i + n);
55
+ i += n;
56
+ return s;
57
+ };
58
+ const state = slice();
59
+ const bundle = slice();
60
+ const count = len();
61
+ const contacts = [];
62
+ for (let k = 0; k < count; k++)
63
+ contacts.push(dec.decode(slice()));
64
+ // blobs saved before presence keys were persisted end after the contacts
65
+ const peerPA = i < b.length ? JSON.parse(dec.decode(slice())) : {};
66
+ if (i === b.length)
67
+ return { state, bundle, contacts, peerPA };
68
+ const inbox = JSON.parse(dec.decode(slice()));
69
+ if (i !== b.length || !inbox || typeof inbox !== "object" || Array.isArray(inbox))
70
+ throw new Error("invalid inbox snapshot");
71
+ const value = inbox;
72
+ if (!Array.isArray(value.receipts) || !value.receipts.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && typeof entry[1] === "number" && Number.isFinite(entry[1])))
73
+ throw new Error("invalid inbox receipts");
74
+ if (value.peerReceipts !== undefined && (!Array.isArray(value.peerReceipts) || !value.peerReceipts.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && (entry[1] === "delivered" || entry[1] === "read"))))
75
+ throw new Error("invalid peer receipts");
76
+ if (value.blobs !== undefined) {
77
+ const blobs = value.blobs;
78
+ if (!blobs || typeof blobs !== "object" || blobs.version !== 1 || !Array.isArray(blobs.pending))
79
+ throw new Error("invalid inbox blobs");
80
+ }
81
+ return { state, bundle, contacts, peerPA, inbox: value };
82
+ }
83
+ /** A guaranteed ArrayBuffer-backed copy — WebCrypto's `BufferSource` rejects the generic
84
+ * `Uint8Array<ArrayBufferLike>` that subarray/params produce under TS 5.7. */
85
+ const ab = (x) => {
86
+ const out = new Uint8Array(x.byteLength);
87
+ out.set(x);
88
+ return out;
89
+ };
90
+ /** HKDF the wallet seed → an AES-GCM-256 key for at-rest encryption (separate salt from the identity). */
91
+ async function deriveAtRestKey(seed) {
92
+ const base = await crypto.subtle.importKey("raw", ab(seed), "HKDF", false, ["deriveKey"]);
93
+ return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: AT_REST_SALT, info: new Uint8Array() }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
94
+ }
95
+ const idb = (db, mode) => db.transaction(STORE, mode).objectStore(STORE);
96
+ const promisify = (req) => new Promise((resolve, reject) => {
97
+ req.onsuccess = () => resolve(req.result);
98
+ req.onerror = () => reject(req.error);
99
+ });
100
+ function openDb() {
101
+ return new Promise((resolve, reject) => {
102
+ const req = indexedDB.open(DB_NAME, 1);
103
+ req.onupgradeneeded = () => req.result.createObjectStore(STORE);
104
+ req.onsuccess = () => resolve(req.result);
105
+ req.onerror = () => reject(req.error);
106
+ });
107
+ }
108
+ /** The standard browser vault: AES-GCM over the snapshot, persisted in IndexedDB keyed by handle. */
109
+ export class EncryptedIdbVault {
110
+ db;
111
+ key;
112
+ constructor(db, key) {
113
+ this.db = db;
114
+ this.key = key;
115
+ }
116
+ static async create(seed) {
117
+ const [db, key] = await Promise.all([openDb(), deriveAtRestKey(seed)]);
118
+ return new EncryptedIdbVault(db, key);
119
+ }
120
+ /** AES-GCM seal: [random 12-byte IV][ciphertext]. A fresh IV per write makes one key safe for every blob. */
121
+ async seal(plain) {
122
+ const iv = crypto.getRandomValues(new Uint8Array(12));
123
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, this.key, ab(plain)));
124
+ return concat([iv, ct]);
125
+ }
126
+ async open(blob) {
127
+ const bytes = blob instanceof Uint8Array ? blob : new Uint8Array(blob);
128
+ const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: ab(bytes.subarray(0, 12)) }, this.key, ab(bytes.subarray(12)));
129
+ return new Uint8Array(plain);
130
+ }
131
+ async get(key) {
132
+ const blob = (await promisify(idb(this.db, "readonly").get(key)));
133
+ return blob ? this.open(blob) : null;
134
+ }
135
+ async save(handle, snap) {
136
+ await this.putRows([[handle, encodeSnapshot(snap)]]);
137
+ }
138
+ async commitInbound(handle, snap, histories) {
139
+ const entries = [[handle, encodeSnapshot(snap)]];
140
+ for (const [remote, messages] of histories)
141
+ entries.push([`h:${handle}:${remote}`, enc.encode(JSON.stringify(messages))]);
142
+ await this.putRows(entries, "strict");
143
+ }
144
+ async putRows(entries, durability = "default") {
145
+ // IndexedDB closes idle transactions. Finish WebCrypto BEFORE opening the transaction, and wait
146
+ // for commit rather than request success: an abort must roll back every row together.
147
+ const sealed = await Promise.all(entries.map(async ([key, plain]) => [key, await this.seal(plain)]));
148
+ const tx = this.db.transaction(STORE, "readwrite", { durability });
149
+ const completion = new Promise((resolve, reject) => {
150
+ tx.oncomplete = () => resolve();
151
+ tx.onabort = () => reject(tx.error ?? new Error("vault write aborted"));
152
+ });
153
+ const store = tx.objectStore(STORE);
154
+ try {
155
+ for (const [key, ciphertext] of sealed)
156
+ store.put(ciphertext, key);
157
+ }
158
+ catch (error) {
159
+ tx.abort();
160
+ await completion.catch(() => { });
161
+ throw error;
162
+ }
163
+ await completion;
164
+ }
165
+ async load(handle) {
166
+ const bytes = await this.get(handle);
167
+ return bytes ? decodeSnapshot(bytes) : null;
168
+ }
169
+ async saveHistory(handle, remote, messages) {
170
+ await this.putRows([[`h:${handle}:${remote}`, enc.encode(JSON.stringify(messages))]]);
171
+ }
172
+ async loadHistory(handle, remote) {
173
+ const bytes = await this.get(`h:${handle}:${remote}`);
174
+ return bytes ? JSON.parse(dec.decode(bytes)) : null;
175
+ }
176
+ async saveQueue(handle, queue) {
177
+ await this.putRows([[`q:${handle}`, enc.encode(JSON.stringify(queue))]]);
178
+ }
179
+ async loadQueue(handle) {
180
+ const bytes = await this.get(`q:${handle}`);
181
+ return bytes ? JSON.parse(dec.decode(bytes)) : null;
182
+ }
183
+ }
@@ -0,0 +1,51 @@
1
+ export interface Envelope {
2
+ to: string;
3
+ body: Uint8Array;
4
+ ts: number;
5
+ slot?: "public" | "pairwise";
6
+ }
7
+ /** Authenticates a PUBLIC first-contact slot registration (Tier 2 Stage 3): given one of my public topics and
8
+ * the helper-assigned `addr`, returns the Ed25519 proof the helper needs (or null for a pairwise/unknown
9
+ * topic, which registers unauthenticated). The signer takes `addr` because it's signed in, and `addr` is only
10
+ * known once the mesh node has its dialable address. */
11
+ export type RegistrationSigner = (topic: string, addr: string) => {
12
+ epoch: number;
13
+ pub: Uint8Array;
14
+ sig: Uint8Array;
15
+ } | null;
16
+ export interface Transport {
17
+ /** Hand an envelope to the network. Resolves `true` if it was delivered/stored, `false` if the network
18
+ * couldn't take it (offline) — the caller should queue and retry. */
19
+ send(envelope: Envelope): Promise<boolean>;
20
+ /** Listen on a SET of routing labels (rotating topics: previous/current/next epoch). Calling again
21
+ * REPLACES the set — the caller re-subscribes on a rotation rollover. `signer` authenticates public-slot
22
+ * registrations (mesh only; ignored by transports without a helper). */
23
+ subscribe(keys: string[], onEnvelope: (e: Envelope) => void, signer?: RegistrationSigner, receiveDurably?: (e: Envelope) => Promise<boolean>): void;
24
+ stop(): void;
25
+ }
26
+ export declare class BroadcastChannelTransport implements Transport {
27
+ #private;
28
+ private channel;
29
+ send(envelope: Envelope): Promise<boolean>;
30
+ subscribe(keys: string[], onEnvelope: (e: Envelope) => void): void;
31
+ stop(): void;
32
+ }
33
+ /**
34
+ * The real transport: a WebRTC-capable libp2p node behind a helper that does relay + presence + mailbox.
35
+ * Delivers DIRECT-FIRST — peer-to-peer over WebRTC when the recipient is online (the helper only brokers
36
+ * the handshake), falling back to the helper's store-and-forward mailbox when they're offline. Works
37
+ * across isolated origins/devices, unlike BroadcastChannel. The heavy libp2p stack (incl. WebRTC) lives
38
+ * behind the dynamic import of ./mesh/client, so the default bundle never pays for it.
39
+ */
40
+ export declare class MeshTransport implements Transport {
41
+ #private;
42
+ private readonly helperAddr;
43
+ private readonly pollMs;
44
+ constructor(helperAddr: string, pollMs?: number);
45
+ send(envelope: Envelope): Promise<boolean>;
46
+ subscribe(keys: string[], onEnvelope: (e: Envelope) => void, signer?: RegistrationSigner, receiveDurably?: (e: Envelope) => Promise<boolean>): void;
47
+ stop(): void;
48
+ /** Resolves once the node is connected and presence is registered (i.e. reachable for direct delivery). */
49
+ whenReady(): Promise<void>;
50
+ private client;
51
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The message transport seam: deliver an opaque (already-E2E-encrypted) envelope to a handle.
3
+ * DEMO impl = BroadcastChannel (live cross-tab on one origin). Production swaps in the libp2p mesh
4
+ * (browser node + helper mailbox) — same interface, same ciphertext-only envelopes.
5
+ */
6
+ import { pairwiseRoutingTopic } from "./mesh/protocol.js";
7
+ const CHANNEL = "handlechat:mesh";
8
+ export class BroadcastChannelTransport {
9
+ channel = new BroadcastChannel(CHANNEL);
10
+ #keys = new Set();
11
+ #cb = null;
12
+ #listening = false;
13
+ async send(envelope) {
14
+ // structured clone carries the Uint8Array; the channel is opaque ciphertext only.
15
+ const raw = pairwiseRoutingTopic(envelope.to);
16
+ this.channel.postMessage(raw ? { ...envelope, to: raw } : envelope); // no mailbox on this transport
17
+ return true;
18
+ }
19
+ subscribe(keys, onEnvelope) {
20
+ this.#keys = new Set(keys.map(key => pairwiseRoutingTopic(key) ?? key)); // same raw wire labels as older tabs
21
+ this.#cb = onEnvelope;
22
+ if (!this.#listening) {
23
+ this.#listening = true;
24
+ this.channel.addEventListener("message", (ev) => {
25
+ const env = ev.data;
26
+ if (env && this.#keys.has(env.to))
27
+ this.#cb?.(env);
28
+ });
29
+ }
30
+ }
31
+ stop() {
32
+ this.channel.close();
33
+ }
34
+ }
35
+ const toB64 = (b) => {
36
+ let s = "";
37
+ for (const x of b)
38
+ s += String.fromCharCode(x);
39
+ return btoa(s);
40
+ };
41
+ const fromB64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
42
+ /**
43
+ * The real transport: a WebRTC-capable libp2p node behind a helper that does relay + presence + mailbox.
44
+ * Delivers DIRECT-FIRST — peer-to-peer over WebRTC when the recipient is online (the helper only brokers
45
+ * the handshake), falling back to the helper's store-and-forward mailbox when they're offline. Works
46
+ * across isolated origins/devices, unlike BroadcastChannel. The heavy libp2p stack (incl. WebRTC) lives
47
+ * behind the dynamic import of ./mesh/client, so the default bundle never pays for it.
48
+ */
49
+ export class MeshTransport {
50
+ helperAddr;
51
+ pollMs;
52
+ #clientP = null;
53
+ #stopped = false;
54
+ #retry = null;
55
+ #retryMs = 1000;
56
+ #keys = [];
57
+ #onWire = () => { };
58
+ #signer = () => null;
59
+ #receiveDurably;
60
+ #subscriptionGeneration = 0;
61
+ constructor(helperAddr, pollMs = 1500) {
62
+ this.helperAddr = helperAddr;
63
+ this.pollMs = pollMs;
64
+ }
65
+ async send(envelope) {
66
+ const wire = { to: envelope.to, body: toB64(envelope.body), ts: envelope.ts, slot: envelope.slot };
67
+ try {
68
+ return await this.client().then((c) => c.send(wire));
69
+ }
70
+ catch {
71
+ return false; // node/helper unreachable — caller queues
72
+ }
73
+ }
74
+ subscribe(keys, onEnvelope, signer, receiveDurably) {
75
+ const generation = ++this.#subscriptionGeneration;
76
+ this.#keys = [...keys];
77
+ this.#onWire = (w) => onEnvelope({ to: w.to, body: fromB64(w.body), ts: w.ts, slot: w.slot });
78
+ this.#receiveDurably = receiveDurably ? async (w) => {
79
+ if (this.#stopped || generation !== this.#subscriptionGeneration)
80
+ return false;
81
+ const accepted = await receiveDurably({ to: w.to, body: fromB64(w.body), ts: w.ts, slot: w.slot });
82
+ return !this.#stopped && generation === this.#subscriptionGeneration && accepted === true;
83
+ } : undefined;
84
+ if (signer)
85
+ this.#signer = signer;
86
+ this.#listen();
87
+ }
88
+ #listen() {
89
+ if (this.#stopped)
90
+ return;
91
+ void this.client().then((c) => {
92
+ if (this.#retry)
93
+ clearTimeout(this.#retry);
94
+ this.#retry = null;
95
+ this.#retryMs = 1000;
96
+ c.setKeys(this.#keys, this.#signer, this.#receiveDurably);
97
+ }).catch(() => {
98
+ // An idle receiver has no outgoing queue to retry the failed initial dial on its behalf.
99
+ if (this.#stopped || this.#retry)
100
+ return;
101
+ this.#retry = setTimeout(() => { this.#retry = null; this.#listen(); }, this.#retryMs);
102
+ this.#retryMs = Math.min(60_000, this.#retryMs * 2);
103
+ });
104
+ }
105
+ stop() {
106
+ if (this.#stopped)
107
+ return;
108
+ this.#stopped = true;
109
+ this.#subscriptionGeneration++;
110
+ if (this.#retry)
111
+ clearTimeout(this.#retry);
112
+ this.#retry = null;
113
+ void this.#clientP?.then((c) => c.stop()).catch(() => { });
114
+ }
115
+ /** Resolves once the node is connected and presence is registered (i.e. reachable for direct delivery). */
116
+ whenReady() {
117
+ return this.client().then(() => undefined);
118
+ }
119
+ client() {
120
+ if (this.#stopped)
121
+ return Promise.reject(new Error("transport stopped"));
122
+ if (!this.#clientP) {
123
+ const pending = import("./mesh/client.js").then((m) => m.MeshClient.start(this.helperAddr, this.#keys, (wire) => {
124
+ if (!this.#stopped)
125
+ this.#onWire(wire);
126
+ }, this.pollMs, this.#signer, this.#receiveDurably));
127
+ this.#clientP = pending;
128
+ void pending.catch(() => {
129
+ if (this.#clientP === pending)
130
+ this.#clientP = null;
131
+ });
132
+ }
133
+ return this.#clientP.then((client) => {
134
+ if (this.#stopped)
135
+ throw new Error("transport stopped");
136
+ return client;
137
+ });
138
+ }
139
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @koralabs/handle-chat-sdk — the programmatic client for handle-to-handle E2E chat.
3
+ *
4
+ * Compiled from chat.handle.me's client core (the single source of truth; see scripts/build.mjs).
5
+ * The surface below is the medium contract SSR (secrets.handle.me) and other apps consume:
6
+ * wallet-rooted identity (sign-to-derive), libsignal WASM sessions, transports/directories,
7
+ * invite links, the typed-message codec, and the four guardian payloads.
8
+ */
9
+ export * from './chat/ChatService';
10
+ export * from './chat/directory';
11
+ export * from './chat/guardian';
12
+ export * from './chat/identity';
13
+ export * from './chat/invite';
14
+ export * from './chat/message';
15
+ export * from './chat/qr';
16
+ export * from './chat/transport';
17
+ export * from './memory';
18
+ export * from './signal/SignalEngine';
19
+ export type { QueuedEnvelope, SessionSnapshot, SessionVault, StoredMessage } from './chat/sessionStore';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @koralabs/handle-chat-sdk — the programmatic client for handle-to-handle E2E chat.
3
+ *
4
+ * Compiled from chat.handle.me's client core (the single source of truth; see scripts/build.mjs).
5
+ * The surface below is the medium contract SSR (secrets.handle.me) and other apps consume:
6
+ * wallet-rooted identity (sign-to-derive), libsignal WASM sessions, transports/directories,
7
+ * invite links, the typed-message codec, and the four guardian payloads.
8
+ */
9
+ export * from './chat/ChatService.js';
10
+ export * from './chat/directory.js';
11
+ export * from './chat/guardian.js';
12
+ export * from './chat/identity.js';
13
+ export * from './chat/invite.js';
14
+ export * from './chat/message.js';
15
+ export * from './chat/qr.js';
16
+ export * from './chat/transport.js';
17
+ export * from './memory.js';
18
+ export * from './signal/SignalEngine.js';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * In-process seams for tests, examples, and Node tools: a Directory and a Transport that need no
3
+ * browser, no relay, and no network. Production apps use LocalStorageDirectory/BroadcastChannel
4
+ * (same origin) or MeshTransport (cross-origin) — these mirror those contracts exactly.
5
+ */
6
+ import type { Directory } from './chat/directory';
7
+ import type { Transport } from './chat/transport';
8
+ /** A Map-backed prekey-bundle directory shared by every party constructed with it. */
9
+ export declare class MemoryDirectory implements Directory {
10
+ #private;
11
+ publish(handle: string, bundle: Uint8Array): void;
12
+ resolve(handle: string): Uint8Array | null;
13
+ }
14
+ /** An in-process message bus: every transport minted by one hub delivers to the others. */
15
+ export declare class MemoryHub {
16
+ #private;
17
+ transport(): Transport;
18
+ }
@@ -0,0 +1,44 @@
1
+ /** A Map-backed prekey-bundle directory shared by every party constructed with it. */
2
+ export class MemoryDirectory {
3
+ #bundles = new Map();
4
+ publish(handle, bundle) {
5
+ this.#bundles.set(handle, bundle);
6
+ }
7
+ resolve(handle) {
8
+ return this.#bundles.get(handle) ?? null;
9
+ }
10
+ }
11
+ /** An in-process message bus: every transport minted by one hub delivers to the others. */
12
+ export class MemoryHub {
13
+ #peers = new Set();
14
+ transport() {
15
+ const t = new MemoryTransport(this.#peers);
16
+ this.#peers.add(t);
17
+ return t;
18
+ }
19
+ }
20
+ class MemoryTransport {
21
+ #peers;
22
+ #keys = new Set();
23
+ #onEnvelope = null;
24
+ constructor(peers) {
25
+ this.#peers = peers;
26
+ }
27
+ send(envelope) {
28
+ for (const peer of this.#peers) {
29
+ if (peer === this || !peer.#keys.has(envelope.to))
30
+ continue;
31
+ // Deliver async (like every real transport) so senders never re-enter receivers mid-call.
32
+ queueMicrotask(() => peer.#onEnvelope?.(envelope));
33
+ }
34
+ return Promise.resolve(true);
35
+ }
36
+ subscribe(keys, onEnvelope, _signer) {
37
+ this.#keys = new Set(keys);
38
+ this.#onEnvelope = onEnvelope;
39
+ }
40
+ stop() {
41
+ this.#peers.delete(this);
42
+ this.#onEnvelope = null;
43
+ }
44
+ }