powr-sdk-api 4.11.2 → 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) {
@@ -4,12 +4,12 @@ const {
4
4
  config
5
5
  } = require('../config');
6
6
 
7
- /**
8
- * Middleware to inject and validate projectId into requests
9
- * @param {Object} options - Configuration options
10
- * @param {boolean} options.isCentralService - Whether this is a central service (like powr-base-cloud)
11
- * @param {Array} options.excludePaths - Array of paths to exclude from projectId validation
12
- * @returns {Function} Express middleware function
7
+ /**
8
+ * Middleware to inject and validate projectId into requests
9
+ * @param {Object} options - Configuration options
10
+ * @param {boolean} options.isCentralService - Whether this is a central service (like powr-base-cloud)
11
+ * @param {Array} options.excludePaths - Array of paths to exclude from projectId validation
12
+ * @returns {Function} Express middleware function
13
13
  */
14
14
  const injectProjectId = (options = {}) => {
15
15
  const isCentralService = options.isCentralService || false;
@@ -13,9 +13,9 @@ function safeEqual(a, b) {
13
13
  return crypto.timingSafeEqual(left, right);
14
14
  }
15
15
 
16
- /**
17
- * Accept a user JWT or X-Service-Key (project-to-project).
18
- * Service key is POWR_SERVICE_KEY (SERVICE_KEY alias). JWT path unchanged.
16
+ /**
17
+ * Accept a user JWT or X-Service-Key (project-to-project).
18
+ * Service key is POWR_SERVICE_KEY (SERVICE_KEY alias). JWT path unchanged.
19
19
  */
20
20
  const verifyTokenOrServiceKey = async (req, res, next) => {
21
21
  const provided = req.get("X-Service-Key");
@@ -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
@@ -27,6 +28,9 @@ const {
27
28
  const {
28
29
  verifyTokenOrServiceKey
29
30
  } = require("../middleware/serviceKey");
31
+ const {
32
+ decideImpersonation
33
+ } = require("../utils/impersonate");
30
34
  const jwt = require("jsonwebtoken");
31
35
  async function issuePasswordResetLink(db, user, appUrl) {
32
36
  const resetPayload = {
@@ -100,6 +104,54 @@ function resolveStoredContact(phoneOrEmail) {
100
104
  phoneNumber
101
105
  };
102
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
+ }
103
155
 
104
156
  // Register User
105
157
  router.post("/register", async (req, res) => {
@@ -303,35 +355,10 @@ router.post("/login", async (req, res) => {
303
355
  }, {
304
356
  $set: userUpdate
305
357
  });
306
- const {
307
- password: _,
308
- _id,
309
- ...userWithoutPassword
310
- } = user;
311
- let mergedUser = {
312
- ...userWithoutPassword,
313
- powrId: user._id
314
- };
315
- if (profile) {
316
- const {
317
- _id,
318
- userId,
319
- projectId,
320
- createdAt,
321
- updatedAt,
322
- lastActiveAt,
323
- lastActiveFrom,
324
- ...profileData
325
- } = profile;
326
- mergedUser = {
327
- ...mergedUser,
328
- ...profileData
329
- };
330
- }
331
358
  return res.status(200).json({
332
359
  success: true,
333
360
  message: "Login successful",
334
- user: mergedUser,
361
+ user: publicUser(user, profile),
335
362
  token,
336
363
  refreshToken
337
364
  });
@@ -589,4 +616,113 @@ router.post("/reset-password", async (req, res) => {
589
616
  });
590
617
  }
591
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
+ });
592
728
  module.exports = router;
@@ -9,15 +9,15 @@ const {
9
9
  } = require("../services/mongo");
10
10
  const router = express.Router();
11
11
 
12
- /**
13
- * User preferences on PowrBase — `/users/me/preferences`.
14
- *
15
- * One doc per (userId, projectId). A second doc with `projectId: null` is the
16
- * user-global fallback (today only `theme.scheme` is mirrored there, so
17
- * light/dark follows the user into a new app before they ever open Settings).
18
- *
19
- * Powr JWT only (mounted with verifyToken). Never a service-key write; never
20
- * a product table. Products read/write through the SDK.
12
+ /**
13
+ * User preferences on PowrBase — `/users/me/preferences`.
14
+ *
15
+ * One doc per (userId, projectId). A second doc with `projectId: null` is the
16
+ * user-global fallback (today only `theme.scheme` is mirrored there, so
17
+ * light/dark follows the user into a new app before they ever open Settings).
18
+ *
19
+ * Powr JWT only (mounted with verifyToken). Never a service-key write; never
20
+ * a product table. Products read/write through the SDK.
21
21
  */
22
22
 
23
23
  const COLLECTION = "preferences";
@@ -14,8 +14,8 @@ const storage = new Storage({
14
14
  }
15
15
  });
16
16
 
17
- /**
18
- * Custom Winston transport for logging to Google Cloud Storage
17
+ /**
18
+ * Custom Winston transport for logging to Google Cloud Storage
19
19
  */
20
20
  class GCSTransport extends winston.Transport {
21
21
  constructor(opts) {
@@ -15,8 +15,8 @@ const s3Client = new S3Client({
15
15
  }
16
16
  });
17
17
 
18
- /**
19
- * Custom Winston transport for logging to S3
18
+ /**
19
+ * Custom Winston transport for logging to S3
20
20
  */
21
21
  class S3Transport extends winston.Transport {
22
22
  constructor(opts) {
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
 
3
- /**
4
- * Swagger configuration for Express applications
3
+ /**
4
+ * Swagger configuration for Express applications
5
5
  */
6
6
 
7
7
  const swaggerJsdoc = require('swagger-jsdoc');
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
 
3
- /**
4
- * Best-effort client IP from the incoming HTTP request
5
- * (uses X-Forwarded-For, X-Real-IP, req.ip, or socket address).
3
+ /**
4
+ * Best-effort client IP from the incoming HTTP request
5
+ * (uses X-Forwarded-For, X-Real-IP, req.ip, or socket address).
6
6
  */
7
7
  function getClientIp(req) {
8
8
  const forwarded = req.headers["x-forwarded-for"];
@@ -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
+ });
@@ -39,10 +39,10 @@ function normalizePhone(input, defaultCountry = DEFAULT_COUNTRY) {
39
39
  return parsed ? parsed.format('E.164') : '';
40
40
  }
41
41
 
42
- /**
43
- * Normalize a phone for DB storage. When the input has trailing junk
44
- * (e.g. "7903658469 welcome"), extracts digits and parses those.
45
- * Returns null when no valid phone can be derived — never returns raw input.
42
+ /**
43
+ * Normalize a phone for DB storage. When the input has trailing junk
44
+ * (e.g. "7903658469 welcome"), extracts digits and parses those.
45
+ * Returns null when no valid phone can be derived — never returns raw input.
46
46
  */
47
47
  function coercePhoneForStorage(input, defaultCountry = DEFAULT_COUNTRY) {
48
48
  if (!input || typeof input !== 'string') return null;
@@ -18,9 +18,9 @@ function phoneVariants(raw) {
18
18
  return getPhoneLookupVariants(String(raw || "").trim()).filter(Boolean);
19
19
  }
20
20
 
21
- /**
22
- * Build a users collection filter from query params.
23
- * Service calls must pass a lookup (no full-table scan).
21
+ /**
22
+ * Build a users collection filter from query params.
23
+ * Service calls must pass a lookup (no full-table scan).
24
24
  */
25
25
  function buildUsersFilter(query = {}, {
26
26
  requireLookup = false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.11.2",
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",