Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/connectors/KeychainTab.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 31.5 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/connectors/KeychainTab.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/connectors/KeychainTab.tsx
-
curl -L -o KeychainTab.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/connectors/KeychainTab.tsx
31.5 kB
| // --------------------------------------------------------------------------- | |
| // 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> | |
| ); | |
| } | |