cautpartener / client / src / app / views / identity-onboarding.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
/**
 * Identity onboarding — shown while the device has no usable identity.
 * Two paths:
 *  - create: generate a seed, show it (text + QR + copy), and gate on an
 *    explicit backup proof (checkbox + retyping the last 4 characters)
 *    before confirmBackup() makes the identity real;
 *  - import: paste the 43-char seed (with live emoji-fingerprint preview) or
 *    scan its QR via BarcodeDetector where the browser has one.
 * The 4-emoji fingerprint is shown prominently after both paths.
 */

import {
  confirmBackup,
  createIdentity,
  importIdentity,
  isValidSeed,
  requestStoragePersist,
  type ActiveIdentity,
} from "../../core/identity-store";
import { Identity } from "../../lib/identity";
import { t } from "../i18n";
import { qrElement } from "../qr";
import { h, sheet, toast } from "../ui-kit";

// ---- BarcodeDetector (not in TS's DOM lib yet) ------------------------------

interface DetectedBarcode {
  rawValue: string;
}
interface BarcodeDetectorLike {
  detect(source: CanvasImageSource): Promise<DetectedBarcode[]>;
}
type BarcodeDetectorCtor = (new (opts?: { formats?: string[] }) => BarcodeDetectorLike) & {
  getSupportedFormats?: () => Promise<string[]>;
};

function barcodeDetectorCtor(): BarcodeDetectorCtor | null {
  return (window as unknown as { BarcodeDetector?: BarcodeDetectorCtor }).BarcodeDetector ?? null;
}

async function qrScanSupported(): Promise<boolean> {
  const BD = barcodeDetectorCtor();
  if (!BD) return false;
  if (!navigator.mediaDevices?.getUserMedia) return false;
  try {
    const formats = (await BD.getSupportedFormats?.()) ?? [];
    return formats.includes("qr_code");
  } catch {
    return false;
  }
}

// ---- shared bits -------------------------------------------------------------

function copyButton(text: string, label: string, testid: string): HTMLButtonElement {
  return h(
    "button",
    {
      type: "button",
      class: "btn ghost",
      "data-testid": testid,
      onclick: () => {
        void navigator.clipboard?.writeText(text).then(
          () => toast(t("copied")),
          () => toast(t("copyFailed")),
        );
      },
    },
    label,
  );
}

function fpBlock(emoji: string, hex: string, testid: string): HTMLElement {
  return h(
    "div",
    { class: "fp-block" },
    h("div", { class: "fp-emoji", "data-testid": testid, title: hex }, emoji),
    h("div", { class: "muted fp-hint" }, t("onbFingerprintHint")),
  );
}

/**
 * The import panel (textarea + live fingerprint preview + optional QR scan),
 * reused by the recovery screen. Calls onDone with the imported identity.
 */
export function importPanel(onDone: (id: ActiveIdentity) => void): HTMLElement {
  const input = h("textarea", {
    class: "seed-input mono",
    rows: 2,
    placeholder: t("onbImportPlaceholder"),
    autocomplete: "off",
    autocapitalize: "off",
    spellcheck: false,
    "data-testid": "import-seed",
  });
  const preview = h("div", { class: "fp-preview" });
  const error = h("p", { class: "field-error", "data-testid": "import-error", hidden: true }, t("onbImportInvalid"));
  const confirm = h(
    "button",
    { type: "button", class: "btn", "data-testid": "import-confirm", disabled: true },
    t("onbImportConfirm"),
  ) as HTMLButtonElement;

  let checkedSeed = ""; // seed currently previewed as valid
  const validate = (): void => {
    const seed = input.value.trim();
    const ok = isValidSeed(seed);
    error.hidden = ok || seed.length === 0;
    confirm.disabled = !ok;
    if (!ok) {
      checkedSeed = "";
      preview.replaceChildren();
      return;
    }
    if (seed === checkedSeed) return;
    checkedSeed = seed;
    // preview the fingerprint BEFORE the user commits — this is how they
    // verify they pasted/scanned the right identity
    void Identity.fromSeed(seed)
      .then((id) => {
        if (input.value.trim() !== seed) return; // stale
        preview.replaceChildren(fpBlock(id.fingerprint.emoji, id.fingerprint.hex, "import-fp"));
      })
      .catch(() => {
        if (input.value.trim() !== seed) return;
        checkedSeed = "";
        error.hidden = false;
        confirm.disabled = true;
      });
  };
  input.addEventListener("input", validate);

  confirm.addEventListener("click", () => {
    const seed = input.value.trim();
    confirm.disabled = true;
    void importIdentity(seed)
      .then((id) => onDone(id))
      .catch(() => {
        error.hidden = false;
        confirm.disabled = false;
      });
  });

  const scanBtn = h(
    "button",
    { type: "button", class: "btn ghost", "data-testid": "import-scan", hidden: true },
    t("onbScanQr"),
  ) as HTMLButtonElement;
  void qrScanSupported().then((ok) => {
    scanBtn.hidden = !ok; // feature-detected: hidden entirely where unsupported
  });
  scanBtn.addEventListener("click", () => openScanSheet(input, validate));

  return h("div", { class: "import-panel" }, input, error, preview, h("div", { class: "btn-row" }, scanBtn, confirm));
}

