aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/marmot.ts
blob: ba1b02f5dddd96b798a9c9543ce6f294325bb727 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/**
 * Marmot protocol integration: MarmotClient setup, storage backends,
 * signer adapter, and network adapter.
 *
 * Uses @internet-privacy/marmot-ts which wraps ts-mls with Nostr-specific
 * MIP-00/01/02/03 protocol handling.
 */

import type { EventTemplate, NostrEvent, UnsignedEvent } from "nostr-tools/pure";
import { finalizeEvent } from "nostr-tools/pure";
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
import { SimplePool } from "nostr-tools/pool";
import { Relay } from "nostr-tools/relay";
import {
  MarmotClient,
  InviteReader,
} from "@internet-privacy/marmot-ts/client";
import { KeyPackageStore } from "@internet-privacy/marmot-ts/store";
import type {
  NostrNetworkInterface,
  PublishResponse,
  Subscribable,
  GroupStateStoreBackend,
  SerializedClientState,
  StoredKeyPackage,
} from "@internet-privacy/marmot-ts";
import { ensureSigner } from "$lib/nip07";
import { encrypt as nip44Encrypt, decrypt as nip44Decrypt, u as nip44u } from "$lib/nip44";
import { PUBLIC_DM_RELAYS } from "$env/static/public";

/** Key-value store interface matching marmot-ts's KeyValueStoreBackend */
interface KVStore<T> {
  getItem(key: string): Promise<T | null>;
  setItem(key: string, value: T): Promise<T>;
  removeItem(key: string): Promise<void>;
  clear(): Promise<void>;
  keys(): Promise<string[]>;
}

const DM_RELAYS = PUBLIC_DM_RELAYS.split(",");
const pool = new SimplePool();

// ---------------------------------------------------------------------------
// EventSigner adapter — bridges our ensureSigner/NIP-07 to applesauce interface
// ---------------------------------------------------------------------------

class CoinosEventSigner {
  private pubkey: string;

  constructor(pubkey: string) {
    this.pubkey = pubkey;
  }

  getPublicKey(): string {
    return this.pubkey;
  }

  async signEvent(draft: EventTemplate | UnsignedEvent): Promise<NostrEvent> {
    const sk = await ensureSigner(this.pubkey);
    if (sk === null) {
      return (window as any).nostr.signEvent(draft);
    }
    return finalizeEvent(draft as any, sk);
  }

  nip44 = {
    encrypt: async (pubkey: string, plaintext: string): Promise<string> => {
      const sk = await ensureSigner(this.pubkey);
      if (sk === null) {
        return (window as any).nostr.nip44.encrypt(pubkey, plaintext);
      }
      const skHex = bytesToHex(sk);
      const ckey = nip44u.getConversationKey(skHex, pubkey);
      return nip44Encrypt(plaintext, ckey);
    },
    decrypt: async (pubkey: string, ciphertext: string): Promise<string> => {
      const sk = await ensureSigner(this.pubkey);
      if (sk === null) {
        return (window as any).nostr.nip44.decrypt(pubkey, ciphertext);
      }
      const skHex = bytesToHex(sk);
      const ckey = nip44u.getConversationKey(skHex, pubkey);
      return nip44Decrypt(ciphertext, ckey);
    },
  };
}

// ---------------------------------------------------------------------------
// NostrNetworkInterface adapter — bridges SimplePool to marmot-ts
// ---------------------------------------------------------------------------

class CoinosNostrNetwork implements NostrNetworkInterface {
  async publish(relays: string[], event: NostrEvent): Promise<Record<string, PublishResponse>> {
    const results: Record<string, PublishResponse> = {};
    await Promise.allSettled(
      relays.map(async (url) => {
        try {
          const relay = await Relay.connect(url);
          await relay.publish(event);
          relay.close();
          results[url] = { from: url, ok: true };
        } catch (e: any) {
          results[url] = { from: url, ok: false, message: e?.message };
        }
      }),
    );
    return results;
  }

