File size: 37,135 Bytes
82cdb59
 
 
367a695
 
 
 
82cdb59
 
103a492
82cdb59
dec006b
367a695
103a492
82cdb59
89af3b2
367a695
8133df9
82cdb59
367a695
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
367a695
 
8133df9
 
367a695
 
8133df9
367a695
 
 
8133df9
367a695
 
 
 
 
 
 
 
103a492
 
 
 
367a695
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
8133df9
 
dec006b
 
 
 
 
 
 
 
 
 
8133df9
dec006b
8133df9
dec006b
 
 
8133df9
 
 
 
 
 
dec006b
 
 
 
 
8133df9
dec006b
 
 
 
8133df9
dec006b
8133df9
 
 
 
 
 
dec006b
 
8133df9
 
dec006b
8133df9
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
dec006b
8133df9
 
 
 
dec006b
8133df9
 
 
 
dec006b
 
 
8133df9
dec006b
 
 
8cbc29f
 
 
8133df9
 
8cbc29f
 
8133df9
 
 
8cbc29f
 
 
 
 
 
 
 
 
8133df9
 
8cbc29f
 
8133df9
 
8cbc29f
 
 
8133df9
 
 
8cbc29f
8133df9
8cbc29f
 
 
 
 
8133df9
8cbc29f
 
 
 
 
 
8133df9
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
8cbc29f
 
 
 
 
 
 
8133df9
8cbc29f
 
 
 
 
 
8133df9
8cbc29f
 
 
 
 
 
 
 
8133df9
8cbc29f
 
 
 
 
 
 
 
 
8133df9
8cbc29f
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
367a695
82cdb59
 
 
 
 
 
 
367a695
8133df9
367a695
 
 
 
 
82cdb59
 
 
8133df9
89af3b2
 
367a695
82cdb59
367a695
 
103a492
 
 
 
 
 
 
 
 
8133df9
103a492
 
 
 
 
 
 
 
 
 
 
82cdb59
 
367a695
82cdb59
103a492
82cdb59
 
 
103a492
82cdb59
 
dec006b
82cdb59
 
367a695
 
 
 
 
 
 
103a492
367a695
 
 
 
 
 
103a492
367a695
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
82cdb59
 
 
89af3b2
 
 
 
 
 
 
82cdb59
 
103a492
 
82cdb59
 
 
 
 
103a492
82cdb59
 
 
 
103a492
 
82cdb59
 
 
 
 
 
 
 
 
367a695
 
103a492
 
367a695
 
 
 
 
 
 
 
 
 
 
 
103a492
367a695
103a492
 
367a695
 
 
103a492
 
 
 
367a695
 
 
89af3b2
367a695
 
 
 
 
 
 
103a492
89af3b2
 
103a492
 
 
 
 
89af3b2
367a695
 
 
 
 
 
 
103a492
 
 
 
 
 
367a695
 
 
8133df9
 
367a695
 
8133df9
 
 
367a695
 
 
 
 
 
 
 
 
8133df9
 
367a695
 
 
8133df9
367a695
 
8133df9
89af3b2
 
 
367a695
8133df9
 
89af3b2
367a695
 
8133df9
 
 
367a695
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
82cdb59
 
 
 
 
8133df9
82cdb59
8133df9
 
82cdb59
 
367a695
 
 
 
 
 
 
82cdb59
 
8133df9
82cdb59
 
 
 
 
8133df9
 
82cdb59
 
 
8133df9
82cdb59
 
 
 
 
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
// ---------------------------------------------------------------------------
// settings / SecurityPane.tsx - W57-T36, R15 / C12.
//
// Every stored account owns its second factor. W59-T31 also renders this pane
// before a session exists: R1 moves the enrollment screen, never the MFA wall.
// Settings reads status, never the installed secret, and can replace a phone
// only after password re-authentication and proof of the candidate factor.
// ---------------------------------------------------------------------------

import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { FormEvent } from "react";
import { errorMessage, isAdmin, me, mfaEnrollConfirm, mfaEnrollStart, mfaStatus, regenerateRecoveryCodes, SERVER_UNAVAILABLE } from "../shell/session";
import type { MFASetup, MFAStatus, SessionUser } from "../shell/session";
import { API_V1, CREDENTIALS, checkTenant, currentTenant, signal, TOAST_EVENT, UNAUTHORIZED_EVENT } from "../apiContract";
import { useEscapeClose } from "../ui/useEscapeClose";
import { CodeInput } from "../ui/CodeInput";
import { encodeQr } from "../shell/qrcode";
import "../styles/sdlc84/settings-security.css";

