Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(mcp): add the consent page for Claude apps

spacesdrivedac3d12020cb
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 43c5f5c..9ebcbdf 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -26,12 +26,18 @@ const Settings = lazy(() => import('./features/settings/Settings'));
const TrackedContent = lazy(() => import('./features/analytics/tracked/TrackedContent'));
const TrackedCategory = lazy(() => import('./features/analytics/tracked/TrackedCategory'));
const NotFound = lazy(() => import('./pages/NotFound'));
+const OAuthConsent = lazy(() => import('./pages/OAuthConsent'));
const router = createBrowserRouter([
{
path: '/login',
element: <Login />,
},
+ {
+ // Supabase's OAuth server sends a person here to approve a Claude app; it stands outside the app shell
+ path: '/oauth/consent',
+ element: <ProtectedRoute><OAuthConsent /></ProtectedRoute>,
+ },
{
path: '/docs/*',
element: <DocsRedirect />,
diff --git a/frontend/src/lib/oauthConsent.ts b/frontend/src/lib/oauthConsent.ts
new file mode 100644
index 0000000..8f91a89
--- /dev/null
+++ b/frontend/src/lib/oauthConsent.ts
@@ -0,0 +1,38 @@
+import type { McpPermission } from '@shared/types/mcp.ts';
+
+const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
+
+// what each choice on the consent page lets the app do, in the person's words
+export const CONSENT_ABILITIES: Record<McpPermission, string[]> = {
+ read: [
+ 'See your connected accounts, analytics and scheduled posts',
+ 'See your settings, without any keys or tokens',
+ ],
+ write: [
+ 'Everything read only allows',
+ 'Schedule, edit and cancel Instagram posts, after you confirm each schedule or cancellation in Claude',
+ 'Change your GitHub scheduling settings',
+ ],
+};
+
+// the app returns the person to this address with a sign-in code, so it must be https, or http on this computer
+// for desktop clients that listen locally
+export function isSafeRedirect(url: string): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol === 'https:') return true;
+ return parsed.protocol === 'http:' && LOCAL_HOSTS.has(parsed.hostname);
+}
+
+// the site the person goes back to, shown so a look-alike app name cannot hide where the code is sent
+export function redirectHost(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
diff --git a/frontend/src/pages/OAuthConsent.tsx b/frontend/src/pages/OAuthConsent.tsx
new file mode 100644
index 0000000..7c53508
--- /dev/null
+++ b/frontend/src/pages/OAuthConsent.tsx
@@ -0,0 +1,124 @@
+import React, { useState } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import { AlertTriangle, Check } from 'lucide-react';
+import { Logo } from '@/components/brand/Logo';
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import SegmentedChoice from '@/components/SegmentedChoice';
+import { FieldRow } from '@/components/DetailPanel';
+import { LoadingState } from '@/components/StateViews';
+import { useDocumentTitle } from '@/hooks/use-document-title';
+import { CONSENT_ABILITIES, redirectHost } from '@/lib/oauthConsent';
+import { PERMISSION_OPTIONS } from '../features/settings/claudeAccessData';
+import { useAuth } from '../context/AuthContext';
+import { useOAuthConsent } from './useOAuthConsent';
+import type { OAuthAuthorizationDetails } from '@supabase/supabase-js';
+import type { McpPermission } from '@shared/types/mcp.ts';
+
+interface ConsentFormProps {
+ details: OAuthAuthorizationDetails;
+ busy: 'allow' | 'deny' | null;
+ onAllow: (permission: McpPermission) => void;
+ onDeny: () => void;
+}
+
+function ConsentForm({ details, busy, onAllow, onDeny }: ConsentFormProps) {
+ const { signOut } = useAuth();
+ // read only is the default, so allowing without a second look cannot change anything
+ const [permission, setPermission] = useState<McpPermission>('read');
+ const appName = details.client.name || 'This app';
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex flex-col gap-2 text-center">
+ <h1 id="consent-title" className="font-heading text-page-title font-semibold text-ink">Allow {appName} to use your Twiligent account?</h1>
+ <p className="text-body text-ink-muted">
+ After you choose, you go back to <span className="font-semibold text-ink">{redirectHost(details.redirect_uri)}</span>.
+ </p>
+ </div>
+
+ <FieldRow label={`What ${appName} may do`} htmlFor="consent-permission" group>
+ <SegmentedChoice<McpPermission>
+ name="consent-permission"
+ id="consent-permission"
+ options={PERMISSION_OPTIONS}
+ value={permission}
+ onChange={setPermission}
+ disabled={busy !== null}
+ />
+ </FieldRow>
+ <ul className="flex flex-col gap-2" aria-label={`What ${PERMISSION_OPTIONS.find(option => option.value === permission)?.label ?? ''} allows`}>
+ {CONSENT_ABILITIES[permission].map(line => (
+ <li key={line} className="flex items-start gap-2 text-body text-ink">
+ <Check className="mt-1 size-4 shrink-0 text-success" aria-hidden="true" />
+ {line}
+ </li>
+ ))}
+ </ul>
+
+ <div className="flex flex-col gap-2 sm:flex-row-reverse">
+ <Button onClick={() => onAllow(permission)} disabled={busy !== null} className="sm:flex-1">
+ {busy === 'allow' && <Spinner className="size-4" />}
+ {busy === 'allow' ? 'Allowing' : 'Allow'}
+ </Button>
+ <Button variant="outline" onClick={onDeny} disabled={busy !== null} className="sm:flex-1">
+ {busy === 'deny' && <Spinner className="size-4" />}
+ {busy === 'deny' ? 'Denying' : 'Deny'}
+ </Button>
+ </div>
+
+ <p className="text-center text-small text-ink-muted">
+ Signed in as {details.user.email}.{' '}
+ <button type="button" onClick={() => { void signOut(); }} className="font-semibold text-ink underline underline-offset-4">
+ Not you? Sign out
+ </button>
+ <br />
+ You can remove {appName} at any time in Settings, Claude.
+ </p>
+ </div>
+ );
+}
+
+function ConsentProblem({ message }: { message: string }) {
+ return (
+ <div role="alert" className="flex flex-col items-center gap-4 text-center">
+ <span className="flex size-11 items-center justify-center rounded-card bg-danger-soft text-danger">
+ <AlertTriangle className="size-5 stroke-[1.75]" aria-hidden="true" />
+ </span>
+ <h1 id="consent-title" className="font-heading text-section font-semibold text-ink">
+ <span className="sr-only">Error: </span>Claude could not be connected
+ </h1>
+ <p className="max-w-prose text-body text-ink-muted">{message}</p>
+ </div>
+ );
+}
+
+export default function OAuthConsent() {
+ useDocumentTitle('Allow access');
+ const [params] = useSearchParams();
+ const { state, busy, allow, deny } = useOAuthConsent(params.get('authorization_id'));
+
+ return (
+ <div className="flex min-h-svh items-center justify-center bg-surface px-4 py-10">
+ <section
+ aria-labelledby="consent-title"
+ aria-busy={state.kind === 'loading' || state.kind === 'leaving'}
+ className="w-full max-w-[30rem] rounded-dialog border border-line bg-popover p-8 text-popover-foreground shadow-lg sm:p-9"
+ >
+ <Logo className="mx-auto mb-6 h-7" />
+ {(state.kind === 'loading' || state.kind === 'leaving') && <h1 id="consent-title" className="sr-only">Connect an app to Twiligent</h1>}
+ {state.kind === 'loading' && <LoadingState label="Loading the request" className="min-h-40" />}
+ {state.kind === 'leaving' && <LoadingState label="Returning you to the app" className="min-h-40" />}
+ {state.kind === 'failed' && <ConsentProblem message={state.message} />}
+ {state.kind === 'ready' && (
+ <ConsentForm
+ details={state.details}
+ busy={busy}
+ onAllow={permission => { void allow(state.details, permission); }}
+ onDeny={() => { void deny(state.details); }}
+ />
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/frontend/src/pages/useOAuthConsent.ts b/frontend/src/pages/useOAuthConsent.ts
new file mode 100644
index 0000000..bd65da6
--- /dev/null
+++ b/frontend/src/pages/useOAuthConsent.ts
@@ -0,0 +1,79 @@
+import { useEffect, useState } from 'react';
+import type { OAuthAuthorizationDetails } from '@supabase/supabase-js';
+import { toast } from 'sonner';
+import { supabase } from '../lib/supabase';
+import { api } from '../services/api';
+import { isSafeRedirect } from '@/lib/oauthConsent';
+import type { McpPermission } from '@shared/types/mcp.ts';
+
+export type ConsentState =
+ | { kind: 'loading' }
+ | { kind: 'failed'; message: string }
+ | { kind: 'leaving' }
+ | { kind: 'ready'; details: OAuthAuthorizationDetails };
+
+const MISSING_REQUEST = 'This page needs the link Claude opened. Start connecting again from Claude.';
+const UNSAFE_RETURN = 'The app asked to return to an address that is not secure, so Twiligent stopped. Connect again from Claude.';
+
+// every way off this page goes through here, so an app that registered an unsafe address never receives a code
+function leaveTo(url: string): boolean {
+ if (!isSafeRedirect(url)) return false;
+ window.location.assign(url);
+ return true;
+}
+
+export function useOAuthConsent(authorizationId: string | null) {
+ const [state, setState] = useState<ConsentState>(() => (authorizationId ? { kind: 'loading' } : { kind: 'failed', message: MISSING_REQUEST }));
+ const [busy, setBusy] = useState<'allow' | 'deny' | null>(null);
+
+ useEffect(() => {
+ if (!authorizationId) return;
+ let cancelled = false;
+ void supabase.auth.oauth.getAuthorizationDetails(authorizationId).then(({ data, error }) => {
+ if (cancelled) return;
+ if (error || !data) {
+ setState({ kind: 'failed', message: `This request could not load. It may have expired; start connecting again from Claude. ${error?.message ?? ''}`.trim() });
+ return;
+ }
+ // the person approved this app before, so Supabase sends them straight back
+ if (!('authorization_id' in data)) {
+ setState(leaveTo(data.redirect_url) ? { kind: 'leaving' } : { kind: 'failed', message: UNSAFE_RETURN });
+ return;
+ }
+ setState(isSafeRedirect(data.redirect_uri) ? { kind: 'ready', details: data } : { kind: 'failed', message: UNSAFE_RETURN });
+ });
+ return () => { cancelled = true; };
+ }, [authorizationId]);
+
+ const allow = async (details: OAuthAuthorizationDetails, permission: McpPermission) => {
+ if (busy) return;
+ setBusy('allow');
+ try {
+ // the choice is saved first: the MCP server refuses an app with a sign-in but no saved choice
+ await api.approveMcpClient({ clientId: details.client.id, clientName: details.client.name || 'Claude', permission });
+ const { data, error } = await supabase.auth.oauth.approveAuthorization(details.authorization_id, { skipBrowserRedirect: true });
+ if (error || !data) throw new Error(error?.message ?? 'Supabase did not answer.');
+ if (!leaveTo(data.redirect_url)) throw new Error(UNSAFE_RETURN);
+ setState({ kind: 'leaving' });
+ } catch (err) {
+ toast.error(`Couldn't allow ${details.client.name || 'the app'}. ${(err as Error).message}`);
+ setBusy(null);
+ }
+ };
+
+ const deny = async (details: OAuthAuthorizationDetails) => {
+ if (busy) return;
+ setBusy('deny');
+ try {
+ const { data, error } = await supabase.auth.oauth.denyAuthorization(details.authorization_id, { skipBrowserRedirect: true });
+ if (error || !data) throw new Error(error?.message ?? 'Supabase did not answer.');
+ if (!leaveTo(data.redirect_url)) throw new Error(UNSAFE_RETURN);
+ setState({ kind: 'leaving' });
+ } catch (err) {
+ toast.error(`Couldn't send the refusal. ${(err as Error).message}`);
+ setBusy(null);
+ }
+ };
+
+ return { state, busy, allow, deny };
+}
diff --git a/frontend/tests/lib/oauthConsent.test.ts b/frontend/tests/lib/oauthConsent.test.ts
new file mode 100644
index 0000000..813a101
--- /dev/null
+++ b/frontend/tests/lib/oauthConsent.test.ts
@@ -0,0 +1,31 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { CONSENT_ABILITIES, isSafeRedirect, redirectHost } from '../../src/lib/oauthConsent.ts';
+
+test('an https return address is safe', () => {
+ assert.equal(isSafeRedirect('https://claude.ai/api/mcp/auth_callback?code=a&state=b'), true);
+});
+
+test('an http return address is safe only on this computer', () => {
+ assert.equal(isSafeRedirect('http://localhost:33418/callback?code=a'), true);
+ assert.equal(isSafeRedirect('http://127.0.0.1:8080/cb'), true);
+ assert.equal(isSafeRedirect('http://[::1]:8080/cb'), true);
+ assert.equal(isSafeRedirect('http://evil.example/cb'), false);
+});
+
+test('other schemes and broken addresses are refused', () => {
+ for (const url of ['javascript:alert(1)', 'data:text/html,hi', 'file:///etc/passwd', 'not a url', '']) {
+ assert.equal(isSafeRedirect(url), false, url);
+ }
+});
+
+test('the return host is shown as the site name', () => {
+ assert.equal(redirectHost('https://claude.ai/api/mcp/auth_callback'), 'claude.ai');
+ assert.equal(redirectHost('http://localhost:33418/callback'), 'localhost:33418');
+ assert.equal(redirectHost('nonsense'), 'nonsense');
+});
+
+test('each permission explains what it allows', () => {
+ assert.ok(CONSENT_ABILITIES.read.length > 0);
+ assert.ok(CONSENT_ABILITIES.write.some(line => line.includes('confirm')));
+});