{"slug":"connectors/AUTH_CONNECTOR_INTEGRATION","title":"Auth ↔ Connector Integration Guide","section":"connectors","sectionLabel":"Connectors","status":"unclassified","type":"document","path":"connectors/AUTH_CONNECTOR_INTEGRATION.mdx","bytes":10861,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n\n> **Tier C — Historical.** This document is a point-in-time snapshot preserved for reference. For current architecture, see [CANONICAL_PLATFORM_ARCHITECTURE.md](../architecture/CANONICAL_PLATFORM_ARCHITECTURE.md).\n\n## IntegrateWise - Continuity Bridge: Complete Flow\n\nThe authentication system is seamlessly integrated with the One Connector to create a unified ecosystem experience.\n\n### Complete Flow\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│ USER JOURNEY: From Identity to Ecosystem Connection             │\n└─────────────────────────────────────────────────────────────────┘\n\n1. AUTHENTICATION (Identity)\n   └─→ User logs in via Clerk or Supabase\n   └─→ Auth provider confirms identity\n   └─→ Session/JWT issued\n\n2. AUTHORIZATION (Permissions)\n   └─→ Check user role (admin/user)\n   └─→ Load permission scope\n   └─→ Determine connector access level\n   └─→ Create authorization context\n\n3. APPROVAL (Confirmation)\n   └─→ Modal shows user information\n   └─→ Display granted permissions\n   └─→ List connected services\n   └─→ User approves connection\n   └─→ Generate connector approval token\n\n4. CONNECTION (Integration)\n   └─→ Initialize One Connector\n   └─→ Connect to Spine API\n   └─→ Initialize MCP pool bridges\n   └─→ Send heartbeat to Spine\n   └─→ Services become available\n\n5. OPERATION (Usage)\n   └─→ Application code uses getConnector()\n   └─→ Services route through One Connector\n   └─→ Health monitoring via Spine\n   └─→ All 4 provider layers functional\n```\n\n## Implementation\n\n### 1. Connector Approval Service\n\n**File:** `lib/auth/connector-approval.ts` (304 lines)\n\nCore functions:\n- `getAuthorizationContext()` - Get user's authorization level\n- `requestConnectorApproval()` - Request ecosystem connection approval\n- `connectToEcosystem()` - Establish One Connector connection\n- `initializeConnectorWithAuth()` - Full flow orchestration\n\n```typescript\n// Full initialization\nconst result = await initializeConnectorWithAuth()\nif (result.success) {\n  // User is authenticated, authorized, and connected\n  // All ecosystem services available\n}\n```\n\n### 2. Connector Approval Modal\n\n**File:** `components/auth/connector-approval-modal.tsx` (200 lines)\n\nShows user:\n- Their identity information\n- Granted permissions\n- Connected services\n- Security notice\n\nUser can:\n- Approve connection\n- Cancel/dismiss\n\n### 3. Connector Approval Hook\n\n**File:** `lib/auth/use-connector-approval.ts` (203 lines)\n\nManages entire flow:\n```typescript\nconst {\n  showModal,      // Modal visibility\n  loading,        // Operation in progress\n  context,        // User authorization context\n  approval,       // Connector approval response\n  error,          // Error message\n  isConnected,    // Connection status\n  approve,        // Function to approve\n  dismiss,        // Function to dismiss modal\n} = useConnectorApproval()\n```\n\n### 4. Auth Connector Provider\n\n**File:** `components/auth/auth-connector-provider.tsx` (60 lines)\n\nWrapper component that:\n- Checks connector status on mount\n- Shows approval modal when needed\n- Handles full flow automatically\n- Wraps entire application\n\n## Usage\n\n### Setup in Root Layout\n\n```typescript\n// app/layout.tsx\n\n  children,\n}: {\n  children: React.ReactNode\n}) {\n  return (\n    <html>\n      <body>\n        <ClerkProvider>\n          <AuthConnectorProvider>\n            {children}\n          </AuthConnectorProvider>\n        </ClerkProvider>\n      </body>\n    </html>\n  )\n}\n```\n\n### Automatic Flow\n\n1. User visits app\n2. Clerk provider handles authentication\n3. AuthConnectorProvider checks status\n4. If user not connected to ecosystem:\n   - Shows approval modal\n   - User approves\n   - One Connector initializes\n   - Modal closes\n   - User has full ecosystem access\n\n### Manual Control\n\n```typescript\n// In any component\n\nfunction MyComponent() {\n  const { isConnected, approve, disconnect } = useConnectorApproval()\n\n  if (!isConnected) {\n    return <p>Not connected to ecosystem</p>\n  }\n\n  return (\n    <div>\n      <p>Connected to ecosystem!</p>\n      <button onClick={disconnect}>Disconnect</button>\n    </div>\n  )\n}\n```\n\n## Authorization Context\n\n```typescript\ninterface ConnectorAuthorizationContext {\n  userId: string\n  tenantId: string\n  email: string\n  name: string\n  isAdmin: boolean\n  permissions: string[]\n  hasConnectorAccess: boolean\n}\n```\n\n### Default Permissions\n\n**Regular Users:**\n- `connector:read` - Read connector status\n- `connector:execute` - Execute through connector\n- `auth:access` - Access auth service\n- `database:read` - Read database\n\n**Administrators:**\n- All regular user permissions +\n- `connector:admin` - Full connector control\n- `auth:admin` - Full auth control\n- `database:write` - Write to database\n- `ai:execute` - Execute AI services\n- `agent:execute` - Execute agents\n\n## Approval Flow\n\n```typescript\ninterface ConnectorApprovalResponse {\n  approved: boolean\n  connectorId: string\n  connectedAt: number\n  expiresAt: number            // 24 hours\n  permissions: string[]\n  error?: string\n}\n```\n\n- Connector ID: Unique identifier for this connection\n- Connected At: Timestamp when connection established\n- Expires At: When approval expires (24 hours by default)\n- Permissions: Scoped permissions for this session\n\n## Storage\n\nConnection context stored in:\n- **SessionStorage**: `connector_context`\n- **Cleared on**: Logout, disconnect, window close\n\n```typescript\n// Structure\n{\n  userId: string\n  tenantId: string\n  connectorId: string\n  connectedAt: number\n  expiresAt: number\n  permissions: string[]\n}\n```\n\n## Lifecycle\n\n### On Login\n1. Auth provider authenticates user\n2. AuthConnectorProvider detects authenticated user\n3. Checks if connector already connected\n4. If not connected, shows approval modal\n\n### On Approval\n1. User reviews information\n2. Clicks \"Approve & Connect\"\n3. System:\n   - Generates connector ID\n   - Initializes One Connector\n   - Connects to Spine API\n   - Stores connection context\n   - Closes modal\n\n### On Use\n1. Application calls `getConnector()`\n2. Returns same connector instance (singleton)\n3. All services route through connector\n4. Spine monitors health\n5. Heartbeat sent every 30 seconds\n\n### On Logout\n1. Auth provider signs out user\n2. AuthConnectorProvider detects logout\n3. Clears connector context\n4. Disconnects from ecosystem\n5. User must re-authenticate and approve on next login\n\n## Security\n\n### Token Management\n- Connector approval includes `expiresAt` (24 hours)\n- Session storage cleared on tab close\n- Service role keys never exposed to client\n- Only necessary permissions scoped\n\n### Spine Integration\n- All connections authenticated with Spine API key\n- Heartbeat validates connection health\n- Signals can revoke connector at any time\n- Tenant isolation enforced\n\n### MCP Bridges\n- Each service has its own credentials\n- Never shared across connectors\n- Per-service rate limiting\n- Audit trail for all operations\n\n## Troubleshooting\n\n### Modal Not Showing\n1. Check if user is authenticated\n2. Verify `AuthConnectorProvider` is in layout\n3. Check browser console for errors\n\n### Approval Fails\n1. Check Spine API connectivity\n2. Verify user has connector access permission\n3. Check MCP pool status\n\n### Services Not Working After Connection\n1. Verify connector is connected: `useConnector().getStatus()`\n2. Check individual service health\n3. Verify environment variables are set\n\n## Environment Variables\n\n```bash\n# Required for Spine integration\nSPINE_URL=https://spine.integratewise.ai\nSPINE_API_KEY=...\n\n# Required for MCP pool\nMCP_URL=https://mcp.integratewise.ai\nMCP_TOKEN=...\n\n# Tenant info\nINTEGRATEWISE_TENANT_ID=integratewise\nINTEGRATEWISE_CLIENT_ID=app-frontend\n\n# Auth provider (Clerk or Supabase)\nNEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=...\nCLERK_SECRET_KEY=...\n# OR\nNEXT_PUBLIC_SUPABASE_URL=...\nNEXT_PUBLIC_SUPABASE_ANON_KEY=...\nSUPABASE_SERVICE_ROLE_KEY=...\n```\n\n## Testing\n\n### Test Both Auth Providers\n\n```typescript\n// Test with Clerk\nNEXT_PUBLIC_AUTH_PROVIDER=clerk\nNEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...\n\n// Test with Supabase\nNEXT_PUBLIC_AUTH_PROVIDER=supabase\nNEXT_PUBLIC_SUPABASE_URL=https://...\n```\n\n### Test Approval Flow\n\n1. **Start fresh:**\n   - Open incognito window\n   - Clear session storage\n   - Verify no connector context\n\n2. **Login:**\n   - Click login\n   - Authenticate with provider\n   - Should redirect back\n\n3. **Approval Modal:**\n   - Should automatically appear\n   - Verify user info is correct\n   - Verify permissions list\n\n4. **Approve:**\n   - Click \"Approve & Connect\"\n   - Should show connecting state\n   - Modal should close\n   - All services should be available\n\n5. **Refresh:**\n   - Reload page\n   - Modal should NOT appear (already connected)\n   - Services should still work\n\n6. **Logout:**\n   - Click logout\n   - Connection context cleared\n   - Session storage empty\n   - Modal should appear on next login\n\n## API Reference\n\n### getAuthorizationContext()\nReturns user's authorization level and permissions\n\n```typescript\nconst context = await getAuthorizationContext()\n```\n\n### requestConnectorApproval(context)\nRequest approval for connector connection\n\n```typescript\nconst approval = await requestConnectorApproval(context)\n```\n\n### connectToEcosystem(context, approval)\nEstablish One Connector connection\n\n```typescript\nconst connected = await connectToEcosystem(context, approval)\n```\n\n### initializeConnectorWithAuth()\nExecute full flow (recommended)\n\n```typescript\nconst result = await initializeConnectorWithAuth()\nif (result.success) {\n  // Connected\n}\n```\n\n### useConnectorApproval()\nReact hook for managing approval flow\n\n```typescript\nconst {\n  showModal,\n  context,\n  isConnected,\n  approve,\n  dismiss,\n  disconnect,\n} = useConnectorApproval()\n```\n\n## Summary\n\n**IntegrateWise - Continuity Bridge** creates a seamless path from authentication to full ecosystem access:\n\n1. **Identity** - Know who the user is\n2. **Authorization** - Know what they can do\n3. **Approval** - User confirms connection\n4. **Connection** - One Connector initialized\n5. **Operation** - Full ecosystem access\n\nAll handled automatically through the `AuthConnectorProvider` wrapper with user-friendly approval modal.\n\n**Result: Single identity. Complete ecosystem. Infinite integration.**\n"}