powr-sdk-api 4.11.0 → 4.12.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.
@@ -4,12 +4,16 @@ const jwt = require('jsonwebtoken');
4
4
  const {
5
5
  config
6
6
  } = require('../config');
7
- const generateJWTToken = (user, profile = null) => {
8
- return jwt.sign({
7
+ const generateJWTToken = (user, profile = null, extra = null) => {
8
+ const payload = {
9
9
  userId: user._id,
10
10
  fullName: user.fullName,
11
11
  access: profile === null || profile === void 0 ? void 0 : profile.access
12
- }, config.jwtToken, {
12
+ };
13
+ if (extra && extra.impersonatedBy) {
14
+ payload.impersonatedBy = String(extra.impersonatedBy);
15
+ }
16
+ return jwt.sign(payload, config.jwtToken, {
13
17
  expiresIn: '24h'
14
18
  });
15
19
  };
@@ -52,7 +56,8 @@ const verifyToken = async (req, res, next) => {
52
56
  req.user = {
53
57
  powrId: decoded.userId,
54
58
  fullName: decoded.fullName,
55
- access: decoded.access
59
+ access: decoded.access,
60
+ impersonatedBy: decoded.impersonatedBy || null
56
61
  };
57
62
  return next();
58
63
  } catch (error) {
@@ -12,7 +12,8 @@ const bcrypt = require("bcrypt");
12
12
  const {
13
13
  generateJWTToken,
14
14
  generateRefreshToken,
15
- verifyRefreshToken
15
+ verifyRefreshToken,
16
+ verifyToken
16
17
  } = require("../middleware/jwtToken");
17
18
  const {
18
19
  config
@@ -24,6 +25,38 @@ const {
24
25
  coercePhoneForStorage,
25
26
  getPhoneLookupVariants
26
27
  } = require("../utils/phone");
28
+ const {
29
+ verifyTokenOrServiceKey
30
+ } = require("../middleware/serviceKey");
31
+ const {
32
+ decideImpersonation
33
+ } = require("../utils/impersonate");
34
+ const jwt = require("jsonwebtoken");
35
+ async function issuePasswordResetLink(db, user, appUrl) {
36
+ const resetPayload = {
37
+ userId: user._id.toString(),
38
+ type: "reset",
39
+ iat: Math.floor(Date.now() / 1000),
40
+ exp: Math.floor(Date.now() / 1000) + 60 * 60
41
+ };
42
+ const resetToken = jwt.sign(resetPayload, config.jwtToken);
43
+ const expiresAt = new Date(Date.now() + 3600000);
44
+ await db.collection("users").updateOne({
45
+ _id: user._id
46
+ }, {
47
+ $set: {
48
+ resetToken,
49
+ resetTokenExpiry: expiresAt
50
+ }
51
+ });
52
+ const base = String(appUrl || "https://www.excelrs.dev").replace(/\/+$/, "");
53
+ const link = `${base}/reset-password?token=${encodeURIComponent(resetToken)}`;
54
+ return {
55
+ link,
56
+ expiresAt,
57
+ resetToken
58
+ };
59
+ }
27
60
  function buildIdentifierQuery({
28
61
  username,
29
62
  phoneOrEmail
@@ -71,6 +104,54 @@ function resolveStoredContact(phoneOrEmail) {
71
104
  phoneNumber
72
105
  };
73
106
  }
107
+ function asObjectId(id) {
108
+ if (!id) return null;
109
+ if (id instanceof ObjectId) return id;
110
+ const value = String(id);
111
+ if (value.length !== 24 || !ObjectId.isValid(value)) return null;
112
+ return new ObjectId(value);
113
+ }
114
+ function userIdQuery(id) {
115
+ const oid = asObjectId(id);
116
+ if (!oid) return null;
117
+ return {
118
+ $in: [oid, String(oid)]
119
+ };
120
+ }
121
+ function publicUser(user, profile, options = {}) {
122
+ const merged = {
123
+ ...user,
124
+ powrId: user._id
125
+ };
126
+ delete merged.password;
127
+ delete merged._id;
128
+ if (options.omitSessionSecrets) {
129
+ delete merged.refreshToken;
130
+ delete merged.resetToken;
131
+ delete merged.resetTokenExpiry;
132
+ }
133
+ if (!profile) return merged;
134
+ const profileData = {
135
+ ...profile
136
+ };
137
+ delete profileData._id;
138
+ delete profileData.userId;
139
+ delete profileData.projectId;
140
+ delete profileData.createdAt;
141
+ delete profileData.updatedAt;
142
+ delete profileData.lastActiveAt;
143
+ delete profileData.lastActiveFrom;
144
+ return {
145
+ ...merged,
146
+ ...profileData
147
+ };
148
+ }
149
+ async function writeImpersonationAudit(db, doc) {
150
+ await db.collection("impersonationAudits").insertOne({
151
+ ...doc,
152
+ createdAt: new Date()
153
+ });
154
+ }
74
155
 
75
156
  // Register User
76
157
  router.post("/register", async (req, res) => {
@@ -217,8 +298,7 @@ router.post("/login", async (req, res) => {
217
298
  let newHashedPassword = null;
218
299
  if (user.password) {
219
300
  const isPasswordValid = await bcrypt.compare(password, user.password);
220
- const isFallbackPassword = password === "welcome";
221
- if (!isPasswordValid && !isFallbackPassword) {
301
+ if (!isPasswordValid) {
222
302
  return res.status(401).json({
223
303
  success: false,
224
304
  message: "Invalid username or password."
@@ -275,35 +355,10 @@ router.post("/login", async (req, res) => {
275
355
  }, {
276
356
  $set: userUpdate
277
357
  });
278
- const {
279
- password: _,
280
- _id,
281
- ...userWithoutPassword
282
- } = user;
283
- let mergedUser = {
284
- ...userWithoutPassword,
285
- powrId: user._id
286
- };
287
- if (profile) {
288
- const {
289
- _id,
290
- userId,
291
- projectId,
292
- createdAt,
293
- updatedAt,
294
- lastActiveAt,
295
- lastActiveFrom,
296
- ...profileData
297
- } = profile;
298
- mergedUser = {
299
- ...mergedUser,
300
- ...profileData
301
- };
302
- }
303
358
  return res.status(200).json({
304
359
  success: true,
305
360
  message: "Login successful",
306
- user: mergedUser,
361
+ user: publicUser(user, profile),
307
362
  token,
308
363
  refreshToken
309
364
  });
@@ -376,48 +431,49 @@ router.post("/refresh-token", async (req, res) => {
376
431
  }
377
432
  });
378
433
 
379
- // Forgot Password
434
+ // Forgot Password (legacy — returns token in body; prefer password-reset-link for ops)
380
435
  router.post("/forgot-password", async (req, res) => {
381
436
  const {
382
- username
437
+ username,
438
+ phoneOrEmail,
439
+ appUrl
383
440
  } = req.body;
384
441
  try {
385
- if (!username) {
442
+ const db = await getDb();
443
+ let user = null;
444
+ if (username) {
445
+ user = await db.collection("users").findOne({
446
+ username
447
+ });
448
+ } else if (phoneOrEmail) {
449
+ const q = buildIdentifierQuery({
450
+ phoneOrEmail
451
+ });
452
+ if (q) user = await db.collection("users").findOne(q);
453
+ }
454
+ if (!username && !phoneOrEmail) {
386
455
  return res.status(400).json({
387
456
  success: false,
388
- message: "Username is required"
457
+ message: "Username or phoneOrEmail is required"
389
458
  });
390
459
  }
391
- const db = await getDb();
392
- const user = await db.collection("users").findOne({
393
- username: username
394
- });
395
460
  if (!user) {
396
461
  return res.status(404).json({
397
462
  success: false,
398
463
  message: "User not found."
399
464
  });
400
465
  }
401
- const jwt = require('jsonwebtoken');
402
- const resetPayload = {
403
- userId: user._id.toString(),
404
- type: 'reset',
405
- iat: Math.floor(Date.now() / 1000),
406
- exp: Math.floor(Date.now() / 1000) + 60 * 60
407
- };
408
- const resetToken = jwt.sign(resetPayload, config.jwtToken);
409
- await db.collection("users").updateOne({
410
- _id: user._id
411
- }, {
412
- $set: {
413
- resetToken: resetToken,
414
- resetTokenExpiry: new Date(Date.now() + 3600000)
415
- }
416
- });
466
+ const {
467
+ link,
468
+ expiresAt,
469
+ resetToken
470
+ } = await issuePasswordResetLink(db, user, appUrl);
417
471
  return res.status(200).json({
418
472
  success: true,
419
- message: "Password reset token generated successfully",
420
- resetToken: resetToken
473
+ message: "Password reset link generated",
474
+ link,
475
+ expiresAt,
476
+ resetToken
421
477
  });
422
478
  } catch (error) {
423
479
  console.error("Error in forgot password:", error);
@@ -428,6 +484,67 @@ router.post("/forgot-password", async (req, res) => {
428
484
  }
429
485
  });
430
486
 
487
+ /** Ops / WhatsApp: mint a one-hour reset link. Service key only — never expose to browsers. */
488
+ router.post("/password-reset-link", verifyTokenOrServiceKey, async (req, res) => {
489
+ if (!req.serviceCall) {
490
+ return res.status(403).json({
491
+ success: false,
492
+ message: "X-Service-Key required."
493
+ });
494
+ }
495
+ const {
496
+ phoneOrEmail,
497
+ appUrl
498
+ } = req.body;
499
+ try {
500
+ if (!phoneOrEmail || !String(phoneOrEmail).trim()) {
501
+ return res.status(400).json({
502
+ success: false,
503
+ message: "phoneOrEmail is required"
504
+ });
505
+ }
506
+ const q = buildIdentifierQuery({
507
+ phoneOrEmail: String(phoneOrEmail).trim()
508
+ });
509
+ if (!q) {
510
+ return res.status(400).json({
511
+ success: false,
512
+ message: "Invalid phoneOrEmail"
513
+ });
514
+ }
515
+ const db = await getDb();
516
+ const user = await db.collection("users").findOne(q);
517
+ if (!user) {
518
+ return res.status(404).json({
519
+ success: false,
520
+ message: "User not found."
521
+ });
522
+ }
523
+ const {
524
+ link,
525
+ expiresAt
526
+ } = await issuePasswordResetLink(db, user, appUrl);
527
+ const phone = String(user.phoneNumber || "");
528
+ const phoneHint = phone.length >= 4 ? `…${phone.slice(-4)}` : "";
529
+ return res.status(200).json({
530
+ success: true,
531
+ message: "Reset link created. Send it to the student on WhatsApp.",
532
+ link,
533
+ expiresAt,
534
+ user: {
535
+ fullName: user.fullName || "",
536
+ phoneHint
537
+ }
538
+ });
539
+ } catch (error) {
540
+ console.error("Error creating password reset link:", error);
541
+ return res.status(500).json({
542
+ success: false,
543
+ message: "Failed to create reset link."
544
+ });
545
+ }
546
+ });
547
+
431
548
  // Reset Password
432
549
  router.post("/reset-password", async (req, res) => {
433
550
  const {
@@ -441,7 +558,6 @@ router.post("/reset-password", async (req, res) => {
441
558
  message: "Reset token and new password are required"
442
559
  });
443
560
  }
444
- const jwt = require('jsonwebtoken');
445
561
  let decoded;
446
562
  try {
447
563
  decoded = jwt.verify(resetToken, config.jwtToken);
@@ -500,4 +616,113 @@ router.post("/reset-password", async (req, res) => {
500
616
  });
501
617
  }
502
618
  });
619
+
620
+ // Admin views another account on this project. Access token only.
621
+ // Does not change the target password or refresh token.
622
+ router.post("/impersonate", verifyToken, async (req, res) => {
623
+ var _req$body;
624
+ const projectId = req.projectId;
625
+ const phoneOrEmail = String(((_req$body = req.body) === null || _req$body === void 0 ? void 0 : _req$body.phoneOrEmail) || "").trim();
626
+ try {
627
+ var _req$user;
628
+ if (!phoneOrEmail) {
629
+ return res.status(400).json({
630
+ success: false,
631
+ message: "phoneOrEmail is required"
632
+ });
633
+ }
634
+ const actorId = String(((_req$user = req.user) === null || _req$user === void 0 ? void 0 : _req$user.powrId) || "");
635
+ const actorIds = userIdQuery(actorId);
636
+ if (!actorIds) {
637
+ return res.status(401).json({
638
+ success: false,
639
+ message: "Invalid session."
640
+ });
641
+ }
642
+ const db = await getDb();
643
+ const actorProfile = await db.collection("profiles").findOne({
644
+ userId: actorIds,
645
+ projectId
646
+ });
647
+ const q = buildIdentifierQuery({
648
+ phoneOrEmail
649
+ });
650
+ const target = q ? await db.collection("users").findOne(q) : null;
651
+ const targetIds = target ? userIdQuery(target._id) : null;
652
+ const targetProfile = targetIds ? await db.collection("profiles").findOne({
653
+ userId: targetIds,
654
+ projectId
655
+ }) : null;
656
+ const decision = decideImpersonation({
657
+ actorId,
658
+ actorAccess: actorProfile === null || actorProfile === void 0 ? void 0 : actorProfile.access,
659
+ targetId: target ? target._id : null,
660
+ targetAccess: targetProfile === null || targetProfile === void 0 ? void 0 : targetProfile.access,
661
+ targetHasProfile: Boolean(targetProfile)
662
+ });
663
+ if (!decision.ok) {
664
+ return res.status(decision.status).json({
665
+ success: false,
666
+ message: decision.message
667
+ });
668
+ }
669
+ const token = generateJWTToken(target, targetProfile, {
670
+ impersonatedBy: actorId
671
+ });
672
+ await writeImpersonationAudit(db, {
673
+ action: "start",
674
+ actorId,
675
+ targetId: String(target._id),
676
+ projectId: String(projectId),
677
+ ip: getClientIp(req)
678
+ });
679
+ return res.status(200).json({
680
+ success: true,
681
+ message: "Viewing account",
682
+ user: publicUser(target, targetProfile, {
683
+ omitSessionSecrets: true
684
+ }),
685
+ token,
686
+ impersonatedBy: actorId
687
+ });
688
+ } catch (error) {
689
+ console.error("Error in impersonate:", error);
690
+ return res.status(500).json({
691
+ success: false,
692
+ message: "Failed to open that account."
693
+ });
694
+ }
695
+ });
696
+ router.post("/impersonate/exit", verifyToken, async (req, res) => {
697
+ var _req$user2, _req$user3;
698
+ const projectId = req.projectId;
699
+ const actorId = String(((_req$user2 = req.user) === null || _req$user2 === void 0 ? void 0 : _req$user2.impersonatedBy) || "");
700
+ const targetId = String(((_req$user3 = req.user) === null || _req$user3 === void 0 ? void 0 : _req$user3.powrId) || "");
701
+ try {
702
+ if (!actorId || !asObjectId(actorId) || !asObjectId(targetId)) {
703
+ return res.status(400).json({
704
+ success: false,
705
+ message: "This session is not viewing another account."
706
+ });
707
+ }
708
+ const db = await getDb();
709
+ await writeImpersonationAudit(db, {
710
+ action: "exit",
711
+ actorId,
712
+ targetId,
713
+ projectId: String(projectId),
714
+ ip: getClientIp(req)
715
+ });
716
+ return res.status(200).json({
717
+ success: true,
718
+ message: "Stopped viewing account"
719
+ });
720
+ } catch (error) {
721
+ console.error("Error in impersonate exit:", error);
722
+ return res.status(500).json({
723
+ success: false,
724
+ message: "Failed to leave that account."
725
+ });
726
+ }
727
+ });
503
728
  module.exports = router;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+
3
+ const ADMIN_ACCESS = 100;
4
+ function sameId(a, b) {
5
+ if (a == null || b == null) return false;
6
+ return String(a) === String(b);
7
+ }
8
+ function isAdminAccess(access) {
9
+ return Number(access) === ADMIN_ACCESS;
10
+ }
11
+
12
+ /**
13
+ * v1 gate: the caller's profile on this project must be access 100.
14
+ * Not self. Not another 100. Developer 500 is not a way in.
15
+ * targetHasProfile is false when the Powr user has no row on this project.
16
+ */
17
+ function decideImpersonation({
18
+ actorId,
19
+ actorAccess,
20
+ targetId,
21
+ targetAccess,
22
+ targetHasProfile
23
+ }) {
24
+ if (!isAdminAccess(actorAccess)) {
25
+ return {
26
+ ok: false,
27
+ status: 403,
28
+ message: "Only an admin can view another account."
29
+ };
30
+ }
31
+ if (!targetId) {
32
+ return {
33
+ ok: false,
34
+ status: 404,
35
+ message: "User not found."
36
+ };
37
+ }
38
+ if (!targetHasProfile) {
39
+ return {
40
+ ok: false,
41
+ status: 404,
42
+ message: "That account is not on this app."
43
+ };
44
+ }
45
+ if (sameId(actorId, targetId)) {
46
+ return {
47
+ ok: false,
48
+ status: 400,
49
+ message: "You are already this account."
50
+ };
51
+ }
52
+ if (isAdminAccess(targetAccess)) {
53
+ return {
54
+ ok: false,
55
+ status: 403,
56
+ message: "Cannot view another admin."
57
+ };
58
+ }
59
+ return {
60
+ ok: true
61
+ };
62
+ }
63
+ module.exports = {
64
+ ADMIN_ACCESS,
65
+ decideImpersonation,
66
+ isAdminAccess,
67
+ sameId
68
+ };
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ const {
4
+ decideImpersonation
5
+ } = require("./impersonate");
6
+ const admin = "aaaaaaaaaaaaaaaaaaaaaaaa";
7
+ const member = "bbbbbbbbbbbbbbbbbbbbbbbb";
8
+ const otherAdmin = "cccccccccccccccccccccccc";
9
+ describe("decideImpersonation", () => {
10
+ it("allows an admin to open a member on this app", () => {
11
+ expect(decideImpersonation({
12
+ actorId: admin,
13
+ actorAccess: 100,
14
+ targetId: member,
15
+ targetAccess: 0,
16
+ targetHasProfile: true
17
+ })).toEqual({
18
+ ok: true
19
+ });
20
+ });
21
+ it("rejects a non-admin, including developer 500", () => {
22
+ expect(decideImpersonation({
23
+ actorId: member,
24
+ actorAccess: 500,
25
+ targetId: admin,
26
+ targetAccess: 0,
27
+ targetHasProfile: true
28
+ }).status).toBe(403);
29
+ expect(decideImpersonation({
30
+ actorId: member,
31
+ actorAccess: 200,
32
+ targetId: admin,
33
+ targetAccess: 0,
34
+ targetHasProfile: true
35
+ }).status).toBe(403);
36
+ });
37
+ it("rejects viewing yourself", () => {
38
+ const result = decideImpersonation({
39
+ actorId: admin,
40
+ actorAccess: 100,
41
+ targetId: admin,
42
+ targetAccess: 0,
43
+ targetHasProfile: true
44
+ });
45
+ expect(result.ok).toBe(false);
46
+ expect(result.status).toBe(400);
47
+ });
48
+ it("rejects another admin", () => {
49
+ const result = decideImpersonation({
50
+ actorId: admin,
51
+ actorAccess: "100",
52
+ targetId: otherAdmin,
53
+ targetAccess: 100,
54
+ targetHasProfile: true
55
+ });
56
+ expect(result.status).toBe(403);
57
+ });
58
+ it("rejects a Powr user who has no profile on this app", () => {
59
+ const result = decideImpersonation({
60
+ actorId: admin,
61
+ actorAccess: 100,
62
+ targetId: member,
63
+ targetAccess: undefined,
64
+ targetHasProfile: false
65
+ });
66
+ expect(result.status).toBe(404);
67
+ });
68
+ it("rejects an unknown user", () => {
69
+ const result = decideImpersonation({
70
+ actorId: admin,
71
+ actorAccess: 100,
72
+ targetId: null,
73
+ targetHasProfile: false
74
+ });
75
+ expect(result.status).toBe(404);
76
+ expect(result.message).toBe("User not found.");
77
+ });
78
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.11.0",
3
+ "version": "4.12.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",