File size: 31,465 Bytes
e9a4c3e
 
 
 
 
 
 
 
7f72224
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
e9a4c3e
 
992a41f
e9a4c3e
7f72224
 
 
e9a4c3e
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
e9a4c3e
7f72224
e9a4c3e
 
992a41f
e9a4c3e
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
e9a4c3e
992a41f
e9a4c3e
 
 
992a41f
0e600b9
992a41f
 
 
 
 
 
 
 
 
 
0e600b9
992a41f
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
0e600b9
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
992a41f
e9a4c3e
 
 
 
 
992a41f
e9a4c3e
 
 
 
 
992a41f
e9a4c3e
 
 
 
992a41f
e9a4c3e
 
 
 
 
 
0e600b9
e9a4c3e
 
 
992a41f
e9a4c3e
 
 
 
 
0e600b9
e9a4c3e
 
 
 
 
0e600b9
e9a4c3e
 
 
 
 
 
 
 
992a41f
e9a4c3e
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
992a41f
 
e9a4c3e
 
 
 
992a41f
e9a4c3e
 
992a41f
e9a4c3e
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
a83fcff
 
 
 
 
 
 
992a41f
a83fcff
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
a83fcff
 
 
992a41f
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
992a41f
a83fcff
 
 
 
992a41f
a83fcff
 
992a41f
a83fcff
 
 
 
 
 
e9a4c3e
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
868b75a
7f72224
e9a4c3e
 
 
 
 
7f72224
868b75a
7f72224
e9a4c3e
 
 
 
 
7f72224
a83fcff
992a41f
e9a4c3e
 
 
 
 
 
 
 
 
 
 
0e600b9
 
 
 
 
e9a4c3e
 
 
 
992a41f
 
e9a4c3e
 
 
 
 
7f72224
e9a4c3e
 
 
 
 
 
 
7f72224
 
 
e9a4c3e
7f72224
e9a4c3e
 
7f72224
e9a4c3e
 
 
 
 
 
 
 
 
992a41f
e9a4c3e
992a41f
e9a4c3e
 
 
 
 
 
 
 
7f72224
 
 
e9a4c3e
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
7f72224
992a41f
 
 
 
e9a4c3e
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
992a41f
 
 
 
a83fcff
 
 
 
 
 
 
 
e9a4c3e
 
7f72224
 
 
868b75a
 
 
 
e9a4c3e
 
 
 
 
 
 
992a41f
 
 
 
7f72224
e9a4c3e
 
7f72224
e9a4c3e
 
 
 
a83fcff
e9a4c3e
 
 
992a41f
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
7f72224
 
992a41f
a83fcff
 
 
 
 
 
992a41f
a83fcff
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
e9a4c3e
 
7f72224
e9a4c3e
 
 
 
992a41f
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
e9a4c3e
7f72224
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
// ---------------------------------------------------------------------------
// connectors/KeychainTab.tsx — W49-T13, ruling R26, contract C4.
//
// ⭐⭐ R26, verbatim: *"The Keychain moves INTO it and Settings > Keychains
// becomes a link to the modal (one door)."* This file is the "moves INTO it"
// half: it replaces `ConnectorModal.tsx::KeychainTabPlaceholder` and is the ONE
// place a connector's credential is added, tested or removed.
//
// Credential editors mount only in connector Setup. Generic secrets use that same door.
//
// ⛔ THE CLIENT OWNS NO CREDENTIAL VOCABULARY. Which fields a connector asks
// for, which scopes it may take, and whether it is tenant-wide all arrive on
// C4's `keychain.connect` half. The tempting shape here is
// `type === "odoo" ? [url, db, user, api_key] : [api_key]` and that is a second
// copy of a credential SHAPE that already lives in `harness/connectors/odoo.py`
// — a connector whose credential grows a field would then need a client edit
// before it could be stored at all.
//
// ⛔⛔ A STORED SECRET LEAVES THE SERVER MASKED OR NOT AT ALL. Nothing here ever
// reads a credential back: the add form is write-only and clears on success,
// `masked` is rendered exactly as served, and there is no reveal affordance
// because the server has no route for one.
//
// Odoo's per-entry DELETE pauses that identity before removal. The existing connector-wide
// disconnect freezes all mirrors. OAuth disconnect still owns its per-user secret slot.
// ---------------------------------------------------------------------------