function SetupQr({ uri }: { uri: string }) {
  const drawing = useMemo(() => {
    try {
      const qr = encodeQr(uri);
      const quiet = 4;
      // One path keeps the modal's DOM small; the four-module light border
      // belongs in the viewBox so responsive sizing cannot crop it away.
      const path = qr.modules.flatMap((row, y) => row.flatMap((dark, x) =>
        dark ? [`M${x + quiet} ${y + quiet}h1v1h-1z`] : [])).join("");
      return { extent: qr.size + 2 * quiet, path };
    } catch {
      // Keep enrollment usable, but never draw a plausible square on failure.
      return null;
    }
  }, [uri]);
  if (!drawing) return <p className="security-qr-help">The QR code could not be drawn.</p>;
  return (
    <>
      <p className="security-qr-help">Or scan this code with your authenticator app.</p>
      <svg className="security-qr-image" viewBox={`0 0 ${drawing.extent} ${drawing.extent}`}
        shapeRendering="crispEdges" role="img" aria-label="Setup code as a QR code" focusable="false">
        <rect className="security-qr-field" width={drawing.extent} height={drawing.extent} />
        <path fill="currentColor" d={drawing.path} />
      </svg>
    </>
  );
}

/** W57-T36 / C12: one show-once treatment in both doors. Copy is a quiet,
 *  explicit export to the person's clipboard, never persistence on their behalf.
 *  Only the acknowledgement can dismiss this surface; Escape names what remains.
 *  Browser reload/close can only be warned about, never made impossible by a page. */
export function RecoveryCodes({ codes, onSaved, onError }: {
  codes: string[];
  onSaved: () => void;
  onError: (message: string) => void;
}) {
  const [copied, setCopied] = useState<boolean>(false);
  const [copying, setCopying] = useState<boolean>(false);
  useEscapeClose(true, () => onError("Save your recovery codes before continuing."));
  useEffect(() => {
    const warn = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      event.returnValue = "";
    };
    window.addEventListener("beforeunload", warn);
    return () => window.removeEventListener("beforeunload", warn);
  }, []);

  async function copy() {
    if (copying) return;
    setCopying(true);
    try {
      await navigator.clipboard.writeText(codes.join("\n"));
      setCopied(true);
      onError("");
    } catch {
      setCopied(false);
      onError("Copy did not work. Select the codes and copy them manually.");
    } finally {
      setCopying(false);
    }
  }

  return (
    <>
      <p className="security-help">These recovery codes are shown only once.</p>
      <p className="security-help">Save them somewhere safe. Each code works once if you lose your authenticator.</p>
      <ul className="security-codes" aria-label="Recovery codes">
        {codes.map((code) => <li key={code}><code>{code}</code></li>)}
      </ul>
      <div className="security-copy-row">
        <button type="button" className="set-secondary" onClick={() => void copy()} disabled={copying}>
          {copying ? "Copying…" : "Copy codes"}
        </button>
        <span className="security-copy-status" role="status">{copied ? "Copied" : ""}</span>
      </div>
      {/* A type=button acknowledgement cannot be submitted by Enter left over
          from the previous code field. There is no Back or secondary exit. */}
      <button type="button" className="set-primary" onClick={onSaved} disabled={copying}>
        I have saved these codes
      </button>
    </>
  );
}

type AuthFailure = { ok: false; message: string };

function showRefusal(text: string) {
  window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
}

// Keep the literal fetch doors visible to D-48. These session-scoped helpers
// mirror authPost's tenant guard and error policy without creating a second session module.
async function startDevice(password: string): Promise<({ ok: true } & MFASetup) | AuthFailure> {
  let res: Response;
  try {
    res = await fetch(`${API_V1}/auth/mfa/device`, {
      method: "POST", credentials: CREDENTIALS, cache: "no-store",
      headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }),
    });
  } catch {
    return { ok: false, message: errorMessage(0, null) };
  }
  if (checkTenant(res)) return { ok: false, message: SERVER_UNAVAILABLE };
  const body = await res.json().catch(() => null);
  if (!res.ok) return { ok: false, message: errorMessage(res.status, body) };
  if (!body || typeof body.secret !== "string" || !body.secret.trim()
      || typeof body.otpauthUri !== "string" || !body.otpauthUri.trim()
      || typeof body.issuer !== "string" || !body.issuer.trim())
    return { ok: false, message: SERVER_UNAVAILABLE };
  return { ok: true, secret: body.secret, otpauthUri: body.otpauthUri, issuer: body.issuer };
}

async function confirmDevice(password: string, secret: string, code: string): Promise<
  { ok: true; recoveryCodes: string[] } | AuthFailure
