@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,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,65 @@
|
|
|
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
|
+
/** What we persist for one handle on this device. The identity key pair is NOT here — it's re-derived
|
|
9
|
+
* from the wallet at sign-in, never stored. */
|
|
10
|
+
export interface SessionSnapshot {
|
|
11
|
+
state: Uint8Array;
|
|
12
|
+
bundle: Uint8Array;
|
|
13
|
+
contacts: string[];
|
|
14
|
+
peerPA?: Record<string, string>;
|
|
15
|
+
}
|
|
16
|
+
/** One persisted (decrypted) message in a conversation's local history. Typed content: `mime` is the
|
|
17
|
+
* IANA type and `body` is the raw content base64-encoded (JSON-safe at rest); `meta` is optional. */
|
|
18
|
+
export interface StoredMessage {
|
|
19
|
+
from: string;
|
|
20
|
+
mime: string;
|
|
21
|
+
body: string;
|
|
22
|
+
meta?: Record<string, string>;
|
|
23
|
+
ts: number;
|
|
24
|
+
}
|
|
25
|
+
/** An outbound envelope queued while offline — already sealed (ciphertext base64), retried on reconnect. */
|
|
26
|
+
export interface QueuedEnvelope {
|
|
27
|
+
id: string;
|
|
28
|
+
remote: string;
|
|
29
|
+
to: string;
|
|
30
|
+
body: string;
|
|
31
|
+
ts: number;
|
|
32
|
+
track?: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface SessionVault {
|
|
35
|
+
load(handle: string): Promise<SessionSnapshot | null>;
|
|
36
|
+
save(handle: string, snap: SessionSnapshot): Promise<void>;
|
|
37
|
+
/** Outbound queue persisted while offline (survives a reload), retried on reconnect. */
|
|
38
|
+
loadQueue(handle: string): Promise<QueuedEnvelope[] | null>;
|
|
39
|
+
saveQueue(handle: string, queue: QueuedEnvelope[]): Promise<void>;
|
|
40
|
+
/** Per-conversation decrypted message history, encrypted at rest under the same wallet-derived key.
|
|
41
|
+
* Plaintext history is stored because Signal's forward secrecy makes old wire ciphertext
|
|
42
|
+
* undecryptable once the ratchet advances — so "history" must be the decrypted text, re-sealed here. */
|
|
43
|
+
loadHistory(handle: string, remote: string): Promise<StoredMessage[] | null>;
|
|
44
|
+
saveHistory(handle: string, remote: string, messages: StoredMessage[]): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
export declare function encodeSnapshot(s: SessionSnapshot): Uint8Array;
|
|
47
|
+
export declare function decodeSnapshot(b: Uint8Array): SessionSnapshot;
|
|
48
|
+
/** The standard browser vault: AES-GCM over the snapshot, persisted in IndexedDB keyed by handle. */
|
|
49
|
+
export declare class EncryptedIdbVault implements SessionVault {
|
|
50
|
+
private readonly db;
|
|
51
|
+
private readonly key;
|
|
52
|
+
private constructor();
|
|
53
|
+
static create(seed: Uint8Array): Promise<EncryptedIdbVault>;
|
|
54
|
+
/** AES-GCM seal: [random 12-byte IV][ciphertext]. A fresh IV per write makes one key safe for every blob. */
|
|
55
|
+
private seal;
|
|
56
|
+
private open;
|
|
57
|
+
private put;
|
|
58
|
+
private get;
|
|
59
|
+
save(handle: string, snap: SessionSnapshot): Promise<void>;
|
|
60
|
+
load(handle: string): Promise<SessionSnapshot | null>;
|
|
61
|
+
saveHistory(handle: string, remote: string, messages: StoredMessage[]): Promise<void>;
|
|
62
|
+
loadHistory(handle: string, remote: string): Promise<StoredMessage[] | null>;
|
|
63
|
+
saveQueue(handle: string, queue: QueuedEnvelope[]): Promise<void>;
|
|
64
|
+
loadQueue(handle: string): Promise<QueuedEnvelope[] | null>;
|
|
65
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
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
|
+
return concat(parts);
|
|
37
|
+
}
|
|
38
|
+
export function decodeSnapshot(b) {
|
|
39
|
+
const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
|
|
40
|
+
let i = 0;
|
|
41
|
+
const len = () => {
|
|
42
|
+
const v = dv.getUint32(i);
|
|
43
|
+
i += 4;
|
|
44
|
+
return v;
|
|
45
|
+
};
|
|
46
|
+
const slice = () => {
|
|
47
|
+
const n = len();
|
|
48
|
+
const s = b.subarray(i, i + n);
|
|
49
|
+
i += n;
|
|
50
|
+
return s;
|
|
51
|
+
};
|
|
52
|
+
const state = slice();
|
|
53
|
+
const bundle = slice();
|
|
54
|
+
const count = len();
|
|
55
|
+
const contacts = [];
|
|
56
|
+
for (let k = 0; k < count; k++)
|
|
57
|
+
contacts.push(dec.decode(slice()));
|
|
58
|
+
// blobs saved before presence keys were persisted end after the contacts
|
|
59
|
+
const peerPA = i < b.length ? JSON.parse(dec.decode(slice())) : {};
|
|
60
|
+
return { state, bundle, contacts, peerPA };
|
|
61
|
+
}
|
|
62
|
+
/** A guaranteed ArrayBuffer-backed copy — WebCrypto's `BufferSource` rejects the generic
|
|
63
|
+
* `Uint8Array<ArrayBufferLike>` that subarray/params produce under TS 5.7. */
|
|
64
|
+
const ab = (x) => {
|
|
65
|
+
const out = new Uint8Array(x.byteLength);
|
|
66
|
+
out.set(x);
|
|
67
|
+
return out;
|
|
68
|
+
};
|
|
69
|
+
/** HKDF the wallet seed → an AES-GCM-256 key for at-rest encryption (separate salt from the identity). */
|
|
70
|
+
async function deriveAtRestKey(seed) {
|
|
71
|
+
const base = await crypto.subtle.importKey("raw", ab(seed), "HKDF", false, ["deriveKey"]);
|
|
72
|
+
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"]);
|
|
73
|
+
}
|
|
74
|
+
const idb = (db, mode) => db.transaction(STORE, mode).objectStore(STORE);
|
|
75
|
+
const promisify = (req) => new Promise((resolve, reject) => {
|
|
76
|
+
req.onsuccess = () => resolve(req.result);
|
|
77
|
+
req.onerror = () => reject(req.error);
|
|
78
|
+
});
|
|
79
|
+
function openDb() {
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
const req = indexedDB.open(DB_NAME, 1);
|
|
82
|
+
req.onupgradeneeded = () => req.result.createObjectStore(STORE);
|
|
83
|
+
req.onsuccess = () => resolve(req.result);
|
|
84
|
+
req.onerror = () => reject(req.error);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/** The standard browser vault: AES-GCM over the snapshot, persisted in IndexedDB keyed by handle. */
|
|
88
|
+
export class EncryptedIdbVault {
|
|
89
|
+
db;
|
|
90
|
+
key;
|
|
91
|
+
constructor(db, key) {
|
|
92
|
+
this.db = db;
|
|
93
|
+
this.key = key;
|
|
94
|
+
}
|
|
95
|
+
static async create(seed) {
|
|
96
|
+
const [db, key] = await Promise.all([openDb(), deriveAtRestKey(seed)]);
|
|
97
|
+
return new EncryptedIdbVault(db, key);
|
|
98
|
+
}
|
|
99
|
+
/** AES-GCM seal: [random 12-byte IV][ciphertext]. A fresh IV per write makes one key safe for every blob. */
|
|
100
|
+
async seal(plain) {
|
|
101
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
102
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, this.key, ab(plain)));
|
|
103
|
+
return concat([iv, ct]);
|
|
104
|
+
}
|
|
105
|
+
async open(blob) {
|
|
106
|
+
const bytes = blob instanceof Uint8Array ? blob : new Uint8Array(blob);
|
|
107
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: ab(bytes.subarray(0, 12)) }, this.key, ab(bytes.subarray(12)));
|
|
108
|
+
return new Uint8Array(plain);
|
|
109
|
+
}
|
|
110
|
+
async put(key, plain) {
|
|
111
|
+
await promisify(idb(this.db, "readwrite").put(await this.seal(plain), key));
|
|
112
|
+
}
|
|
113
|
+
async get(key) {
|
|
114
|
+
const blob = (await promisify(idb(this.db, "readonly").get(key)));
|
|
115
|
+
return blob ? this.open(blob) : null;
|
|
116
|
+
}
|
|
117
|
+
async save(handle, snap) {
|
|
118
|
+
await this.put(handle, encodeSnapshot(snap));
|
|
119
|
+
}
|
|
120
|
+
async load(handle) {
|
|
121
|
+
const bytes = await this.get(handle);
|
|
122
|
+
return bytes ? decodeSnapshot(bytes) : null;
|
|
123
|
+
}
|
|
124
|
+
async saveHistory(handle, remote, messages) {
|
|
125
|
+
await this.put(`h:${handle}:${remote}`, enc.encode(JSON.stringify(messages)));
|
|
126
|
+
}
|
|
127
|
+
async loadHistory(handle, remote) {
|
|
128
|
+
const bytes = await this.get(`h:${handle}:${remote}`);
|
|
129
|
+
return bytes ? JSON.parse(dec.decode(bytes)) : null;
|
|
130
|
+
}
|
|
131
|
+
async saveQueue(handle, queue) {
|
|
132
|
+
await this.put(`q:${handle}`, enc.encode(JSON.stringify(queue)));
|
|
133
|
+
}
|
|
134
|
+
async loadQueue(handle) {
|
|
135
|
+
const bytes = await this.get(`q:${handle}`);
|
|
136
|
+
return bytes ? JSON.parse(dec.decode(bytes)) : null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -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): 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): 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,79 @@
|
|
|
1
|
+
const CHANNEL = "handlechat:mesh";
|
|
2
|
+
export class BroadcastChannelTransport {
|
|
3
|
+
channel = new BroadcastChannel(CHANNEL);
|
|
4
|
+
#keys = new Set();
|
|
5
|
+
#cb = null;
|
|
6
|
+
#listening = false;
|
|
7
|
+
async send(envelope) {
|
|
8
|
+
// structured clone carries the Uint8Array; the channel is opaque ciphertext only.
|
|
9
|
+
this.channel.postMessage(envelope);
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
subscribe(keys, onEnvelope) {
|
|
13
|
+
this.#keys = new Set(keys); // re-subscribe replaces the active label set
|
|
14
|
+
this.#cb = onEnvelope;
|
|
15
|
+
if (!this.#listening) {
|
|
16
|
+
this.#listening = true;
|
|
17
|
+
this.channel.addEventListener("message", (ev) => {
|
|
18
|
+
const env = ev.data;
|
|
19
|
+
if (env && this.#keys.has(env.to))
|
|
20
|
+
this.#cb?.(env);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
stop() {
|
|
25
|
+
this.channel.close();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const toB64 = (b) => {
|
|
29
|
+
let s = "";
|
|
30
|
+
for (const x of b)
|
|
31
|
+
s += String.fromCharCode(x);
|
|
32
|
+
return btoa(s);
|
|
33
|
+
};
|
|
34
|
+
const fromB64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
|
35
|
+
/**
|
|
36
|
+
* The real transport: a WebRTC-capable libp2p node behind a helper that does relay + presence + mailbox.
|
|
37
|
+
* Delivers DIRECT-FIRST — peer-to-peer over WebRTC when the recipient is online (the helper only brokers
|
|
38
|
+
* the handshake), falling back to the helper's store-and-forward mailbox when they're offline. Works
|
|
39
|
+
* across isolated origins/devices, unlike BroadcastChannel. The heavy libp2p stack (incl. WebRTC) lives
|
|
40
|
+
* behind the dynamic import of ./mesh/client, so the default bundle never pays for it.
|
|
41
|
+
*/
|
|
42
|
+
export class MeshTransport {
|
|
43
|
+
helperAddr;
|
|
44
|
+
pollMs;
|
|
45
|
+
#clientP = null;
|
|
46
|
+
#keys = [];
|
|
47
|
+
#onWire = () => { };
|
|
48
|
+
#signer = () => null;
|
|
49
|
+
constructor(helperAddr, pollMs = 1500) {
|
|
50
|
+
this.helperAddr = helperAddr;
|
|
51
|
+
this.pollMs = pollMs;
|
|
52
|
+
}
|
|
53
|
+
async send(envelope) {
|
|
54
|
+
const wire = { to: envelope.to, body: toB64(envelope.body), ts: envelope.ts, slot: envelope.slot };
|
|
55
|
+
try {
|
|
56
|
+
return await this.client().then((c) => c.send(wire));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return false; // node/helper unreachable — caller queues
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
subscribe(keys, onEnvelope, signer) {
|
|
63
|
+
this.#keys = keys;
|
|
64
|
+
this.#onWire = (w) => onEnvelope({ to: w.to, body: fromB64(w.body), ts: w.ts, slot: w.slot });
|
|
65
|
+
if (signer)
|
|
66
|
+
this.#signer = signer;
|
|
67
|
+
void this.client().then((c) => c.setKeys(this.#keys, this.#signer)).catch(() => { });
|
|
68
|
+
}
|
|
69
|
+
stop() {
|
|
70
|
+
void this.#clientP?.then((c) => c.stop()).catch(() => { });
|
|
71
|
+
}
|
|
72
|
+
/** Resolves once the node is connected and presence is registered (i.e. reachable for direct delivery). */
|
|
73
|
+
whenReady() {
|
|
74
|
+
return this.client().then(() => undefined);
|
|
75
|
+
}
|
|
76
|
+
client() {
|
|
77
|
+
return (this.#clientP ??= import("./mesh/client.js").then((m) => m.MeshClient.start(this.helperAddr, this.#keys, this.#onWire, this.pollMs, this.#signer)));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -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';
|
package/lib/src/index.js
ADDED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import initWasm from "../../libsignal-wasm/pkg/handle_libsignal_wasm.js";
|
|
2
|
+
/**
|
|
3
|
+
* Initialize the libsignal WASM once. Browsers need nothing — the default fetches {@link WASM_URL}
|
|
4
|
+
* from the serving origin. Non-browser hosts (Node tools, the SDK's examples/tests) call this first
|
|
5
|
+
* with the module bytes, since there is no origin to fetch from.
|
|
6
|
+
*/
|
|
7
|
+
export declare const initSignalWasm: (input?: Parameters<typeof initWasm>[0]) => Promise<void>;
|
|
8
|
+
export declare class SignalEngine {
|
|
9
|
+
private readonly account;
|
|
10
|
+
readonly handle: string;
|
|
11
|
+
private constructor();
|
|
12
|
+
static create(handle: string, identityPriv: Uint8Array, registrationId: number): Promise<SignalEngine>;
|
|
13
|
+
/** The publishable PQXDH bundle — goes in the on-chain anchor. */
|
|
14
|
+
createBundle(): Uint8Array;
|
|
15
|
+
/** Open an outbound session to a peer from their published bundle. */
|
|
16
|
+
processBundle(remote: string, bundle: Uint8Array): void;
|
|
17
|
+
encrypt(remote: string, plaintext: string): Uint8Array;
|
|
18
|
+
decrypt(remote: string, message: Uint8Array): string;
|
|
19
|
+
/**
|
|
20
|
+
* Sealed-sender encrypt: the sender handle is sealed INSIDE the ciphertext (libsignal native sealed
|
|
21
|
+
* sender), so the envelope this returns carries no sender label for a relay to read.
|
|
22
|
+
*/
|
|
23
|
+
sealedSend(remote: string, plaintext: Uint8Array): Uint8Array;
|
|
24
|
+
/**
|
|
25
|
+
* Sealed-sender decrypt: recovers the sender handle + its certificate identity key (for the caller's
|
|
26
|
+
* on-chain anchor cross-check) and the plaintext bytes, opening the seal with our own identity key
|
|
27
|
+
* alone. The crypto layer is bytes-native; the typed-message codec lives above it (see `message.ts`).
|
|
28
|
+
*/
|
|
29
|
+
sealedReceive(ciphertext: Uint8Array): {
|
|
30
|
+
sender: string;
|
|
31
|
+
identityKey: Uint8Array;
|
|
32
|
+
body: Uint8Array;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Serialize this device's session state (Double-Ratchet records + learned peer identities + our own
|
|
36
|
+
* pre-keys) for at-rest persistence. The identity key pair is NOT included — it's re-derived from the
|
|
37
|
+
* wallet on the next sign-in. Pass the handles of known contacts (sessions/identities are keyed by them).
|
|
38
|
+
*/
|
|
39
|
+
exportState(remotes: string[]): Uint8Array;
|
|
40
|
+
/** Restore state from `exportState` into this (freshly created, same-wallet) engine. */
|
|
41
|
+
importState(blob: Uint8Array): void;
|
|
42
|
+
/** My rotating routing labels (previous + current + next epoch) — what I subscribe under, so the relay
|
|
43
|
+
* never sees my handle and can't track a stable pseudonym. Listening on the neighbours covers a rollover
|
|
44
|
+
* boundary + clock skew. */
|
|
45
|
+
myTopics(now?: number): string[];
|
|
46
|
+
/** A peer's CURRENT-epoch routing label — where I deposit a message (needs an open session to them). */
|
|
47
|
+
peerTopic(remote: string, now?: number): string;
|
|
48
|
+
/** Tier 2: the per-CONVERSATION label I deposit a message to `remote` at (current epoch). Derived from the
|
|
49
|
+
* static-static identity-key agreement, so it's unguessable without one of our private keys — the
|
|
50
|
+
* chain-watcher can't recompute it, and it's bound to the two keys (survives a handle transfer). */
|
|
51
|
+
convSendTopic(remote: string, now?: number): string;
|
|
52
|
+
/** Tier 2: the per-conversation labels `remote` deposits at FOR me (previous + current + next epoch) — I
|
|
53
|
+
* subscribe to the union of these over all known contacts, plus my public first-contact slot (myTopics). */
|
|
54
|
+
convRecvTopics(remote: string, now?: number): string[];
|
|
55
|
+
/** The peer identity key the established session authenticates (the verify-once TRUSTED key), or null if
|
|
56
|
+
* there's no session for `remote`. Survives a reopen via the persisted session, independent of the anchor. */
|
|
57
|
+
peerIdentityKey(remote: string): Uint8Array | null;
|
|
58
|
+
/** Tier 2 Stage 3: my per-identity Ed25519 presence-auth PUBLIC key (goes in my bundle; the helper verifies
|
|
59
|
+
* my public-slot registrations against it). */
|
|
60
|
+
presenceAuthPub(): Uint8Array;
|
|
61
|
+
/** Tier 2 Stage 3: sign a public-slot presence registration (Ed25519 over topic‖addr‖epoch). */
|
|
62
|
+
signPresence(topic: Uint8Array, addr: string, epoch: number): Uint8Array;
|
|
63
|
+
/** Tier 2 Stage 3: my PUBLIC first-contact slot labels (prev/cur/next) = HKDF(presenceAuthPub, epoch). */
|
|
64
|
+
publicSlotTopics(now?: number): string[];
|
|
65
|
+
/** Tier 2 Stage 3: a PEER's current-epoch public first-contact slot from their presence-auth pub key — where
|
|
66
|
+
* I deposit a first-contact message before our pairwise topic exists. */
|
|
67
|
+
publicSlotTopicFor(peerPresenceAuthPub: Uint8Array, now?: number): string;
|
|
68
|
+
}
|