@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,67 @@
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 { jsonMessage, jsonMime, messageJson } from "./message.js";
14
+ export const GUARDIAN_KINDS = ["guardian-invite", "guardian-consent", "recovery-notify", "approval-coordination"];
15
+ // ---- builders (→ typed ContentMessage) ----
16
+ export const guardianInvite = (v) => jsonMessage("guardian-invite", v);
17
+ export const guardianConsent = (v) => jsonMessage("guardian-consent", v);
18
+ export const recoveryNotify = (v) => jsonMessage("recovery-notify", v);
19
+ export const approvalCoordination = (v) => jsonMessage("approval-coordination", v);
20
+ const KIND_BY_MIME = new Map(GUARDIAN_KINDS.map((k) => [jsonMime(k), k]));
21
+ export const isGuardian = (c) => KIND_BY_MIME.has(c.mime);
22
+ /** Parse a typed message into a guardian payload, or null if it isn't one. The body is peer-controlled,
23
+ * so malformed JSON is "not a guardian payload" (null), never an exception that breaks rendering. */
24
+ export function parseGuardian(c) {
25
+ const kind = KIND_BY_MIME.get(c.mime);
26
+ if (!kind)
27
+ return null;
28
+ let value;
29
+ try {
30
+ value = messageJson(c);
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ if (value === null || typeof value !== "object" || Array.isArray(value))
36
+ return null;
37
+ const v = value;
38
+ if (typeof v.secretRef !== "string" || (v.label !== undefined && typeof v.label !== "string"))
39
+ return null;
40
+ if (kind === "guardian-consent" && typeof v.accept !== "boolean")
41
+ return null;
42
+ if (kind === "approval-coordination" && typeof v.approve !== "boolean")
43
+ return null;
44
+ for (const field of ["shard", "session", "gekPub", "continuation"]) {
45
+ if (v[field] !== undefined && typeof v[field] !== "string")
46
+ return null;
47
+ }
48
+ return { kind, value };
49
+ }
50
+ const invitesFor = (thread, secretRef) => thread.flatMap((m) => {
51
+ const p = parseGuardian(m.content);
52
+ return p?.kind === "guardian-invite" && p.value.secretRef === secretRef ? [{ from: m.from, value: p.value }] : [];
53
+ });
54
+ /** The human label from the invite that introduced `secretRef` (so reply cards read well). */
55
+ export const inviteLabel = (thread, secretRef) => invitesFor(thread, secretRef).find((i) => i.value.label)?.value.label;
56
+ /** The opaque shard handed over in the guardian-invite for `secretRef`. A shard-bearing invite wins over a
57
+ * shard-less consent ask with the same ref. */
58
+ export const heldShard = (thread, secretRef) => invitesFor(thread, secretRef).find((i) => i.value.shard)?.value.shard;
59
+ /** The most recent guardian-invite `me` sent in this thread, for starting recovery. */
60
+ export function findMyInvite(thread, me) {
61
+ for (let i = thread.length - 1; i >= 0; i--) {
62
+ const p = parseGuardian(thread[i].content);
63
+ if (p?.kind === "guardian-invite" && thread[i].from === me)
64
+ return { secretRef: p.value.secretRef, label: p.value.label };
65
+ }
66
+ return null;
67
+ }
@@ -0,0 +1,3 @@
1
+ import { type ThreadEntry } from "./guardian";
2
+ /** Keep the rolling transcript plus the local consent and opaque invite material the user agreed to hold. A peer cannot create permanent records just by sending invites. */
3
+ export declare function retainedHistory<T extends ThreadEntry>(thread: T[], me: string, limit: number): T[];
@@ -0,0 +1,36 @@
1
+ import { parseGuardian } from "./guardian.js";
2
+ /** Keep the rolling transcript plus the local consent and opaque invite material the user agreed to hold. A peer cannot create permanent records just by sending invites. */
3
+ export function retainedHistory(thread, me, limit) {
4
+ if (thread.length <= limit)
5
+ return thread;
6
+ const decisions = new Map();
7
+ const materials = new Map();
8
+ const sessionRequests = new Map();
9
+ for (const row of thread) {
10
+ const payload = parseGuardian(row.content);
11
+ if (row.from === me && payload?.kind === "guardian-consent") {
12
+ decisions.set(payload.value.secretRef, { accepted: payload.value.accept, row });
13
+ }
14
+ else if (row.from !== me && payload?.kind === "guardian-invite" && payload.value.shard && !materials.has(payload.value.secretRef)) {
15
+ // Match heldShard: the first material accepted for a given reference is not replaced by later traffic.
16
+ materials.set(payload.value.secretRef, row);
17
+ }
18
+ else if (row.from !== me && payload?.kind === "recovery-notify" && payload.value.session !== undefined) {
19
+ sessionRequests.set(payload.value.secretRef, row);
20
+ }
21
+ }
22
+ const pinned = new Set();
23
+ for (const [ref, decision] of decisions) {
24
+ if (!decision.accepted)
25
+ continue;
26
+ pinned.add(decision.row); // the actual material may arrive after the original consent has rolled off
27
+ const material = materials.get(ref);
28
+ if (material)
29
+ pinned.add(material);
30
+ // Never reinterpret this consent as legacy just because the original Secrets request aged out.
31
+ const request = sessionRequests.get(ref);
32
+ if (request)
33
+ pinned.add(request);
34
+ }
35
+ return thread.filter((row, i) => i >= thread.length - limit || pinned.has(row));
36
+ }
@@ -0,0 +1,5 @@
1
+ export declare class ProviderRateLimitError extends Error {
2
+ readonly retryAfter: number;
3
+ constructor(retryAfter: number);
4
+ }
5
+ export declare function providerFetch(fetchImpl: typeof fetch, url: string, init?: RequestInit): Promise<Response>;
@@ -0,0 +1,54 @@
1
+ // Shared across all provider calls in this process. Do not retry before a provider's reset.
2
+ const blockedUntil = new Map();
3
+ export class ProviderRateLimitError extends Error {
4
+ retryAfter;
5
+ constructor(retryAfter) {
6
+ super(`provider rate limited, retry in ${retryAfter}s`);
7
+ this.retryAfter = retryAfter;
8
+ }
9
+ }
10
+ export async function providerFetch(fetchImpl, url, init) {
11
+ const origin = new URL(url).origin;
12
+ const remaining = (blockedUntil.get(origin) ?? 0) - Date.now();
13
+ if (remaining > 0)
14
+ throw new ProviderRateLimitError(Math.ceil(remaining / 1000));
15
+ // A provider must never redirect a credential-bearing request to another host.
16
+ const res = await fetchImpl(url, { ...init, redirect: "manual" });
17
+ const now = Date.now();
18
+ const delay = (value) => {
19
+ if (!value)
20
+ return 0;
21
+ const seconds = Number(value);
22
+ return Number.isFinite(seconds) ? Math.max(0, seconds * 1000) : Math.max(0, Date.parse(value) - now) || 0;
23
+ };
24
+ let wait = Math.max(delay(res.headers?.get("retry-after")), delay(res.headers?.get("x-ratelimit-reset-after")));
25
+ if (res.headers?.get("x-ratelimit-remaining") === "0" || res.headers?.get("ratelimit-remaining") === "0") {
26
+ for (const name of ["x-ratelimit-reset", "ratelimit-reset"]) {
27
+ const value = res.headers.get(name);
28
+ if (value) {
29
+ const n = Number(value);
30
+ wait = Math.max(wait, Number.isFinite(n) ? (n > 1e9 ? n * 1000 - now : n * 1000) : delay(value));
31
+ }
32
+ }
33
+ }
34
+ if (res.status === 429) {
35
+ try {
36
+ const body = await res.clone().json();
37
+ if (typeof body.retry_after === "number")
38
+ wait = Math.max(wait, body.retry_after * 1000);
39
+ for (const detail of body.error?.details ?? []) {
40
+ if (/^\d+(?:\.\d+)?s$/.test(detail.retryDelay ?? ""))
41
+ wait = Math.max(wait, parseFloat(detail.retryDelay) * 1000);
42
+ }
43
+ }
44
+ catch { /* Not every provider supplies a JSON delay. */ }
45
+ }
46
+ if (wait > 0) {
47
+ blockedUntil.set(origin, Math.max(blockedUntil.get(origin) ?? 0, now + wait));
48
+ if (res.status === 429)
49
+ throw new ProviderRateLimitError(Math.ceil(wait / 1000));
50
+ }
51
+ if (res.status >= 300 && res.status < 400)
52
+ throw new Error(`provider redirect: ${res.status}`);
53
+ return res;
54
+ }
@@ -0,0 +1,28 @@
1
+ export interface DerivedIdentity {
2
+ priv: Uint8Array;
3
+ registrationId: number;
4
+ }
5
+ export declare function deriveIdentity(seed: Uint8Array, handle: string): Promise<DerivedIdentity>;
6
+ /** Hex string → bytes. */
7
+ export declare const hexToBytes: (hex: string) => Uint8Array;
8
+ /** The handle-independent message a wallet signs to derive its chat identity. Must stay identical across
9
+ * chat and secrets.handle.me so a handle has ONE identity key everywhere. */
10
+ export declare const IDENTITY_MESSAGE = "koralabs:handle-identity:derive:v1";
11
+ /** A CIP-30 data signature (COSE_Sign1 + COSE_Key, both hex). */
12
+ export interface DataSignature {
13
+ signature: string;
14
+ key: string;
15
+ }
16
+ /** The slice of CIP-30 we need: sign arbitrary data with the wallet key (CIP-8). */
17
+ export type SignData = (addressHex: string, payloadHex: string) => Promise<DataSignature>;
18
+ /**
19
+ * Sign-to-derive: the identity seed is the wallet's signature over {@link IDENTITY_MESSAGE} at the stake
20
+ * address. Re-signing reproduces it (deterministic wallets), so nothing is stored. The handle is folded
21
+ * in later by {@link deriveIdentity}, so one signature covers every handle the wallet controls.
22
+ */
23
+ export declare function deriveSeedFromWallet(signData: SignData, stakeAddressHex: string, verifyDeterministic?: boolean): Promise<Uint8Array>;
24
+ /**
25
+ * Enroll-time guard: a wallet that randomizes its signatures can't reproduce the identity on a later
26
+ * visit, silently orphaning every session. Sign the same message twice and fail loudly if they differ.
27
+ */
28
+ export declare function assertDeterministicSigning(signData: SignData, stakeAddressHex: string): Promise<void>;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Derive the wallet-rooted chat identity in the browser (WebCrypto HKDF → 32-byte key for the WASM
3
+ * SignalEngine), byte-compatible with `poc/`'s derivation (same salt + info=handle).
4
+ *
5
+ * The seed is the wallet's signature over a fixed, handle-independent message at its stake address
6
+ * (sign-to-derive). It is stored nowhere — re-signing reproduces it. One signature serves all of a
7
+ * wallet's handles; `deriveIdentity(seed, handle)` makes each handle's key distinct.
8
+ */
9
+ const enc = new TextEncoder();
10
+ const SALT = enc.encode("koralabs:handle-identity:x25519:v1");
11
+ async function hkdf(seed, info, lenBytes) {
12
+ const key = await crypto.subtle.importKey("raw", new Uint8Array(seed), "HKDF", false, ["deriveBits"]);
13
+ const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(SALT), info: new Uint8Array(enc.encode(info)) }, key, lenBytes * 8);
14
+ return new Uint8Array(bits);
15
+ }
16
+ export async function deriveIdentity(seed, handle) {
17
+ const priv = await hkdf(seed, handle, 32);
18
+ const [hi = 0, lo = 0] = await hkdf(seed, `${handle}:regid`, 2);
19
+ return { priv, registrationId: (((hi << 8) | lo) % 16383) + 1 };
20
+ }
21
+ /** Hex string → bytes. */
22
+ export const hexToBytes = (hex) => {
23
+ const clean = hex.length % 2 === 0 ? hex : `0${hex}`;
24
+ const out = new Uint8Array(clean.length / 2);
25
+ for (let i = 0; i < out.length; i++)
26
+ out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
27
+ return out;
28
+ };
29
+ /** The handle-independent message a wallet signs to derive its chat identity. Must stay identical across
30
+ * chat and secrets.handle.me so a handle has ONE identity key everywhere. */
31
+ export const IDENTITY_MESSAGE = "koralabs:handle-identity:derive:v1";
32
+ const utf8ToHex = (s) => Array.from(enc.encode(s), (b) => b.toString(16).padStart(2, "0")).join("");
33
+ /**
34
+ * Sign-to-derive: the identity seed is the wallet's signature over {@link IDENTITY_MESSAGE} at the stake
35
+ * address. Re-signing reproduces it (deterministic wallets), so nothing is stored. The handle is folded
36
+ * in later by {@link deriveIdentity}, so one signature covers every handle the wallet controls.
37
+ */
38
+ export async function deriveSeedFromWallet(signData, stakeAddressHex, verifyDeterministic = false) {
39
+ const payload = utf8ToHex(IDENTITY_MESSAGE);
40
+ const { signature } = await signData(stakeAddressHex, payload);
41
+ if (!signature)
42
+ throw new Error("wallet returned an empty signature");
43
+ if (verifyDeterministic) {
44
+ const second = await signData(stakeAddressHex, payload);
45
+ if (signature !== second.signature)
46
+ throw new Error("This wallet produces different signatures and cannot reproduce your chat identity. Use a wallet with deterministic signing.");
47
+ }
48
+ return hexToBytes(signature);
49
+ }
50
+ /**
51
+ * Enroll-time guard: a wallet that randomizes its signatures can't reproduce the identity on a later
52
+ * visit, silently orphaning every session. Sign the same message twice and fail loudly if they differ.
53
+ */
54
+ export async function assertDeterministicSigning(signData, stakeAddressHex) {
55
+ const payload = utf8ToHex(IDENTITY_MESSAGE);
56
+ const [a, b] = await Promise.all([signData(stakeAddressHex, payload), signData(stakeAddressHex, payload)]);
57
+ if (a.signature !== b.signature) {
58
+ throw new Error("This wallet produces a different signature each time, so it can't reproduce your chat identity. " +
59
+ "Use a wallet with deterministic (RFC 8032) signing.");
60
+ }
61
+ }
@@ -0,0 +1,19 @@
1
+ export declare function encodeInvite(handle: string, bundle: Uint8Array): string;
2
+ export declare function decodeInvite(payload: string): {
3
+ handle: string;
4
+ bundle: Uint8Array;
5
+ };
6
+ /** A shareable invite URL: `<origin>/#i=<payload>`. */
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;
15
+ /** Pull an invite out of a URL (or null if there isn't one). */
16
+ export declare function parseInviteUrl(url: string): {
17
+ handle: string;
18
+ bundle: Uint8Array;
19
+ } | null;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Out-of-band invite: the no-transaction first-contact path. An invite carries the same thing a chain
3
+ * anchor would — a handle + its Signal key-bundle — but you hand it to someone directly (a URL or a QR),
4
+ * so the trust is "you got it from them." Chain-agnostic: identical on Cardano, Bitcoin, anywhere.
5
+ *
6
+ * Wire format (then base64url): `[2-byte handle length][handle utf8][bundle bytes]`.
7
+ */
8
+ const toB64url = (bytes) => {
9
+ let bin = "";
10
+ for (const b of bytes)
11
+ bin += String.fromCharCode(b);
12
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
13
+ };
14
+ const fromB64url = (s) => {
15
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
16
+ const bin = atob(b64);
17
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
18
+ };
19
+ export function encodeInvite(handle, bundle) {
20
+ const h = new TextEncoder().encode(handle);
21
+ if (h.length > 0xffff)
22
+ throw new Error("handle too long");
23
+ const out = new Uint8Array(2 + h.length + bundle.length);
24
+ out[0] = (h.length >> 8) & 0xff;
25
+ out[1] = h.length & 0xff;
26
+ out.set(h, 2);
27
+ out.set(bundle, 2 + h.length);
28
+ return toB64url(out);
29
+ }
30
+ export function decodeInvite(payload) {
31
+ const bytes = fromB64url(payload.trim());
32
+ if (bytes.length < 2)
33
+ throw new Error("invite too short");
34
+ const hLen = (bytes[0] << 8) | bytes[1];
35
+ if (bytes.length < 2 + hLen)
36
+ throw new Error("invite truncated");
37
+ return {
38
+ handle: new TextDecoder().decode(bytes.subarray(2, 2 + hLen)),
39
+ bundle: bytes.subarray(2 + hLen),
40
+ };
41
+ }
42
+ /** A shareable invite URL: `<origin>/#i=<payload>`. */
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
+ }
62
+ /** Pull an invite out of a URL (or null if there isn't one). */
63
+ export function parseInviteUrl(url) {
64
+ const m = url.match(/[#&]i=([A-Za-z0-9_-]+)/);
65
+ if (!m)
66
+ return null;
67
+ try {
68
+ return decodeInvite(m[1]);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
@@ -0,0 +1,17 @@
1
+ import type { Libp2p } from "@libp2p/interface";
2
+ /**
3
+ * The device-mesh primitive: two browsers connect **directly** over WebRTC. A circuit-relay superpeer
4
+ * only brokers the handshake (it carries no conversation); after that the data channel is peer-to-peer.
5
+ * Self-contained (own module) so its WebRTC deps load only when direct delivery is used — not in the
6
+ * mailbox mesh chunk. Ported from `poc/src/browser/b2b.ts`.
7
+ */
8
+ export declare const B2B_PROTOCOL = "/handle-chat/b2b/1.0.0";
9
+ /** A browser node that can be dialed directly over WebRTC, reachable for the handshake via a relay. */
10
+ export declare function createWebrtcNode(): Promise<Libp2p>;
11
+ /** Reserve a relay slot, accept direct messages, and return our dialable /webrtc address. */
12
+ export declare function startDirectListener(relayAddr: string, onMessage: (text: string) => void): Promise<{
13
+ node: Libp2p;
14
+ addr: string;
15
+ }>;
16
+ /** Connect to a peer's /webrtc address (handshake brokered by the relay) and send directly. */
17
+ export declare function dialDirect(node: Libp2p, targetAddr: string, text: string): Promise<void>;
@@ -0,0 +1,50 @@
1
+ import { multiaddr } from "@multiformats/multiaddr";
2
+ import { readFrame, sendFrame } from "./wire.js";
3
+ import { waitForWebrtcAddr } from "./webrtcAddr.js";
4
+ /**
5
+ * The device-mesh primitive: two browsers connect **directly** over WebRTC. A circuit-relay superpeer
6
+ * only brokers the handshake (it carries no conversation); after that the data channel is peer-to-peer.
7
+ * Self-contained (own module) so its WebRTC deps load only when direct delivery is used — not in the
8
+ * mailbox mesh chunk. Ported from `poc/src/browser/b2b.ts`.
9
+ */
10
+ export const B2B_PROTOCOL = "/handle-chat/b2b/1.0.0";
11
+ /** A browser node that can be dialed directly over WebRTC, reachable for the handshake via a relay. */
12
+ export async function createWebrtcNode() {
13
+ // Loaded here, not at module top, so importing B2B_PROTOCOL/dialDirect never pulls in the WebRTC stack.
14
+ const [{ createLibp2p }, { webSockets }, { webRTC }, { circuitRelayTransport }, { noise }, { yamux }, { identify }] = await Promise.all([
15
+ import("libp2p"),
16
+ import("@libp2p/websockets"),
17
+ import("@libp2p/webrtc"),
18
+ import("@libp2p/circuit-relay-v2"),
19
+ import("@chainsafe/libp2p-noise"),
20
+ import("@chainsafe/libp2p-yamux"),
21
+ import("@libp2p/identify"),
22
+ ]);
23
+ return createLibp2p({
24
+ addresses: { listen: ["/p2p-circuit", "/webrtc"] },
25
+ transports: [webSockets(), webRTC(), circuitRelayTransport()],
26
+ connectionEncrypters: [noise()],
27
+ streamMuxers: [yamux()],
28
+ services: { identify: identify() },
29
+ connectionGater: { denyDialMultiaddr: () => false },
30
+ });
31
+ }
32
+ /** Reserve a relay slot, accept direct messages, and return our dialable /webrtc address. */
33
+ export async function startDirectListener(relayAddr, onMessage) {
34
+ const node = await createWebrtcNode();
35
+ await node.handle(B2B_PROTOCOL, (stream) => {
36
+ void (async () => {
37
+ onMessage(new TextDecoder().decode(await readFrame(stream)));
38
+ await stream.close().catch(() => { });
39
+ })();
40
+ });
41
+ await node.dial(multiaddr(relayAddr)); // reserve a relay slot so we're reachable for the handshake
42
+ return { node, addr: await waitForWebrtcAddr(node) };
43
+ }
44
+ /** Connect to a peer's /webrtc address (handshake brokered by the relay) and send directly. */
45
+ export async function dialDirect(node, targetAddr, text) {
46
+ const stream = await node.dialProtocol(multiaddr(targetAddr), B2B_PROTOCOL);
47
+ sendFrame(stream, new TextEncoder().encode(text));
48
+ await new Promise((r) => setTimeout(r, 200));
49
+ await stream.close().catch(() => { });
50
+ }
@@ -0,0 +1,28 @@
1
+ import { type WireEnvelope, type MailboxAckRequest } from "./protocol";
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>;
6
+ /**
7
+ * The mesh client: one WebRTC-capable node that registers its presence with the helper, receives direct
8
+ * (peer-to-peer) envelopes AND polls the mailbox, and sends DIRECT-FIRST — dialing the recipient
9
+ * peer-to-peer when they're online (helper only brokers the handshake), falling back to the helper's
10
+ * store-and-forward mailbox when they're not. The helper becomes optional for live chat.
11
+ */
12
+ export declare class MeshClient {
13
+ private readonly node;
14
+ private readonly helperAddr;
15
+ private readonly ref;
16
+ private readonly refresh;
17
+ private readonly poll;
18
+ private readonly reRegister;
19
+ private constructor();
20
+ static start(helperAddr: string, keys: string[], onEnvelope: (e: WireEnvelope) => void, pollMs?: number, signer?: RegistrationSigner, receiveDurably?: (e: WireEnvelope) => Promise<boolean>): Promise<MeshClient>;
21
+ /** Replace the active label set (called on a topic-rotation rollover) and register the new labels now. The
22
+ * signer authenticates the public-slot labels among them (Tier 2 Stage 3). */
23
+ setKeys(keys: string[], signer?: RegistrationSigner, receiveDurably?: (e: WireEnvelope) => Promise<boolean>): void;
24
+ /** Send DIRECT-FIRST: dial the recipient peer-to-peer if present, else store in the mailbox. Resolves
25
+ * `true` if delivered/stored, `false` if neither path could take it (helper unreachable → caller queues). */
26
+ send(env: WireEnvelope): Promise<boolean>;
27
+ stop(): Promise<void>;
28
+ }