@koralabs/handle-chat-sdk 0.0.13 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +6 -0
  2. package/README.md +97 -0
  3. package/assets/libsignal_bg.wasm +0 -0
  4. package/examples/guardian-flow.mjs +88 -0
  5. package/examples/quickstart.mjs +74 -0
  6. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.d.ts +207 -0
  7. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.js +945 -0
  8. package/lib/src/chat/ChatService.d.ts +117 -0
  9. package/lib/src/chat/ChatService.js +922 -0
  10. package/lib/src/chat/anchor.d.ts +17 -0
  11. package/lib/src/chat/anchor.js +43 -0
  12. package/lib/src/chat/blob.d.ts +55 -0
  13. package/lib/src/chat/blob.js +247 -0
  14. package/lib/src/chat/chainDirectory.d.ts +24 -0
  15. package/lib/src/chat/chainDirectory.js +93 -0
  16. package/lib/src/chat/demeter.d.ts +3 -0
  17. package/lib/src/chat/demeter.js +8 -0
  18. package/lib/src/chat/directory.d.ts +24 -0
  19. package/lib/src/chat/directory.js +37 -0
  20. package/lib/src/chat/guardian.d.ts +75 -0
  21. package/lib/src/chat/guardian.js +67 -0
  22. package/lib/src/chat/guardianHistory.d.ts +3 -0
  23. package/lib/src/chat/guardianHistory.js +36 -0
  24. package/lib/src/chat/httpRateLimit.d.ts +5 -0
  25. package/lib/src/chat/httpRateLimit.js +54 -0
  26. package/lib/src/chat/identity.d.ts +28 -0
  27. package/lib/src/chat/identity.js +61 -0
  28. package/lib/src/chat/invite.d.ts +19 -0
  29. package/lib/src/chat/invite.js +73 -0
  30. package/lib/src/chat/mesh/b2b.d.ts +17 -0
  31. package/lib/src/chat/mesh/b2b.js +50 -0
  32. package/lib/src/chat/mesh/client.d.ts +28 -0
  33. package/lib/src/chat/mesh/client.js +209 -0
  34. package/lib/src/chat/mesh/node.d.ts +12 -0
  35. package/lib/src/chat/mesh/node.js +46 -0
  36. package/lib/src/chat/mesh/presenceAuth.d.ts +19 -0
  37. package/lib/src/chat/mesh/presenceAuth.js +46 -0
  38. package/lib/src/chat/mesh/protocol.d.ts +92 -0
  39. package/lib/src/chat/mesh/protocol.js +19 -0
  40. package/lib/src/chat/mesh/webrtcAddr.d.ts +3 -0
  41. package/lib/src/chat/mesh/webrtcAddr.js +14 -0
  42. package/lib/src/chat/mesh/wire.d.ts +5 -0
  43. package/lib/src/chat/mesh/wire.js +36 -0
  44. package/lib/src/chat/message.d.ts +28 -0
  45. package/lib/src/chat/message.js +92 -0
  46. package/lib/src/chat/publish.d.ts +6 -0
  47. package/lib/src/chat/publish.js +33 -0
  48. package/lib/src/chat/qr.d.ts +9 -0
  49. package/lib/src/chat/qr.js +25 -0
  50. package/lib/src/chat/receipt.d.ts +17 -0
  51. package/lib/src/chat/receipt.js +22 -0
  52. package/lib/src/chat/sessionStore.d.ts +74 -0
  53. package/lib/src/chat/sessionStore.js +183 -0
  54. package/lib/src/chat/transport.d.ts +51 -0
  55. package/lib/src/chat/transport.js +139 -0
  56. package/lib/src/index.d.ts +19 -0
  57. package/lib/src/index.js +18 -0
  58. package/lib/src/memory.d.ts +18 -0
  59. package/lib/src/memory.js +44 -0
  60. package/lib/src/signal/SignalEngine.d.ts +73 -0
  61. package/lib/src/signal/SignalEngine.js +131 -0
  62. package/package.json +44 -19
  63. package/index.d.ts +0 -8
  64. package/index.js +0 -8
  65. package/interfaces/Chat.d.ts +0 -33
  66. package/interfaces/Chat.js +0 -1
  67. package/interfaces/Directory.d.ts +0 -27
  68. package/interfaces/Directory.js +0 -1
  69. package/interfaces/SessionMessage.d.ts +0 -15
  70. package/interfaces/SessionMessage.js +0 -1
  71. package/interfaces/Store.d.ts +0 -29
  72. package/interfaces/Store.js +0 -1
  73. package/lib/SignalDirectory.d.ts +0 -23
  74. package/lib/SignalDirectory.js +0 -157
  75. package/lib/SignalProtocolStore.d.ts +0 -46
  76. package/lib/SignalProtocolStore.js +0 -195
  77. package/lib/helper.d.ts +0 -2
  78. package/lib/helper.js +0 -17
  79. package/lib/helper.test.d.ts +0 -1
  80. package/lib/helper.test.js +0 -10
  81. package/lib/message-helper.d.ts +0 -20
  82. package/lib/message-helper.js +0 -53