/** Camera QR scan sheet (only reachable when BarcodeDetector supports qr_code). */
function openScanSheet(input: HTMLTextAreaElement, onFilled: () => void): void {
  const BD = barcodeDetectorCtor();
  if (!BD) return;
  const video = h("video", { class: "scan-video", playsinline: true, muted: true }) as HTMLVideoElement;
  const body = h("div", {}, h("h2", { class: "sheet-title" }, t("onbScanQr")), video);
  const s = sheet(body);
  let stream: MediaStream | null = null;
  let timer: ReturnType<typeof setInterval> | null = null;
  const stop = (): void => {
    if (timer) clearInterval(timer);
    timer = null;
    stream?.getTracks().forEach((tr) => tr.stop());
    stream = null;
  };
  // sheet() removes its backdrop on dismiss; watch for that to stop the camera
  const obs = new MutationObserver(() => {
    if (!document.body.contains(video)) {
      stop();
      obs.disconnect();
    }
  });
  obs.observe(document.body, { childList: true, subtree: true });

  void navigator.mediaDevices
    .getUserMedia({ video: { facingMode: "environment" } })
    .then((st) => {
      stream = st;
      video.srcObject = st;
      return video.play();
    })
    .then(() => {
      const detector = new BD({ formats: ["qr_code"] });
      timer = setInterval(() => {
        void detector
          .detect(video)
          .then((codes) => {
            const hit = codes.find((c) => isValidSeed(c.rawValue.trim()));
            if (hit) {
              input.value = hit.rawValue.trim();
              stop();
              s.close();
              onFilled();
            }
          })
          .catch(() => {});
      }, 350);
    })
    .catch(() => {
      toast(t("onbScanFail"));
      stop();
      s.close();
    });
}

// ---- the onboarding flow ------------------------------------------------------

export function renderOnboarding(root: HTMLElement, onDone: (id: ActiveIdentity) => void): void {
  const frame = (...children: (HTMLElement | string)[]): HTMLElement =>
    h("div", { class: "onboarding", "data-testid": "onboarding" }, h("div", { class: "onb-inner" }, ...children));

  const showChoice = (): void => {
    root.replaceChildren(
      frame(
        h("div", { class: "glyph" }, "🔑"),
        h("h2", {}, t("onbTitle")),
        h("p", { class: "muted" }, t("onbIntro")),
        h(
          "div",
          { class: "btn-col" },
          h("button", { type: "button", class: "btn", "data-testid": "create-id", onclick: () => void showCreate() }, t("onbCreate")),
          h("button", { type: "button", class: "btn ghost", "data-testid": "import-id", onclick: showImport }, t("onbImport")),
        ),
      ),
    );
  };

  const showCreate = async (): Promise<void> => {
    const { seed, identity } = await createIdentity();
    const fp = identity.fingerprint;

    const check = h("input", { type: "checkbox", id: "backup-check", "data-testid": "backup-check" }) as HTMLInputElement;
    const last4 = h("input", {
      type: "text",
      class: "last4-input mono",
      maxlength: 4,
      autocomplete: "off",
      autocapitalize: "off",
      spellcheck: false,
      inputmode: "text",
      placeholder: "····",
      "data-testid": "backup-last4",
    }) as HTMLInputElement;
    const last4Err = h("p", { class: "field-error", hidden: true }, t("onbLast4Bad"));
    const proceed = h(
      "button",
      { type: "button", class: "btn", "data-testid": "backup-confirm", disabled: true },
      t("onbContinue"),
    ) as HTMLButtonElement;

    const gate = (): void => {
      const typed = last4.value.trim();
      const match = typed === seed.slice(-4);
      last4Err.hidden = match || typed.length < 4;
      proceed.disabled = !(check.checked && match);
    };
    check.addEventListener("change", gate);
    last4.addEventListener("input", gate);
    proceed.addEventListener("click", () => {
      proceed.disabled = true;
      void confirmBackup(seed)
        .then((id) => {
          onDone(id);
          // Safari ITP / eviction honesty: when the browser refuses durable
          // storage, warn once that it may evict this app's data and the
          // saved seed is the only safety net. (persist() is idempotent —
          // confirmBackup already fired it for the meta record.)
          void requestStoragePersist().then((granted) => {
            if (granted === false) toast(t("onbPersistWarn"), 6000);
          });
        })
        .catch(() => {
          toast(t("onbPersistFailed"));
          proceed.disabled = false;
        });
    });

    root.replaceChildren(
      frame(
        h("h2", {}, t("onbSeedTitle")),
        // Safari ITP blind spot (see identity-store.ts): after a total
        // eviction wipeCheck() says "none", so a returning user lands HERE —
        // a low-key hint steers them to import instead of minting a second
        // identity that orphans their contacts.
        h("p", { class: "muted", "data-testid": "create-import-hint" }, t("onbCreateImportHint")),
        fpBlock(fp.emoji, fp.hex, "fp-new"),
        h("p", { class: "seed-warn" }, t("onbSeedExplain")),
        h("div", { class: "seed-text mono", "data-testid": "seed-text" }, seed),
        qrElement(seed, "seed-qr"),
        h("div", { class: "btn-row" }, copyButton(seed, t("copySeed"), "seed-copy")),
        h(
          "div",
          { class: "backup-gate" },
          h("label", { class: "check-row", for: "backup-check" }, check, h("span", {}, t("onbSavedCheck"))),
          h("label", { class: "last4-row" }, h("span", {}, t("onbLast4Label")), last4),
          last4Err,
          proceed,
        ),
        h("button", { type: "button", class: "btn ghost", "data-testid": "onb-back", onclick: showChoice }, t("back")),
      ),
    );
  };

  const showImport = (): void => {
    root.replaceChildren(
      frame(
        h("h2", {}, t("onbImportTitle")),
        h("p", { class: "muted" }, t("onbImportExplain")),
        importPanel(onDone),
        h("button", { type: "button", class: "btn ghost", "data-testid": "onb-back", onclick: showChoice }, t("back")),
      ),
    );
  };

  showChoice();
}

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