@koralabs/handle-chat-sdk 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/assets/libsignal_bg.wasm +0 -0
  2. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.d.ts +20 -0
  3. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.js +85 -0
  4. package/lib/src/chat/ChatService.d.ts +13 -9
  5. package/lib/src/chat/ChatService.js +384 -105
  6. package/lib/src/chat/anchor.d.ts +2 -2
  7. package/lib/src/chat/anchor.js +2 -2
  8. package/lib/src/chat/blob.d.ts +14 -0
  9. package/lib/src/chat/blob.js +107 -6
  10. package/lib/src/chat/chainDirectory.d.ts +14 -19
  11. package/lib/src/chat/chainDirectory.js +73 -31
  12. package/lib/src/chat/demeter.d.ts +3 -0
  13. package/lib/src/chat/demeter.js +8 -0
  14. package/lib/src/chat/directory.d.ts +12 -2
  15. package/lib/src/chat/directory.js +23 -0
  16. package/lib/src/chat/guardian.d.ts +6 -4
  17. package/lib/src/chat/guardian.js +17 -5
  18. package/lib/src/chat/guardianHistory.d.ts +3 -0
  19. package/lib/src/chat/guardianHistory.js +36 -0
  20. package/lib/src/chat/httpRateLimit.d.ts +5 -0
  21. package/lib/src/chat/httpRateLimit.js +54 -0
  22. package/lib/src/chat/identity.d.ts +1 -1
  23. package/lib/src/chat/identity.js +8 -2
  24. package/lib/src/chat/invite.d.ts +7 -0
  25. package/lib/src/chat/invite.js +18 -0
  26. package/lib/src/chat/mesh/client.d.ts +6 -3
  27. package/lib/src/chat/mesh/client.js +89 -13
  28. package/lib/src/chat/mesh/protocol.d.ts +35 -0
  29. package/lib/src/chat/mesh/protocol.js +11 -0
  30. package/lib/src/chat/publish.d.ts +1 -1
  31. package/lib/src/chat/publish.js +13 -2
  32. package/lib/src/chat/sessionStore.d.ts +10 -1
  33. package/lib/src/chat/sessionStore.js +52 -7
  34. package/lib/src/chat/transport.d.ts +2 -2
  35. package/lib/src/chat/transport.js +66 -6
  36. package/lib/src/signal/SignalEngine.d.ts +5 -0
  37. package/lib/src/signal/SignalEngine.js +10 -0
  38. package/package.json +3 -2
@@ -4,8 +4,8 @@
4
4
  * `poc/`'s `ChainAnchorStore` codec. Pure data — no chain or crypto deps, so it unit-tests in node.
5
5
  *
6
6
  * The bundle is `SignalEngine.createBundle()` output (idPub + signed pre-key + Kyber, self-signed by the
7
- * identity key). What binds it to the handle is provenance: the anchor is published from the handle
8
- * owner's address, so only the owner can write it. (Resolve verifies that — see the ChainAnchorStore.)
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
9
  */
10
10
  export declare const ANCHOR_METADATA_LABEL = 7368n;
11
11
  /** Build the metadata value for a handle's bundle: `[handle, ...hex chunks]`. */
@@ -4,8 +4,8 @@
4
4
  * `poc/`'s `ChainAnchorStore` codec. Pure data — no chain or crypto deps, so it unit-tests in node.
5
5
  *
6
6
  * The bundle is `SignalEngine.createBundle()` output (idPub + signed pre-key + Kyber, self-signed by the
7
- * identity key). What binds it to the handle is provenance: the anchor is published from the handle
8
- * owner's address, so only the owner can write it. (Resolve verifies that — see the ChainAnchorStore.)
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
9
  */
10
10
  export const ANCHOR_METADATA_LABEL = 7368n;
11
11
  /** Cardano metadata strings cap at 64 bytes; hex is ASCII so 64 chars = 64 bytes. */
@@ -35,7 +35,21 @@ export declare const isBlobRef: (c: ContentMessage) => boolean;
35
35
  export declare const isBlobChunk: (c: ContentMessage) => boolean;
36
36
  export declare const isBlobPart: (c: ContentMessage) => boolean;
37
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
+ }
38
47
  export declare class BlobAssembler {
39
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;
40
54
  accept(c: ContentMessage): Promise<ContentMessage | null>;
41
55
  }