> {
  let res: Response;
  try {
    res = await fetch(`${API_V1}/auth/mfa/device/confirm`, {
      method: "POST", credentials: CREDENTIALS, cache: "no-store",
      headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password, secret, code }),
    });
  } catch {
    return { ok: false, message: errorMessage(0, null) };
  }
  if (checkTenant(res)) return { ok: false, message: SERVER_UNAVAILABLE };
  const body = await res.json().catch(() => null);
  if (!res.ok) return { ok: false, message: errorMessage(res.status, body) };
  const codes: unknown = body?.recoveryCodes;
  // Accept the whole fresh set or refuse success, just like the existing issuers.
  if (!Array.isArray(codes) || codes.length === 0
      || !codes.every((value): value is string => typeof value === "string" && value.trim().length > 0)
      || new Set(codes).size !== codes.length)
    return { ok: false, message: SERVER_UNAVAILABLE };
  return { ok: true, recoveryCodes: codes };
}

export type EnrolmentGate = {
  username: string;
  password: string;
  onEnrolled: (user: SessionUser, recoveryCodes: string[]) => void;
  onBack: () => void;
};

type SecurityEvent = {
  kind: string;
  user: string;
  tenant: string;
  detail: Record<string, string | number | boolean>;
  at: string;
};
const EVENTS_UNAVAILABLE = "Security events could not be loaded.";
const EVENT_LABELS: Record<string, string> = {
  "auth.login": "Signed in",
  "auth.login_failed": "Sign-in failed",
  "auth.lockout": "Account locked",
  "auth.mfa_enrolled": "Two-step sign-in set up",
  "auth.mfa_failed": "Two-step sign-in failed",
  "auth.logout": "Signed out",
  "admin.grant": "Access changed",
  "credential.added": "Credential added",
  "credential.rotated": "Credential replaced",
  "credential.revoked": "Credential revoked",
  "amazon.sync": "Amazon sync",
  "amazon.throttled": "Amazon request limited",
  "amazon.authorization_lost": "Amazon authorization lost",
  "amazon.deletion_scheduled": "Amazon deletion scheduled",
  "amazon.personal_read": "Amazon personal data read",
  "customer.personal_read": "Customer personal data read",
  "data.purge": "Data deleted",
  "data.restore": "Data restored",
  "config.changed": "Setting changed",
  "external.query": "External query",
  "external.write": "External change",
};

function readableLabel(value: string) {
  const words = value.replace(/[._-]+/g, " ").trim().toLowerCase();
  return words ? words[0].toUpperCase() + words.slice(1) : "Security event";
}

function SecuritySkeleton({ label }: { label: string }) {
  return <div className="set-skeleton security-skeleton" role="status" aria-label={label} aria-busy="true">
    <span className="set-skeleton-line" aria-hidden="true" />
    <span className="set-skeleton-line" aria-hidden="true" />
  </div>;
}

