cautpartener / client / src / main.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
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
366
367
368
369
370
371
372
/**
 * Bootstrap: PWA update flow + app shell, then a descriptor fetch that
 * (a) resolves the live relay config, (b) refreshes RuntimeLimits and
 * (c) doubles as the relay reachability probe for the lobby status line.
 * No libp2p node is started here — that arrives in M3.
 */

import { registerSW } from "virtual:pwa-register";
import "./app/style.css";
import { RELAY_DEFAULTS, updateRuntimeLimits } from "./config";
import type { MailboxConfig, RelayConfig } from "./lib/descriptor";

export const VERSION = __APP_VERSION__;

/** The relay config the p2p stack (M3+) should use; boot refines it. */
export const RelayState: { config: RelayConfig } = { config: RELAY_DEFAULTS };

/** What version is live on the server right now? (bypasses the SW precache) */
async function fetchLiveVersion(): Promise<string | null> {
  try {
    const res = await fetch(`./version.json?cb=${Date.now()}`, { cache: "no-store" });
    const v: unknown = (await res.json())?.version;
    return typeof v === "string" ? v : null;
  } catch {
    return null;
  }
}

function setupUpdates(): void {
  // When ANY tab's controller changes (a new SW took over — e.g. the user
  // tapped the update banner in another tab), reload so every open tab runs
  // the new assets. Guard 1: only when a controller already existed at
  // registration time, so the very first SW install doesn't trigger a reload.
  // Guard 2: a boolean so we never reload twice.
  const sw = navigator.serviceWorker;
  if (sw) {
    const hadController = sw.controller !== null;
    let reloadedOnChange = false;
    sw.addEventListener("controllerchange", () => {
      if (hadController && !reloadedOnChange) {
        reloadedOnChange = true;
        location.reload();
      }
    });
  }

  const updateSW = registerSW({
    immediate: true,
    async onNeedRefresh() {
      if (document.getElementById("upd-banner")) return;
      const { t } = await import("./app/i18n");
      const live = await fetchLiveVersion();
      const b = document.createElement("button");
      b.id = "upd-banner";
      b.className = "update-banner";
      b.textContent = live && live !== VERSION ? t("updateReady", { version: live }) : t("updateReadyGeneric");
      b.addEventListener("click", () => {
        b.textContent = t("updating");
        // Own the reload: vite-pwa only reloads for updates it discovered
        // itself, not ones surfaced by our periodic reg.update() checks.
        let reloaded = false;
        const reload = (): void => {
          if (!reloaded) {
            reloaded = true;
            location.reload();
          }
        };
        navigator.serviceWorker?.addEventListener("controllerchange", reload, { once: true });
        setTimeout(reload, 4000); // fallback if controllerchange never fires
        void updateSW(false); // sends skip-waiting to the new worker
      });
      document.body.appendChild(b);
    },
    onRegisteredSW(_url, reg) {
      if (!reg) return;
      // look for updates every 5 minutes and whenever the app comes back
      setInterval(() => void reg.update().catch(() => {}), 5 * 60_000);
      document.addEventListener("visibilitychange", () => {
        if (document.visibilityState === "visible") void reg.update().catch(() => {});
      });
    },
  });
}

/** Shape of the /.well-known/ap2p descriptor fields this app reads. */
interface Ap2pDescriptor {
  relay?: { multiaddrs?: string[]; pubsub_discovery_topic?: string };
  endpoints?: { turn_credentials?: string };
  mailbox?: {
    endpoint?: string;
    mint_endpoint?: string;
    ttl_hours?: number;
    max_message_kb?: number;
  };
}

/** Extract the DNS host from a /dns4|dns6|dnsaddr multiaddr; undefined for ip4 etc. */
function relayHostOf(multiaddr: string): string | undefined {
  return /^\/dns(?:4|6|addr)?\/([^/]+)\//.exec(multiaddr)?.[1];
}

