// --------------------------------------------------------------------------- // 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>; onRotate?: () => void; disabled?: boolean; }) { return (
{notice.message} {onRotate ? ( ) : null}
); } /** 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 (
onChange(event.target.value)} />

Amazon issues this with the client secret. Include its timezone; blank means no expiry warnings.

); } /** * ⭐ 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 = { 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 { 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 { 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
{ 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); } }}>
setLabel(event.target.value)} />
{error ?

{error}

: null}
; } /** * 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>(() => Object.fromEntries(spec.fields.map((field) => [field.key, field.default ?? ""])) ); const [storedId, setStoredId] = useState(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 = {}; 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 (
{storedId === null ? <>
setEntryLabel(event.target.value)} />
{spec.scopes.length > 1 ? ( ) : (

{scopeLabel(scope)}

)}
{spec.fields.map((field) => (
setValues((current) => ({ ...current, [field.key]: event.target.value })) } />
))} {spec.type === "amazon_sp" ? ( ) : null} : null} {error ? (

{error}

) : null}
); } /** * 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>({}); 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 (

{stored ? "Test connection" : spec.type === "amazon_sp" ? "Rotate secret" : "Replace key"}

{!stored ? <>

The current key stays unchanged until the complete replacement is stored.

{fields.length > 1 ? (

{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."}

) : null} {fields.map((field) => (
setValues((current) => ({ ...current, [field.key]: event.target.value })) } />
))} {spec.type === "amazon_sp" ? ( ) : null} : null}
{error ? (

{error}

) : null}
); } /** * ⭐ 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(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

Only an admin can manage connector keys.

; if (error) return

{error}

; if (!keychain) return
; return 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>({}); const [error, setError] = useState(""); const [adding, setAdding] = useState(false); const [renaming, setRenaming] = useState(null); const [replacing, setReplacing] = useState(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

Only an admin can manage connector keys.

; if (renaming) return setRenaming(null)} onDone={() => { setRenaming(null); onChanged(); }} />; if (adding && keychain.connect && row.key !== "generic") { return
{ setAdding(false); onChanged(); }} onDone={() => { setAdding(false); onChanged(); }} />
; } if (adding && keychain.connect) { return ( { setAdding(false); onChanged(); }} onDone={() => { setAdding(false); onChanged(); }} /> ); } if (replacing && keychain.connect) { return ( { setReplacing(null); onChanged(); }} onDone={() => { setReplacing(null); onChanged(); }} /> ); } return (
{keychain.migrationPending ?

Odoo credential migration is pending. Ask an administrator to finish setup.

: null} {connectionId ?
Connection id
{connectionId}
: null} {error ? (

{error}

) : null} {keychain.entries.length ? (
    {keychain.entries.map((entry) => { const notice = row.key === "amazon_sp" ? amazonRotationNotice(entry.client_secret_rotation_deadline, now) : null; return (
  • {entry.label} {entry.status ? {entry.status} : null} {/* 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)} {notice ? ( setReplacing(entry) : undefined} /> ) : null} {tested[entry.id] && notice?.tone !== "expired" ? ( {tested[entry.id]} ) : null}
    {!ownDisconnect ? : null} {entry.replaceable && keychain.connect && !notice ? ( ) : null} {entry.testable ? ( ) : null} {ownDisconnect ? null : ( )}
  • ); })}
) : ( // One line, plus the action that fills it. Never a paragraph (DESIGN.md).

{keychain.canConnect ? "No key is stored for this connector yet." : "No key is stored for this connector, and this account cannot add one."}

)}
{keychain.canConnect && keychain.connect ? ( ) : 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 ? ( {keychain.entries.length ? "Reconnect" : "Connect"} ) : null} {keychain.canDisconnect ? ( ) : null}
); }