// Secrets stay in this mounted draft until a successful test or dismissal. import { useEffect, useRef, useState } from "react"; import { Copy } from "@phosphor-icons/react/dist/csr/Copy"; import { Check } from "@phosphor-icons/react/dist/csr/Check"; import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, WORKSPACE_STALE_EVENT, checkTenant } from "../apiContract"; import { ConnectionWizard, GuideSteps } from "../settings/ExternalAccessPane"; import { listAutomations } from "../automation/automationApi"; import { clearConnectorDetailCache, parseConnectSpec } from "./ConnectorModal"; import type { ConnectorConnectSpec } from "./ConnectorModal"; import type { ConnectorRow } from "./ConnectorsPage"; export interface TutorialGuide { need: string; steps: string[]; failureAction: string; testNote: string; } const screenText = (value: unknown) => typeof value === "string" ? value.trim().replace(/[\u2013\u2014]/g, ", ") : ""; const object = (value: unknown): Record => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; export function parseTutorialGuide(value: unknown, mode: "database" | "ai" = "database"): TutorialGuide | null { const row = object(value); const need = screenText(row.need); const steps = Array.isArray(row.steps) ? row.steps.map(screenText).filter(Boolean) : []; const failureAction = screenText(row.failureAction); const testNote = screenText(row.testNote); const validTestNote = typeof row.testNote === "string" && (mode === "ai" || testNote !== ""); return need && steps.length && failureAction && validTestNote ? { need, steps, failureAction, testNote } : null; } type SetupSpec = ConnectorConnectSpec & { hint: string; fieldHints: Record; tutorial: TutorialGuide; initialDatabases: { key: string; label: string; selected: boolean }[]; }; type SetupRead = { phase: "loading" } | { phase: "error"; message: string } | { phase: "held" } | { phase: "ready"; spec: SetupSpec }; // Never display raw provider/exception text: a failed probe can echo a submitted secret. async function call(path: string, init?: RequestInit): Promise<{ ok: boolean; status: number; body: Record; stopped?: boolean; }> { const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init }); if (checkTenant(response)) return { ok: false, status: 409, body: {}, stopped: true }; if (response.status === 401) { window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); return { ok: false, status: 401, body: {}, stopped: true }; } return { ok: response.ok, status: response.status, body: object(await response.json().catch(() => null)) }; } export default function ConnectTutorial(props: { row: ConnectorRow; onDone: () => void; onOpenSettings: () => void; intent?: "connect" | "add"; }) { return props.row.key === "webhooks" ? : ; } function CredentialTutorial({ row, onDone, onOpenSettings, intent = "connect" }: { row: ConnectorRow; onDone: () => void; onOpenSettings: () => void; intent?: "connect" | "add"; }) { const [read, setRead] = useState({ phase: "loading" }); const [readVersion, setReadVersion] = useState(0); const [connected, setConnected] = useState(false); const [label, setLabel] = useState(row.label); const [scope, setScope] = useState(""); const [values, setValues] = useState>({}); const [selectedDatabases, setSelectedDatabases] = useState([]); const [storedId, setStoredId] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const [uncertainSave, setUncertainSave] = useState(false); const inFlight = useRef(false); const mounted = useRef(false); useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []); useEffect(() => { const controller = new AbortController(); setRead({ phase: "loading" }); void (async () => { try { const response = await call(`/connectors/${encodeURIComponent(row.key)}/detail` + "?databases_offset=0&databases_limit=1&fields=summary", { signal: controller.signal }); if (controller.signal.aborted || response.stopped) return; const keychain = object(response.body.keychain); if (!response.ok || keychain.canConnect !== true) { setRead({ phase: "error", message: response.status === 403 || keychain.canConnect === false ? "Ask your workspace administrator for permission to connect this source." : "Setup could not be loaded. Try again." }); return; } // Only Setup's explicit Add another action can add beside an existing connection. if (intent !== "add" && Array.isArray(keychain.entries) && keychain.entries.length > 0) { setRead({ phase: "held" }); return; } const rawSpec = object(keychain.connect); const spec = parseConnectSpec(rawSpec); const tutorial = parseTutorialGuide(rawSpec.tutorial); if (!spec || !tutorial) { setRead({ phase: "error", message: "Setup instructions are unavailable. Open connection settings." }); return; } const fieldHints: Record = {}; for (const value of Array.isArray(rawSpec.fields) ? rawSpec.fields : []) { const field = object(value); if (typeof field.key === "string") fieldHints[field.key] = screenText(field.hint); } setValues(Object.fromEntries(spec.fields.map((field) => [field.key, field.default ?? ""]))); setLabel(spec.defaultLabel ?? ""); setScope(spec.scopes[0]); const initialDatabases = (intent !== "add" && Array.isArray(rawSpec.initialDatabases) ? rawSpec.initialDatabases : []) .map(object).filter((item) => typeof item.key === "string" && typeof item.label === "string") .map((item) => ({ key: String(item.key), label: screenText(item.label), selected: item.selected === true })); setSelectedDatabases(initialDatabases.filter((item) => item.selected).map((item) => item.key)); setRead({ phase: "ready", spec: { ...spec, hint: screenText(rawSpec.hint), fieldHints, tutorial, initialDatabases } }); } catch { if (!controller.signal.aborted) setRead({ phase: "error", message: "Cannot reach the server. Try again." }); } })(); return () => controller.abort(); }, [row.key, readVersion, intent]); if (read.phase === "loading") return
; if (read.phase === "error") return

{read.message}

; if (read.phase === "held") return

A key is already stored.