@@ -78,31 +78,132 @@ export const isBlobRef = (c) => c.mime === BLOB_REF_MIME;
78
78
  export const isBlobChunk = (c) => c.mime === BLOB_CHUNK_MIME;
79
79
  export const isBlobPart = (c) => isBlobRef(c) || isBlobChunk(c);
80
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;
81
94
  export class BlobAssembler {
82
95
  #pending = new Map();
83
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
+ }
84
176
  async accept(c) {
177
+ this.#used = true;
85
178
  const refMeta = parseBlobRef(c);
86
179
  if (refMeta) {
87
180
  // Reject implausible refs up front (anti-DoS): bounded chunk count + declared size.
88
- if (!Number.isInteger(refMeta.chunks) || refMeta.chunks < 1 || refMeta.chunks > MAX_CHUNKS)
89
- return null;
90
- if (!Number.isInteger(refMeta.size) || refMeta.size < 0 || refMeta.size > MAX_BLOB_SIZE)
181
+ if (!validMeta(refMeta))
91
182
  return null;
92
183
  const e = this.#pending.get(refMeta.ref) ?? this.#fresh(refMeta.ref);
93
- e.meta = refMeta;
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();
94
195
  return this.#tryComplete(refMeta.ref);
95
196
  }
96
197
  if (isBlobChunk(c)) {
97
198
  const ref = c.meta?.ref;
98
199
  const i = Number(c.meta?.i);
99
- if (!ref || !Number.isInteger(i) || i < 0 || i >= MAX_CHUNKS || c.body.length > CHUNK_SIZE)
200
+ if (!validRef(ref) || !Number.isInteger(i) || i < 0 || i >= MAX_CHUNKS || c.body.length > CHUNK_SIZE)
100
201
  return null;
101
202
  const e = this.#pending.get(ref) ?? this.#fresh(ref);
102
203
  if (e.meta && i >= e.meta.chunks)
103
204
  return null; // index past the declared count
104
205
  if (!e.parts.has(i)) {
105
- e.parts.set(i, c.body);
206
+ e.parts.set(i, c.body.slice());
106
207
  e.bytes += c.body.length;
107
208
  this.#totalBytes += c.body.length;
108
209
  this.#evict();
@@ -1,29 +1,24 @@
1
- /**
2
- * Chain-as-directory resolution (read side): given a handle, find its published Signal key-bundle on
3
- * Cardano. Fetch-only — Handle API for handle→address, Blockfrost for the address's anchor metadata —
4
- * so it stays browser-light (no @cardano-sdk in the app bundle). The bundle is bound to the handle by
5
- * provenance: it sits in a tx from the handle's own resolved address.
6
- *
7
- * Publish (the write side) is intentionally NOT here — building a Cardano tx in the browser means
8
- * bundling @cardano-sdk (heavy) or a backend tx-builder; that's an open architecture decision.
9
- */
1
+ import { type ChainNetwork } from "./demeter";
2
+ /** Server-side chain resolution. The provider key must never be shipped to a browser. */
10
3
  export interface ChainAnchorConfig {
11
- env: "preview" | "preprod" | "mainnet";
12
- blockfrostApiKey: string;
13
- /** Injectable for tests; defaults to global fetch. */
4
+ env: ChainNetwork;
5
+ demeterApiKey: string;
14
6
  fetchImpl?: typeof fetch;
7
+ /** Must validate the address and its payment credential using a Cardano address library. */
8
+ isKeyOwnerAddress?: (address: string) => boolean;
15
9
  }
16
10
  export declare class ChainAnchorStore {
17
11
  private readonly apiBase;
18
12
  private readonly bfBase;
19
- private readonly blockfrostApiKey;
13
+ private readonly key;
20
14
  private readonly fetchImpl;
15
+ private readonly isKeyOwnerAddress?;
21
16
  constructor(cfg: ChainAnchorConfig);
22
- /** Resolve a handle's published bundle from chain (newest anchor wins), or null if none. */
23
- resolve(handle: string, max?: number): Promise<Uint8Array | null>;
24
- /** Resolve by a known address (skips the Handle API lookup). */
25
- resolveByAddress(address: string, handle: string, max?: number): Promise<Uint8Array | null>;
26
- /** handle → the address its NFT resolves to (where its owner publishes the anchor). */
27
- private handleAddress;
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;
28
23
  private bf;
29
24
  }
@@ -1,51 +1,93 @@
1
1
  import { decodeAnchorMetadata, ANCHOR_METADATA_LABEL } from "./anchor.js";
2
+ import { providerFetch } from "./httpRateLimit.js";
3
+ import { chainNetwork, demeterBase } from "./demeter.js";
2
4
  export class ChainAnchorStore {
3
5
  apiBase;
4
6
  bfBase;
5
- blockfrostApiKey;
7
+ key;
6
8
  fetchImpl;
9
+ isKeyOwnerAddress;
7
10
  constructor(cfg) {
8
- this.apiBase = `https://${cfg.env === "mainnet" ? "" : `${cfg.env}.`}api.handle.me`;
9
- this.bfBase = `https://cardano-${cfg.env}.blockfrost.io/api/v0`;
10
- this.blockfrostApiKey = cfg.blockfrostApiKey;
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;
11
15
  this.fetchImpl = cfg.fetchImpl ?? fetch;
16
+ this.isKeyOwnerAddress = cfg.isKeyOwnerAddress;
12
17
  }
13
- /** Resolve a handle's published bundle from chain (newest anchor wins), or null if none. */
14
- async resolve(handle, max = 25) {
15
- const address = await this.handleAddress(handle);
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);
16
21
  if (!address)
17
22
  return null;
18
- return this.resolveByAddress(address, handle, max);
23
+ return this.resolveOwnerAddress(address, `$${handle.replace(/^\$/, "")}`);
19
24
  }
20
- /** Resolve by a known address (skips the Handle API lookup). */
21
- async resolveByAddress(address, handle, max = 25) {
22
- const txs = (await this.bf(`/addresses/${address}/transactions?order=desc&count=${max}`));
23
- for (const { tx_hash } of txs) {
24
- const md = (await this.bf(`/txs/${tx_hash}/metadata`));
25
- const entry = md.find((m) => String(m.label) === String(ANCHOR_METADATA_LABEL));
26
- if (!entry)
27
- continue;
28
- const decoded = decodeAnchorMetadata(entry.json_metadata);
29
- if (decoded && decoded.handle === handle)
30
- return decoded.bundle;
31
- }
32
- return null;
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(/^\$/, "")}`);
33
31
  }
34
- /** handle → the address its NFT resolves to (where its owner publishes the anchor). */
35
- async handleAddress(handle) {
32
+ async ownerAddress(handle) {
36
33
  const name = handle.replace(/^\$/, "");
37
- const res = await this.fetchImpl(`${this.apiBase}/handles/${name}`);
38
- if (!res.ok)
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)
39
38
  return null;
40
- const data = (await res.json());
41
- return data.resolved_addresses?.ada ?? 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");
42
86
  }
43
87
  async bf(path) {
44
- const res = await this.fetchImpl(`${this.bfBase}${path}`, {
45
- headers: { project_id: this.blockfrostApiKey },
46
- });
88
+ const res = await providerFetch(this.fetchImpl, `${this.bfBase}${path}`, { headers: { "dmtr-api-key": this.key } });
47
89
  if (!res.ok)
48
- throw new Error(`Blockfrost ${path}: ${res.status}`);
90
+ throw new Error(`Demeter: ${res.status}`);
49
91
  return res.json();
50
92
  }
51
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
+ }
@@ -1,12 +1,22 @@
1
1
  /**
2
2
  * The anchor directory seam: publish/look up a handle's published Signal bundle.
3
- * DEMO impl = localStorage (shared across same-origin tabs). Production swaps in the on-chain
4
- * `ChainAnchorStore` (Cardano preview) — same interface.
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
5
  */
6
6
  export interface Directory {
7
7
  publish(handle: string, bundle: Uint8Array): void;
8
8
  resolve(handle: string): Uint8Array | null;
9
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
+ }
10
20
  export declare class LocalStorageDirectory implements Directory {
11
21
  private key;
12
22
  publish(handle: string, bundle: Uint8Array): void;
@@ -1,4 +1,27 @@
1
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
+ }
2
25
  const bytesToHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
3
26
  export class LocalStorageDirectory {
4
27
  key(handle) {
@@ -1,11 +1,12 @@
1
1
  /**
2
2
  * The guardian protocol — Social Secret Recovery (secrets.handle.me) riding on chat. chat is the MEDIUM:
3
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. The `shard` here is OPAQUE to chat —
5
- * a guardian holds whatever bytes the principal hands it and returns them verbatim on an approved recovery.
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.
6
7
  *
7
- * Flow: principal → `guardian-invite` (with a shard) → guardian → `guardian-consent` (accept/decline).
8
- * Later, recovering user → `recovery-notify` → each guardian → `approval-coordination` (returning the shard).
8
+ * Flow: principal → `guardian-invite` → guardian → `guardian-consent` (accept/decline).
9
+ * Later, recovering user → `recovery-notify` → guardian → `approval-coordination`.
9
10
  * Built on the typed-message foundation — each payload is `application/vnd.handle.<kind>+json`, so it's
10
11
  * E2E-encrypted for free and a relay sees only ciphertext.
11
12
  */
@@ -28,6 +29,7 @@ export interface RecoveryNotify {
28
29
  secretRef: string;
29
30
  label?: string;
30
31
  session?: string;
32
+ continuation?: string;
31
33
  }
32
34
  export interface ApprovalCoordination {
33
35
  secretRef: string;
@@ -1,11 +1,12 @@
1
1
  /**
2
2
  * The guardian protocol — Social Secret Recovery (secrets.handle.me) riding on chat. chat is the MEDIUM:
3
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. The `shard` here is OPAQUE to chat —
5
- * a guardian holds whatever bytes the principal hands it and returns them verbatim on an approved recovery.
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.
6
7
  *
7
- * Flow: principal → `guardian-invite` (with a shard) → guardian → `guardian-consent` (accept/decline).
8
- * Later, recovering user → `recovery-notify` → each guardian → `approval-coordination` (returning the shard).
8
+ * Flow: principal → `guardian-invite` → guardian → `guardian-consent` (accept/decline).
9
+ * Later, recovering user → `recovery-notify` → guardian → `approval-coordination`.
9
10
  * Built on the typed-message foundation — each payload is `application/vnd.handle.<kind>+json`, so it's
10
11
  * E2E-encrypted for free and a relay sees only ciphertext.
11
12
  */
@@ -31,8 +32,19 @@ export function parseGuardian(c) {
31
32
  catch {
32
33
  return null;
33
34
  }
34
- if (value === null || typeof value !== "object")
35
+ if (value === null || typeof value !== "object" || Array.isArray(value))
35
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
+ }
36
48
  return { kind, value };
37
49
  }
38
50
  const invitesFor = (thread, secretRef) => thread.flatMap((m) => {
@@ -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
+ }
@@ -20,7 +20,7 @@ export type SignData = (addressHex: string, payloadHex: string) => Promise<DataS
20
20
  * address. Re-signing reproduces it (deterministic wallets), so nothing is stored. The handle is folded
21
21
  * in later by {@link deriveIdentity}, so one signature covers every handle the wallet controls.
22
22
  */
23
- export declare function deriveSeedFromWallet(signData: SignData, stakeAddressHex: string): Promise<Uint8Array>;
23
+ export declare function deriveSeedFromWallet(signData: SignData, stakeAddressHex: string, verifyDeterministic?: boolean): Promise<Uint8Array>;
24
24
  /**
25
25
  * Enroll-time guard: a wallet that randomizes its signatures can't reproduce the identity on a later
26
26
  * visit, silently orphaning every session. Sign the same message twice and fail loudly if they differ.
@@ -35,10 +35,16 @@ const utf8ToHex = (s) => Array.from(enc.encode(s), (b) => b.toString(16).padStar
35
35
  * address. Re-signing reproduces it (deterministic wallets), so nothing is stored. The handle is folded
36
36
  * in later by {@link deriveIdentity}, so one signature covers every handle the wallet controls.
37
37
  */
38
- export async function deriveSeedFromWallet(signData, stakeAddressHex) {
39
- const { signature } = await signData(stakeAddressHex, utf8ToHex(IDENTITY_MESSAGE));
38
+ export async function deriveSeedFromWallet(signData, stakeAddressHex, verifyDeterministic = false) {
39
+ const payload = utf8ToHex(IDENTITY_MESSAGE);
40
+ const { signature } = await signData(stakeAddressHex, payload);
40
41
  if (!signature)
41
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
+ }
42
48
  return hexToBytes(signature);
43
49
  }
44
50
  /**