function SecurityEvents() {
  const [denied, setDenied] = useState(false);
  const [events, setEvents] = useState<SecurityEvent[]>([]);
  const [loading, setLoading] = useState(true);
  const [problem, setProblem] = useState("");
  const [revision, setRevision] = useState(0);

  useEffect(() => {
    const controller = new AbortController();
    let active = true;
    const clear = () => {
      active = false;
      controller.abort();
      setDenied(true); setEvents([]); setProblem(""); setLoading(false);
    };
    setDenied(false); setEvents([]); setLoading(true); setProblem("");
    async function load() {
      try {
        const identity = await me();
        if (!active) return;
        if (!identity?.tenant) throw new Error(EVENTS_UNAVAILABLE);
        if (currentTenant() !== null && currentTenant() !== identity.tenant) {
          setDenied(true); return;
        }
        if (!isAdmin(identity)) { setDenied(true); return; }
        const response = await fetch(`${API_V1}/security/events`, {
          credentials: CREDENTIALS, cache: "no-store", signal: controller.signal,
        });
        if (!active || checkTenant(response)) return;
        if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
        if (response.status === 403) { setDenied(true); return; }
        if (!response.ok) throw new Error(EVENTS_UNAVAILABLE);
        const body = await response.json();
        if (!active) return;
        if (!body || !Array.isArray(body.events)) throw new Error(EVENTS_UNAVAILABLE);
        const entries: SecurityEvent[] = [];
        for (const event of body.events) {
          if (!event || event.tenant !== identity.tenant) continue;
          if (typeof event.kind !== "string" || !event.kind.trim()
              || typeof event.principal !== "string" || !event.principal.trim()
              || !event.detail || typeof event.detail !== "object" || Array.isArray(event.detail)
              || !Object.values(event.detail).every((value) => typeof value === "string"
                || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))
              || typeof event.ts !== "number" || !Number.isFinite(event.ts)
              || !Number.isFinite(new Date(event.ts * 1000).getTime())) throw new Error(EVENTS_UNAVAILABLE);
          entries.push({ kind: event.kind, user: event.principal, tenant: event.tenant,
            detail: event.detail, at: new Date(event.ts * 1000).toISOString() });
        }
        setEvents(entries.reverse());
      } catch {
        if (active) { setEvents([]); setProblem(EVENTS_UNAVAILABLE); }
      } finally {
        if (active) setLoading(false);
      }
    }
    window.addEventListener(UNAUTHORIZED_EVENT, clear);
    window.addEventListener("aios:signed-out", clear);
    void load();
    return () => {
      active = false;
      controller.abort();
      window.removeEventListener(UNAUTHORIZED_EVENT, clear);
      window.removeEventListener("aios:signed-out", clear);
    };
  }, [revision]);

  return <section className="security-events" aria-labelledby="security-events-heading">
    <h4 className="set-h4" id="security-events-heading">Security events</h4>
    {loading ? <SecuritySkeleton label="Loading security events" /> : problem ? <div className="set-error" role="alert"><span>{problem}</span>
      <button type="button" className="set-secondary" onClick={() => setRevision((value) => value + 1)}>Retry</button>
    </div> : denied ? <p className="security-help" role="status">Only administrators can view security events</p>
      : events.length ? <div className="security-event-scroll" role="region" aria-label="Security event log" tabIndex={0}>
      <table className="set-table" aria-label="Security events">
        <thead><tr><th scope="col">Event</th><th scope="col">User</th><th scope="col">Details</th><th scope="col">Time (UTC)</th></tr></thead>
        <tbody>{events.map((event, index) => <tr key={`${event.at}:${index}`}>
          <td><span>{Object.hasOwn(EVENT_LABELS, event.kind) ? EVENT_LABELS[event.kind] : readableLabel(event.kind)}</span>
            <span className="security-event-kind">{event.kind}</span></td>
          <td>{event.user}</td>
          <td>{Object.entries(event.detail).map(([key, value]) => `${readableLabel(key)}: ${String(value)}`).join(" · ") || "No details"}</td>
          <td><time dateTime={event.at}>{event.at.replace("T", " ").replace("Z", " UTC")}</time></td>
        </tr>)}</tbody>
      </table>
    </div> : <p className="security-help" role="status">No security events yet</p>}
  </section>;
}

