handle undefined credential more gracefully
[squeep-authentication-module] / lib / session-manager.js
1 'use strict';
2
3 /**
4 * Here we process activities which support login sessions.
5 */
6
7 const { Communication: IndieAuthCommunication } = require('@squeep/indieauth-helper');
8 const { MysteryBox } = require('@squeep/mystery-box');
9 const common = require('./common');
10 const Enum = require('./enum');
11 const Template = require('./template');
12
13 const _fileScope = common.fileScope(__filename);
14
15 class SessionManager {
16 /**
17 * @param {Console} logger
18 * @param {Authenticator} authenticator
19 * @param {Object} options
20 * @param {Object} options.authenticator
21 * @param {String[]} options.authenticator.authnEnabled
22 * @param {Number=} options.authenticator.inactiveSessionLifespanSeconds
23 * @param {Boolean} options.authenticator.secureAuthOnly
24 * @param {Object} options.dingus
25 * @param {Object} options.dingus.proxyPrefix
26 * @param {Object} options.dingus.selfBaseUrl
27 */
28 constructor(logger, authenticator, options) {
29 this.logger = logger;
30 this.authenticator = authenticator;
31 this.options = options;
32 this.indieAuthCommunication = new IndieAuthCommunication(logger, options);
33 this.mysteryBox = new MysteryBox(logger, options);
34
35 this.cookieLifespan = options.authenticator.inactiveSessionLifespanSeconds || 60 * 60 * 24 * 32;
36 }
37
38
39 /**
40 * Set or update our session cookie.
41 * @param {http.ServerResponse} res
42 * @param {Object} session
43 * @param {Number} maxAge
44 * @param {String} path
45 */
46 async _sessionCookieSet(res, session, maxAge, path = '/') {
47 const _scope = _fileScope('_sessionCookieSet');
48
49 const cookieName = Enum.SessionCookie;
50 const secureSession = session && await this.mysteryBox.pack(session) || '';
51 const cookieParts = [
52 `${cookieName}=${secureSession}`,
53 'HttpOnly',
54 'SameSite=Lax',
55 ];
56 if (this.options.authenticator.secureAuthOnly) {
57 cookieParts.push('Secure');
58 }
59 if (typeof(maxAge) === 'number') {
60 cookieParts.push(`Max-Age=${maxAge}`);
61 }
62 if (path) {
63 cookieParts.push(`Path=${this.options.dingus.proxyPrefix}${path}`);
64 }
65 const cookie = cookieParts.join('; ');
66 this.logger.debug(_scope, 'session cookie', { cookie, session })
67 res.setHeader(Enum.Header.SetCookie, cookie);
68 }
69
70
71 /**
72 * GET request for establishing admin session.
73 * @param {http.ServerResponse} res
74 * @param {Object} ctx
75 */
76 async getAdminLogin(res, ctx) {
77 const _scope = _fileScope('getAdminLogin');
78 this.logger.debug(_scope, 'called', { ctx });
79
80 res.end(Template.LoginHTML(ctx, this.options));
81 this.logger.info(_scope, 'finished', { ctx })
82 }
83
84
85 /**
86 * POST request for taking form data to establish admin session.
87 * @param {http.ServerResponse} res
88 * @param {Object} ctx
89 */
90 async postAdminLogin(res, ctx) {
91 const _scope = _fileScope('postAdminLogin');
92 this.logger.debug(_scope, 'called', { ctx });
93
94 ctx.errors = [];
95
96 const redirect = ctx.queryParams['r'] || './';
97
98 // Only attempt user login if no IndieAuth profile is set
99 if (!this.options.authenticator.authnEnabled.includes('indieAuth') || !ctx.parsedBody['me']) {
100
101 const identifier = ctx.parsedBody['identifier'];
102 const credential = ctx.parsedBody['credential']; // N.B. Logger must specifically mask this field from ctx.
103
104 const isValidLocalIdentifier = await this.authenticator.isValidIdentifierCredential(identifier, credential, ctx);
105 if (!isValidLocalIdentifier) {
106 ctx.errors.push('Invalid username or password');
107 }
108
109 if (ctx.errors.length) {
110 res.end(Template.LoginHTML(ctx, this.options));
111 return;
112 }
113
114 // Valid auth, persist the authenticated session
115 ctx.session = {
116 authenticatedIdentifier: ctx.authenticationId,
117 };
118 await this._sessionCookieSet(res, ctx.session, this.cookieLifespan);
119 res.statusCode = 302;
120 res.setHeader(Enum.Header.Location, redirect);
121 res.end();
122 this.logger.info(_scope, 'finished local', { ctx });
123 return;
124 }
125
126 // Otherwise, carry on with IndieAuth handshake.
127 let me, session, authorizationEndpoint;
128 try {
129 me = new URL(ctx.parsedBody['me']);
130 } catch (e) {
131 this.logger.debug(_scope, 'failed to parse supplied profile url', { ctx });
132 ctx.errors.push(`Unable to understand '${ctx.parsedBody['me']}' as a profile URL.`);
133 }
134
135 if (this.options.authenticator.authnEnabled.includes('indieAuth')
136 && me) {
137 const profile = await this.indieAuthCommunication.fetchProfile(me);
138 if (!profile || !profile.metadata) {
139 this.logger.debug(_scope, 'failed to find any profile information at url', { ctx });
140 ctx.errors.push(`No profile information was found at '${me}'.`);
141 } else {
142 // fetch and parse me for 'authorization_endpoint' relation links
143 try {
144 authorizationEndpoint = new URL(profile.metadata.authorizationEndpoint);
145 } catch (e) {
146 ctx.errors.push(`Unable to understand the authorization endpoint ('${profile.metadata.authorizationEndpoint}') indicated by that profile ('${me}') as a URL.`);
147 }
148
149 if (profile.metadata.issuer) {
150 // Validate issuer
151 try {
152 const issuer = new URL(profile.metadata.issuer);
153 if (issuer.hash
154 || issuer.search
155 || issuer.protocol.toLowerCase() !== 'https:') { // stupid URL trailing colon thing
156 this.logger.debug(_scope, 'supplied issuer url invalid', { ctx });
157 ctx.errors.push('Authorization server provided an invalid issuer field.');
158 }
159 } catch (e) {
160 this.logger.debug(_scope, 'failed to parse supplied issuer url', { ctx });
161 ctx.errors.push('Authorization server provided an unparsable issuer field.');
162 }
163 } else {
164 this.logger.debug(_scope, 'no issuer in metadata, assuming legacy mode', { ctx });
165 // Strict 20220212 compliance would error here.
166 // ctx.errors.push('Authorization server did not provide issuer field, as required by current specification.');
167 }
168 }
169
170 if (authorizationEndpoint) {
171 const pkce = await IndieAuthCommunication.generatePKCE();
172
173 session = {
174 authorizationEndpoint: authorizationEndpoint.href,
175 state: ctx.requestId,
176 codeVerifier: pkce.codeVerifier,
177 me,
178 redirect,
179 issuer: profile.metadata.issuer,
180 };
181
182 // Update auth endpoint parameters
183 Object.entries({
184 'response_type': 'code',
185 'client_id': this.options.dingus.selfBaseUrl,
186 'redirect_uri': `${this.options.dingus.selfBaseUrl}admin/_ia`,
187 'state': session.state,
188 'code_challenge': pkce.codeChallenge,
189 'code_challenge_method': pkce.codeChallengeMethod,
190 'me': me,
191 }).forEach(([name, value]) => authorizationEndpoint.searchParams.set(name, value));
192 }
193 }
194
195 if (ctx.errors.length) {
196 res.end(Template.LoginHTML(ctx, this.options));
197 return;
198 }
199
200 await this._sessionCookieSet(res, session, this.cookieLifespan);
201 res.setHeader(Enum.Header.Location, authorizationEndpoint.href);
202 res.statusCode = 302; // Found
203 res.end();
204
205 this.logger.info(_scope, 'finished indieauth', { ctx })
206 }
207
208
209 /**
210 * GET request to remove current credentials.
211 * @param {http.ServerResponse} res
212 * @param {Object} ctx
213 */
214 async getAdminLogout(res, ctx) {
215 const _scope = _fileScope('getAdminLogout');
216 this.logger.debug(_scope, 'called', { ctx });
217
218 this._sessionCookieSet(res, '', 0);
219
220 const redirect = ctx.queryParams['r'] || './';
221
222 res.statusCode = 302;
223 res.setHeader(Enum.Header.Location, redirect);
224 res.end();
225
226 this.logger.info(_scope, 'finished', { ctx });
227 }
228
229
230 /**
231 * GET request for returning IndieAuth redirect.
232 * This currently only redeems a scope-less profile.
233 * @param {http.ServerResponse} res
234 * @param {Object} ctx
235 */
236 async getAdminIA(res, ctx) {
237 const _scope = _fileScope('getAdminIA');
238 this.logger.debug(_scope, 'called', { ctx });
239
240 ctx.errors = [];
241 ctx.session = {};
242
243 // Unpack cookie to restore session data
244
245 const [ cookieName, cookieValue ] = common.splitFirst((ctx.cookie || ''), '=', '');
246 if (cookieName !== Enum.SessionCookie) {
247 this.logger.debug(_scope, 'no cookie', { ctx });
248 ctx.errors.push('missing required cookie');
249 } else {
250 try {
251 ctx.session = await this.mysteryBox.unpack(cookieValue);
252 this.logger.debug(_scope, 'restored session from cookie', { ctx });
253 } catch (e) {
254 this.logger.debug(_scope, 'could not unpack cookie');
255 ctx.errors.push('invalid cookie');
256 }
257 }
258
259 // Validate unpacked session values
260 // ...
261
262 // Add any auth errors
263 if (ctx.queryParams['error']) {
264 ctx.errors.push(ctx.queryParams['error']);
265 if (ctx.queryParams['error_description']) {
266 ctx.errors.push(ctx.queryParams['error_description']);
267 }
268 }
269
270 // check stuff
271 if (ctx.queryParams['state'] !== ctx.session.state) {
272 this.logger.debug(_scope, 'state mismatch', { ctx });
273 ctx.errors.push('invalid state');
274 }
275
276 const code = ctx.queryParams['code'];
277 if (!code) {
278 this.logger.debug(_scope, 'missing code', { ctx });
279 ctx.errors.push('invalid code');
280 }
281
282 // check issuer
283 if (ctx.session.issuer) {
284 if (ctx.queryParams['iss'] !== ctx.session.issuer) {
285 this.logger.debug(_scope, 'issuer mismatch', { ctx });
286 ctx.errors.push('invalid issuer');
287 }
288 } else {
289 this.logger.debug(_scope, 'no issuer in metadata, assuming legacy mode', { ctx });
290 // Strict 20220212 compliance would error here. (Also earlier.)
291 // ctx.errors.push('invalid issuer');
292 }
293
294 let redeemProfileUrl;
295 try {
296 redeemProfileUrl = new URL(ctx.session.authorizationEndpoint);
297 } catch (e) {
298 this.logger.debug(_scope, 'failed to parse restored session authorization endpoint as url', { ctx });
299 ctx.errors.push('invalid cookie');
300 }
301 let profile;
302 if (redeemProfileUrl) {
303 profile = await this.indieAuthCommunication.redeemProfileCode(redeemProfileUrl, code, ctx.session.codeVerifier, this.options.dingus.selfBaseUrl, `${this.options.dingus.selfBaseUrl}admin/_ia`);
304 if (!profile) {
305 this.logger.debug(_scope, 'no profile from code redemption', { ctx });
306 ctx.errors.push('did not get a profile response from authorization endpoint code redemption');
307 } else if (!profile.me) {
308 this.logger.debug(_scope, 'no profile me identifier from code redemption', { ctx });
309 ctx.errors.push('did not get \'me\' value from authorization endpoint code redemption');
310 } else if (profile.me !== ctx.session.me) {
311 this.logger.debug(_scope, 'mis-matched canonical me from redeemed profile', { ctx, profile });
312 const newProfileUrl = new URL(profile.me);
313 // Rediscover auth endpoint for the new returned profile.
314 const newProfile = await this.indieAuthCommunication.fetchProfile(newProfileUrl);
315 if (newProfile.metadata.authorizationEndpoint !== ctx.session.authorizationEndpoint) {
316 this.logger.debug(_scope, 'mis-matched auth endpoints between provided me and canonical me', { ctx, profile, newProfile });
317 ctx.errors.push('canonical profile url provided by authorization endpoint is not handled by that endpoint, cannot continue');
318 } else {
319 // The endpoints match, all is okay, update our records.
320 ctx.session.me = profile.me;
321 }
322 }
323 }
324
325 if (ctx.errors.length) {
326 await this._sessionCookieSet(res, '', 0);
327 res.end(Template.IAHTML(ctx, this.options));
328 return;
329 }
330
331 const redirect = ctx.session.redirect || './';
332
333 // Set cookie as auth valid, redirect to original location.
334 ctx.session = {
335 authenticatedProfile: ctx.session.me,
336 };
337
338 await this._sessionCookieSet(res, ctx.session, this.cookieLifespan);
339 res.statusCode = 302;
340 res.setHeader(Enum.Header.Location, redirect);
341 res.end();
342
343 this.logger.info(_scope, 'finished', { ctx })
344 }
345
346
347 }
348
349 module.exports = SessionManager;