-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathinteractions.js
More file actions
392 lines (337 loc) · 12.2 KB
/
Copy pathinteractions.js
File metadata and controls
392 lines (337 loc) · 12.2 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/**
* Interaction handlers for login, consent, and registration flows
* Handles the user-facing parts of the authentication flow
*/
import { authenticate, findById, createAccount } from './accounts.js';
import { loginPage, consentPage, errorPage, registerPage } from './views.js';
import * as storage from '../storage/filesystem.js';
import { createPodStructure } from '../handlers/container.js';
/**
* Handle GET /idp/interaction/:uid
* Shows login or consent page based on interaction state
*/
export async function handleInteractionGet(request, reply, provider) {
const { uid } = request.params;
try {
const interaction = await provider.Interaction.find(uid);
if (!interaction) {
return reply.code(404).type('text/html').send(errorPage('Interaction not found', 'This login session has expired. Please try again.'));
}
const { prompt, params, session } = interaction;
// If we need login
if (prompt.name === 'login') {
return reply.type('text/html').send(loginPage(uid, params.client_id, interaction.lastError));
}
// If we need consent
if (prompt.name === 'consent') {
const client = await provider.Client.find(params.client_id);
const account = session?.accountId ? await findById(session.accountId) : null;
return reply.type('text/html').send(consentPage(uid, client, params, account));
}
// Unknown prompt
return reply.code(400).type('text/html').send(errorPage('Unknown prompt', `Unexpected prompt: ${prompt.name}`));
} catch (err) {
request.log.error(err, 'Interaction error');
return reply.code(500).type('text/html').send(errorPage('Server Error', err.message));
}
}
/**
* Handle POST /idp/interaction/:uid/login
* Processes login form submission
*/
export async function handleLogin(request, reply, provider) {
const { uid } = request.params;
// Parse body - handle multiple formats (Buffer, string, object)
let parsedBody = request.body || {};
const contentType = request.headers['content-type'] || '';
if (Buffer.isBuffer(parsedBody)) {
const bodyStr = parsedBody.toString();
if (contentType.includes('application/json')) {
try {
parsedBody = JSON.parse(bodyStr);
} catch (e) {
parsedBody = {};
}
} else {
// Assume form-urlencoded
const params = new URLSearchParams(bodyStr);
parsedBody = Object.fromEntries(params.entries());
}
} else if (typeof parsedBody === 'string') {
// Body might be a string for form-urlencoded
if (contentType.includes('application/json')) {
try {
parsedBody = JSON.parse(parsedBody);
} catch (e) {
parsedBody = {};
}
} else {
const params = new URLSearchParams(parsedBody);
parsedBody = Object.fromEntries(params.entries());
}
}
// If it's already an object, use as-is
// Support username, email, or legacy 'email' field for backwards compatibility
const identifier = parsedBody.username || parsedBody.email;
const password = parsedBody.password;
request.log.info({ identifier, hasPassword: !!password, bodyType: typeof request.body, keys: Object.keys(parsedBody) }, 'Login attempt');
try {
const interaction = await provider.Interaction.find(uid);
if (!interaction) {
return reply.code(404).type('text/html').send(errorPage('Session expired', 'Please try logging in again.'));
}
// Validate input
if (!identifier || !password) {
interaction.lastError = 'Username and password are required';
await interaction.save(interaction.exp - Math.floor(Date.now() / 1000));
return reply.redirect(`/idp/interaction/${uid}`);
}
// Authenticate
const account = await authenticate(identifier, password);
if (!account) {
interaction.lastError = 'Invalid username or password';
await interaction.save(interaction.exp - Math.floor(Date.now() / 1000));
return reply.redirect(`/idp/interaction/${uid}`);
}
// Login successful - complete the interaction
const result = {
login: {
accountId: account.id,
remember: true,
},
};
request.log.info({ accountId: account.id, uid }, 'Login successful');
// Detect if this is a browser (wants HTML/redirect) or programmatic client (wants JSON)
const acceptHeader = request.headers.accept || '';
const wantsBrowserRedirect = acceptHeader.includes('text/html') && !acceptHeader.includes('application/json');
// Save the login result to the interaction
interaction.result = result;
await interaction.save(interaction.exp - Math.floor(Date.now() / 1000));
// For browsers (mashlib, etc): do a proper HTTP redirect
if (wantsBrowserRedirect) {
reply.hijack();
return provider.interactionFinished(request.raw, reply.raw, result, { mergeWithLastSubmission: false });
}
// For CTH and programmatic clients: return JSON with location
// CTH expects a 200 response with "location" in body (CSS v3+ style)
try {
reply.hijack();
// Create a mock response that captures the redirect and returns JSON
let capturedLocation = null;
let headersSent = false;
const mockRes = {
statusCode: 200,
headersSent: false,
setHeader: (name, value) => {
if (name.toLowerCase() === 'location') {
capturedLocation = value;
}
return mockRes;
},
getHeader: (name) => {
if (name.toLowerCase() === 'location') return capturedLocation;
return undefined;
},
removeHeader: () => mockRes,
writeHead: (status, headers) => {
if (headers) {
if (typeof headers === 'object' && !Array.isArray(headers)) {
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase() === 'location') {
capturedLocation = value;
}
}
}
}
return mockRes;
},
write: () => mockRes,
end: (body) => {
if (!headersSent) {
headersSent = true;
const location = capturedLocation || `/idp/auth/${uid}`;
reply.raw.writeHead(200, {
'Content-Type': 'application/json',
'Location': location,
});
reply.raw.end(JSON.stringify({ location }));
}
},
finished: false,
on: () => mockRes,
once: () => mockRes,
emit: () => mockRes,
};
await provider.interactionFinished(request.raw, mockRes, result, { mergeWithLastSubmission: false });
return;
} catch (err) {
request.log.warn({ err: err.message, errName: err.name, uid }, 'interactionFinished failed, using fallback');
// Fallback: return the redirect URL for manual following
const redirectTo = `/idp/auth/${uid}`;
return reply
.code(200)
.header('Location', redirectTo)
.type('application/json')
.send({ location: redirectTo });
}
} catch (err) {
request.log.error(err, 'Login error');
return reply.code(500).type('text/html').send(errorPage('Login failed', err.message));
}
}
/**
* Handle POST /idp/interaction/:uid/confirm
* Processes consent confirmation
*/
export async function handleConsent(request, reply, provider) {
const { uid } = request.params;
try {
const interaction = await provider.Interaction.find(uid);
if (!interaction) {
return reply.code(404).type('text/html').send(errorPage('Session expired', 'Please try again.'));
}
const { prompt, params, session } = interaction;
if (prompt.name !== 'consent') {
return reply.code(400).type('text/html').send(errorPage('Invalid state', 'Not in consent stage.'));
}
// Grant consent
const grant = new provider.Grant({
accountId: session.accountId,
clientId: params.client_id,
});
// Grant requested scopes
if (params.scope) {
grant.addOIDCScope(params.scope);
}
// Grant resource-specific scopes if present
if (params.resource) {
const resources = Array.isArray(params.resource) ? params.resource : [params.resource];
for (const resource of resources) {
grant.addResourceScope(resource, params.scope);
}
}
const grantId = await grant.save();
const result = {
consent: {
grantId,
},
};
// Mark reply as sent since interactionFinished will handle the response
reply.hijack();
// Use interactionFinished which handles the redirect directly
return provider.interactionFinished(
request.raw,
reply.raw,
result,
{ mergeWithLastSubmission: true }
);
} catch (err) {
request.log.error(err, 'Consent error');
return reply.code(500).type('text/html').send(errorPage('Consent failed', err.message));
}
}
/**
* Handle POST /idp/interaction/:uid/abort
* User cancelled the flow
*/
export async function handleAbort(request, reply, provider) {
const { uid } = request.params;
try {
const result = {
error: 'access_denied',
error_description: 'User cancelled the authorization request',
};
// oidc-provider is configured with /idp routes, so redirectTo will have correct path
const redirectTo = await provider.interactionResult(
request.raw,
reply.raw,
result,
{ mergeWithLastSubmission: false }
);
return reply.redirect(redirectTo);
} catch (err) {
request.log.error(err, 'Abort error');
return reply.code(500).type('text/html').send(errorPage('Error', err.message));
}
}
/**
* Handle GET /idp/register
* Shows registration page
*/
export async function handleRegisterGet(request, reply) {
const uid = request.query.uid || null;
return reply.type('text/html').send(registerPage(uid));
}
/**
* Handle POST /idp/register
* Creates account and pod
*/
export async function handleRegisterPost(request, reply, issuer) {
const uid = request.query.uid || null;
// Parse body
let parsedBody = request.body || {};
const contentType = request.headers['content-type'] || '';
if (Buffer.isBuffer(parsedBody)) {
const bodyStr = parsedBody.toString();
if (contentType.includes('application/json')) {
try {
parsedBody = JSON.parse(bodyStr);
} catch (e) {
parsedBody = {};
}
} else {
const params = new URLSearchParams(bodyStr);
parsedBody = Object.fromEntries(params.entries());
}
} else if (typeof parsedBody === 'string') {
const params = new URLSearchParams(parsedBody);
parsedBody = Object.fromEntries(params.entries());
}
const { username, password, confirmPassword } = parsedBody;
// Validate input
if (!username || !password) {
return reply.type('text/html').send(registerPage(uid, 'Username and password are required'));
}
// Validate username format
const usernameRegex = /^[a-z0-9]+$/;
if (!usernameRegex.test(username)) {
return reply.type('text/html').send(registerPage(uid, 'Username must contain only lowercase letters and numbers'));
}
if (username.length < 3) {
return reply.type('text/html').send(registerPage(uid, 'Username must be at least 3 characters'));
}
if (password !== confirmPassword) {
return reply.type('text/html').send(registerPage(uid, 'Passwords do not match'));
}
try {
// Build URLs
const baseUrl = issuer.endsWith('/') ? issuer.slice(0, -1) : issuer;
const podUri = `${baseUrl}/${username}/`;
const webId = `${podUri}#me`;
// Check if pod already exists
const podPath = `${username}/`;
const podExists = await storage.exists(podPath);
if (podExists) {
return reply.type('text/html').send(registerPage(uid, 'Username is already taken'));
}
// Create pod structure
await createPodStructure(username, webId, baseUrl);
// Create account
await createAccount({
username,
password,
webId,
podName: username,
});
request.log.info({ username, webId }, 'Account and pod created');
// Redirect to login
if (uid) {
return reply.redirect(`/idp/interaction/${uid}`);
} else {
return reply.type('text/html').send(registerPage(null, null, `Account created! You can now sign in as "${username}".`));
}
} catch (err) {
request.log.error(err, 'Registration error');
return reply.type('text/html').send(registerPage(uid, err.message));
}
}