import { useCallback, useEffect, useState } from "react";
import { API_V1, CREDENTIALS } from "../apiContract";
import { listKeychain } from "../settings/settingsApi";
import { useEscapeClose } from "../ui/useEscapeClose";
import ConnectTutorial from "./ConnectTutorial";
import type {
  ConnectorConnectSpec,
  ConnectorKeychainEntry,
  ConnectorKeychainHalf,
} from "./ConnectorModal";
import type { ConnectorRow } from "./ConnectorsPage";

const AMAZON_ROTATION_DEADLINE_FIELD = "client_secret_rotation_deadline";
const DAY_MS = 24 * 60 * 60 * 1000;

export function amazonRotationNotice(deadline: string | undefined, now: number) {
  if (!deadline) return null;
  const remaining = Date.parse(deadline) - now;
  if (!Number.isFinite(remaining) || remaining > 30 * DAY_MS) return null;
  if (remaining <= 0) return { tone: "expired", message: "Client secret expired." };
  const days = Math.ceil(remaining / DAY_MS);
  const time = days === 1 ? "within a day" : `in ${days} days`;
  return remaining <= 7 * DAY_MS
    ? { tone: "urgent", message: `Secret expires ${time}.` }
    : { tone: "attention", message: `Client secret expires ${time}.` };
}

export function RotationNotice({ notice, onRotate, disabled = false }: {
  notice: NonNullable<ReturnType<typeof amazonRotationNotice>>;
  onRotate?: () => void;
  disabled?: boolean;
}) {
  return (
    <div
      className={`conn-kc-rotation is-${notice.tone}`}
      role={notice.tone === "expired" ? "alert" : "status"}
    >
      <span>{notice.message}</span>
      {onRotate ? (
        <button
          type="button"
          className="conn-kc-rotation-action"
          disabled={disabled}
          onClick={onRotate}
        >
          {notice.tone === "attention" ? "Rotate secret" : "Rotate now"}
        </button>
      ) : null}
    </div>
  );
}

/** Recalculate even when the tab stays open across a deadline or resumes from sleep. */
export function useRotationClock() {
  const [now, setNow] = useState(Date.now);
  useEffect(() => {
    const refresh = () => setNow(Date.now());
    const timer = window.setInterval(refresh, 60_000);
    window.addEventListener("focus", refresh);
    document.addEventListener("visibilitychange", refresh);
    return () => {
      window.clearInterval(timer);
      window.removeEventListener("focus", refresh);
      document.removeEventListener("visibilitychange", refresh);
    };
  }, []);
  return now;
}

function RotationDeadlineField({
  id, value, onChange, disabled, replacement = false,
}: {
  id: string;
  value: string;
  onChange: (value: string) => void;
  disabled: boolean;
  replacement?: boolean;
}) {
  return (
    <div className="conn-kc-field">
      <label htmlFor={id}>
        {replacement ? "New client secret expiry (optional)" : "Client secret expiry (optional)"}
      </label>
      <input
        id={id}
        name={AMAZON_ROTATION_DEADLINE_FIELD}
        type="text"
        autoComplete="off"
        placeholder="Amazon timestamp with timezone"
        aria-describedby={`${id}-help`}
        disabled={disabled}
        value={value}
        onChange={(event) => onChange(event.target.value)}
      />
      <p id={`${id}-help`} className="conn-kc-note">
        Amazon issues this with the client secret. Include its timezone; blank means no expiry warnings.
      </p>
    </div>
  );
}

/**
 * ⭐ WAVE 32 · R4 / contract C1 — WHO A CONNECTION IS FOR, in the two words the server declares.
 *
 * ⛔ THE VOCABULARY IS THE SERVER'S AND THIS IS A PRESENTATION OF IT, never a union: a scope the
 * server adds later renders as its own word rather than dropping the row (the wave-9 law).
 * ⚠ EXPORTED, AND `SettingsModal` IMPORTS IT FROM HERE rather than keeping the copy it used to
 * hold. Two label maps for one server vocabulary is [[one-question-two-normalizers]], and the
 * direction is this one because the pane is becoming a link INTO this tab.
 */
