4 * Here we process activities which support login sessions.
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');
13 const _fileScope
= common
.fileScope(__filename
);
15 class SessionManager
{
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
28 constructor(logger
, authenticator
, options
) {
30 this.authenticator
= authenticator
;
31 this.options
= options
;
32 this.indieAuthCommunication
= new IndieAuthCommunication(logger
, options
);
33 this.mysteryBox
= new MysteryBox(logger
, options
);
35 this.cookieLifespan
= options
.authenticator
.inactiveSessionLifespanSeconds
|| 60 * 60 * 24 * 32;
40 * Set or update our session cookie.
41 * @param {http.ServerResponse} res
42 * @param {Object} session
43 * @param {Number} maxAge
44 * @param {String} path
46 async
_sessionCookieSet(res
, session
, maxAge
, path
= '/') {
47 const _scope
= _fileScope('_sessionCookieSet');
49 const cookieName
= Enum
.SessionCookie
;
50 const secureSession
= session
&& await
this.mysteryBox
.pack(session
) || '';
52 `${cookieName}=${secureSession}`,
56 if (this.options
.authenticator
.secureAuthOnly
) {
57 cookieParts
.push('Secure');
59 if (typeof(maxAge
) === 'number') {
60 cookieParts
.push(`Max-Age=${maxAge}`);
63 cookieParts
.push(`Path=${this.options.dingus.proxyPrefix}${path}`);
65 const cookie
= cookieParts
.join('; ');
66 this.logger
.debug(_scope
, 'session cookie', { cookie
, session
})
67 res
.setHeader(Enum
.Header
.SetCookie
, cookie
);
72 * GET request for establishing admin session.
73 * @param {http.ServerResponse} res
76 async
getAdminLogin(res
, ctx
) {
77 const _scope
= _fileScope('getAdminLogin');
78 this.logger
.debug(_scope
, 'called', { ctx
});
80 res
.end(Template
.LoginHTML(ctx
, this.options
));
81 this.logger
.info(_scope
, 'finished', { ctx
})
86 * POST request for taking form data to establish admin session.
87 * @param {http.ServerResponse} res
90 async
postAdminLogin(res
, ctx
) {
91 const _scope
= _fileScope('postAdminLogin');
92 this.logger
.debug(_scope
, 'called', { ctx
});
96 const redirect
= ctx
.queryParams
['r'] || './';
98 // Only attempt user login if no IndieAuth profile is set
99 if (!this.options
.authenticator
.authnEnabled
.includes('indieAuth') || !ctx
.parsedBody
['me']) {
101 const identifier
= ctx
.parsedBody
['identifier'];
102 const credential
= ctx
.parsedBody
['credential']; // N.B. Logger must specifically mask this field from ctx.
104 const isValidLocalIdentifier
= await
this.authenticator
.isValidIdentifierCredential(identifier
, credential
, ctx
);
105 if (!isValidLocalIdentifier
) {
106 ctx
.errors
.push('Invalid username or password');
109 if (ctx
.errors
.length
) {
110 res
.end(Template
.LoginHTML(ctx
, this.options
));
114 // Valid auth, persist the authenticated session
116 authenticatedIdentifier: ctx
.authenticationId
,
118 await
this._sessionCookieSet(res
, ctx
.session
, this.cookieLifespan
);
119 res
.statusCode
= 302;
120 res
.setHeader(Enum
.Header
.Location
, redirect
);
122 this.logger
.info(_scope
, 'finished local', { ctx
});
126 // Otherwise, carry on with IndieAuth handshake.
127 let me
, session
, authorizationEndpoint
;
129 me
= new URL(ctx
.parsedBody
['me']);
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.`);
135 if (this.options
.authenticator
.authnEnabled
.includes('indieAuth')
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}'.`);
142 // fetch and parse me for 'authorization_endpoint' relation links
144 authorizationEndpoint
= new URL(profile
.metadata
.authorizationEndpoint
);
146 ctx
.errors
.push(`Unable to understand the authorization endpoint ('${profile.metadata.authorizationEndpoint}') indicated by that profile ('${me}') as a URL.`);
149 if (profile
.metadata
.issuer
) {
152 const issuer
= new URL(profile
.metadata
.issuer
);
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.');
160 this.logger
.debug(_scope
, 'failed to parse supplied issuer url', { ctx
});
161 ctx
.errors
.push('Authorization server provided an unparsable issuer field.');
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.');
170 if (authorizationEndpoint
) {
171 const pkce
= await IndieAuthCommunication
.generatePKCE();
174 authorizationEndpoint: authorizationEndpoint
.href
,
175 state: ctx
.requestId
,
176 codeVerifier: pkce
.codeVerifier
,
179 issuer: profile
.metadata
.issuer
,
182 // Update auth endpoint parameters
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
,
191 }).forEach(([name
, value
]) => authorizationEndpoint
.searchParams
.set(name
, value
));
195 if (ctx
.errors
.length
) {
196 res
.end(Template
.LoginHTML(ctx
, this.options
));
200 await
this._sessionCookieSet(res
, session
, this.cookieLifespan
);
201 res
.setHeader(Enum
.Header
.Location
, authorizationEndpoint
.href
);
202 res
.statusCode
= 302; // Found
205 this.logger
.info(_scope
, 'finished indieauth', { ctx
})
210 * GET request to remove current credentials.
211 * @param {http.ServerResponse} res
212 * @param {Object} ctx
214 async
getAdminLogout(res
, ctx
) {
215 const _scope
= _fileScope('getAdminLogout');
216 this.logger
.debug(_scope
, 'called', { ctx
});
218 this._sessionCookieSet(res
, '', 0);
220 const redirect
= ctx
.queryParams
['r'] || './';
222 res
.statusCode
= 302;
223 res
.setHeader(Enum
.Header
.Location
, redirect
);
226 this.logger
.info(_scope
, 'finished', { ctx
});
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
236 async
getAdminIA(res
, ctx
) {
237 const _scope
= _fileScope('getAdminIA');
238 this.logger
.debug(_scope
, 'called', { ctx
});
243 // Unpack cookie to restore session data
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');
251 ctx
.session
= await
this.mysteryBox
.unpack(cookieValue
);
252 this.logger
.debug(_scope
, 'restored session from cookie', { ctx
});
254 this.logger
.debug(_scope
, 'could not unpack cookie');
255 ctx
.errors
.push('invalid cookie');
259 // Validate unpacked session values
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']);
271 if (ctx
.queryParams
['state'] !== ctx
.session
.state
) {
272 this.logger
.debug(_scope
, 'state mismatch', { ctx
});
273 ctx
.errors
.push('invalid state');
276 const code
= ctx
.queryParams
['code'];
278 this.logger
.debug(_scope
, 'missing code', { ctx
});
279 ctx
.errors
.push('invalid code');
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');
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');
294 let redeemProfileUrl
;
296 redeemProfileUrl
= new URL(ctx
.session
.authorizationEndpoint
);
298 this.logger
.debug(_scope
, 'failed to parse restored session authorization endpoint as url', { ctx
});
299 ctx
.errors
.push('invalid cookie');
302 if (redeemProfileUrl
) {
303 profile
= await
this.indieAuthCommunication
.redeemProfileCode(redeemProfileUrl
, code
, ctx
.session
.codeVerifier
, this.options
.dingus
.selfBaseUrl
, `${this.options.dingus.selfBaseUrl}admin/_ia`);
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');
319 // The endpoints match, all is okay, update our records.
320 ctx
.session
.me
= profile
.me
;
325 if (ctx
.errors
.length
) {
326 await
this._sessionCookieSet(res
, '', 0);
327 res
.end(Template
.IAHTML(ctx
, this.options
));
331 const redirect
= ctx
.session
.redirect
|| './';
333 // Set cookie as auth valid, redirect to original location.
335 authenticatedProfile: ctx
.session
.me
,
338 await
this._sessionCookieSet(res
, ctx
.session
, this.cookieLifespan
);
339 res
.statusCode
= 302;
340 res
.setHeader(Enum
.Header
.Location
, redirect
);
343 this.logger
.info(_scope
, 'finished', { ctx
})
349 module
.exports
= SessionManager
;