cautpartener / client / src / app / views / add-contact.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
/**
 * #/add/<inviteSecret>.<creatorPub> โ€” the invitee side of the rendezvous
 * exchange. Parses and validates the token, replays the invite room, finds
 * the creator's card (cert verified AND card.pub must equal the creatorPub
 * from the link โ€” a mismatch is rejected), then runs the MANDATORY 4-emoji
 * fingerprint comparison; our own card is deposited only AFTER the
 * fingerprint confirmation AND the TOFU decision both passed (ยง2b). Honest
 * terminal states for: own link, already-contact, malformed link,
 * missing/expired invite, ambiguous room (โ‰ฅ2 xPubs for the creator's pub),
 * TOFU key change.
 */

import { RuntimeLimits } from "../../config";
import { clampName, type ContactCard } from "../../core/contacts";
import { parseInviteToken, Rendezvous, type InviteRef } from "../../core/rendezvous";
import { Session } from "../../core/session";
import { fingerprintOf } from "../../lib/identity";
import { t } from "../i18n";
import { h, toast } from "../ui-kit";
import { buildMyCard, myCardName, openTofuSheet } from "./contacts-tab";
import { presetTab } from "./lobby";

function frame(...children: (HTMLElement | string | null)[]): HTMLElement {
  return h(
    "div",
    { class: "onboarding", "data-testid": "add-view" },
    h("div", { class: "onb-inner" }, ...children.filter((c): c is HTMLElement | string => c !== null)),
  );
}

function goContactsBtn(): HTMLElement {
  return h(
    "a",
    {
      class: "btn",
      href: "#/",
      "data-testid": "add-go-contacts",
      onclick: () => presetTab("contacts"),
    },
    t("addGoContacts"),
  );
}

function terminal(root: HTMLElement, glyph: string, msg: string, testid: string, extra?: HTMLElement): void {
  root.replaceChildren(
    frame(
      h("div", { class: "glyph" }, glyph),
      h("p", { class: "add-msg", "data-testid": testid }, msg),
      h("div", { class: "btn-col" }, extra ?? null, h("a", { class: "btn ghost", href: "#/" }, t("backHome"))),
    ),
  );
}

async function waitFor<T>(get: () => T | null, timeoutMs: number): Promise<T | null> {
  const until = Date.now() + timeoutMs;
  for (;;) {
    const v = get();
    if (v) return v;
    if (Date.now() > until) return null;
    await new Promise((r) => setTimeout(r, 250));
  }
}

export function renderAddContact(root: HTMLElement, token: string): void {
  const ref = parseInviteToken(token);
  if (!ref) {
    terminal(root, "๐Ÿšซ", t("addBadLink"), "add-error");
    return;
  }
  const myPub = Session.identity?.identity.publicKeyB64 ?? "";
  if (ref.creatorPub === myPub) {
    terminal(root, "๐Ÿ”", t("addOwnLink"), "add-own");
    return;
  }
  void runFlow(root, ref);
}

async function runFlow(root: HTMLElement, ref: InviteRef): Promise<void> {
  root.replaceChildren(
    frame(h("div", { class: "glyph" }, "๐Ÿ”"), h("p", { class: "muted", "data-testid": "add-loading" }, t("addLoading"))),
  );

  // contacts service is required to store the result; the selfroom stack
  // boots in the background โ€” wait honestly instead of failing
  const svc = await waitFor(() => Session.contacts, 90_000);
  if (!svc || !root.isConnected) {
    if (root.isConnected) terminal(root, "๐Ÿšซ", t("syncNoMailbox"), "add-error");
    return;
  }

  const rdv = await Rendezvous.open(ref.secret);
  const res = rdv ? await rdv.fetchCards() : null;
  if (!root.isConnected) return;

  // ยง2b ambiguity refusal: the room binds the creator's pub to โ‰ฅ2 distinct
  // xPubs โ€” we refuse to pick one. Honest warning, no compare screen.
  if (res?.ambiguous.includes(ref.creatorPub)) {
    terminal(root, "โš ๏ธ", t("addAmbiguous"), "add-ambiguous");
    return;
  }

  const card = res?.cards.find((c) => c.pub === ref.creatorPub) ?? null;
  if (!rdv || !card) {
    // unreachable mailbox, empty room, or only cards whose pub does not match
    // the link's creator (forgery or expiry) โ€” same honest terminal state
    terminal(
      root,
      "โณ",
      t("addNotFound", { hours: RuntimeLimits.ttlHours }),
      "add-error",
      h("button", { type: "button", class: "btn", "data-testid": "add-retry", onclick: () => void runFlow(root, ref) }, t("addRetry")),
    );
    return;
  }

  const existing = svc.state.contacts.get(card.pub);
  if (existing?.status === "active" && existing.xPub === card.xPub) {
    terminal(root, "โœ…", t("addKnown", { name: existing.name }), "add-known", goContactsBtn());
    return;
  }

  await showCompare(root, rdv, card, svc);
}

