cautpartener / client / src / core / rendezvous.ts
  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
/**
 * One-shot offline contact exchange over a rendezvous mailbox room
 * (docs/PROTOCOL.md §2: inviteSecret = random 32 B).
 *
 * The invite link carries the secret plus the creator's pub:
 *   https://cautpartener.ro/#/add/<inviteSecret>.<creatorPub>
 * Both halves are 43-char b64url (32 bytes). The room is the mailbox room of
 * RoomCrypto.create(inviteSecret, APP_SALT) — deliberately NO OrbitDB here:
 * MailboxClient deposit/replay is the whole transport, and payloads are the
 * room's mbxCipher()-sealed contact cards, so only invite-secret holders can
 * read (or forge-into) the exchange. The mailbox node sees opaque blobs.
 *
 * Wire envelope (inside the seal): JSON { v:1, kind:"card", card } — sealed
 * with a random IV, so re-deposits are distinct blobs; dedup happens on the
 * reading side per (pub, xPub). Cards with an invalid cert are dropped
 * silently (receiver-rules discipline).
 *
 * Pending invites (creator side) persist under nsKey("pending-invites") and
 * TTL-expire after the mailbox descriptor's ttlHours — once the node evicted
 * the room, the link is honestly dead.
 */

import { APP_SALT, nsKey, RELAY_DEFAULTS, RuntimeLimits } from "../config";
import { fromB64, fromB64url, randomBytes, RoomCrypto, toB64url, type AtRestCipher, type Bytes } from "../lib/crypto";
import type { MailboxConfig } from "../lib/descriptor";
import { MailboxClient } from "../lib/mailbox";
import { appMailboxAuth } from "./app-mailbox-auth";
import { RelayState } from "../main";
import { isValidCard, verifyContactCert, type ContactCard } from "./contacts";

const utf8 = (s: string): Bytes => new TextEncoder().encode(s) as Bytes;
const td = new TextDecoder();

export const INVITE_BASE = "https://cautpartener.ro/#/add/";
const B64URL_32 = /^[A-Za-z0-9_-]{43}$/;

export interface InviteRef {
  secret: string;
  creatorPub: string;
}

export function newInviteSecret(): string {
  return toB64url(randomBytes(32));
}

export function inviteToken(secret: string, creatorPub: string): string {
  return `${secret}.${creatorPub}`;
}

export function inviteLink(secret: string, creatorPub: string): string {
  return INVITE_BASE + inviteToken(secret, creatorPub);
}

/** Parse "<secret>.<creatorPub>" — both 43-char b64url decoding to 32 bytes. */
export function parseInviteToken(token: string): InviteRef | null {
  const parts = token.split(".");
  if (parts.length !== 2) return null;
  const [secret, creatorPub] = parts;
  if (!B64URL_32.test(secret) || !B64URL_32.test(creatorPub)) return null;
  try {
    if (fromB64url(secret).length !== 32 || fromB64url(creatorPub).length !== 32) return null;
  } catch {
    return null;
  }
  return { secret, creatorPub };
}

/**
 * Extract an invite token from arbitrary pasted/scanned text: the full link
 * (any origin, e.g. a self-hosted mirror), a "#/add/…" fragment or the bare
 * token itself.
 */
