-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe101-path-based-basic-oidc.js
More file actions
171 lines (153 loc) · 4.96 KB
/
Copy pathe101-path-based-basic-oidc.js
File metadata and controls
171 lines (153 loc) · 4.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/**
* Example 101: Path-based Basic + OIDC
*
* Demonstrates how to run the API Plugin with:
* - `/v1/**` protected by Basic Auth (email:apiToken)
* - `/app/**` protected by OIDC (Authorization Code flow)
* - Public routes for docs/metrics/health
* - Rate limit rules + logging filters + Prometheus metrics
*
* This is a generic blueprint for migrating Express stacks that had
* Basic tokens + dashboard login into the ApiPlugin/Raffel runtime.
*
* Usage:
* pnpm exec node docs/examples/e101-path-based-basic-oidc.js
*
* (OIDC config uses placeholders. Plug real credentials to test end-to-end.)
*/
import { Database } from '../../src/database.class.js';
import { ApiPlugin } from '../../src/plugins/api/index.js';
import { idGenerator } from '../../src/concerns/id.js';
function generateApiToken() {
return `token_${idGenerator({ size: 12 })}_${Date.now()}`;
}
async function createDatabase() {
const db = new Database({
connectionString: 'memory://path-based-basic-oidc',
security: { passphrase: process.env.SECRET_PASSPHRASE || 'dev-secret-passphrase' },
verbose: false
});
await db.connect();
await db.createResource({
name: 'users',
attributes: {
id: 'string|required',
email: 'email|required|unique',
name: 'string|required',
role: 'string|default:user',
apToken: 'secret|required',
metadata: 'json|optional'
},
timestamps: true
});
await db.createResource({
name: 'links',
attributes: {
id: 'string|required',
slug: 'string|required|unique',
destination: 'string|required',
ownerEmail: 'email|required'
},
timestamps: true
});
await db.resources.users.insert({
id: 'admin@example.com',
email: 'admin@example.com',
name: 'Admin',
role: 'admin',
apToken: generateApiToken()
});
await db.resources.links.insert({
id: 'link-001',
slug: 'welcome',
destination: 'https://example.com/welcome',
ownerEmail: 'admin@example.com'
});
return db;
}
async function main() {
const db = await createDatabase();
const api = new ApiPlugin({
port: process.env.PORT || 3100,
versionPrefix: 'v1',
basePath: '',
verbose: true,
auth: {
resource: 'users',
drivers: [
{
driver: 'basic',
config: {
realm: 'API Tokens',
usernameField: 'email',
passwordField: 'apToken'
}
},
{
driver: 'oidc',
config: {
issuer: process.env.OIDC_ISSUER || 'https://example-issuer',
clientId: process.env.OIDC_CLIENT_ID || 'client-id',
clientSecret: process.env.OIDC_CLIENT_SECRET || 'client-secret',
redirectUri: process.env.OIDC_REDIRECT_URI || 'http://localhost:3100/auth/callback',
cookieSecret: process.env.COOKIE_SECRET || 'change-me-cookie-secret-32chars',
detectApiTokenField: true,
generateApiToken: ({ user }) => `api_${user.id}_${idGenerator({ size: 10 })}`
}
}
],
pathRules: [
{ path: '/v1/**', methods: ['basic'], required: true },
{ path: '/app/**', methods: ['oidc'], required: true },
{ path: '/docs', methods: [], required: false },
{ path: '/openapi.json', methods: [], required: false },
{ path: '/metrics', methods: [], required: false },
{ path: '/health', methods: [], required: false },
{ path: '/health/**', methods: [], required: false },
{ path: '/**', methods: [], required: false }
]
},
logging: {
enabled: true,
format: ':method :url => :status (:elapsed ms)',
excludePaths: ['/health/**', '/metrics'],
filter: ({ duration }) => duration > 1
},
rateLimit: {
enabled: true,
windowMs: 60000,
maxRequests: 500,
rules: [
{ path: '/v1/**', maxRequests: 200, key: 'apiKey', keyHeader: 'x-api-key' },
{ path: '/app/**', maxRequests: 60, key: 'user' },
{ path: '/health/**', maxRequests: 2000, key: 'ip' }
]
},
metrics: { enabled: true, format: 'prometheus' },
resources: {
users: false,
links: { methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] }
},
routes: {
'GET /': async (c) => c.json({ success: true, message: 'API Plugin path-based auth demo' }),
'GET /app': async (c) => c.html(`
<html>
<body>
<h1>Protected dashboard</h1>
<p>User: ${c.get('user')?.email || 'anonymous'}</p>
<p>Try <code>curl -u email:apiToken http://localhost:3100/v1/links</code></p>
</body>
</html>
`)
}
});
await db.usePlugin(api);
console.log('🚀 API Plugin running at http://localhost:3100');
console.log(' Public: GET /, /docs, /openapi.json, /metrics, /health');
console.log(' Basic Auth: /v1/links');
console.log(' OIDC Session: /app/*');
}
main().catch((err) => {
console.error('Example failed:', err);
process.exit(1);
});