  async request(relays: string[], filters: any): Promise<NostrEvent[]> {
    if (Array.isArray(filters)) {
      return pool.querySync(relays, filters[0], ...filters.slice(1)) as any;
    }
    return pool.querySync(relays, filters) as any;
  }

  subscription(relays: string[], filters: any): Subscribable<NostrEvent> {
    const filterArr = Array.isArray(filters) ? filters : [filters];

    return {
      subscribe(observer) {
        const subs: (() => void)[] = [];

        for (const url of relays) {
          Relay.connect(url)
            .then((relay) => {
              const sub = relay.subscribe(filterArr, {
                onevent: (event) => observer.next?.(event as NostrEvent),
                oneose: () => {},
              });
              subs.push(() => sub.close());
            })
            .catch((e) => observer.error?.(e));
        }

        return {
          unsubscribe() {
            subs.forEach((close) => close());
          },
        };
      },
    };
  }

  async getUserInboxRelays(pubkey: string): Promise<string[]> {
    // Fetch kind 10050 (NIP-17 inbox relays) from discovery relays, fall back to DM_RELAYS
    const discoveryRelays = [
      ...DM_RELAYS,
      "wss://relay.damus.io",
      "wss://relay.primal.net",
      "wss://nos.lol",
      "wss://purplepag.es",
    ];
    try {
      const events = await pool.querySync(discoveryRelays, {
        kinds: [10050],
        authors: [pubkey],
        limit: 1,
      });
      if (events.length > 0) {
        const relays = events[0].tags
          .filter((t: string[]) => t[0] === "relay")
          .map((t: string[]) => t[1]);
        if (relays.length > 0) return relays;
      }
    } catch {}
    return DM_RELAYS;
  }
}

// ---------------------------------------------------------------------------
// IndexedDB-backed KeyValueStoreBackend
// ---------------------------------------------------------------------------

const IDB_VERSION = 1;
const STORE_NAMES = ["group-state", "key-packages", "invites-received", "invites-unread", "invites-seen"];

let _idbPubkey: string | null = null;
let _idbCache: IDBDatabase | null = null;

function openMarmotDb(pubkey?: string): Promise<IDBDatabase> {
  const pk = pubkey || _idbPubkey || "default";
  if (_idbCache && _idbPubkey === pk) return Promise.resolve(_idbCache);

  return new Promise((resolve, reject) => {
    const dbName = `coinos-marmot-${pk.slice(0, 16)}`;
    const req = indexedDB.open(dbName, IDB_VERSION);
    req.onupgradeneeded = () => {
      const db = req.result;
      for (const name of STORE_NAMES) {
        if (!db.objectStoreNames.contains(name)) db.createObjectStore(name);
      }
    };
    req.onsuccess = () => {
      _idbPubkey = pk;
      _idbCache = req.result;
      resolve(req.result);
    };
    req.onerror = () => reject(req.error);
  });
}

/** Generic IndexedDB key-value backend for marmot-ts stores. */
function createIDBKeyValueStore<T>(storeName: string): KVStore<T> {
  return {
    async getItem(key: string): Promise<T | null> {
      const db = await openMarmotDb();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(storeName, "readonly");
        const req = tx.objectStore(storeName).get(key);
        req.onsuccess = () => resolve(req.result ?? null);
        req.onerror = () => reject(req.error);
      });
    },
    async setItem(key: string, value: T): Promise<T> {
      const db = await openMarmotDb();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(storeName, "readwrite");
        tx.objectStore(storeName).put(value, key);
        tx.oncomplete = () => resolve(value);
        tx.onerror = () => reject(tx.error);
      });
    },
    async removeItem(key: string): Promise<void> {
      const db = await openMarmotDb();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(storeName, "readwrite");
        tx.objectStore(storeName).delete(key);
        tx.oncomplete = () => resolve();
        tx.onerror = () => reject(tx.error);
      });
    },
    async clear(): Promise<void> {
      const db = await openMarmotDb();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(storeName, "readwrite");
        tx.objectStore(storeName).clear();
        tx.oncomplete = () => resolve();
        tx.onerror = () => reject(tx.error);
      });
    },
    async keys(): Promise<string[]> {
      const db = await openMarmotDb();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(storeName, "readonly");
        const req = tx.objectStore(storeName).getAllKeys();
        req.onsuccess = () => resolve(req.result.map(String));
        req.onerror = () => reject(req.error);
      });
    },
  };
}

