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.
- π¬ 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
- Cloudflare account with Workers & Workers AI enabled
- OpenAI API key
- Auth0 account with a configured:
- Web Application
- API (resource server)
- Log in to your Auth0 dashboard
- Navigate to "Applications > APIs" and click "Create API"
- Provide a name and identifier (audience)
- Note the API Identifier (audience) for later use
Note: you can also use the default app.
- In your Auth0 dashboard, go to "Applications" and click "Create Application"
- Select "Web Application" as the application type
- 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
- Allowed Callback URLs:
- Note your Domain, Client ID, and Client Secret for later use
- Create a new Cloudflare Workers project using the Auth0 starter template:
npx create-cloudflare@latest --template auth0-lab/cloudflare-agents-starter
- 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
- Run locally:
npm start
- Deploy:
npm run deploy
βββ 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
This starter kit uses Auth0 for authentication and authorization:
- Users log in using Auth0 credentials
- Auth0 provides JWT tokens for API authentication
- The Agent use the
WithAuth
mixin from theagents-oauth2-jwt-bearer
package to validate the JWT token - API requests and WebSocket connections are secured with the JWT token
- Each chat is associated with its owner (user ID) to ensure data isolation
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.
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.
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
};
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.
@auth0/auth0-hono
@auth0/auth0-cloudflare-agents-api
@auth0/ai
agents
- Cloudflare Agents Documentation
- Cloudflare Workers Documentation
- Auth0 Documentation
We appreciate feedback and contribution to this repo! Before you get started, please see the following:
To provide feedback or report a bug, please raise an issue on our issue tracker.
Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
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.