DEV Community

Cover image for Nexus AI - Secure Multi-Tenant AI Workspace Automation
Julio Díaz
Julio Díaz Subscriber

Posted on

Nexus AI - Secure Multi-Tenant AI Workspace Automation

Auth0 for AI Agents Challenge Submission

This is a submission for the Auth0 for AI Agents Challenge

What I Built

Nexus AI is a secure, multi-tenant AI workspace automation platform that enables teams to leverage AI agents for email management, document creation, and task automation—all while maintaining enterprise-grade security through Auth0.

Key Features:

  • 🤖 Agentic AI powered by Google Gemini 2.5 Flash with tool calling
  • 📧 Gmail Integration - Read, send, and manage emails via AI
  • 📝 Notion Integration - Create, read, update, and search pages/databases
  • 🏢 Multi-tenancy with Auth0 Organizations
  • 🔐 Fine-Grained Authorization using Auth0 FGA
  • 👤 Per-User OAuth - Each user connects their own Gmail/Notion (Token Vault)
  • Human-in-the-Loop confirmations for sensitive actions
  • 🔑 Personal API Keys - Users can bring their own Gemini API keys
  • Auto-onboarding - Personal workspaces created on first login

Demo

🌐 Live Application

Production URL: https://nexus-ai-kappa-dun.vercel.app

📹 Demo Video

📸 Screenshots

Dashboard with AI Chat

Dashboard
AI agent with tool calling for Gmail and Notion

Settings - Integration Management

Settings
Users connect their personal Gmail and Notion accounts

Human-in-the-Loop Confirmation

Confirmation
AI requests user confirmation before sending emails

🧪 Testing Instructions

Auto-Register (Recommended)

  1. Visit the app and sign up with any email (Google/email)
  2. A personal workspace is automatically created
  3. Go to Settings → Connect your Gmail and Notion
  4. Try commands like:
    • "Read my latest 5 emails"
    • "Send an email to test@example.com saying hello"
    • "Create a Notion page called 'Meeting Notes' with content: ..."

How I Used Auth0 for AI Agents

Nexus AI leverages all 5 core Auth0 for AI Agents features:

1️⃣ User Authentication

  • Implemented Auth0 Universal Login with social (Google) and email/password
  • Protected routes with Auth0 session management
  • Role-based UI rendering (Admin, Manager, Member, Guest)
// lib/auth0.ts
export async function getSession() {
  const session = await auth0.getSession()
  if (!session) return null
  return session
}
Enter fullscreen mode Exit fullscreen mode

2️⃣ Call Your APIs on User's Behalf

  • AI agent uses each user's OAuth tokens for Gmail and Notion
  • Tokens are scoped per user and organization
  • All actions are performed on behalf of the authenticated user
// AI tool execution with user context
execute: async ({ to, subject, body }) => {
  // Uses session.user.sub to get user's personal Gmail tokens
  const result = await sendEmail(
    session.user.sub, 
    organizationId, 
    to, 
    subject, 
    body
  )
}
Enter fullscreen mode Exit fullscreen mode

3️⃣ Token Vault (OAuth per User)

  • Each user connects their own Gmail and Notion accounts
  • OAuth tokens stored securely in Supabase (encrypted at rest)
  • Automatic token refresh for expired access tokens
  • Users maintain control over their own credentials
// lib/supabase.ts - Token Vault implementation
export async function saveGmailTokens(
  userId: string,
  organizationId: string,
  accessToken: string,
  refreshToken?: string,
  expiresIn: number = 3600
) {
  await supabase.from("user_connections").upsert({
    user_id: userId,
    organization_id: organizationId,
    gmail_access_token: accessToken,
    gmail_refresh_token: refreshToken,
    gmail_expires_at: new Date(Date.now() + expiresIn * 1000)
  })
}
Enter fullscreen mode Exit fullscreen mode

4️⃣ Fine-Grained Authorization (FGA)

  • Auth0 FGA enforces permissions before every tool execution
  • Role-based access: Admin, Manager, Member, Guest
  • Organization-scoped permissions prevent cross-tenant data access
// app/api/chat/route.ts
const canSendEmail = await checkPermission(
  session.user.sub,
  organizationId,
  'send_email',
  'member'
)

if (!canSendEmail) {
  return { 
    error: "You don't have permission to send emails" 
  }
}
Enter fullscreen mode Exit fullscreen mode

FGA Model:

type user
type organization

type role
  relations
    define member: [user]
    define manager: [user] or member
    define admin: [user] or manager