/**
 * ONE descriptor round-trip serves three purposes: (a) the reachability probe
 * behind the lobby's "conectat / offline" status line, (b) the server's real
 * mailbox limits (ttl_hours / max_message_kb — never hardcoded in UI logic)
 * into RuntimeLimits, and (c) the live relay config into RelayState.config so
 * the operator can rotate PeerId / TURN / mailbox without a client release.
 * Offline-safe: every field falls back to the baked RELAY_DEFAULTS.
 */
async function probeRelay(setStatus: (s: "online" | "offline") => void): Promise<void> {
  const host = relayHostOf(RELAY_DEFAULTS.relayMultiaddr);
  if (!host) {
    // dev/self-host ip4 multiaddr — no descriptor host to probe
    setStatus("offline");
    return;
  }
  try {
    const res = await fetch(`https://${host}/.well-known/ap2p`, { signal: AbortSignal.timeout(4000) });
    if (!res.ok) throw new Error(`descriptor ${res.status}`);
    const d = (await res.json()) as Ap2pDescriptor;

    // (b) server-side limits the UI must respect
    updateRuntimeLimits({ ttlHours: d.mailbox?.ttl_hours, maxMessageKb: d.mailbox?.max_message_kb });

    // (c) live relay config, field-by-field with RELAY_DEFAULTS as fallback
    const addrs = d.relay?.multiaddrs?.filter((a) => typeof a === "string") ?? [];
    const relayMultiaddr = addrs.find((a) => a.includes(host)) ?? addrs[0] ?? RELAY_DEFAULTS.relayMultiaddr;
    const mailbox: MailboxConfig | undefined =
      d.mailbox?.endpoint && d.mailbox?.mint_endpoint
        ? {
            baseUrl: d.mailbox.endpoint,
            credsUrl: d.mailbox.mint_endpoint,
            maxMessageKb: d.mailbox.max_message_kb ?? RELAY_DEFAULTS.mailbox?.maxMessageKb ?? 64,
          }
        : RELAY_DEFAULTS.mailbox;
    RelayState.config = {
      relayMultiaddr,
      turnCredsUrl: d.endpoints?.turn_credentials ?? RELAY_DEFAULTS.turnCredsUrl,
      discoveryTopic: d.relay?.pubsub_discovery_topic ?? RELAY_DEFAULTS.discoveryTopic,
      ...(mailbox ? { mailbox } : {}),
    };

    // (a) it answered — we're online
    setStatus("online");
  } catch {
    setStatus("offline");
  }
}

// ---- boot gate: identity state decides the first screen ---------------------
//
//   none   → onboarding (create / import)
//   wiped  → recovery (explain the eviction, offer import — never a silent
//            new identity)
//   active → the lobby immediately; the selfroom (home-log) stack loads and
//            syncs in the background — first paint never waits on the network.

type ActiveIdentity = import("./core/identity-store").ActiveIdentity;

async function enterApp(root: HTMLElement, active: ActiveIdentity): Promise<void> {
  const { Session } = await import("./core/session");
  Session.identity = active;
  const [{ startRouter }, { setRelayStatus }] = await Promise.all([
    import("./app/router"),
    import("./app/views/lobby"),
  ]);
  startRouter(root);
  // descriptor probe first (it refines the mailbox endpoint), then the heavy
  // selfroom stack — all behind the first paint
  void probeRelay(setRelayStatus).then(() => startSelfRoom(active));
}