function BrowserSecurity() {
  const [user, setUser] = useState<SessionUser | null>(null);
  const [enabled, setEnabled] = useState<boolean | null>(null);
  const [loading, setLoading] = useState(true);
  const [denied, setDenied] = useState(false);
  const [busy, setBusy] = useState(false);
  const [problem, setProblem] = useState("");
  const [signOutProblem, setSignOutProblem] = useState("");
  const [operation, setOperation] = useState<"load" | "save" | "logout">("load");
  const retryValue = useRef<boolean | null>(null);
  const [revision, setRevision] = useState(0);
  const scope = useRef<AbortController | null>(null);
  const flight = useRef(false);

  useEffect(() => {
    const controller = new AbortController();
    scope.current = controller;
    const clear = () => {
      controller.abort();
      setUser(null); setEnabled(null); setProblem(""); setSignOutProblem("");
      setBusy(false); setLoading(false); setDenied(true);
      flight.current = false;
    };
    setUser(null); setEnabled(null); setProblem(""); setSignOutProblem("");
    setLoading(true); setDenied(false); setOperation("load"); retryValue.current = null;
    async function load() {
      try {
        const identity = await me();
        if (controller.signal.aborted) return;
        if (!identity?.tenant) throw new Error("identity");
        if (currentTenant() !== null && currentTenant() !== identity.tenant) { setDenied(true); return; }
        setUser(identity);
        if (!isAdmin(identity)) { setDenied(true); return; }
        const response = await fetch(`${API_V1}/security/trusted-browser`, {
          credentials: CREDENTIALS, cache: "no-store", signal: controller.signal,
        });
        if (controller.signal.aborted || checkTenant(response)) return;
        if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
        if (response.status === 403) { setDenied(true); return; }
        const body: unknown = await response.json().catch(() => null);
        if (controller.signal.aborted) return;
        if (!response.ok || !body || typeof (body as { enabled?: unknown }).enabled !== "boolean")
          throw new Error("policy");
        setEnabled((body as { enabled: boolean }).enabled);
      } catch {
        if (!controller.signal.aborted) setProblem("Remembered browser settings could not be loaded.");
      } finally {
        if (!controller.signal.aborted) setLoading(false);
      }
    }
    window.addEventListener(UNAUTHORIZED_EVENT, clear);
    window.addEventListener("aios:signed-out", clear);
    void load();
    return () => {
      controller.abort();
      window.removeEventListener(UNAUTHORIZED_EVENT, clear);
      window.removeEventListener("aios:signed-out", clear);
    };
  }, [revision]);

  async function save(next: boolean) {
    const request = scope.current?.signal;
    if (!request || request.aborted || flight.current || !isAdmin(user) || denied || enabled === null) return;
    flight.current = true; setBusy(true); setProblem(""); setOperation("save"); retryValue.current = next;
    try {
      const response = await fetch(`${API_V1}/security/trusted-browser`, {
        method: "PUT", credentials: CREDENTIALS, cache: "no-store", signal: request,
        headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled: next }),
      });
      if (request.aborted || checkTenant(response)) return;
      if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
      if (response.status === 403) { setDenied(true); return; }
      const body: unknown = await response.json().catch(() => null);
      if (request.aborted) return;
      if (!response.ok || !body || typeof (body as { enabled?: unknown }).enabled !== "boolean")
        throw new Error("policy");
      setEnabled((body as { enabled: boolean }).enabled);
    } catch {
      if (!request.aborted) setProblem("Remembered browser settings could not be saved.");
    } finally {
      if (!request.aborted) { flight.current = false; setBusy(false); }
    }
  }

  async function signOutEverywhere() {
    const request = scope.current?.signal;
    if (!request || request.aborted || flight.current || !user) return;
    flight.current = true; setBusy(true); setSignOutProblem(""); setOperation("logout");
    try {
      const response = await fetch(`${API_V1}/auth/logout-everywhere`, {
        method: "POST", credentials: CREDENTIALS, cache: "no-store", signal: request,
      });
      if (request.aborted || checkTenant(response)) return;
      if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
      if (!response.ok) throw new Error("sign out");
      signal(UNAUTHORIZED_EVENT);
    } catch {
      if (!request.aborted) setSignOutProblem("Your account could not be signed out everywhere.");
    } finally {
      if (!request.aborted) { flight.current = false; setBusy(false); }
    }
  }

  return <>
    <section className="security-control" aria-labelledby="security-browsers-heading" data-testid="trusted-browser-settings">
      <div className="security-control-head">
        <div className="security-control-copy">
          <h4 className="set-h4" id="security-browsers-heading">Remembered browsers</h4>
          <p className="security-help">Allow browsers to skip two-step sign-in for 7 days</p>
        </div>
        <button id="security-trusted-browser" type="button" role="switch" aria-checked={enabled === true}
          aria-label="Allow remembered browsers for 7 days" className="set-secondary security-control-action"
          disabled={busy || loading || denied || enabled === null} onClick={() => void save(!enabled)}>
          {loading ? "Loading…" : busy && operation === "save" ? "Saving…" : enabled === null ? "Unavailable" : enabled ? "On" : "Off"}
        </button>
      </div>
      {loading ? <SecuritySkeleton label="Loading remembered browser settings" />
        : denied ? <p className="security-help" role="status">Only administrators can change this setting</p> : null}
      {problem ? <div className="set-error" role="alert"><span>{problem}</span>
        <button type="button" className="set-secondary" disabled={busy} onClick={() => {
          if (retryValue.current !== null) void save(retryValue.current);
          else setRevision((value) => value + 1);
        }}>Retry</button>
      </div> : null}
    </section>
    <section className="security-control" aria-labelledby="security-signout-heading">
      <div className="security-control-head">
        <div className="security-control-copy">
          <h4 className="set-h4" id="security-signout-heading">Sign out everywhere</h4>
          <p className="security-help">End all sessions for your account, including this one</p>
        </div>
        <button type="button" className="set-secondary security-control-action security-destructive"
          disabled={busy || loading || !user} onClick={() => void signOutEverywhere()}>
          {busy && operation === "logout" ? "Signing out…" : "Sign out everywhere"}
        </button>
      </div>
      {loading ? <SecuritySkeleton label="Loading sign-out settings" />
        : !user ? <p className="security-help" role="status">Sign-out controls are unavailable until your account loads</p> : null}
      {signOutProblem ? <div className="set-error" role="alert"><span>{signOutProblem}</span>
        <button type="button" className="set-secondary" disabled={busy} onClick={() => void signOutEverywhere()}>Retry</button>
      </div> : null}
    </section>
  </>;
}