const SCOPE_LABEL: Record<string, string> = {
  business: "Business-wide",
  personal: "Personal",
};

export function scopeLabel(scope: string | undefined): string {
  const word = String(scope || "business");
  return SCOPE_LABEL[word] || word;
}

/** OAuth disconnect owns its per-user slot. Stored accounts each expose Remove by entry id. */
export function hasOwnDisconnect(row: ConnectorRow): boolean {
  return row.kind === "oauth";
}

async function post(path: string, body?: unknown): Promise<{ message: string; entryId: string }> {
  try {
    const res = await fetch(`${API_V1}${path}`, {
      method: "POST",
      credentials: CREDENTIALS,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body ?? {}),
    });
    const payload = (await res.json().catch(() => null)) as
      | { entry?: { id?: string }; error?: { message?: string } }
      | null;
    if (!res.ok) {
      return { message: payload?.error?.message || `The server answered ${res.status}.`, entryId: "" };
    }
    return { message: "", entryId: typeof payload?.entry?.id === "string" ? payload.entry.id : "" };
  } catch {
    return { message: "Cannot reach the server.", entryId: "" };
  }
}

async function testAmazonEntry(entryId: string): Promise<string> {
  if (!entryId) return "Key unavailable";
  try {
    const res = await fetch(`${API_V1}/admin/keychain/${encodeURIComponent(entryId)}/test`, {
      method: "POST",
      credentials: CREDENTIALS,
    });
    const body = (await res.json().catch(() => null)) as { ok?: boolean } | null;
    if (res.ok && body?.ok === true) return "";
  } catch {
    // Storage already succeeded. Retrying must test the same entry, never create another one.
  }
  return "Needs a test";
}

