@koralabs/handle-chat-sdk 0.0.12 → 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,643 @@
|
|
|
1
|
+
import { SignalEngine } from "../signal/SignalEngine.js";
|
|
2
|
+
import { deriveIdentity } from "./identity.js";
|
|
3
|
+
import { EncryptedIdbVault } from "./sessionStore.js";
|
|
4
|
+
import { encodeMessage, decodeMessage, textMessage, mediaMessage, messageText } from "./message.js";
|
|
5
|
+
import { receiptMessage, parseReceipt } from "./receipt.js";
|
|
6
|
+
import { buildBlobMessages, BlobAssembler, isBlobPart } from "./blob.js";
|
|
7
|
+
import { presenceEpoch } from "./mesh/presenceAuth.js";
|
|
8
|
+
// Anti-DoS bounds.
|
|
9
|
+
const MAX_QUEUE = 1000; // cap the offline send queue — drop oldest beyond this
|
|
10
|
+
const MAX_SENT_STATE = 2000; // cap the per-message status map (LRU) so a long session can't leak it
|
|
11
|
+
const MAX_ENVELOPE_BYTES = 256 * 1024; // reject oversized inbound envelopes before decrypting (legit: inline ≤32KB, chunk ≤16KB + sealing)
|
|
12
|
+
const MAX_SEEN_ENVELOPES = 4000; // cap the inbound dedup set (LRU) — bounds memory while covering live + mailbox copies
|
|
13
|
+
// Abuse gate: cold first-contacts from UN-anchored senders (the spam vector) are rate-limited. Anchored
|
|
14
|
+
// senders cost ada per identity (Handle + on-chain anchor) and are chain-verified, so they're unlimited;
|
|
15
|
+
// known contacts (we initiated, or already accepted) are unlimited too.
|
|
16
|
+
export const UNVERIFIED_FIRST_CONTACT_LIMIT = 8;
|
|
17
|
+
const UNVERIFIED_WINDOW_MS = 60_000;
|
|
18
|
+
// Sent-message status is monotonic — it only advances. A late/out-of-order receipt must never regress it.
|
|
19
|
+
const SEND_STATE_RANK = { queued: 0, sent: 1, delivered: 2, read: 3 };
|
|
20
|
+
// Re-derive + re-subscribe to my rotating routing labels this often. Just needs to be < the rotation
|
|
21
|
+
// period (the ±1-epoch neighbour coverage means no message is missed as long as we refresh within it).
|
|
22
|
+
const TOPIC_REFRESH_MS = 30 * 60 * 1000;
|
|
23
|
+
const bytesEqual = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
24
|
+
// The sealed-sender certificate's handle field is SELF-SIGNED + free-form, so an inbound `sender` is
|
|
25
|
+
// attacker-controlled until chain-as-CA verifies it. Constrain it before it touches any state or the DOM —
|
|
26
|
+
// defense in depth behind output-escaping (which is the real fix). A DENYLIST (not an ASCII allowlist) so
|
|
27
|
+
// legitimate unicode/emoji handles still work: reject HTML-special, quote, whitespace, and control chars.
|
|
28
|
+
const HANDLE_RE = /^\$[^\s<>"'&]{1,100}$/;
|
|
29
|
+
const isValidHandle = (h) => HANDLE_RE.test(h);
|
|
30
|
+
const toB64 = (b) => {
|
|
31
|
+
let s = "";
|
|
32
|
+
for (const x of b)
|
|
33
|
+
s += String.fromCharCode(x);
|
|
34
|
+
return btoa(s);
|
|
35
|
+
};
|
|
36
|
+
const fromB64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
|
37
|
+
const toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
38
|
+
const fromHex = (h) => {
|
|
39
|
+
const o = new Uint8Array(h.length / 2);
|
|
40
|
+
for (let i = 0; i < o.length; i++)
|
|
41
|
+
o[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
|
|
42
|
+
return o;
|
|
43
|
+
};
|
|
44
|
+
// Copy into a fresh ArrayBuffer — WASM-memory-backed views can't be passed to crypto.subtle directly.
|
|
45
|
+
const ab = (x) => {
|
|
46
|
+
const out = new Uint8Array(x.byteLength);
|
|
47
|
+
out.set(x);
|
|
48
|
+
return out;
|
|
49
|
+
};
|
|
50
|
+
// Content fingerprint of a sealed envelope body, for inbound dedup (SHA-256 → base64). Identical for the
|
|
51
|
+
// two copies of the same message (direct + mailbox); distinct ciphertexts seal to distinct bodies.
|
|
52
|
+
const envelopeFp = async (body) => toB64(new Uint8Array(await crypto.subtle.digest("SHA-256", ab(body))));
|
|
53
|
+
const toStored = (m) => ({ from: m.from, mime: m.content.mime, body: toB64(m.content.body), meta: m.content.meta, ts: m.ts });
|
|
54
|
+
const fromStored = (s) => ({ from: s.from, content: { mime: s.mime, body: fromB64(s.body), meta: s.meta }, ts: s.ts });
|
|
55
|
+
/**
|
|
56
|
+
* Walk a serialized PQXDH bundle's length-prefixed fields — mirrors libsignal-wasm `createBundle`'s layout:
|
|
57
|
+
* regId, deviceId, spkId, spkPub, spkSig, kyberId, kyberPub, kyberSig, identityKey, presenceAuthPub.
|
|
58
|
+
* Returns the identity key and the presence-auth key (Tier 2 Stage 3; absent in older bundles → empty).
|
|
59
|
+
*/
|
|
60
|
+
const parseBundle = (bundle) => {
|
|
61
|
+
const dv = new DataView(bundle.buffer, bundle.byteOffset, bundle.byteLength);
|
|
62
|
+
let i = 0;
|
|
63
|
+
const u32 = () => {
|
|
64
|
+
const v = dv.getUint32(i);
|
|
65
|
+
i += 4;
|
|
66
|
+
return v;
|
|
67
|
+
};
|
|
68
|
+
const bytes = () => {
|
|
69
|
+
const n = u32();
|
|
70
|
+
const b = bundle.subarray(i, i + n);
|
|
71
|
+
i += n;
|
|
72
|
+
return b;
|
|
73
|
+
};
|
|
74
|
+
u32(); // registration id
|
|
75
|
+
u32(); // device id
|
|
76
|
+
u32(); // signed-pre-key id
|
|
77
|
+
bytes(); // signed-pre-key pub
|
|
78
|
+
bytes(); // signed-pre-key sig
|
|
79
|
+
u32(); // kyber id
|
|
80
|
+
bytes(); // kyber pub
|
|
81
|
+
bytes(); // kyber sig
|
|
82
|
+
const identityKey = bytes();
|
|
83
|
+
const presenceAuthPub = i < bundle.byteLength ? bytes() : new Uint8Array(0);
|
|
84
|
+
return { identityKey, presenceAuthPub };
|
|
85
|
+
};
|
|
86
|
+
/** The identity key (chain-as-CA cross-check of a sealed sender's claimed key vs. what the handle publishes). */
|
|
87
|
+
const bundleIdentityKey = (bundle) => parseBundle(bundle).identityKey;
|
|
88
|
+
/**
|
|
89
|
+
* Orchestrates one handle's chat: derive the wallet-rooted identity, provision the WASM Signal
|
|
90
|
+
* engine, publish the bundle to the directory, and send/receive E2E messages over the transport.
|
|
91
|
+
* Crypto = libsignal (WASM). Directory/transport are seams (demo: localStorage + BroadcastChannel).
|
|
92
|
+
*/
|
|
93
|
+
export class ChatService {
|
|
94
|
+
handle;
|
|
95
|
+
directory;
|
|
96
|
+
transport;
|
|
97
|
+
now;
|
|
98
|
+
engine;
|
|
99
|
+
onMessageCb = null;
|
|
100
|
+
onReceiptCb = null;
|
|
101
|
+
onKeyChangeCb = null;
|
|
102
|
+
onSendUpdateCb = null;
|
|
103
|
+
/** State of my outbound messages by id: "queued" (offline) → "sent" → delivered/read (peer acks). */
|
|
104
|
+
#sentState = new Map();
|
|
105
|
+
/** Outbound messages sealed but not yet handed to the network (offline) — retried on reconnect. */
|
|
106
|
+
#queue = [];
|
|
107
|
+
#flushTimer = null;
|
|
108
|
+
#flushing = false;
|
|
109
|
+
#onlineHandler = null;
|
|
110
|
+
/** My current rotating routing labels (prev/current/next epoch) + the timer that rolls them over. */
|
|
111
|
+
#topics = [];
|
|
112
|
+
#topicTimer = null;
|
|
113
|
+
/** Reassembles inbound streamed blobs (large media sent as ref + chunks). */
|
|
114
|
+
#assembler = new BlobAssembler();
|
|
115
|
+
/** Timestamps of recently-admitted cold first-contacts from un-anchored senders (sliding-window limit). */
|
|
116
|
+
#unverifiedAdmissions = [];
|
|
117
|
+
started = false;
|
|
118
|
+
#bundle = null;
|
|
119
|
+
#vault;
|
|
120
|
+
#useDefaultVault;
|
|
121
|
+
#contacts = new Set();
|
|
122
|
+
// Peers I've received from — they know me, so they subscribe to our pairwise label and I can address them
|
|
123
|
+
// there (Tier 2). Until then I deposit at their PUBLIC first-contact slot. Reconstructed from history on
|
|
124
|
+
// restore (any thread with an inbound message). [[tier2-session-bound-topics]]
|
|
125
|
+
#convReady = new Set();
|
|
126
|
+
// Tier 2 Stage 3: each contact's presence-auth public key (from their bundle), used to address their PUBLIC
|
|
127
|
+
// first-contact slot `HKDF(peerPA, epoch)`. Persisted in the snapshot.
|
|
128
|
+
#peerPA = new Map();
|
|
129
|
+
// Verify-once-then-warn (Tier 2): the identity key I verified for each conversation at first contact. I
|
|
130
|
+
// trust THIS key + the ratchet thereafter — NOT the live, mutable on-chain anchor — so an established
|
|
131
|
+
// conversation survives a handle re-anchor/transfer instead of being silently dropped. Reconstructed from
|
|
132
|
+
// the persisted session on restore (`engine.peerIdentityKey`). [[tier2-session-bound-topics]]
|
|
133
|
+
#trustedKey = new Map();
|
|
134
|
+
#persistChain = Promise.resolve();
|
|
135
|
+
#recvChain = Promise.resolve(); // serializes inbound processing in arrival order
|
|
136
|
+
#seenEnvelopes = new Set(); // content fingerprints of processed envelopes (LRU) — inbound dedup
|
|
137
|
+
/** Decrypted conversation history (per remote), restored on start + appended on every message. */
|
|
138
|
+
#history = new Map();
|
|
139
|
+
#historyChain = Promise.resolve();
|
|
140
|
+
static MAX_HISTORY = 500; // cap per thread — bound the at-rest blob + memory
|
|
141
|
+
constructor(handle, directory, transport,
|
|
142
|
+
/** Where per-device session state persists. Omit for the default (wallet-encrypted IndexedDB);
|
|
143
|
+
* pass `null` to disable persistence; inject a custom vault in tests. */
|
|
144
|
+
vault,
|
|
145
|
+
/** Clock for topic-epoch derivation — injectable so tests can cross a rotation boundary. */
|
|
146
|
+
now = () => Date.now()) {
|
|
147
|
+
this.handle = handle;
|
|
148
|
+
this.directory = directory;
|
|
149
|
+
this.transport = transport;
|
|
150
|
+
this.now = now;
|
|
151
|
+
this.#vault = vault === undefined ? null : vault;
|
|
152
|
+
this.#useDefaultVault = vault === undefined;
|
|
153
|
+
}
|
|
154
|
+
/** Provision identity + Signal engine from the wallet seed, restore any persisted session, publish, receive. */
|
|
155
|
+
async start(seed) {
|
|
156
|
+
if (this.started)
|
|
157
|
+
return;
|
|
158
|
+
const { priv, registrationId } = await deriveIdentity(seed, this.handle);
|
|
159
|
+
this.engine = await SignalEngine.create(this.handle, priv, registrationId);
|
|
160
|
+
// Persistence: default to the wallet-encrypted IndexedDB vault (re-derives its key from the seed).
|
|
161
|
+
if (this.#useDefaultVault)
|
|
162
|
+
this.#vault = await EncryptedIdbVault.create(seed).catch(() => null);
|
|
163
|
+
// CRITICAL: the snapshot load must distinguish "no record" (null → genuine new user) from a transient
|
|
164
|
+
// read/decrypt error (throws). We must NOT catch-to-null here: doing so would treat a recoverable error
|
|
165
|
+
// as a fresh user and mint+persist a NEW identity over the intact snapshot, destroying the session,
|
|
166
|
+
// anchor binding, and history. On error we let start() throw so the caller can retry — never clobber.
|
|
167
|
+
const snapshot = this.#vault ? await this.#vault.load(this.handle) : null;
|
|
168
|
+
if (snapshot) {
|
|
169
|
+
// Resume: restore the ratchets/identities/pre-keys and re-publish the SAME bundle (so the
|
|
170
|
+
// on-chain anchor stays valid) — no re-handshake.
|
|
171
|
+
this.engine.importState(snapshot.state);
|
|
172
|
+
this.#bundle = snapshot.bundle;
|
|
173
|
+
this.#contacts = new Set(snapshot.contacts);
|
|
174
|
+
for (const [h, hex] of Object.entries(snapshot.peerPA ?? {}))
|
|
175
|
+
this.#peerPA.set(h, fromHex(hex)); // Tier 2 Stage 3
|
|
176
|
+
// Restore each conversation's decrypted history (encrypted at rest under the same wallet key).
|
|
177
|
+
for (const remote of this.#contacts) {
|
|
178
|
+
// Reconstruct the verify-once TRUSTED key from the restored session (NOT the live anchor, which may
|
|
179
|
+
// have since moved). This is what keeps an established conversation alive across a handle re-anchor.
|
|
180
|
+
const trusted = this.engine.peerIdentityKey(remote);
|
|
181
|
+
if (trusted)
|
|
182
|
+
this.#trustedKey.set(remote, trusted);
|
|
183
|
+
const stored = this.#vault ? await this.#vault.loadHistory(this.handle, remote).catch(() => null) : null;
|
|
184
|
+
if (stored && stored.length) {
|
|
185
|
+
this.#history.set(remote, stored.map(fromStored));
|
|
186
|
+
// A thread with any INBOUND message means this peer has reached me → they know me → I can address
|
|
187
|
+
// them at our pairwise topic (Tier 2). A contact I only opened-but-never-heard-from stays public.
|
|
188
|
+
if (stored.some((m) => m.from === remote))
|
|
189
|
+
this.#convReady.add(remote);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
// Restore the outbound queue (messages sealed while offline before a reload).
|
|
193
|
+
const queued = this.#vault ? await this.#vault.loadQueue(this.handle).catch(() => null) : null;
|
|
194
|
+
if (queued && queued.length) {
|
|
195
|
+
this.#queue = queued;
|
|
196
|
+
for (const q of queued)
|
|
197
|
+
this.#setSentState(q.id, "queued");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
this.#bundle = this.engine.createBundle();
|
|
202
|
+
}
|
|
203
|
+
this.directory.publish(this.handle, this.#bundle);
|
|
204
|
+
// Subscribe under our scrambled, ROTATING topics (prev/current/next epoch), not our handle — the relay
|
|
205
|
+
// routes by opaque labels that change over time, so it can't track us or who messages us. A timer rolls
|
|
206
|
+
// the set forward as epochs advance.
|
|
207
|
+
this.#topics = this.#myTopicSet();
|
|
208
|
+
this.transport.subscribe(this.#topics, (env) => this.receive(env), this.#sign);
|
|
209
|
+
this.#topicTimer = setInterval(() => this.#resubscribe(), TOPIC_REFRESH_MS);
|
|
210
|
+
this.started = true;
|
|
211
|
+
if (!snapshot)
|
|
212
|
+
this.persist(); // persist the fresh bundle/pre-keys so a new identity survives a reopen
|
|
213
|
+
// Flush the outbound queue now and whenever connectivity returns.
|
|
214
|
+
if (typeof globalThis.addEventListener === "function") {
|
|
215
|
+
this.#onlineHandler = () => void this.flushQueue();
|
|
216
|
+
globalThis.addEventListener("online", this.#onlineHandler);
|
|
217
|
+
}
|
|
218
|
+
void this.flushQueue();
|
|
219
|
+
this.#scheduleFlush();
|
|
220
|
+
}
|
|
221
|
+
/** Serialize + encrypt the current session state to the vault. Serialized via a chain so concurrent
|
|
222
|
+
* mutations don't interleave writes. Fire-and-forget; failures never block messaging. */
|
|
223
|
+
persist() {
|
|
224
|
+
if (!this.#vault || !this.#bundle)
|
|
225
|
+
return;
|
|
226
|
+
const peerPA = {};
|
|
227
|
+
for (const [h, k] of this.#peerPA)
|
|
228
|
+
peerPA[h] = toHex(k);
|
|
229
|
+
const snap = { state: this.engine.exportState([...this.#contacts]), bundle: this.#bundle, contacts: [...this.#contacts], peerPA };
|
|
230
|
+
this.#persistChain = this.#persistChain.then(() => this.#vault?.save(this.handle, snap)).catch(() => { });
|
|
231
|
+
}
|
|
232
|
+
/** Append a message to a conversation's history and persist that thread (capped, chained writes). */
|
|
233
|
+
record(remote, msg) {
|
|
234
|
+
const list = this.#history.get(remote) ?? [];
|
|
235
|
+
list.push(msg);
|
|
236
|
+
if (list.length > ChatService.MAX_HISTORY)
|
|
237
|
+
list.splice(0, list.length - ChatService.MAX_HISTORY);
|
|
238
|
+
this.#history.set(remote, list);
|
|
239
|
+
if (!this.#vault)
|
|
240
|
+
return;
|
|
241
|
+
const snapshot = list.map(toStored);
|
|
242
|
+
this.#historyChain = this.#historyChain.then(() => this.#vault?.saveHistory(this.handle, remote, snapshot)).catch(() => { });
|
|
243
|
+
}
|
|
244
|
+
/** Restored conversation history (per remote handle) — for the UI to seed its threads on reopen. */
|
|
245
|
+
loadedHistory() {
|
|
246
|
+
return this.#history;
|
|
247
|
+
}
|
|
248
|
+
/** Await any in-flight persistence (session state + history) — so a reopen reads the latest. */
|
|
249
|
+
async flush() {
|
|
250
|
+
await Promise.all([this.#persistChain, this.#historyChain]);
|
|
251
|
+
}
|
|
252
|
+
/** Tear down timers + the global `online` listener, and stop the transport. Idempotent. Call before
|
|
253
|
+
* discarding the service (e.g. a wallet switch / re-provision) so nothing leaks or fires on a stale engine. */
|
|
254
|
+
stop() {
|
|
255
|
+
if (this.#flushTimer)
|
|
256
|
+
clearInterval(this.#flushTimer);
|
|
257
|
+
if (this.#topicTimer)
|
|
258
|
+
clearInterval(this.#topicTimer);
|
|
259
|
+
this.#flushTimer = null;
|
|
260
|
+
this.#topicTimer = null;
|
|
261
|
+
if (this.#onlineHandler && typeof globalThis.removeEventListener === "function") {
|
|
262
|
+
globalThis.removeEventListener("online", this.#onlineHandler);
|
|
263
|
+
}
|
|
264
|
+
this.#onlineHandler = null;
|
|
265
|
+
this.transport.stop();
|
|
266
|
+
}
|
|
267
|
+
/** This identity's publishable key-bundle — what goes in an invite (or the chain anchor). */
|
|
268
|
+
myBundle() {
|
|
269
|
+
if (!this.#bundle)
|
|
270
|
+
throw new Error("ChatService not started");
|
|
271
|
+
return this.#bundle;
|
|
272
|
+
}
|
|
273
|
+
/** My wallet-rooted identity public key (libsignal serialization: type byte + 32-byte Curve25519).
|
|
274
|
+
* SSR (secrets.handle.me) hands this out in a guardian-consent — "the key is handed over the medium". */
|
|
275
|
+
myIdentityKey() {
|
|
276
|
+
return bundleIdentityKey(this.myBundle());
|
|
277
|
+
}
|
|
278
|
+
/** Open an outbound session to a peer by resolving their published bundle (cold lookup). */
|
|
279
|
+
openChat(remote) {
|
|
280
|
+
const bundle = this.directory.resolve(remote);
|
|
281
|
+
if (!bundle)
|
|
282
|
+
return false;
|
|
283
|
+
this.engine.processBundle(remote, bundle);
|
|
284
|
+
this.#contacts.add(remote);
|
|
285
|
+
this.#learnFromBundle(remote, bundle);
|
|
286
|
+
this.#resubscribe(); // listen on our pairwise label too, so the peer's reply on it reaches me
|
|
287
|
+
this.persist();
|
|
288
|
+
return true;
|
|
289
|
+
}
|
|
290
|
+
/** Open an outbound session from a bundle handed over directly (invite link / QR — no directory). */
|
|
291
|
+
openChatWithBundle(remote, bundle) {
|
|
292
|
+
this.engine.processBundle(remote, bundle);
|
|
293
|
+
this.#contacts.add(remote);
|
|
294
|
+
this.#learnFromBundle(remote, bundle);
|
|
295
|
+
this.#resubscribe(); // listen on our pairwise label too, so the peer's reply on it reaches me
|
|
296
|
+
this.persist();
|
|
297
|
+
}
|
|
298
|
+
/** Record what a peer's bundle tells us: the verify-once trusted identity key, and (Tier 2 Stage 3) their
|
|
299
|
+
* presence-auth key so we can address their public first-contact slot. */
|
|
300
|
+
#learnFromBundle(remote, bundle) {
|
|
301
|
+
const { identityKey, presenceAuthPub } = parseBundle(bundle);
|
|
302
|
+
this.#trustedKey.set(remote, identityKey); // verify-once: trust the key I open the session with
|
|
303
|
+
if (presenceAuthPub.length)
|
|
304
|
+
this.#peerPA.set(remote, presenceAuthPub);
|
|
305
|
+
}
|
|
306
|
+
/** Send a plain-text message (convenience over {@link sendContent}). */
|
|
307
|
+
send(remote, text) {
|
|
308
|
+
this.sendContent(remote, textMessage(text));
|
|
309
|
+
}
|
|
310
|
+
/** Sealed-sender encrypt and send typed content (any MIME) to a peer (must have an open session). The
|
|
311
|
+
* wire envelope carries no sender label — the recipient recovers it from the seal. Returns the message
|
|
312
|
+
* id (stamped into `meta.id`), which delivery/read receipts reference. */
|
|
313
|
+
sendContent(remote, content) {
|
|
314
|
+
const id = content.meta?.id ?? crypto.randomUUID();
|
|
315
|
+
const stamped = content.meta?.id ? content : { ...content, meta: { ...content.meta, id } };
|
|
316
|
+
const ts = this.now();
|
|
317
|
+
const env = this.#seal(remote, stamped, ts); // sealed at the current epoch; a retry re-addresses
|
|
318
|
+
this.#setSentState(id, "queued"); // pending until the network takes it
|
|
319
|
+
this.record(remote, { from: this.handle, content: stamped, ts });
|
|
320
|
+
this.persist();
|
|
321
|
+
this.#emitSendUpdate();
|
|
322
|
+
void this.#dispatch(id, remote, env);
|
|
323
|
+
return id;
|
|
324
|
+
}
|
|
325
|
+
/** Seal + address an envelope. The relay sees only an opaque, rotating label. The `slot` tells the mesh
|
|
326
|
+
* which presence table to use: a first-contact message rides the PUBLIC slot, an established one the
|
|
327
|
+
* unguessable PAIRWISE slot (Tier 2 Stage 3). */
|
|
328
|
+
#seal(remote, content, ts) {
|
|
329
|
+
const slot = this.#convReady.has(remote) ? "pairwise" : "public";
|
|
330
|
+
return { to: this.#sendTopic(remote, ts), body: this.engine.sealedSend(remote, encodeMessage(content)), ts, slot };
|
|
331
|
+
}
|
|
332
|
+
/** Authenticate a PUBLIC-slot presence registration (Tier 2 Stage 3): if `topic` is one of my current
|
|
333
|
+
* public first-contact labels, sign `topic‖addr‖epoch` so the helper accepts it. Returns null for a
|
|
334
|
+
* pairwise/unknown topic (registered unauthenticated — it's unguessable). Bound as a field so it can be
|
|
335
|
+
* handed to the transport as a callback. */
|
|
336
|
+
#sign = (topic, addr) => {
|
|
337
|
+
const now = this.now();
|
|
338
|
+
const e = presenceEpoch(now);
|
|
339
|
+
const idx = this.engine.publicSlotTopics(now).indexOf(topic); // [prev, cur, next]
|
|
340
|
+
if (idx < 0)
|
|
341
|
+
return null;
|
|
342
|
+
const epoch = [e - 1, e, e + 1][idx];
|
|
343
|
+
return { epoch, pub: this.engine.presenceAuthPub(), sig: this.engine.signPresence(fromHex(topic), addr, epoch) };
|
|
344
|
+
};
|
|
345
|
+
/** Where to deposit a message for `remote` (Tier 2). Once the peer has reached me they subscribe to our
|
|
346
|
+
* unguessable PAIRWISE label — use it (defeats the chain-watcher; survives a handle transfer). Before that
|
|
347
|
+
* (I'm initiating, no reply yet) the peer may not know me, so I deposit at their PUBLIC first-contact slot. */
|
|
348
|
+
#sendTopic(remote, ts) {
|
|
349
|
+
if (this.#convReady.has(remote)) {
|
|
350
|
+
try {
|
|
351
|
+
return this.engine.convSendTopic(remote, ts);
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
/* no session/identity — fall back to the public slot */
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
// Public first-contact slot = HKDF(peer's presence-auth pub, epoch), derived from their bundle (Stage 3).
|
|
358
|
+
const pa = this.#peerPA.get(remote);
|
|
359
|
+
if (pa)
|
|
360
|
+
return this.engine.publicSlotTopicFor(pa, ts);
|
|
361
|
+
return this.engine.peerTopic(remote, ts); // legacy fallback (peer bundle predates presence-auth)
|
|
362
|
+
}
|
|
363
|
+
/** My full subscription set: the PUBLIC first-contact slot (prev/cur/next), plus — for every known contact
|
|
364
|
+
* — the pairwise labels they deposit at FOR me (prev/cur/next). All rotate by epoch. */
|
|
365
|
+
#myTopicSet() {
|
|
366
|
+
const set = new Set(this.engine.publicSlotTopics(this.now())); // public first-contact slot (Stage 3)
|
|
367
|
+
for (const c of this.#contacts) {
|
|
368
|
+
try {
|
|
369
|
+
for (const t of this.engine.convRecvTopics(c, this.now()))
|
|
370
|
+
set.add(t);
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
/* no identity for this contact yet — only the public slot covers them */
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return [...set];
|
|
377
|
+
}
|
|
378
|
+
/** Recompute the subscription set and re-subscribe if it changed (epoch rolled, or a new contact added a
|
|
379
|
+
* pairwise label). Idempotent. */
|
|
380
|
+
#resubscribe() {
|
|
381
|
+
if (!this.started)
|
|
382
|
+
return;
|
|
383
|
+
const next = this.#myTopicSet();
|
|
384
|
+
if (next.join() !== this.#topics.join()) {
|
|
385
|
+
this.#topics = next;
|
|
386
|
+
this.transport.subscribe(next, (env) => this.receive(env), this.#sign);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** Hand an envelope to the network; queue it if we're offline or the network can't take it. `track`
|
|
390
|
+
* is false for blob chunks — reliable, but not a user-visible message whose status should change. */
|
|
391
|
+
async #dispatch(id, remote, env, track = true) {
|
|
392
|
+
// Offline OR a non-empty backlog → queue, so the queue is the sole ordering authority (a fresh send
|
|
393
|
+
// must not overtake messages still waiting to flush).
|
|
394
|
+
if (this.#offline() || this.#queue.length > 0)
|
|
395
|
+
return this.#enqueue(id, remote, env, track);
|
|
396
|
+
const ok = await this.transport.send(env).catch(() => false);
|
|
397
|
+
if (ok) {
|
|
398
|
+
if (track)
|
|
399
|
+
this.#advanceSentState(id, "sent");
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
this.#enqueue(id, remote, env, track);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
#enqueue(id, remote, env, track = true) {
|
|
406
|
+
this.#queue.push({ id, remote, to: env.to, body: toB64(env.body), ts: env.ts, track });
|
|
407
|
+
if (this.#queue.length > MAX_QUEUE)
|
|
408
|
+
this.#queue.splice(0, this.#queue.length - MAX_QUEUE); // bound memory/storage
|
|
409
|
+
if (track) {
|
|
410
|
+
this.#setSentState(id, "queued");
|
|
411
|
+
this.#emitSendUpdate();
|
|
412
|
+
}
|
|
413
|
+
this.#persistQueue();
|
|
414
|
+
this.#scheduleFlush();
|
|
415
|
+
}
|
|
416
|
+
/** Set a sent-message status, bounding the map (LRU by insertion order) so a long session can't leak it. */
|
|
417
|
+
#setSentState(id, state) {
|
|
418
|
+
this.#sentState.set(id, state);
|
|
419
|
+
if (this.#sentState.size > MAX_SENT_STATE) {
|
|
420
|
+
const oldest = this.#sentState.keys().next().value;
|
|
421
|
+
if (oldest !== undefined && oldest !== id)
|
|
422
|
+
this.#sentState.delete(oldest);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
#offline() {
|
|
426
|
+
return typeof navigator !== "undefined" && navigator.onLine === false;
|
|
427
|
+
}
|
|
428
|
+
/** Sliding-window rate limit for cold first-contacts from un-anchored senders. */
|
|
429
|
+
#admitUnverified() {
|
|
430
|
+
const now = Date.now();
|
|
431
|
+
this.#unverifiedAdmissions = this.#unverifiedAdmissions.filter((t) => now - t < UNVERIFIED_WINDOW_MS);
|
|
432
|
+
if (this.#unverifiedAdmissions.length >= UNVERIFIED_FIRST_CONTACT_LIMIT)
|
|
433
|
+
return false;
|
|
434
|
+
this.#unverifiedAdmissions.push(now);
|
|
435
|
+
return true;
|
|
436
|
+
}
|
|
437
|
+
/** Retry queued envelopes in order, stopping at the first the network still won't take (preserves order). */
|
|
438
|
+
async flushQueue() {
|
|
439
|
+
if (this.#flushing || this.#offline())
|
|
440
|
+
return;
|
|
441
|
+
this.#flushing = true;
|
|
442
|
+
try {
|
|
443
|
+
while (this.#queue.length) {
|
|
444
|
+
const item = this.#queue[0];
|
|
445
|
+
// RE-ADDRESS to the recipient's CURRENT-epoch topic (topics rotate daily; a long-offline message's
|
|
446
|
+
// frozen label is dead). Re-address only — the body was sealed once, so we don't re-encrypt.
|
|
447
|
+
let to = item.to;
|
|
448
|
+
if (item.remote) {
|
|
449
|
+
try {
|
|
450
|
+
to = this.#sendTopic(item.remote, this.now());
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
/* no session for remote (shouldn't happen post-restore) — fall back to the frozen label */
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
const ok = await this.transport.send({ to, body: fromB64(item.body), ts: item.ts }).catch(() => false);
|
|
457
|
+
if (!ok)
|
|
458
|
+
break;
|
|
459
|
+
this.#queue.shift();
|
|
460
|
+
if (item.track !== false)
|
|
461
|
+
this.#advanceSentState(item.id, "sent");
|
|
462
|
+
}
|
|
463
|
+
this.#persistQueue();
|
|
464
|
+
if (this.#queue.length === 0 && this.#flushTimer) {
|
|
465
|
+
clearInterval(this.#flushTimer);
|
|
466
|
+
this.#flushTimer = null;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
finally {
|
|
470
|
+
this.#flushing = false;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
#scheduleFlush() {
|
|
474
|
+
if (this.#flushTimer || this.#queue.length === 0)
|
|
475
|
+
return;
|
|
476
|
+
this.#flushTimer = setInterval(() => void this.flushQueue(), 3000);
|
|
477
|
+
}
|
|
478
|
+
#persistQueue() {
|
|
479
|
+
if (this.#vault)
|
|
480
|
+
void this.#vault.saveQueue(this.handle, [...this.#queue]).catch(() => { });
|
|
481
|
+
}
|
|
482
|
+
#emitSendUpdate() {
|
|
483
|
+
this.onSendUpdateCb?.();
|
|
484
|
+
}
|
|
485
|
+
/** Send a control message (receipt) — best-effort, never queued. */
|
|
486
|
+
#sendRaw(remote, content, ts) {
|
|
487
|
+
void this.transport.send(this.#seal(remote, content, ts)).catch(() => { });
|
|
488
|
+
}
|
|
489
|
+
/** Mark a received message read — sends a "read" receipt to its sender. */
|
|
490
|
+
markRead(remote, messageId) {
|
|
491
|
+
this.#sendRaw(remote, receiptMessage(messageId, "read"), Date.now());
|
|
492
|
+
this.persist();
|
|
493
|
+
}
|
|
494
|
+
/** Advance a sent message's status, never regressing it (out-of-order delivered/read acks are common). */
|
|
495
|
+
#advanceSentState(id, state) {
|
|
496
|
+
const cur = this.#sentState.get(id);
|
|
497
|
+
if (cur && SEND_STATE_RANK[cur] >= SEND_STATE_RANK[state])
|
|
498
|
+
return;
|
|
499
|
+
this.#setSentState(id, state);
|
|
500
|
+
this.#emitSendUpdate();
|
|
501
|
+
}
|
|
502
|
+
/** Current delivery state of one of my sent messages ("queued"/"sent" until the peer acks). */
|
|
503
|
+
sentState(messageId) {
|
|
504
|
+
return this.#sentState.get(messageId);
|
|
505
|
+
}
|
|
506
|
+
onReceipt(cb) {
|
|
507
|
+
this.onReceiptCb = cb;
|
|
508
|
+
}
|
|
509
|
+
/** Register a handler for a conversation's identity key changing after first contact (verify-once-then-warn
|
|
510
|
+
* — the handle was re-anchored / may have changed hands, or a different key tried to claim it). */
|
|
511
|
+
onKeyChange(cb) {
|
|
512
|
+
this.onKeyChangeCb = cb;
|
|
513
|
+
}
|
|
514
|
+
/** Fires when any sent-message state changes (queued/sent/delivered/read) — for the UI to refresh ticks. */
|
|
515
|
+
onSendUpdate(cb) {
|
|
516
|
+
this.onSendUpdateCb = cb;
|
|
517
|
+
}
|
|
518
|
+
/** Send a large blob (image/audio/video/…) by STREAMING it: encrypt + chunk + content-address, then
|
|
519
|
+
* send a small `blob-ref` (tracked, carries the message id) + raw `blob-chunk` messages (reliable, but
|
|
520
|
+
* untracked). The recipient reassembles + verifies + decrypts. Returns the message id. The caller still
|
|
521
|
+
* echoes the full media locally (the sender already has the bytes). */
|
|
522
|
+
async sendBlob(remote, mime, bytes, name) {
|
|
523
|
+
const id = crypto.randomUUID();
|
|
524
|
+
this.#setSentState(id, "queued");
|
|
525
|
+
this.record(remote, { from: this.handle, content: mediaMessage(mime, bytes, { name: name ?? "", id }), ts: Date.now() });
|
|
526
|
+
this.persist();
|
|
527
|
+
this.#emitSendUpdate();
|
|
528
|
+
const { ref, chunks } = await buildBlobMessages(id, mime, bytes, name);
|
|
529
|
+
this.#reliableSend(remote, ref, id, true); // the ref's delivery flips the blob's status
|
|
530
|
+
for (const c of chunks)
|
|
531
|
+
this.#reliableSend(remote, c, `chunk:${crypto.randomUUID()}`, false);
|
|
532
|
+
return id;
|
|
533
|
+
}
|
|
534
|
+
/** Reliable (queue-aware) send that does NOT record in history — for blob ref/chunk transport messages. */
|
|
535
|
+
#reliableSend(remote, content, id, track) {
|
|
536
|
+
void this.#dispatch(id, remote, this.#seal(remote, content, Date.now()), track);
|
|
537
|
+
}
|
|
538
|
+
onMessage(cb) {
|
|
539
|
+
this.onMessageCb = cb;
|
|
540
|
+
}
|
|
541
|
+
/** Serialize inbound processing: each envelope fully completes (incl. async blob reassembly) before the
|
|
542
|
+
* next, so app-level ordering of history/UI is preserved even when a blob await interleaves. */
|
|
543
|
+
receive(env) {
|
|
544
|
+
this.#recvChain = this.#recvChain.then(() => this.#receiveInner(env)).catch(() => { });
|
|
545
|
+
}
|
|
546
|
+
async #receiveInner(env) {
|
|
547
|
+
if (env.body.length > MAX_ENVELOPE_BYTES)
|
|
548
|
+
return; // anti-DoS: drop oversized envelopes before decrypting
|
|
549
|
+
// Dedup before decrypting: the same envelope now arrives via BOTH the direct dial and the mailbox
|
|
550
|
+
// (send deposits to both — see MeshClient.send), and a relay may redeliver. Drop a repeat by its content
|
|
551
|
+
// fingerprint so the redundant copy never advances the ratchet, double-records history, or re-emits.
|
|
552
|
+
const fp = await envelopeFp(env.body);
|
|
553
|
+
if (this.#seenEnvelopes.has(fp))
|
|
554
|
+
return;
|
|
555
|
+
this.#seenEnvelopes.add(fp);
|
|
556
|
+
if (this.#seenEnvelopes.size > MAX_SEEN_ENVELOPES) {
|
|
557
|
+
const oldest = this.#seenEnvelopes.values().next().value;
|
|
558
|
+
if (oldest !== undefined)
|
|
559
|
+
this.#seenEnvelopes.delete(oldest);
|
|
560
|
+
}
|
|
561
|
+
try {
|
|
562
|
+
const { sender, identityKey, body } = this.engine.sealedReceive(env.body);
|
|
563
|
+
if (!isValidHandle(sender))
|
|
564
|
+
return; // drop malformed/forged sender handles before they touch state or the DOM
|
|
565
|
+
// Verify-once-then-warn. The WASM already bound this cert key to the session-authenticated identity, so
|
|
566
|
+
// `identityKey` is cryptographically the peer. The TRUST question is handle↔key:
|
|
567
|
+
const bundle = this.directory.resolve(sender);
|
|
568
|
+
const anchorKey = bundle ? bundleIdentityKey(bundle) : null;
|
|
569
|
+
const trusted = this.#trustedKey.get(sender);
|
|
570
|
+
if (trusted) {
|
|
571
|
+
// Established conversation: trust the key I verified at first contact + the ratchet — do NOT re-check
|
|
572
|
+
// the live anchor per message (that's what silently broke a conversation when its handle was
|
|
573
|
+
// re-anchored / sold). A DIFFERENT key claiming this conversation is a key change I never verified:
|
|
574
|
+
// warn and DROP (the app must explicitly re-verify before trusting it).
|
|
575
|
+
if (!bytesEqual(trusted, identityKey)) {
|
|
576
|
+
this.onKeyChangeCb?.({ handle: sender, knownKey: trusted, newKey: identityKey, anchorDiverged: false });
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
// Same trusted key, but the on-chain anchor has since moved → the handle was re-anchored (may have
|
|
580
|
+
// changed hands). Surface it, but keep trusting the established session and accept the message.
|
|
581
|
+
if (anchorKey && !bytesEqual(anchorKey, trusted)) {
|
|
582
|
+
this.onKeyChangeCb?.({ handle: sender, knownKey: trusted, newKey: anchorKey, anchorDiverged: true });
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
else {
|
|
586
|
+
// First contact: chain-as-CA if the handle is anchored (the claimed key MUST match the on-chain
|
|
587
|
+
// anchor, else it's an impersonator → drop); otherwise TOFU (invite/out-of-band bundle). Record the
|
|
588
|
+
// verified key as this conversation's trusted identity.
|
|
589
|
+
if (anchorKey && !bytesEqual(anchorKey, identityKey))
|
|
590
|
+
return;
|
|
591
|
+
this.#trustedKey.set(sender, identityKey);
|
|
592
|
+
}
|
|
593
|
+
// Abuse gate. Always admit a KNOWN contact (we initiated, or already accepted) or an ANCHORED sender
|
|
594
|
+
// (chain-verified above; an anchor + Handle cost ada per identity → Sybil-resistant). A cold
|
|
595
|
+
// first-contact from an UN-anchored sender is the spam vector — rate-limit it. (An invitee holds our
|
|
596
|
+
// bundle by our consent and gets through within the budget, then is known and unlimited thereafter.)
|
|
597
|
+
if (!this.#contacts.has(sender) && !bundle && !this.#admitUnverified())
|
|
598
|
+
return;
|
|
599
|
+
// The sender reached me → they know me and subscribe to our pairwise label, so address them there from
|
|
600
|
+
// now on (Tier 2). A receipt counts too. If this is a newly-known contact, re-subscribe so I also listen
|
|
601
|
+
// on the pairwise label they'll deposit at.
|
|
602
|
+
this.#convReady.add(sender);
|
|
603
|
+
if (!this.#contacts.has(sender)) {
|
|
604
|
+
this.#contacts.add(sender);
|
|
605
|
+
this.#resubscribe();
|
|
606
|
+
}
|
|
607
|
+
const content = decodeMessage(body);
|
|
608
|
+
// Receipts are control, not content: update my sent-message state and surface to the UI, never record.
|
|
609
|
+
const receipt = parseReceipt(content);
|
|
610
|
+
if (receipt) {
|
|
611
|
+
this.persist(); // the inbound receipt advanced the ratchet regardless
|
|
612
|
+
// Only honor a receipt for a message we actually sent (a known id) — this prevents forged/arbitrary
|
|
613
|
+
// refs from spoofing status or growing #sentState — and only advance, never regress, the status.
|
|
614
|
+
if (this.#sentState.has(receipt.ref)) {
|
|
615
|
+
this.#advanceSentState(receipt.ref, receipt.state);
|
|
616
|
+
this.onReceiptCb?.({ from: sender, ref: receipt.ref, state: receipt.state });
|
|
617
|
+
}
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
// Streamed blob: ref/chunk parts are control until the blob completes — then surface the full media.
|
|
621
|
+
if (isBlobPart(content)) {
|
|
622
|
+
const media = await this.#assembler.accept(content);
|
|
623
|
+
this.persist(); // the inbound part advanced the ratchet
|
|
624
|
+
if (media)
|
|
625
|
+
this.#surface(sender, media, env.ts);
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
this.#surface(sender, content, env.ts);
|
|
629
|
+
this.persist(); // inbound message + the delivery ack both advanced the ratchet
|
|
630
|
+
}
|
|
631
|
+
catch {
|
|
632
|
+
// ignore undecryptable / unverifiable envelopes (not for us, or impersonation attempt)
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
/** Record a received message, hand it to the app, and auto-acknowledge delivery to the sender. */
|
|
636
|
+
#surface(sender, content, ts) {
|
|
637
|
+
this.record(sender, { from: sender, content, ts });
|
|
638
|
+
this.onMessageCb?.({ from: sender, content, text: messageText(content), ts });
|
|
639
|
+
const id = content.meta?.id; // the inbound message gave us a usable return session for the ack
|
|
640
|
+
if (id)
|
|
641
|
+
this.#sendRaw(sender, receiptMessage(id, "delivered"), Date.now());
|
|
642
|
+
}
|
|
643
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The on-chain anchor codec: a handle's published Signal key-bundle, carried in Cardano transaction
|
|
3
|
+
* metadata (CIP-20-style), label 7368 → `[handle, ...64-char hex chunks of the bundle]`. Mirrors
|
|
4
|
+
* `poc/`'s `ChainAnchorStore` codec. Pure data — no chain or crypto deps, so it unit-tests in node.
|
|
5
|
+
*
|
|
6
|
+
* The bundle is `SignalEngine.createBundle()` output (idPub + signed pre-key + Kyber, self-signed by the
|
|
7
|
+
* identity key). What binds it to the handle is provenance: the anchor is published from the handle
|
|
8
|
+
* owner's address, so only the owner can write it. (Resolve verifies that — see the ChainAnchorStore.)
|
|
9
|
+
*/
|
|
10
|
+
export declare const ANCHOR_METADATA_LABEL = 7368n;
|
|
11
|
+
/** Build the metadata value for a handle's bundle: `[handle, ...hex chunks]`. */
|
|
12
|
+
export declare function encodeAnchorMetadata(handle: string, bundle: Uint8Array): string[];
|
|
13
|
+
/** Decode a metadata value back into `{ handle, bundle }`, or null if it isn't a well-formed anchor. */
|
|
14
|
+
export declare function decodeAnchorMetadata(value: unknown): {
|
|
15
|
+
handle: string;
|
|
16
|
+
bundle: Uint8Array;
|
|
17
|
+
} | null;
|