-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
296 lines (259 loc) · 9.88 KB
/
Copy pathindex.js
File metadata and controls
296 lines (259 loc) · 9.88 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/**
* Identity Provider Fastify Plugin
* Mounts oidc-provider and interaction routes
*/
import middie from '@fastify/middie';
import { createProvider } from './provider.js';
import { initializeKeys, getPublicJwks } from './keys.js';
import {
handleInteractionGet,
handleLogin,
handleConsent,
handleAbort,
handleRegisterGet,
handleRegisterPost,
} from './interactions.js';
import {
handleCredentials,
handleCredentialsInfo,
} from './credentials.js';
import { addTrustedIssuer } from '../auth/solid-oidc.js';
/**
* IdP Fastify Plugin
* @param {FastifyInstance} fastify
* @param {object} options
* @param {string} options.issuer - The issuer URL
*/
export async function idpPlugin(fastify, options) {
const { issuer, inviteOnly = false } = options;
if (!issuer) {
throw new Error('IdP requires issuer URL');
}
// Register our own issuer as trusted (bypasses SSRF check for self-validation)
addTrustedIssuer(issuer);
// Initialize signing keys
await initializeKeys();
// Create the OIDC provider
const provider = await createProvider(issuer);
// Add error listener to catch internal oidc-provider errors
provider.on('server_error', (ctx, err) => {
fastify.log.error({
err: err.message,
stack: err.stack,
path: ctx?.path,
cause: err.cause?.message,
error_description: err.error_description,
}, 'oidc-provider server error');
});
provider.on('grant.error', (ctx, err) => {
fastify.log.error({
err: err.message,
stack: err.stack?.substring(0, 800),
cause: err.cause?.message,
error_description: err.error_description,
}, 'oidc-provider grant error');
});
// Store provider reference on fastify for handlers
fastify.decorate('oidcProvider', provider);
// Register middleware support for oidc-provider (Koa app)
await fastify.register(middie);
// Helper to forward requests to oidc-provider
const forwardToProvider = async (request, reply) => {
return new Promise((resolve, reject) => {
// Get raw Node.js req/res
const req = request.raw;
const res = reply.raw;
// Set CORS headers on raw response before oidc-provider handles it
// This is needed because oidc-provider writes directly to the raw response
const origin = request.headers.origin;
if (origin) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, DPoP, If-Match, If-None-Match, Link, Slug, Origin');
res.setHeader('Access-Control-Expose-Headers', 'Accept-Patch, Accept-Post, Allow, Content-Type, ETag, Link, Location, Updates-Via, WAC-Allow');
res.setHeader('Access-Control-Max-Age', '86400');
}
// Handle OPTIONS preflight requests directly
if (request.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return resolve();
}
// oidc-provider is now configured with /idp routes, no stripping needed
// Ensure parsed body is accessible to oidc-provider
// Fastify parses body into request.body, oidc-provider looks for req.body
if (request.body !== undefined) {
if (Buffer.isBuffer(request.body)) {
// Parse buffer to object if it's JSON
const contentType = request.headers['content-type'] || '';
if (contentType.includes('application/json')) {
try {
req.body = JSON.parse(request.body.toString());
} catch (e) {
req.body = request.body;
}
} else if (contentType.includes('application/x-www-form-urlencoded')) {
// Parse form data
const params = new URLSearchParams(request.body.toString());
req.body = Object.fromEntries(params.entries());
} else {
req.body = request.body;
}
} else {
req.body = request.body;
}
}
// Call oidc-provider's callback
provider.callback()(req, res);
// Wait for response to finish
res.on('finish', resolve);
res.on('error', reject);
});
};
// Legacy handler for /auth/:uid without prefix - redirect to /idp/auth/:uid
// In case any old redirects or cached URLs exist
fastify.get('/auth/:uid', async (request, reply) => {
return reply.redirect(`/idp/auth/${request.params.uid}`);
});
// Catch-all route for oidc-provider paths
// Must be registered BEFORE specific routes to be matched as fallback
const oidcPaths = ['/idp/auth', '/idp/token', '/idp/reg', '/idp/me', '/idp/session', '/idp/session/*'];
for (const path of oidcPaths) {
fastify.route({
method: ['GET', 'POST', 'DELETE', 'OPTIONS'],
url: path,
handler: forwardToProvider,
});
}
// Also handle /idp/auth/:uid for continued authorization after login
fastify.get('/idp/auth/:uid', forwardToProvider);
// Token sub-paths
fastify.route({
method: ['GET', 'POST'],
url: '/idp/token/introspection',
handler: forwardToProvider,
});
fastify.route({
method: ['GET', 'POST'],
url: '/idp/token/revocation',
handler: forwardToProvider,
});
// /.well-known/openid-configuration
fastify.get('/.well-known/openid-configuration', async (request, reply) => {
// Ensure issuer has trailing slash for CTH compatibility
const normalizedIssuer = issuer.endsWith('/') ? issuer : issuer + '/';
// Base URL without trailing slash for building endpoint URLs
const baseUrl = issuer.endsWith('/') ? issuer.slice(0, -1) : issuer;
// Build discovery document
const config = {
issuer: normalizedIssuer,
authorization_endpoint: `${baseUrl}/idp/auth`,
token_endpoint: `${baseUrl}/idp/token`,
userinfo_endpoint: `${baseUrl}/idp/me`,
jwks_uri: `${baseUrl}/.well-known/jwks.json`,
registration_endpoint: `${baseUrl}/idp/reg`,
introspection_endpoint: `${baseUrl}/idp/token/introspection`,
revocation_endpoint: `${baseUrl}/idp/token/revocation`,
end_session_endpoint: `${baseUrl}/idp/session/end`,
scopes_supported: ['openid', 'webid', 'profile', 'email', 'offline_access'],
response_types_supported: ['code'],
response_modes_supported: ['query', 'fragment', 'form_post'],
grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
subject_types_supported: ['public'],
id_token_signing_alg_values_supported: ['RS256', 'ES256'],
token_endpoint_auth_methods_supported: ['none', 'client_secret_basic', 'client_secret_post'],
claims_supported: ['sub', 'webid', 'name', 'email', 'email_verified'],
code_challenge_methods_supported: ['S256'],
dpop_signing_alg_values_supported: ['ES256', 'RS256'],
// RFC 9207 - OAuth 2.0 Authorization Server Issuer Identification
authorization_response_iss_parameter_supported: true,
// Solid-OIDC specific
solid_oidc_supported: 'https://solidproject.org/TR/solid-oidc',
};
reply.header('Cache-Control', 'public, max-age=3600');
return config;
});
// /.well-known/jwks.json
fastify.get('/.well-known/jwks.json', async (request, reply) => {
const jwks = await getPublicJwks();
reply.header('Cache-Control', 'public, max-age=3600');
return jwks;
});
// Programmatic credentials endpoint for CTH compatibility
// Allows obtaining tokens via email/password without browser interaction
// GET credentials info
fastify.get('/idp/credentials', async (request, reply) => {
return handleCredentialsInfo(request, reply, issuer);
});
// POST credentials - obtain tokens (with rate limiting for brute force protection)
fastify.post('/idp/credentials', {
config: {
rateLimit: {
max: 10,
timeWindow: '1 minute',
keyGenerator: (request) => request.ip
}
}
}, async (request, reply) => {
return handleCredentials(request, reply, issuer);
});
// Interaction routes (our custom login/consent UI)
// These bypass oidc-provider and use our handlers
// GET interaction - show login or consent page
fastify.get('/idp/interaction/:uid', async (request, reply) => {
return handleInteractionGet(request, reply, provider);
});
// POST interaction - direct form submission (CTH compatibility)
// This handles form submissions directly to /idp/interaction/:uid
// Rate limited to prevent brute force attacks
fastify.post('/idp/interaction/:uid', {
config: {
rateLimit: {
max: 10,
timeWindow: '1 minute',
keyGenerator: (request) => request.ip
}
}
}, async (request, reply) => {
return handleLogin(request, reply, provider);
});
// POST login (explicit path) - rate limited
fastify.post('/idp/interaction/:uid/login', {
config: {
rateLimit: {
max: 10,
timeWindow: '1 minute',
keyGenerator: (request) => request.ip
}
}
}, async (request, reply) => {
return handleLogin(request, reply, provider);
});
// POST consent
fastify.post('/idp/interaction/:uid/confirm', async (request, reply) => {
return handleConsent(request, reply, provider);
});
// POST abort
fastify.post('/idp/interaction/:uid/abort', async (request, reply) => {
return handleAbort(request, reply, provider);
});
// Registration routes
fastify.get('/idp/register', async (request, reply) => {
return handleRegisterGet(request, reply, inviteOnly);
});
// Registration - rate limited to prevent spam accounts
fastify.post('/idp/register', {
config: {
rateLimit: {
max: 5,
timeWindow: '1 hour',
keyGenerator: (request) => request.ip
}
}
}, async (request, reply) => {
return handleRegisterPost(request, reply, issuer, inviteOnly);
});
fastify.log.info(`IdP initialized with issuer: ${issuer}`);
}
export default idpPlugin;