@koralabs/handle-chat-sdk 1.0.1 → 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.
- package/assets/libsignal_bg.wasm +0 -0
- package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.d.ts +20 -0
- package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.js +85 -0
- package/lib/src/chat/ChatService.d.ts +13 -9
- package/lib/src/chat/ChatService.js +384 -105
- package/lib/src/chat/anchor.d.ts +2 -2
- package/lib/src/chat/anchor.js +2 -2
- package/lib/src/chat/blob.d.ts +14 -0
- package/lib/src/chat/blob.js +107 -6
- package/lib/src/chat/chainDirectory.d.ts +14 -19
- package/lib/src/chat/chainDirectory.js +73 -31
- package/lib/src/chat/demeter.d.ts +3 -0
- package/lib/src/chat/demeter.js +8 -0
- package/lib/src/chat/directory.d.ts +12 -2
- package/lib/src/chat/directory.js +23 -0
- package/lib/src/chat/guardian.d.ts +6 -4
- package/lib/src/chat/guardian.js +17 -5
- package/lib/src/chat/guardianHistory.d.ts +3 -0
- package/lib/src/chat/guardianHistory.js +36 -0
- package/lib/src/chat/httpRateLimit.d.ts +5 -0
- package/lib/src/chat/httpRateLimit.js +54 -0
- package/lib/src/chat/identity.d.ts +1 -1
- package/lib/src/chat/identity.js +8 -2
- package/lib/src/chat/invite.d.ts +7 -0
- package/lib/src/chat/invite.js +18 -0
- package/lib/src/chat/mesh/client.d.ts +6 -3
- package/lib/src/chat/mesh/client.js +89 -13
- package/lib/src/chat/mesh/protocol.d.ts +35 -0
- package/lib/src/chat/mesh/protocol.js +11 -0
- package/lib/src/chat/publish.d.ts +1 -1
- package/lib/src/chat/publish.js +13 -2
- package/lib/src/chat/sessionStore.d.ts +10 -1
- package/lib/src/chat/sessionStore.js +52 -7
- package/lib/src/chat/transport.d.ts +2 -2
- package/lib/src/chat/transport.js +66 -6
- package/lib/src/signal/SignalEngine.d.ts +5 -0
- package/lib/src/signal/SignalEngine.js +10 -0
- package/package.json +3 -2
package/lib/src/chat/invite.d.ts
CHANGED
|
@@ -5,6 +5,13 @@ export declare function decodeInvite(payload: string): {
|
|
|
5
5
|
};
|
|
6
6
|
/** A shareable invite URL: `<origin>/#i=<payload>`. */
|
|
7
7
|
export declare const inviteUrl: (origin: string, handle: string, bundle: Uint8Array) => string;
|
|
8
|
+
/** A recovery continuation conveys only the requester's public invite and session identifier, never the share or a ratchet. */
|
|
9
|
+
export declare function recoveryContinuation(handle: string, bundle: Uint8Array, sessionId: string): string;
|
|
10
|
+
export declare function parseRecoveryContinuation(hash: string): {
|
|
11
|
+
handle: string;
|
|
12
|
+
bundle: Uint8Array;
|
|
13
|
+
sessionId: string;
|
|
14
|
+
} | null;
|
|
8
15
|
/** Pull an invite out of a URL (or null if there isn't one). */
|
|
9
16
|
export declare function parseInviteUrl(url: string): {
|
|
10
17
|
handle: string;
|
package/lib/src/chat/invite.js
CHANGED
|
@@ -41,6 +41,24 @@ export function decodeInvite(payload) {
|
|
|
41
41
|
}
|
|
42
42
|
/** A shareable invite URL: `<origin>/#i=<payload>`. */
|
|
43
43
|
export const inviteUrl = (origin, handle, bundle) => `${origin}/#i=${encodeInvite(handle, bundle)}`;
|
|
44
|
+
/** A recovery continuation conveys only the requester's public invite and session identifier, never the share or a ratchet. */
|
|
45
|
+
export function recoveryContinuation(handle, bundle, sessionId) {
|
|
46
|
+
if (!/^[0-9a-f]{64}$/.test(sessionId))
|
|
47
|
+
throw new Error("invalid recovery session id");
|
|
48
|
+
return `#/guardian?i=${encodeInvite(handle, bundle)}&session=${sessionId}`;
|
|
49
|
+
}
|
|
50
|
+
export function parseRecoveryContinuation(hash) {
|
|
51
|
+
const match = /^#\/guardian\?i=([A-Za-z0-9_-]{1,32768})&session=([0-9a-f]{64})$/.exec(hash);
|
|
52
|
+
if (!match)
|
|
53
|
+
return null;
|
|
54
|
+
try {
|
|
55
|
+
const invite = decodeInvite(match[1]);
|
|
56
|
+
return invite.handle && invite.bundle.length ? { ...invite, sessionId: match[2] } : null;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
44
62
|
/** Pull an invite out of a URL (or null if there isn't one). */
|
|
45
63
|
export function parseInviteUrl(url) {
|
|
46
64
|
const m = url.match(/[#&]i=([A-Za-z0-9_-]+)/);
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import { type WireEnvelope } from "./protocol";
|
|
1
|
+
import { type WireEnvelope, type MailboxAckRequest } from "./protocol";
|
|
2
2
|
import type { RegistrationSigner } from "../transport";
|
|
3
|
+
export type AcknowledgedMailboxRequest = MailboxAckRequest;
|
|
4
|
+
/** Fetch without deleting; acknowledge only after durable acceptance and while the subscription is current. */
|
|
5
|
+
export declare function drainAcknowledgedTopic(to: string, rpc: (request: AcknowledgedMailboxRequest) => Promise<unknown>, receiveDurably: (envelope: WireEnvelope) => Promise<boolean>, signer: RegistrationSigner, isCurrent?: () => boolean): Promise<void>;
|
|
3
6
|
/**
|
|
4
7
|
* The mesh client: one WebRTC-capable node that registers its presence with the helper, receives direct
|
|
5
8
|
* (peer-to-peer) envelopes AND polls the mailbox, and sends DIRECT-FIRST — dialing the recipient
|
|
@@ -14,10 +17,10 @@ export declare class MeshClient {
|
|
|
14
17
|
private readonly poll;
|
|
15
18
|
private readonly reRegister;
|
|
16
19
|
private constructor();
|
|
17
|
-
static start(helperAddr: string, keys: string[], onEnvelope: (e: WireEnvelope) => void, pollMs?: number, signer?: RegistrationSigner): Promise<MeshClient>;
|
|
20
|
+
static start(helperAddr: string, keys: string[], onEnvelope: (e: WireEnvelope) => void, pollMs?: number, signer?: RegistrationSigner, receiveDurably?: (e: WireEnvelope) => Promise<boolean>): Promise<MeshClient>;
|
|
18
21
|
/** Replace the active label set (called on a topic-rotation rollover) and register the new labels now. The
|
|
19
22
|
* signer authenticates the public-slot labels among them (Tier 2 Stage 3). */
|
|
20
|
-
setKeys(keys: string[], signer?: RegistrationSigner): void;
|
|
23
|
+
setKeys(keys: string[], signer?: RegistrationSigner, receiveDurably?: (e: WireEnvelope) => Promise<boolean>): void;
|
|
21
24
|
/** Send DIRECT-FIRST: dial the recipient peer-to-peer if present, else store in the mailbox. Resolves
|
|
22
25
|
* `true` if delivered/stored, `false` if neither path could take it (helper unreachable → caller queues). */
|
|
23
26
|
send(env: WireEnvelope): Promise<boolean>;
|
|
@@ -3,7 +3,7 @@ import { createWebrtcNode } from "./b2b.js";
|
|
|
3
3
|
import { request } from "./node.js";
|
|
4
4
|
import { readFrame, sendFrame } from "./wire.js";
|
|
5
5
|
import { waitForWebrtcAddr } from "./webrtcAddr.js";
|
|
6
|
-
import { MAILBOX_PROTOCOL, PRESENCE_PROTOCOL, DIRECT_PROTOCOL, } from "./protocol.js";
|
|
6
|
+
import { MAILBOX_PROTOCOL, MAILBOX_ACK_PROTOCOL, pairwiseRoutingTopic, PRESENCE_PROTOCOL, DIRECT_PROTOCOL, } from "./protocol.js";
|
|
7
7
|
const enc = new TextEncoder();
|
|
8
8
|
const dec = new TextDecoder();
|
|
9
9
|
const b64 = (b) => {
|
|
@@ -12,13 +12,57 @@ const b64 = (b) => {
|
|
|
12
12
|
s += String.fromCharCode(x);
|
|
13
13
|
return btoa(s);
|
|
14
14
|
};
|
|
15
|
+
/** Fetch without deleting; acknowledge only after durable acceptance and while the subscription is current. */
|
|
16
|
+
export async function drainAcknowledgedTopic(to, rpc, receiveDurably, signer, isCurrent = () => true) {
|
|
17
|
+
if (!isCurrent())
|
|
18
|
+
return;
|
|
19
|
+
const proof = (address) => {
|
|
20
|
+
const signed = signer(to, address);
|
|
21
|
+
return signed ? { epoch: signed.epoch, pub: b64(signed.pub), sig: b64(signed.sig) } : undefined;
|
|
22
|
+
};
|
|
23
|
+
let result;
|
|
24
|
+
const raw = pairwiseRoutingTopic(to);
|
|
25
|
+
try {
|
|
26
|
+
result = await rpc({ op: "fetch", to, proof: proof("mailbox-fetch") });
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (!isCurrent() || !result || typeof result !== "object" || !("deliveries" in result) || !Array.isArray(result.deliveries))
|
|
32
|
+
return;
|
|
33
|
+
for (const delivery of result.deliveries) {
|
|
34
|
+
if (!isCurrent())
|
|
35
|
+
return;
|
|
36
|
+
if (delivery?.legacy === true) {
|
|
37
|
+
// Read-only copies from old pairwise senders: never ACK these or consume them via v1 fetch.
|
|
38
|
+
if (raw && delivery.envelope?.to === raw)
|
|
39
|
+
await receiveDurably({ ...delivery.envelope, to }).catch(() => false);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (typeof delivery?.id !== "string" || !delivery.id || delivery.envelope?.to !== to)
|
|
43
|
+
continue;
|
|
44
|
+
let accepted = false;
|
|
45
|
+
try {
|
|
46
|
+
accepted = await receiveDurably(delivery.envelope);
|
|
47
|
+
}
|
|
48
|
+
catch { /* Keep the delivery for retry. */ }
|
|
49
|
+
if (!isCurrent())
|
|
50
|
+
return;
|
|
51
|
+
if (accepted === true) {
|
|
52
|
+
try {
|
|
53
|
+
await rpc({ op: "ack", to, id: delivery.id, proof: proof(`mailbox-ack:${delivery.id}`) });
|
|
54
|
+
}
|
|
55
|
+
catch { /* An unacknowledged delivery will be retried. */ }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
15
59
|
/** Build a presence registration for one routing label: an AUTHENTICATED public-slot registration if the
|
|
16
60
|
* signer vouches for it (Tier 2 Stage 3), else an unauthenticated pairwise one. */
|
|
17
61
|
const registration = (key, addr, signer) => {
|
|
18
62
|
const auth = signer(key, addr);
|
|
19
63
|
return auth
|
|
20
64
|
? { op: "register", key, addr, slot: "public", epoch: auth.epoch, pub: b64(auth.pub), sig: b64(auth.sig) }
|
|
21
|
-
: { op: "register", key, addr, slot: "pairwise" };
|
|
65
|
+
: { op: "register", key: pairwiseRoutingTopic(key) ?? key, addr, slot: "pairwise" };
|
|
22
66
|
};
|
|
23
67
|
async function jsonReq(node, addr, protocol, req) {
|
|
24
68
|
const bytes = await request(node, addr, protocol, enc.encode(JSON.stringify(req)));
|
|
@@ -45,7 +89,7 @@ export class MeshClient {
|
|
|
45
89
|
this.poll = poll;
|
|
46
90
|
this.reRegister = reRegister;
|
|
47
91
|
}
|
|
48
|
-
static async start(helperAddr, keys, onEnvelope, pollMs = 1500, signer = () => null) {
|
|
92
|
+
static async start(helperAddr, keys, onEnvelope, pollMs = 1500, signer = () => null, receiveDurably) {
|
|
49
93
|
const node = await createWebrtcNode();
|
|
50
94
|
// A failed start must not leak the running libp2p node (its listeners keep the process alive).
|
|
51
95
|
try {
|
|
@@ -65,19 +109,37 @@ export class MeshClient {
|
|
|
65
109
|
await node.dial(multiaddr(helperAddr));
|
|
66
110
|
const myAddr = await waitForWebrtcAddr(node);
|
|
67
111
|
// Our rotating label set (updatable via setKeys). Register presence + poll the mailbox under EACH.
|
|
68
|
-
const ref = { keys: [...keys], signer, myAddr };
|
|
112
|
+
const ref = { keys: [...keys], signer, myAddr, receiveDurably, generation: 0, active: true };
|
|
69
113
|
const register = async () => {
|
|
70
114
|
for (const key of ref.keys)
|
|
71
115
|
await jsonReq(node, helperAddr, PRESENCE_PROTOCOL, registration(key, ref.myAddr, ref.signer)).catch(() => { });
|
|
72
116
|
};
|
|
73
117
|
await register();
|
|
74
118
|
const reRegister = setInterval(() => void register(), 30_000); // refresh before the helper's TTL
|
|
119
|
+
let draining = false;
|
|
75
120
|
const drain = async () => {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
121
|
+
if (draining || !ref.active)
|
|
122
|
+
return;
|
|
123
|
+
draining = true;
|
|
124
|
+
const generation = ref.generation;
|
|
125
|
+
const current = () => ref.active && ref.generation === generation;
|
|
126
|
+
try {
|
|
127
|
+
for (const key of [...ref.keys]) {
|
|
128
|
+
if (!current())
|
|
129
|
+
break;
|
|
130
|
+
const durable = ref.receiveDurably;
|
|
131
|
+
if (!durable) {
|
|
132
|
+
const res = await jsonReq(node, helperAddr, MAILBOX_PROTOCOL, { op: "fetch", to: pairwiseRoutingTopic(key) ?? key }).catch(() => null);
|
|
133
|
+
if (res && "envelopes" in res)
|
|
134
|
+
for (const env of res.envelopes)
|
|
135
|
+
onEnvelope(env);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
await drainAcknowledgedTopic(key, (req) => jsonReq(node, helperAddr, MAILBOX_ACK_PROTOCOL, req), durable, ref.signer, current);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
draining = false;
|
|
81
143
|
}
|
|
82
144
|
};
|
|
83
145
|
void drain().catch(() => { });
|
|
@@ -91,24 +153,34 @@ export class MeshClient {
|
|
|
91
153
|
}
|
|
92
154
|
/** Replace the active label set (called on a topic-rotation rollover) and register the new labels now. The
|
|
93
155
|
* signer authenticates the public-slot labels among them (Tier 2 Stage 3). */
|
|
94
|
-
setKeys(keys, signer = this.ref.signer) {
|
|
156
|
+
setKeys(keys, signer = this.ref.signer, receiveDurably) {
|
|
157
|
+
if (arguments.length < 3)
|
|
158
|
+
receiveDurably = this.ref.receiveDurably;
|
|
159
|
+
if (signer === this.ref.signer && receiveDurably === this.ref.receiveDurably &&
|
|
160
|
+
keys.length === this.ref.keys.length && keys.every((key, i) => key === this.ref.keys[i]))
|
|
161
|
+
return;
|
|
95
162
|
this.ref.keys = [...keys];
|
|
96
163
|
this.ref.signer = signer;
|
|
164
|
+
this.ref.receiveDurably = receiveDurably;
|
|
165
|
+
this.ref.generation++;
|
|
97
166
|
this.refresh();
|
|
98
167
|
}
|
|
99
168
|
/** Send DIRECT-FIRST: dial the recipient peer-to-peer if present, else store in the mailbox. Resolves
|
|
100
169
|
* `true` if delivered/stored, `false` if neither path could take it (helper unreachable → caller queues). */
|
|
101
170
|
async send(env) {
|
|
171
|
+
const pair = pairwiseRoutingTopic(env.to);
|
|
172
|
+
const legacy = pair ? { ...env, to: pair } : env;
|
|
102
173
|
const res = await jsonReq(this.node, this.helperAddr, PRESENCE_PROTOCOL, {
|
|
103
174
|
op: "lookup",
|
|
104
|
-
key:
|
|
175
|
+
key: legacy.to,
|
|
105
176
|
slot: env.slot ?? "pairwise",
|
|
177
|
+
...(pair ? { queryMailboxAddressing: true } : {}),
|
|
106
178
|
}).catch(() => ({ addr: null }));
|
|
107
179
|
const addr = "addr" in res ? res.addr : null;
|
|
108
180
|
if (addr) {
|
|
109
181
|
try {
|
|
110
182
|
const stream = await this.node.dialProtocol(multiaddr(addr), DIRECT_PROTOCOL);
|
|
111
|
-
sendFrame(stream, enc.encode(JSON.stringify(
|
|
183
|
+
sendFrame(stream, enc.encode(JSON.stringify(legacy)));
|
|
112
184
|
await new Promise((r) => setTimeout(r, 100));
|
|
113
185
|
await stream.close().catch(() => { });
|
|
114
186
|
return true;
|
|
@@ -118,7 +190,9 @@ export class MeshClient {
|
|
|
118
190
|
}
|
|
119
191
|
}
|
|
120
192
|
try {
|
|
121
|
-
|
|
193
|
+
// Keep bare v1 addresses when the helper does not advertise the new mailbox addressing.
|
|
194
|
+
const envelope = "pairwiseMailbox" in res && res.pairwiseMailbox === true ? env : legacy;
|
|
195
|
+
const r = await jsonReq(this.node, this.helperAddr, MAILBOX_PROTOCOL, { op: "store", envelope });
|
|
122
196
|
return "ok" in r && r.ok === true;
|
|
123
197
|
}
|
|
124
198
|
catch {
|
|
@@ -126,6 +200,8 @@ export class MeshClient {
|
|
|
126
200
|
}
|
|
127
201
|
}
|
|
128
202
|
async stop() {
|
|
203
|
+
this.ref.active = false;
|
|
204
|
+
this.ref.generation++;
|
|
129
205
|
clearInterval(this.poll);
|
|
130
206
|
clearInterval(this.reRegister);
|
|
131
207
|
await this.node.stop();
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
/** The store-and-forward mailbox protocol — the helper's one job. */
|
|
2
2
|
export declare const MAILBOX_PROTOCOL = "/handle-chat/mailbox/1.0.0";
|
|
3
|
+
/** Opt-in non-destructive fetch and explicit acknowledgement; stores remain on v1. */
|
|
4
|
+
export declare const MAILBOX_ACK_PROTOCOL = "/handle-chat/mailbox/2.0.0";
|
|
5
|
+
export declare function pairwiseMailbox(topic: string): string;
|
|
6
|
+
export declare const pairwiseRoutingTopic: (address: string) => string | undefined;
|
|
3
7
|
/** An envelope on the wire (JSON-safe): the ciphertext `body` is base64. With sealed sender there is NO
|
|
4
8
|
* sender field, and `to` is a scrambled TOPIC, not a handle — so the helper sees only an opaque routing
|
|
5
9
|
* label + opaque ciphertext: neither who sent it, who receives it, nor any plaintext. */
|
|
@@ -23,6 +27,35 @@ export type MailboxResponse = {
|
|
|
23
27
|
} | {
|
|
24
28
|
error: string;
|
|
25
29
|
};
|
|
30
|
+
export interface MailboxProof {
|
|
31
|
+
epoch: number;
|
|
32
|
+
pub: string;
|
|
33
|
+
sig: string;
|
|
34
|
+
}
|
|
35
|
+
export type MailboxAckRequest = {
|
|
36
|
+
op: "fetch";
|
|
37
|
+
to: string;
|
|
38
|
+
proof?: MailboxProof;
|
|
39
|
+
} | {
|
|
40
|
+
op: "ack";
|
|
41
|
+
to: string;
|
|
42
|
+
id: string;
|
|
43
|
+
proof?: MailboxProof;
|
|
44
|
+
};
|
|
45
|
+
export type MailboxDelivery = {
|
|
46
|
+
id: string;
|
|
47
|
+
envelope: WireEnvelope;
|
|
48
|
+
} | {
|
|
49
|
+
legacy: true;
|
|
50
|
+
envelope: WireEnvelope;
|
|
51
|
+
};
|
|
52
|
+
export type MailboxAckResponse = {
|
|
53
|
+
ok: true;
|
|
54
|
+
} | {
|
|
55
|
+
deliveries: MailboxDelivery[];
|
|
56
|
+
} | {
|
|
57
|
+
error: string;
|
|
58
|
+
};
|
|
26
59
|
/** Presence: an online peer registers its direct (/webrtc) address under its routing key, so a sender
|
|
27
60
|
* can find it and connect PEER-TO-PEER. The helper learns only the opaque routing key + a multiaddr —
|
|
28
61
|
* it never carries the conversation. (Expires by TTL; refreshed while online.) */
|
|
@@ -45,11 +78,13 @@ export type PresenceRequest = {
|
|
|
45
78
|
op: "lookup";
|
|
46
79
|
key: string;
|
|
47
80
|
slot: PresenceSlot;
|
|
81
|
+
queryMailboxAddressing?: true;
|
|
48
82
|
};
|
|
49
83
|
export type PresenceResponse = {
|
|
50
84
|
ok: true;
|
|
51
85
|
} | {
|
|
52
86
|
addr: string | null;
|
|
87
|
+
pairwiseMailbox?: true;
|
|
53
88
|
} | {
|
|
54
89
|
error: string;
|
|
55
90
|
};
|
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
/** The store-and-forward mailbox protocol — the helper's one job. */
|
|
2
2
|
export const MAILBOX_PROTOCOL = "/handle-chat/mailbox/1.0.0";
|
|
3
|
+
/** Opt-in non-destructive fetch and explicit acknowledgement; stores remain on v1. */
|
|
4
|
+
export const MAILBOX_ACK_PROTOCOL = "/handle-chat/mailbox/2.0.0";
|
|
5
|
+
// Both underlying routing labels are 32-byte hashes. Only this disjoint mailbox ADDRESS is
|
|
6
|
+
// authorized by possession. Never infer permission to delete a bare topic from a sender's slot.
|
|
7
|
+
const rawTopic = /^[0-9a-f]{64}$/;
|
|
8
|
+
export function pairwiseMailbox(topic) {
|
|
9
|
+
if (!rawTopic.test(topic))
|
|
10
|
+
throw new Error("invalid pairwise routing label");
|
|
11
|
+
return `pair:${topic}`;
|
|
12
|
+
}
|
|
13
|
+
export const pairwiseRoutingTopic = (address) => address.startsWith("pair:") && rawTopic.test(address.slice(5)) ? address.slice(5) : undefined;
|
|
3
14
|
/** Presence: an online peer registers its direct (/webrtc) address under its routing key, so a sender
|
|
4
15
|
* can find it and connect PEER-TO-PEER. The helper learns only the opaque routing key + a multiaddr —
|
|
5
16
|
* it never carries the conversation. (Expires by TTL; refreshed while online.) */
|
|
@@ -3,4 +3,4 @@ export interface PublishDeps {
|
|
|
3
3
|
signTx: (txCbor: string, partialSign?: boolean) => Promise<string>;
|
|
4
4
|
submitTx: (signedTxCbor: string) => Promise<string>;
|
|
5
5
|
}
|
|
6
|
-
export declare function publishAnchor(handle: string, bundle: Uint8Array, address: string, deps: PublishDeps): Promise<string>;
|
|
6
|
+
export declare function publishAnchor(handle: string, bundle: Uint8Array, address: string | undefined, deps: PublishDeps): Promise<string>;
|
package/lib/src/chat/publish.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { providerFetch } from "./httpRateLimit.js";
|
|
1
2
|
/**
|
|
2
3
|
* Publish a handle's Signal key-bundle as an on-chain anchor (the cold-discovery path). The app is a
|
|
3
4
|
* thin relay — no @cardano-sdk in the bundle: the BFF builds + assembles the tx, the wallet signs +
|
|
@@ -5,13 +6,23 @@
|
|
|
5
6
|
*/
|
|
6
7
|
const toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
7
8
|
async function postJson(url, body) {
|
|
8
|
-
const
|
|
9
|
+
const absolute = new URL(url, globalThis.location?.origin).href;
|
|
10
|
+
const res = await providerFetch(fetch, absolute, {
|
|
9
11
|
method: "POST",
|
|
10
12
|
headers: { "content-type": "application/json" },
|
|
11
13
|
body: JSON.stringify(body),
|
|
12
14
|
});
|
|
13
|
-
if (!res.ok)
|
|
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
|
+
}
|
|
14
24
|
throw new Error(`${url} → ${res.status}`);
|
|
25
|
+
}
|
|
15
26
|
return (await res.json());
|
|
16
27
|
}
|
|
17
28
|
export async function publishAnchor(handle, bundle, address, deps) {
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* IndexedDB blob is useless on its own. State is inherently per-device (the ratchet mutates on every
|
|
6
6
|
* message and can't be shared without desync), so this is local-only, scoped to the handle.
|
|
7
7
|
*/
|
|
8
|
+
import type { BlobAssemblySnapshot } from "./blob";
|
|
8
9
|
/** What we persist for one handle on this device. The identity key pair is NOT here — it's re-derived
|
|
9
10
|
* from the wallet at sign-in, never stored. */
|
|
10
11
|
export interface SessionSnapshot {
|
|
@@ -12,6 +13,11 @@ export interface SessionSnapshot {
|
|
|
12
13
|
bundle: Uint8Array;
|
|
13
14
|
contacts: string[];
|
|
14
15
|
peerPA?: Record<string, string>;
|
|
16
|
+
inbox?: {
|
|
17
|
+
receipts: [string, number][];
|
|
18
|
+
peerReceipts?: [string, "delivered" | "read"][];
|
|
19
|
+
blobs?: BlobAssemblySnapshot;
|
|
20
|
+
};
|
|
15
21
|
}
|
|
16
22
|
/** One persisted (decrypted) message in a conversation's local history. Typed content: `mime` is the
|
|
17
23
|
* IANA type and `body` is the raw content base64-encoded (JSON-safe at rest); `meta` is optional. */
|
|
@@ -34,6 +40,8 @@ export interface QueuedEnvelope {
|
|
|
34
40
|
export interface SessionVault {
|
|
35
41
|
load(handle: string): Promise<SessionSnapshot | null>;
|
|
36
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>;
|
|
37
45
|
/** Outbound queue persisted while offline (survives a reload), retried on reconnect. */
|
|
38
46
|
loadQueue(handle: string): Promise<QueuedEnvelope[] | null>;
|
|
39
47
|
saveQueue(handle: string, queue: QueuedEnvelope[]): Promise<void>;
|
|
@@ -54,9 +62,10 @@ export declare class EncryptedIdbVault implements SessionVault {
|
|
|
54
62
|
/** AES-GCM seal: [random 12-byte IV][ciphertext]. A fresh IV per write makes one key safe for every blob. */
|
|
55
63
|
private seal;
|
|
56
64
|
private open;
|
|
57
|
-
private put;
|
|
58
65
|
private get;
|
|
59
66
|
save(handle: string, snap: SessionSnapshot): Promise<void>;
|
|
67
|
+
commitInbound(handle: string, snap: SessionSnapshot, histories: ReadonlyMap<string, StoredMessage[]>): Promise<void>;
|
|
68
|
+
private putRows;
|
|
60
69
|
load(handle: string): Promise<SessionSnapshot | null>;
|
|
61
70
|
saveHistory(handle: string, remote: string, messages: StoredMessage[]): Promise<void>;
|
|
62
71
|
loadHistory(handle: string, remote: string): Promise<StoredMessage[] | null>;
|
|
@@ -33,6 +33,10 @@ export function encodeSnapshot(s) {
|
|
|
33
33
|
}
|
|
34
34
|
const pa = enc.encode(JSON.stringify(s.peerPA ?? {}));
|
|
35
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
|
+
}
|
|
36
40
|
return concat(parts);
|
|
37
41
|
}
|
|
38
42
|
export function decodeSnapshot(b) {
|
|
@@ -45,6 +49,8 @@ export function decodeSnapshot(b) {
|
|
|
45
49
|
};
|
|
46
50
|
const slice = () => {
|
|
47
51
|
const n = len();
|
|
52
|
+
if (n > b.length - i)
|
|
53
|
+
throw new Error("invalid session snapshot length");
|
|
48
54
|
const s = b.subarray(i, i + n);
|
|
49
55
|
i += n;
|
|
50
56
|
return s;
|
|
@@ -57,7 +63,22 @@ export function decodeSnapshot(b) {
|
|
|
57
63
|
contacts.push(dec.decode(slice()));
|
|
58
64
|
// blobs saved before presence keys were persisted end after the contacts
|
|
59
65
|
const peerPA = i < b.length ? JSON.parse(dec.decode(slice())) : {};
|
|
60
|
-
|
|
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 };
|
|
61
82
|
}
|
|
62
83
|
/** A guaranteed ArrayBuffer-backed copy — WebCrypto's `BufferSource` rejects the generic
|
|
63
84
|
* `Uint8Array<ArrayBufferLike>` that subarray/params produce under TS 5.7. */
|
|
@@ -107,29 +128,53 @@ export class EncryptedIdbVault {
|
|
|
107
128
|
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: ab(bytes.subarray(0, 12)) }, this.key, ab(bytes.subarray(12)));
|
|
108
129
|
return new Uint8Array(plain);
|
|
109
130
|
}
|
|
110
|
-
async put(key, plain) {
|
|
111
|
-
await promisify(idb(this.db, "readwrite").put(await this.seal(plain), key));
|
|
112
|
-
}
|
|
113
131
|
async get(key) {
|
|
114
132
|
const blob = (await promisify(idb(this.db, "readonly").get(key)));
|
|
115
133
|
return blob ? this.open(blob) : null;
|
|
116
134
|
}
|
|
117
135
|
async save(handle, snap) {
|
|
118
|
-
await this.
|
|
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;
|
|
119
164
|
}
|
|
120
165
|
async load(handle) {
|
|
121
166
|
const bytes = await this.get(handle);
|
|
122
167
|
return bytes ? decodeSnapshot(bytes) : null;
|
|
123
168
|
}
|
|
124
169
|
async saveHistory(handle, remote, messages) {
|
|
125
|
-
await this.
|
|
170
|
+
await this.putRows([[`h:${handle}:${remote}`, enc.encode(JSON.stringify(messages))]]);
|
|
126
171
|
}
|
|
127
172
|
async loadHistory(handle, remote) {
|
|
128
173
|
const bytes = await this.get(`h:${handle}:${remote}`);
|
|
129
174
|
return bytes ? JSON.parse(dec.decode(bytes)) : null;
|
|
130
175
|
}
|
|
131
176
|
async saveQueue(handle, queue) {
|
|
132
|
-
await this.
|
|
177
|
+
await this.putRows([[`q:${handle}`, enc.encode(JSON.stringify(queue))]]);
|
|
133
178
|
}
|
|
134
179
|
async loadQueue(handle) {
|
|
135
180
|
const bytes = await this.get(`q:${handle}`);
|
|
@@ -20,7 +20,7 @@ export interface Transport {
|
|
|
20
20
|
/** Listen on a SET of routing labels (rotating topics: previous/current/next epoch). Calling again
|
|
21
21
|
* REPLACES the set — the caller re-subscribes on a rotation rollover. `signer` authenticates public-slot
|
|
22
22
|
* registrations (mesh only; ignored by transports without a helper). */
|
|
23
|
-
subscribe(keys: string[], onEnvelope: (e: Envelope) => void, signer?: RegistrationSigner): void;
|
|
23
|
+
subscribe(keys: string[], onEnvelope: (e: Envelope) => void, signer?: RegistrationSigner, receiveDurably?: (e: Envelope) => Promise<boolean>): void;
|
|
24
24
|
stop(): void;
|
|
25
25
|
}
|
|
26
26
|
export declare class BroadcastChannelTransport implements Transport {
|
|
@@ -43,7 +43,7 @@ export declare class MeshTransport implements Transport {
|
|
|
43
43
|
private readonly pollMs;
|
|
44
44
|
constructor(helperAddr: string, pollMs?: number);
|
|
45
45
|
send(envelope: Envelope): Promise<boolean>;
|
|
46
|
-
subscribe(keys: string[], onEnvelope: (e: Envelope) => void, signer?: RegistrationSigner): void;
|
|
46
|
+
subscribe(keys: string[], onEnvelope: (e: Envelope) => void, signer?: RegistrationSigner, receiveDurably?: (e: Envelope) => Promise<boolean>): void;
|
|
47
47
|
stop(): void;
|
|
48
48
|
/** Resolves once the node is connected and presence is registered (i.e. reachable for direct delivery). */
|
|
49
49
|
whenReady(): Promise<void>;
|
|
@@ -1,3 +1,9 @@
|
|
|
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";
|
|
1
7
|
const CHANNEL = "handlechat:mesh";
|
|
2
8
|
export class BroadcastChannelTransport {
|
|
3
9
|
channel = new BroadcastChannel(CHANNEL);
|
|
@@ -6,11 +12,12 @@ export class BroadcastChannelTransport {
|
|
|
6
12
|
#listening = false;
|
|
7
13
|
async send(envelope) {
|
|
8
14
|
// structured clone carries the Uint8Array; the channel is opaque ciphertext only.
|
|
9
|
-
|
|
15
|
+
const raw = pairwiseRoutingTopic(envelope.to);
|
|
16
|
+
this.channel.postMessage(raw ? { ...envelope, to: raw } : envelope); // no mailbox on this transport
|
|
10
17
|
return true;
|
|
11
18
|
}
|
|
12
19
|
subscribe(keys, onEnvelope) {
|
|
13
|
-
this.#keys = new Set(keys); //
|
|
20
|
+
this.#keys = new Set(keys.map(key => pairwiseRoutingTopic(key) ?? key)); // same raw wire labels as older tabs
|
|
14
21
|
this.#cb = onEnvelope;
|
|
15
22
|
if (!this.#listening) {
|
|
16
23
|
this.#listening = true;
|
|
@@ -43,9 +50,14 @@ export class MeshTransport {
|
|
|
43
50
|
helperAddr;
|
|
44
51
|
pollMs;
|
|
45
52
|
#clientP = null;
|
|
53
|
+
#stopped = false;
|
|
54
|
+
#retry = null;
|
|
55
|
+
#retryMs = 1000;
|
|
46
56
|
#keys = [];
|
|
47
57
|
#onWire = () => { };
|
|
48
58
|
#signer = () => null;
|
|
59
|
+
#receiveDurably;
|
|
60
|
+
#subscriptionGeneration = 0;
|
|
49
61
|
constructor(helperAddr, pollMs = 1500) {
|
|
50
62
|
this.helperAddr = helperAddr;
|
|
51
63
|
this.pollMs = pollMs;
|
|
@@ -59,14 +71,45 @@ export class MeshTransport {
|
|
|
59
71
|
return false; // node/helper unreachable — caller queues
|
|
60
72
|
}
|
|
61
73
|
}
|
|
62
|
-
subscribe(keys, onEnvelope, signer) {
|
|
63
|
-
|
|
74
|
+
subscribe(keys, onEnvelope, signer, receiveDurably) {
|
|
75
|
+
const generation = ++this.#subscriptionGeneration;
|
|
76
|
+
this.#keys = [...keys];
|
|
64
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;
|
|
65
84
|
if (signer)
|
|
66
85
|
this.#signer = signer;
|
|
67
|
-
|
|
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
|
+
});
|
|
68
104
|
}
|
|
69
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;
|
|
70
113
|
void this.#clientP?.then((c) => c.stop()).catch(() => { });
|
|
71
114
|
}
|
|
72
115
|
/** Resolves once the node is connected and presence is registered (i.e. reachable for direct delivery). */
|
|
@@ -74,6 +117,23 @@ export class MeshTransport {
|
|
|
74
117
|
return this.client().then(() => undefined);
|
|
75
118
|
}
|
|
76
119
|
client() {
|
|
77
|
-
|
|
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
|
+
});
|
|
78
138
|
}
|
|
79
139
|
}
|
|
@@ -21,6 +21,11 @@ export declare class SignalEngine {
|
|
|
21
21
|
* sender), so the envelope this returns carries no sender label for a relay to read.
|
|
22
22
|
*/
|
|
23
23
|
sealedSend(remote: string, plaintext: Uint8Array): Uint8Array;
|
|
24
|
+
/** Read an untrusted sender hint without changing the session; authenticate it after decryption. */
|
|
25
|
+
sealedSenderHint(ciphertext: Uint8Array): {
|
|
26
|
+
sender: string;
|
|
27
|
+
identityKey: Uint8Array;
|
|
28
|
+
};
|
|
24
29
|
/**
|
|
25
30
|
* Sealed-sender decrypt: recovers the sender handle + its certificate identity key (for the caller's
|
|
26
31
|
* on-chain anchor cross-check) and the plaintext bytes, opening the seal with our own identity key
|