powr-sdk-api 4.19.2 → 4.21.1
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/dist/middleware/jwtToken.js +21 -0
- package/dist/middleware/projectId.js +1 -1
- package/dist/routes/auth.js +226 -46
- package/dist/routes/auth.otp.test.js +206 -0
- package/dist/routes/index.js +6 -0
- package/dist/services/otp.js +102 -0
- package/dist/services/otp.test.js +88 -0
- package/package.json +1 -1
|
@@ -4,6 +4,13 @@ const jwt = require('jsonwebtoken');
|
|
|
4
4
|
const {
|
|
5
5
|
config
|
|
6
6
|
} = require('../config');
|
|
7
|
+
function tenDigitMobile(raw) {
|
|
8
|
+
const digits = String(raw || "").replace(/\D/g, "");
|
|
9
|
+
if (digits.length === 10) return digits;
|
|
10
|
+
if (digits.length === 12 && digits.startsWith("91")) return digits.slice(2);
|
|
11
|
+
if (digits.length > 10) return digits.slice(-10);
|
|
12
|
+
return digits;
|
|
13
|
+
}
|
|
7
14
|
const generateJWTToken = (user, profile = null, extra = null) => {
|
|
8
15
|
const payload = {
|
|
9
16
|
userId: user._id,
|
|
@@ -11,6 +18,8 @@ const generateJWTToken = (user, profile = null, extra = null) => {
|
|
|
11
18
|
access: profile === null || profile === void 0 ? void 0 : profile.access
|
|
12
19
|
};
|
|
13
20
|
if (user && user.phoneNumber) payload.phoneNumber = String(user.phoneNumber);
|
|
21
|
+
const mobile = tenDigitMobile(user && user.phoneNumber);
|
|
22
|
+
if (mobile.length === 10) payload.mobile = mobile;
|
|
14
23
|
if (extra && extra.impersonatedBy) {
|
|
15
24
|
payload.impersonatedBy = String(extra.impersonatedBy);
|
|
16
25
|
}
|
|
@@ -18,6 +27,16 @@ const generateJWTToken = (user, profile = null, extra = null) => {
|
|
|
18
27
|
expiresIn: '24h'
|
|
19
28
|
});
|
|
20
29
|
};
|
|
30
|
+
const generatePhoneProofToken = mobile => {
|
|
31
|
+
const digits = tenDigitMobile(mobile);
|
|
32
|
+
const payload = {
|
|
33
|
+
mobile: digits
|
|
34
|
+
};
|
|
35
|
+
if (digits.length === 10) payload.phoneNumber = `+91${digits}`;
|
|
36
|
+
return jwt.sign(payload, config.jwtToken, {
|
|
37
|
+
expiresIn: "24h"
|
|
38
|
+
});
|
|
39
|
+
};
|
|
21
40
|
const generateRefreshToken = user => {
|
|
22
41
|
return jwt.sign({
|
|
23
42
|
userId: user._id,
|
|
@@ -58,6 +77,7 @@ const verifyToken = async (req, res, next) => {
|
|
|
58
77
|
powrId: decoded.userId,
|
|
59
78
|
fullName: decoded.fullName,
|
|
60
79
|
access: decoded.access,
|
|
80
|
+
phoneNumber: decoded.phoneNumber || decoded.phone_number || null,
|
|
61
81
|
impersonatedBy: decoded.impersonatedBy || null
|
|
62
82
|
};
|
|
63
83
|
return next();
|
|
@@ -71,6 +91,7 @@ const verifyToken = async (req, res, next) => {
|
|
|
71
91
|
};
|
|
72
92
|
module.exports = {
|
|
73
93
|
generateJWTToken,
|
|
94
|
+
generatePhoneProofToken,
|
|
74
95
|
generateRefreshToken,
|
|
75
96
|
verifyRefreshToken,
|
|
76
97
|
verifyToken
|
|
@@ -18,7 +18,7 @@ const injectProjectId = (options = {}) => {
|
|
|
18
18
|
try {
|
|
19
19
|
// Skip validation for excluded paths
|
|
20
20
|
if (req.path === "/scheduler/tick" || excludePaths.some(path => req.path.startsWith(path))) {
|
|
21
|
-
req.projectId = null;
|
|
21
|
+
req.projectId = req.query && req.query.projectId || req.body && req.body.projectId || null;
|
|
22
22
|
return next();
|
|
23
23
|
}
|
|
24
24
|
if (isCentralService) {
|
package/dist/routes/auth.js
CHANGED
|
@@ -11,6 +11,7 @@ const {
|
|
|
11
11
|
const bcrypt = require("bcrypt");
|
|
12
12
|
const {
|
|
13
13
|
generateJWTToken,
|
|
14
|
+
generatePhoneProofToken,
|
|
14
15
|
generateRefreshToken,
|
|
15
16
|
verifyRefreshToken,
|
|
16
17
|
verifyToken
|
|
@@ -32,6 +33,17 @@ const {
|
|
|
32
33
|
decideImpersonation
|
|
33
34
|
} = require("../utils/impersonate");
|
|
34
35
|
const jwt = require("jsonwebtoken");
|
|
36
|
+
const {
|
|
37
|
+
otpAppName,
|
|
38
|
+
tenDigitMobile,
|
|
39
|
+
isTestMobile,
|
|
40
|
+
generateOtpCode,
|
|
41
|
+
otpExpiryDate,
|
|
42
|
+
findTemplate,
|
|
43
|
+
saveOtp,
|
|
44
|
+
findLatestOtp,
|
|
45
|
+
getSendOtpSms
|
|
46
|
+
} = require("../services/otp");
|
|
35
47
|
const PASSWORD_RESET_TTL_MS = 24 * 60 * 60 * 1000;
|
|
36
48
|
async function issuePasswordResetLink(db, user, appUrl) {
|
|
37
49
|
const expiresAt = new Date(Date.now() + PASSWORD_RESET_TTL_MS);
|
|
@@ -50,7 +62,7 @@ async function issuePasswordResetLink(db, user, appUrl) {
|
|
|
50
62
|
resetTokenExpiry: expiresAt
|
|
51
63
|
}
|
|
52
64
|
});
|
|
53
|
-
const base = String(appUrl || "https://
|
|
65
|
+
const base = String(appUrl || "https://powr-api.lawazia.tech").replace(/\/+$/, "");
|
|
54
66
|
const link = `${base}/reset-password?token=${encodeURIComponent(resetToken)}`;
|
|
55
67
|
return {
|
|
56
68
|
link,
|
|
@@ -119,6 +131,55 @@ function userIdQuery(id) {
|
|
|
119
131
|
$in: [oid, String(oid)]
|
|
120
132
|
};
|
|
121
133
|
}
|
|
134
|
+
async function issuePowrSession(db, req, user, projectId, extraUserSet = {}) {
|
|
135
|
+
let profile = null;
|
|
136
|
+
if (projectId) {
|
|
137
|
+
profile = await db.collection("profiles").findOne({
|
|
138
|
+
userId: user._id,
|
|
139
|
+
projectId: projectId
|
|
140
|
+
});
|
|
141
|
+
if (profile) {
|
|
142
|
+
const now = new Date();
|
|
143
|
+
await db.collection("profiles").updateOne({
|
|
144
|
+
_id: profile._id
|
|
145
|
+
}, {
|
|
146
|
+
$set: {
|
|
147
|
+
lastActiveAt: now,
|
|
148
|
+
lastActiveFrom: getClientIp(req)
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
} else {
|
|
152
|
+
const now = new Date();
|
|
153
|
+
const newProfile = {
|
|
154
|
+
userId: user._id,
|
|
155
|
+
projectId: projectId,
|
|
156
|
+
createdAt: now,
|
|
157
|
+
lastActiveAt: now,
|
|
158
|
+
lastActiveFrom: getClientIp(req)
|
|
159
|
+
};
|
|
160
|
+
const profileResult = await db.collection("profiles").insertOne(newProfile);
|
|
161
|
+
profile = {
|
|
162
|
+
_id: profileResult.insertedId,
|
|
163
|
+
...newProfile
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const token = generateJWTToken(user, profile);
|
|
168
|
+
const refreshToken = generateRefreshToken(user);
|
|
169
|
+
await db.collection("users").updateOne({
|
|
170
|
+
_id: user._id
|
|
171
|
+
}, {
|
|
172
|
+
$set: {
|
|
173
|
+
refreshToken,
|
|
174
|
+
...extraUserSet
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
return {
|
|
178
|
+
token,
|
|
179
|
+
refreshToken,
|
|
180
|
+
profile
|
|
181
|
+
};
|
|
182
|
+
}
|
|
122
183
|
function publicUser(user, profile, options = {}) {
|
|
123
184
|
const merged = {
|
|
124
185
|
...user,
|
|
@@ -309,53 +370,15 @@ router.post("/login", async (req, res) => {
|
|
|
309
370
|
const saltRounds = 10;
|
|
310
371
|
newHashedPassword = await bcrypt.hash(password, saltRounds);
|
|
311
372
|
}
|
|
312
|
-
|
|
313
|
-
// Fetch profile data if projectId is provided
|
|
314
|
-
let profile = null;
|
|
315
|
-
if (projectId) {
|
|
316
|
-
profile = await db.collection("profiles").findOne({
|
|
317
|
-
userId: user._id,
|
|
318
|
-
projectId: projectId
|
|
319
|
-
});
|
|
320
|
-
if (profile) {
|
|
321
|
-
const now = new Date();
|
|
322
|
-
await db.collection("profiles").updateOne({
|
|
323
|
-
_id: profile._id
|
|
324
|
-
}, {
|
|
325
|
-
$set: {
|
|
326
|
-
lastActiveAt: now,
|
|
327
|
-
lastActiveFrom: getClientIp(req)
|
|
328
|
-
}
|
|
329
|
-
});
|
|
330
|
-
} else {
|
|
331
|
-
const now = new Date();
|
|
332
|
-
const newProfile = {
|
|
333
|
-
userId: user._id,
|
|
334
|
-
projectId: projectId,
|
|
335
|
-
createdAt: now,
|
|
336
|
-
lastActiveAt: now,
|
|
337
|
-
lastActiveFrom: getClientIp(req)
|
|
338
|
-
};
|
|
339
|
-
const profileResult = await db.collection("profiles").insertOne(newProfile);
|
|
340
|
-
profile = {
|
|
341
|
-
_id: profileResult.insertedId,
|
|
342
|
-
...newProfile
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
const token = generateJWTToken(user, profile);
|
|
347
|
-
const refreshToken = generateRefreshToken(user);
|
|
348
|
-
const userUpdate = {
|
|
349
|
-
refreshToken
|
|
350
|
-
};
|
|
373
|
+
const extraUserSet = {};
|
|
351
374
|
if (newHashedPassword) {
|
|
352
|
-
|
|
375
|
+
extraUserSet.password = newHashedPassword;
|
|
353
376
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
});
|
|
377
|
+
const {
|
|
378
|
+
token,
|
|
379
|
+
refreshToken,
|
|
380
|
+
profile
|
|
381
|
+
} = await issuePowrSession(db, req, user, projectId, extraUserSet);
|
|
359
382
|
return res.status(200).json({
|
|
360
383
|
success: true,
|
|
361
384
|
message: "Login successful",
|
|
@@ -726,4 +749,161 @@ router.post("/impersonate/exit", verifyToken, async (req, res) => {
|
|
|
726
749
|
});
|
|
727
750
|
}
|
|
728
751
|
});
|
|
752
|
+
router.post("/send-otp", async (req, res) => {
|
|
753
|
+
var _req$body2, _req$body3;
|
|
754
|
+
const mobile = tenDigitMobile(((_req$body2 = req.body) === null || _req$body2 === void 0 ? void 0 : _req$body2.mobile) || ((_req$body3 = req.body) === null || _req$body3 === void 0 ? void 0 : _req$body3.phoneOrEmail));
|
|
755
|
+
if (mobile.length !== 10) {
|
|
756
|
+
return res.status(400).json({
|
|
757
|
+
success: false,
|
|
758
|
+
message: "Mobile is required"
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
const app = otpAppName(req);
|
|
762
|
+
try {
|
|
763
|
+
const db = await getDb();
|
|
764
|
+
const template = await findTemplate(db, app);
|
|
765
|
+
if (!template || !template.sender_id || !template.message_id) {
|
|
766
|
+
return res.status(400).json({
|
|
767
|
+
success: false,
|
|
768
|
+
message: "OTP failed"
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
const generatedOtp = generateOtpCode(mobile);
|
|
772
|
+
const expiresAt = otpExpiryDate();
|
|
773
|
+
await saveOtp(db, {
|
|
774
|
+
mobile,
|
|
775
|
+
otp: generatedOtp,
|
|
776
|
+
app,
|
|
777
|
+
expiresAt
|
|
778
|
+
});
|
|
779
|
+
if (!isTestMobile(mobile)) {
|
|
780
|
+
const send = getSendOtpSms();
|
|
781
|
+
if (!send) {
|
|
782
|
+
return res.status(503).json({
|
|
783
|
+
success: false,
|
|
784
|
+
message: "OTP is not configured"
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
await send({
|
|
788
|
+
sender_id: template.sender_id,
|
|
789
|
+
message_id: template.message_id,
|
|
790
|
+
otp: generatedOtp,
|
|
791
|
+
number: mobile
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
return res.status(200).json({
|
|
795
|
+
success: true,
|
|
796
|
+
message: "OTP generated."
|
|
797
|
+
});
|
|
798
|
+
} catch (error) {
|
|
799
|
+
const status = error.status || 500;
|
|
800
|
+
return res.status(status).json({
|
|
801
|
+
success: false,
|
|
802
|
+
message: status === 500 ? "Internal server error." : error.message
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
});
|
|
806
|
+
router.post("/verify-otp", async (req, res) => {
|
|
807
|
+
var _req$body4, _req$body5, _req$body6;
|
|
808
|
+
const mobile = tenDigitMobile(((_req$body4 = req.body) === null || _req$body4 === void 0 ? void 0 : _req$body4.mobile) || ((_req$body5 = req.body) === null || _req$body5 === void 0 ? void 0 : _req$body5.phoneOrEmail));
|
|
809
|
+
const otp = String(((_req$body6 = req.body) === null || _req$body6 === void 0 ? void 0 : _req$body6.otp) || "").replace(/\D/g, "");
|
|
810
|
+
if (mobile.length !== 10 || !otp) {
|
|
811
|
+
return res.status(400).json({
|
|
812
|
+
success: false,
|
|
813
|
+
message: "Both mobile and OTP are required."
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
const app = otpAppName(req);
|
|
817
|
+
const projectId = req.projectId;
|
|
818
|
+
try {
|
|
819
|
+
const db = await getDb();
|
|
820
|
+
const otpRecord = await findLatestOtp(db, {
|
|
821
|
+
mobile,
|
|
822
|
+
app
|
|
823
|
+
});
|
|
824
|
+
if (!otpRecord) {
|
|
825
|
+
return res.status(400).json({
|
|
826
|
+
success: false,
|
|
827
|
+
message: "Invalid OTP, Please try again."
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
if (otpRecord.verifyAttempts >= 5) {
|
|
831
|
+
return res.status(400).json({
|
|
832
|
+
success: false,
|
|
833
|
+
message: "Too many verification attempts. Please request a new OTP."
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
if (otpRecord.expiresAt < new Date()) {
|
|
837
|
+
return res.status(400).json({
|
|
838
|
+
success: false,
|
|
839
|
+
message: "OTP expired, Please try again."
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
if (otpRecord.verified) {
|
|
843
|
+
return res.status(400).json({
|
|
844
|
+
success: false,
|
|
845
|
+
message: "OTP already verified."
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
if (otpRecord.otp !== otp) {
|
|
849
|
+
await db.collection("otps").updateOne({
|
|
850
|
+
_id: otpRecord._id
|
|
851
|
+
}, {
|
|
852
|
+
$inc: {
|
|
853
|
+
verifyAttempts: 1
|
|
854
|
+
}
|
|
855
|
+
});
|
|
856
|
+
const attempts = (otpRecord.verifyAttempts || 0) + 1;
|
|
857
|
+
if (attempts >= 5) {
|
|
858
|
+
return res.status(400).json({
|
|
859
|
+
success: false,
|
|
860
|
+
message: "Too many verification attempts. Please request a new OTP."
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
return res.status(400).json({
|
|
864
|
+
success: false,
|
|
865
|
+
message: "Invalid OTP, Please try again."
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
await db.collection("otps").updateOne({
|
|
869
|
+
_id: otpRecord._id
|
|
870
|
+
}, {
|
|
871
|
+
$set: {
|
|
872
|
+
verified: true
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
const q = buildIdentifierQuery({
|
|
876
|
+
phoneOrEmail: mobile
|
|
877
|
+
});
|
|
878
|
+
const user = q ? await db.collection("users").findOne(q) : null;
|
|
879
|
+
if (!user) {
|
|
880
|
+
const token = generatePhoneProofToken(mobile);
|
|
881
|
+
return res.status(200).json({
|
|
882
|
+
success: true,
|
|
883
|
+
message: "OTP verified successfully.",
|
|
884
|
+
token,
|
|
885
|
+
access_token: token
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
const {
|
|
889
|
+
token,
|
|
890
|
+
refreshToken,
|
|
891
|
+
profile
|
|
892
|
+
} = await issuePowrSession(db, req, user, projectId);
|
|
893
|
+
return res.status(200).json({
|
|
894
|
+
success: true,
|
|
895
|
+
message: "OTP verified successfully.",
|
|
896
|
+
user: publicUser(user, profile),
|
|
897
|
+
token,
|
|
898
|
+
refreshToken,
|
|
899
|
+
access_token: token
|
|
900
|
+
});
|
|
901
|
+
} catch (error) {
|
|
902
|
+
console.error("Error in verify-otp:", error);
|
|
903
|
+
return res.status(500).json({
|
|
904
|
+
success: false,
|
|
905
|
+
message: "Internal server error."
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
});
|
|
729
909
|
module.exports = router;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
jest.mock("../config", () => ({
|
|
4
|
+
config: {
|
|
5
|
+
jwtToken: "test-powr-jwt"
|
|
6
|
+
},
|
|
7
|
+
credentials: {}
|
|
8
|
+
}));
|
|
9
|
+
jest.mock("bcrypt", () => ({
|
|
10
|
+
hash: jest.fn(),
|
|
11
|
+
compare: jest.fn()
|
|
12
|
+
}));
|
|
13
|
+
jest.mock("../services/mongo", () => ({
|
|
14
|
+
getDb: jest.fn()
|
|
15
|
+
}));
|
|
16
|
+
jest.mock("../services/otp", () => {
|
|
17
|
+
const actual = jest.requireActual("../services/otp");
|
|
18
|
+
return {
|
|
19
|
+
...actual,
|
|
20
|
+
findTemplate: jest.fn(),
|
|
21
|
+
saveOtp: jest.fn(),
|
|
22
|
+
findLatestOtp: jest.fn(),
|
|
23
|
+
getSendOtpSms: jest.fn(() => null),
|
|
24
|
+
generateOtpCode: jest.fn(() => "12345"),
|
|
25
|
+
otpExpiryDate: jest.fn(() => new Date(Date.now() + 10 * 60 * 1000)),
|
|
26
|
+
isTestMobile: jest.fn(() => true)
|
|
27
|
+
};
|
|
28
|
+
});
|
|
29
|
+
const {
|
|
30
|
+
ObjectId
|
|
31
|
+
} = require("mongodb");
|
|
32
|
+
const {
|
|
33
|
+
getDb
|
|
34
|
+
} = require("../services/mongo");
|
|
35
|
+
const otp = require("../services/otp");
|
|
36
|
+
const authRouter = require("./auth");
|
|
37
|
+
function mockRes() {
|
|
38
|
+
const res = {};
|
|
39
|
+
res.status = jest.fn().mockReturnValue(res);
|
|
40
|
+
res.json = jest.fn().mockReturnValue(res);
|
|
41
|
+
return res;
|
|
42
|
+
}
|
|
43
|
+
function findRoute(method, path) {
|
|
44
|
+
const layer = authRouter.stack.find(item => item.route && item.route.path === path && item.route.methods[method]);
|
|
45
|
+
return layer.route.stack[0].handle;
|
|
46
|
+
}
|
|
47
|
+
describe("auth OTP routes", () => {
|
|
48
|
+
const userId = new ObjectId("507f1f77bcf86cd799439011");
|
|
49
|
+
it("send-otp defaults to powr and never echoes the code", async () => {
|
|
50
|
+
const inserted = [];
|
|
51
|
+
otp.findTemplate.mockResolvedValue({
|
|
52
|
+
app: "powr",
|
|
53
|
+
sender_id: "SID",
|
|
54
|
+
message_id: "MID"
|
|
55
|
+
});
|
|
56
|
+
otp.saveOtp.mockImplementation(async (_db, doc) => {
|
|
57
|
+
inserted.push(doc);
|
|
58
|
+
return {
|
|
59
|
+
insertedId: "otp1"
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
getDb.mockResolvedValue({});
|
|
63
|
+
const req = {
|
|
64
|
+
body: {
|
|
65
|
+
mobile: "7903658469"
|
|
66
|
+
},
|
|
67
|
+
headers: {}
|
|
68
|
+
};
|
|
69
|
+
const res = mockRes();
|
|
70
|
+
await findRoute("post", "/send-otp")(req, res);
|
|
71
|
+
expect(otp.findTemplate).toHaveBeenCalledWith({}, "powr");
|
|
72
|
+
expect(inserted[0].otp).toBe("12345");
|
|
73
|
+
expect(res.status).toHaveBeenCalledWith(200);
|
|
74
|
+
const body = res.json.mock.calls[0][0];
|
|
75
|
+
expect(body.success).toBe(true);
|
|
76
|
+
expect(JSON.stringify(body)).not.toContain("12345");
|
|
77
|
+
expect(body.otp).toBeUndefined();
|
|
78
|
+
});
|
|
79
|
+
it("send-otp is 503 when the host has not injected a sender", async () => {
|
|
80
|
+
otp.isTestMobile.mockReturnValue(false);
|
|
81
|
+
otp.findTemplate.mockResolvedValue({
|
|
82
|
+
app: "powr",
|
|
83
|
+
sender_id: "SID",
|
|
84
|
+
message_id: "MID"
|
|
85
|
+
});
|
|
86
|
+
otp.saveOtp.mockResolvedValue({
|
|
87
|
+
insertedId: "otp1"
|
|
88
|
+
});
|
|
89
|
+
otp.getSendOtpSms.mockReturnValue(null);
|
|
90
|
+
getDb.mockResolvedValue({});
|
|
91
|
+
const req = {
|
|
92
|
+
body: {
|
|
93
|
+
mobile: "7903658469"
|
|
94
|
+
},
|
|
95
|
+
headers: {}
|
|
96
|
+
};
|
|
97
|
+
const res = mockRes();
|
|
98
|
+
await findRoute("post", "/send-otp")(req, res);
|
|
99
|
+
expect(res.status).toHaveBeenCalledWith(503);
|
|
100
|
+
expect(res.json.mock.calls[0][0].message).toBe("OTP is not configured");
|
|
101
|
+
otp.isTestMobile.mockReturnValue(true);
|
|
102
|
+
});
|
|
103
|
+
it("verify-otp issues a Powr user token, not a mobile-only token", async () => {
|
|
104
|
+
const user = {
|
|
105
|
+
_id: userId,
|
|
106
|
+
fullName: "Test User",
|
|
107
|
+
phoneNumber: "+917903658469"
|
|
108
|
+
};
|
|
109
|
+
otp.findLatestOtp.mockResolvedValue({
|
|
110
|
+
_id: "otp1",
|
|
111
|
+
mobile: "7903658469",
|
|
112
|
+
otp: "12345",
|
|
113
|
+
app: "powr",
|
|
114
|
+
verified: false,
|
|
115
|
+
verifyAttempts: 0,
|
|
116
|
+
expiresAt: new Date(Date.now() + 60 * 1000)
|
|
117
|
+
});
|
|
118
|
+
const updateOne = jest.fn();
|
|
119
|
+
getDb.mockResolvedValue({
|
|
120
|
+
collection(name) {
|
|
121
|
+
if (name === "otps") return {
|
|
122
|
+
updateOne
|
|
123
|
+
};
|
|
124
|
+
if (name === "users") {
|
|
125
|
+
return {
|
|
126
|
+
findOne: async () => user,
|
|
127
|
+
updateOne
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
if (name === "profiles") {
|
|
131
|
+
return {
|
|
132
|
+
findOne: async () => ({
|
|
133
|
+
access: 100,
|
|
134
|
+
userId,
|
|
135
|
+
projectId: "proj1"
|
|
136
|
+
}),
|
|
137
|
+
updateOne
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
throw new Error(name);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
const req = {
|
|
144
|
+
body: {
|
|
145
|
+
mobile: "7903658469",
|
|
146
|
+
otp: "12345"
|
|
147
|
+
},
|
|
148
|
+
headers: {},
|
|
149
|
+
projectId: "proj1"
|
|
150
|
+
};
|
|
151
|
+
const res = mockRes();
|
|
152
|
+
await findRoute("post", "/verify-otp")(req, res);
|
|
153
|
+
expect(res.status).toHaveBeenCalledWith(200);
|
|
154
|
+
const body = res.json.mock.calls[0][0];
|
|
155
|
+
expect(body.success).toBe(true);
|
|
156
|
+
expect(body.token).toEqual(expect.any(String));
|
|
157
|
+
expect(body.refreshToken).toEqual(expect.any(String));
|
|
158
|
+
expect(body.access_token).toBe(body.token);
|
|
159
|
+
expect(body.user.fullName).toBe("Test User");
|
|
160
|
+
const jwt = require("jsonwebtoken");
|
|
161
|
+
const decoded = jwt.decode(body.token);
|
|
162
|
+
expect(decoded.userId).toBe(String(userId));
|
|
163
|
+
expect(decoded.fullName).toBe("Test User");
|
|
164
|
+
expect(decoded.mobile).toBe("7903658469");
|
|
165
|
+
expect(decoded.phoneNumber).toBe("+917903658469");
|
|
166
|
+
});
|
|
167
|
+
it("verify-otp still returns a phone-proof token when there is no Powr user", async () => {
|
|
168
|
+
otp.findLatestOtp.mockResolvedValue({
|
|
169
|
+
_id: "otp2",
|
|
170
|
+
mobile: "7903658469",
|
|
171
|
+
otp: "12345",
|
|
172
|
+
app: "powr",
|
|
173
|
+
verified: false,
|
|
174
|
+
verifyAttempts: 0,
|
|
175
|
+
expiresAt: new Date(Date.now() + 60 * 1000)
|
|
176
|
+
});
|
|
177
|
+
getDb.mockResolvedValue({
|
|
178
|
+
collection(name) {
|
|
179
|
+
if (name === "otps") return {
|
|
180
|
+
updateOne: jest.fn()
|
|
181
|
+
};
|
|
182
|
+
if (name === "users") return {
|
|
183
|
+
findOne: async () => null
|
|
184
|
+
};
|
|
185
|
+
throw new Error(name);
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
const req = {
|
|
189
|
+
body: {
|
|
190
|
+
mobile: "7903658469",
|
|
191
|
+
otp: "12345"
|
|
192
|
+
},
|
|
193
|
+
headers: {}
|
|
194
|
+
};
|
|
195
|
+
const res = mockRes();
|
|
196
|
+
await findRoute("post", "/verify-otp")(req, res);
|
|
197
|
+
expect(res.status).toHaveBeenCalledWith(200);
|
|
198
|
+
const body = res.json.mock.calls[0][0];
|
|
199
|
+
expect(body.user).toBeUndefined();
|
|
200
|
+
expect(body.access_token).toBe(body.token);
|
|
201
|
+
const jwt = require("jsonwebtoken");
|
|
202
|
+
const decoded = jwt.decode(body.token);
|
|
203
|
+
expect(decoded.userId).toBeUndefined();
|
|
204
|
+
expect(decoded.mobile).toBe("7903658469");
|
|
205
|
+
});
|
|
206
|
+
});
|
package/dist/routes/index.js
CHANGED
|
@@ -4,6 +4,9 @@ const express = require('express');
|
|
|
4
4
|
const {
|
|
5
5
|
injectProjectId
|
|
6
6
|
} = require('../middleware/projectId');
|
|
7
|
+
const {
|
|
8
|
+
setSendOtpSms
|
|
9
|
+
} = require('../services/otp');
|
|
7
10
|
const {
|
|
8
11
|
verifyToken
|
|
9
12
|
} = require('../middleware/jwtToken');
|
|
@@ -41,6 +44,9 @@ const postsRoutes = require('./posts');
|
|
|
41
44
|
// Synchronous router creation
|
|
42
45
|
const createPowrRoutes = (options = {}) => {
|
|
43
46
|
const router = express.Router();
|
|
47
|
+
if (Object.prototype.hasOwnProperty.call(options, "sendOtpSms")) {
|
|
48
|
+
setSendOtpSms(options.sendOtpSms);
|
|
49
|
+
}
|
|
44
50
|
|
|
45
51
|
// Use the dedicated projectId injection middleware
|
|
46
52
|
router.use(injectProjectId(options));
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const crypto = require("crypto");
|
|
4
|
+
const DEFAULT_OTP_MINUTES = 10;
|
|
5
|
+
let sendOtpSms = null;
|
|
6
|
+
function setSendOtpSms(fn) {
|
|
7
|
+
sendOtpSms = typeof fn === "function" ? fn : null;
|
|
8
|
+
}
|
|
9
|
+
function getSendOtpSms() {
|
|
10
|
+
return sendOtpSms;
|
|
11
|
+
}
|
|
12
|
+
function otpAppName(req) {
|
|
13
|
+
const fromBody = req.body && req.body.app;
|
|
14
|
+
const fromHeader = req.headers && req.headers.app;
|
|
15
|
+
const raw = String(fromBody || fromHeader || "").trim();
|
|
16
|
+
return raw || "powr";
|
|
17
|
+
}
|
|
18
|
+
function tenDigitMobile(raw) {
|
|
19
|
+
const digits = String(raw || "").replace(/\D/g, "");
|
|
20
|
+
if (digits.length === 10) return digits;
|
|
21
|
+
if (digits.length === 12 && digits.startsWith("91")) return digits.slice(2);
|
|
22
|
+
if (digits.length === 11 && digits.startsWith("0")) return digits.slice(1);
|
|
23
|
+
if (digits.length > 10) return digits.slice(-10);
|
|
24
|
+
return digits;
|
|
25
|
+
}
|
|
26
|
+
function isTestMobile(mobile) {
|
|
27
|
+
if (!mobile) return false;
|
|
28
|
+
const envVal = process.env.TEST_MOBILE;
|
|
29
|
+
if (!envVal) return false;
|
|
30
|
+
let testMobiles = [];
|
|
31
|
+
try {
|
|
32
|
+
const parsed = JSON.parse(envVal.replace(/'/g, '"'));
|
|
33
|
+
if (Array.isArray(parsed)) {
|
|
34
|
+
testMobiles = parsed.map(m => String(m).trim());
|
|
35
|
+
}
|
|
36
|
+
} catch (error) {
|
|
37
|
+
testMobiles = [];
|
|
38
|
+
}
|
|
39
|
+
if (testMobiles.length === 0) {
|
|
40
|
+
testMobiles = envVal.replace(/[\[\]'"]/g, "").split(",").map(m => m.trim()).filter(Boolean);
|
|
41
|
+
}
|
|
42
|
+
return testMobiles.includes(String(mobile).trim());
|
|
43
|
+
}
|
|
44
|
+
function generateOtpCode(mobile) {
|
|
45
|
+
if (isTestMobile(mobile)) return "12345";
|
|
46
|
+
return crypto.randomInt(10000, 100000).toString();
|
|
47
|
+
}
|
|
48
|
+
function otpExpiryDate() {
|
|
49
|
+
const minutes = Number(process.env.OTP_TIME_MINUTES || DEFAULT_OTP_MINUTES);
|
|
50
|
+
const safe = Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_OTP_MINUTES;
|
|
51
|
+
return new Date(Date.now() + safe * 60 * 1000);
|
|
52
|
+
}
|
|
53
|
+
async function findTemplate(db, app) {
|
|
54
|
+
return db.collection("templates").findOne({
|
|
55
|
+
app
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
async function saveOtp(db, {
|
|
59
|
+
mobile,
|
|
60
|
+
otp,
|
|
61
|
+
app,
|
|
62
|
+
expiresAt
|
|
63
|
+
}) {
|
|
64
|
+
const col = db.collection("otps");
|
|
65
|
+
await col.createIndex({
|
|
66
|
+
mobile: 1,
|
|
67
|
+
app: 1,
|
|
68
|
+
createdAt: -1
|
|
69
|
+
});
|
|
70
|
+
return col.insertOne({
|
|
71
|
+
mobile,
|
|
72
|
+
otp,
|
|
73
|
+
app,
|
|
74
|
+
expiresAt,
|
|
75
|
+
verified: false,
|
|
76
|
+
verifyAttempts: 0,
|
|
77
|
+
createdAt: new Date()
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
async function findLatestOtp(db, {
|
|
81
|
+
mobile,
|
|
82
|
+
app
|
|
83
|
+
}) {
|
|
84
|
+
return db.collection("otps").find({
|
|
85
|
+
mobile,
|
|
86
|
+
app
|
|
87
|
+
}).sort({
|
|
88
|
+
createdAt: -1
|
|
89
|
+
}).limit(1).next();
|
|
90
|
+
}
|
|
91
|
+
module.exports = {
|
|
92
|
+
setSendOtpSms,
|
|
93
|
+
getSendOtpSms,
|
|
94
|
+
otpAppName,
|
|
95
|
+
tenDigitMobile,
|
|
96
|
+
isTestMobile,
|
|
97
|
+
generateOtpCode,
|
|
98
|
+
otpExpiryDate,
|
|
99
|
+
findTemplate,
|
|
100
|
+
saveOtp,
|
|
101
|
+
findLatestOtp
|
|
102
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
otpAppName,
|
|
5
|
+
tenDigitMobile,
|
|
6
|
+
isTestMobile,
|
|
7
|
+
generateOtpCode,
|
|
8
|
+
setSendOtpSms,
|
|
9
|
+
getSendOtpSms,
|
|
10
|
+
findTemplate
|
|
11
|
+
} = require("./otp");
|
|
12
|
+
describe("otpAppName", () => {
|
|
13
|
+
it("uses powr when app is omitted", () => {
|
|
14
|
+
expect(otpAppName({
|
|
15
|
+
body: {},
|
|
16
|
+
headers: {}
|
|
17
|
+
})).toBe("powr");
|
|
18
|
+
});
|
|
19
|
+
it("prefers body.app, then header app", () => {
|
|
20
|
+
expect(otpAppName({
|
|
21
|
+
body: {
|
|
22
|
+
app: "urbanstall"
|
|
23
|
+
},
|
|
24
|
+
headers: {}
|
|
25
|
+
})).toBe("urbanstall");
|
|
26
|
+
expect(otpAppName({
|
|
27
|
+
body: {},
|
|
28
|
+
headers: {
|
|
29
|
+
app: "urbanstall"
|
|
30
|
+
}
|
|
31
|
+
})).toBe("urbanstall");
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
describe("tenDigitMobile", () => {
|
|
35
|
+
it("normalizes +91 and 91 prefixes", () => {
|
|
36
|
+
expect(tenDigitMobile("+917903658469")).toBe("7903658469");
|
|
37
|
+
expect(tenDigitMobile("917903658469")).toBe("7903658469");
|
|
38
|
+
expect(tenDigitMobile("7903658469")).toBe("7903658469");
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
describe("isTestMobile / generateOtpCode", () => {
|
|
42
|
+
const previous = process.env.TEST_MOBILE;
|
|
43
|
+
afterEach(() => {
|
|
44
|
+
if (previous === undefined) delete process.env.TEST_MOBILE;else process.env.TEST_MOBILE = previous;
|
|
45
|
+
});
|
|
46
|
+
it("uses 12345 for TEST_MOBILE and never a random code", () => {
|
|
47
|
+
process.env.TEST_MOBILE = "7777777777";
|
|
48
|
+
expect(isTestMobile("7777777777")).toBe(true);
|
|
49
|
+
expect(generateOtpCode("7777777777")).toBe("12345");
|
|
50
|
+
});
|
|
51
|
+
it("returns a 5-digit code for a live number", () => {
|
|
52
|
+
delete process.env.TEST_MOBILE;
|
|
53
|
+
const code = generateOtpCode("7903658469");
|
|
54
|
+
expect(code).toMatch(/^\d{5}$/);
|
|
55
|
+
expect(code).not.toBe("12345");
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
describe("send hook", () => {
|
|
59
|
+
afterEach(() => {
|
|
60
|
+
setSendOtpSms(null);
|
|
61
|
+
});
|
|
62
|
+
it("has no SMS sender until the host injects one", () => {
|
|
63
|
+
expect(getSendOtpSms()).toBeNull();
|
|
64
|
+
});
|
|
65
|
+
it("accepts a host sender and can clear it", () => {
|
|
66
|
+
const send = async () => {};
|
|
67
|
+
setSendOtpSms(send);
|
|
68
|
+
expect(getSendOtpSms()).toBe(send);
|
|
69
|
+
setSendOtpSms(null);
|
|
70
|
+
expect(getSendOtpSms()).toBeNull();
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
describe("findTemplate", () => {
|
|
74
|
+
it("only reads PowrBase templates — no company seed in the library", async () => {
|
|
75
|
+
const findOne = jest.fn().mockResolvedValue(null);
|
|
76
|
+
const db = {
|
|
77
|
+
collection: jest.fn(() => ({
|
|
78
|
+
findOne
|
|
79
|
+
}))
|
|
80
|
+
};
|
|
81
|
+
const row = await findTemplate(db, "powr");
|
|
82
|
+
expect(db.collection).toHaveBeenCalledWith("templates");
|
|
83
|
+
expect(findOne).toHaveBeenCalledWith({
|
|
84
|
+
app: "powr"
|
|
85
|
+
});
|
|
86
|
+
expect(row).toBeNull();
|
|
87
|
+
});
|
|
88
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "powr-sdk-api",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.21.1",
|
|
4
4
|
"description": "Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|