@@ -0,0 +1,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). The resolver checks that a transaction spends an input at the current owner-token
8
+ * key address; merely paying that address does not authorize an anchor.
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;
@@ -0,0 +1,43 @@
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). The resolver checks that a transaction spends an input at the current owner-token
8
+ * key address; merely paying that address does not authorize an anchor.
9
+ */
10
+ export const ANCHOR_METADATA_LABEL = 7368n;
11
+ /** Cardano metadata strings cap at 64 bytes; hex is ASCII so 64 chars = 64 bytes. */
12
+ const CHUNK = 64;
13
+ const bytesToHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
14
+ const hexToBytes = (hex) => {
15
+ const clean = hex.length % 2 === 0 ? hex : `0${hex}`;
16
+ const out = new Uint8Array(clean.length / 2);
17
+ for (let i = 0; i < out.length; i++)
18
+ out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
19
+ return out;
20
+ };
21
+ const chunk = (s, n) => {
22
+ const out = [];
23
+ for (let i = 0; i < s.length; i += n)
24
+ out.push(s.slice(i, i + n));
25
+ return out;
26
+ };
27
+ /** Build the metadata value for a handle's bundle: `[handle, ...hex chunks]`. */
28
+ export function encodeAnchorMetadata(handle, bundle) {
29
+ return [handle, ...chunk(bytesToHex(bundle), CHUNK)];
30
+ }
31
+ /** Decode a metadata value back into `{ handle, bundle }`, or null if it isn't a well-formed anchor. */
32
+ export function decodeAnchorMetadata(value) {
33
+ if (!Array.isArray(value) || value.length < 2)
34
+ return null;
35
+ const parts = value;
36
+ if (!parts.every((p) => typeof p === "string"))
37
+ return null;
38
+ const [handle, ...chunks] = parts;
39
+ const hex = chunks.join("");
40
+ if (!/^[0-9a-fA-F]*$/.test(hex) || hex.length === 0)
41
+ return null;
42
+ return { handle, bundle: hexToBytes(hex) };
43
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Large-blob media streaming. Inlining a multi-MB image/audio/video in one sealed message is wrong for the
3
+ * mesh (a giant ciphertext through the mailbox / WebRTC). Instead a blob is encrypted under a random
4
+ * per-blob key, **content-addressed** by the hash of its ciphertext, chunked, and streamed as:
5
+ * - one `blob-ref` payload (small JSON: ref, mime, name, size, key, iv, chunk count, the message id), and
6
+ * - N `blob-chunk` payloads (raw ciphertext bytes — no base64 bloat — tagged with ref + index).
7
+ * All ride the typed-message channel, so they're E2E for free. The recipient reassembles, verifies the
8
+ * hash, decrypts, and surfaces a normal media message. Per-blob encryption keeps the design ready for an
9
+ * out-of-band/relay blob store later (the chunks are already ciphertext, the key travels inline via Signal).
10
+ */
11
+ import { type ContentMessage } from "./message";
12
+ export declare const BLOB_REF_KIND = "blob-ref";
13
+ export declare const BLOB_REF_MIME: string;
14
+ export declare const BLOB_CHUNK_MIME = "application/vnd.handle.blob-chunk";
15
+ export declare const BLOB_THRESHOLD: number;
16
+ export declare const CHUNK_SIZE: number;
17
+ export declare const MAX_BLOB_SIZE: number;
18
+ export declare const MAX_CHUNKS: number;
19
+ export interface BlobRef {
20
+ id: string;
21
+ ref: string;
22
+ mime: string;
23
+ name?: string;
24
+ size: number;
25
+ key: string;
26
+ iv: string;
27
+ chunks: number;
28
+ }
29
+ /** Encrypt + chunk a blob into a ref message + chunk messages (all typed, E2E via Signal). */
30
+ export declare function buildBlobMessages(id: string, mime: string, bytes: Uint8Array, name?: string): Promise<{
31
+ ref: ContentMessage;
32
+ chunks: ContentMessage[];
33
+ }>;
34
+ export declare const isBlobRef: (c: ContentMessage) => boolean;
35
+ export declare const isBlobChunk: (c: ContentMessage) => boolean;
36
+ export declare const isBlobPart: (c: ContentMessage) => boolean;
37
+ export declare const parseBlobRef: (c: ContentMessage) => BlobRef | null;
38
+ /** JSON-safe partial ciphertext state. Persist only inside the encrypted wallet vault. */
39
+ export interface BlobAssemblySnapshot {
40
+ version: 1;
41
+ pending: {
42
+ ref: string;
43
+ meta?: BlobRef;
44
+ parts: [number, string][];
45
+ }[];
46
+ }
47
+ export declare class BlobAssembler {
48
+ #private;
49
+ snapshot(): BlobAssemblySnapshot | undefined;
50
+ /** Restore atomically into a fresh assembler; never trust persisted bounds or byte counters. */
51
+ restore(snapshot: BlobAssemblySnapshot): void;
52
+ /** True only while this exact part remains buffered. Completion or eviction removes it. */
53
+ hasPart(c: ContentMessage): boolean;
54
+ accept(c: ContentMessage): Promise<ContentMessage | null>;
55
+ }
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Large-blob media streaming. Inlining a multi-MB image/audio/video in one sealed message is wrong for the
3
+ * mesh (a giant ciphertext through the mailbox / WebRTC). Instead a blob is encrypted under a random
4
+ * per-blob key, **content-addressed** by the hash of its ciphertext, chunked, and streamed as:
5
+ * - one `blob-ref` payload (small JSON: ref, mime, name, size, key, iv, chunk count, the message id), and
6
+ * - N `blob-chunk` payloads (raw ciphertext bytes — no base64 bloat — tagged with ref + index).
7
+ * All ride the typed-message channel, so they're E2E for free. The recipient reassembles, verifies the
8
+ * hash, decrypts, and surfaces a normal media message. Per-blob encryption keeps the design ready for an
9
+ * out-of-band/relay blob store later (the chunks are already ciphertext, the key travels inline via Signal).
10
+ */
11
+ import { mediaMessage, jsonMime, jsonMessage, messageJson } from "./message.js";
12
+ export const BLOB_REF_KIND = "blob-ref";
13
+ export const BLOB_REF_MIME = jsonMime(BLOB_REF_KIND);
14
+ export const BLOB_CHUNK_MIME = "application/vnd.handle.blob-chunk";
15
+ export const BLOB_THRESHOLD = 32 * 1024; // bodies larger than this stream; smaller inline
16
+ export const CHUNK_SIZE = 16 * 1024;
17
+ // Anti-DoS limits — a malicious peer must not be able to exhaust memory via the reassembler.
18
+ export const MAX_BLOB_SIZE = 25 * 1024 * 1024; // largest blob we'll reassemble (~25 MB)
19
+ export const MAX_CHUNKS = Math.ceil(MAX_BLOB_SIZE / CHUNK_SIZE) + 2;
20
+ const MAX_PENDING_BLOBS = 24; // concurrent in-flight blobs
21
+ const MAX_PENDING_BYTES = 48 * 1024 * 1024; // total buffered chunk bytes across all in-flight blobs
22
+ const toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
23
+ const toB64 = (b) => {
24
+ let s = "";
25
+ for (const x of b)
26
+ s += String.fromCharCode(x);
27
+ return btoa(s);
28
+ };
29
+ const fromB64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
30
+ /** Guaranteed ArrayBuffer-backed copy — WebCrypto's BufferSource rejects the generic Uint8Array under TS 5.7. */
31
+ const ab = (x) => {
32
+ const out = new Uint8Array(x.byteLength);
33
+ out.set(x);
34
+ return out;
35
+ };
36
+ const concat = (parts) => {
37
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
38
+ let i = 0;
39
+ for (const p of parts) {
40
+ out.set(p, i);
41
+ i += p.length;
42
+ }
43
+ return out;
44
+ };
45
+ async function seal(plain) {
46
+ const key = crypto.getRandomValues(new Uint8Array(32));
47
+ const iv = crypto.getRandomValues(new Uint8Array(12));
48
+ const ck = await crypto.subtle.importKey("raw", ab(key), "AES-GCM", false, ["encrypt"]);
49
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: ab(iv) }, ck, ab(plain)));
50
+ return { ct, key, iv };
51
+ }
52
+ async function open(ct, key, iv) {
53
+ const ck = await crypto.subtle.importKey("raw", ab(key), "AES-GCM", false, ["decrypt"]);
54
+ return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: ab(iv) }, ck, ab(ct)));
55
+ }
56
+ const hash = async (b) => toHex(new Uint8Array(await crypto.subtle.digest("SHA-256", ab(b))));
57
+ /** Encrypt + chunk a blob into a ref message + chunk messages (all typed, E2E via Signal). */
58
+ export async function buildBlobMessages(id, mime, bytes, name) {
59
+ const { ct, key, iv } = await seal(bytes);
60
+ const ref = await hash(ct);
61
+ const parts = [];
62
+ for (let o = 0; o < ct.length; o += CHUNK_SIZE)
63
+ parts.push(ct.subarray(o, o + CHUNK_SIZE));
64
+ const refMsg = jsonMessage(BLOB_REF_KIND, {
65
+ id,
66
+ ref,
67
+ mime,
68
+ name,
69
+ size: bytes.length,
70
+ key: toB64(key),
71
+ iv: toB64(iv),
72
+ chunks: parts.length,
73
+ });
74
+ const chunks = parts.map((c, i) => mediaMessage(BLOB_CHUNK_MIME, c, { ref, i: String(i) }));
75
+ return { ref: refMsg, chunks };
76
+ }
77
+ export const isBlobRef = (c) => c.mime === BLOB_REF_MIME;
78
+ export const isBlobChunk = (c) => c.mime === BLOB_CHUNK_MIME;
79
+ export const isBlobPart = (c) => isBlobRef(c) || isBlobChunk(c);
80
+ export const parseBlobRef = (c) => (isBlobRef(c) ? messageJson(c) : null);
81
+ const validRef = (ref) => typeof ref === "string" && ref.length > 0 && ref.length <= 256;
82
+ const validMeta = (m) => !!m && validRef(m.ref) && typeof m.id === "string" && m.id.length <= 1024 &&
83
+ typeof m.mime === "string" && m.mime.length <= 1024 &&
84
+ (m.name === undefined || (typeof m.name === "string" && m.name.length <= 4096)) &&
85
+ typeof m.key === "string" && m.key.length <= 128 && typeof m.iv === "string" && m.iv.length <= 128 &&
86
+ Number.isInteger(m.chunks) && m.chunks >= 1 && m.chunks <= MAX_CHUNKS &&
87
+ Number.isInteger(m.size) && m.size >= 0 && m.size <= MAX_BLOB_SIZE;
88
+ const copyMeta = (m) => ({
89
+ id: m.id, ref: m.ref, mime: m.mime, ...(m.name !== undefined ? { name: m.name } : {}),
90
+ size: m.size, key: m.key, iv: m.iv, chunks: m.chunks,
91
+ });
92
+ const sameMeta = (a, b) => a.id === b.id && a.ref === b.ref && a.mime === b.mime && a.name === b.name && a.size === b.size &&
93
+ a.key === b.key && a.iv === b.iv && a.chunks === b.chunks;
94
+ export class BlobAssembler {
95
+ #pending = new Map();
96
+ #totalBytes = 0;
97
+ #used = false;
98
+ snapshot() {
99
+ if (!this.#pending.size)
100
+ return undefined;
101
+ return {
102
+ version: 1,
103
+ pending: [...this.#pending].map(([ref, e]) => ({
104
+ ref,
105
+ ...(e.meta ? { meta: copyMeta(e.meta) } : {}),
106
+ parts: [...e.parts].map(([i, bytes]) => [i, toB64(bytes)]),
107
+ })),
108
+ };
109
+ }
110
+ /** Restore atomically into a fresh assembler; never trust persisted bounds or byte counters. */
111
+ restore(snapshot) {
112
+ if (this.#used)
113
+ throw new Error("blob assembler is not fresh");
114
+ if (!snapshot || snapshot.version !== 1 || !Array.isArray(snapshot.pending) || snapshot.pending.length > MAX_PENDING_BLOBS) {
115
+ throw new Error("invalid blob assembly snapshot");
116
+ }
117
+ const pending = new Map();
118
+ let total = 0;
119
+ for (const item of snapshot.pending) {
120
+ if (!item || !validRef(item.ref) || pending.has(item.ref) || !Array.isArray(item.parts) || item.parts.length > MAX_CHUNKS ||
121
+ (item.meta !== undefined && (!validMeta(item.meta) || item.meta.ref !== item.ref))) {
122
+ throw new Error("invalid blob assembly snapshot");
123
+ }
124
+ const e = { ...(item.meta ? { meta: copyMeta(item.meta) } : {}), parts: new Map(), bytes: 0 };
125
+ for (const part of item.parts) {
126
+ if (!Array.isArray(part) || part.length !== 2)
127
+ throw new Error("invalid blob assembly snapshot");
128
+ const [i, encoded] = part;
129
+ if (!Number.isInteger(i) || i < 0 || i >= MAX_CHUNKS || (e.meta && i >= e.meta.chunks) || e.parts.has(i) || typeof encoded !== "string" ||
130
+ encoded.length > 4 * Math.ceil(CHUNK_SIZE / 3) || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {
131
+ throw new Error("invalid blob assembly snapshot");
132
+ }
133
+ const bytes = fromB64(encoded);
134
+ if (bytes.length > CHUNK_SIZE || toB64(bytes) !== encoded)
135
+ throw new Error("invalid blob assembly snapshot");
136
+ e.parts.set(i, bytes);
137
+ e.bytes += bytes.length;
138
+ total += bytes.length;
139
+ if (total > MAX_PENDING_BYTES)
140
+ throw new Error("invalid blob assembly snapshot");
141
+ }
142
+ pending.set(item.ref, e);
143
+ }
144
+ for (const [ref, e] of pending)
145
+ this.#pending.set(ref, e);
146
+ this.#totalBytes = total;
147
+ this.#used = true;
148
+ }
149
+ /** True only while this exact part remains buffered. Completion or eviction removes it. */
150
+ hasPart(c) {
151
+ if (isBlobRef(c)) {
152
+ let meta;
153
+ try {
154
+ meta = parseBlobRef(c);
155
+ }
156
+ catch {
157
+ return false;
158
+ }
159
+ if (!meta || !validMeta(meta))
160
+ return false;
161
+ const stored = this.#pending.get(meta.ref)?.meta;
162
+ return !!stored && sameMeta(stored, meta);
163
+ }
164
+ if (!isBlobChunk(c))
165
+ return false;
166
+ const ref = c.meta?.ref;
167
+ const i = Number(c.meta?.i);
168
+ if (!validRef(ref) || !Number.isInteger(i) || i < 0 || i >= MAX_CHUNKS || c.body.length > CHUNK_SIZE)
169
+ return false;
170
+ const entry = this.#pending.get(ref);
171
+ if (entry?.meta && i >= entry.meta.chunks)
172
+ return false;
173
+ const stored = entry?.parts.get(i);
174
+ return !!stored && stored.length === c.body.length && stored.every((byte, index) => byte === c.body[index]);
175
+ }
176
+ async accept(c) {
177
+ this.#used = true;
178
+ const refMeta = parseBlobRef(c);
179
+ if (refMeta) {
180
+ // Reject implausible refs up front (anti-DoS): bounded chunk count + declared size.
181
+ if (!validMeta(refMeta))
182
+ return null;
183
+ const e = this.#pending.get(refMeta.ref) ?? this.#fresh(refMeta.ref);
184
+ if (e.meta && !sameMeta(e.meta, refMeta))
185
+ return null;
186
+ e.meta = copyMeta(refMeta);
187
+ for (const [i, bytes] of e.parts) {
188
+ if (i >= refMeta.chunks) {
189
+ e.parts.delete(i);
190
+ e.bytes -= bytes.length;
191
+ this.#totalBytes -= bytes.length;
192
+ }
193
+ }
194
+ this.#evict();
195
+ return this.#tryComplete(refMeta.ref);
196
+ }
197
+ if (isBlobChunk(c)) {
198
+ const ref = c.meta?.ref;
199
+ const i = Number(c.meta?.i);
200
+ if (!validRef(ref) || !Number.isInteger(i) || i < 0 || i >= MAX_CHUNKS || c.body.length > CHUNK_SIZE)
201
+ return null;
202
+ const e = this.#pending.get(ref) ?? this.#fresh(ref);
203
+ if (e.meta && i >= e.meta.chunks)
204
+ return null; // index past the declared count
205
+ if (!e.parts.has(i)) {
206
+ e.parts.set(i, c.body.slice());
207
+ e.bytes += c.body.length;
208
+ this.#totalBytes += c.body.length;
209
+ this.#evict();
210
+ }
211
+ return this.#tryComplete(ref);
212
+ }
213
+ return null;
214
+ }
215
+ #fresh(ref) {
216
+ const e = { parts: new Map(), bytes: 0 };
217
+ this.#pending.set(ref, e);
218
+ return e;
219
+ }
220
+ #drop(ref) {
221
+ const e = this.#pending.get(ref);
222
+ if (e) {
223
+ this.#totalBytes -= e.bytes;
224
+ this.#pending.delete(ref);
225
+ }
226
+ }
227
+ /** Evict oldest in-flight blobs until within the concurrent-blob + total-byte caps. */
228
+ #evict() {
229
+ while (this.#pending.size > MAX_PENDING_BLOBS || this.#totalBytes > MAX_PENDING_BYTES) {
230
+ const oldest = this.#pending.keys().next().value;
231
+ if (oldest === undefined)
232
+ break;
233
+ this.#drop(oldest);
234
+ }
235
+ }
236
+ async #tryComplete(ref) {
237
+ const e = this.#pending.get(ref);
238
+ if (!e?.meta || e.parts.size < e.meta.chunks)
239
+ return null;
240
+ const ct = concat(Array.from({ length: e.meta.chunks }, (_, i) => e.parts.get(i) ?? new Uint8Array(0)));
241
+ this.#drop(ref);
242
+ if ((await hash(ct)) !== ref)
243
+ return null; // integrity failure — drop
244
+ const plain = await open(ct, fromB64(e.meta.key), fromB64(e.meta.iv));
245
+ return mediaMessage(e.meta.mime, plain, { name: e.meta.name ?? "", id: e.meta.id });
246
+ }
247
+ }
@@ -0,0 +1,24 @@
1
+ import { type ChainNetwork } from "./demeter";
2
+ /** Server-side chain resolution. The provider key must never be shipped to a browser. */
3
+ export interface ChainAnchorConfig {
4
+ env: ChainNetwork;
5
+ demeterApiKey: string;
6
+ fetchImpl?: typeof fetch;
7
+ /** Must validate the address and its payment credential using a Cardano address library. */
8
+ isKeyOwnerAddress?: (address: string) => boolean;
9
+ }
10
+ export declare class ChainAnchorStore {
11
+ private readonly apiBase;
12
+ private readonly bfBase;
13
+ private readonly key;
14
+ private readonly fetchImpl;
15
+ private readonly isKeyOwnerAddress?;
16
+ constructor(cfg: ChainAnchorConfig);
17
+ /** Only key-controlled current owner addresses are supported; absence is distinct from provider failure. */
18
+ resolve(handle: string): Promise<Uint8Array | null>;
19
+ /** Compatibility with callers that supply an address: it must still be the actual owner. */
20
+ resolveByAddress(address: string, handle: string): Promise<Uint8Array | null>;
21
+ ownerAddress(handle: string): Promise<string | null>;
22
+ private resolveOwnerAddress;
23
+ private bf;
24
+ }
@@ -0,0 +1,93 @@
1
+ import { decodeAnchorMetadata, ANCHOR_METADATA_LABEL } from "./anchor.js";
2
+ import { providerFetch } from "./httpRateLimit.js";
3
+ import { chainNetwork, demeterBase } from "./demeter.js";
4
+ export class ChainAnchorStore {
5
+ apiBase;
6
+ bfBase;
7
+ key;
8
+ fetchImpl;
9
+ isKeyOwnerAddress;
10
+ constructor(cfg) {
11
+ const network = chainNetwork(cfg.env);
12
+ this.apiBase = `https://${network === "mainnet" ? "" : `${network}.`}api.handle.me`;
13
+ this.bfBase = demeterBase(network);
14
+ this.key = cfg.demeterApiKey;
15
+ this.fetchImpl = cfg.fetchImpl ?? fetch;
16
+ this.isKeyOwnerAddress = cfg.isKeyOwnerAddress;
17
+ }
18
+ /** Only key-controlled current owner addresses are supported; absence is distinct from provider failure. */
19
+ async resolve(handle) {
20
+ const address = await this.ownerAddress(handle);
21
+ if (!address)
22
+ return null;
23
+ return this.resolveOwnerAddress(address, `$${handle.replace(/^\$/, "")}`);
24
+ }
25
+ /** Compatibility with callers that supply an address: it must still be the actual owner. */
26
+ async resolveByAddress(address, handle) {
27
+ const owner = await this.ownerAddress(handle);
28
+ if (!owner || owner !== address)
29
+ return null;
30
+ return this.resolveOwnerAddress(owner, `$${handle.replace(/^\$/, "")}`);
31
+ }
32
+ async ownerAddress(handle) {
33
+ const name = handle.replace(/^\$/, "");
34
+ if (!/^[a-z0-9_.@-]{1,64}$/.test(name))
35
+ throw new Error("invalid handle");
36
+ const res = await providerFetch(this.fetchImpl, `${this.apiBase}/handles/${encodeURIComponent(name)}`);
37
+ if (res.status === 404)
38
+ return null;
39
+ if (!res.ok)
40
+ throw new Error(`Handle API: ${res.status}`);
41
+ const data = await res.json();
42
+ if (data.virtual || data.handle_type?.toLowerCase().includes("virtual"))
43
+ throw new Error("virtual handle ownership is not supported");
44
+ if (!/^[0-9a-f]{56}$/i.test(data.policy ?? "") || !/^(?:[0-9a-f]{2}){1,32}$/i.test(data.hex ?? "")) {
45
+ throw new Error("Handle API returned an invalid owner asset");
46
+ }
47
+ const asset = `${data.policy}${data.hex}`;
48
+ const owners = await this.bf(`/assets/${asset}/addresses?count=100&page=1`);
49
+ if (!Array.isArray(owners) || owners.length !== 1 || owners[0].quantity !== "1" || typeof owners[0].address !== "string") {
50
+ throw new Error("owner asset does not have one current owner");
51
+ }
52
+ const address = owners[0].address;
53
+ const details = await this.bf(`/addresses/${encodeURIComponent(address)}`);
54
+ if (details.address !== address || details.type !== "shelley" || details.script !== false || (this.isKeyOwnerAddress && !this.isKeyOwnerAddress(address)))
55
+ throw new Error("owner address is not key-controlled");
56
+ return address;
57
+ }
58
+ async resolveOwnerAddress(address, handle) {
59
+ const pageSize = 25;
60
+ const maxPages = 4;
61
+ for (let page = 1; page <= maxPages; page++) {
62
+ const txs = await this.bf(`/addresses/${encodeURIComponent(address)}/transactions?order=desc&count=${pageSize}&page=${page}`);
63
+ if (!Array.isArray(txs))
64
+ throw new Error("invalid transaction list");
65
+ for (const { tx_hash } of txs) {
66
+ const md = await this.bf(`/txs/${tx_hash}/metadata`);
67
+ if (!Array.isArray(md))
68
+ throw new Error("invalid transaction metadata");
69
+ const entry = md.find((m) => String(m.label) === String(ANCHOR_METADATA_LABEL));
70
+ const decoded = entry && decodeAnchorMetadata(entry.json_metadata);
71
+ if (!decoded || decoded.handle !== handle)
72
+ continue;
73
+ const tx = await this.bf(`/txs/${tx_hash}`);
74
+ if (tx.valid_contract !== true)
75
+ continue;
76
+ const utxos = await this.bf(`/txs/${tx_hash}/utxos`);
77
+ if (!Array.isArray(utxos.inputs))
78
+ throw new Error("invalid transaction inputs");
79
+ if (utxos.inputs.some((input) => input.address === address && !input.reference && !input.collateral))
80
+ return decoded.bundle;
81
+ }
82
+ if (txs.length < pageSize)
83
+ return null;
84
+ }
85
+ throw new Error("anchor history scan limit reached; result inconclusive");
86
+ }
87
+ async bf(path) {
88
+ const res = await providerFetch(this.fetchImpl, `${this.bfBase}${path}`, { headers: { "dmtr-api-key": this.key } });
89
+ if (!res.ok)
90
+ throw new Error(`Demeter: ${res.status}`);
91
+ return res.json();
92
+ }
93
+ }
@@ -0,0 +1,3 @@
1
+ export type ChainNetwork = "preview" | "preprod" | "mainnet";
2
+ export declare function chainNetwork(value: string): ChainNetwork;
3
+ export declare function demeterBase(network: string): string;
@@ -0,0 +1,8 @@
1
+ export function chainNetwork(value) {
2
+ if (value !== "preview" && value !== "preprod" && value !== "mainnet")
3
+ throw new Error("unsupported chain network");
4
+ return value;
5
+ }
6
+ export function demeterBase(network) {
7
+ return `https://cardano-${chainNetwork(network)}.blockfrost-m1.dmtr.host`;
8
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The anchor directory seam: publish/look up a handle's published Signal bundle.
3
+ * Keep the synchronous SDK contract for memory/local directories. The deployed client uses the
4
+ * asynchronous owner-verified backend; a synchronous call must not start an unobserved lookup.
5
+ */
6
+ export interface Directory {
7
+ publish(handle: string, bundle: Uint8Array): void;
8
+ resolve(handle: string): Uint8Array | null;
9
+ }
10
+ export interface AsyncDirectory {
11
+ publish(handle: string, bundle: Uint8Array): void;
12
+ resolveAsync(handle: string): Promise<Uint8Array | null>;
13
+ }
14
+ export declare class AnchorDirectory implements AsyncDirectory {
15
+ private readonly origin;
16
+ constructor(origin?: string);
17
+ publish(): void;
18
+ resolveAsync(handle: string): Promise<Uint8Array | null>;
19
+ }
20
+ export declare class LocalStorageDirectory implements Directory {
21
+ private key;
22
+ publish(handle: string, bundle: Uint8Array): void;
23
+ resolve(handle: string): Uint8Array | null;
24
+ }
@@ -0,0 +1,37 @@
1
+ import { hexToBytes } from "./identity.js";
2
+ import { providerFetch } from "./httpRateLimit.js";
3
+ export class AnchorDirectory {
4
+ origin;
5
+ constructor(origin = globalThis.location.origin) {
6
+ this.origin = origin;
7
+ }
8
+ publish() { } // Publishing is an explicit wallet-signed transaction, not a local directory write.
9
+ async resolveAsync(handle) {
10
+ const url = new URL(`/anchor/resolve?handle=${encodeURIComponent(handle)}`, this.origin).href;
11
+ const response = await providerFetch(fetch, url);
12
+ if (!response.ok)
13
+ throw new Error(`Anchor lookup failed: ${response.status}`);
14
+ const data = await response.json();
15
+ if (!data || typeof data !== "object" || !("bundle" in data))
16
+ throw new Error("Invalid anchor lookup response");
17
+ const bundle = data.bundle;
18
+ if (bundle === null)
19
+ return null;
20
+ if (typeof bundle !== "string" || !/^(?:[0-9a-fA-F]{2})+$/.test(bundle))
21
+ throw new Error("Invalid anchor bundle");
22
+ return hexToBytes(bundle);
23
+ }
24
+ }
25
+ const bytesToHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
26
+ export class LocalStorageDirectory {
27
+ key(handle) {
28
+ return `handlechat:bundle:${handle}`;
29
+ }
30
+ publish(handle, bundle) {
31
+ localStorage.setItem(this.key(handle), bytesToHex(bundle));
32
+ }
33
+ resolve(handle) {
34
+ const hex = localStorage.getItem(this.key(handle));
35
+ return hex ? hexToBytes(hex) : null;
36
+ }
37
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The guardian protocol — Social Secret Recovery (secrets.handle.me) riding on chat. chat is the MEDIUM:
3
+ * it provides handle-addressed E2E sessions + these structured payloads; the SSR crypto (Shamir/threshold
4
+ * splitting, on-chain guardian policies) lives in secrets.handle.me. Both payloads named `shard` are opaque
5
+ * to chat, but they are not interchangeable: an invite carries recovery material and an approval carries
6
+ * a session-specific artifact produced by secrets.handle.me. Chat must never create that artifact itself.
7
+ *
8
+ * Flow: principal → `guardian-invite` → guardian → `guardian-consent` (accept/decline).
9
+ * Later, recovering user → `recovery-notify` → guardian → `approval-coordination`.
10
+ * Built on the typed-message foundation — each payload is `application/vnd.handle.<kind>+json`, so it's
11
+ * E2E-encrypted for free and a relay sees only ciphertext.
12
+ */
13
+ import { type ContentMessage } from "./message";
14
+ export declare const GUARDIAN_KINDS: readonly ["guardian-invite", "guardian-consent", "recovery-notify", "approval-coordination"];
15
+ export type GuardianKind = (typeof GUARDIAN_KINDS)[number];
16
+ /** Principal asks a candidate to guard a secret; `shard` is the opaque piece the guardian will hold. */
17
+ export interface GuardianInvite {
18
+ secretRef: string;
19
+ label?: string;
20
+ shard?: string;
21
+ }
22
+ export interface GuardianConsent {
23
+ secretRef: string;
24
+ accept: boolean;
25
+ label?: string;
26
+ gekPub?: string;
27
+ }
28
+ export interface RecoveryNotify {
29
+ secretRef: string;
30
+ label?: string;
31
+ session?: string;
32
+ continuation?: string;
33
+ }
34
+ export interface ApprovalCoordination {
35
+ secretRef: string;
36
+ approve: boolean;
37
+ label?: string;
38
+ shard?: string;
39
+ }
40
+ export type GuardianPayload = {
41
+ kind: "guardian-invite";
42
+ value: GuardianInvite;
43
+ } | {
44
+ kind: "guardian-consent";
45
+ value: GuardianConsent;
46
+ } | {
47
+ kind: "recovery-notify";
48
+ value: RecoveryNotify;
49
+ } | {
50
+ kind: "approval-coordination";
51
+ value: ApprovalCoordination;
52
+ };
53
+ export declare const guardianInvite: (v: GuardianInvite) => ContentMessage;
54
+ export declare const guardianConsent: (v: GuardianConsent) => ContentMessage;
55
+ export declare const recoveryNotify: (v: RecoveryNotify) => ContentMessage;
56
+ export declare const approvalCoordination: (v: ApprovalCoordination) => ContentMessage;
57
+ export declare const isGuardian: (c: ContentMessage) => boolean;
58
+ /** Parse a typed message into a guardian payload, or null if it isn't one. The body is peer-controlled,
59
+ * so malformed JSON is "not a guardian payload" (null), never an exception that breaks rendering. */
60
+ export declare function parseGuardian(c: ContentMessage): GuardianPayload | null;
61
+ /** A thread entry as far as guardian lookups care. */
62
+ export interface ThreadEntry {
63
+ from: string;
64
+ content: ContentMessage;
65
+ }
66
+ /** The human label from the invite that introduced `secretRef` (so reply cards read well). */
67
+ export declare const inviteLabel: (thread: readonly ThreadEntry[], secretRef: string) => string | undefined;
68
+ /** The opaque shard handed over in the guardian-invite for `secretRef`. A shard-bearing invite wins over a
69
+ * shard-less consent ask with the same ref. */
70
+ export declare const heldShard: (thread: readonly ThreadEntry[], secretRef: string) => string | undefined;
71
+ /** The most recent guardian-invite `me` sent in this thread, for starting recovery. */
72
+ export declare function findMyInvite(thread: readonly ThreadEntry[], me: string | null): {
73
+ secretRef: string;
74
+ label?: string;
75
+ } | null;