relations
  define member: [user]
  define admin: [role#admin]
  define manager: [role#manager]
  define can_send_email: admin or manager or member
  define can_read_email: admin or manager or member
  define can_create_notion_page: admin or manager or member
Enter fullscreen mode Exit fullscreen mode

5️⃣ Asynchronous Authorization (Human-in-the-Loop)

  • Sensitive actions require explicit user confirmation
  • AI prompts user before executing destructive operations
  • Confirmation flow integrated into conversational UI
// Human-in-the-loop confirmation for sendEmail
if (!confirmed) {
  return {
    success: false,
    requiresConfirmation: true,
    message: `⚠️ This action requires confirmation. 
              You are about to send an email to ${to} 
              with subject "${subject}". 
              Please confirm to proceed.`
  }
}

// User confirms by replying "yes", "confirm", etc.
// AI retries with confirmed: true
Enter fullscreen mode Exit fullscreen mode

Architecture & Tech Stack

Frontend

  • Framework: Next.js 15.2.4 with App Router
  • UI: React 18.3.1 + TailwindCSS + shadcn/ui
  • AI SDK: Vercel AI SDK 5.0 with streaming responses
  • State: React Context for organization/user management

Backend

  • Runtime: Node.js on Vercel Edge Functions
  • Authentication: Auth0 (Organizations + FGA)
  • AI Model: Google Gemini 2.5 Flash with tool calling
  • Database: Supabase (PostgreSQL) for token storage
  • APIs: Gmail API, Notion API

Security Features

  • ✅ OAuth 2.0 for Gmail and Notion
  • ✅ Automatic token refresh
  • ✅ Row-level security (disabled for service role, enabled for user access)
  • ✅ Environment variable protection
  • ✅ HTTPS everywhere
  • ✅ Personal API keys stored in browser localStorage (never sent to server)

Lessons Learned and Takeaways

🎯 Key Insights

1. Token Management is Hard - OAuth per user revealed token lifecycle complexities: 60min expiry, secure refresh storage, graceful rotation. Solution: Transparent automatic refresh.

2. FGA Requires Planning - Auth0 FGA needs careful schema design balancing granularity vs. complexity. Takeaway: Start simple with RBAC, add granular permissions incrementally.

3. AI Tool Calling is Revolutionary - Function calling transforms chatbots to agents with natural language → API calls, multi-step workflows, and conversational error handling. Gemini 2.5 Flash excels at parameter extraction.

4. Human-in-the-Loop Builds Trust - Users hesitate with autonomous AI actions. Confirmation flows increase adoption and allow easy cancellation. Future: Manager approval workflows.

5. Multi-Tenancy Edge Cases - Auth0 Organizations solved isolation but revealed scenarios: org-less users (auto-create), mid-session switching, invitation vs. auto-registration. Solution: Support both paths.

🚧 Challenges Faced

Challenge 1: Gemini Tool Schema Format

  • Issue: Gemini 2.5 uses inputSchema instead of parameters
  • Solution: Read official docs, updated to new API format

Challenge 2: Email Body Empty

  • Issue: Gemini sometimes didn't extract body parameter
  • Solution: Improved Gmail MIME format with proper headers (\r\n, Content-Type)

Challenge 3: Notion API Changes

  • Issue: Notion deprecated database in favor of data_source (2025-09-03 version)
  • Solution: Updated all queries, added fallback logic

Challenge 4: Supabase RLS Blocking Inserts

  • Issue: Row Level Security prevented server-side token storage
  • Solution: Disabled RLS for service role (acceptable for M2M operations)

Challenge 5: Personal API Keys Not Working

  • Issue: useChat body object evaluated once at mount
  • Solution: Changed to function body that reads fresh from localStorage on each request

💡 What I'd Do Differently

If I Had More Time:

  1. RAG with Auth0 FGA - Implement document-level access control in RAG pipeline
  2. Async Approval Workflows - Use CIBA for push notification approvals
  3. Activity Logging - Real-time audit logs in Supabase (currently mock)
  4. Multi-step Agent Workflows - Chain multiple tools (e.g., "Summarize emails and create Notion page with summary")
  5. MCP Integration - Connect to Model Context Protocol for standardized tool interfaces

Architecture Improvements:

  • Move token encryption to application level (currently relying on Supabase encryption at rest)
  • Implement rate limiting per user
  • Add Redis for caching frequently-accessed data

🎓 Key Takeaways for Other Developers

1. Start with Auth0 Organizations
Multi-tenancy from day 1 saves refactoring later. Organizations provide clean isolation.

2. FGA is Worth the Learning Curve
Fine-grained permissions seem complex initially but pay dividends in enterprise scenarios.

3. Token Vault Pattern is Essential
Never share API credentials across users. Each user owns their connections.

4. AI Agents Need Guardrails
Human-in-the-loop isn't optional for production AI agents. Users need control.

5. Edge Functions are Perfect for AI
Streaming responses from LLMs work beautifully with Vercel Edge Functions.

🔮 Future Vision

Nexus AI Roadmap:

  • 📊 Analytics Dashboard with real activity logs
  • 🔗 More Integrations (Slack, Google Calendar, Linear, GitHub)
  • 🤝 Collaboration Features (shared AI threads, team templates)
  • 📱 Mobile App with push notifications for human-in-the-loop
  • 🧠 Memory System (AI remembers user preferences and context)
  • 🌍 Multi-language Support

Acknowledgments

  • Auth0 for the amazing AI Agents platform and documentation
  • Google for Gemini 2.5 Flash and AI Studio
  • Vercel for the AI SDK and seamless deployment
  • Supabase for the secure, scalable database

License

MIT License


Built with ❤️ for the Auth0 for AI Agents Challenge

Top comments (0)