Skip to content

auth0-lab/cloudflare-agents-starter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

22 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– Chat Agent Starter Kit with Auth0 Authentication

agents-header

A starter template for building AI-powered chat agents using Cloudflare's Agent platform, powered by agents and secured with Auth0 authentication. This project provides a foundation for creating interactive chat experiences with AI, complete with a modern UI, tool integration capabilities, and user authentication.

Features

  • πŸ’¬ Interactive chat interface with AI
  • πŸ” Auth0 authentication and authorization
  • πŸ“œ Securely get access tokens for Federated Connections using Auth0 Token Vault
  • πŸ™†β€β™‚οΈ Backchannel Authentication for human-in-the-loop interactions using Auth0 CIBA
  • πŸ‘€ User-specific chat history and management
  • πŸ› οΈ Built-in tool system with human-in-the-loop confirmation
  • πŸ“… Advanced task scheduling (one-time, delayed, and recurring via cron)
  • πŸŒ“ Dark/Light theme support
  • ⚑️ Real-time streaming responses
  • πŸ”„ State management and chat history
  • 🎨 Modern, responsive UI

Prerequisites

  • Cloudflare account with Workers & Workers AI enabled
  • OpenAI API key
  • Auth0 account with a configured:
    • Web Application
    • API (resource server)

Auth0 Configuration

Step 1: Create an Auth0 API

  1. Log in to your Auth0 dashboard
  2. Navigate to "Applications > APIs" and click "Create API"
  3. Provide a name and identifier (audience)
  4. Note the API Identifier (audience) for later use

Step 2: Create an Auth0 Application

Note: you can also use the default app.

  1. In your Auth0 dashboard, go to "Applications" and click "Create Application"
  2. Select "Web Application" as the application type
  3. Configure the following settings:
    • Allowed Callback URLs: http://localhost:3000/auth/callback (development) and your production URL
    • Allowed Logout URLs: http://localhost:3000 (development) and your production URL
  4. Note your Domain, Client ID, and Client Secret for later use

Quick Start

  1. Create a new Cloudflare Workers project using the Auth0 starter template:
npx create-cloudflare@latest --template auth0-lab/cloudflare-agents-starter
  1. Set up your environment:

Create a .dev.vars file based on the example:

# OpenAI API key
OPENAI_API_KEY=sk-your-openai-api-key

# Auth0 Configuration
# trailing slash in ISSUER is important:
AUTH0_DOMAIN="your-tenant.us.auth0.com/"
AUTH0_CLIENT_ID="your-auth0-client-id"
AUTH0_CLIENT_SECRET="your-auth0-client-secret"
AUTH0_SESSION_ENCRYPTION_KEY="generate-a-random-key-at-least-32-characters-long"
AUTH0_AUDIENCE="https://your-auth0-api-identifier"

# Application base URL
BASE_URL=http://localhost:3000
  1. Run locally:
npm start
  1. Deploy:
npm run deploy

Project Structure

β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ server.ts                # Main worker with auth configuration
β”‚   β”œβ”€β”€ chats.ts                 # Chat management functions using Cloudflare KV
β”‚   β”œβ”€β”€ agent/                   # Agent-related code
β”‚   β”‚   β”œβ”€β”€ index.ts             # Chat agent implementation with Auth0 integration
β”‚   β”‚   β”œβ”€β”€ tools.ts             # Tool definitions and implementations
β”‚   β”‚   β”œβ”€β”€ utils.ts             # Agent utility functions
β”‚   β”‚   β”œβ”€β”€ auth0-ai.ts          # Auth0 AI initialization and configuration
β”‚   β”‚   └── shared.ts            # Shared constants and types
β”‚   β”œβ”€β”€ client/                  # Frontend client application
β”‚   β”‚   β”œβ”€β”€ app.tsx              # Chat UI implementation
β”‚   β”‚   β”œβ”€β”€ home.tsx             # Home page component
β”‚   β”‚   β”œβ”€β”€ index.tsx            # Entry point for React app
β”‚   β”‚   β”œβ”€β”€ Layout.tsx           # Layout component
β”‚   β”‚   └── styles.css           # UI styling
β”‚   β”œβ”€β”€ components/              # UI components
β”‚   β”‚   β”œβ”€β”€ auth0/               # Auth0-specific components
β”‚   β”‚   β”œβ”€β”€ auth0-ai/            # Auth0-specific components
β”‚   β”‚   β”œβ”€β”€ chatList/            # Chat list components
β”‚   β”‚   └── ...                  # Other UI components
β”‚   └── hooks/                   # React hooks
β”‚       β”œβ”€β”€ useUser.tsx          # User authentication hook
β”‚       └── ...                  # Other custom hooks