export default function SecurityPane({ gate }: { gate?: EnrolmentGate } = {}) {
  const [status, setStatus] = useState<MFAStatus | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [reload, setReload] = useState<number>(0);
  const [password, setPassword] = useState<string>("");
  const [busy, setBusy] = useState<boolean>(false);
  const [codes, setCodes] = useState<string[] | null>(null);
  const [error, setError] = useState<string>("");
  const [device, setDevice] = useState<boolean>(false);
  const [recovering, setRecovering] = useState(false);
  const [setup, setSetup] = useState<MFASetup | null>(null);
  const [code, setCode] = useState<string>("");
  const [preparing, setPreparing] = useState<boolean>(false);
  const [setupRetry, setSetupRetry] = useState<number>(0);
  const [enrolledUser, setEnrolledUser] = useState<SessionUser | null>(null);
  const flight = useRef<boolean>(false);
  const dialog = useRef<HTMLDialogElement>(null);
  const passwordField = useRef<HTMLInputElement>(null);
  const recoveryAction = useRef<HTMLButtonElement>(null);
  const enrolForm = useRef<HTMLFormElement>(null);
  const focusCodeOnRetry = useRef<boolean>(false);
  const heading = useRef<HTMLHeadingElement>(null);
  const locked = busy || codes !== null;
  const gateUsername = gate?.username;
  const gatePassword = gate?.password;
  const requestScope = useRef<AbortController | null>(null);

  useLayoutEffect(() => {
    const scope = new AbortController();
    requestScope.current = scope;
    const clear = () => {
      flight.current = false;
      focusCodeOnRetry.current = false;
      setPassword(""); setCode(""); setSetup(null); setCodes(null); setEnrolledUser(null);
      setError(""); setBusy(false); setPreparing(false); setDevice(false); setRecovering(false); setStatus(null);
    };
    clear();
    const invalidate = () => { scope.abort(); clear(); };
    window.addEventListener(UNAUTHORIZED_EVENT, invalidate);
    window.addEventListener("aios:signed-out", invalidate);
    return () => {
      scope.abort();
      window.removeEventListener(UNAUTHORIZED_EVENT, invalidate);
      window.removeEventListener("aios:signed-out", invalidate);
    };
  }, [gateUsername, gatePassword]);

  useEffect(() => {
    if (gate) return;
    let current = true;
    const request = requestScope.current?.signal;
    setLoading(true);
    setError("");
    void mfaStatus().then((next) => {
      if (!current || !request || request.aborted) return;
      setStatus(next);
      setLoading(false);
      if (!next) setError("Security status could not be loaded.");
    });
    return () => { current = false; };
  }, [gate, reload]);

  // Scalar dependencies keep a parent re-render from replacing the candidate.
  // Starting setup is read-only; ignore a late response after Back or a retry.
  useEffect(() => {
    if (gateUsername === undefined || gatePassword === undefined) return;
    let current = true;
    const request = requestScope.current?.signal;
    heading.current?.focus();
    setPreparing(true);
    setSetup(null);
    setCode("");
    setError("");
    void mfaEnrollStart(gateUsername, gatePassword).then((result) => {
      if (!current || !request || request.aborted) return;
      setPreparing(false);
      if (result.ok === false) setError(result.message);
      else setSetup(result);
    });
    return () => { current = false; };
  }, [gateUsername, gatePassword, setupRetry]);

  // Lock BEFORE issuing codes, not only after receiving them: closing Settings
  // during the POST would throw away its only clear response. A native modal
  // makes the rail, close button and backdrop inert without changing the parent.
  // The shared Escape arbiter stops Settings' older window listener as well.
  useEscapeClose(busy, () => setError("Wait for your recovery codes before leaving."));
  useEffect(() => {
    if (!locked) return;
    const node = dialog.current;
    if (!node) return;
    node.showModal();
    return () => {
      node.close();
      (passwordField.current ?? recoveryAction.current)?.focus();
    };
  }, [locked]);

  // Retry focus follows the busy dialog's password focus restoration.
  useEffect(() => {
    if (locked || preparing || !setup || !focusCodeOnRetry.current) return;
    focusCodeOnRetry.current = false;
    enrolForm.current?.querySelector<HTMLInputElement>("#security-enrol-code")?.focus();
  }, [locked, preparing, setup]);

  async function generate(event: FormEvent) {
    event.preventDefault();
    const request = requestScope.current?.signal;
    if (!request || request.aborted) return;
    if (flight.current || codes || !status?.enrolled || !password) return;
    flight.current = true;
    setBusy(true);
    setError("");
    const result = await regenerateRecoveryCodes(password);
    if (request.aborted) return;
    // No password survives a write attempt. The response is the new set only;
    // do not re-read or cache it, and do not offer generation while it is shown.
    setPassword("");
    if (result.ok === false) {
      setError("");
      showRefusal(result.message);
    } else {
      setCodes(result.recoveryCodes);
      setStatus((previous) => previous
        ? { ...previous, recoveryCodesRemaining: result.recoveryCodes.length } : null);
    }
    flight.current = false;
    setBusy(false);
  }

  async function enrol(event: FormEvent) {
    event.preventDefault();
    const request = requestScope.current?.signal;
    if (!request || request.aborted) return;
    if (flight.current || locked || preparing) return;
    if (!setup) {
      if (gate) {
        setSetupRetry((value) => value + 1);
        return;
      }
      if (!status?.enrolled || !password) return;
      flight.current = true;
      setPreparing(true);
      setError("");
      try {
        const result = await startDevice(password);
        if (request.aborted) return;
        if (result.ok === false) {
          setError("");
          showRefusal(result.message);
          setPassword("");
        } else setSetup(result);
      } finally {
        if (!request.aborted) {
          flight.current = false;
          setPreparing(false);
        }
      }
      return;
    }
    if (!/^[0-9]{6}$/.test(code) || (!gate && (!status?.enrolled || !password))) return;
    flight.current = true;
    setBusy(true);
    setError("");
    try {
      const result: { ok: true; user?: SessionUser; recoveryCodes: string[] } | AuthFailure = gate
        ? await mfaEnrollConfirm(gate.username, gate.password, setup.secret, code)
        : await confirmDevice(password, setup.secret, code);
      if (request.aborted) return;
      if (result.ok === false) {
        focusCodeOnRetry.current = true;
        if (gate) setError(result.message);
        else {
          setError("");
          showRefusal(result.message);
        }
      } else {
        // A cookie exists only now. The frame still waits for the show-once acknowledgement.
        if (result.user) setEnrolledUser(result.user);
        setCodes(result.recoveryCodes);
        setSetup(null);
        setDevice(false);
      }
    } finally {
      if (!request.aborted) {
        setPassword("");
        setCode("");
        flight.current = false;
        setBusy(false);
      }
    }
  }

  const enrollmentForm = (gate || device) && !locked ? (
        <form className="security-form" ref={enrolForm} onSubmit={enrol}>
          {!gate ? (
            <>
              <p className="security-help">A new device replaces your recovery codes and signs out your other sessions.</p>
              <label className="security-label" htmlFor="security-device-password">Account password</label>
              <input id="security-device-password" className="security-input" type="password" autoComplete="current-password"
                ref={passwordField} value={password} disabled={preparing} required
                aria-invalid={error ? true : undefined} aria-describedby="security-message"
                onChange={(event) => { setPassword(event.target.value); setError(""); }} />
            </>
          ) : null}
          {setup ? (
            <>
              {/* The in-app encoder adds no dependency or external QR service.
                  Keep manual setup available even when the QR cannot be drawn. */}
              <p className="security-help">Type this setup code into any authenticator app.</p>
              <span className="security-label">{setup.issuer} setup code</span>
              <code className="login-mfa-secret">{setup.secret.match(/.{1,4}/g)?.join(" ")}</code>
              <div className="security-qr-setup">
                <SetupQr uri={setup.otpauthUri} />
                <span className="security-label">Authenticator setup link</span>
                <code className="login-mfa-uri">{setup.otpauthUri}</code>
              </div>
              <label className="security-label" htmlFor="security-enrol-code">First authenticator code</label>
              <CodeInput id="security-enrol-code" value={code} disabled={busy || preparing}
                onChange={(value) => { setCode(value); setError(""); }}
                invalid={Boolean(error)} describedBy="security-message" />
            </>
          ) : preparing ? <SecuritySkeleton label="Preparing your setup code" /> : null}
          <button type="submit" className="set-primary"
            disabled={preparing || (!gate && !password) || (setup !== null && !/^[0-9]{6}$/.test(code))}>
            {preparing ? "Preparing setup…" : setup ? "Confirm setup" : gate ? "Try setup again" : "Set up new device"}
          </button>
          {gate ? <button type="button" className="set-secondary" disabled={preparing} onClick={gate.onBack}>
            Back to sign in
          </button> : null}
        </form>
      ) : null;

  return (
    <div className="set-pane set-security">
      <h3 className="set-h" ref={heading} tabIndex={gate ? -1 : undefined}>Security</h3>
      {gate ? <>
        <p className="security-help">Two-step sign-in is required before the rest of the app opens.</p>
        {enrollmentForm}
      </> : <div className="security-controls">
        <section className="security-control" aria-labelledby="security-factor-heading">
          <div className="security-control-head">
            <div className="security-control-copy">
              <h4 className="set-h4" id="security-factor-heading">Two-step sign-in</h4>
              <p className="security-help">{status && !status.enrolled
                ? "Sign in again to set up your authenticator app" : "Use an authenticator app to protect your account"}</p>
            </div>
            <button type="button" className="set-secondary security-control-action"
              disabled={loading || locked || preparing || !status?.enrolled} aria-expanded={device}
              aria-controls={device ? "security-device-setup" : undefined} onClick={() => {
                setDevice(!device); setRecovering(false); setPassword(""); setCode(""); setSetup(null); setError("");
              }}>{device ? "Cancel" : "Enrol a new device"}</button>
          </div>
          {loading ? <SecuritySkeleton label="Loading two-step sign-in status" />
            : status ? <p className={`security-control-status ${status.enrolled ? "is-positive" : "is-attention"}`}>
              {status.enrolled ? "On" : "Not set up"}
              {status.enrolled && status.enrolledAt ? <> · Since <time dateTime={status.enrolledAt}>
                {new Date(status.enrolledAt).toLocaleDateString()}</time></> : null}
            </p> : <div className="set-error" role="alert">
              <span>Security status could not be loaded.</span>
              <button type="button" className="set-secondary" onClick={() => setReload((value) => value + 1)}>Retry</button>
            </div>}
          {device ? <div id="security-device-setup">{enrollmentForm}</div> : null}
        </section>
        <section className="security-control" aria-labelledby="security-recovery-heading">
          <div className="security-control-head">
            <div className="security-control-copy">
              <h4 className="set-h4" id="security-recovery-heading">Recovery codes</h4>
              <p className="security-help">Use a saved code if you lose your authenticator</p>
            </div>
            <button type="button" ref={recoveryAction} className="set-secondary security-control-action"
              disabled={loading || locked || preparing || !status?.enrolled} aria-expanded={recovering}
              aria-controls={recovering && !locked ? "security-recovery-setup" : undefined} onClick={() => {
                setRecovering(!recovering); setDevice(false); setPassword(""); setCode(""); setSetup(null); setError("");
              }}>{recovering ? "Cancel" : "Generate codes"}</button>
          </div>
          {loading ? <SecuritySkeleton label="Loading recovery code status" />
            : status?.enrolled ? <p className={`security-control-status ${status.recoveryCodesRemaining === 0 ? "is-attention" : ""}`}>
              {status.recoveryCodesRemaining === 0 ? "No recovery codes left" : `${status.recoveryCodesRemaining} codes left`}
            </p> : <p className="security-help">{status ? "Set up two-step sign-in to use recovery codes" : "Recovery code status is unavailable"}</p>}
          {recovering && !locked ? <form id="security-recovery-setup" className="security-form" onSubmit={generate}>
            <p className="security-help">New codes replace your old codes and sign out your other sessions.</p>
            <label className="security-label" htmlFor="security-password">Account password</label>
            <input id="security-password" className="security-input" type="password" autoComplete="current-password"
              ref={passwordField} value={password} disabled={busy} required autoFocus
              aria-invalid={error ? true : undefined} aria-describedby="security-message"
              onChange={(event) => { setPassword(event.target.value); setError(""); }} />
            <button type="submit" className="set-primary" disabled={!password || busy}>Generate new recovery codes</button>
          </form> : null}
        </section>
        <BrowserSecurity />
      </div>}
      <p className="security-message" id="security-message" role="status" aria-live="polite">{locked || (!gate && !status) ? "" : error}</p>
      {!gate ? <SecurityEvents /> : null}

      {/* R15/C12's explicit acknowledgement is the exception to ordinary
          dismissible dialogs. Native cancel is prevented, outside clicks have
          no close handler, and there is no close control or method=dialog form. */}
      {locked ? (
        <dialog ref={dialog} className="security-codes-dialog" aria-labelledby="security-codes-heading"
          onCancel={(event) => event.preventDefault()}>
          <h4 id="security-codes-heading" className="set-h4" tabIndex={-1} autoFocus>Recovery codes</h4>
          <div className="security-form">
            {codes ? (
              <RecoveryCodes codes={codes} onError={setError} onSaved={() => {
                if (gate) {
                  if (!enrolledUser) return;
                  gate.onEnrolled(enrolledUser, codes);
                  setEnrolledUser(null);
                  setCodes(null);
                  return;
                }
                setCodes(null);
                setError("");
                setRecovering(false);
                // Count only, independently re-read after acknowledgement.
                setReload((value) => value + 1);
              }} />
            ) : (
              <>
                <p className="security-help" role="status">Generating your recovery codes…</p>
                <button type="button" className="set-primary" disabled>Generating codes…</button>
              </>
            )}
          </div>
          <p className="security-message" role="status" aria-live="polite">{error}</p>
        </dialog>
      ) : null}
    </div>
  );
}