export function extractInviteToken(text: string): InviteRef | null {
  const s = text.trim();
  const at = s.indexOf("#/add/");
  const candidate = at >= 0 ? s.slice(at + "#/add/".length) : s;
  return parseInviteToken(candidate.split(/[?#\s]/, 1)[0]);
}

/** Live mailbox endpoint (descriptor-refined RelayState, baked fallback). */
export function mailboxConfig(): MailboxConfig | null {
  return RelayState.config.mailbox ?? RELAY_DEFAULTS.mailbox ?? null;
}

// ---- the rendezvous room -----------------------------------------------------

const PAGE_LIMIT = 100;
const MAX_PAGES = 50;

export class Rendezvous {
  #client: MailboxClient;
  #cipher: AtRestCipher;

  private constructor(client: MailboxClient, cipher: AtRestCipher) {
    this.#client = client;
    this.#cipher = cipher;
  }

  /** Derive the room from the invite secret; null when no mailbox endpoint. */
  static async open(secret: string, mailbox: MailboxConfig | null = mailboxConfig()): Promise<Rendezvous | null> {
    if (!mailbox) return null;
    const rc = await RoomCrypto.create(secret, APP_SALT);
    const mbxRoomId = await rc.mailboxRoomId();
    const client = new MailboxClient(mailbox.baseUrl, mbxRoomId, appMailboxAuth(mailbox.credsUrl));
    return new Rendezvous(client, await rc.mbxCipher());
  }

  /** Seal + deposit one contact card. True on success (dedup counts as ok). */
  async depositCard(card: ContactCard): Promise<boolean> {
    const sealed = await this.#cipher.seal(utf8(JSON.stringify({ v: 1, kind: "card", card })));
    const r = await this.#client.deposit(sealed);
    return r.ok;
  }

  /**
   * Replay the whole room and return every VALID card: envelope shape ok,
   * cert verified (Ed25519 over the §3 string, name included), deduped by
   * (pub, xPub) — the last deposit wins per pair. Invalid/undecryptable blobs
   * are dropped silently.
   *
   * §2b ambiguity refusal: when the room holds ≥2 DISTINCT xPubs for the same
   * pub, the reader refuses to pick one — those pubs land in `ambiguous` and
   * NONE of their cards are returned. `partial` is true when a later replay
   * page failed after ≥1 page succeeded (history may be incomplete — callers
   * must not treat the result as the room's full truth, e.g. no heal
   * re-deposits). Null = the mailbox could not be reached at all (honest
   * "unknown", distinct from an empty room).
   */
  async fetchCards(): Promise<FetchResult | null> {
    const byKey = new Map<string, ContactCard>();
    const xPubsByPub = new Map<string, Set<string>>();
    let cursor: string | null = null;
    let reached = false;
    let partial = false;
    for (let page = 0; page < MAX_PAGES; page++) {
      const r = await this.#client.replay(cursor, PAGE_LIMIT);
      if (!r.ok) {
        if (!reached) return null;
        partial = true; // a later page failed after ≥1 success
        break;
      }
      reached = true;
      for (const m of r.page.messages) {
        const card = await this.#decodeCard(m.payload);
        if (card) {
          byKey.set(`${card.pub}|${card.xPub}`, card);
          let set = xPubsByPub.get(card.pub);
          if (!set) xPubsByPub.set(card.pub, (set = new Set()));
          set.add(card.xPub);
        }
      }
      if (r.page.messages.length > 0) cursor = r.page.messages[r.page.messages.length - 1].seq;
      if (!r.page.hasMore) break;
    }
    const ambiguous = [...xPubsByPub.entries()].filter(([, xs]) => xs.size > 1).map(([pub]) => pub);
    const ambiguousSet = new Set(ambiguous);
    return { cards: [...byKey.values()].filter((c) => !ambiguousSet.has(c.pub)), ambiguous, partial };
  }

  async #decodeCard(payloadB64: string): Promise<ContactCard | null> {
    try {
      const opened = await this.#cipher.open(fromB64(payloadB64));
      if (!opened) return null;
      const env = JSON.parse(td.decode(opened)) as { v?: unknown; kind?: unknown; card?: unknown };
      // isValidCard rejects unsanitized/oversized names at the wire; the cert
      // is then verified over the card's LITERAL name (§3)
      if (env.v !== 1 || env.kind !== "card" || !isValidCard(env.card)) return null;
      const card = env.card;
      if (!(await verifyContactCert(card.pub, card.xPub, card.xSig, card.name))) return null;
      return { pub: card.pub, xPub: card.xPub, xSig: card.xSig, name: card.name };
    } catch {
      return null;
    }
  }
}

/** fetchCards() result — see the method docs for the field contracts. */
export interface FetchResult {
  cards: ContactCard[];
  /** Pubs the room binds to ≥2 distinct xPubs — refused, cards withheld. */
  ambiguous: string[];
  /** True when a later page failed after ≥1 success — incomplete view. */
  partial: boolean;
}

// ---- pending invites (creator side, persisted) --------------------------------

export interface PendingInvite {
  secret: string;
  createdAt: number;
}

/** Cancel marker: once written, no other tab's save can resurrect the id. */
interface InviteTombstone {
  id: string; // the invite secret
  cancelledAt: number;
}

interface PendingStore {
  invites: PendingInvite[];
  tombstones: InviteTombstone[];
}

const PENDING_KEY = nsKey("pending-invites");

export function inviteExpiresAt(inv: PendingInvite): number {
  return inv.createdAt + RuntimeLimits.ttlHours * 3_600_000;
}

function loadStore(): PendingStore {
  try {
    const raw = localStorage.getItem(PENDING_KEY);
    if (!raw) return { invites: [], tombstones: [] };
    const data = JSON.parse(raw) as unknown;
    // legacy format: a bare invite array (pre-tombstone clients)
    const listPart = Array.isArray(data) ? data : (data as PendingStore)?.invites;
    const tombPart = Array.isArray(data) ? [] : (data as PendingStore)?.tombstones;
    const invites = (Array.isArray(listPart) ? listPart : []).filter(
      (i): i is PendingInvite =>
        !!i && typeof i === "object" && B64URL_32.test((i as PendingInvite).secret ?? "") &&
        typeof (i as PendingInvite).createdAt === "number",
    );
    const tombstones = (Array.isArray(tombPart) ? tombPart : []).filter(
      (t): t is InviteTombstone =>
        !!t && typeof t === "object" && B64URL_32.test((t as InviteTombstone).id ?? "") &&
        typeof (t as InviteTombstone).cancelledAt === "number",
    );
    return { invites, tombstones };
  } catch {
    return { invites: [], tombstones: [] };
  }
}

/**
 * Persist, MERGING tombstones with whatever is on disk right now: a cancel in
 * one tab wins against a concurrent save in another (the resurrected invite
 * is filtered back out here). Tombstones expire with the invite TTL — after
 * that the room itself is gone, so the marker has nothing left to guard.
 */
function saveStore(store: PendingStore): void {
  const now = Date.now();
  const onDisk = loadStore();
  const byId = new Map<string, InviteTombstone>();
  for (const t of [...onDisk.tombstones, ...store.tombstones]) {
    if (t.cancelledAt + RuntimeLimits.ttlHours * 3_600_000 > now) byId.set(t.id, t);
  }
  const tombstones = [...byId.values()];
  const invites = store.invites.filter((i) => !byId.has(i.secret));
  try {
    localStorage.setItem(PENDING_KEY, JSON.stringify({ invites, tombstones }));
  } catch {}
}

/** Current pending invites, newest first; expired ones are pruned in place. */
export function listPendingInvites(): PendingInvite[] {
  const now = Date.now();
  const store = loadStore();
  const tombs = new Set(store.tombstones.map((t) => t.id));
  const live = store.invites.filter((i) => inviteExpiresAt(i) > now && !tombs.has(i.secret));
  if (live.length !== store.invites.length) saveStore({ invites: live, tombstones: store.tombstones });
  return live.sort((a, b) => b.createdAt - a.createdAt);
}

export function addPendingInvite(secret: string): PendingInvite {
  const inv: PendingInvite = { secret, createdAt: Date.now() };
  const store = loadStore();
  saveStore({ invites: [...store.invites.filter((i) => i.secret !== secret), inv], tombstones: store.tombstones });
  return inv;
}

/** Cancel an invite: tombstone it (merged on every save) and drop the row. */
export function removePendingInvite(secret: string): void {
  const store = loadStore();
  saveStore({
    invites: store.invites.filter((i) => i.secret !== secret),
    tombstones: [...store.tombstones, { id: secret, cancelledAt: Date.now() }],
  });
}

// ---- dismissed/declined cards (creator side, persisted per invite) ------------

const DISMISSED_KEY = nsKey("dismissed-cards");

const dismissedId = (secret: string, pub: string, xPub: string): string => `${secret}|${pub}|${xPub}`;

function loadDismissed(): string[] {
  try {
    const raw = localStorage.getItem(DISMISSED_KEY);
    const list = raw ? (JSON.parse(raw) as unknown) : [];
    return Array.isArray(list) ? list.filter((x): x is string => typeof x === "string") : [];
  } catch {
    return [];
  }
}

/**
 * Persist a dismissed/declined card for one invite so it never re-prompts on
 * a later poll or boot. Entries for invites that no longer exist are pruned
 * on write (their rooms expired — nothing can re-surface those cards).
 */
export function dismissInviteCard(secret: string, pub: string, xPub: string): void {
  const liveSecrets = new Set(listPendingInvites().map((i) => i.secret));
  liveSecrets.add(secret);
  const keep = loadDismissed().filter((id) => liveSecrets.has(id.split("|", 1)[0]));
  const id = dismissedId(secret, pub, xPub);
  if (!keep.includes(id)) keep.push(id);
  try {
    localStorage.setItem(DISMISSED_KEY, JSON.stringify(keep));
  } catch {}
}

export function isInviteCardDismissed(secret: string, pub: string, xPub: string): boolean {
  return loadDismissed().includes(dismissedId(secret, pub, xPub));
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git