@decentnetwork/beagle 0.1.132 → 0.1.142
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/dist/call-claims.d.ts +73 -0
- package/dist/call-claims.js +270 -0
- package/dist/carrier-node.d.ts +21 -0
- package/dist/carrier-node.js +17 -1
- package/dist/desktop/app.js +387 -46
- package/dist/desktop/vendor/peer-webrtc.js +176 -65
- package/dist/embedded-host.d.ts +13 -0
- package/dist/embedded-host.js +347 -45
- package/dist/file-route.d.ts +43 -0
- package/dist/file-route.js +55 -0
- package/dist/group-file.d.ts +18 -0
- package/dist/group-file.js +20 -0
- package/dist/message-store.d.ts +16 -2
- package/dist/message-store.js +42 -3
- package/dist/server.js +55 -10
- package/package.json +5 -4
- package/dist/chat-components.d.ts +0 -67
- package/dist/chat-components.js +0 -208
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Where an outgoing file goes: live, Express, or this computer's outbox.
|
|
2
|
+
//
|
|
3
|
+
// decent-hq TASK-2026-11-13-desktop-multifile-and-offline-files, part C.2,
|
|
4
|
+
// following iOS (1.8.37+, Elastos.NET.WebRTC.Swift.SDK docs/OFFLINE-FILE-MESSAGE.md,
|
|
5
|
+
// "Sender rules"):
|
|
6
|
+
//
|
|
7
|
+
// friend offline, fits Express → ONE offline file message on Express
|
|
8
|
+
// (peer >= 0.1.176 sendFileViaExpress); the
|
|
9
|
+
// row reads "offline" — stored, not yet theirs.
|
|
10
|
+
// friend offline, too big → the local outbox (25 MB cap, as before); the
|
|
11
|
+
// row says it waits on this computer until the
|
|
12
|
+
// friend is online. Over 25 MB: refused.
|
|
13
|
+
// friend online → live transfer. When it fits Express and the
|
|
14
|
+
// friend has not accepted within OFFER_WINDOW_MS
|
|
15
|
+
// (iOS `offerWindow`), the offer is withdrawn
|
|
16
|
+
// and the file goes to Express instead.
|
|
17
|
+
//
|
|
18
|
+
// "Fits Express" is the whole message: [u32 metaLen][meta JSON][bytes] ≤
|
|
19
|
+
// 5 242 880 bytes (Carrier's legacy bulk-message cap), meta ≤ 4096.
|
|
20
|
+
import { OFFLINE_FILE_MAX_MESSAGE_BYTES, OFFLINE_FILE_MAX_META_BYTES, contentTypeForFileName } from "@decentnetwork/peer";
|
|
21
|
+
/** Files bigger than this are not queued for an offline friend — the bytes sit
|
|
22
|
+
* on disk until they reconnect, and an unbounded queue is how you fill a
|
|
23
|
+
* user's disk by accident. Live transfers have no such limit. */
|
|
24
|
+
export const OUTBOX_MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
25
|
+
/** iOS `offerWindow`: how long a live offer may go unaccepted before a file
|
|
26
|
+
* that fits Express is withdrawn and parked there instead. */
|
|
27
|
+
export const OFFER_WINDOW_MS = 10_000;
|
|
28
|
+
/** The exact size of the offline file message sendFileViaExpress would post
|
|
29
|
+
* for this name and size (the meta JSON is built the same way). */
|
|
30
|
+
export function expressMessageBytes(name, size) {
|
|
31
|
+
const meta = Buffer.byteLength(JSON.stringify({ type: "file", filename: name, contentType: contentTypeForFileName(name), size }), "utf-8");
|
|
32
|
+
return { total: 4 + meta + size, meta };
|
|
33
|
+
}
|
|
34
|
+
/** True when one offline file message on Express can carry this file. */
|
|
35
|
+
export function fitsExpress(name, size) {
|
|
36
|
+
const { total, meta } = expressMessageBytes(name, size);
|
|
37
|
+
return total <= OFFLINE_FILE_MAX_MESSAGE_BYTES && meta <= OFFLINE_FILE_MAX_META_BYTES;
|
|
38
|
+
}
|
|
39
|
+
/** The routing table above. `expressAvailable` is false on a peer SDK without
|
|
40
|
+
* sendFileViaExpress or with no Express node: then an offline file of any
|
|
41
|
+
* size waits in the outbox, as it did before. */
|
|
42
|
+
export function routeFileSend(opts) {
|
|
43
|
+
const fits = opts.expressAvailable && fitsExpress(opts.name, opts.size);
|
|
44
|
+
if (opts.online)
|
|
45
|
+
return { kind: "live", offerWindow: fits };
|
|
46
|
+
if (fits)
|
|
47
|
+
return { kind: "express" };
|
|
48
|
+
if (opts.size <= OUTBOX_MAX_FILE_BYTES)
|
|
49
|
+
return { kind: "outbox" };
|
|
50
|
+
return {
|
|
51
|
+
kind: "refuse",
|
|
52
|
+
reason: `Peer is offline — queued files are limited to ${(OUTBOX_MAX_FILE_BYTES / 1024 / 1024) | 0} MB ` +
|
|
53
|
+
`(this is ${(opts.size / 1024 / 1024).toFixed(1)} MB). Send it once they're online.`,
|
|
54
|
+
};
|
|
55
|
+
}
|
package/dist/group-file.d.ts
CHANGED
|
@@ -44,3 +44,21 @@ export declare function withoutFileData(text: string): string;
|
|
|
44
44
|
* name, same post time)? Used to replace the "not delivered" card when the
|
|
45
45
|
* bytes arrive later for the same message. */
|
|
46
46
|
export declare function sameGroupFile(storedText: string, f: GroupFile): boolean;
|
|
47
|
+
/** Stored messages that still hold a group file's bytes as CGP1 text: those a
|
|
48
|
+
* daemon older than 0.1.315 received after the group service began sending
|
|
49
|
+
* data_base64 (2026-11-05 17:53 PST). They show as "not delivered" although
|
|
50
|
+
* the bytes are in messages.json. Each one is to be saved as a file in place,
|
|
51
|
+
* or dropped when the thread already holds the same bytes (`duplicate`).
|
|
52
|
+
* Pure: the caller does the writing. */
|
|
53
|
+
export declare function storedGroupFiles(thread: readonly {
|
|
54
|
+
id: string;
|
|
55
|
+
dir: string;
|
|
56
|
+
text: string;
|
|
57
|
+
file?: {
|
|
58
|
+
sha256?: string;
|
|
59
|
+
};
|
|
60
|
+
}[]): Array<{
|
|
61
|
+
id: string;
|
|
62
|
+
file: GroupFile;
|
|
63
|
+
duplicate: boolean;
|
|
64
|
+
}>;
|
package/dist/group-file.js
CHANGED
|
@@ -90,3 +90,23 @@ export function sameGroupFile(storedText, f) {
|
|
|
90
90
|
return d.timestampUs === f.timestampUs;
|
|
91
91
|
return d.size === f.size;
|
|
92
92
|
}
|
|
93
|
+
/** Stored messages that still hold a group file's bytes as CGP1 text: those a
|
|
94
|
+
* daemon older than 0.1.315 received after the group service began sending
|
|
95
|
+
* data_base64 (2026-11-05 17:53 PST). They show as "not delivered" although
|
|
96
|
+
* the bytes are in messages.json. Each one is to be saved as a file in place,
|
|
97
|
+
* or dropped when the thread already holds the same bytes (`duplicate`).
|
|
98
|
+
* Pure: the caller does the writing. */
|
|
99
|
+
export function storedGroupFiles(thread) {
|
|
100
|
+
const have = new Set(thread.map((m) => m.file?.sha256).filter((s) => !!s));
|
|
101
|
+
const out = [];
|
|
102
|
+
for (const m of thread) {
|
|
103
|
+
if (m.dir !== "in" || m.file || !m.text || !m.text.includes("data_base64"))
|
|
104
|
+
continue;
|
|
105
|
+
const f = parseGroupFile(m.text);
|
|
106
|
+
if (!f?.data || !f.sha256)
|
|
107
|
+
continue;
|
|
108
|
+
out.push({ id: m.id, file: f, duplicate: have.has(f.sha256) });
|
|
109
|
+
have.add(f.sha256);
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
package/dist/message-store.d.ts
CHANGED
|
@@ -80,6 +80,9 @@ export declare class MessageStore {
|
|
|
80
80
|
/** Record how an outgoing text travelled: "online" over a live session,
|
|
81
81
|
* "offline" posted to the express relay for the peer to collect. */
|
|
82
82
|
setVia(peer: string, id: string, via: "online" | "offline"): boolean;
|
|
83
|
+
/** The same for a FILE row: "offline" = parked on Express, "online" = a
|
|
84
|
+
* live transfer, undefined = not on the wire yet (waiting in the outbox). */
|
|
85
|
+
setFileVia(peer: string, id: string, via: "online" | "offline" | undefined): boolean;
|
|
83
86
|
/** Has this peer ever sent us anything? Used as proof-of-friendship for
|
|
84
87
|
* records that predate the SDK's acceptedAt bookkeeping — a message can
|
|
85
88
|
* only arrive over an established session. */
|
|
@@ -102,8 +105,19 @@ export declare class MessageStore {
|
|
|
102
105
|
origin?: ChatMessage["origin"];
|
|
103
106
|
via?: "online" | "offline";
|
|
104
107
|
}): ChatMessage;
|
|
105
|
-
/**
|
|
106
|
-
|
|
108
|
+
/** Turn an existing message into a file message in place (same id, same
|
|
109
|
+
* position): a stored group file's CGP1 text becomes the playable file. */
|
|
110
|
+
convertToFile(peer: string, id: string, file: {
|
|
111
|
+
name: string;
|
|
112
|
+
size: number;
|
|
113
|
+
sha256?: string;
|
|
114
|
+
}, origin?: ChatMessage["origin"]): ChatMessage | undefined;
|
|
115
|
+
/** Every message in a peer's thread (oldest first). Read-only use. */
|
|
116
|
+
thread(peer: string): readonly ChatMessage[];
|
|
117
|
+
/** True when this peer's thread already holds a file with these bytes —
|
|
118
|
+
* in `dir` only, when given (a received file must not be dropped because
|
|
119
|
+
* we once SENT the same bytes). */
|
|
120
|
+
hasFileSha(peer: string, sha256: string, dir?: "in" | "out"): boolean;
|
|
107
121
|
/** Patch an existing file message's transfer fields (status / sent bytes).
|
|
108
122
|
* No-op if the id isn't found. Returns true if it patched. */
|
|
109
123
|
patchFile(peer: string, id: string, patch: {
|
package/dist/message-store.js
CHANGED
|
@@ -38,6 +38,12 @@ export class MessageStore {
|
|
|
38
38
|
for (const m of msgs)
|
|
39
39
|
if (m.status === "sending")
|
|
40
40
|
m.status = "queued";
|
|
41
|
+
// Same for an outgoing file: its transfer died with the process, and
|
|
42
|
+
// its bytes are still in outbox/<id>. Left "sending" it was stuck
|
|
43
|
+
// forever — nothing ever offers a "sending" row again.
|
|
44
|
+
for (const m of msgs)
|
|
45
|
+
if (m.dir === "out" && m.file?.status === "sending")
|
|
46
|
+
m.file.status = "queued";
|
|
41
47
|
this.byPeer.set(peer, msgs);
|
|
42
48
|
total += msgs.length;
|
|
43
49
|
}
|
|
@@ -96,6 +102,19 @@ export class MessageStore {
|
|
|
96
102
|
this.scheduleSave();
|
|
97
103
|
return true;
|
|
98
104
|
}
|
|
105
|
+
/** The same for a FILE row: "offline" = parked on Express, "online" = a
|
|
106
|
+
* live transfer, undefined = not on the wire yet (waiting in the outbox). */
|
|
107
|
+
setFileVia(peer, id, via) {
|
|
108
|
+
const msg = this.byPeer.get(peer)?.find((m) => m.id === id);
|
|
109
|
+
if (!msg || !msg.file)
|
|
110
|
+
return false;
|
|
111
|
+
if (via)
|
|
112
|
+
msg.via = via;
|
|
113
|
+
else
|
|
114
|
+
delete msg.via;
|
|
115
|
+
this.scheduleSave();
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
99
118
|
/** Has this peer ever sent us anything? Used as proof-of-friendship for
|
|
100
119
|
* records that predate the SDK's acceptedAt bookkeeping — a message can
|
|
101
120
|
* only arrive over an established session. */
|
|
@@ -128,9 +147,29 @@ export class MessageStore {
|
|
|
128
147
|
msg.via = extra.via;
|
|
129
148
|
return this.push(peer, msg);
|
|
130
149
|
}
|
|
131
|
-
/**
|
|
132
|
-
|
|
133
|
-
|
|
150
|
+
/** Turn an existing message into a file message in place (same id, same
|
|
151
|
+
* position): a stored group file's CGP1 text becomes the playable file. */
|
|
152
|
+
convertToFile(peer, id, file, origin) {
|
|
153
|
+
const msg = this.byPeer.get(peer)?.find((m) => m.id === id);
|
|
154
|
+
if (!msg)
|
|
155
|
+
return undefined;
|
|
156
|
+
msg.text = "";
|
|
157
|
+
msg.file = file;
|
|
158
|
+
if (origin)
|
|
159
|
+
msg.origin = origin;
|
|
160
|
+
this.scheduleSave();
|
|
161
|
+
return msg;
|
|
162
|
+
}
|
|
163
|
+
/** Every message in a peer's thread (oldest first). Read-only use. */
|
|
164
|
+
thread(peer) {
|
|
165
|
+
return this.byPeer.get(peer) ?? [];
|
|
166
|
+
}
|
|
167
|
+
/** True when this peer's thread already holds a file with these bytes —
|
|
168
|
+
* in `dir` only, when given (a received file must not be dropped because
|
|
169
|
+
* we once SENT the same bytes). */
|
|
170
|
+
hasFileSha(peer, sha256, dir) {
|
|
171
|
+
const want = sha256.toLowerCase();
|
|
172
|
+
return (this.history(peer)[peer] ?? []).some((m) => m.file?.sha256?.toLowerCase() === want && (!dir || m.dir === dir));
|
|
134
173
|
}
|
|
135
174
|
/** Patch an existing file message's transfer fields (status / sent bytes).
|
|
136
175
|
* No-op if the id isn't found. Returns true if it patched. */
|
package/dist/server.js
CHANGED
|
@@ -28,6 +28,7 @@ import { historyStats } from "./assistant-stats.js";
|
|
|
28
28
|
import { readFriendStore, pickPunk } from "./friend-store.js";
|
|
29
29
|
import { desktopRequestRow, findPending } from "./pending-requests.js";
|
|
30
30
|
import { GreetingStore, mergeGreetings } from "./friend-greetings.js";
|
|
31
|
+
import { CallRegistry, pageOf } from "./call-claims.js";
|
|
31
32
|
import { createDiscoverFetch } from "./discover-cache.js";
|
|
32
33
|
import { applyWalletBind } from "@decentnetwork/beagle-ui/wallet-proof";
|
|
33
34
|
import { settleUpload } from "./upload-settle.js";
|
|
@@ -969,6 +970,9 @@ export function startBeagleServer(opts) {
|
|
|
969
970
|
const port = opts.listenPort ?? 8765;
|
|
970
971
|
const log = opts.log ?? ((s) => console.log(s));
|
|
971
972
|
const greetings = opts.greetingsPath ? new GreetingStore(opts.greetingsPath) : null;
|
|
973
|
+
// Who has each recent incoming call — see call-claims.ts. Every page polls
|
|
974
|
+
// through here, so this is where "answered elsewhere" is decided.
|
|
975
|
+
const calls = new CallRegistry();
|
|
972
976
|
// Exit reachability with memory (see exit-probe.ts). One per server, state
|
|
973
977
|
// kept next to routes.yaml so a restart does not re-probe dead exits.
|
|
974
978
|
const exitProber = new ExitProber({
|
|
@@ -2600,11 +2604,31 @@ export function startBeagleServer(opts) {
|
|
|
2600
2604
|
// RtcSignals here and long-polls call-poll for inbound ones; the daemon
|
|
2601
2605
|
// relays both over the Carrier "carrier" invite extension.
|
|
2602
2606
|
if (req.method === "POST" && url === "/api/call-signal") {
|
|
2603
|
-
const { userid, data } = await readBody(req);
|
|
2607
|
+
const { userid, data, page } = await readBody(req);
|
|
2608
|
+
// First claim wins: another page's answer / accept / decline for a
|
|
2609
|
+
// call already claimed never reaches the caller.
|
|
2610
|
+
const gate = calls.observeOutbound(pageOf(page), userid, data);
|
|
2611
|
+
if (!gate.allow) {
|
|
2612
|
+
sendJson(res, 409, { ok: false, error: "answered elsewhere", answeredElsewhere: true, call: gate.record });
|
|
2613
|
+
return;
|
|
2614
|
+
}
|
|
2604
2615
|
const r = await opts.call({ op: "call-signal", userid, data });
|
|
2605
2616
|
sendJson(res, r.ok ? 200 : 400, r);
|
|
2606
2617
|
return;
|
|
2607
2618
|
}
|
|
2619
|
+
// A page answers or declines an incoming call: claim it before sending
|
|
2620
|
+
// anything to the caller. `won: false` = another page or client has it;
|
|
2621
|
+
// stop ringing and send nothing.
|
|
2622
|
+
if (req.method === "POST" && url === "/api/call-claim") {
|
|
2623
|
+
const { callId, peerId, action, page } = await readBody(req);
|
|
2624
|
+
if (typeof callId !== "string" || !callId) {
|
|
2625
|
+
sendJson(res, 400, { ok: false, error: "callId required" });
|
|
2626
|
+
return;
|
|
2627
|
+
}
|
|
2628
|
+
const r = calls.claim(callId, String(peerId ?? ""), pageOf(page), action === "rejected" ? "rejected" : "accepted");
|
|
2629
|
+
sendJson(res, 200, { ok: true, won: r.won, call: r.record, callsVersion: calls.version });
|
|
2630
|
+
return;
|
|
2631
|
+
}
|
|
2608
2632
|
// Carrier bootstrap TURN for browser RTCPeerConnection — same scheme as
|
|
2609
2633
|
// Android WebrtcClient.getIceServers() / carrier_get_turn_server().
|
|
2610
2634
|
if (req.method === "GET" && url === "/api/call-ice-servers") {
|
|
@@ -2630,18 +2654,39 @@ export function startBeagleServer(opts) {
|
|
|
2630
2654
|
// `since` is the caller's broadcast cursor: signal delivery is
|
|
2631
2655
|
// per-subscriber, so two open tabs BOTH ring on an incoming call.
|
|
2632
2656
|
// Without it (older UI) the backend serves only future signals.
|
|
2633
|
-
const
|
|
2657
|
+
const qs = new URL(req.url || "/", "http://x").searchParams;
|
|
2658
|
+
const sinceRaw = qs.get("since");
|
|
2634
2659
|
const since = sinceRaw !== null && sinceRaw !== "" ? Number(sinceRaw) : undefined;
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2660
|
+
// `cv`: the calls-table version this page holds (call-claims.ts). A
|
|
2661
|
+
// claim or an end must reach every page within about a second, but
|
|
2662
|
+
// the backend may hold this poll ~20 s, so a change to the table
|
|
2663
|
+
// answers the poll at once — with the page's own cursor, so the
|
|
2664
|
+
// signals the backend is still holding are read on the next poll
|
|
2665
|
+
// (the log is broadcast; reading never consumes).
|
|
2666
|
+
const cvRaw = qs.get("cv");
|
|
2667
|
+
const cv = cvRaw !== null && cvRaw !== "" ? Number(cvRaw) : undefined;
|
|
2668
|
+
const backendP = opts
|
|
2669
|
+
.call({ op: "call-poll", ...(Number.isFinite(since) ? { since } : {}) })
|
|
2670
|
+
.catch(() => null);
|
|
2671
|
+
let r;
|
|
2672
|
+
if (Number.isFinite(since) && Number.isFinite(cv)) {
|
|
2673
|
+
const w = calls.wait(cv, 25_000);
|
|
2674
|
+
const CHANGED = Symbol("calls changed");
|
|
2675
|
+
const onChange = w.promise.then((changed) => changed ? CHANGED : backendP);
|
|
2676
|
+
const first = await Promise.race([backendP, onChange]);
|
|
2677
|
+
w.cancel();
|
|
2678
|
+
r = first === CHANGED ? null : first;
|
|
2641
2679
|
}
|
|
2642
|
-
|
|
2643
|
-
|
|
2680
|
+
else {
|
|
2681
|
+
r = await backendP;
|
|
2644
2682
|
}
|
|
2683
|
+
const data = r === null ? { signals: [], cursor: since } : r.ok ? { signals: [], ...(r.data ?? {}) } : { signals: [] };
|
|
2684
|
+
for (const sig of data.signals ?? []) {
|
|
2685
|
+
calls.observeInbound(String(sig.userid ?? ""), sig.data);
|
|
2686
|
+
}
|
|
2687
|
+
data.calls = calls.snapshot();
|
|
2688
|
+
data.callsVersion = calls.version;
|
|
2689
|
+
sendJson(res, 200, data);
|
|
2645
2690
|
return;
|
|
2646
2691
|
}
|
|
2647
2692
|
if (req.method === "POST" && url === "/api/friend-remove") {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decentnetwork/beagle",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.142",
|
|
4
4
|
"description": "Beagle — P2P chat, file transfer and calls for regular users, on the Decent Network. No admin privilege required.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -26,11 +26,11 @@
|
|
|
26
26
|
"start": "node dist/cli.js"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@decentnetwork/beagle-ui": "^0.2.
|
|
29
|
+
"@decentnetwork/beagle-ui": "^0.2.44",
|
|
30
30
|
"@decentnetwork/chat-components": "^0.1.3",
|
|
31
31
|
"@decentnetwork/lan": "^0.1.316",
|
|
32
|
-
"@decentnetwork/peer": "^0.1.
|
|
33
|
-
"@decentnetwork/peer-webrtc": "^0.2.
|
|
32
|
+
"@decentnetwork/peer": "^0.1.178",
|
|
33
|
+
"@decentnetwork/peer-webrtc": "^0.2.21",
|
|
34
34
|
"js-yaml": "^4.1.0",
|
|
35
35
|
"ws": "^8.21.1",
|
|
36
36
|
"yargs": "^17.7.2"
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@types/js-yaml": "^4.0.9",
|
|
40
40
|
"@types/node": "^20.11.0",
|
|
41
|
+
"@types/ws": "^8.18.2",
|
|
41
42
|
"@types/yargs": "^17.0.32",
|
|
42
43
|
"esbuild": "^0.20.0",
|
|
43
44
|
"typescript": "^5.3.0"
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
/** Custom packet id for the components channel.
|
|
2
|
-
*
|
|
3
|
-
* 160-191 is toxcore's LOSSLESS range — a form must not be silently dropped.
|
|
4
|
-
* decentlan owns 161 (session), 162 (dora), 163 (IP), 164 (rate); 165 is the
|
|
5
|
-
* first free slot. Clients that don't implement this id never see the packet,
|
|
6
|
-
* which is exactly the backward-compatibility story we want. */
|
|
7
|
-
export declare const PACKET_ID_CHAT_COMPONENTS = 165;
|
|
8
|
-
/** Payload version. Receivers ignore payloads they don't know how to read
|
|
9
|
-
* rather than best-effort parsing a future shape. */
|
|
10
|
-
export declare const COMPONENTS_WIRE_VERSION = 1;
|
|
11
|
-
export declare const MAX_COMPONENTS = 12;
|
|
12
|
-
export declare const MAX_OPTIONS = 40;
|
|
13
|
-
export declare const MAX_LABEL_LEN = 120;
|
|
14
|
-
export declare const MAX_ID_LEN = 64;
|
|
15
|
-
export declare const MAX_VALUE_LEN = 512;
|
|
16
|
-
export declare const MAX_CUSTOM_ID_LEN = 128;
|
|
17
|
-
/** Hard ceiling on a decoded payload before we even try to parse it. */
|
|
18
|
-
export declare const MAX_PAYLOAD_BYTES: number;
|
|
19
|
-
export type ComponentType = "select" | "submit" | "text" | "button" | "attachment";
|
|
20
|
-
export interface SelectOption {
|
|
21
|
-
label: string;
|
|
22
|
-
value: string;
|
|
23
|
-
}
|
|
24
|
-
export interface ChatComponent {
|
|
25
|
-
type: ComponentType;
|
|
26
|
-
id: string;
|
|
27
|
-
label?: string;
|
|
28
|
-
required?: boolean;
|
|
29
|
-
default?: string;
|
|
30
|
-
placeholder?: string;
|
|
31
|
-
options?: SelectOption[];
|
|
32
|
-
}
|
|
33
|
-
export interface ComponentsMessage {
|
|
34
|
-
v: number;
|
|
35
|
-
type: "components";
|
|
36
|
-
/** Chosen by the agent; echoed back so it can route the reply. */
|
|
37
|
-
custom_id: string;
|
|
38
|
-
components: ChatComponent[];
|
|
39
|
-
}
|
|
40
|
-
export interface InteractionMessage {
|
|
41
|
-
v: number;
|
|
42
|
-
type: "interaction";
|
|
43
|
-
custom_id: string;
|
|
44
|
-
/** id of the submit/button that fired. */
|
|
45
|
-
component: string;
|
|
46
|
-
values: Record<string, string | {
|
|
47
|
-
fileId: string;
|
|
48
|
-
name: string;
|
|
49
|
-
size: number;
|
|
50
|
-
}>;
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Validate a remote components payload. Returns null when nothing renderable
|
|
54
|
-
* survives — the caller then shows only the text message, which is the correct
|
|
55
|
-
* degraded state, never an error.
|
|
56
|
-
*/
|
|
57
|
-
export declare function parseComponentsMessage(raw: unknown): ComponentsMessage | null;
|
|
58
|
-
/** Build the interaction reply. Values are the user's own input, but they are
|
|
59
|
-
* bounded here too so a pathological local state can't emit an oversized
|
|
60
|
-
* packet at the peer. */
|
|
61
|
-
export declare function buildInteraction(customId: string, component: string, values: Record<string, string>): InteractionMessage;
|
|
62
|
-
/** Decode a received packet. Returns null for anything malformed or oversized —
|
|
63
|
-
* a peer must not be able to make us throw on the receive path. */
|
|
64
|
-
export declare function decodePacket(data: Uint8Array): ComponentsMessage | InteractionMessage | null;
|
|
65
|
-
/** Validate an inbound interaction (the agent side of the channel). */
|
|
66
|
-
export declare function parseInteractionMessage(raw: unknown): InteractionMessage | null;
|
|
67
|
-
export declare function encodePacket(msg: ComponentsMessage | InteractionMessage): Uint8Array;
|
package/dist/chat-components.js
DELETED
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
// Brief 30 — interactive components in chat.
|
|
2
|
-
//
|
|
3
|
-
// An agent declares a form as DATA; this client renders it with its own trusted
|
|
4
|
-
// widgets. No HTML crosses the wire, no URL is fetched, no script runs. The UI's
|
|
5
|
-
// escape-everything policy (dkHtmlEscape) is untouched — components are a
|
|
6
|
-
// separate, whitelisted channel, not an escape hatch from it.
|
|
7
|
-
//
|
|
8
|
-
// Wire shape: a sibling packet, not a field on the chat message. Answering the
|
|
9
|
-
// brief's first open question that way makes "old clients still see the
|
|
10
|
-
// message" a property of the protocol rather than a rule senders must remember:
|
|
11
|
-
// the human-readable text goes out as an ordinary chat message that every
|
|
12
|
-
// existing client already renders, and the component payload rides a custom
|
|
13
|
-
// packet id that any client not built for it never even receives.
|
|
14
|
-
//
|
|
15
|
-
// EVERY value here arrives from a remote peer. The validator is the trust
|
|
16
|
-
// boundary: it whitelists types, caps every count and length, and drops what it
|
|
17
|
-
// does not understand instead of guessing.
|
|
18
|
-
/** Custom packet id for the components channel.
|
|
19
|
-
*
|
|
20
|
-
* 160-191 is toxcore's LOSSLESS range — a form must not be silently dropped.
|
|
21
|
-
* decentlan owns 161 (session), 162 (dora), 163 (IP), 164 (rate); 165 is the
|
|
22
|
-
* first free slot. Clients that don't implement this id never see the packet,
|
|
23
|
-
* which is exactly the backward-compatibility story we want. */
|
|
24
|
-
export const PACKET_ID_CHAT_COMPONENTS = 165;
|
|
25
|
-
/** Payload version. Receivers ignore payloads they don't know how to read
|
|
26
|
-
* rather than best-effort parsing a future shape. */
|
|
27
|
-
export const COMPONENTS_WIRE_VERSION = 1;
|
|
28
|
-
// --- caps -------------------------------------------------------------------
|
|
29
|
-
// "The client caps sizes/counts itself — a peer must not be able to freeze
|
|
30
|
-
// another peer's UI." (Brief 30, Security). These are deliberately small: a
|
|
31
|
-
// legitimate form is a handful of fields, and anything larger is either a bug
|
|
32
|
-
// or an attempt to hang the renderer.
|
|
33
|
-
export const MAX_COMPONENTS = 12;
|
|
34
|
-
export const MAX_OPTIONS = 40;
|
|
35
|
-
export const MAX_LABEL_LEN = 120;
|
|
36
|
-
export const MAX_ID_LEN = 64;
|
|
37
|
-
export const MAX_VALUE_LEN = 512;
|
|
38
|
-
export const MAX_CUSTOM_ID_LEN = 128;
|
|
39
|
-
/** Hard ceiling on a decoded payload before we even try to parse it. */
|
|
40
|
-
export const MAX_PAYLOAD_BYTES = 64 * 1024;
|
|
41
|
-
/** Types this build actually renders. Anything else is dropped — forward
|
|
42
|
-
* compatibility per the brief: an older client must ignore, not break. */
|
|
43
|
-
const RENDERABLE = new Set(["select", "submit", "text"]);
|
|
44
|
-
const str = (v, max) => {
|
|
45
|
-
if (typeof v !== "string")
|
|
46
|
-
return undefined;
|
|
47
|
-
const s = v.trim();
|
|
48
|
-
if (!s || s.length > max)
|
|
49
|
-
return undefined;
|
|
50
|
-
return s;
|
|
51
|
-
};
|
|
52
|
-
/**
|
|
53
|
-
* Validate a remote components payload. Returns null when nothing renderable
|
|
54
|
-
* survives — the caller then shows only the text message, which is the correct
|
|
55
|
-
* degraded state, never an error.
|
|
56
|
-
*/
|
|
57
|
-
export function parseComponentsMessage(raw) {
|
|
58
|
-
if (!raw || typeof raw !== "object")
|
|
59
|
-
return null;
|
|
60
|
-
const o = raw;
|
|
61
|
-
if (o.type !== "components")
|
|
62
|
-
return null;
|
|
63
|
-
if (o.v !== COMPONENTS_WIRE_VERSION)
|
|
64
|
-
return null;
|
|
65
|
-
const customId = str(o.custom_id, MAX_CUSTOM_ID_LEN);
|
|
66
|
-
if (!customId)
|
|
67
|
-
return null;
|
|
68
|
-
if (!Array.isArray(o.components))
|
|
69
|
-
return null;
|
|
70
|
-
const seen = new Set();
|
|
71
|
-
const out = [];
|
|
72
|
-
for (const entry of o.components.slice(0, MAX_COMPONENTS)) {
|
|
73
|
-
if (!entry || typeof entry !== "object")
|
|
74
|
-
continue;
|
|
75
|
-
const c = entry;
|
|
76
|
-
const type = typeof c.type === "string" ? c.type : "";
|
|
77
|
-
if (!RENDERABLE.has(type))
|
|
78
|
-
continue; // unknown/unsupported: drop, don't guess
|
|
79
|
-
const id = str(c.id, MAX_ID_LEN);
|
|
80
|
-
if (!id || seen.has(id))
|
|
81
|
-
continue; // duplicate ids would alias each other's values
|
|
82
|
-
seen.add(id);
|
|
83
|
-
const component = { type: type, id };
|
|
84
|
-
const label = str(c.label, MAX_LABEL_LEN);
|
|
85
|
-
if (label)
|
|
86
|
-
component.label = label;
|
|
87
|
-
if (c.required === true)
|
|
88
|
-
component.required = true;
|
|
89
|
-
const placeholder = str(c.placeholder, MAX_LABEL_LEN);
|
|
90
|
-
if (placeholder)
|
|
91
|
-
component.placeholder = placeholder;
|
|
92
|
-
if (type === "select") {
|
|
93
|
-
if (!Array.isArray(c.options))
|
|
94
|
-
continue; // a select with no options is unusable
|
|
95
|
-
const options = [];
|
|
96
|
-
const seenValues = new Set();
|
|
97
|
-
for (const raw of c.options.slice(0, MAX_OPTIONS)) {
|
|
98
|
-
if (!raw || typeof raw !== "object")
|
|
99
|
-
continue;
|
|
100
|
-
const opt = raw;
|
|
101
|
-
const value = str(opt.value, MAX_VALUE_LEN);
|
|
102
|
-
if (!value || seenValues.has(value))
|
|
103
|
-
continue;
|
|
104
|
-
seenValues.add(value);
|
|
105
|
-
options.push({ label: str(opt.label, MAX_LABEL_LEN) ?? value, value });
|
|
106
|
-
}
|
|
107
|
-
if (!options.length)
|
|
108
|
-
continue;
|
|
109
|
-
component.options = options;
|
|
110
|
-
// A default that isn't one of the options would submit a value the agent
|
|
111
|
-
// never offered; ignore it rather than pass it through.
|
|
112
|
-
const def = str(c.default, MAX_VALUE_LEN);
|
|
113
|
-
if (def && options.some((o2) => o2.value === def))
|
|
114
|
-
component.default = def;
|
|
115
|
-
}
|
|
116
|
-
if (type === "text") {
|
|
117
|
-
const def = str(c.default, MAX_VALUE_LEN);
|
|
118
|
-
if (def)
|
|
119
|
-
component.default = def;
|
|
120
|
-
}
|
|
121
|
-
out.push(component);
|
|
122
|
-
}
|
|
123
|
-
// A form with no way to submit can never be completed — treat it as noise.
|
|
124
|
-
if (!out.some((c) => c.type === "submit"))
|
|
125
|
-
return null;
|
|
126
|
-
// ...and a submit button with nothing to fill in is equally pointless.
|
|
127
|
-
if (!out.some((c) => c.type === "select" || c.type === "text"))
|
|
128
|
-
return null;
|
|
129
|
-
return { v: COMPONENTS_WIRE_VERSION, type: "components", custom_id: customId, components: out };
|
|
130
|
-
}
|
|
131
|
-
/** Build the interaction reply. Values are the user's own input, but they are
|
|
132
|
-
* bounded here too so a pathological local state can't emit an oversized
|
|
133
|
-
* packet at the peer. */
|
|
134
|
-
export function buildInteraction(customId, component, values) {
|
|
135
|
-
const clean = {};
|
|
136
|
-
for (const [k, v] of Object.entries(values)) {
|
|
137
|
-
const key = str(k, MAX_ID_LEN);
|
|
138
|
-
if (!key)
|
|
139
|
-
continue;
|
|
140
|
-
clean[key] = typeof v === "string" ? v.slice(0, MAX_VALUE_LEN) : "";
|
|
141
|
-
}
|
|
142
|
-
return {
|
|
143
|
-
v: COMPONENTS_WIRE_VERSION,
|
|
144
|
-
type: "interaction",
|
|
145
|
-
custom_id: customId.slice(0, MAX_CUSTOM_ID_LEN),
|
|
146
|
-
component: component.slice(0, MAX_ID_LEN),
|
|
147
|
-
values: clean,
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
/** Decode a received packet. Returns null for anything malformed or oversized —
|
|
151
|
-
* a peer must not be able to make us throw on the receive path. */
|
|
152
|
-
export function decodePacket(data) {
|
|
153
|
-
if (!data?.length || data.length > MAX_PAYLOAD_BYTES)
|
|
154
|
-
return null;
|
|
155
|
-
let parsed;
|
|
156
|
-
try {
|
|
157
|
-
parsed = JSON.parse(Buffer.from(data).toString("utf-8"));
|
|
158
|
-
}
|
|
159
|
-
catch {
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
const o = parsed;
|
|
163
|
-
if (!o || typeof o !== "object")
|
|
164
|
-
return null;
|
|
165
|
-
if (o.type === "components")
|
|
166
|
-
return parseComponentsMessage(o);
|
|
167
|
-
if (o.type === "interaction")
|
|
168
|
-
return parseInteractionMessage(o);
|
|
169
|
-
return null;
|
|
170
|
-
}
|
|
171
|
-
/** Validate an inbound interaction (the agent side of the channel). */
|
|
172
|
-
export function parseInteractionMessage(raw) {
|
|
173
|
-
if (!raw || typeof raw !== "object")
|
|
174
|
-
return null;
|
|
175
|
-
const o = raw;
|
|
176
|
-
if (o.type !== "interaction" || o.v !== COMPONENTS_WIRE_VERSION)
|
|
177
|
-
return null;
|
|
178
|
-
const customId = str(o.custom_id, MAX_CUSTOM_ID_LEN);
|
|
179
|
-
const component = str(o.component, MAX_ID_LEN);
|
|
180
|
-
if (!customId || !component)
|
|
181
|
-
return null;
|
|
182
|
-
const values = {};
|
|
183
|
-
if (o.values && typeof o.values === "object") {
|
|
184
|
-
for (const [k, v] of Object.entries(o.values).slice(0, MAX_COMPONENTS)) {
|
|
185
|
-
const key = str(k, MAX_ID_LEN);
|
|
186
|
-
if (!key)
|
|
187
|
-
continue;
|
|
188
|
-
if (typeof v === "string") {
|
|
189
|
-
values[key] = v.slice(0, MAX_VALUE_LEN);
|
|
190
|
-
continue;
|
|
191
|
-
}
|
|
192
|
-
// File values are {fileId, name, size} — fileId is the content sha256,
|
|
193
|
-
// which is what makes the reference exact (Brief 30 §3).
|
|
194
|
-
if (v && typeof v === "object") {
|
|
195
|
-
const f = v;
|
|
196
|
-
const fileId = str(f.fileId, 128);
|
|
197
|
-
const name = str(f.name, MAX_LABEL_LEN);
|
|
198
|
-
const size = typeof f.size === "number" && Number.isFinite(f.size) ? f.size : undefined;
|
|
199
|
-
if (fileId && name && size !== undefined)
|
|
200
|
-
values[key] = { fileId, name, size };
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
return { v: COMPONENTS_WIRE_VERSION, type: "interaction", custom_id: customId, component, values };
|
|
205
|
-
}
|
|
206
|
-
export function encodePacket(msg) {
|
|
207
|
-
return new Uint8Array(Buffer.from(JSON.stringify(msg), "utf-8"));
|
|
208
|
-
}
|