-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
385 lines (324 loc) · 10.7 KB
/
index.js
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
const process = require('node:process');
const Boom = require('@hapi/boom');
const auth = require('basic-auth');
const isSANB = require('is-string-and-not-blank');
const { boolean } = require('boolean');
const { request } = require('undici');
function hasFlashAndAcceptsHTML(ctx) {
return typeof ctx.flash === 'function' && ctx.accepts('html');
}
function hasTranslationHelper(ctx) {
return typeof ctx.request === 'object' && typeof ctx.request.t === 'function';
}
class Policies {
constructor(config, findByTokenFn) {
this.config = {
requireVerificationPostLogin: false,
verifyRoute: '/verify',
loginRoute: '/login',
loginOtpRoute: '/otp/login',
schemeName: null,
passport: {
fields: {
otpEnabled: 'otp_enabled'
}
},
userFields: {
hasVerifiedEmail: 'has_verified_email'
},
turnstileEnabled: false,
turnstileSecretKey: null,
...config
};
if (typeof findByTokenFn !== 'function')
throw new TypeError('findByTokenFn must be defined and return a Promise');
// bind the function to this instance
this.findByTokenFn = findByTokenFn;
// bind this
this.checkVerifiedEmail = this.checkVerifiedEmail.bind(this);
this.ensureLoggedIn = this.ensureLoggedIn.bind(this);
this.ensureApiToken = this.ensureApiToken.bind(this);
this.ensureLoggedOut = this.ensureLoggedOut.bind(this);
this.ensureAdmin = this.ensureAdmin.bind(this);
this.ensureOtp = this.ensureOtp.bind(this);
this.ensureTurnstile = this.ensureTurnstile.bind(this);
}
// eslint-disable-next-line complexity
async checkVerifiedEmail(ctx, next) {
if (!ctx.isAuthenticated()) {
ctx.session.returnTo = ctx.originalUrl || ctx.req.url;
const message = ctx.translate
? ctx.translate('LOGIN_REQUIRED')
: 'Please log in to view the page you requested.';
if (ctx.api) return ctx.throw(Boom.unauthorized(message));
if (hasFlashAndAcceptsHTML(ctx)) {
if (hasTranslationHelper(ctx)) {
ctx.flash('custom', {
title: ctx.request.t('Warning'),
text: message,
type: 'warning',
toast: true,
showConfirmButton: false,
timer: 3000,
position: 'top'
});
} else {
ctx.flash('warning', message);
}
}
const redirectTo =
typeof ctx.state.l === 'function'
? ctx.state.l(this.config.loginRoute)
: this.config.loginRoute;
if (ctx.accepts('html')) ctx.redirect(redirectTo);
else ctx.body = { message, redirectTo };
return;
}
if (!this.config.userFields.hasVerifiedEmail) {
if (next) return next();
return;
}
if (ctx.state.user[this.config.userFields.hasVerifiedEmail]) {
if (next) return next();
return;
}
if (
typeof ctx.pathWithoutLocale === 'string'
? ctx.pathWithoutLocale === this.config.verifyRoute
: ctx.path === this.config.verifyRoute
) {
if (next) return next();
return;
}
const message = ctx.translate
? ctx.translate('EMAIL_VERIFICATION_REQUIRED')
: 'Please verify your email address to continue.';
if (ctx.api) return ctx.throw(Boom.unauthorized(message));
if (hasFlashAndAcceptsHTML(ctx)) {
if (hasTranslationHelper(ctx)) {
ctx.flash('custom', {
title: ctx.request.t('Warning'),
text: message,
type: 'warning',
toast: true,
showConfirmButton: false,
timer: 3000,
position: 'top'
});
} else {
ctx.flash('warning', message);
}
}
const redirect = `${this.config.verifyRoute}?redirect_to=${
ctx.originalUrl || ctx.req.url
}`;
const redirectTo =
typeof ctx.state.l === 'function' ? ctx.state.l(redirect) : redirect;
if (ctx.accepts('html')) ctx.redirect(redirectTo);
else ctx.body = { message, redirectTo };
}
async ensureOtp(ctx, next) {
if (!boolean(process.env.AUTH_OTP_ENABLED)) return next();
if (
!ctx.isAuthenticated() ||
(ctx.state.user[this.config.passport.fields.otpEnabled] &&
!ctx.session.otp)
) {
ctx.session.returnTo = ctx.originalUrl || ctx.req.url;
const message = ctx.translate
? ctx.translate('TWO_FACTOR_REQUIRED')
: 'Please log in with two-factor authentication to continue.';
// if (hasFlashAndAcceptsHTML(ctx)) ctx.flash('warning', message);
const redirectTo =
typeof ctx.state.l === 'function'
? ctx.state.l(this.config.loginOtpRoute)
: this.config.loginOtpRoute;
if (ctx.accepts('html')) ctx.redirect(redirectTo);
else ctx.body = { message, redirectTo };
return;
}
return next();
}
async ensureLoggedIn(ctx, next) {
// a more simpler version that is adapted from
// `koa-ensure-login` to use async/await
// (this is adapted = require(the original `connect-ensure-login`)
// <https://github.com/RobinQu/koa-ensure-login>
// <https://github.com/jaredhanson/connect-ensure-login>
if (!ctx.isAuthenticated()) {
ctx.session.returnTo = ctx.originalUrl || ctx.req.url;
const message = ctx.translate
? ctx.translate('LOGIN_REQUIRED')
: 'Please log in to view the page you requested.';
if (ctx.api) return ctx.throw(Boom.unauthorized(message));
if (hasFlashAndAcceptsHTML(ctx)) {
if (hasTranslationHelper(ctx)) {
ctx.flash('custom', {
title: ctx.request.t('Warning'),
text: message,
type: 'warning',
toast: true,
showConfirmButton: false,
timer: 3000,
position: 'top'
});
} else {
ctx.flash('warning', message);
}
}
let redirectTo =
typeof ctx.state.l === 'function'
? ctx.state.l(this.config.loginRoute)
: this.config.loginRoute;
if (ctx.url && ctx.url !== '/')
redirectTo += `?return_to=${encodeURIComponent(ctx.url)}`;
if (ctx.accepts('html')) ctx.redirect(redirectTo);
else ctx.body = { message, redirectTo };
return;
}
// check if the user has a verified email
if (this.config.requireVerificationPostLogin)
return this.checkVerifiedEmail(ctx, next);
return next();
}
async ensureApiToken(ctx, next) {
const credentials = auth(ctx.req);
if (
credentials === undefined ||
typeof credentials.name !== 'string' ||
!credentials.name
)
return ctx.throw(
Boom.unauthorized(
ctx.translate
? ctx.translate('INVALID_API_CREDENTIALS')
: 'Invalid API credentials.',
this.config.schemeName
)
);
const user = await this.findByTokenFn(credentials.name, ctx);
if (!user)
return ctx.throw(
Boom.unauthorized(
ctx.translate
? ctx.translate('INVALID_API_TOKEN')
: 'Invalid API token.',
this.config.schemeName
)
);
await ctx.login(user, { session: false });
// check if the user has a verified email
return this.checkVerifiedEmail(ctx, next);
}
async ensureLoggedOut(ctx, next) {
if (ctx.isAuthenticated()) {
ctx.session.returnTo = ctx.originalUrl || ctx.req.url;
const message = ctx.translate
? ctx.translate('LOGOUT_REQUIRED')
: 'Please log out to view the page you requested.';
if (ctx.api) return ctx.throw(Boom.unauthorized(message));
if (hasFlashAndAcceptsHTML(ctx)) {
if (hasTranslationHelper(ctx)) {
ctx.flash('custom', {
title: ctx.request.t('Warning'),
text: message,
type: 'warning',
toast: true,
showConfirmButton: false,
timer: 3000,
position: 'top'
});
} else {
ctx.flash('warning', message);
}
}
const redirectTo =
ctx.get('Referrer') || typeof ctx.state.l === 'function'
? ctx.state.l('/')
: '/';
if (ctx.accepts('html')) ctx.redirect(redirectTo);
else ctx.body = { message, redirectTo };
return;
}
return next();
}
async ensureAdmin(ctx, next) {
if (!ctx.isAuthenticated() || ctx.state.user.group !== 'admin')
return ctx.throw(
Boom.unauthorized(
ctx.translate
? ctx.translate('IS_NOT_ADMIN')
: 'You do not belong to the administrative user group.'
)
);
// check if the user has a verified email
return this.checkVerifiedEmail(ctx, next);
}
async ensureTurnstile(ctx, next) {
if (!boolean(this.config.turnstileEnabled)) return next();
if (
ctx.isAuthenticated() &&
ctx.state.user &&
ctx.state.user.group === 'admin'
)
return next();
if (!isSANB(ctx.request.body['cf-turnstile-response'])) {
const err = Boom.badRequest(
ctx.translate
? ctx.translate('TURNSTILE_NOT_VERIFIED')
: 'Turnstile not verified.'
);
err.is_turnstile = true;
ctx.throw(err);
return;
}
try {
// <https://github.com/cloudflare/turnstile-demo-workers/blob/main/src/index.mjs>
const res = await request(
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
secret: this.config.turnstileSecretKey,
response: ctx.request.body['cf-turnstile-response'],
remoteip: ctx.request.headers['CF-Connecting-IP'] || ctx.ip
})
}
);
const body = await res.body.json();
ctx.logger.debug('turnstile response', {
headers: res.headers,
statusCode: res.statusCode,
body
});
if (body.success !== true) {
// https://developers.cloudflare.com/turnstile/get-started/server-side-validation/#error-codes
// body['error-codes'] = [ ... ]
ctx.logger.warn('turnstile error', {
headers: res.headers,
statusCode: res.statusCode,
body
});
// https://docs.turnstile.com/#siteverify-error-codes-table
const err = Boom.badRequest(
ctx.translate
? ctx.translate('TURNSTILE_NOT_VERIFIED')
: 'Turnstile not verified.'
);
err.is_turnstile = true;
ctx.throw(err);
return;
}
return next();
} catch (err) {
// this indicates an HTTP error or error while parsing JSON response
// (e.g. in case the turnstile service goes down)
ctx.logger.fatal(err);
return next();
}
}
}
module.exports = Policies;