Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(cms): connect a brand's WordPress site from Settings › Integrations (#1331) (#1571)
Cihan6b38c2ba69dd
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 373d3de86..67dff79a0 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -9361,6 +9361,57 @@"failed": "Couldn't reach Webflow. Try again later."}},+ "wordpress": {+ "title": "WordPress",+ "description": "Send to CMS puts {brand}'s pages on its WordPress site as draft posts. You publish them in WordPress.",+ "noBrand": "Pick a brand to connect its WordPress site.",+ "unavailable": "Couldn't read the WordPress connection right now.",+ "notConfigured": "WordPress isn't set up on this server yet.",+ "connected": "Connected",+ "refused": "Sign-in refused",+ "site": "Site: {site}",+ "account": "signs in as {account}",+ "notConnectedMember": "Not connected. Admins and managers can connect WordPress.",+ "refusedMember": "WordPress refused the sign-in. Pages can't go there until an admin or manager connects it again.",+ "pagesGoTo": "Pages go to {site} as draft posts.",+ "siteLabel": "Site address",+ "sitePlaceholder": "https://blog.example.com",+ "userLabel": "User",+ "userPlaceholder": "WordPress user name",+ "passwordLabel": "Application Password",+ "passwordPlaceholder": "xxxx xxxx xxxx xxxx xxxx xxxx",+ "passwordShort": "That's shorter than an Application Password: WordPress makes one of 24 letters and digits. Paste the one it made, not the user's own password.",+ "passwordHint": "In WordPress: Users › Profile › Application Passwords. Name it Ansvisor, add it, and paste it here. A separate user with the Author role is enough: Ansvisor writes drafts only. It's kept encrypted by our API, never shown again.",+ "connect": "Connect",+ "connecting": "Checking the site…",+ "connectedToast": "WordPress connected",+ "refusedNote": "WordPress refused the saved sign-in. Connect it again to send pages.",+ "replace": "Change sign-in",+ "cancel": "Cancel",+ "disconnect": "Disconnect",+ "disconnectTitle": "Disconnect WordPress?",+ "disconnectDescription": "Pages stop going to WordPress, and its Application Password is revoked where the site allows. Posts already sent stay in WordPress.",+ "disconnected": "WordPress disconnected",+ "disconnectedNotRevoked": "WordPress disconnected. The site didn't let us revoke the Application Password: delete it in WordPress under Users › Profile.",+ "errors": {+ "not_configured": "WordPress isn't set up on this server yet.",+ "invalid": "Check the site's https address (without a port), and that you pasted the Application Password WordPress made, not the user's own password.",+ "forbidden": "Only admins and managers can change the WordPress connection.",+ "not_wordpress": "There's no WordPress REST API at that address. Check the address, and that Settings › Permalinks in WordPress isn't set to Plain.",+ "no_app_passwords": "This site has Application Passwords turned off. WordPress 5.6 and later have them; a security plugin may turn them off.",+ "auth_failed": "WordPress refused the user or the Application Password. Check them and try again.",+ "header_dropped": "The site's server didn't pass the sign-in on to WordPress. In WordPress, save Settings › Permalinks once, or ask your host to pass the Authorization header.",+ "users_hidden": "The site hides its users from the REST API, as some security plugins do. Let signed-in users reach /wp-json/wp/v2/users/me.",+ "site_refused": "The site refused the request: a firewall or a security plugin may block its REST API.",+ "redirect": "The site sends its /wp-json/ address on to another one. If it's a WordPress site, use the address it goes to (with or without www); if it isn't, there's no WordPress here.",+ "no_access": "This user can't write posts on the site. Use an Author, an Editor or an Administrator.",+ "unreachable": "The site couldn't be reached. Check the address and try again.",+ "session": "Your session expired. Sign in again.",+ "workspace": "This brand isn't in your workspace.",+ "busy": "Too many requests. Wait a few minutes.",+ "failed": "Couldn't reach WordPress. Try again later."+ }+ },"integrations_connected": "Connected","integrations_notConfigured": "Not configured","integrations_comingSoon": "Coming soon",diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsxindex 93e0e0f2d..c971e154b 100644--- a/web/src/components/settings/integrations-section.tsx+++ b/web/src/components/settings/integrations-section.tsx@@ -44,6 +44,7 @@ import { CatalogSourcesCard, type CatalogSourcesRead } from './catalog-sources-cimport { CatalogCategoryPages } from './catalog-category-pages';import { MerchantCenterAccounts } from './merchant-center-accounts';import { WebflowCard } from './webflow-card';+import { WordPressCard } from './wordpress-card';import { useIntegrationConnect } from '@/hooks/use-integration-connect';import { useUpgradeGate } from '@/components/providers/upgrade-gate';@@ -129,6 +130,8 @@ export function IntegrationsSection() {{/* Send to CMS destinations: a new CMS's card goes in this group. */}<IntegrationGroup title={t('integrations_cms')}><WebflowCard />++ <WordPressCard /></IntegrationGroup></CardContent></Card>diff --git a/web/src/components/settings/wordpress-card.test.tsx b/web/src/components/settings/wordpress-card.test.tsxnew file mode 100644index 000000000..ebe3efc94--- /dev/null+++ b/web/src/components/settings/wordpress-card.test.tsx@@ -0,0 +1,316 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import type { WordPressConnection, WordPressError } from '@/lib/wordpress-client';++const client = vi.hoisted(() => ({+ readWordPress: vi.fn(),+ connectWordPress: vi.fn(),+ disconnectWordPress: vi.fn(),+}));+vi.mock('@/lib/wordpress-client', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/wordpress-client')>()),+ ...client,+}));+const role = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));+const store = vi.hoisted(() => ({ activeBrandId: 'b1' }));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: () => ({+ activeBrandId: store.activeBrandId,+ brands: [+ { id: 'b1', name: 'Acme' },+ { id: 'b2', name: 'Beta' },+ ],+ }),+}));+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn(), warning: vi.fn() }));+vi.mock('sonner', () => ({ toast }));+// The read-only workspace's upgrade dialog.+const openUpgrade = vi.hoisted(() => vi.fn());+const gate = vi.hoisted(() => ({ isLocked: false }));+vi.mock('@/components/providers/upgrade-gate', () => ({+ useUpgradeGate: () => ({+ isLocked: gate.isLocked,+ openUpgrade,+ guard:+ <Args extends unknown[]>(fn: (...args: Args) => unknown, options: { action?: string } = {}) =>+ (...args: Args) =>+ gate.isLocked ? openUpgrade(options.action) : fn(...args),+ }),+}));++const { WordPressCard } = await import('./wordpress-card');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++/** Settings › Integrations › WordPress (Send to CMS #1331, phase 2; 00294): a brand's site and sign-in. */++// Every reason the client names has its words: a missing one fails typecheck. A read-only+// workspace's refusal opens the upgrade dialog instead.+const ERROR_TEXTS: Record<Exclude<WordPressError, 'subscription'>, string> = messages.settings+ .wordpress.errors;++let container: HTMLDivElement;+let root: Root;++const CONNECTED: WordPressConnection = {+ status: 'connected',+ siteUrl: 'https://blog.acme.example',+ siteName: 'Acme Coffee Blog',+ account: 'editor',+ connectedAt: '2026-10-27T10:00:00Z',+ updatedAt: '2026-10-27T10:00:00Z',+};++async function render() {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <WordPressCard />+ </NextIntlClientProvider>,+ );+ });+}+const button = (label: string, within: ParentNode = container) =>+ [...within.querySelectorAll('button')].find((b) => b.textContent === label);+const click = async (el: Element | undefined) => {+ await act(async () => {+ el!.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ (el as HTMLElement).click();+ });+};+/** The input a label names. */+const field = (label: string) => {+ const name = [...container.querySelectorAll('label')].find((l) => l.textContent === label);+ return container.querySelector<HTMLInputElement>(`[id="${name!.htmlFor}"]`)!;+};+async function type(label: string, value: string) {+ const input = field(label);+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ setter.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}+const submit = async () => {+ await act(async () => {+ container+ .querySelector('form')!+ .dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));+ });+};++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ role.canManage = true;+ store.activeBrandId = 'b1';+ gate.isLocked = false;+ openUpgrade.mockReset();+ for (const fn of Object.values(client)) fn.mockReset();+ for (const fn of Object.values(toast)) fn.mockReset();+ client.readWordPress.mockResolvedValue({ ok: true, configured: true, connection: null });+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('WordPressCard', () => {+ it('connects the site with a user and an Application Password, never keeping the password', async () => {+ client.connectWordPress.mockResolvedValue({ ok: true, connection: CONNECTED });+ await render();+ expect(field('Application Password').type).toBe('password');+ expect(button('Connect')!.disabled).toBe(true);+ await type('Site address', 'blog.acme.example ');+ await type('User', 'editor');+ await type('Application Password', 'abcd efgh ijkl mnop qrst uvwx');+ await submit();+ expect(client.connectWordPress).toHaveBeenCalledWith('b1', {+ siteUrl: 'blog.acme.example',+ username: 'editor',+ password: 'abcd efgh ijkl mnop qrst uvwx',+ });+ expect(toast.success).toHaveBeenCalledWith('WordPress connected');+ expect(container.textContent).toContain('Connected');+ expect(container.textContent).toContain('Site: https://blog.acme.example · signs in as editor');+ expect(container.textContent).toContain('Pages go to Acme Coffee Blog as draft posts.');+ expect(container.querySelector('input[type="password"]')).toBeNull();+ });++ it('offers no saved password, and stops a password too short to be an Application Password', async () => {+ await render();+ expect(field('Application Password').autocomplete).toBe('new-password');+ await type('Site address', 'blog.acme.example');+ await type('User', 'editor');+ await type('Application Password', 'hunter2 pass');+ expect(button('Connect')!.disabled).toBe(true);+ expect(container.textContent).toContain(messages.settings.wordpress.passwordShort);+ await type('Application Password', 'abcd efgh ijkl mnop qrst uvwx');+ expect(button('Connect')!.disabled).toBe(false);+ expect(container.textContent).not.toContain(messages.settings.wordpress.passwordShort);+ });++ it('says what the site answered, in our words, and keeps what was typed', async () => {+ client.connectWordPress.mockResolvedValue({ ok: false, code: 'header_dropped' });+ await render();+ await type('Site address', 'blog.acme.example');+ await type('User', 'editor');+ await type('Application Password', 'abcd efgh ijkl mnop qrst uvwx');+ await submit();+ expect(toast.error).toHaveBeenCalledWith(ERROR_TEXTS.header_dropped);+ expect(field('Site address').value).toBe('blog.acme.example');+ });++ it('asks to connect again after a refused sign-in, with the site and user filled in', async () => {+ client.readWordPress.mockResolvedValue({+ ok: true,+ configured: true,+ connection: { ...CONNECTED, status: 'auth_failed' },+ });+ await render();+ expect(container.textContent).toContain('Sign-in refused');+ expect(container.textContent).toContain('WordPress refused the saved sign-in.');+ expect(field('Site address').value).toBe('https://blog.acme.example');+ expect(field('User').value).toBe('editor');+ expect(field('Application Password').value).toBe('');+ });++ it('changes the sign-in on demand, and goes back on Cancel, not while the site is checked', async () => {+ client.readWordPress.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });+ await render();+ expect(container.querySelector('form')).toBeNull();+ await click(button('Change sign-in'));+ expect(container.querySelector('form')).not.toBeNull();+ await click(button('Cancel'));+ expect(container.querySelector('form')).toBeNull();++ await click(button('Change sign-in'));+ client.connectWordPress.mockReturnValueOnce(new Promise(() => {}));+ await type('Application Password', 'abcd efgh ijkl mnop qrst uvwx');+ await submit();+ expect(button('Cancel')!.disabled).toBe(true);+ });++ it('shows another brand’s connection never, while its own is read', async () => {+ client.readWordPress.mockResolvedValueOnce({+ ok: true,+ configured: true,+ connection: CONNECTED,+ });+ await render();+ expect(container.textContent).toContain('https://blog.acme.example');+ client.readWordPress.mockReturnValueOnce(new Promise(() => {}));+ store.activeBrandId = 'b2';+ await render();+ expect(container.textContent).not.toContain('https://blog.acme.example');+ expect(client.readWordPress).toHaveBeenLastCalledWith('b2');+ });++ it('disconnects, saying so when the password was revoked too', async () => {+ client.readWordPress.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });+ client.disconnectWordPress.mockResolvedValue({ ok: true, success: true, revoked: true });+ await render();+ await click(button('Disconnect'));+ await click(button('Disconnect', document.querySelector('[role="dialog"]')!));+ expect(toast.success).toHaveBeenCalledWith('WordPress disconnected');+ expect(toast.warning).not.toHaveBeenCalled();+ });++ it('disconnects, and says to delete the password in WordPress when the site didn’t let it go', async () => {+ client.readWordPress.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });+ client.disconnectWordPress.mockResolvedValue({ ok: true, success: true, revoked: false });+ await render();+ await click(button('Disconnect'));+ await click(button('Disconnect', document.querySelector('[role="dialog"]')!));+ expect(client.disconnectWordPress).toHaveBeenCalledWith('b1');+ expect(toast.warning).toHaveBeenCalledWith(messages.settings.wordpress.disconnectedNotRevoked);+ expect(container.textContent).not.toContain('Connected');+ });++ it('shows members where pages go, with no form or buttons', async () => {+ role.canManage = false;+ client.readWordPress.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });+ await render();+ expect(container.textContent).toContain('Pages go to Acme Coffee Blog as draft posts.');+ expect(container.querySelector('form')).toBeNull();+ expect(button('Disconnect')).toBeUndefined();+ client.readWordPress.mockResolvedValue({ ok: true, configured: true, connection: null });+ act(() => root.unmount());+ root = createRoot(container);+ await render();+ expect(container.textContent).toContain(+ 'Not connected. Admins and managers can connect WordPress.',+ );+ });++ it('says when the server can’t keep a sign-in, or the connection can’t be read', async () => {+ client.readWordPress.mockResolvedValue({ ok: true, configured: false, connection: null });+ await render();+ expect(container.textContent).toContain("WordPress isn't set up on this server yet.");+ act(() => root.unmount());+ root = createRoot(container);+ client.readWordPress.mockResolvedValue({ ok: false, code: 'failed' });+ await render();+ expect(container.textContent).toContain("Couldn't read the WordPress connection right now.");+ });+ it('opens the upgrade dialog, not an error, when a read-only workspace’s connect or disconnect is refused', async () => {+ client.connectWordPress.mockResolvedValue({ ok: false, code: 'subscription' });+ await render();+ await type('Site address', 'blog.acme.example');+ await type('User', 'editor');+ await type('Application Password', 'abcd efgh ijkl mnop qrst uvwx');+ await submit();+ expect(client.connectWordPress).toHaveBeenCalledTimes(1);+ expect(openUpgrade).toHaveBeenCalledTimes(1);+ expect(toast.error).not.toHaveBeenCalled();++ client.readWordPress.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });+ client.disconnectWordPress.mockResolvedValue({ ok: false, code: 'subscription' });+ act(() => root.unmount());+ root = createRoot(container);+ await render();+ await click(button('Disconnect'));+ const confirm = [...document.body.querySelectorAll('button')].filter(+ (b) => b.textContent === 'Disconnect',+ );+ await click(confirm[confirm.length - 1]);+ expect(client.disconnectWordPress).toHaveBeenCalledTimes(1);+ expect(openUpgrade).toHaveBeenCalledTimes(2);+ expect(toast.error).not.toHaveBeenCalled();+ });++ it('on a read-only workspace, connects and changes nothing, and still disconnects', async () => {+ gate.isLocked = true;+ await render();+ await type('Site address', 'blog.acme.example');+ await type('User', 'editor');+ await type('Application Password', 'abcd efgh ijkl mnop qrst uvwx');+ await submit();+ expect(openUpgrade).toHaveBeenLastCalledWith('Connecting your CMS needs a plan');+ expect(client.connectWordPress).not.toHaveBeenCalled();++ client.readWordPress.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });+ client.disconnectWordPress.mockResolvedValue({ ok: true, success: true, revoked: true });+ act(() => root.unmount());+ root = createRoot(container);+ await render();+ await click(button('Change sign-in'));+ expect(openUpgrade).toHaveBeenLastCalledWith('Connecting your CMS needs a plan');+ expect(container.querySelector('input[type="password"]')).toBeNull();+ // Disconnect ends an access: it stays open.+ await click(button('Disconnect'));+ const confirm = [...document.body.querySelectorAll('button')].filter(+ (b) => b.textContent === 'Disconnect',+ );+ await click(confirm[confirm.length - 1]);+ expect(client.disconnectWordPress).toHaveBeenCalledWith('b1');+ expect(toast.success).toHaveBeenCalledWith('WordPress disconnected');+ });+});diff --git a/web/src/components/settings/wordpress-card.tsx b/web/src/components/settings/wordpress-card.tsxnew file mode 100644index 000000000..13a4b99fa--- /dev/null+++ b/web/src/components/settings/wordpress-card.tsx@@ -0,0 +1,346 @@+'use client';++import { useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { AlertTriangle, Loader2, Newspaper, Unplug } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Skeleton } from '@/components/ui/skeleton';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@/components/ui/dialog';+import { useUserRole } from '@/hooks/use-user-role';+import {+ connectWordPress,+ disconnectWordPress,+ readWordPress,+ type WordPressConnection,+} from '@/lib/wordpress-client';+import { useBrandStore } from '@/stores/use-brand-store';++/**+ * Send to CMS → WordPress (#1331, phase 2; 00294): the active brand's+ * WordPress site. Admins and managers connect it with a user's Application+ * Password, replace the sign-in and disconnect; members see where pages go.+ * Pages go as draft posts, published in WordPress.+ */+export function WordPressCard() {+ const t = useTranslations('settings.wordpress');+ const { activeBrandId, brands } = useBrandStore();+ const { canManage } = useUserRole();+ // A read-only workspace's refusal opens the upgrade dialog, not a toast;+ // while it is read-only, Change sign-in opens it at once. Disconnect stays+ // open: it ends an access, it starts nothing.+ const { guard, openUpgrade } = useUpgradeGate();+ const tActions = useTranslations('readOnly.actions');+ const brand = brands.find((b) => b.id === activeBrandId) ?? null;++ // The connection as read for a brand: another brand's never shows.+ const [read, setRead] = useState<{+ brandId: string;+ configured: boolean;+ connection: WordPressConnection | null;+ failed: boolean;+ } | null>(null);+ // Replacing the sign-in, for the brand it was asked for.+ const [replacingFor, setReplacingFor] = useState<string | null>(null);+ const replacing = replacingFor !== null && replacingFor === activeBrandId;+ const [disconnecting, setDisconnecting] = useState(false);++ useEffect(() => {+ if (!activeBrandId) return;+ let cancelled = false;+ readWordPress(activeBrandId).then((result) => {+ if (cancelled) return;+ setRead(+ result.ok+ ? {+ brandId: activeBrandId,+ configured: result.configured,+ connection: result.connection,+ failed: false,+ }+ : { brandId: activeBrandId, configured: true, connection: null, failed: true },+ );+ });+ return () => {+ cancelled = true;+ };+ }, [activeBrandId]);++ const current = read?.brandId === activeBrandId ? read : null;+ const connection = current?.connection ?? null;+ const setConnection = (next: WordPressConnection | null) =>+ setRead((r) => (r && r.brandId === activeBrandId ? { ...r, connection: next } : r));+ const site = connection ? (connection.siteName ?? connection.siteUrl) : '';++ const disconnect = async () => {+ if (!activeBrandId) return;+ setDisconnecting(true);+ const result = await disconnectWordPress(activeBrandId);+ setDisconnecting(false);+ if (!result.ok) {+ if (result.code === 'subscription') openUpgrade();+ else toast.error(t(`errors.${result.code}`));+ return;+ }+ setConnection(null);+ setReplacingFor(null);+ // Not revoked: the password still works until it's deleted in WordPress.+ if (result.revoked) toast.success(t('disconnected'));+ else toast.warning(t('disconnectedNotRevoked'));+ };++ return (+ <div className="space-y-4 rounded-lg border p-4">+ <div className="flex items-start gap-3">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md border bg-muted/50">+ <Newspaper className="h-5 w-5 text-muted-foreground" />+ </div>+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <p className="text-sm font-medium">{t('title')}</p>+ {connection?.status === 'connected' && (+ <Badge+ variant="outline"+ className="border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"+ >+ {t('connected')}+ </Badge>+ )}+ {connection?.status === 'auth_failed' && (+ <Badge+ variant="outline"+ className="border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-400"+ >+ {t('refused')}+ </Badge>+ )}+ </div>+ <p className="text-sm text-muted-foreground">+ {brand ? t('description', { brand: brand.name }) : t('noBrand')}+ </p>+ {connection && (+ <p className="mt-1 text-xs text-muted-foreground [overflow-wrap:anywhere]">+ {t('site', { site: connection.siteUrl })}+ {' · '}+ {t('account', { account: connection.account })}+ </p>+ )}+ {canManage && connection && (+ <div className="mt-3 flex flex-wrap items-center gap-2">+ {!replacing && current?.configured && connection.status === 'connected' && (+ <Button+ variant="outline"+ size="sm"+ onClick={guard(() => setReplacingFor(activeBrandId), {+ action: tActions('connectCms'),+ })}+ >+ {t('replace')}+ </Button>+ )}+ <Dialog>+ <DialogTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="gap-2"+ disabled={disconnecting}+ />+ }+ >+ {disconnecting ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Unplug className="h-3.5 w-3.5" />+ )}+ {t('disconnect')}+ </DialogTrigger>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t('disconnectTitle')}</DialogTitle>+ <DialogDescription>{t('disconnectDescription')}</DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>{t('cancel')}</DialogClose>+ <DialogClose render={<Button variant="destructive" onClick={disconnect} />}>+ {t('disconnect')}+ </DialogClose>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )}+ </div>+ </div>++ {!activeBrandId ? null : !current ? (+ <Skeleton className="h-16 w-full" />+ ) : current.failed ? (+ <p className="text-sm text-muted-foreground">{t('unavailable')}</p>+ ) : !current.configured ? (+ <p className="text-sm text-muted-foreground">{t('notConfigured')}</p>+ ) : !canManage ? (+ <p className="text-sm text-muted-foreground">+ {!connection+ ? t('notConnectedMember')+ : connection.status === 'auth_failed'+ ? t('refusedMember')+ : t('pagesGoTo', { site })}+ </p>+ ) : !connection || connection.status === 'auth_failed' || replacing ? (+ <div className="space-y-3">+ {connection?.status === 'auth_failed' && (+ <div className="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300">+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />+ <span>{t('refusedNote')}</span>+ </div>+ )}+ <SignInForm+ brandId={activeBrandId}+ // Connecting again, the site and user as they were.+ initial={connection}+ onCancel={replacing ? () => setReplacingFor(null) : undefined}+ onConnected={(next) => {+ setReplacingFor(null);+ setConnection(next);+ }}+ />+ </div>+ ) : (+ <p className="text-sm text-muted-foreground">{t('pagesGoTo', { site })}</p>+ )}+ </div>+ );+}++/** The site, its user and an Application Password: the password goes to the API once, never shown again. */+function SignInForm({+ brandId,+ initial,+ onConnected,+ onCancel,+}: {+ brandId: string;+ initial: WordPressConnection | null;+ onConnected: (connection: WordPressConnection) => void;+ onCancel?: () => void;+}) {+ const t = useTranslations('settings.wordpress');+ // Read-only (plan not active): Connect opens the upgrade dialog before anything is sent.+ const { guard, openUpgrade } = useUpgradeGate();+ const tActions = useTranslations('readOnly.actions');+ const [siteUrl, setSiteUrl] = useState(initial?.siteUrl ?? '');+ const [username, setUsername] = useState(initial?.account ?? '');+ const [password, setPassword] = useState('');+ const [connecting, setConnecting] = useState(false);+ const id = (field: string) => `wordpress-${field}-${brandId}`;+ // An Application Password is 24 letters and digits; a user's own password is the usual mix-up.+ const short = password.trim() !== '' && password.replace(/\s+/g, '').length < 16;+ const ready = siteUrl.trim() && username.trim() && password.trim() && !short;++ const connect = async () => {+ setConnecting(true);+ const result = await connectWordPress(brandId, {+ siteUrl: siteUrl.trim(),+ username: username.trim(),+ password: password.trim(),+ });+ setConnecting(false);+ if (!result.ok) {+ if (result.code === 'subscription') openUpgrade();+ else toast.error(t(`errors.${result.code}`));+ return;+ }+ setPassword('');+ toast.success(t('connectedToast'));+ onConnected(result.connection);+ };+ const connectSite = guard(() => void connect(), { action: tActions('connectCms') });++ return (+ <form+ className="space-y-3"+ onSubmit={(e) => {+ e.preventDefault();+ if (ready && !connecting) connectSite();+ }}+ >+ <div className="grid gap-3 sm:grid-cols-2">+ <div className="space-y-1.5 sm:col-span-2">+ <Label htmlFor={id('site')}>{t('siteLabel')}</Label>+ <Input+ id={id('site')}+ inputMode="url"+ autoComplete="url"+ spellCheck={false}+ value={siteUrl}+ onChange={(e) => setSiteUrl(e.target.value)}+ placeholder={t('sitePlaceholder')}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor={id('user')}>{t('userLabel')}</Label>+ <Input+ id={id('user')}+ autoComplete="off"+ spellCheck={false}+ value={username}+ onChange={(e) => setUsername(e.target.value)}+ placeholder={t('userPlaceholder')}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor={id('password')}>{t('passwordLabel')}</Label>+ <Input+ id={id('password')}+ aria-describedby={id('hint')}+ aria-invalid={short || undefined}+ type="password"+ // Not a sign-in to Ansvisor: no saved password is offered here.+ autoComplete="new-password"+ spellCheck={false}+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder={t('passwordPlaceholder')}+ />+ </div>+ </div>+ <p id={id('hint')} className="text-xs text-muted-foreground">+ {t('passwordHint')}+ </p>+ {short && <p className="text-xs text-amber-700 dark:text-amber-400">{t('passwordShort')}</p>}+ <div className="flex flex-wrap gap-2">+ <Button type="submit" size="sm" className="h-9 gap-2" disabled={!ready || connecting}>+ {connecting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {connecting ? t('connecting') : t('connect')}+ </Button>+ {onCancel && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-9"+ disabled={connecting}+ onClick={onCancel}+ >+ {t('cancel')}+ </Button>+ )}+ </div>+ </form>+ );+}diff --git a/web/src/lib/wordpress-client.test.ts b/web/src/lib/wordpress-client.test.tsnew file mode 100644index 000000000..9239e1a72--- /dev/null+++ b/web/src/lib/wordpress-client.test.ts@@ -0,0 +1,70 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** Send to CMS › WordPress (#1331, phase 2): a brand's connection from the browser, through the API's proxy. */++vi.mock('@/lib/supabase/client', () => ({+ createClient: () => ({+ auth: { getSession: async () => ({ data: { session: { access_token: 'tok' } } }) },+ }),+}));++const { connectWordPress, disconnectWordPress, readWordPress } = await import('./wordpress-client');++const fetchMock = vi.fn();+beforeEach(() => {+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+});++const answer = (status: number, body: unknown) =>+ fetchMock.mockResolvedValue(new Response(JSON.stringify(body), { status }));+const BASE = '/api/aeo/api/cms/brands/b1/wordpress';+const input = { siteUrl: 'blog.acme.example', username: 'editor', password: 'abcd efgh ijkl mnop' };++describe('wordpress-client', () => {+ it('reads the connection, and whether the server can keep a sign-in', async () => {+ answer(200, { configured: true, connection: null });+ expect(await readWordPress('b1')).toEqual({ ok: true, configured: true, connection: null });+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(BASE);+ expect(init.headers).toEqual({ Authorization: 'Bearer tok' });+ });++ it('sends the sign-in once, in the body, with the session', async () => {+ answer(200, { connection: { status: 'connected' } });+ expect(await connectWordPress('b1', input)).toEqual({+ ok: true,+ connection: { status: 'connected' },+ });+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(BASE);+ expect(init).toMatchObject({+ method: 'POST',+ body: JSON.stringify(input),+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer tok' },+ });+ });++ it('says whether the password was revoked on disconnect', async () => {+ answer(200, { success: true, revoked: false });+ expect(await disconnectWordPress('b1')).toEqual({ ok: true, success: true, revoked: false });+ expect(fetchMock.mock.calls[0][1]).toMatchObject({ method: 'DELETE' });+ });++ it("names the API's reasons, and the general ones", async () => {+ for (const code of ['header_dropped', 'not_wordpress', 'auth_failed', 'redirect']) {+ answer(409, { code, error: 'x' });+ expect(await connectWordPress('b1', input)).toEqual({ ok: false, code });+ }+ answer(401, { error: 'Unauthorized' });+ expect(await readWordPress('b1')).toEqual({ ok: false, code: 'session' });+ // A read-only workspace: the upgrade dialog's, not a message.+ answer(402, { code: 'subscription_inactive', error: 'x' });+ expect(await connectWordPress('b1', input)).toEqual({ ok: false, code: 'subscription' });+ answer(500, { code: 'something_else' });+ expect(await readWordPress('b1')).toEqual({ ok: false, code: 'failed' });+ fetchMock.mockRejectedValue(new TypeError('offline'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(await readWordPress('b1')).toEqual({ ok: false, code: 'failed' });+ });+});diff --git a/web/src/lib/wordpress-client.ts b/web/src/lib/wordpress-client.tsnew file mode 100644index 000000000..09a3d8ff5--- /dev/null+++ b/web/src/lib/wordpress-client.ts@@ -0,0 +1,119 @@+import { BROWSER_API_BASE_URL } from '@/config/api';+import { apiFailure } from '@/lib/api-failure';+import { createClient } from '@/lib/supabase/client';++/**+ * A brand's WordPress connection for Send to CMS (#1331, phase 2; 00294),+ * from the browser through the API's same-origin proxy. The Application+ * Password goes from here to the API once, which checks it with the site+ * and keeps it encrypted: never through a server action, a log or a+ * response.+ */++export interface WordPressConnection {+ status: 'connected' | 'auth_failed';+ siteUrl: string;+ siteName: string | null;+ /** The WordPress user the connection signs in as. */+ account: string;+ connectedAt: string;+ updatedAt: string;+}++export type WordPressError =+ | 'not_configured'+ | 'invalid'+ | 'forbidden'+ | 'not_wordpress'+ | 'no_app_passwords'+ | 'auth_failed'+ | 'header_dropped'+ | 'users_hidden'+ | 'site_refused'+ | 'redirect'+ | 'no_access'+ | 'unreachable'+ | 'session'+ | 'workspace'+ | 'busy'+ /** A read-only workspace (plan not active): the upgrade dialog, not a message. */+ | 'subscription'+ | 'failed';++const KNOWN: readonly WordPressError[] = [+ 'not_configured',+ 'invalid',+ 'forbidden',+ 'not_wordpress',+ 'no_app_passwords',+ 'auth_failed',+ 'header_dropped',+ 'users_hidden',+ 'site_refused',+ 'redirect',+ 'no_access',+ 'unreachable',+];++export type WordPressResult<T> = ({ ok: true } & T) | { ok: false; code: WordPressError };++async function call<T>(brandId: string, init: RequestInit = {}): Promise<WordPressResult<T>> {+ try {+ const {+ data: { session },+ } = await createClient().auth.getSession();+ if (!session) return { ok: false, code: 'session' };+ const res = await fetch(+ `${BROWSER_API_BASE_URL}/api/cms/brands/${encodeURIComponent(brandId)}/wordpress`,+ {+ ...init,+ headers: {+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),+ ...init.headers,+ Authorization: `Bearer ${session.access_token}`,+ },+ },+ );+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ if (!res.ok) {+ const known = KNOWN.find((c) => c === body.code);+ if (known) return { ok: false, code: known };+ const general = apiFailure(res.status, body);+ return {+ ok: false,+ code:+ general === 'session' ||+ general === 'workspace' ||+ general === 'busy' ||+ general === 'subscription'+ ? general+ : 'failed',+ };+ }+ return { ok: true, ...(body as T) };+ } catch (err) {+ console.error('WordPress call failed:', err);+ return { ok: false, code: 'failed' };+ }+}++/** The brand's connection, and whether this server can keep a WordPress sign-in. */+export function readWordPress(brandId: string) {+ return call<{ configured: boolean; connection: WordPressConnection | null }>(brandId);+}++/** Connects the brand's site, or replaces its sign-in: the API checks it with the site first. */+export function connectWordPress(+ brandId: string,+ input: { siteUrl: string; username: string; password: string },+) {+ return call<{ connection: WordPressConnection }>(brandId, {+ method: 'POST',+ body: JSON.stringify(input),+ });+}++/** Disconnects the brand's site; `revoked` says whether its Application Password went too. */+export function disconnectWordPress(brandId: string) {+ return call<{ success: boolean; revoked: boolean }>(brandId, { method: 'DELETE' });+}