4 * Here we wrangle activities which support login sessions, serving and
5 * processing the HTML forms a user interacts with.
8 const { Communication: IndieAuthCommunication
} = require('@squeep/indieauth-helper');
9 const { MysteryBox
} = require('@squeep/mystery-box');
10 const { TOTP
} = require('@squeep/totp');
11 const { randomUUID
} = require('crypto');
12 const common
= require('./common');
13 const Enum
= require('./enum');
14 const Template
= require('./template');
16 const _fileScope
= common
.fileScope(__filename
);
18 class SessionManager
{
20 * @param {Console} logger
21 * @param {Authenticator} authenticator
22 * @param {Object} options
23 * @param {Object} options.authenticator
24 * @param {String[]} options.authenticator.authnEnabled
25 * @param {Number=} options.authenticator.inactiveSessionLifespanSeconds
26 * @param {Boolean} options.authenticator.secureAuthOnly
27 * @param {Object=} options.dingus
28 * @param {String=} options.dingus.proxyPrefix
29 * @param {String} options.dingus.selfBaseUrl
30 * @param {Object} options.manager
31 * @param {String} options.manager.pageTitle
33 constructor(logger
, authenticator
, options
) {
35 this.authenticator
= authenticator
;
36 this.db
= authenticator
.db
; // TODO: take db arg in next major version bump
37 this.options
= options
;
38 this.proxyPrefix
= options
.dingus
?.proxyPrefix
?? '';
39 this.indieAuthCommunication
= new IndieAuthCommunication(logger
, options
);
40 this.mysteryBox
= new MysteryBox(options
);
41 this.mysteryBox
.on('statistics', common
.mysteryBoxLogger(logger
, _fileScope(this.constructor.name
)));
43 this.cookieLifespan
= options
.authenticator
.inactiveSessionLifespanSeconds
|| 60 * 60 * 24 * 32;
48 * Set or update our session cookie.
49 * @param {http.ServerResponse} res
50 * @param {Object=} session
51 * @param {Number=} maxAge
52 * @param {String=} path
54 async
_sessionCookieSet(res
, session
, maxAge
= this.cookieLifespan
, path
= '/') {
55 const cookieName
= Enum
.SessionCookie
;
56 const secureSession
= session
&& await
this.mysteryBox
.pack(session
) || '""';
57 common
.addCookie(res
, cookieName
, secureSession
, {
60 secure: this.options
.authenticator
.secureAuthOnly
,
61 maxAge: session
&& maxAge
|| 0,
68 * Remove any current session cookie.
69 * @param {http.ServerResponse} res
70 * @param {String} path
72 async
_sessionCookieClear(res
, path
= '/') {
73 await
this._sessionCookieSet(res
, undefined, 0, path
);
77 * GET request for establishing admin session.
78 * @param {http.ServerResponse} res
81 async
getAdminLogin(res
, ctx
) {
82 const _scope
= _fileScope('getAdminLogin');
83 this.logger
.debug(_scope
, 'called', { ctx
});
85 // If there is already a valid session established, and if a
86 // redirect is present, follow it. Why? Maybe someone had
87 // multiple tabs open, their session expired, and their browser
88 // restarted, reloading all of them, and they have relogged in
89 // on one and just want to hit reload on the others to go back
90 // to where they were.
91 const redirect
= ctx
.queryParams
['r'];
92 if (ctx
.authenticationId
&& redirect
) {
94 res
.setHeader(Enum
.Header
.Location
, redirect
);
97 res
.end(Template
.LoginHTML(ctx
, this.options
));
100 this.logger
.info(_scope
, 'finished', { ctx
});
105 * POST request for taking form data to establish admin session.
106 * @param {http.ServerResponse} res
107 * @param {Object} ctx
109 async
postAdminLogin(res
, ctx
) {
110 const _scope
= _fileScope('postAdminLogin');
111 this.logger
.debug(_scope
, 'called', { ctx
});
115 // Check if this was an OTP entry attempt.
116 if (await
this._otpSubmission(res
, ctx
)) {
117 // OTP path was taken, either successful entry and session creation, or re-prompting for otp.
121 if (await
this._localUserAuth(res
, ctx
)) {
122 // Local auth path was taken.
126 // Otherwise, carry on with IndieAuth handshake.
128 // Is profile a reasonable url?
129 let me
, meAutoScheme
, session
, authorizationEndpoint
;
131 me
= new URL(ctx
.parsedBody
['me']);
132 meAutoScheme
= !!ctx
.parsedBody
['me_auto_scheme'];
134 this.logger
.debug(_scope
, 'failed to parse supplied profile url', { ctx
});
135 ctx
.errors
.push(`Unable to understand '${ctx.parsedBody['me']}' as a profile URL.`);
138 if (ctx
.errors
.length
) {
139 res
.end(Template
.LoginHTML(ctx
, this.options
));
144 profile
= await
this.indieAuthCommunication
.fetchProfile(me
);
145 if ((!profile
?.metadata
)
147 this.logger
.debug(_scope
, 'trying http fallback', { ctx
});
148 me
.protocol
= 'http';
149 profile
= await
this.indieAuthCommunication
.fetchProfile(me
);
151 if (!profile
?.metadata
) {
152 this.logger
.debug(_scope
, 'failed to find any profile information at url', { ctx
});
153 ctx
.errors
.push(`No profile information was found at '${me}'.`);
155 // fetch and parse me for 'authorization_endpoint' relation links
157 authorizationEndpoint
= new URL(profile
.metadata
.authorizationEndpoint
);
159 ctx
.errors
.push(`Unable to understand the authorization endpoint ('${profile.metadata.authorizationEndpoint}') indicated by that profile ('${me}') as a URL.`);
162 if (profile
.metadata
.issuer
) {
165 const issuer
= new URL(profile
.metadata
.issuer
);
168 || issuer
.protocol
.toLowerCase() !== 'https:') { // stupid URL trailing colon thing
169 this.logger
.debug(_scope
, 'supplied issuer url invalid', { ctx
});
170 ctx
.errors
.push('Authorization server provided an invalid issuer field.');
173 this.logger
.debug(_scope
, 'failed to parse supplied issuer url', { ctx
});
174 ctx
.errors
.push('Authorization server provided an unparsable issuer field.');
177 this.logger
.debug(_scope
, 'no issuer in metadata, assuming legacy mode', { ctx
});
178 // Strict 20220212 compliance would error here.
179 // ctx.errors.push('Authorization server did not provide issuer field, as required by current specification.');
183 if (authorizationEndpoint
) {
184 const pkce
= await IndieAuthCommunication
.generatePKCE();
186 const state
= randomUUID();
187 const redirect
= ctx
.queryParams
['r'] || './';
189 authorizationEndpoint: authorizationEndpoint
.href
,
191 codeVerifier: pkce
.codeVerifier
,
194 issuer: profile
.metadata
.issuer
,
197 // Update auth endpoint parameters
199 'response_type': 'code',
200 'client_id': this.options
.dingus
.selfBaseUrl
,
201 'redirect_uri': `${this.options.dingus.selfBaseUrl}admin/_ia`,
202 'state': session
.state
,
203 'code_challenge': pkce
.codeChallenge
,
204 'code_challenge_method': pkce
.codeChallengeMethod
,
206 }).forEach(([name
, value
]) => authorizationEndpoint
.searchParams
.set(name
, value
));
209 if (ctx
.errors
.length
) {
210 res
.end(Template
.LoginHTML(ctx
, this.options
));
214 await
this._sessionCookieSet(res
, session
);
215 res
.setHeader(Enum
.Header
.Location
, authorizationEndpoint
.href
);
216 res
.statusCode
= 302; // Found
219 this.logger
.info(_scope
, 'finished indieauth', { ctx
});
224 * @typedef {Object} OTPState
225 * @property {String} authenticatedIdentifier
226 * @property {Buffer|String} key
227 * @property {Number} attempt
228 * @property {Number} epochMs
229 * @property {String} redirect
232 * @param {OTPState} otpState
234 static _validateOTPState(otpState
) {
235 if (!otpState
.authenticatedIdentifier
) {
236 throw new Error('otp state missing authentication identifier');
239 throw new Error('otp state missing otp key');
241 if (!('attempt' in otpState
)) {
242 throw new Error('otp state missing attempt count');
244 if (!('epochMs' in otpState
)) {
245 throw new Error('otp state missing timestamp');
247 if (!otpState
.redirect
) {
248 throw new Error('otp state missing redirect');
254 * Check if processing an OTP entry attempt. If not, resume login flow.
255 * If so, validate otp and establish session, else reprompt for OTP, or
256 * return to login entry after too many failures.
257 * @param {http.ServerResponse} res
258 * @param {Object} ctx
259 * @param {Object} ctx.parsedBody
260 * @param {String} ctx.parsedBody.state
261 * @param {String} ctx.parsedBody.otp
262 * @returns {Promise<Boolean>} true if otp was handled, otherwise false indicates further login processing needed
264 async
_otpSubmission(res
, ctx
) {
265 const _scope
= _fileScope('_otpSubmission');
271 // Are we processing an OTP entry attempt?
273 // Ignore and continue back to main login.
276 /** @type OTPState */
279 state
= await
this.mysteryBox
.unpack(stateBox
);
280 this.constructor._validateOTPState(state
);
282 this.logger
.debug(_scope
, 'failed to unpack otp state', { error: e
, ctx
});
283 // Ignore and continue back to main login.
288 // Nothing submitted, but valid state, just present otp form again, do not count as attempt.
289 ctx
.otpState
= stateBox
;
290 res
.end(Template
.OTPHTML(ctx
, this.options
));
291 this.logger
.info(_scope
, 'finished otp, nothing entered, request again', { ctx
});
295 const OTPResult
= await
this.authenticator
.checkOTP(state
, otp
);
297 case Enum
.OTPResult
.Valid:
298 // Valid auth, persist the authenticated session
300 authenticatedIdentifier: state
.authenticatedIdentifier
,
302 await
this._sessionCookieSet(res
, ctx
.session
);
303 res
.statusCode
= 302;
304 res
.setHeader(Enum
.Header
.Location
, state
.redirect
);
306 this.logger
.info(_scope
, 'finished otp', { ctx
});
309 case Enum
.OTPResult
.InvalidSoftFail:
311 ctx
.errors
.push('Invalid OTP token.');
312 ctx
.otpState
= await
this.mysteryBox
.pack({
314 attempt: state
.attempt
+ 1,
316 res
.end(Template
.OTPHTML(ctx
, this.options
));
317 this.logger
.info(_scope
, 'finished otp, invalid, request again', { ctx
});
320 case Enum
.OTPResult
.InvalidHardFail:
321 // Return to initial login.
322 this.logger
.debug(_scope
, 'too many otp failures', { ctx
});
323 ctx
.errors
.push('Unable to verify OTP token at this time. Try again.');
327 throw new RangeError('Unexpected OTPResult');
334 * @param {http.ServerResponse} res
335 * @param {Object} ctx
336 * @returns {Promise<Boolean>} true if handled, false if flow should continue
338 async
_localUserAuth(res
, ctx
) {
339 const _scope
= _fileScope('_localUserAuth');
341 // If Indiauth enabled and profile was submitted, defer to that.
342 if (this.options
.authenticator
.authnEnabled
.includes('indieAuth')
343 && ctx
.parsedBody
['me']) {
347 const redirect
= ctx
.queryParams
['r'] || './';
348 const identifier
= ctx
.parsedBody
['identifier'];
349 const credential
= ctx
.parsedBody
['credential']; // N.B. Logger must specifically mask this field from ctx.
351 // N.B. validity check also sets authenticationId and maybe otpKey on ctx
352 const isValidLocalIdentifier
= await
this.authenticator
.isValidIdentifierCredential(identifier
, credential
, ctx
);
353 if (!isValidLocalIdentifier
) {
354 ctx
.errors
.push('Invalid username or password');
357 if (ctx
.errors
.length
) {
358 res
.end(Template
.LoginHTML(ctx
, this.options
));
362 // If OTP exists for valid identifier, follow that flow.
364 ctx
.otpState
= await
this.mysteryBox
.pack({
365 authenticatedIdentifier: ctx
.authenticationId
,
371 res
.end(Template
.OTPHTML(ctx
, this.options
));
372 this.logger
.info(_scope
, 'finished local, otp required', { ctx
});
376 // Valid auth, persist the authenticated session
378 authenticatedIdentifier: ctx
.authenticationId
,
380 await
this._sessionCookieSet(res
, ctx
.session
);
381 res
.statusCode
= 302;
382 res
.setHeader(Enum
.Header
.Location
, redirect
);
384 this.logger
.info(_scope
, 'finished local, no otp', { ctx
});
390 * GET request to remove current credentials.
391 * @param {http.ServerResponse} res
392 * @param {Object} ctx
394 async
getAdminLogout(res
, ctx
) {
395 const _scope
= _fileScope('getAdminLogout');
396 this.logger
.debug(_scope
, 'called', { ctx
});
398 await
this._sessionCookieClear(res
);
400 const redirect
= ctx
.queryParams
['r'] || './';
402 res
.statusCode
= 302;
403 res
.setHeader(Enum
.Header
.Location
, redirect
);
406 this.logger
.info(_scope
, 'finished', { ctx
});
411 * GET request for returning IndieAuth redirect.
412 * This currently only redeems a scope-less profile.
413 * @param {http.ServerResponse} res
414 * @param {Object} ctx
416 async
getAdminIA(res
, ctx
) {
417 const _scope
= _fileScope('getAdminIA');
418 this.logger
.debug(_scope
, 'called', { ctx
});
423 // Unpack cookie to restore session data
425 const cookieValue
= ctx
.cookie
?.[Enum
.SessionCookie
];
427 this.logger
.debug(_scope
, 'no cookie', { ctx
});
428 ctx
.errors
.push('missing required cookie');
431 ctx
.session
= await
this.mysteryBox
.unpack(cookieValue
);
432 this.logger
.debug(_scope
, 'restored session from cookie', { ctx
});
434 this.logger
.debug(_scope
, 'could not unpack cookie');
435 ctx
.errors
.push('invalid cookie');
439 // Validate unpacked session values
442 // Add any auth errors
443 if (ctx
.queryParams
['error']) {
444 ctx
.errors
.push(ctx
.queryParams
['error']);
445 if (ctx
.queryParams
['error_description']) {
446 ctx
.errors
.push(ctx
.queryParams
['error_description']);
451 if (ctx
.queryParams
['state'] !== ctx
.session
.state
) {
452 this.logger
.debug(_scope
, 'state mismatch', { ctx
});
453 ctx
.errors
.push('invalid state');
456 const code
= ctx
.queryParams
['code'];
458 this.logger
.debug(_scope
, 'missing code', { ctx
});
459 ctx
.errors
.push('invalid code');
463 if (ctx
.session
.issuer
) {
464 if (ctx
.queryParams
['iss'] !== ctx
.session
.issuer
) {
465 this.logger
.debug(_scope
, 'issuer mismatch', { ctx
});
466 ctx
.errors
.push('invalid issuer');
469 this.logger
.debug(_scope
, 'no issuer in metadata, assuming legacy mode', { ctx
});
470 // Strict 20220212 compliance would error here. (Also earlier.)
471 // ctx.errors.push('invalid issuer');
474 let redeemProfileUrl
;
476 redeemProfileUrl
= new URL(ctx
.session
.authorizationEndpoint
);
478 this.logger
.debug(_scope
, 'failed to parse restored session authorization endpoint as url', { ctx
});
479 ctx
.errors
.push('invalid cookie');
482 if (redeemProfileUrl
) {
483 profile
= await
this.indieAuthCommunication
.redeemProfileCode(redeemProfileUrl
, code
, ctx
.session
.codeVerifier
, this.options
.dingus
.selfBaseUrl
, `${this.options.dingus.selfBaseUrl}admin/_ia`);
485 this.logger
.debug(_scope
, 'no profile from code redemption', { ctx
});
486 ctx
.errors
.push('did not get a profile response from authorization endpoint code redemption');
487 } else if (!profile
.me
) {
488 this.logger
.debug(_scope
, 'no profile me identifier from code redemption', { ctx
});
489 ctx
.errors
.push('did not get \'me\' value from authorization endpoint code redemption');
490 } else if (profile
.me
!== ctx
.session
.me
) {
491 this.logger
.debug(_scope
, 'mis-matched canonical me from redeemed profile', { ctx
, profile
});
492 const newProfileUrl
= new URL(profile
.me
);
493 // Rediscover auth endpoint for the new returned profile.
494 const newProfile
= await
this.indieAuthCommunication
.fetchProfile(newProfileUrl
);
495 if (newProfile
.metadata
.authorizationEndpoint
!== ctx
.session
.authorizationEndpoint
) {
496 this.logger
.debug(_scope
, 'mis-matched auth endpoints between provided me and canonical me', { ctx
, profile
, newProfile
});
497 ctx
.errors
.push('canonical profile url provided by authorization endpoint is not handled by that endpoint, cannot continue');
499 // The endpoints match, all is okay, update our records.
500 ctx
.session
.me
= profile
.me
;
505 if (ctx
.errors
.length
) {
506 await
this._sessionCookieClear(res
);
507 res
.end(Template
.IAHTML(ctx
, this.options
));
511 const redirect
= ctx
.session
.redirect
|| './';
513 // Set cookie as auth valid, redirect to original location.
515 authenticatedProfile: ctx
.session
.me
,
518 await
this._sessionCookieSet(res
, ctx
.session
);
519 res
.statusCode
= 302;
520 res
.setHeader(Enum
.Header
.Location
, redirect
);
523 this.logger
.info(_scope
, 'finished', { ctx
});
528 * Page for modifying credentials and OTP.
529 * @param {http.ServerResponse} res
530 * @param {Object} ctx
532 async
getAdminSettings(res
, ctx
) {
533 const _scope
= _fileScope('getAdminSettings');
534 this.logger
.debug(_scope
, 'called', { ctx
});
537 await
this.db
.context(async (dbCtx
) => {
538 const authData
= await
this.db
.authenticationGet(dbCtx
, ctx
.authenticationId
);
540 ctx
.errors
.push('Sorry, you do not seem to exist! <pre>¯\\_(ツ)_/¯</pre> Cannot do anything useful here!');
543 ctx
.otpKey
= authData
.otpKey
;
546 this.logger
.error(_scope
, 'failed', { ctx
, error: e
});
547 ctx
.errors
.push('An error was encountered. Sorry that is not very helpful.');
550 res
.end(Template
.SettingsHTML(ctx
, this.options
));
551 this.logger
.info(_scope
, 'finished', { ctx
});
556 * Page for modifying credentials and OTP.
557 * @param {http.ServerResponse} res
558 * @param {Object} ctx
560 async
postAdminSettings(res
, ctx
) {
561 const _scope
= _fileScope('postAdminSettings');
562 this.logger
.debug(_scope
, 'called', { ctx
});
565 await
this.db
.context(async (dbCtx
) => {
566 const authData
= await
this.db
.authenticationGet(dbCtx
, ctx
.authenticationId
);
568 ctx
.errors
.push('Sorry, you do not seem to exist! <pre>¯\\_(ツ)_/¯</pre> Cannot do anything useful here!');
571 ctx
.otpKey
= authData
.otpKey
;
573 const otpSubmitButton
= ctx
.parsedBody
?.otp
;
574 switch (otpSubmitButton
) {
576 await
this._otpDisable(dbCtx
, ctx
, authData
);
580 await
this._otpConfirm(dbCtx
, ctx
);
584 await
this._otpEnable(ctx
);
588 const credentialSubmitButton
= ctx
.parsedBody
?.credential
;
589 switch (credentialSubmitButton
) { // eslint-disable-line sonarjs/no-small-switch
591 await
this._credentialUpdate(dbCtx
, ctx
, authData
);
596 this.logger
.error(_scope
, 'failed', { ctx
, error: e
});
597 ctx
.errors
.push('An error was encountered. Sorry that is not very helpful.');
600 res
.end(Template
.SettingsHTML(ctx
, this.options
));
601 this.logger
.info(_scope
, 'finished', { ctx
});
606 * Submission to disable OTP.
609 * @param {AuthInfo} authData
611 async
_otpDisable(dbCtx
, ctx
, authData
) {
612 const _scope
= _fileScope('_otpDisable');
614 authData
.otpKey
= null;
615 await
this.db
.authenticationUpdateOTPKey(dbCtx
, ctx
.authenticationId
, null);
616 ctx
.notifications
.push('OTP removed!');
618 this.logger
.info(_scope
, 'otp disabled', { identifier: ctx
.authenticationId
});
620 this.logger
.error(_scope
, 'failed', { error: e
, ctx
});
621 ctx
.errors
.push('Failed to disable OTP!');
627 * Submission to enable OTP.
628 * @param {Object} ctx
630 async
_otpEnable(ctx
) {
631 const _scope
= _fileScope('_otpEnable');
633 ctx
.otpConfirmKey
= await TOTP
.createKey('sha1', 'base32');
634 ctx
.otpConfirmBox
= await
this.mysteryBox
.pack({
635 otpKey: ctx
.otpConfirmKey
,
637 otpInitiatedMs: Date
.now(),
640 delete ctx
.otpConfirmKey
;
641 delete ctx
.otpConfirmBox
;
642 this.logger
.error(_scope
, 'failed', { error: e
, ctx
});
643 ctx
.errors
.push('Failed to enable OTP!');
649 * Submission to confirm enabling OTP.
651 * @param {Object} ctx
653 async
_otpConfirm(dbCtx
, ctx
) {
654 const _scope
= _fileScope('_otpConfirm');
657 'otp-box': otpConfirmBox
,
658 'otp-token': otpToken
,
660 let otpKey
, otpAttempt
, otpInitiatedMs
;
662 ({ otpKey
, otpAttempt
, otpInitiatedMs
} = await
this.mysteryBox
.unpack(otpConfirmBox
));
664 this.logger
.debug(_scope
, 'failed to unpack otp box', { error: e
, ctx
});
665 ctx
.errors
.push('Problem with form data.');
669 // No token entered, just prompt again.
670 ctx
.otpConfirmKey
= otpKey
;
671 ctx
.otpConfirmBox
= otpConfirmBox
;
672 ctx
.notifications
.push('Please enter the OTP token to enable 2FA.');
676 const totp
= new TOTP({
678 keyEncoding: 'base32',
680 if (!totp
.validate(otpToken
)) {
681 // Bad token, prompt again.
682 ctx
.otpConfirmKey
= otpKey
;
683 ctx
.otpConfirmBox
= await
this.mysteryBox
.pack({
688 ctx
.errors
.push('Invalid token!');
693 await
this.db
.context(async (dbCtx
) => {
694 await
this.db
.authenticationUpdateOTPKey(dbCtx
, ctx
.authenticationId
, otpKey
);
696 ctx
.notifications
.push('OTP enabled!');
697 this.logger
.info(_scope
, 'otp enabled', { identifier: ctx
.authenticationId
, otpAttempt
, otpInitiatedMs
});
700 this.logger
.debug(_scope
, 'failed', { error: e
, ctx
});
701 ctx
.errors
.push('An error occurred, OTP was not enabled. Sorry this is not very helpful.');
707 * Submission to set new credential.
709 * @param {Object} ctx
710 * @param {AuthInfo} authData
712 async
_credentialUpdate(dbCtx
, ctx
, authData
) {
713 const _scope
= _fileScope('_credentialUpdate');
716 'credential-new': newCredential
,
717 'credential-new-2': newCredential2
,
718 'credential-current': oldCredential
,
720 if (newCredential
!== newCredential2
) {
721 ctx
.errors
.push('New password confirmation did not match!');
723 if (!newCredential
) {
724 ctx
.errors
.push('Password cannot be empty!');
726 if (! await
this.authenticator
._validateAuthDataCredential(authData
, oldCredential
)) {
727 ctx
.errors
.push('Invalid current password!');
729 if (ctx
.errors
.length
) {
733 await
this.authenticator
.updateCredential(dbCtx
, ctx
.authenticationId
, newCredential
);
734 ctx
.notifications
.push('Password updated!');
736 this.logger
.error(_scope
, 'failed', { error: e
, ctx
});
737 ctx
.errors
.push('Failed to update password!');
744 module
.exports
= SessionManager
;