async function del(path: string): Promise<string> {
  try {
    const res = await fetch(`${API_V1}${path}`, { method: "DELETE", credentials: CREDENTIALS });
    const payload = (await res.json().catch(() => null)) as
      | { error?: { message?: string } }
      | null;
    if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`;
    return "";
  } catch {
    return "Cannot reach the server.";
  }
}

function RenameConnection({ entry, onDone, onCancel }: {
  entry: ConnectorKeychainEntry;
  onDone: () => void;
  onCancel: () => void;
}) {
  const [label, setLabel] = useState(entry.label);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  useEscapeClose(true, () => { if (!busy) onCancel(); });
  return <form className="conn-kc-form" onSubmit={async (event) => {
    event.preventDefault();
    if (busy || !label.trim()) return;
    setBusy(true);
    setError("");
    try {
      const response = await fetch(`${API_V1}/admin/keychain/${encodeURIComponent(entry.id)}`, {
        method: "PUT", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ label: label.trim() }),
      });
      const payload = await response.json().catch(() => null) as { error?: { message?: string } } | null;
      if (response.ok) onDone();
      else setError(payload?.error?.message || "The name was not saved. Try again.");
    } catch {
      setError("Cannot reach the server.");
    } finally {
      setBusy(false);
    }
  }}>
    <div className="conn-kc-field">
      <label htmlFor={`conn-kc-rename-${entry.id}`}>Connection name</label>
      <input id={`conn-kc-rename-${entry.id}`} autoFocus maxLength={80} value={label} disabled={busy}
        onChange={(event) => setLabel(event.target.value)} />
    </div>
    {error ? <p className="conn-kc-error" role="alert">{error}</p> : null}
    <div className="conn-kc-actions">
      <button type="button" className="conn-kc-btn" disabled={busy} onClick={onCancel}>Cancel</button>
      <button type="submit" className="conn-kc-btn is-primary" disabled={busy || !label.trim()}>
        {busy ? "Saving" : "Save"}
      </button>
    </div>
  </form>;
}

/**
 * The Connect form: exactly the fields C4 said this connector asks for.
 *
 * `connect.scopes` carries what the server will honour. Keep scope labels short whether a
 * reader can choose a scope or has only one allowed option.
 */
function ConnectForm({
  spec,
  label,
  onDone,
  onCancel,
}: {
  spec: ConnectorConnectSpec;
  label: string;
  onDone: () => void;
  onCancel: () => void;
}) {
  const [entryLabel, setEntryLabel] = useState(label);
  const [values, setValues] = useState<Record<string, string>>(() =>
    Object.fromEntries(spec.fields.map((field) => [field.key, field.default ?? ""]))
  );
  const [storedId, setStoredId] = useState<string | null>(null);
  const [rotationDeadline, setRotationDeadline] = useState("");
  const [scope, setScope] = useState(spec.scopes[0] || "business");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  const save = async () => {
    if (busy) return;
    setBusy(true);
    setError("");
    let entryId = storedId;
    if (entryId === null) {
      const fields: Record<string, string> = {};
      for (const field of spec.fields) {
        const value = (values[field.key] || "").trim();
        if (value) fields[field.key] = value;
      }
      if (spec.type === "amazon_sp") {
        fields[AMAZON_ROTATION_DEADLINE_FIELD] = rotationDeadline.trim();
      }
      const result = await post("/admin/keychain", {
        label: entryLabel.trim(),
        type: spec.type,
        scope,
        fields,
      });
      if (result.message) {
        setError(result.message);
        setBusy(false);
        return;
      }
      entryId = result.entryId;
      setStoredId(entryId);
      setValues({});
      setRotationDeadline("");
    }
    const message = spec.type === "amazon_sp" ? await testAmazonEntry(entryId) : "";
    if (message) {
      setError(message);
      setBusy(false);
      return;
    }
    // Values were cleared at storage; close only after the required connection test answers.
    onDone();
  };

  return (
    <div className="conn-kc-form">
      {storedId === null ? <>
      <div className="conn-kc-field">
        <label htmlFor="conn-kc-label">Name this connection</label>
        <input
          id="conn-kc-label"
          disabled={busy}
          value={entryLabel}
          maxLength={80}
          onChange={(event) => setEntryLabel(event.target.value)}
        />
      </div>
      <div className="conn-kc-field">
        <label htmlFor={spec.scopes.length > 1 ? "conn-kc-scope" : undefined}>Scope</label>
        {spec.scopes.length > 1 ? (
          <select
            id="conn-kc-scope"
            disabled={busy}
            value={scope}
            onChange={(event) => setScope(event.target.value)}
          >
            {spec.scopes.map((option) => (
              <option key={option} value={option}>
                {scopeLabel(option)}
              </option>
            ))}
          </select>
        ) : (
          <p className="conn-kc-note">
            {scopeLabel(scope)}
          </p>
        )}
      </div>
      {spec.fields.map((field) => (
        <div className="conn-kc-field" key={field.key}>
          <label htmlFor={`conn-kc-${field.key}`}>{field.label}</label>
          <input
            id={`conn-kc-${field.key}`}
            disabled={busy}
            type={field.secret ? "password" : "text"}
            autoComplete={field.secret ? "new-password" : "off"}
            value={values[field.key] ?? ""}
            onChange={(event) =>
              setValues((current) => ({ ...current, [field.key]: event.target.value }))
            }
          />
        </div>
      ))}
      {spec.type === "amazon_sp" ? (
        <RotationDeadlineField
          id="conn-kc-rotation-deadline"
          value={rotationDeadline}
          onChange={setRotationDeadline}
          disabled={busy}
        />
      ) : null}
      </> : null}
      {error ? (
        <p className="conn-kc-error" role="alert">
          {error}
        </p>
      ) : null}
      <div className="conn-kc-actions">
        <button type="button" className="conn-kc-btn" disabled={busy} onClick={onCancel}>
          {storedId !== null ? "Close" : "Cancel"}
        </button>
        <button
          type="button"
          className="conn-kc-btn is-primary"
          disabled={busy || (storedId === null ? !entryLabel.trim() : !storedId)}
          onClick={() => void save()}
        >
          {busy ? (storedId !== null ? "Testing" : "Storing") : storedId !== null ? "Test again" : "Store the key"}
        </button>
      </div>
    </div>
  );
}

/**
 * A stored credential is never opened into this form. Every field starts empty and the current
 * key remains active while the server validates, merges and encrypts the replacement. Only the
 * server-declared secret fields render; account, server and database settings never cross back
 * through the browser.
 */
function ReplaceForm({
  connectorKey,
  spec,
  entry,
  onDone,
  onCancel,
}: {
  connectorKey: string;
  spec: ConnectorConnectSpec;
  entry: ConnectorKeychainEntry;
  onDone: () => void;
  onCancel: () => void;
}) {
  const [values, setValues] = useState<Record<string, string>>({});
  const [rotationDeadline, setRotationDeadline] = useState("");
  const [stored, setStored] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const fields = spec.fields.filter((field) => field.secret);
  const complete =
    fields.length > 0 && fields.every((field) => Boolean((values[field.key] || "").trim()));

  const save = async () => {
    if (busy || (!stored && !complete)) return;
    setBusy(true);
    setError("");
    if (!stored) {
      const replacement = Object.fromEntries(
        fields.map((field) => [field.key, (values[field.key] || "").trim()])
      );
      if (spec.type === "amazon_sp") {
        replacement[AMAZON_ROTATION_DEADLINE_FIELD] = rotationDeadline.trim();
      }
      const result = await post(
        `/connectors/${encodeURIComponent(connectorKey)}/keychain/${encodeURIComponent(entry.id)}/replace`,
        { fields: replacement }
      );
      if (result.message) {
        setError(result.message);
        setBusy(false);
        return;
      }
      setStored(true);
      setValues({});
      setRotationDeadline("");
    }
    const message = spec.type === "amazon_sp" ? await testAmazonEntry(entry.id) : "";
    if (message) {
      setError(message);
      setBusy(false);
      return;
    }
    // Dropping this component clears every write-only value from React state before the detail
    // payload is fetched again. No submitted credential is copied into a response-facing model.
    onDone();
  };

  return (
    <div className="conn-kc-form conn-kc-replace">
      <h3>{stored ? "Test connection" : spec.type === "amazon_sp" ? "Rotate secret" : "Replace key"}</h3>
      {!stored ? <>
      <p className="conn-kc-note">
        The current key stays unchanged until the complete replacement is stored.
      </p>
      {fields.length > 1 ? (
        <p className="conn-kc-note">
          {spec.type === "amazon_sp"
            ? "Re-enter both the client secret and refresh token together. The connection stays in place."
            : "To rotate one secret, re-enter all secrets together."}
        </p>
      ) : null}
      {fields.map((field) => (
        <div className="conn-kc-field" key={field.key}>
          <label htmlFor={`conn-kc-replace-${entry.id}-${field.key}`}>
            {`New ${field.label.toLocaleLowerCase()}`}
          </label>
          <input
            id={`conn-kc-replace-${entry.id}-${field.key}`}
            type="password"
            autoComplete="new-password"
            disabled={busy}
            value={values[field.key] ?? ""}
            onChange={(event) =>
              setValues((current) => ({ ...current, [field.key]: event.target.value }))
            }
          />
        </div>
      ))}
      {spec.type === "amazon_sp" ? (
        <RotationDeadlineField
          id={`conn-kc-replace-${entry.id}-rotation-deadline`}
          value={rotationDeadline}
          onChange={setRotationDeadline}
          disabled={busy}
          replacement
        />
      ) : null}
      </> : null}
      <div className="conn-kc-message-slot">
        {error ? (
          <p className="conn-kc-error" role="alert">
            {error}
          </p>
        ) : null}
      </div>
      <div className="conn-kc-actions">
        <button type="button" className="conn-kc-btn" disabled={busy} onClick={onCancel}>
          {stored ? "Close" : "Cancel"}
        </button>
        <button
          type="button"
          className="conn-kc-btn is-primary"
          disabled={busy || (!stored && !complete)}
          onClick={() => void save()}
        >
          {busy ? (stored ? "Testing" : "Replacing") : stored ? "Test again" : "Store replacement"}
        </button>
      </div>
    </div>
  );
}

/**
 * ⭐ THE PANEL, PURE AND EXPORTED, for the reason `ConnectorOverviewPanel` is: the modal fetches
 * on mount and `renderToStaticMarkup` runs no effects, so a static proof of this tab has to be
 * paintable from a payload rather than from a request.
 */
/** Generic secrets keep the same write-only editor under their own connector Setup. */
export function GenericSecretsSetup({ isAdmin = false }: { isAdmin?: boolean }) {
  const [version, setVersion] = useState(0);
  const [keychain, setKeychain] = useState<ConnectorKeychainHalf | null>(null);
  const [error, setError] = useState("");
  useEffect(() => {
    if (!isAdmin) return;
    let cancelled = false;
    setKeychain(null);
    setError("");
    void listKeychain().then((result) => {
      if (cancelled) return;
      if (!result.ok) { setError(result.message); return; }
      if (result.data.locked) { setError("Keys are locked."); return; }
      setKeychain({
        entries: result.data.entries.filter((entry) => entry.type === "generic").map((entry) => ({
          id: entry.id, label: entry.label, masked: entry.preview || "", scope: entry.scope || "business",
          testable: true, replaceable: false,
        })),
        canConnect: true,
        canDisconnect: false,
        connect: {
          type: "generic", tenantWide: false,
          scopes: result.data.canBusiness ? ["business", "personal"] : ["personal"],
          fields: [{ key: "name", label: "Name", secret: false },
            { key: "value", label: "Secret value", secret: true }],
        },
      });
    }).catch(() => { if (!cancelled) setError("Cannot reach the server."); });
    return () => { cancelled = true; };
  }, [isAdmin, version]);
  if (!isAdmin) return <p className="conn-setup-refusal">Only an admin can manage connector keys.</p>;
  if (error) return <div className="conn-modal-error">
    <p role="alert">{error}</p>
    <button type="button" className="conn-modal-retry" onClick={() => setVersion((value) => value + 1)}>Retry</button>
  </div>;
  if (!keychain) return <div className="conn-settings-skeleton" role="status" aria-label="Loading keys"><span /><span /><span /></div>;
  return <KeychainTab row={GENERIC_SECRETS_CONNECTOR} keychain={keychain} isAdmin={isAdmin}
    onChanged={() => setVersion((value) => value + 1)} />;
}

/** The retired generic editor has no provider detail endpoint or sync capability. */
export const GENERIC_SECRETS_CONNECTOR: ConnectorRow = {
  key: "generic", label: "Secrets", desc: "Keys for your automations", state: "available", kind: "builtin",
  section: "sources", action: "settings", manage: "keychain",
  relationshipGraph: { connectionKey: "generic", status: "ready", reason: "", tables: [], relationships: [] },
};

export default function KeychainTab({
  row,
  keychain,
  onChanged,
  connectionId,
  isAdmin = false,
}: {
  row: ConnectorRow;
  keychain: ConnectorKeychainHalf;
  /** Re-read `/detail` after a write. Without it a deleted key stays on screen until the modal
   *  is closed and reopened, which reads as a delete that did not land. */
  onChanged: (notice?: string) => void;
  connectionId?: string;
  isAdmin?: boolean;
}) {
  const [busyId, setBusyId] = useState("");
  const [tested, setTested] = useState<Record<string, string>>({});
  const [error, setError] = useState("");
  const [adding, setAdding] = useState(false);
  const [renaming, setRenaming] = useState<ConnectorKeychainEntry | null>(null);
  const [replacing, setReplacing] = useState<ConnectorKeychainEntry | null>(null);
  const now = useRotationClock();

  const runTest = useCallback(async (entry: ConnectorKeychainEntry) => {
    setTested((current) => ({ ...current, [entry.id]: "Testing" }));
    try {
      const res = await fetch(
        `${API_V1}/admin/keychain/${encodeURIComponent(entry.id)}/test`,
        { method: "POST", credentials: CREDENTIALS }
      );
      const body = (await res.json().catch(() => null)) as
        | { ok?: boolean; message?: string; error?: { message?: string } }
        | null;
      const said = row.key === "amazon_sp"
        ? (res.ok && body?.ok === true ? "Connected" : "Needs a test")
        : res.ok
          ? `${body?.ok ? "Working" : "Refused"}: ${body?.message || "the connector said nothing"}`
          : body?.error?.message || `The server answered ${res.status}.`;
      setTested((current) => ({ ...current, [entry.id]: said }));
    } catch {
      setTested((current) => ({ ...current, [entry.id]: "Cannot reach the server." }));
    }
    if (row.key === "amazon_sp") onChanged();
  }, [onChanged, row.key]);

  const remove = useCallback(
    async (entry: ConnectorKeychainEntry) => {
      const sure = window.confirm(
        `Remove the connection "${entry.label}"? A stored secret cannot be recovered.`
        + (row.key === "odoo" ? " Its Odoo mirror will pause and saved data stays available." : "")
      );
      if (!sure) return;
      setBusyId(entry.id);
      setError("");
      const message = await del(`/admin/keychain/${encodeURIComponent(entry.id)}`);
      setBusyId("");
      if (message) setError(message);
      else {
        onChanged(row.key === "odoo" ? "Odoo connection removed. Its mirror is paused." : undefined);
      }
    },
    [onChanged, row.key]
  );

  // The no-id Odoo disconnect keeps its connector-wide freeze guarantee.
  const disconnect = useCallback(async () => {
    const sure = window.confirm(
      `Disconnect ${row.label}? Data already read stays; nothing new will be read.`
    );
    if (!sure) return;
    setBusyId("disconnect");
    setError("");
    let message = "";
    if (row.key === "odoo") {
      message = (await post("/admin/connectors/odoo/disconnect")).message;
    } else if (row.kind === "oauth") {
      message = (await post(`/oauth/${encodeURIComponent(row.key)}/disconnect`)).message;
    } else {
      for (const entry of keychain.entries) {
        message = await del(`/admin/keychain/${encodeURIComponent(entry.id)}`);
        if (message) break;
      }
    }
    setBusyId("");
    if (message) setError(message);
    else {
      onChanged(row.key === "odoo" ? "Odoo disconnected. Its mirrors are paused and saved data stays available." : undefined);
    }
  }, [keychain.entries, onChanged, row.key, row.kind, row.label]);

  const ownDisconnect = hasOwnDisconnect(row);

  if (!isAdmin) return <p className="conn-setup-refusal">Only an admin can manage connector keys.</p>;

  if (renaming) return <RenameConnection entry={renaming}
    onCancel={() => setRenaming(null)} onDone={() => { setRenaming(null); onChanged(); }} />;

  if (adding && keychain.connect && row.key !== "generic") {
    return <div className="conn-kc-add">
      <button type="button" className="conn-kc-btn" onClick={() => { setAdding(false); onChanged(); }}>Back to accounts</button>
      <ConnectTutorial row={row} intent={keychain.entries.length ? "add" : "connect"}
        onOpenSettings={() => { setAdding(false); onChanged(); }}
        onDone={() => { setAdding(false); onChanged(); }} />
    </div>;
  }

  if (adding && keychain.connect) {
    return (
      <ConnectForm
        spec={keychain.connect}
        label={keychain.connect.defaultLabel ?? ""}
        onCancel={() => {
          setAdding(false);
          onChanged();
        }}
        onDone={() => {
          setAdding(false);
          onChanged();
        }}
      />
    );
  }

  if (replacing && keychain.connect) {
    return (
      <ReplaceForm
        connectorKey={row.key}
        spec={keychain.connect}
        entry={replacing}
        onCancel={() => {
          setReplacing(null);
          onChanged();
        }}
        onDone={() => {
          setReplacing(null);
          onChanged();
        }}
      />
    );
  }

  return (
    <div className="conn-kc">
      {keychain.migrationPending ? <p className="conn-kc-note" role="status">
        Odoo credential migration is pending. Ask an administrator to finish setup.
      </p> : null}
      {connectionId ? <dl className="conn-keychain-identity">
        <dt>Connection id</dt>
        <dd>{connectionId}</dd>
      </dl> : null}
      {error ? (
        <p className="conn-kc-error" role="alert">
          {error}
        </p>
      ) : null}
      {keychain.entries.length ? (
        <ul className="conn-kc-list">
          {keychain.entries.map((entry) => {
            const notice = row.key === "amazon_sp"
              ? amazonRotationNotice(entry.client_secret_rotation_deadline, now) : null;
            return (
            <li className="conn-kc-row" key={entry.id} data-connection-id={entry.connectionId || entry.id}>
              <div className="conn-kc-main">
                <span className="conn-kc-label">{entry.label}</span>
                {entry.status ? <span className="conn-kc-meta">{entry.status}</span> : null}
                <span className="conn-kc-meta">
                  {/* An empty preview is a RULE, not a gap: R4 withholds the last four characters
                      of a business key from a member who did not store it, and saying so is
                      better than an empty cell that reads as a bug. */}
                  {entry.masked ? `Stored key ${entry.masked}` : "Stored key. Preview hidden"}
                  {" · "}
                  {scopeLabel(entry.scope)}
                </span>
                {notice ? (
                  <RotationNotice
                    notice={notice}
                    disabled={Boolean(busyId)}
                    onRotate={entry.replaceable && keychain.connect
                      ? () => setReplacing(entry) : undefined}
                  />
                ) : null}
                {tested[entry.id] && notice?.tone !== "expired" ? (
                  <span className="conn-kc-test" role="status">
                    {tested[entry.id]}
                  </span>
                ) : null}
              </div>
              <div className="conn-kc-controls">
                {!ownDisconnect ? <button type="button" className="conn-kc-btn" disabled={Boolean(busyId)}
                  aria-label={`Rename ${entry.label}`} onClick={() => setRenaming(entry)}>Rename</button> : null}
                {entry.replaceable && keychain.connect && !notice ? (
                  <button
                    type="button"
                    className="conn-kc-btn"
                    disabled={Boolean(busyId)}
                    onClick={() => setReplacing(entry)}
                  >
                    {row.key === "amazon_sp" ? "Rotate secret" : "Replace"}
                  </button>
                ) : null}
                {entry.testable ? (
                  <button
                    type="button"
                    className="conn-kc-btn"
                    onClick={() => void runTest(entry)}
                  >
                    Test
                  </button>
                ) : null}
                {ownDisconnect ? null : (
                  <button
                    type="button"
                    className="conn-kc-btn is-danger"
                    disabled={Boolean(busyId)}
                    aria-label={`Remove ${entry.label}`}
                    onClick={() => void remove(entry)}
                  >
                    {busyId === entry.id ? "Removing" : "Remove"}
                  </button>
                )}
              </div>
            </li>
            );
          })}
        </ul>
      ) : (
        // One line, plus the action that fills it. Never a paragraph (DESIGN.md).
        <p className="conn-kc-empty">
          {keychain.canConnect
            ? "No key is stored for this connector yet."
            : "No key is stored for this connector, and this account cannot add one."}
        </p>
      )}
      <div className="conn-kc-actions">
        {keychain.canConnect && keychain.connect ? (
          <button
            type="button"
            className="conn-kc-btn is-primary"
            disabled={Boolean(busyId)}
            onClick={() => {
              setError("");
              setAdding(true);
            }}
          >
            {keychain.entries.length ? "Add another" : "Connect"}
          </button>
        ) : null}
        {/* An OAuth connection starts at the provider, so its Connect is a real link and not a
            form. `startUrl` is the server's, never composed here. */}
        {keychain.canConnect && !keychain.connect && row.startUrl ? (
          <a className="conn-kc-btn is-primary" href={row.startUrl}>
            {keychain.entries.length ? "Reconnect" : "Connect"}
          </a>
        ) : null}
        {keychain.canDisconnect ? (
          <button
            type="button"
            className="conn-kc-btn is-danger"
            disabled={busyId === "disconnect"}
            onClick={() => void disconnect()}
          >
            {busyId === "disconnect" ? "Disconnecting" : "Disconnect"}
          </button>
        ) : null}
      </div>
    </div>
  );
}