async function startSelfRoom(active: ActiveIdentity): Promise<void> {
  try {
    const [{ SelfRoom }, { Session }, { getLang, setLang }, { rerenderRoute }] = await Promise.all([
      import("./core/selfroom"),
      import("./core/session"),
      import("./app/i18n"),
      import("./app/router"),
    ]);
    const room = await SelfRoom.start(active.identity, active.seed, RelayState.config);
    Session.selfroom = room;
    const { ContactsService } = await import("./core/contacts");
    Session.contacts = new ContactsService(room, active.identity.publicKeyB64);
    const { ChatService } = await import("./core/conversations");
    Session.chat = new ChatService(room, { seed: active.seed, pub: active.identity.publicKeyB64 });

    // M5b audience restriction: group epoch keys + grant plumbing. Grants ride
    // the pairwise rooms (ChatService owns those); membership changes in the
    // contacts service trigger grants/rekeys; a rekey re-seals the published
    // profile so removed members lose the CURRENT sections, not just future ones.
    const { AudienceService } = await import("./core/audience");
    const audience = new AudienceService(room, active.identity.publicKeyB64, async (pub) => {
      const r = await Session.chat!.open(pub);
      return r?.handle ?? null;
    });
    Session.audience = audience;
    Session.contacts.onMembershipChanged = (gid, pub, on) =>
      void audience.onMembershipChanged(gid, pub, on).catch(() => {});
    Session.contacts.onContactRemoved = (pub) => void audience.onContactRemoved(pub).catch(() => {});
    Session.contacts.onKeyChanged = (pub) => void audience.onKeyChanged(pub).catch(() => {});
    Session.chat.onPairGrant = (senderPub, op) => void audience.registerGrant(senderPub, op).catch(() => {});
    audience.onRekeyed = (gid) => {
      void import("./public/profile-service")
        .then((m) => m.republishAfterRekey(gid))
        .catch(() => {});
    };
    // a deleted group: republish the profile so its sealed section (now for an
    // inactive group) is dropped from the served doc immediately (M5b).
    Session.contacts.onGroupDeleted = (gid) => {
      void import("./public/profile-service")
        .then((m) => m.republishAfterRekey(gid))
        .catch(() => {});
    };
    // §3b convergence: every home-log fold (incl. a concurrent device's gkey
    // syncing in) may reveal that a locally-minted gkey lost LWW — re-grant +
    // re-seal so all devices and members converge on the one winning key.
    room.onStateChanged(() => void audience.converge().catch(() => {}));

    // probe conversations + auto-open rooms with new mail (offline delivery
    // of chat messages and pairwise ginvites/grants) — never blocks boot
    void Session.chat.boot().catch(() => {});

    // A language chosen before the room was up → append it now, with the
    // CLICK-time ts (LWW orders the intent when the user acted). AWAIT the
    // flush before folding state into the UI below — applying the stale
    // folded lang first and the flushed one after would flip-flop the UI.
    if (Session.pendingLang) {
      const { lang, ts } = Session.pendingLang;
      Session.pendingLang = null;
      await room.setSettings({ lang }, ts).catch(() => {});
    }

    // folded settings drive the UI: a lang change made on another device (or
    // replayed from the mailbox on this fresh device) applies live
    const applyFolded = (s: { settings: { lang?: "ro" | "en" | "hu" } }): void => {
      const lang = s.settings.lang;
      if (lang && lang !== getLang()) {
        setLang(lang);
        rerenderRoute();
      }
    };
    room.onState = applyFolded;
    applyFolded(room.state);

    // P2/P3 matching: a received-like ingest (inbox poll) may mint a new
    // mutual match — refresh the conversation list live
    const matchSvc = await import("./public/match-service");
    matchSvc.onMatchesChanged(() => Session.chat?.pokeList());

    // P4 calls: subscribe every pair/match conversation's sealed call topic
    // (rings app-wide) and mount the overlays. Contact/match changes
    // re-reconcile the subscriptions.
    const { CallService } = await import("./core/calls");
    const calls = new CallService({
      hub: room.hub,
      chat: Session.chat,
      identity: { seed: active.seed, pub: active.identity.publicKeyB64 },
      turnCredsUrl: RelayState.config.turnCredsUrl,
    });
    Session.calls = calls;
    const { wireCallUi } = await import("./app/views/call-ui");
    wireCallUi(calls);
    calls.refresh();
    room.onStateChanged(() => calls.refresh());
    matchSvc.onMatchesChanged(() => calls.refresh());

    window.addEventListener("beforeunload", () => {
      calls.stop();
      room.stop();
    });
    // console/e2e debug handle — grants nothing an open console doesn't already have (localStorage holds the seed)
    (window as unknown as Record<string, unknown>).__cp = {
      selfroom: room,
      identity: active,
      contacts: Session.contacts,
      chat: Session.chat,
      audience: Session.audience,
      calls,
      hub: room.hub,
      // matching introspection for e2e (counts + peers only; NO secrets)
      match: {
        matches: () => matchSvc.matches().map((m) => ({ peer: m.peer, name: m.name, pool: m.pool, ts: m.ts })),
        likedMeCount: matchSvc.likedMeCount,
        sentPendingCount: matchSvc.sentPendingCount,
      },
    };

    // creator-side rendezvous poll: any card deposited into a pending invite
    // room runs the fingerprint-confirm flow (contacts-tab owns the UI);
    // the same boot pass polls the public inboxRoom (creq/cack, M4)
    void import("./app/views/contacts-tab")
      .then((m) => {
        void m.pollPendingInvites();
        void m.pollContactRequests();
      })
      .catch(() => {});

    // M4 public-plane boot (§6): re-deposit the current profile + mod +
    // avatar blocks and re-seed the visible comments on the own profile —
    // dedup makes it free, and it re-arms the mailbox TTL. Jittered and
    // non-blocking so boot never waits on it.
    setTimeout(
      () => {
        void import("./public/profile-service")
          .then((m) => m.republishOwn())
          .catch(() => {});
        void import("./public/comment-service")
          .then((m) => m.reseedVisibleComments())
          .catch(() => {});
        // M5 (§6): re-seed pass for the last-viewed feed shard — a one-page
        // replay primes the raw-envelope cache, then own docs + up to 5 aged
        // foreign docs are re-deposited (jittered + budget-capped inside).
        void import("./public/feed-service")
          .then((m) => m.bootReseedLastShard())
          .catch(() => {});
        // P2 (§6): re-arm my matching cards (active AND retired — the
        // withdrawal must outlive the older active revision in the window).
        void import("./public/match-service")
          .then((m) => m.reseedMyCards())
          .catch(() => {});
      },
      500 + Math.random() * 2500,
    );
  } catch (err) {
    console.warn("selfroom failed to start", err);
  }
}