Authentication Flow

This starter kit uses Auth0 for authentication and authorization:

  1. Users log in using Auth0 credentials
  2. Auth0 provides JWT tokens for API authentication
  3. The Agent use the WithAuth mixin from the agents-oauth2-jwt-bearer package to validate the JWT token
  4. API requests and WebSocket connections are secured with the JWT token
  5. Each chat is associated with its owner (user ID) to ensure data isolation

Authentication Packages

This project utilizes two key npm packages for authentication:

  • @auth0/auth0-hono - Handles browser-based authentication flows, session management, and token handling for the web interface.
  • @auth0/auth0-cloudflare-agents-api - Secures WebSocket connections and API endpoints for the agent, providing token validation and authorization for all agent interactions.
  • @auth0/ai - Provides AI capabilities for the agent. Token Vault for Federated Connections, Backchannel Authorization, and more.

These packages work together to provide a comprehensive authentication solution that secures both the web interface and the underlying agent communication.

Auth0 AI Powerful Integrations

The example contains two powerful integrations with Auth0 AI:

  • Token Vault: Securely store and retrieve access tokens for Federated Connections, allowing the agent to access third-party APIs on behalf of the user.
  • Backchannel Authentication: Implement human-in-the-loop interactions using Client-Initiated Backchannel Authentication (CIBA) flow, allowing the agent to request user confirmation for actions that require human input.

Prompts:

  • Am I available next monday 9am? - This messsage will call the check-user-calendar which is wrapped by the @auth0/ai Authorizer. If the application can't access the user's calendar it will fire a popup window with the Authorization process. Once completed, the agent will be able to access the user's calendar and answer the question.
  • Buy 100 shares of MSFT - This message will call the buy-stock tool which is wrapped by the @auth0/ai Backchannel Authorizer. The agent fires an authorization request to the user, who will receive a push notification on their device. The user can then approve or deny the request. If approved, the agent will execute the tool and "buy the stock".

Another interesting scenario is triggering the buy stock tool on a schedule. For example, you can ask the agent to "buy 100 shares in 5 minutes". The agent will schedule the tool execution using the Cloudflare agent Task Scheduler, which supports one-time, delayed, and recurring tasks via cron expressions. Once it executes the task, it will again fire the authorization request to the user, who can approve or deny the request.

Customization Guide

Adding New Tools

Add new tools in src/agent/tools.ts using the tool builder:

// Example of a tool that requires confirmation
const searchDatabase = tool({
  description: "Search the database for user records",
  parameters: z.object({
    query: z.string(),
    limit: z.number().optional(),
  }),
  // No execute function = requires confirmation
});

// Example of an auto-executing tool
const getCurrentTime = tool({
  description: "Get current server time",
  parameters: z.object({}),
  execute: async () => new Date().toISOString(),
});

To handle tool confirmations, add execution functions to the executions object:

export const executions = {
  searchDatabase: async ({
    query,
    limit,
  }: {
    query: string;
    limit?: number;
  }) => {
    // Implementation for when the tool is confirmed
    const results = await db.search(query, limit);
    return results;
  },
  // Add more execution handlers for other tools that require confirmation
};

Extending Auth0 Integration

The integration uses Hono's OpenID Connect middleware for authentication and session management. You can customize the authentication behavior in src/server.ts.

The agent uses the WithAuth mixin from agents-oauth2-jwt-bearer package to secure API endpoints and WebSocket connections. Each chat is associated with its owner through the setOwner method to ensure users can only access their own chats.

Learn More

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the Apache 2.0 license. See the LICENSE file for more info.

About

A starter kit for building secure ai agents on Cloudflare with Auth0

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published