powr-sdk-api 4.19.2 → 4.21.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/dist/middleware/projectId.js +1 -1
- package/dist/routes/auth.js +221 -46
- package/dist/routes/auth.otp.test.js +166 -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
|
@@ -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
|
@@ -32,6 +32,17 @@ const {
|
|
|
32
32
|
decideImpersonation
|
|
33
33
|
} = require("../utils/impersonate");
|
|
34
34
|
const jwt = require("jsonwebtoken");
|
|
35
|
+
const {
|
|
36
|
+
otpAppName,
|
|
37
|
+
tenDigitMobile,
|
|
38
|
+
isTestMobile,
|
|
39
|
+
generateOtpCode,
|
|
40
|
+
otpExpiryDate,
|
|
41
|
+
findTemplate,
|
|
42
|
+
saveOtp,
|
|
43
|
+
findLatestOtp,
|
|
44
|
+
getSendOtpSms
|
|
45
|
+
} = require("../services/otp");
|
|
35
46
|
const PASSWORD_RESET_TTL_MS = 24 * 60 * 60 * 1000;
|
|
36
47
|
async function issuePasswordResetLink(db, user, appUrl) {
|
|
37
48
|
const expiresAt = new Date(Date.now() + PASSWORD_RESET_TTL_MS);
|
|
@@ -50,7 +61,7 @@ async function issuePasswordResetLink(db, user, appUrl) {
|
|
|
50
61
|
resetTokenExpiry: expiresAt
|
|
51
62
|
}
|
|
52
63
|
});
|
|
53
|
-
const base = String(appUrl || "https://
|
|
64
|
+
const base = String(appUrl || "https://powr-api.lawazia.tech").replace(/\/+$/, "");
|
|
54
65
|
const link = `${base}/reset-password?token=${encodeURIComponent(resetToken)}`;
|
|
55
66
|
return {
|
|
56
67
|
link,
|
|
@@ -119,6 +130,55 @@ function userIdQuery(id) {
|
|
|
119
130
|
$in: [oid, String(oid)]
|
|
120
131
|
};
|
|
121
132
|
}
|
|
133
|
+
async function issuePowrSession(db, req, user, projectId, extraUserSet = {}) {
|
|
134
|
+
let profile = null;
|
|
135
|
+
if (projectId) {
|
|
136
|
+
profile = await db.collection("profiles").findOne({
|
|
137
|
+
userId: user._id,
|
|
138
|
+
projectId: projectId
|
|
139
|
+
});
|
|
140
|
+
if (profile) {
|
|
141
|
+
const now = new Date();
|
|
142
|
+
await db.collection("profiles").updateOne({
|
|
143
|
+
_id: profile._id
|
|
144
|
+
}, {
|
|
145
|
+
$set: {
|
|
146
|
+
lastActiveAt: now,
|
|
147
|
+
lastActiveFrom: getClientIp(req)
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
} else {
|
|
151
|
+
const now = new Date();
|
|
152
|
+
const newProfile = {
|
|
153
|
+
userId: user._id,
|
|
154
|
+
projectId: projectId,
|
|
155
|
+
createdAt: now,
|
|
156
|
+
lastActiveAt: now,
|
|
157
|
+
lastActiveFrom: getClientIp(req)
|
|
158
|
+
};
|
|
159
|
+
const profileResult = await db.collection("profiles").insertOne(newProfile);
|
|
160
|
+
profile = {
|
|
161
|
+
_id: profileResult.insertedId,
|
|
162
|
+
...newProfile
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const token = generateJWTToken(user, profile);
|
|
167
|
+
const refreshToken = generateRefreshToken(user);
|
|
168
|
+
await db.collection("users").updateOne({
|
|
169
|
+
_id: user._id
|
|
170
|
+
}, {
|
|
171
|
+
$set: {
|
|
172
|
+
refreshToken,
|
|
173
|
+
...extraUserSet
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
return {
|
|
177
|
+
token,
|
|
178
|
+
refreshToken,
|
|
179
|
+
profile
|
|
180
|
+
};
|
|
181
|
+
}
|
|
122
182
|
function publicUser(user, profile, options = {}) {
|
|
123
183
|
const merged = {
|
|
124
184
|
...user,
|
|
@@ -309,53 +369,15 @@ router.post("/login", async (req, res) => {
|
|
|
309
369
|
const saltRounds = 10;
|
|
310
370
|
newHashedPassword = await bcrypt.hash(password, saltRounds);
|
|
311
371
|
}
|
|
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
|
-
};
|
|
372
|
+
const extraUserSet = {};
|
|
351
373
|
if (newHashedPassword) {
|
|
352
|
-
|
|
374
|
+
extraUserSet.password = newHashedPassword;
|
|
353
375
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
});
|
|
376
|
+
const {
|
|
377
|
+
token,
|
|
378
|
+
refreshToken,
|
|
379
|
+
profile
|
|
380
|
+
} = await issuePowrSession(db, req, user, projectId, extraUserSet);
|
|
359
381
|
return res.status(200).json({
|
|
360
382
|
success: true,
|
|
361
383
|
message: "Login successful",
|
|
@@ -726,4 +748,157 @@ router.post("/impersonate/exit", verifyToken, async (req, res) => {
|
|
|
726
748
|
});
|
|
727
749
|
}
|
|
728
750
|
});
|
|
751
|
+
router.post("/send-otp", async (req, res) => {
|
|
752
|
+
var _req$body2, _req$body3;
|
|
753
|
+
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));
|
|
754
|
+
if (mobile.length !== 10) {
|
|
755
|
+
return res.status(400).json({
|
|
756
|
+
success: false,
|
|
757
|
+
message: "Mobile is required"
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
const app = otpAppName(req);
|
|
761
|
+
try {
|
|
762
|
+
const db = await getDb();
|
|
763
|
+
const template = await findTemplate(db, app);
|
|
764
|
+
if (!template || !template.sender_id || !template.message_id) {
|
|
765
|
+
return res.status(400).json({
|
|
766
|
+
success: false,
|
|
767
|
+
message: "OTP failed"
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
const generatedOtp = generateOtpCode(mobile);
|
|
771
|
+
const expiresAt = otpExpiryDate();
|
|
772
|
+
await saveOtp(db, {
|
|
773
|
+
mobile,
|
|
774
|
+
otp: generatedOtp,
|
|
775
|
+
app,
|
|
776
|
+
expiresAt
|
|
777
|
+
});
|
|
778
|
+
if (!isTestMobile(mobile)) {
|
|
779
|
+
const send = getSendOtpSms();
|
|
780
|
+
if (!send) {
|
|
781
|
+
return res.status(503).json({
|
|
782
|
+
success: false,
|
|
783
|
+
message: "OTP is not configured"
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
await send({
|
|
787
|
+
sender_id: template.sender_id,
|
|
788
|
+
message_id: template.message_id,
|
|
789
|
+
otp: generatedOtp,
|
|
790
|
+
number: mobile
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
return res.status(200).json({
|
|
794
|
+
success: true,
|
|
795
|
+
message: "OTP generated."
|
|
796
|
+
});
|
|
797
|
+
} catch (error) {
|
|
798
|
+
const status = error.status || 500;
|
|
799
|
+
return res.status(status).json({
|
|
800
|
+
success: false,
|
|
801
|
+
message: status === 500 ? "Internal server error." : error.message
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
});
|
|
805
|
+
router.post("/verify-otp", async (req, res) => {
|
|
806
|
+
var _req$body4, _req$body5, _req$body6;
|
|
807
|
+
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));
|
|
808
|
+
const otp = String(((_req$body6 = req.body) === null || _req$body6 === void 0 ? void 0 : _req$body6.otp) || "").replace(/\D/g, "");
|
|
809
|
+
if (mobile.length !== 10 || !otp) {
|
|
810
|
+
return res.status(400).json({
|
|
811
|
+
success: false,
|
|
812
|
+
message: "Both mobile and OTP are required."
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
const app = otpAppName(req);
|
|
816
|
+
const projectId = req.projectId;
|
|
817
|
+
try {
|
|
818
|
+
const db = await getDb();
|
|
819
|
+
const otpRecord = await findLatestOtp(db, {
|
|
820
|
+
mobile,
|
|
821
|
+
app
|
|
822
|
+
});
|
|
823
|
+
if (!otpRecord) {
|
|
824
|
+
return res.status(400).json({
|
|
825
|
+
success: false,
|
|
826
|
+
message: "Invalid OTP, Please try again."
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
if (otpRecord.verifyAttempts >= 5) {
|
|
830
|
+
return res.status(400).json({
|
|
831
|
+
success: false,
|
|
832
|
+
message: "Too many verification attempts. Please request a new OTP."
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
if (otpRecord.expiresAt < new Date()) {
|
|
836
|
+
return res.status(400).json({
|
|
837
|
+
success: false,
|
|
838
|
+
message: "OTP expired, Please try again."
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
if (otpRecord.verified) {
|
|
842
|
+
return res.status(400).json({
|
|
843
|
+
success: false,
|
|
844
|
+
message: "OTP already verified."
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
if (otpRecord.otp !== otp) {
|
|
848
|
+
await db.collection("otps").updateOne({
|
|
849
|
+
_id: otpRecord._id
|
|
850
|
+
}, {
|
|
851
|
+
$inc: {
|
|
852
|
+
verifyAttempts: 1
|
|
853
|
+
}
|
|
854
|
+
});
|
|
855
|
+
const attempts = (otpRecord.verifyAttempts || 0) + 1;
|
|
856
|
+
if (attempts >= 5) {
|
|
857
|
+
return res.status(400).json({
|
|
858
|
+
success: false,
|
|
859
|
+
message: "Too many verification attempts. Please request a new OTP."
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
return res.status(400).json({
|
|
863
|
+
success: false,
|
|
864
|
+
message: "Invalid OTP, Please try again."
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
await db.collection("otps").updateOne({
|
|
868
|
+
_id: otpRecord._id
|
|
869
|
+
}, {
|
|
870
|
+
$set: {
|
|
871
|
+
verified: true
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
const q = buildIdentifierQuery({
|
|
875
|
+
phoneOrEmail: mobile
|
|
876
|
+
});
|
|
877
|
+
const user = q ? await db.collection("users").findOne(q) : null;
|
|
878
|
+
if (!user) {
|
|
879
|
+
return res.status(401).json({
|
|
880
|
+
success: false,
|
|
881
|
+
message: "User not found."
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
const {
|
|
885
|
+
token,
|
|
886
|
+
refreshToken,
|
|
887
|
+
profile
|
|
888
|
+
} = await issuePowrSession(db, req, user, projectId);
|
|
889
|
+
return res.status(200).json({
|
|
890
|
+
success: true,
|
|
891
|
+
message: "OTP verified successfully.",
|
|
892
|
+
user: publicUser(user, profile),
|
|
893
|
+
token,
|
|
894
|
+
refreshToken
|
|
895
|
+
});
|
|
896
|
+
} catch (error) {
|
|
897
|
+
console.error("Error in verify-otp:", error);
|
|
898
|
+
return res.status(500).json({
|
|
899
|
+
success: false,
|
|
900
|
+
message: "Internal server error."
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
});
|
|
729
904
|
module.exports = router;
|
|
@@ -0,0 +1,166 @@
|
|
|
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).toBeUndefined();
|
|
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).toBeUndefined();
|
|
165
|
+
});
|
|
166
|
+
});
|
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.0",
|
|
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",
|