@xeplr/auth 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,546 @@
1
+ /**
2
+ * SIGNING IN WITH A CODE, AND THE SECOND STEP.
3
+ *
4
+ * Two things, sharing one code store (@xeplr/utils otp, in Redis) and one
5
+ * idea: a code proves you hold an inbox, a phone, or an authenticator app.
6
+ *
7
+ * 1. A code INSTEAD of a password — AUTH_LOGIN_METHODS email_otp / phone_otp.
8
+ * The address or number finds an EXISTING account; a code never creates
9
+ * one. A mobile number counts only once it is verified on the account
10
+ * (from the profile), so nobody can type someone else's number onto their
11
+ * own account and sign in as them — and a verified number belongs to one
12
+ * account only.
13
+ *
14
+ * 2. A code AFTER the first step (two-factor) — AUTH_2FA off | optional |
15
+ * required, AUTH_2FA_METHODS authenticator,email,sms. The first step
16
+ * gives a short-lived ticket instead of tokens; the second step turns the
17
+ * ticket into tokens. EMAIL IS ALWAYS OFFERED: someone who cannot open
18
+ * their authenticator app can have a code mailed instead. An admin can
19
+ * reset a person's second step (POST /admin/users/:id/two-factor/reset).
20
+ *
21
+ * The second step never asks again for what the first step already proved:
22
+ * signing in with an emailed code does not then mail another one. When
23
+ * nothing else is set up, the sign-in code counts.
24
+ *
25
+ * "Trust this device" (AUTH_2FA_TRUST_DAYS, 0 = never offered): the device
26
+ * keeps a random token; Redis keeps its hash, the user and when their second
27
+ * step last changed. An admin reset, or any change of method, makes every
28
+ * trusted device ask again.
29
+ */
30
+ var crypto = require('crypto');
31
+ var utils = require('@xeplr/utils');
32
+ var { encrypt, decrypt } = require('@xeplr/utils/isomorphic/crypto');
33
+ var { normalizeEmail } = require('@xeplr/utils/isomorphic');
34
+ var User = require('../models/User');
35
+ var { createSession } = require('./sessionService');
36
+ var { getUserAccess, clearUserAccess } = require('./accessService');
37
+ var hooks = require('./hooks');
38
+ var { refusal } = require('./userRoles');
39
+
40
+ var otp = utils.otp;
41
+ var totp = utils.totp;
42
+ var cache = utils.cache;
43
+
44
+ var LOGIN_METHODS = ['password', 'email_otp', 'phone_otp'];
45
+ var MODES = ['off', 'optional', 'required'];
46
+ var SECOND_METHODS = ['authenticator', 'email', 'sms'];
47
+
48
+ var TICKET_SECONDS = 600; // first step → second step
49
+ var SETUP_SECONDS = 900; // authenticator scanned → first code typed
50
+ var MAX_TICKET_TRIES = 5; // wrong authenticator codes on one ticket
51
+ var CODES_PER_WINDOW = 5; // codes sent to one person …
52
+ var CODE_WINDOW_SECONDS = 900; // … per 15 minutes
53
+ var APP_FAILS_PER_WINDOW = 10; // wrong authenticator codes for one person, across sign-ins, per 15 minutes
54
+
55
+ // ── settings ─────────────────────────────────────────────────────────────
56
+
57
+ function list(raw, fallback) {
58
+ if (raw === undefined || raw === null || String(raw).trim() === '') return fallback.slice();
59
+ return String(raw).split(',').map(function(s) { return s.trim().toLowerCase(); }).filter(Boolean);
60
+ }
61
+
62
+ function invalid(name, value, allowed) {
63
+ return refusal('AUTH_SETTING_INVALID', name + ' has "' + value + '"; allowed: ' + allowed.join(', '));
64
+ }
65
+
66
+ /**
67
+ * The sign-in settings, read at call time. Throws on a value it does not know,
68
+ * naming the variable — a typo must not quietly turn the second step off.
69
+ */
70
+ function settings() {
71
+ var login = list(process.env.AUTH_LOGIN_METHODS, ['password']);
72
+ login.forEach(function(m) { if (LOGIN_METHODS.indexOf(m) === -1) throw invalid('AUTH_LOGIN_METHODS', m, LOGIN_METHODS); });
73
+ if (!login.length) throw refusal('AUTH_SETTING_INVALID', 'AUTH_LOGIN_METHODS names no way to sign in');
74
+
75
+ var mode = String(process.env.AUTH_2FA || 'off').trim().toLowerCase();
76
+ if (MODES.indexOf(mode) === -1) throw invalid('AUTH_2FA', mode, MODES);
77
+
78
+ var methods = list(process.env.AUTH_2FA_METHODS, ['authenticator', 'email']);
79
+ methods.forEach(function(m) { if (SECOND_METHODS.indexOf(m) === -1) throw invalid('AUTH_2FA_METHODS', m, SECOND_METHODS); });
80
+ if (methods.indexOf('email') === -1) methods.push('email'); // always the way back in
81
+
82
+ var rawDays = process.env.AUTH_2FA_TRUST_DAYS;
83
+ var trustDays = rawDays === undefined || String(rawDays).trim() === '' ? 0 : Number(rawDays);
84
+ if (!(trustDays >= 0) || Math.floor(trustDays) !== trustDays) {
85
+ throw refusal('AUTH_SETTING_INVALID', 'AUTH_2FA_TRUST_DAYS must be a whole number of days (0 = never trust a device), not "' + rawDays + '"');
86
+ }
87
+
88
+ return { login: login, mode: mode, methods: methods, trustDays: trustDays };
89
+ }
90
+
91
+ /** Whether these settings send text messages — and so need an SMS provider. */
92
+ function needsSms(s) {
93
+ return s.login.indexOf('phone_otp') !== -1 || (s.mode !== 'off' && s.methods.indexOf('sms') !== -1);
94
+ }
95
+
96
+ /**
97
+ * At start: the settings parse, and what they need exists. An SMS provider is
98
+ * registered by the host (@xeplr/utils sms.register) before boot(); without
99
+ * one, a code by text cannot go out, so the server refuses to start rather
100
+ * than have the first person to try it find out.
101
+ */
102
+ function checkSettings() {
103
+ var s = settings();
104
+ if (needsSms(s) && !utils.sms.getProviders().length) {
105
+ throw refusal('SMS_NOT_SET_UP', 'Signing in by text message is turned on (' +
106
+ (s.login.indexOf('phone_otp') !== -1 ? 'AUTH_LOGIN_METHODS has phone_otp' : 'AUTH_2FA_METHODS has sms') +
107
+ ') but no SMS provider is registered. Register one with @xeplr/utils sms.register() before boot(), or remove it.');
108
+ }
109
+ return s;
110
+ }
111
+
112
+ /** What the sign-in page needs to know — public, nothing about any account. */
113
+ function signInOptions() {
114
+ var s = settings();
115
+ return { methods: s.login, twoFactor: s.mode, twoFactorMethods: s.methods, trustDays: s.trustDays };
116
+ }
117
+
118
+ function requireLoginMethod(s, method, words) {
119
+ if (s.login.indexOf(method) === -1) throw refusal('METHOD_OFF', words + ' is turned off on this server');
120
+ }
121
+
122
+ // ── phone numbers ────────────────────────────────────────────────────────
123
+
124
+ /** "+91 98765-43210" → "+919876543210": a leading + and the digits. */
125
+ function cleanPhone(typed) {
126
+ var t = String(typed || '').trim();
127
+ var digits = t.replace(/\D/g, '');
128
+ if (!digits) return '';
129
+ return (t.charAt(0) === '+' ? '+' : '') + digits;
130
+ }
131
+
132
+ var PHONE_SQL = 'regexp_replace("phoneNumber", \'[^0-9+]\', \'\', \'g\')';
133
+ var DIGITS_SQL = 'regexp_replace("phoneNumber", \'[^0-9]\', \'\', \'g\')';
134
+
135
+ function verifiedPhones() {
136
+ return User.query().where('phoneVerified', true).whereNotNull('phoneNumber');
137
+ }
138
+
139
+ /**
140
+ * The one account whose VERIFIED number this is. Typed with its country code,
141
+ * it must match exactly; typed without (9876543210), it matches a number that
142
+ * ends with those digits — and only when exactly one account does.
143
+ */
144
+ async function findByVerifiedPhone(typed) {
145
+ var p = cleanPhone(typed);
146
+ if (!p) return null;
147
+ var exact = await verifiedPhones().whereRaw(PHONE_SQL + ' = ?', [p]).withGraphFetched('roles');
148
+ if (exact.length === 1) return exact[0];
149
+ if (exact.length > 1 || p.charAt(0) === '+' || p.length < 10) return null;
150
+ var ending = await verifiedPhones().whereRaw(DIGITS_SQL + ' LIKE ?', ['%' + p]).withGraphFetched('roles');
151
+ return ending.length === 1 ? ending[0] : null;
152
+ }
153
+
154
+ /** Another account already holds this number, verified. */
155
+ async function phoneTakenByOther(userId, number) {
156
+ var p = cleanPhone(number);
157
+ if (!p) return false;
158
+ var others = await verifiedPhones().whereRaw(PHONE_SQL + ' = ?', [p]).whereNot('id', userId).select('id');
159
+ return others.length > 0;
160
+ }
161
+
162
+ // ── showing where a code went, without saying all of it ─────────────────
163
+
164
+ function maskEmail(email) {
165
+ var parts = String(email || '').split('@');
166
+ if (parts.length !== 2) return '';
167
+ return parts[0].charAt(0) + '•••@' + parts[1];
168
+ }
169
+
170
+ function maskPhone(phone) {
171
+ var d = String(phone || '').replace(/\D/g, '');
172
+ return d ? '•••' + d.slice(-4) : '';
173
+ }
174
+
175
+ function sentTo(user, method) {
176
+ if (method === 'email') return maskEmail(user.email);
177
+ if (method === 'sms') return maskPhone(user.phoneNumber);
178
+ return '';
179
+ }
180
+
181
+ // ── sending a code ───────────────────────────────────────────────────────
182
+
183
+ var _sendLimiter = null;
184
+ function sendLimiter() {
185
+ if (!_sendLimiter) _sendLimiter = new utils.RateLimiter({ windowInSeconds: CODE_WINDOW_SECONDS, max: CODES_PER_WINDOW, store: 'redis' });
186
+ return _sendLimiter;
187
+ }
188
+
189
+ /** Five codes per person per 15 minutes, whichever way they go. */
190
+ async function countSend(userId) {
191
+ var key = 'auth-codes:' + userId;
192
+ var wait = await sendLimiter().lockedFor(key);
193
+ if (wait > 0) {
194
+ throw refusal('TOO_MANY_CODES', 'Too many codes asked for. Try again in ' + Math.ceil(wait / 60) + ' minute' + (wait > 60 ? 's' : '') + '.');
195
+ }
196
+ await sendLimiter().fail(key);
197
+ }
198
+
199
+ // Wrong authenticator codes for one PERSON, across every sign-in: someone who
200
+ // has the password can start as many sign-ins as they like, each with its own
201
+ // five tries — this is what bounds the guessing.
202
+ var _appFails = null;
203
+ function appFails() {
204
+ if (!_appFails) _appFails = new utils.RateLimiter({ windowInSeconds: CODE_WINDOW_SECONDS, max: APP_FAILS_PER_WINDOW, store: 'redis' });
205
+ return _appFails;
206
+ }
207
+
208
+ function lockedOut(wait) {
209
+ return refusal('TOO_MANY_TRIES', 'Too many wrong codes. Try again in ' + Math.ceil(wait / 60) + ' minute' + (wait > 60 ? 's' : '') + ', or ask for a code by email.');
210
+ }
211
+
212
+ function codeEmail(code, why) {
213
+ return '<h2>' + why + '</h2>'
214
+ + '<p>Your code is:</p>'
215
+ + '<p style="font-size:28px;letter-spacing:6px;font-weight:bold">' + code + '</p>'
216
+ + '<p>It works once, for 5 minutes. If you did not try to sign in, ignore this email — and consider changing your password.</p>';
217
+ }
218
+
219
+ /** One code under `key`, to the person's email or verified phone. */
220
+ async function sendCode(key, method, user) {
221
+ if (method === 'email') {
222
+ return otp.requestOtp(key, {
223
+ send: async function(code) {
224
+ try {
225
+ await utils.sendEmail(user.email, 'Your sign-in code: ' + code, codeEmail(code, 'Your sign-in code'));
226
+ } catch (err) {
227
+ var e = refusal('EMAIL_SEND_FAILED', 'Could not send the code by email: ' + err.message);
228
+ e.cause = err;
229
+ throw e;
230
+ }
231
+ }
232
+ });
233
+ }
234
+ if (method === 'sms') return otp.requestOtp(key, { to: cleanPhone(user.phoneNumber) });
235
+ throw refusal('BAD_METHOD', 'Codes are sent by email or text message, not "' + method + '"');
236
+ }
237
+
238
+ function codeRefusal(reason) {
239
+ if (reason === 'too_many_attempts') return refusal('TOO_MANY_TRIES', 'Too many wrong codes. Ask for a new one.');
240
+ if (reason === 'expired') return refusal('CODE_EXPIRED', 'That code has expired or was already used. Ask for a new one.');
241
+ return refusal('BAD_CODE', 'That code is not right.');
242
+ }
243
+
244
+ // ── the session at the end of every way in ───────────────────────────────
245
+
246
+ async function issueSession(user) {
247
+ var full = user.roles ? user : await User.query().findById(user.id).withGraphFetched('roles');
248
+ var tokenUser = {
249
+ id: full.id,
250
+ email: full.email,
251
+ name: full.name,
252
+ roles: (full.roles || []).map(function(r) { return r.name; })
253
+ };
254
+ var pair = await createSession(tokenUser);
255
+ await clearUserAccess(full.id);
256
+ var access = await getUserAccess(full.id);
257
+ await hooks.fire('user', 'login', full.id);
258
+ return {
259
+ accessToken: pair.accessToken,
260
+ refreshToken: pair.refreshToken,
261
+ user: { id: full.id, email: full.email, name: full.name, isActivated: full.isActivated },
262
+ access: access
263
+ };
264
+ }
265
+
266
+ function canSignIn(user) {
267
+ return Boolean(user && user.isActive && user.isActivated);
268
+ }
269
+
270
+ // ── the second step ──────────────────────────────────────────────────────
271
+
272
+ /**
273
+ * Which second steps this person may use, after a first step that used
274
+ * `used` ('password', 'email', 'sms'); null when none is asked.
275
+ */
276
+ function secondStepFor(user, used, s) {
277
+ if (s.mode === 'off') return null;
278
+ if (s.mode === 'optional' && !user.twoFactorMethod) return null;
279
+ var have = [];
280
+ if (s.methods.indexOf('authenticator') !== -1 && user.totpSecret) have.push('authenticator');
281
+ if (s.methods.indexOf('sms') !== -1 && user.phoneVerified && user.phoneNumber) have.push('sms');
282
+ have.push('email');
283
+ have = have.filter(function(m) { return m !== used; });
284
+ if (!have.length) return null;
285
+ var method = have.indexOf(user.twoFactorMethod) !== -1 ? user.twoFactorMethod : have[0];
286
+ return { methods: have, method: method };
287
+ }
288
+
289
+ function stampOf(user) {
290
+ return user.twoFactorChangedOn ? new Date(user.twoFactorChangedOn).getTime() : 0;
291
+ }
292
+
293
+ function trustKey(token) {
294
+ return '2fa-trust:' + crypto.createHash('sha256').update(String(token)).digest('hex');
295
+ }
296
+
297
+ async function trusted(user, token, s) {
298
+ if (!token || !s.trustDays) return false;
299
+ var rec = await cache.get(trustKey(token));
300
+ return Boolean(rec && rec.userId === user.id && rec.stamp === stampOf(user));
301
+ }
302
+
303
+ async function trustThisDevice(user, s) {
304
+ var token = crypto.randomBytes(32).toString('hex');
305
+ await cache.set(trustKey(token), { userId: user.id, stamp: stampOf(user) }, s.trustDays * 86400);
306
+ return token;
307
+ }
308
+
309
+ function ticketKey(ticket) { return '2fa-ticket:' + ticket; }
310
+ function codeKeyFor(ticket) { return '2fa:' + ticket; }
311
+
312
+ /**
313
+ * After a first step that proved `used`: tokens, or — when a second step is
314
+ * asked and this device is not trusted — a ticket for it. Sends the code
315
+ * straight away when the second step is a code by email or text.
316
+ */
317
+ async function afterFirstStep(user, used, trustToken) {
318
+ var s = settings();
319
+ var step = secondStepFor(user, used, s);
320
+ if (!step || await trusted(user, trustToken, s)) return issueSession(user);
321
+
322
+ var ticket = crypto.randomBytes(24).toString('hex');
323
+ await cache.set(ticketKey(ticket), { userId: user.id, methods: step.methods, tries: 0 }, TICKET_SECONDS);
324
+ if (step.method !== 'authenticator') {
325
+ await countSend(user.id);
326
+ await sendCode(codeKeyFor(ticket), step.method, user);
327
+ }
328
+ return {
329
+ secondStep: {
330
+ ticket: ticket,
331
+ method: step.method,
332
+ methods: step.methods,
333
+ sentTo: sentTo(user, step.method),
334
+ trustDays: s.trustDays
335
+ }
336
+ };
337
+ }
338
+
339
+ async function readTicket(ticket) {
340
+ var t = ticket ? await cache.get(ticketKey(ticket)) : null;
341
+ if (!t) throw refusal('SIGN_IN_EXPIRED', 'This sign-in has expired. Start again.');
342
+ return t;
343
+ }
344
+
345
+ async function ticketUser(t) {
346
+ var user = await User.query().findById(t.userId).withGraphFetched('roles');
347
+ if (!canSignIn(user)) throw refusal('SIGN_IN_EXPIRED', 'This sign-in has expired. Start again.');
348
+ return user;
349
+ }
350
+
351
+ /** Send (or send again) the second-step code, by email or text. */
352
+ async function sendSecondStepCode({ ticket, method }) {
353
+ var t = await readTicket(ticket);
354
+ if (t.methods.indexOf(method) === -1 || method === 'authenticator') {
355
+ throw refusal('BAD_METHOD', 'A code cannot be sent that way for this sign-in');
356
+ }
357
+ var user = await ticketUser(t);
358
+ await countSend(user.id);
359
+ await sendCode(codeKeyFor(ticket), method, user);
360
+ return { sent: true, method: method, sentTo: sentTo(user, method) };
361
+ }
362
+
363
+ async function readSecret(user) {
364
+ return decrypt(user.totpSecret, process.env.ENCRYPTION_KEY);
365
+ }
366
+
367
+ /** An authenticator code is good once: the same six digits a second time are refused. */
368
+ async function usedBefore(userId, code) {
369
+ var key = 'totp-used:' + userId + ':' + String(code).replace(/\s/g, '');
370
+ if (await cache.get(key)) return true;
371
+ await cache.set(key, { at: Date.now() }, 120);
372
+ return false;
373
+ }
374
+
375
+ /** The second step's code → tokens (and, when asked for, a trusted-device token). */
376
+ async function verifySecondStep({ ticket, method, code, trustDevice }) {
377
+ var s = settings();
378
+ var t = await readTicket(ticket);
379
+ if (t.methods.indexOf(method) === -1) throw refusal('BAD_METHOD', 'That way is not offered for this sign-in');
380
+ var user = await ticketUser(t);
381
+
382
+ if (method === 'authenticator') {
383
+ var failKey = 'auth-app-fails:' + user.id;
384
+ var wait = await appFails().lockedFor(failKey);
385
+ if (wait > 0) throw lockedOut(wait);
386
+ var ok = totp.verify(await readSecret(user), code);
387
+ if (!ok || await usedBefore(user.id, code)) {
388
+ var counted = await appFails().fail(failKey);
389
+ if (counted.lockedFor > 0) {
390
+ await cache.del(ticketKey(ticket));
391
+ throw lockedOut(counted.lockedFor);
392
+ }
393
+ t.tries = (t.tries || 0) + 1;
394
+ if (t.tries >= MAX_TICKET_TRIES) {
395
+ await cache.del(ticketKey(ticket));
396
+ throw refusal('TOO_MANY_TRIES', 'Too many wrong codes. Sign in again.');
397
+ }
398
+ await cache.set(ticketKey(ticket), t, TICKET_SECONDS);
399
+ throw refusal('BAD_CODE', 'That code is not right. Use the one your authenticator app shows now.');
400
+ }
401
+ await appFails().reset(failKey);
402
+ } else {
403
+ var r = await otp.verifyOtp(codeKeyFor(ticket), code);
404
+ if (!r.success) throw codeRefusal(r.reason);
405
+ }
406
+
407
+ await cache.del(ticketKey(ticket));
408
+ await otp.cancelOtp(codeKeyFor(ticket));
409
+ var session = await issueSession(user);
410
+ if (trustDevice && s.trustDays) session.trustToken = await trustThisDevice(user, s);
411
+ return session;
412
+ }
413
+
414
+ // ── signing in with a code instead of a password ─────────────────────────
415
+
416
+ async function accountFor({ email, phoneNumber }, s) {
417
+ if (email) {
418
+ requireLoginMethod(s, 'email_otp', 'Signing in with an emailed code');
419
+ return User.query().findOne({ normalizedEmail: normalizeEmail(email) }).withGraphFetched('roles');
420
+ }
421
+ if (phoneNumber) {
422
+ requireLoginMethod(s, 'phone_otp', 'Signing in with your mobile number');
423
+ return findByVerifiedPhone(phoneNumber);
424
+ }
425
+ throw refusal('BAD_REQUEST', 'Email or mobile number is required');
426
+ }
427
+
428
+ /**
429
+ * Send a sign-in code. The SAME answer whether or not an account matched —
430
+ * it must not tell anyone which addresses or numbers have accounts.
431
+ */
432
+ async function requestSignInCode({ email, phoneNumber }) {
433
+ var s = settings();
434
+ var user = await accountFor({ email: email, phoneNumber: phoneNumber }, s);
435
+ if (!canSignIn(user)) return { sent: true };
436
+ await countSend(user.id);
437
+ await sendCode('signin:' + user.id, email ? 'email' : 'sms', user);
438
+ return { sent: true };
439
+ }
440
+
441
+ async function verifySignInCode({ email, phoneNumber, code, trustToken }) {
442
+ var s = settings();
443
+ var user = await accountFor({ email: email, phoneNumber: phoneNumber }, s);
444
+ if (!canSignIn(user)) throw codeRefusal('invalid');
445
+ var r = await otp.verifyOtp('signin:' + user.id, code);
446
+ if (!r.success) throw codeRefusal(r.reason);
447
+ return afterFirstStep(user, email ? 'email' : 'sms', trustToken);
448
+ }
449
+
450
+ // ── my own second step (signed in) ───────────────────────────────────────
451
+
452
+ async function mine(userId) {
453
+ var user = await User.query().findById(userId);
454
+ if (!user) throw refusal('USER_NOT_FOUND', 'User not found');
455
+ return user;
456
+ }
457
+
458
+ function statusOf(user, s) {
459
+ return {
460
+ mode: s.mode,
461
+ methods: s.methods,
462
+ method: user.twoFactorMethod || null,
463
+ authenticator: Boolean(user.totpSecret),
464
+ phoneNumber: user.phoneNumber || null,
465
+ phoneVerified: Boolean(user.phoneVerified),
466
+ trustDays: s.trustDays,
467
+ signIn: s.login
468
+ };
469
+ }
470
+
471
+ async function twoFactorStatus(userId) {
472
+ return statusOf(await mine(userId), settings());
473
+ }
474
+
475
+ /** A new authenticator secret, held for 15 minutes until a code from the app confirms it. */
476
+ async function startAuthenticator(userId, issuer) {
477
+ var s = settings();
478
+ if (s.methods.indexOf('authenticator') === -1) throw refusal('METHOD_OFF', 'Authenticator apps are turned off on this server');
479
+ var user = await mine(userId);
480
+ var secret = totp.newSecret();
481
+ await cache.set('totp-setup:' + userId, { secret: secret }, SETUP_SECONDS);
482
+ var name = String(issuer || '').trim().slice(0, 60) || 'Xeplr';
483
+ return { secret: secret, otpauthUrl: totp.otpauthUrl(secret, user.email, name) };
484
+ }
485
+
486
+ async function changed(userId, patch) {
487
+ var now = utils.formatDbDateTime();
488
+ await User.query().findById(userId).patch(Object.assign({ twoFactorChangedOn: now, recordModifiedDate: now }, patch));
489
+ await hooks.fire('user', 'update', userId);
490
+ }
491
+
492
+ async function confirmAuthenticator(userId, code) {
493
+ var held = await cache.get('totp-setup:' + userId);
494
+ if (!held) throw refusal('SETUP_EXPIRED', 'Setting up took too long. Start again.');
495
+ if (!totp.verify(held.secret, code)) {
496
+ throw refusal('BAD_CODE', 'That code is not right. Check the app shows this account, and that the phone sets its time automatically.');
497
+ }
498
+ var stored = await encrypt(held.secret, process.env.ENCRYPTION_KEY);
499
+ await changed(userId, { totpSecret: stored, twoFactorMethod: 'authenticator' });
500
+ await cache.del('totp-setup:' + userId);
501
+ return twoFactorStatus(userId);
502
+ }
503
+
504
+ /** Choose the second step ('authenticator', 'email', 'sms'), or turn it off (null). */
505
+ async function chooseMethod(userId, method) {
506
+ var s = settings();
507
+ var user = await mine(userId);
508
+ if (!method || method === 'off') {
509
+ if (s.mode === 'required') throw refusal('REQUIRED', 'The second step is required on this server; choose how, it cannot be turned off');
510
+ await changed(userId, { twoFactorMethod: null });
511
+ return twoFactorStatus(userId);
512
+ }
513
+ if (s.methods.indexOf(method) === -1) throw refusal('METHOD_OFF', '"' + method + '" is not offered on this server');
514
+ if (method === 'authenticator' && !user.totpSecret) throw refusal('NOT_SET_UP', 'Set up the authenticator app first');
515
+ if (method === 'sms' && !(user.phoneVerified && user.phoneNumber)) throw refusal('NOT_SET_UP', 'Verify your mobile number first');
516
+ await changed(userId, { twoFactorMethod: method });
517
+ return twoFactorStatus(userId);
518
+ }
519
+
520
+ /** An admin clears someone's second step: no method, no authenticator; trusted devices ask again. */
521
+ async function resetTwoFactor(userId, adminId) {
522
+ await mine(userId);
523
+ await changed(userId, { twoFactorMethod: null, totpSecret: null, recordModifiedBy: adminId || null });
524
+ return { reset: true };
525
+ }
526
+
527
+ module.exports = {
528
+ settings: settings,
529
+ checkSettings: checkSettings,
530
+ signInOptions: signInOptions,
531
+ requireLoginMethod: requireLoginMethod,
532
+ cleanPhone: cleanPhone,
533
+ findByVerifiedPhone: findByVerifiedPhone,
534
+ phoneTakenByOther: phoneTakenByOther,
535
+ issueSession: issueSession,
536
+ afterFirstStep: afterFirstStep,
537
+ sendSecondStepCode: sendSecondStepCode,
538
+ verifySecondStep: verifySecondStep,
539
+ requestSignInCode: requestSignInCode,
540
+ verifySignInCode: verifySignInCode,
541
+ twoFactorStatus: twoFactorStatus,
542
+ startAuthenticator: startAuthenticator,
543
+ confirmAuthenticator: confirmAuthenticator,
544
+ chooseMethod: chooseMethod,
545
+ resetTwoFactor: resetTwoFactor
546
+ };
@@ -0,0 +1,115 @@
1
+ -- 0015_otp_two_factor.sql
2
+ -- Signing in with a code (email or mobile) and the second step (2FA).
3
+ --
4
+ -- users:
5
+ -- twoFactorMethod what this person's second step uses: 'authenticator',
6
+ -- 'email' or 'sms'; NULL = not turned on (AUTH_2FA=optional)
7
+ -- totpSecret the authenticator app's secret, encrypted with
8
+ -- ENCRYPTION_KEY (never stored in clear)
9
+ -- twoFactorChangedOn when the above last changed. A trusted device
10
+ -- remembers this value; a change (or an admin reset)
11
+ -- makes every earlier "trust this device" ask again.
12
+
13
+ ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "twoFactorMethod" varchar(20);
14
+ ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "totpSecret" varchar(500);
15
+ ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "twoFactorChangedOn" timestamp;
16
+
17
+ -- ONE PERSON PER VERIFIED NUMBER: signing in by mobile finds the account by
18
+ -- its number, so two accounts holding the same verified number would make it
19
+ -- a guess. The code refuses a second one at verification; this index holds it
20
+ -- in the database too. An install that already has duplicates is not stopped
21
+ -- from starting — it is told, and the code's check still applies.
22
+ DO $$
23
+ BEGIN
24
+ IF EXISTS (
25
+ SELECT 1 FROM "users"
26
+ WHERE "phoneVerified" = true AND "phoneNumber" IS NOT NULL
27
+ GROUP BY regexp_replace("phoneNumber", '[^0-9+]', '', 'g')
28
+ HAVING count(*) > 1
29
+ ) THEN
30
+ RAISE NOTICE 'users: some verified phone numbers belong to more than one account; unique index not created. Unverify the duplicates, then create users_verified_phone_unique.';
31
+ ELSE
32
+ CREATE UNIQUE INDEX IF NOT EXISTS "users_verified_phone_unique"
33
+ ON "users" (regexp_replace("phoneNumber", '[^0-9+]', '', 'g'))
34
+ WHERE "phoneVerified" = true AND "phoneNumber" IS NOT NULL;
35
+ END IF;
36
+ END $$;
37
+
38
+ -- ROUTES.
39
+ --
40
+ -- public (how a caller gets a token, so no group):
41
+ -- GET /auth/api/sign-in-options which ways in this server offers
42
+ -- POST /auth/api/login/code send a sign-in code (email or mobile)
43
+ -- POST /auth/api/login/code/verify sign in with it
44
+ -- POST /auth/api/login/second-step/send send the second-step code (email/SMS)
45
+ -- POST /auth/api/login/second-step/verify finish signing in
46
+ -- account:* (my own second step):
47
+ -- GET /auth/api/two-factor account:view
48
+ -- POST /auth/api/two-factor/authenticator account:edit start setting up the app
49
+ -- POST /auth/api/two-factor/authenticator/confirm account:edit
50
+ -- POST /auth/api/two-factor/method account:edit choose / turn off
51
+ -- users:edit:
52
+ -- POST /auth/api/admin/users/:id/two-factor/reset
53
+
54
+ INSERT INTO "apis" (id, name, "apiGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
55
+ SELECT encode(gen_random_bytes(12), 'hex'), v.name, v.grp, v.pub, true, '*', now(), now()
56
+ FROM (VALUES
57
+ ('GET /auth/api/sign-in-options', '', true),
58
+ ('POST /auth/api/login/code', '', true),
59
+ ('POST /auth/api/login/code/verify', '', true),
60
+ ('POST /auth/api/login/second-step/send', '', true),
61
+ ('POST /auth/api/login/second-step/verify', '', true),
62
+ ('GET /auth/api/two-factor', 'account:view', false),
63
+ ('POST /auth/api/two-factor/authenticator', 'account:edit', false),
64
+ ('POST /auth/api/two-factor/authenticator/confirm', 'account:edit', false),
65
+ ('POST /auth/api/two-factor/method', 'account:edit', false),
66
+ ('POST /auth/api/admin/users/:id/two-factor/reset', 'users:edit', false)
67
+ ) AS v(name, grp, pub)
68
+ WHERE NOT EXISTS (SELECT 1 FROM "apis" a WHERE a.name = v.name AND a."apiGroup" = v.grp);
69
+
70
+ -- WHO GETS THEM: every role that can already reach the route beside it — any
71
+ -- role that opens its own profile gets its own second step; any role that can
72
+ -- activate a user by hand can reset one's second step. That covers auth's
73
+ -- default roles AND each app's own (BI's CompanyAdmin, Creator, Viewer;
74
+ -- Taskie's), whose account:* mappings their own migrations made long before
75
+ -- these routes existed and will not run again.
76
+
77
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
78
+ SELECT DISTINCT ON (m."roleId", a.id) encode(gen_random_bytes(12), 'hex'), m."roleId", a.id, true, '*', now(), now()
79
+ FROM "apisRolesMapping" m
80
+ JOIN "apis" have ON have.id = m."apiId" AND have.name = '/auth/api/profile' AND have."apiGroup" = 'account:view'
81
+ CROSS JOIN "apis" a
82
+ WHERE m."isActive" = true
83
+ AND a.name IN ('GET /auth/api/two-factor', 'POST /auth/api/two-factor/authenticator',
84
+ 'POST /auth/api/two-factor/authenticator/confirm', 'POST /auth/api/two-factor/method')
85
+ AND a."apiGroup" IN ('account:view', 'account:edit')
86
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" x WHERE x."roleId" = m."roleId" AND x."apiId" = a.id);
87
+
88
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
89
+ SELECT DISTINCT ON (m."roleId", a.id) encode(gen_random_bytes(12), 'hex'), m."roleId", a.id, true, '*', now(), now()
90
+ FROM "apisRolesMapping" m
91
+ JOIN "apis" have ON have.id = m."apiId" AND have.name = 'POST /auth/api/admin/users/:id/activate' AND have."apiGroup" = 'users:edit'
92
+ CROSS JOIN "apis" a
93
+ WHERE m."isActive" = true
94
+ AND a.name = 'POST /auth/api/admin/users/:id/two-factor/reset' AND a."apiGroup" = 'users:edit'
95
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" x WHERE x."roleId" = m."roleId" AND x."apiId" = a.id);
96
+
97
+ -- Super Admin and Admin by name as well, in case a fresh install's mapping of
98
+ -- the neighbour route is still to come.
99
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
100
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
101
+ FROM "roles" r CROSS JOIN "apis" a
102
+ WHERE r.name IN ('Super Admin', 'Admin')
103
+ AND a.name IN ('GET /auth/api/two-factor', 'POST /auth/api/two-factor/authenticator',
104
+ 'POST /auth/api/two-factor/authenticator/confirm', 'POST /auth/api/two-factor/method',
105
+ 'POST /auth/api/admin/users/:id/two-factor/reset')
106
+ AND a."apiGroup" <> ''
107
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
108
+
109
+ INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
110
+ SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
111
+ FROM "roles" r CROSS JOIN "apis" a
112
+ WHERE r.name IN ('Editor', 'Viewer')
113
+ AND a.name IN ('GET /auth/api/two-factor', 'POST /auth/api/two-factor/authenticator',
114
+ 'POST /auth/api/two-factor/authenticator/confirm', 'POST /auth/api/two-factor/method')
115
+ AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
package/models/User.js CHANGED
@@ -39,7 +39,10 @@ class User extends BaseModel {
39
39
  resetToken: { type: ['string', 'null'], maxLength: 255 },
40
40
  resetTokenExpiry: { type: ['string', 'null'] },
41
41
  activationToken: { type: ['string', 'null'], maxLength: 255 },
42
- normalizedEmail: { type: ['string', 'null'], maxLength: 255 }
42
+ normalizedEmail: { type: ['string', 'null'], maxLength: 255 },
43
+ twoFactorMethod: { type: ['string', 'null'], maxLength: 20 },
44
+ totpSecret: { type: ['string', 'null'], maxLength: 500 },
45
+ twoFactorChangedOn: { type: ['string', 'null'] }
43
46
  }
44
47
  };
45
48
  }