Skip to content

Commit 7c60015

Browse files
committed
Add auth extension examples
Covers basic auth, tool permissions, persona tiers, custom providers, and no-auth usage.
1 parent 3f57cc1 commit 7c60015

5 files changed

Lines changed: 618 additions & 0 deletions

File tree

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
/**
2+
* Example 1: Basic Authentication
3+
*
4+
* This example shows how to use the auth extension with AgentOS for basic
5+
* JWT authentication and subscription management.
6+
*/
7+
8+
import { AgentOS } from '@framers/agentos';
9+
import { createAuthExtension } from '@framers/agentos-extensions/auth';
10+
11+
async function main() {
12+
console.log('=== Example 1: Basic Authentication ===\n');
13+
14+
// 1. Create auth extension with configuration
15+
const { authService, subscriptionService } = createAuthExtension({
16+
auth: {
17+
jwtSecret: process.env.JWT_SECRET || 'demo-secret-change-in-production',
18+
jwtExpiresIn: '7d',
19+
bcryptSaltRounds: 12,
20+
},
21+
subscription: {
22+
defaultTier: 'free',
23+
tiers: [
24+
{ name: 'free', level: 0, features: [], isActive: true },
25+
{ name: 'pro', level: 1, features: ['FEATURE_ADVANCED_SEARCH'], isActive: true },
26+
],
27+
},
28+
});
29+
30+
// 2. Initialize AgentOS with auth services
31+
const agentos = new AgentOS();
32+
await agentos.initialize({
33+
authService,
34+
subscriptionService,
35+
// ... other AgentOS config
36+
});
37+
38+
console.log('✓ AgentOS initialized with auth extension\n');
39+
40+
// 3. User Registration Flow
41+
console.log('--- User Registration ---');
42+
const userId = 'user-123';
43+
const email = 'user@example.com';
44+
const password = 'secure-password-123';
45+
46+
// Hash password for storage
47+
const passwordHash = await authService.hashPassword!(password);
48+
console.log(`✓ Password hashed for user: ${email}`);
49+
50+
// 4. User Login Flow
51+
console.log('\n--- User Login ---');
52+
53+
// Verify password
54+
const isPasswordValid = await authService.verifyPassword!(password, passwordHash);
55+
if (!isPasswordValid) {
56+
throw new Error('Invalid password');
57+
}
58+
console.log('✓ Password verified');
59+
60+
// Generate JWT token
61+
const token = authService.generateToken!(userId, {
62+
email,
63+
roles: ['user'],
64+
tier: 'pro',
65+
});
66+
console.log('✓ JWT token generated:', token.substring(0, 20) + '...');
67+
68+
// 5. Token Validation (on subsequent requests)
69+
console.log('\n--- Token Validation ---');
70+
const authenticatedUser = await authService.validateToken(token);
71+
if (!authenticatedUser) {
72+
throw new Error('Token validation failed');
73+
}
74+
75+
console.log('✓ User authenticated:');
76+
console.log(' - ID:', authenticatedUser.id);
77+
console.log(' - Email:', authenticatedUser.email);
78+
console.log(' - Tier:', authenticatedUser.tier);
79+
80+
// 6. Check Subscription Tier
81+
console.log('\n--- Subscription Check ---');
82+
subscriptionService.setUserTier!(userId, 'pro');
83+
const tier = await subscriptionService.getUserSubscription(userId);
84+
85+
console.log('✓ User subscription tier:');
86+
console.log(' - Name:', tier?.name);
87+
console.log(' - Level:', tier?.level);
88+
console.log(' - Features:', tier?.features?.join(', ') || 'none');
89+
90+
// 7. Feature Access Check
91+
const hasAdvancedSearch = await subscriptionService.validateAccess(
92+
userId,
93+
'FEATURE_ADVANCED_SEARCH'
94+
);
95+
console.log(' - Advanced Search:', hasAdvancedSearch ? '✓ Allowed' : '✗ Denied');
96+
97+
// 8. Token Refresh
98+
console.log('\n--- Token Refresh ---');
99+
const refreshedToken = await authService.refreshToken!(token);
100+
if (refreshedToken) {
101+
console.log('✓ Token refreshed:', refreshedToken.substring(0, 20) + '...');
102+
} else {
103+
console.log('ℹ Token not yet in refresh window');
104+
}
105+
106+
// 9. Token Revocation (logout)
107+
console.log('\n--- Logout ---');
108+
await authService.revokeToken!(token);
109+
const afterRevocation = await authService.validateToken(token);
110+
console.log('✓ Token revoked:', afterRevocation === null ? 'success' : 'failed');
111+
112+
console.log('\n✅ Basic auth example complete!');
113+
}
114+
115+
main().catch((error) => {
116+
console.error('Error:', error);
117+
process.exit(1);
118+
});
119+
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
/**
2+
* Example 2: Tool Permission Integration
3+
*
4+
* This example shows how to integrate the auth extension with AgentOS tool
5+
* permissions to control which tools users can access based on their subscription tier.
6+
*/
7+
8+
import { AgentOS } from '@framers/agentos';
9+
import { createAuthExtension, ToolPermissionProvider } from '@framers/agentos-extensions/auth';
10+
11+
async function main() {
12+
console.log('=== Example 2: Tool Permission Integration ===\n');
13+
14+
// 1. Create auth extension with tiered features
15+
const { authService, subscriptionService } = createAuthExtension({
16+
auth: { jwtSecret: 'demo-secret' },
17+
subscription: {
18+
defaultTier: 'free',
19+
tiers: [
20+
{
21+
name: 'free',
22+
level: 0,
23+
features: [],
24+
isActive: true,
25+
},
26+
{
27+
name: 'basic',
28+
level: 1,
29+
features: ['FEATURE_WEB_SEARCH'],
30+
isActive: true,
31+
},
32+
{
33+
name: 'pro',
34+
level: 2,
35+
features: ['FEATURE_WEB_SEARCH', 'FEATURE_CODE_EXECUTION'],
36+
isActive: true,
37+
},
38+
{
39+
name: 'enterprise',
40+
level: 3,
41+
features: [
42+
'FEATURE_WEB_SEARCH',
43+
'FEATURE_CODE_EXECUTION',
44+
'FEATURE_DATABASE_ACCESS',
45+
],
46+
isActive: true,
47+
},
48+
],
49+
},
50+
});
51+
52+
// 2. Create tool permission provider
53+
const toolPermissions = new ToolPermissionProvider(subscriptionService);
54+
55+
// 3. Initialize AgentOS
56+
const agentos = new AgentOS();
57+
await agentos.initialize({
58+
authService,
59+
subscriptionService,
60+
});
61+
62+
console.log('✓ AgentOS initialized with auth extension\n');
63+
64+
// 4. Define available tools with their requirements
65+
const availableTools = [
66+
{
67+
id: 'basic-calculator',
68+
name: 'calculator',
69+
requiredFeatures: [], // Free for all
70+
},
71+
{
72+
id: 'web-search',
73+
name: 'webSearch',
74+
requiredFeatures: ['FEATURE_WEB_SEARCH'],
75+
},
76+
{
77+
id: 'code-executor',
78+
name: 'executeCode',
79+
requiredFeatures: ['FEATURE_CODE_EXECUTION'],
80+
},
81+
{
82+
id: 'database-query',
83+
name: 'queryDatabase',
84+
requiredFeatures: ['FEATURE_DATABASE_ACCESS'],
85+
},
86+
];
87+
88+
// 5. Test access for different user tiers
89+
const users = [
90+
{ id: 'user-free', tier: 'free' },
91+
{ id: 'user-basic', tier: 'basic' },
92+
{ id: 'user-pro', tier: 'pro' },
93+
{ id: 'user-enterprise', tier: 'enterprise' },
94+
];
95+
96+
for (const user of users) {
97+
console.log(`\n--- ${user.tier.toUpperCase()} User (${user.id}) ---`);
98+
subscriptionService.setUserTier!(user.id, user.tier);
99+
100+
// Check access to each tool
101+
for (const tool of availableTools) {
102+
const result = await toolPermissions.checkToolAccess({
103+
userId: user.id,
104+
toolId: tool.id,
105+
toolName: tool.name,
106+
requiredFeatures: tool.requiredFeatures,
107+
});
108+
109+
const status = result.allowed ? '✓ Allowed' : '✗ Denied';
110+
console.log(` ${tool.name}: ${status}`);
111+
112+
if (!result.allowed && result.missingFeatures) {
113+
console.log(` Missing: ${result.missingFeatures.join(', ')}`);
114+
}
115+
}
116+
117+
// Get list of accessible tools
118+
const accessibleTools = await toolPermissions.getAccessibleTools(
119+
user.id,
120+
availableTools
121+
);
122+
console.log(` Accessible tools: ${accessibleTools.join(', ')}`);
123+
}
124+
125+
// 6. Simulate tool execution with permission check
126+
console.log('\n--- Simulating Tool Execution ---');
127+
const userId = 'user-basic';
128+
const toolToExecute = 'webSearch';
129+
const tool = availableTools.find((t) => t.name === toolToExecute);
130+
131+
if (tool) {
132+
const result = await toolPermissions.checkToolAccess({
133+
userId,
134+
toolId: tool.id,
135+
toolName: tool.name,
136+
requiredFeatures: tool.requiredFeatures,
137+
});
138+
139+
if (result.allowed) {
140+
console.log(`✓ Executing ${toolToExecute}...`);
141+
// Execute tool here
142+
console.log(` Result: [search results]`);
143+
} else {
144+
console.log(`✗ Access denied: ${result.reason}`);
145+
console.log(' Upgrade to:', result.missingFeatures?.join(', '));
146+
}
147+
}
148+
149+
console.log('\n✅ Tool permissions example complete!');
150+
}
151+
152+
main().catch((error) => {
153+
console.error('Error:', error);
154+
process.exit(1);
155+
});
156+

0 commit comments

Comments
 (0)