async function showOnboarding(root: HTMLElement): Promise<void> {
  const { renderOnboarding } = await import("./app/views/identity-onboarding");
  renderOnboarding(root, (id) => void enterApp(root, id));
}

async function boot(): Promise<void> {
  setupUpdates();

  if (import.meta.env.DEV) {
    // dev-only crypto self-test; also keeps lib/ compiling into the bundle
    const { runSelfTest } = await import("./lib/selftest");
    void runSelfTest()
      .then(() => console.info("[selftest] crypto self-test passed"))
      .catch((e: unknown) => console.error("[selftest]", e));
    // app-plane checks: pairSecret must be symmetric (both sides of a 1:1
    // room derive the SAME secret) and pair-distinct — docs/PROTOCOL.md §2
    const { pairSecretSelfTest } = await import("./core/pairwise");
    void pairSecretSelfTest()
      .then(() => console.info("[selftest] pairSecret symmetry passed"))
      .catch((e: unknown) => console.error("[selftest] pairSecret", e));
  }

  const root = document.getElementById("app")!;
  const { wipeCheck, getIdentity } = await import("./core/identity-store");
  const state = await wipeCheck();

  if (state === "active") {
    const active = await getIdentity();
    if (active) return void enterApp(root, active);
  }
  if (state === "wiped") {
    const { renderRecovery } = await import("./app/views/recovery");
    renderRecovery(
      root,
      (id) => void enterApp(root, id),
      () => void showOnboarding(root),
    );
    return;
  }
  await showOnboarding(root);
}

void boot();

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