// ---------------------------------------------------------------------------
// GroupStateStoreBackend (uses Uint8Array keys, needs special handling)
// ---------------------------------------------------------------------------

class IDBGroupStateBackend implements GroupStateStoreBackend {
  private storeName = "group-state";

  private keyToStr(groupId: Uint8Array): string {
    return bytesToHex(groupId);
  }

  async get(groupId: Uint8Array): Promise<SerializedClientState | null> {
    const db = await openMarmotDb();
    return new Promise((resolve, reject) => {
      const tx = db.transaction(this.storeName, "readonly");
      const req = tx.objectStore(this.storeName).get(this.keyToStr(groupId));
      req.onsuccess = () => {
        const result = req.result;
        if (!result) return resolve(null);
        resolve(result instanceof Uint8Array ? result : new Uint8Array(result));
      };
      req.onerror = () => reject(req.error);
    });
  }

  async set(groupId: Uint8Array, stateBytes: SerializedClientState): Promise<void> {
    const db = await openMarmotDb();
    return new Promise((resolve, reject) => {
      const tx = db.transaction(this.storeName, "readwrite");
      tx.objectStore(this.storeName).put(stateBytes, this.keyToStr(groupId));
      tx.oncomplete = () => resolve();
      tx.onerror = () => reject(tx.error);
    });
  }

  async remove(groupId: Uint8Array): Promise<void> {
    const db = await openMarmotDb();
    return new Promise((resolve, reject) => {
      const tx = db.transaction(this.storeName, "readwrite");
      tx.objectStore(this.storeName).delete(this.keyToStr(groupId));
      tx.oncomplete = () => resolve();
      tx.onerror = () => reject(tx.error);
    });
  }

  async list(): Promise<Uint8Array[]> {
    const db = await openMarmotDb();
    return new Promise((resolve, reject) => {
      const tx = db.transaction(this.storeName, "readonly");
      const req = tx.objectStore(this.storeName).getAllKeys();
      req.onsuccess = () => resolve(req.result.map((k) => hexToBytes(String(k))));
      req.onerror = () => reject(req.error);
    });
  }
}

// ---------------------------------------------------------------------------
// Singleton MarmotClient + InviteReader
// ---------------------------------------------------------------------------

let _client: MarmotClient | null = null;
let _inviteReader: InviteReader | null = null;
let _currentPubkey: string | null = null;
const _network = new CoinosNostrNetwork();

export function getMarmotClient(pubkey: string): MarmotClient {
  if (_client && _currentPubkey === pubkey) return _client;

  // Tear down old client if user changed
  _client = null;
  _inviteReader = null;
  _currentPubkey = pubkey;
  _idbPubkey = pubkey;
  _idbCache = null;

  const signer = new CoinosEventSigner(pubkey);
  const groupStateBackend = new IDBGroupStateBackend();
  const keyPackageBackend = createIDBKeyValueStore<StoredKeyPackage>("key-packages") as any;
  const keyPackageStore = new KeyPackageStore(keyPackageBackend);

  _client = new MarmotClient({
    signer,
    groupStateBackend,
    keyPackageStore,
    network: _network,
  });

  return _client;
}

export function getInviteReader(pubkey: string): InviteReader {
  if (_inviteReader && _currentPubkey === pubkey) return _inviteReader;

  // Ensure client is initialized
  getMarmotClient(pubkey);

  const signer = new CoinosEventSigner(pubkey);
  const store = {
    received: createIDBKeyValueStore("invites-received"),
    unread: createIDBKeyValueStore("invites-unread"),
    seen: createIDBKeyValueStore("invites-seen"),
  } as any;

  _inviteReader = new InviteReader({ signer, store });
  return _inviteReader;
}

export function getNetwork(): CoinosNostrNetwork {
  return _network;
}

export { DM_RELAYS };