@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.
- package/README.md +92 -6
- package/index.js +42 -3
- package/lib/adminRouter.js +18 -1
- package/lib/authMiddleware.js +11 -0
- package/lib/authRouter.js +142 -7
- package/lib/authService.js +31 -35
- package/lib/internalToken.js +66 -0
- package/lib/signInSteps.js +546 -0
- package/migrations/0015_otp_two_factor.sql +115 -0
- package/models/User.js +4 -1
- package/package.json +5 -5
package/lib/authService.js
CHANGED
|
@@ -3,10 +3,11 @@ const { sendEmail, configureEmail, formatDbDateTime, otp } = require('@xeplr/uti
|
|
|
3
3
|
const { normalizeEmail } = require('@xeplr/utils/isomorphic');
|
|
4
4
|
const { generateId, hashPassword, comparePassword } = require('./authHelper');
|
|
5
5
|
const User = require('../models/User');
|
|
6
|
-
const {
|
|
7
|
-
const {
|
|
6
|
+
const { clearUserAccess } = require('./accessService');
|
|
7
|
+
const { destroyAllUserSessions } = require('./sessionService');
|
|
8
8
|
const hooks = require('./hooks');
|
|
9
9
|
const { grantRoles, registerRoleIds, refusal } = require('./userRoles');
|
|
10
|
+
const signInSteps = require('./signInSteps');
|
|
10
11
|
|
|
11
12
|
// WHERE THE LINKS IN OUR EMAILS POINT.
|
|
12
13
|
//
|
|
@@ -318,7 +319,14 @@ async function adminActivate(userId, adminId) {
|
|
|
318
319
|
return { id: user.id, email: user.email, name: user.name, isActivated: true };
|
|
319
320
|
}
|
|
320
321
|
|
|
321
|
-
|
|
322
|
+
/**
|
|
323
|
+
* Email and password. When a second step is asked (AUTH_2FA) and this device
|
|
324
|
+
* is not trusted, the answer is { secondStep: { ticket, method, methods,
|
|
325
|
+
* sentTo, trustDays } } instead of tokens — see lib/signInSteps.js.
|
|
326
|
+
*/
|
|
327
|
+
async function login({ email, password, trustToken }) {
|
|
328
|
+
signInSteps.requireLoginMethod(signInSteps.settings(), 'password', 'Signing in with a password');
|
|
329
|
+
|
|
322
330
|
const normalized = normalizeEmail(email);
|
|
323
331
|
const user = await User.query()
|
|
324
332
|
.findOne({ normalizedEmail: normalized })
|
|
@@ -345,33 +353,9 @@ async function login({ email, password }) {
|
|
|
345
353
|
throw new Error('NOT_ACTIVATED');
|
|
346
354
|
}
|
|
347
355
|
|
|
348
|
-
//
|
|
349
|
-
//
|
|
350
|
-
|
|
351
|
-
id: user.id,
|
|
352
|
-
email: user.email,
|
|
353
|
-
name: user.name,
|
|
354
|
-
roles: (user.roles || []).map(function(r) { return r.name; })
|
|
355
|
-
};
|
|
356
|
-
|
|
357
|
-
const { accessToken, refreshToken } = await createSession(tokenUser);
|
|
358
|
-
|
|
359
|
-
await clearUserAccess(user.id);
|
|
360
|
-
const access = await getUserAccess(user.id);
|
|
361
|
-
|
|
362
|
-
await hooks.fire('user', 'login', user.id);
|
|
363
|
-
|
|
364
|
-
return {
|
|
365
|
-
accessToken,
|
|
366
|
-
refreshToken,
|
|
367
|
-
user: {
|
|
368
|
-
id: user.id,
|
|
369
|
-
email: user.email,
|
|
370
|
-
name: user.name,
|
|
371
|
-
isActivated: user.isActivated
|
|
372
|
-
},
|
|
373
|
-
access
|
|
374
|
-
};
|
|
356
|
+
// Role names ride in the JWT so middleware (e.g. requireSuperAdmin) can gate
|
|
357
|
+
// without a per-request DB lookup — signInSteps.issueSession packs them.
|
|
358
|
+
return signInSteps.afterFirstStep(user, 'password', trustToken);
|
|
375
359
|
}
|
|
376
360
|
|
|
377
361
|
/**
|
|
@@ -631,10 +615,13 @@ async function requestPhoneOtp(userId, phoneNumber) {
|
|
|
631
615
|
const user = await User.query().findById(userId);
|
|
632
616
|
if (!user) throw new Error('User not found');
|
|
633
617
|
|
|
634
|
-
const targetPhone = phoneNumber || user.phoneNumber;
|
|
618
|
+
const targetPhone = signInSteps.cleanPhone(phoneNumber || user.phoneNumber);
|
|
635
619
|
if (!targetPhone) throw new Error('phoneNumber is required');
|
|
620
|
+
if (await signInSteps.phoneTakenByOther(userId, targetPhone)) {
|
|
621
|
+
throw refusal('PHONE_TAKEN', 'This number is already verified on another account');
|
|
622
|
+
}
|
|
636
623
|
|
|
637
|
-
if (
|
|
624
|
+
if (targetPhone !== signInSteps.cleanPhone(user.phoneNumber)) {
|
|
638
625
|
// Changing the number on file invalidates any prior verification.
|
|
639
626
|
await User.query().findById(userId).patch({
|
|
640
627
|
phoneNumber: targetPhone,
|
|
@@ -656,6 +643,12 @@ async function verifyPhoneOtp(userId, code) {
|
|
|
656
643
|
if (!user) throw new Error('User not found');
|
|
657
644
|
if (!user.phoneNumber) throw new Error('No phone number on file — request a code first');
|
|
658
645
|
|
|
646
|
+
// One person per verified number — signing in by mobile finds the account
|
|
647
|
+
// by it. Checked again here: someone else may have verified it meanwhile.
|
|
648
|
+
if (await signInSteps.phoneTakenByOther(userId, user.phoneNumber)) {
|
|
649
|
+
throw refusal('PHONE_TAKEN', 'This number is already verified on another account');
|
|
650
|
+
}
|
|
651
|
+
|
|
659
652
|
const result = await otp.verifyOtp(user.phoneNumber, code);
|
|
660
653
|
if (!result.success) {
|
|
661
654
|
const messages = {
|
|
@@ -712,9 +705,12 @@ async function updateProfile(userId, fields) {
|
|
|
712
705
|
data.name = fields.name;
|
|
713
706
|
}
|
|
714
707
|
|
|
715
|
-
if (fields.phoneNumber !== undefined
|
|
716
|
-
|
|
717
|
-
|
|
708
|
+
if (fields.phoneNumber !== undefined) {
|
|
709
|
+
const cleaned = signInSteps.cleanPhone(fields.phoneNumber) || null;
|
|
710
|
+
if (cleaned !== (signInSteps.cleanPhone(user.phoneNumber) || null)) {
|
|
711
|
+
data.phoneNumber = cleaned;
|
|
712
|
+
data.phoneVerified = false;
|
|
713
|
+
}
|
|
718
714
|
}
|
|
719
715
|
|
|
720
716
|
if (fields.email !== undefined) {
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* internalToken — a token the SERVER makes for itself, to call its own API
|
|
3
|
+
* (or another xeplr service) as a user: a scheduled export, a print, a job
|
|
4
|
+
* step. A library function, never a route — nothing outside the server can
|
|
5
|
+
* make one.
|
|
6
|
+
*
|
|
7
|
+
* const token = await createInternalToken({ id, email, name, roles })
|
|
8
|
+
* fetch(api + '/reports/r1/export', { headers: { authorization: 'Bearer ' + token, … } })
|
|
9
|
+
*
|
|
10
|
+
* A random string (`xit_` + 32 random bytes) kept in Redis with the user it
|
|
11
|
+
* acts as, for 30 seconds unless asked otherwise. authMiddleware knows it by
|
|
12
|
+
* its prefix and serves the request as that user — so /verify, every app's
|
|
13
|
+
* gate, the company membership and the API access rules apply to it exactly
|
|
14
|
+
* as to a sign-in token: it opens nothing that user could not open.
|
|
15
|
+
*
|
|
16
|
+
* Long and random, not a short code: it works on the API, so it must not be
|
|
17
|
+
* guessable within its life. Not single-use: an export is started, waited on
|
|
18
|
+
* and fetched with one token, within its 30 seconds.
|
|
19
|
+
*
|
|
20
|
+
* Keys go through @xeplr/utils' cache, under REDIS_PREFIX — the same Redis
|
|
21
|
+
* and prefix the auth service reads, as for sessions.
|
|
22
|
+
*/
|
|
23
|
+
const crypto = require('crypto');
|
|
24
|
+
const { cache } = require('@xeplr/utils');
|
|
25
|
+
|
|
26
|
+
const KEY = 'token:internal:';
|
|
27
|
+
const PREFIX = 'xit_';
|
|
28
|
+
const DEFAULT_TTL = 30; // seconds
|
|
29
|
+
const MAX_TTL = 300;
|
|
30
|
+
|
|
31
|
+
/** Whether a bearer token is an internal one (by its prefix). */
|
|
32
|
+
function isInternalToken(token) {
|
|
33
|
+
return typeof token === 'string' && token.startsWith(PREFIX);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Make a token acting as `user` ({ id, email, name, roles: [names] } — the
|
|
38
|
+
* claims a sign-in carries). Throws if Redis is unreachable: an auth surface
|
|
39
|
+
* fails loud.
|
|
40
|
+
*
|
|
41
|
+
* @param {object} user
|
|
42
|
+
* @param {object} [opts] { ttl } seconds, 1–300 (default 30)
|
|
43
|
+
* @returns {Promise<string>}
|
|
44
|
+
*/
|
|
45
|
+
async function createInternalToken(user, opts) {
|
|
46
|
+
if (!user || !user.id) throw new Error('createInternalToken: user.id is required');
|
|
47
|
+
const ttl = Math.min(MAX_TTL, Math.max(1, Math.floor(Number((opts && opts.ttl) || DEFAULT_TTL))));
|
|
48
|
+
const token = PREFIX + crypto.randomBytes(32).toString('base64url');
|
|
49
|
+
const claims = {
|
|
50
|
+
id: user.id, email: user.email || null, name: user.name || null,
|
|
51
|
+
roles: Array.isArray(user.roles) ? user.roles.map(function(r) { return typeof r === 'string' ? r : r && r.name; }).filter(Boolean) : [],
|
|
52
|
+
internal: true
|
|
53
|
+
};
|
|
54
|
+
await cache.getClient().set(KEY + token, JSON.stringify(claims), 'EX', ttl);
|
|
55
|
+
return token;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The user an internal token acts as, or null (unknown, or its time is up). */
|
|
59
|
+
async function readInternalToken(token) {
|
|
60
|
+
if (!isInternalToken(token)) return null;
|
|
61
|
+
const raw = await cache.getClient().get(KEY + token);
|
|
62
|
+
if (!raw) return null;
|
|
63
|
+
try { return JSON.parse(raw); } catch (_) { return null; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = { createInternalToken, readInternalToken, isInternalToken, DEFAULT_TTL };
|