async function showCompare(
  root: HTMLElement,
  rdv: Rendezvous,
  card: ContactCard,
  svc: NonNullable<typeof Session.contacts>,
): Promise<void> {
  const fp = await fingerprintOf(card.pub);
  if (!root.isConnected) return;

  const nameInput = h("input", {
    type: "text",
    class: "text-input",
    maxlength: 40,
    autocomplete: "name",
    placeholder: t("ctInviteNamePh"),
    value: myCardName(),
    "data-testid": "add-my-name",
  }) as HTMLInputElement;
  const confirm = h(
    "button",
    { type: "button", class: "btn", "data-testid": "add-confirm" },
    t("addConfirm"),
  ) as HTMLButtonElement;
  const cancel = h("a", { class: "btn ghost", href: "#/", "data-testid": "add-cancel" }, t("cancel"));

  const gate = (): void => {
    confirm.disabled = clampName(nameInput.value).length === 0;
  };
  nameInput.addEventListener("input", gate);
  gate();

  root.replaceChildren(
    frame(
      h("h2", {}, t("addCompareTitle")),
      // card.name passed the wire sanitation check; clamp again before display
      h("p", { class: "add-msg", "data-testid": "add-name" }, clampName(card.name)),
      h("div", { class: "fp-block", "data-testid": "add-compare" },
        h("div", { class: "fp-emoji", "data-testid": "add-fp", title: fp.hex }, fp.emoji),
        h("div", { class: "muted fp-hint" }, t("onbFingerprintHint")),
      ),
      h("p", { class: "seed-warn" }, t("addCompareBody")),
      h("label", { class: "field-label" }, t("ctInviteNameLabel")),
      nameInput,
      h("div", { class: "btn-col" }, confirm, cancel),
    ),
  );

  confirm.addEventListener("click", () => {
    confirm.disabled = true;
    void (async () => {
      const myName = clampName(nameInput.value);
      await Session.selfroom?.setSettings({ name: myName }).catch(() => {});

      // fingerprint was confirmed (this click); run the TOFU decision BEFORE
      // depositing our own card โ€” a rejected key change must leave nothing of
      // ours in a possibly-compromised room (ยง2b).
      const outcome = await svc.addContact(card);
      if (outcome.kind === "key-change") {
        const accepted = await openTofuSheet(card, outcome.existing, svc);
        if (!accepted) {
          terminal(root, "๐Ÿ›ก๏ธ", t("tofuRejected"), "add-rejected");
          return;
        }
      } else if (outcome.kind === "invalid") {
        terminal(root, "๐Ÿšซ", t("addBadLink"), "add-error");
        return;
      }

      // deposit OUR card so the creator's poll can complete their side
      const mine = await buildMyCard(myName);
      const sent = mine ? await rdv.depositCard(mine).catch(() => false) : false;
      if (!sent) {
        // contact stored locally; re-enable so the user can retry the deposit
        // (addContact is idempotent โ€” it reports "unchanged" on the retry)
        toast(t("addDepositFailed"));
        confirm.disabled = false;
        return;
      }
      terminal(root, "๐ŸŽ‰", t("addSuccess", { name: clampName(card.name) }), "add-success", goContactsBtn());
    })().catch(() => {
      toast(t("addDepositFailed"));
      confirm.disabled = false;
    });
  });
}

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