diff --git a/apps/api/deps.py b/apps/api/deps.py index 4c65307..38d93dd 100644 --- a/apps/api/deps.py +++ b/apps/api/deps.py @@ -25,6 +25,13 @@ verify_supabase_jwt_from_settings, ) from packages.media_engine import CloudEditingService, RenderBackend, create_render_backend +from packages.meta_integrations import ( + EncryptedSecretStore, + MetaConnectionService, + MetaGraphClient, + SecretStore, + create_meta_graph_client, +) from packages.muse_adapter import MuseAdapter, create_muse_adapter from packages.shared.config import BaseAppSettings from packages.shared.enums import ErrorCode @@ -88,6 +95,8 @@ class AppContainer: video_registry: VideoGatewayRegistry video_service: VideoGatewayService editing_service: CloudEditingService + secret_store: SecretStore + meta_service: MetaConnectionService supabase_jwks_cache: SupabaseJwksCache | None = None @classmethod @@ -103,6 +112,8 @@ def from_settings( storage: StorageBackend | None = None, video_registry: VideoGatewayRegistry | None = None, render_backend: RenderBackend | None = None, + meta_graph_client: MetaGraphClient | None = None, + secret_store: SecretStore | None = None, enable_db: bool = True, ) -> AppContainer: resolved_factory = session_factory @@ -158,6 +169,13 @@ def from_settings( storage=resolved_storage, renderer=resolved_renderer, ) + resolved_secret_store = secret_store or EncryptedSecretStore.from_settings(settings) + resolved_meta_client = meta_graph_client or create_meta_graph_client(settings) + resolved_meta_service = MetaConnectionService( + settings=settings, + graph_client=resolved_meta_client, + secret_store=resolved_secret_store, + ) return cls( settings=settings, @@ -170,6 +188,8 @@ def from_settings( video_registry=resolved_video_registry, video_service=resolved_video_service, editing_service=resolved_editing_service, + secret_store=resolved_secret_store, + meta_service=resolved_meta_service, supabase_jwks_cache=resolved_jwks, ) diff --git a/apps/api/main.py b/apps/api/main.py index 29f2352..6554a09 100644 --- a/apps/api/main.py +++ b/apps/api/main.py @@ -21,6 +21,7 @@ editing, health, jobs, + meta, projects, video, workspaces, @@ -117,6 +118,7 @@ async def metuse_error_handler(request: Request, exc: MetuseError) -> JSONRespon app.include_router(video.router) app.include_router(editing.router) app.include_router(approvals.router) + app.include_router(meta.router) app.include_router(audit.router) return app diff --git a/apps/api/routes/meta.py b/apps/api/routes/meta.py new file mode 100644 index 0000000..2c19af1 --- /dev/null +++ b/apps/api/routes/meta.py @@ -0,0 +1,325 @@ +"""Tenant-scoped Meta Account Connection, Unified Login, Capabilities & Webhook routes.""" + +from __future__ import annotations + +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import PlainTextResponse +from pydantic import BaseModel, ConfigDict, Field +from sqlalchemy.orm import Session, sessionmaker + +from apps.api.deps import ( + AppContainer, + AuthenticatedActor, + get_container, + get_current_actor, + get_request_id, + get_session_factory, +) +from packages.auth import require_permission +from packages.meta_integrations.contracts import ( + MetaCapabilitiesView, + MetaConnectedAssetView, + MetaConnectionView, + MetaWebhookReceipt, + PermissionMatrixEntry, + UnifiedLoginStartResponse, +) +from packages.shared.context import TenantContext +from packages.shared.enums import MetaConnectionType +from packages.shared.errors import WorkspaceAccessDeniedError +from packages.tenancy import rls_transaction, tenant_transaction + +router = APIRouter(prefix="/api/v1/workspaces/{workspace_id}/meta", tags=["meta"]) + + +class UnifiedLoginStartPayload(BaseModel): + model_config = ConfigDict(extra="forbid") + + connection_type: MetaConnectionType + client_id: UUID | None = None + redirect_uri: str | None = Field(default=None, max_length=512) + include_ads: bool = False + include_comments: bool = False + include_messages: bool = False + + +class UnifiedLoginCallbackPayload(BaseModel): + model_config = ConfigDict(extra="forbid") + + code: str = Field(min_length=1, max_length=2048) + state: str = Field(min_length=1, max_length=4096) + redirect_uri: str | None = Field(default=None, max_length=512) + + +class ReconnectPayload(BaseModel): + model_config = ConfigDict(extra="forbid") + + redirect_uri: str | None = Field(default=None, max_length=512) + + +def _require_ws_perm(ctx: TenantContext, permission: str) -> None: + if ctx.role_name is None: + raise WorkspaceAccessDeniedError("Access to the requested workspace is denied") + require_permission(ctx.role_name, permission) + + +@router.get("/permission-matrix", response_model=list[PermissionMatrixEntry]) +def get_meta_permission_matrix( + workspace_id: UUID, + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], +) -> list[PermissionMatrixEntry]: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (_, ctx): + _require_ws_perm(ctx, "meta:read") + return container.meta_service.get_permission_matrix() + + +@router.get("/connections", response_model=list[MetaConnectionView]) +def get_meta_connections( + workspace_id: UUID, + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], + client_id: Annotated[UUID | None, Query()] = None, +) -> list[MetaConnectionView]: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (session, ctx): + _require_ws_perm(ctx, "meta:read") + return container.meta_service.list_connections( + session, workspace_id=workspace_id, client_id=client_id + ) + + +@router.post("/connections/unified-login/start", response_model=UnifiedLoginStartResponse) +def post_unified_login_start( + workspace_id: UUID, + body: UnifiedLoginStartPayload, + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], +) -> UnifiedLoginStartResponse: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (session, ctx): + _require_ws_perm(ctx, "meta:write") + return container.meta_service.start_unified_login( + session, + workspace_id=workspace_id, + actor_user_id=actor.user_id, + connection_type=body.connection_type, + client_id=body.client_id, + redirect_uri=body.redirect_uri, + include_ads=body.include_ads, + include_comments=body.include_comments, + include_messages=body.include_messages, + request_id=request_id, + ) + + +@router.get("/connections/unified-login/callback", response_model=MetaConnectionView) +def get_unified_login_callback( + workspace_id: UUID, + code: Annotated[str, Query(min_length=1, max_length=2048)], + state: Annotated[str, Query(min_length=1, max_length=4096)], + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], + redirect_uri: Annotated[str | None, Query()] = None, +) -> MetaConnectionView: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (session, ctx): + _require_ws_perm(ctx, "meta:write") + return container.meta_service.complete_unified_login( + session, + workspace_id=workspace_id, + actor_user_id=actor.user_id, + code=code, + state=state, + redirect_uri=redirect_uri, + request_id=request_id, + ) + + +@router.post( + "/connections/unified-login/callback", + response_model=MetaConnectionView, + status_code=status.HTTP_201_CREATED, +) +def post_unified_login_callback( + workspace_id: UUID, + body: UnifiedLoginCallbackPayload, + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], +) -> MetaConnectionView: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (session, ctx): + _require_ws_perm(ctx, "meta:write") + return container.meta_service.complete_unified_login( + session, + workspace_id=workspace_id, + actor_user_id=actor.user_id, + code=body.code, + state=body.state, + redirect_uri=body.redirect_uri, + request_id=request_id, + ) + + +@router.post("/connections/{connection_id}/reconnect", response_model=UnifiedLoginStartResponse) +def post_reconnect_meta_connection( + workspace_id: UUID, + connection_id: UUID, + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], + body: ReconnectPayload | None = None, +) -> UnifiedLoginStartResponse: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (session, ctx): + _require_ws_perm(ctx, "meta:write") + return container.meta_service.reconnect_connection( + session, + workspace_id=workspace_id, + connection_id=connection_id, + actor_user_id=actor.user_id, + redirect_uri=body.redirect_uri if body else None, + request_id=request_id, + ) + + +@router.delete("/connections/{connection_id}", response_model=MetaConnectionView) +def delete_meta_connection( + workspace_id: UUID, + connection_id: UUID, + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], +) -> MetaConnectionView: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (session, ctx): + _require_ws_perm(ctx, "meta:write") + return container.meta_service.disconnect_connection( + session, + workspace_id=workspace_id, + connection_id=connection_id, + actor_user_id=actor.user_id, + request_id=request_id, + ) + + +@router.get("/connections/{connection_id}/assets", response_model=list[MetaConnectedAssetView]) +def get_meta_connection_assets( + workspace_id: UUID, + connection_id: UUID, + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], +) -> list[MetaConnectedAssetView]: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (session, ctx): + _require_ws_perm(ctx, "meta:read") + return container.meta_service.list_connection_assets( + session, workspace_id=workspace_id, connection_id=connection_id + ) + + +@router.get("/connections/{connection_id}/capabilities", response_model=MetaCapabilitiesView) +def get_meta_connection_capabilities( + workspace_id: UUID, + connection_id: UUID, + actor: Annotated[AuthenticatedActor, Depends(get_current_actor)], + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], +) -> MetaCapabilitiesView: + with tenant_transaction( + session_factory, + user_id=actor.user_id, + workspace_id=workspace_id, + request_id=request_id, + ) as (session, ctx): + _require_ws_perm(ctx, "meta:read") + return container.meta_service.get_connection_capabilities( + session, workspace_id=workspace_id, connection_id=connection_id + ) + + +@router.get("/webhooks", response_class=PlainTextResponse) +def get_meta_webhook_challenge( + workspace_id: UUID, + hub_mode: Annotated[str, Query(alias="hub.mode")], + hub_verify_token: Annotated[str, Query(alias="hub.verify_token")], + hub_challenge: Annotated[str, Query(alias="hub.challenge")], + container: Annotated[AppContainer, Depends(get_container)], +) -> str: + _ = workspace_id + return container.meta_service.verify_webhook_challenge( + hub_mode=hub_mode, + hub_verify_token=hub_verify_token, + hub_challenge=hub_challenge, + ) + + +@router.post("/webhooks", response_model=MetaWebhookReceipt) +async def post_meta_webhook( + workspace_id: UUID, + request: Request, + session_factory: Annotated[sessionmaker[Session], Depends(get_session_factory)], + container: Annotated[AppContainer, Depends(get_container)], + request_id: Annotated[UUID, Depends(get_request_id)], +) -> MetaWebhookReceipt: + raw_body = await request.body() + headers = dict(request.headers) + with rls_transaction(session_factory, user_id=None, workspace_id=workspace_id) as session: + return container.meta_service.ingest_webhook( + session, + workspace_id=workspace_id, + raw_body=raw_body, + headers=headers, + request_id=request_id, + ) diff --git a/apps/web/src/app/(app)/connections/page.tsx b/apps/web/src/app/(app)/connections/page.tsx new file mode 100644 index 0000000..233f8eb --- /dev/null +++ b/apps/web/src/app/(app)/connections/page.tsx @@ -0,0 +1,333 @@ +"use client"; + +import React, { useCallback, useEffect, useState } from "react"; +import Link from "next/link"; +import { Link2, Loader2, RefreshCw, ShieldCheck, Trash2 } from "lucide-react"; +import { useAuth } from "@/lib/auth-context"; +import { ApiClientError, apiClient } from "@/lib/api-client"; +import type { ClientRecord } from "@/lib/types"; +import { + metaApi, + type MetaConnectionRecord, + type MetaConnectionType, + type PermissionMatrixEntry, +} from "@/lib/meta-api"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { Label } from "@/components/ui/input"; +import { Alert, Badge } from "@/components/ui/badge"; + +export default function MetaConnectionsPage() { + const { activeWorkspace } = useAuth(); + const [clients, setClients] = useState([]); + const [matrix, setMatrix] = useState([]); + const [connections, setConnections] = useState([]); + + const [connectionType, setConnectionType] = useState("creator_professional"); + const [selectedClientId, setSelectedClientId] = useState(""); + const [includeAds, setIncludeAds] = useState(false); + + const [loading, setLoading] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [notice, setNotice] = useState(null); + + const loadData = useCallback(async () => { + if (!activeWorkspace) return; + setLoading(true); + setError(null); + try { + const [clientList, permMatrix, connList] = await Promise.all([ + apiClient.listClients(activeWorkspace.workspace_id), + metaApi.getPermissionMatrix(activeWorkspace.workspace_id), + metaApi.listConnections(activeWorkspace.workspace_id), + ]); + setClients(clientList); + setMatrix(permMatrix); + setConnections(connList); + } catch (err) { + setError(err instanceof ApiClientError ? err.message : "Failed to load Meta connections."); + } finally { + setLoading(false); + } + }, [activeWorkspace]); + + useEffect(() => { + void loadData(); + }, [loadData]); + + async function handleConnect(mockScenarioCode?: string) { + if (!activeWorkspace) return; + setBusy(true); + setError(null); + setNotice(null); + try { + const start = await metaApi.startUnifiedLogin(activeWorkspace.workspace_id, { + connection_type: connectionType, + client_id: selectedClientId || null, + include_ads: includeAds, + }); + + if (start.mode === "live" && !mockScenarioCode) { + window.location.assign(start.authorization_url); + return; + } + + const code = + mockScenarioCode || + (connectionType === "agency_business" ? "mock_agency_biz" : "mock_creator_pro"); + const created = await metaApi.completeUnifiedLogin(activeWorkspace.workspace_id, { + code, + state: start.state, + redirect_uri: start.redirect_uri, + }); + setNotice( + `Connected ${created.connection_type} (${created.instagram_account_ids.length} Instagram Professional account(s)).` + ); + await loadData(); + } catch (err) { + setError(err instanceof ApiClientError ? err.message : "Meta connection failed."); + } finally { + setBusy(false); + } + } + + async function handleDisconnect(connectionId: string) { + if (!activeWorkspace) return; + setBusy(true); + setError(null); + try { + await metaApi.disconnect(activeWorkspace.workspace_id, connectionId); + setNotice("Meta connection disconnected and token removed from server secret vault."); + await loadData(); + } catch (err) { + setError(err instanceof ApiClientError ? err.message : "Failed to disconnect."); + } finally { + setBusy(false); + } + } + + if (!activeWorkspace) { + return ( + + + Create a workspace first + + Meta account connections bind strictly to a tenant-isolated workspace or client. + + + + + + + + + ); + } + + return ( +
+
+
+

Meta Account Connections

+

+ Instagram API with Unified Login · Server-side encrypted secret references · Zero raw tokens in browser or Postgres. +

+
+ +
+ + {error && {error}} + {notice && {notice}} + +
+ {/* Left: Onboarding Flow */} + + + + + Connect via Meta Unified Login + + + Personal Instagram accounts are blocked with conversion instructions; Creators do not need an ad account. + + + +
+ + +
+ + {connectionType === "agency_business" && ( +
+ + +
+ )} + + + +
+ + +
+
+
+ + {/* Right: Active Connections & Capabilities */} +
+ + + Connected Accounts ({connections.length}) + + Capabilities are computed server-side from granted scopes and eligible assets. + + + + {connections.length === 0 ? ( +

+ No Meta accounts connected yet. You can still use AI Workers, Video Studio, and Cloud Studio without connecting Meta. +

+ ) : ( + connections.map((conn) => ( +
+
+
+ + {conn.status} + + {conn.connection_type} + {conn.token_configured && ( + + + Vault Secret Ref + + )} +
+ {conn.status !== "disconnected" && ( + + )} +
+

+ IG Accounts: {conn.instagram_account_ids.join(", ") || "none"} · Pages:{" "} + {conn.page_ids.join(", ") || "none"} · Ad Accounts:{" "} + {conn.ad_account_ids.join(", ") || "none"} +

+
+ {Object.entries(conn.capabilities).map(([cap, enabled]) => ( + + {cap}: {enabled ? "on" : "off"} + + ))} +
+
+ )) + )} +
+
+ + + + Permission Matrix (Section 2.3) + + Metuse requests only minimal permissions required for enabled features. + + + + {matrix.map((row) => ( +
+
+

+ {row.permission} ({row.capability}) +

+

{row.description}

+
+ + {row.required_for_creator_organic ? "Organic" : "Optional / Ads"} + +
+ ))} +
+
+
+
+
+ ); +} diff --git a/apps/web/src/components/layout/app-shell.tsx b/apps/web/src/components/layout/app-shell.tsx index b77995f..d5d1577 100644 --- a/apps/web/src/components/layout/app-shell.tsx +++ b/apps/web/src/components/layout/app-shell.tsx @@ -9,6 +9,7 @@ import { Film, FolderKanban, LayoutDashboard, + Link2, LogOut, Menu, PlusCircle, @@ -28,6 +29,7 @@ const NAV_ITEMS = [ { href: "/jobs", label: "AI Workers", icon: FolderKanban }, { href: "/video", label: "Video Studio", icon: Film }, { href: "/studio", label: "Cloud Studio", icon: Clapperboard }, + { href: "/connections", label: "Connections", icon: Link2 }, { href: "/onboarding/workspace", label: "New Workspace", icon: Building2 }, { href: "/onboarding/client", label: "New Client", icon: PlusCircle }, ]; @@ -59,7 +61,7 @@ export function AppShell({ children }: { children: React.ReactNode }) {

Metuse AI

-

Agency OS · Phase 4

+

Agency OS · Phase 5