Repository navigation
Expand file tree
/
Copy pathmembers-ssr.js
More file actions
380 lines (343 loc) · 10.3 KB
/
Copy pathmembers-ssr.js
File metadata and controls
380 lines (343 loc) · 10.3 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
const { parse: parseUrl } = require('url');
const createCookies = require('cookies');
const debug = require('@tryghost/debug')('members-ssr');
const { BadRequestError, IncorrectUsageError } = require('@tryghost/errors');
/**
* @typedef {import('http').IncomingMessage} Request
* @typedef {import('http').ServerResponse} Response
* @typedef {import('cookies').ICookies} Cookies
* @typedef {import('cookies').Option} CookiesOptions
* @typedef {import('cookies').SetOption} SetCookieOptions
* @typedef {string} JWT
*/
/**
* @typedef {object} Member
* @prop {string} id
* @prop {string} transient_id
* @prop {string} email
*/
const SIX_MONTHS_MS = 1000 * 60 * 60 * 24 * 184;
class MembersSSR {
/**
* @typedef {object} MembersSSROptions
*
* @prop {string|string[]} cookieKeys - A secret or array of secrets used to sign cookies
* @prop {() => object} getMembersApi - A function which returns an instance of members-api
* @prop {boolean} [cookieSecure = true] - Whether the cookie should have Secure flag
* @prop {string} [cookieName] - The name of the members-ssr cookie
* @prop {number} [cookieMaxAge] - The max age in ms of the members-ssr cookie
* @prop {string} [cookiePath] - The Path flag for the cookie
* @prop {boolean} [dangerousRemovalOfSignedCookie] - Flag for removing signed cookie
*/
/**
* Create an instance of MembersSSR
*
* @param {MembersSSROptions} options - The options for the members ssr class
*/
constructor(options) {
const {
cookieSecure = true,
cookieName = 'members-ssr',
cookieMaxAge = SIX_MONTHS_MS,
cookiePath = '/',
cookieKeys,
getMembersApi,
dangerousRemovalOfSignedCookie,
} = options;
if (!getMembersApi) {
throw new IncorrectUsageError({ message: 'Missing option getMembersApi' });
}
this._getMembersApi = getMembersApi;
if (!cookieKeys) {
throw new IncorrectUsageError({ message: 'Missing option cookieKeys' });
}
this.sessionCookieName = cookieName;
/**
* @type SetCookieOptions
*/
this.sessionCookieOptions = {
signed: true,
httpOnly: true,
sameSite: 'lax',
maxAge: cookieMaxAge,
path: cookiePath,
};
if (dangerousRemovalOfSignedCookie === true) {
this.sessionCookieOptions.signed = false;
}
/**
* @type CookiesOptions
*/
this.cookiesOptions = {
keys: Array.isArray(cookieKeys) ? cookieKeys : [cookieKeys],
secure: cookieSecure,
};
}
/**
* @method _getCookies
*
* @param {Request} req
* @param {Response} res
*
* @returns {Cookies} An instance of the cookies object for current request/response
*/
_getCookies(req, res) {
return createCookies(req, res, this.cookiesOptions);
}
/**
* @method _removeSessionCookie
*
* @param {Request} req
* @param {Response} res
*/
_removeSessionCookie(req, res) {
const cookies = this._getCookies(req, res);
cookies.set(this.sessionCookieName, null, this.sessionCookieOptions);
// If members caching cookies are set, remove them
if (cookies.get('ghost-access') || cookies.get('ghost-access-hmac')) {
cookies.set('ghost-access', null, { ...this.sessionCookieOptions, signed: false });
cookies.set('ghost-access-hmac', null, { ...this.sessionCookieOptions, signed: false });
}
}
/**
* @method _setSessionCookie
*
* @param {Request} req
* @param {Response} res
* @param {string} value
*/
_setSessionCookie(req, res, value) {
if (!value) {
return this._removeSessionCookie(req, res);
}
const cookies = this._getCookies(req, res);
cookies.set(this.sessionCookieName, value, this.sessionCookieOptions);
}
/**
* @method _getSessionCookies
*
* @param {Request} req
* @param {Response} res
*
* @returns {string} The cookie value
*/
_getSessionCookies(req, res) {
const cookies = this._getCookies(req, res);
const value = cookies.get(this.sessionCookieName, { signed: true });
if (!value) {
// Clear orphaned cookie (cookies library only clears .sig on invalid signature)
const unsignedValue = cookies.get(this.sessionCookieName, { signed: false });
if (unsignedValue) {
cookies.set(this.sessionCookieName, null, { ...this.sessionCookieOptions, signed: false });
}
throw new BadRequestError({
message: `Cookie ${this.sessionCookieName} not found`,
});
}
return value;
}
/**
* @method _getMemberDataFromToken
*
* @param {JWT} token
* @param {string} [otcVerification]
*
* @returns {Promise<Member>} member
*/
async _getMemberDataFromToken(token, otcVerification) {
const api = await this._getMembersApi();
return api.getMemberDataFromMagicLinkToken(token, otcVerification);
}
/**
* @method _getMemberIdentityData
*
* @param {string} email
*
* @returns {Promise<Member>} member
*/
async _getMemberIdentityData(email) {
const api = await this._getMembersApi();
return api.getMemberIdentityData(email);
}
/**
* @method _getMemberIdentityData
*
* @param {string} transientId
*
* @returns {Promise<Member>} member
*/
async _getMemberIdentityDataFromTransientId(transientId) {
const api = await this._getMembersApi();
return api.getMemberIdentityDataFromTransientId(transientId);
}
/**
* @method _getMemberIdentityToken
*
* @param {string} email
*
* @returns {Promise<JWT>} member
*/
async _getMemberIdentityToken(transientId) {
const api = await this._getMembersApi();
return api.getMemberIdentityToken(transientId);
}
async _getMemberEntitlementToken(transientId) {
const api = await this._getMembersApi();
return api.getMemberEntitlementToken(transientId);
}
/**
* @method _setMemberGeolocationFromIp
* @param {string} email
* @param {string} ip
*
* @returns {Promise<Member>} member
*/
async _setMemberGeolocationFromIp(email, ip) {
const api = await this._getMembersApi();
return api.setMemberGeolocationFromIp(email, ip);
}
/**
* @method exchangeTokenForSession
* @param {Request} req
* @param {Response} res
*
* @returns {Promise<Member>} The member the session was created for
*/
async exchangeTokenForSession(req, res) {
if (!req.url) {
return Promise.reject(
new BadRequestError({
message: 'Expected token param containing JWT',
}),
);
}
const { query } = parseUrl(req.url, true);
if (!query || !query.token) {
return Promise.reject(
new BadRequestError({
message: 'Expected token param containing JWT',
}),
);
}
const token = Array.isArray(query.token) ? query.token[0] : query.token;
const otcVerification = Array.isArray(query.otc_verification)
? query.otc_verification[0]
: query.otc_verification;
const member = await this._getMemberDataFromToken(token, otcVerification);
if (!member) {
// The member doesn't exist any longer (could be a sign in token for a member that was deleted)
return Promise.reject(
new BadRequestError({
message: 'Invalid token',
}),
);
}
// perform and store geoip lookup for members when they log in
if (!member.geolocation) {
try {
await this._setMemberGeolocationFromIp(member.email, req.ip);
} catch (err) {
// no-op, we don't want to stop anything working due to
// geolocation lookup failing
debug(`Geolocation lookup failed: ${err.message}`);
}
}
this._setSessionCookie(req, res, member.transient_id);
return member;
}
async _cycleTransientId(memberId) {
const api = await this._getMembersApi();
return api.cycleTransientId(memberId);
}
/**
* @method deleteSession
* @param {Request} req
* @param {Response} res
*
* @returns {Promise<void>}
*/
async deleteSession(req, res) {
if (req.body && typeof req.body === 'object' && req.body.all) {
// Update transient_id to invalidate all sessions
const member = await this.getMemberDataFromSession(req, res);
if (member) {
await this._cycleTransientId(member.id);
}
}
this._removeSessionCookie(req, res);
}
/**
* @method getMemberDataFromSession
*
* @param {Request} req
* @param {Response} res
*
* @returns {Promise<Member>}
*/
/**
* Who this session belongs to, without loading them.
*
* The counterpart to `getMemberDataFromSession`, for callers that need to know a
* member is there rather than what is on their record.
*
* @method getMemberIdentityFromSession
* @param {Request} req
* @param {Response} res
*
* @returns {Promise<{id: string, email: string} | null>}
*/
async getMemberIdentityFromSession(req, res) {
const transientId = this._getSessionCookies(req, res);
const api = await this._getMembersApi();
return api.getMemberIdentity(transientId);
}
async getMemberDataFromSession(req, res) {
const transientId = this._getSessionCookies(req, res);
const member = await this._getMemberIdentityDataFromTransientId(transientId);
return member;
}
/**
* @method getIdentityTokenForMemberFromSession
*
* @param {Request} req
* @param {Response} res
*
* @returns {Promise<JWT>} identity token
*/
async getIdentityTokenForMemberFromSession(req, res) {
const transientId = this._getSessionCookies(req, res);
const token = await this._getMemberIdentityToken(transientId);
if (!token) {
await this.deleteSession(req, res);
throw new BadRequestError({
message: 'Invalid session, could not get identity token',
});
}
return token;
}
async getEntitlementTokenForMemberFromSession(req, res) {
const transientId = this._getSessionCookies(req, res);
const token = await this._getMemberEntitlementToken(transientId);
if (!token) {
await this.deleteSession(req, res);
throw new BadRequestError({
message: 'Invalid session, could not get entitlement token',
});
}
return token;
}
}
/**
* Factory function for creating instance of MembersSSR
*
* @param {MembersSSROptions} options
* @returns {MembersSSR}
*/
module.exports = function create(options) {
if (!options) {
throw new IncorrectUsageError({
message: 'Must pass options',
});
}
return new MembersSSR(options);
};