; const { spec } = read; const complete = Boolean(label.trim()) && spec.scopes.includes(scope) && spec.fields.every((field) => Boolean(values[field.key]?.trim())); const hasSelection = spec.initialDatabases.length > 0; const test = async () => { if (inFlight.current || !complete || uncertainSave || connected) return; inFlight.current = true; setBusy(true); setError(""); let entryId = storedId; let saving = entryId === null; try { if (saving) { const result = await call("/admin/keychain", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ label: label.trim() === spec.defaultLabel ? "" : label.trim(), type: spec.type, scope, ...(hasSelection ? { initialDatabases: selectedDatabases } : {}), fields: Object.fromEntries(spec.fields.map((field) => [field.key, values[field.key].trim()])) }), }); if (!mounted.current || result.stopped) return; if (!result.ok) { const code = object(result.body.error).code; setError(result.status === 403 ? "Ask your workspace administrator for permission to add this connection." : code === "keychain_locked" ? "Ask your workspace administrator to unlock the keychain, then try again." : result.status >= 500 ? "Open connection settings to check whether the key was saved before trying again." : `The key was not saved. ${spec.tutorial.failureAction}`); if (result.status >= 500) setUncertainSave(true); return; } const id = object(result.body.entry).id; if (typeof id !== "string" || !id) { setUncertainSave(true); setError("Open connection settings to find the saved key. Do not store it again."); return; } entryId = id; setStoredId(id); clearConnectorDetailCache(); window.dispatchEvent(new CustomEvent(WORKSPACE_STALE_EVENT)); saving = false; } // Only this explicit button reaches the existing canonical test door. A retry uses the // returned ID, never another create. Draft fields remain available after a failed Test. const result = await call(`/admin/keychain/${encodeURIComponent(entryId!)}/test`, { method: "POST" }); if (!mounted.current || result.stopped) return; if (!result.ok || result.body.ok !== true) { setError(result.status === 403 ? "Ask your workspace administrator for permission to test this connection." : result.status === 404 ? "The saved key is unavailable. Open connection settings and select the current key." : `Test failed. ${spec.tutorial.failureAction}`); return; } clearConnectorDetailCache(); setValues({}); setConnected(true); } catch { if (!mounted.current) return; if (saving) { setUncertainSave(true); setError("Cannot reach the server. Open connection settings to check whether the key was saved before trying again."); } else { setError("Cannot reach the server. Check your connection, then test the saved key again."); } } finally { inFlight.current = false; if (mounted.current) setBusy(false); } }; return
}> ({ text })), { text:
Connect account
setLabel(event.target.value)} />
{spec.scopes.length > 1 ?
: null} {spec.fields.map((field) =>
setValues((current) => ({ ...current, [field.key]: event.target.value }))} /> {spec.fieldHints[field.key] ?

{spec.fieldHints[field.key]}

: null}
)} {hasSelection ?
Choose databases {spec.initialDatabases.map((database) => )}
: null} {storedId || uncertainSave ? : null}
}, ]} /> {error || connected ? <> {error ?

{error}

{storedId || uncertainSave ? : null}
: null} {connected ?

{spec.type === "stripe" || spec.type === "shopify" ? "Key stored" : spec.type === "odoo" ? "Server reachable" : "Connected"}

: null} : null}
; } type HookRead = { phase: "loading" } | { phase: "error" } | { phase: "ready"; hooks: { id: string; name: string; url: string }[] }; function WebhookTutorial({ row, onDone }: { row: ConnectorRow; onDone: () => void }) { const [hookRead, setHookRead] = useState({ phase: "loading" }); const [copiedId, setCopiedId] = useState(""); const [copying, setCopying] = useState(false); const [copyError, setCopyError] = useState(""); const guide = row.tutorial; const hasGuide = Boolean(guide); useEffect(() => { if (!hasGuide) return; const controller = new AbortController(); setHookRead({ phase: "loading" }); listAutomations(controller.signal).then((data) => { if (controller.signal.aborted || !data) return; // The URL shape matches AutomationBuilder's Hook URL field: real id, minted trigger token. const hooks = (Array.isArray(data.automations) ? data.automations : []) .filter((automation) => !automation.retired && automation.trigger?.key === "webhook" && typeof automation.trigger.token === "string" && automation.trigger.token) .map((automation) => ({ id: automation.id, name: screenText(automation.name) || "Untitled automation", url: `${window.location.origin}${API_V1}/automations/${encodeURIComponent(automation.id)}` + `/hook/${automation.trigger?.token ?? ""}`, })); setHookRead({ phase: "ready", hooks }); }).catch(() => { if (!controller.signal.aborted) setHookRead({ phase: "error" }); }); return () => controller.abort(); }, [hasGuide]); if (!guide) return

Webhook instructions are unavailable.

Automations
; const hooks = hookRead.phase === "ready" ? hookRead.hooks : []; const copyAddress = async (id: string, value: string) => { if (copying) return; setCopying(true); setCopyError(""); try { await navigator.clipboard.writeText(value); setCopiedId(id); } catch { setCopiedId(""); setCopyError("Select the URL and copy it manually."); } finally { setCopying(false); } }; const hookSteps = hookRead.phase === "loading" ? [{ id: "hook-loading", text:

Loading webhook URLs

}] : hookRead.phase === "error" ? [{ id: "hook-error", text:

Webhook URLs could not be loaded.

}] : hooks.length === 0 ? [{ id: "hook-empty", text: "No automation uses the Webhooks trigger yet." }] : hooks.map((hook) => ({ id: `hook-${hook.id}`, text: hook.name, block: hook.url })); return
Automations }> { const hook = hooks.find((item) => `hook-${item.id}` === step.id); if (!hook) return null; const copied = copiedId === hook.id; return ; }} steps={[ ...guide.steps.map((text) => ({ text })), ...hookSteps, ]} /> {copyError ?

{copyError}

: null}
; }