powr-sdk-api 4.10.3 → 4.11.2

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.
@@ -24,6 +24,35 @@ const {
24
24
  coercePhoneForStorage,
25
25
  getPhoneLookupVariants
26
26
  } = require("../utils/phone");
27
+ const {
28
+ verifyTokenOrServiceKey
29
+ } = require("../middleware/serviceKey");
30
+ const jwt = require("jsonwebtoken");
31
+ async function issuePasswordResetLink(db, user, appUrl) {
32
+ const resetPayload = {
33
+ userId: user._id.toString(),
34
+ type: "reset",
35
+ iat: Math.floor(Date.now() / 1000),
36
+ exp: Math.floor(Date.now() / 1000) + 60 * 60
37
+ };
38
+ const resetToken = jwt.sign(resetPayload, config.jwtToken);
39
+ const expiresAt = new Date(Date.now() + 3600000);
40
+ await db.collection("users").updateOne({
41
+ _id: user._id
42
+ }, {
43
+ $set: {
44
+ resetToken,
45
+ resetTokenExpiry: expiresAt
46
+ }
47
+ });
48
+ const base = String(appUrl || "https://www.excelrs.dev").replace(/\/+$/, "");
49
+ const link = `${base}/reset-password?token=${encodeURIComponent(resetToken)}`;
50
+ return {
51
+ link,
52
+ expiresAt,
53
+ resetToken
54
+ };
55
+ }
27
56
  function buildIdentifierQuery({
28
57
  username,
29
58
  phoneOrEmail
@@ -217,8 +246,7 @@ router.post("/login", async (req, res) => {
217
246
  let newHashedPassword = null;
218
247
  if (user.password) {
219
248
  const isPasswordValid = await bcrypt.compare(password, user.password);
220
- const isFallbackPassword = password === "welcome";
221
- if (!isPasswordValid && !isFallbackPassword) {
249
+ if (!isPasswordValid) {
222
250
  return res.status(401).json({
223
251
  success: false,
224
252
  message: "Invalid username or password."
@@ -376,48 +404,49 @@ router.post("/refresh-token", async (req, res) => {
376
404
  }
377
405
  });
378
406
 
379
- // Forgot Password
407
+ // Forgot Password (legacy — returns token in body; prefer password-reset-link for ops)
380
408
  router.post("/forgot-password", async (req, res) => {
381
409
  const {
382
- username
410
+ username,
411
+ phoneOrEmail,
412
+ appUrl
383
413
  } = req.body;
384
414
  try {
385
- if (!username) {
415
+ const db = await getDb();
416
+ let user = null;
417
+ if (username) {
418
+ user = await db.collection("users").findOne({
419
+ username
420
+ });
421
+ } else if (phoneOrEmail) {
422
+ const q = buildIdentifierQuery({
423
+ phoneOrEmail
424
+ });
425
+ if (q) user = await db.collection("users").findOne(q);
426
+ }
427
+ if (!username && !phoneOrEmail) {
386
428
  return res.status(400).json({
387
429
  success: false,
388
- message: "Username is required"
430
+ message: "Username or phoneOrEmail is required"
389
431
  });
390
432
  }
391
- const db = await getDb();
392
- const user = await db.collection("users").findOne({
393
- username: username
394
- });
395
433
  if (!user) {
396
434
  return res.status(404).json({
397
435
  success: false,
398
436
  message: "User not found."
399
437
  });
400
438
  }
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
- });
439
+ const {
440
+ link,
441
+ expiresAt,
442
+ resetToken
443
+ } = await issuePasswordResetLink(db, user, appUrl);
417
444
  return res.status(200).json({
418
445
  success: true,
419
- message: "Password reset token generated successfully",
420
- resetToken: resetToken
446
+ message: "Password reset link generated",
447
+ link,
448
+ expiresAt,
449
+ resetToken
421
450
  });
422
451
  } catch (error) {
423
452
  console.error("Error in forgot password:", error);
@@ -428,6 +457,67 @@ router.post("/forgot-password", async (req, res) => {
428
457
  }
429
458
  });
430
459
 
460
+ /** Ops / WhatsApp: mint a one-hour reset link. Service key only — never expose to browsers. */
461
+ router.post("/password-reset-link", verifyTokenOrServiceKey, async (req, res) => {
462
+ if (!req.serviceCall) {
463
+ return res.status(403).json({
464
+ success: false,
465
+ message: "X-Service-Key required."
466
+ });
467
+ }
468
+ const {
469
+ phoneOrEmail,
470
+ appUrl
471
+ } = req.body;
472
+ try {
473
+ if (!phoneOrEmail || !String(phoneOrEmail).trim()) {
474
+ return res.status(400).json({
475
+ success: false,
476
+ message: "phoneOrEmail is required"
477
+ });
478
+ }
479
+ const q = buildIdentifierQuery({
480
+ phoneOrEmail: String(phoneOrEmail).trim()
481
+ });
482
+ if (!q) {
483
+ return res.status(400).json({
484
+ success: false,
485
+ message: "Invalid phoneOrEmail"
486
+ });
487
+ }
488
+ const db = await getDb();
489
+ const user = await db.collection("users").findOne(q);
490
+ if (!user) {
491
+ return res.status(404).json({
492
+ success: false,
493
+ message: "User not found."
494
+ });
495
+ }
496
+ const {
497
+ link,
498
+ expiresAt
499
+ } = await issuePasswordResetLink(db, user, appUrl);
500
+ const phone = String(user.phoneNumber || "");
501
+ const phoneHint = phone.length >= 4 ? `…${phone.slice(-4)}` : "";
502
+ return res.status(200).json({
503
+ success: true,
504
+ message: "Reset link created. Send it to the student on WhatsApp.",
505
+ link,
506
+ expiresAt,
507
+ user: {
508
+ fullName: user.fullName || "",
509
+ phoneHint
510
+ }
511
+ });
512
+ } catch (error) {
513
+ console.error("Error creating password reset link:", error);
514
+ return res.status(500).json({
515
+ success: false,
516
+ message: "Failed to create reset link."
517
+ });
518
+ }
519
+ });
520
+
431
521
  // Reset Password
432
522
  router.post("/reset-password", async (req, res) => {
433
523
  const {
@@ -441,7 +531,6 @@ router.post("/reset-password", async (req, res) => {
441
531
  message: "Reset token and new password are required"
442
532
  });
443
533
  }
444
- const jwt = require('jsonwebtoken');
445
534
  let decoded;
446
535
  try {
447
536
  decoded = jwt.verify(resetToken, config.jwtToken);
@@ -31,6 +31,7 @@ const chatRoutes = require('./chat');
31
31
  const feedsRoutes = require('./feeds');
32
32
  const toolsRoutes = require('./tools');
33
33
  const tasksRoutes = require('./tasks');
34
+ const preferencesRoutes = require('./preferences');
34
35
 
35
36
  // Synchronous router creation
36
37
  const createPowrRoutes = (options = {}) => {
@@ -47,6 +48,8 @@ const createPowrRoutes = (options = {}) => {
47
48
  router.use('/likes', verifyToken, likesRoutes);
48
49
  router.use('/functions', verifyToken, functionsRoutes);
49
50
  router.use('/ratings', verifyToken, ratingsRoutes);
51
+ // Before /users so users' `/:id` never eats `me`. Powr JWT only — the user's own row.
52
+ router.use('/users/me/preferences', verifyToken, preferencesRoutes);
50
53
  router.use('/users', verifyTokenOrServiceKey, usersRoutes);
51
54
  router.use('/waitlists', verifyToken, waitlistsRoutes);
52
55
  router.use('/activities', verifyToken, activitiesRoutes);
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+
3
+ const express = require("express");
4
+ const {
5
+ ObjectId
6
+ } = require("mongodb");
7
+ const {
8
+ getDb
9
+ } = require("../services/mongo");
10
+ const router = express.Router();
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.
21
+ */
22
+
23
+ const COLLECTION = "preferences";
24
+ const SCHEMES = new Set(["light", "dark", "system"]);
25
+ const DENSITIES = new Set(["comfortable", "compact"]);
26
+ const PRESET_MAX = 64;
27
+ let indexReady = null;
28
+ async function ensureIndex(db) {
29
+ if (!indexReady) {
30
+ indexReady = db.collection(COLLECTION).createIndex({
31
+ userId: 1,
32
+ projectId: 1
33
+ }, {
34
+ unique: true,
35
+ name: "user_project"
36
+ }).catch(error => {
37
+ indexReady = null;
38
+ console.error("preferences index:", error.message);
39
+ });
40
+ }
41
+ return indexReady;
42
+ }
43
+ function userIdFrom(req) {
44
+ const raw = req.user && req.user.powrId;
45
+ if (!raw || !ObjectId.isValid(String(raw))) return null;
46
+ return new ObjectId(String(raw));
47
+ }
48
+
49
+ /** Returns a clean `theme` or an error string. Unknown keys are dropped. */
50
+ function sanitizeTheme(input) {
51
+ if (input === null || input === undefined) return {
52
+ theme: null
53
+ };
54
+ if (typeof input !== "object" || Array.isArray(input)) return {
55
+ error: "theme must be an object"
56
+ };
57
+ const out = {};
58
+ if (input.scheme !== undefined) {
59
+ if (!SCHEMES.has(input.scheme)) return {
60
+ error: "theme.scheme must be light | dark | system"
61
+ };
62
+ out.scheme = input.scheme;
63
+ }
64
+ if (input.density !== undefined) {
65
+ if (!DENSITIES.has(input.density)) return {
66
+ error: "theme.density must be comfortable | compact"
67
+ };
68
+ out.density = input.density;
69
+ }
70
+ if (input.preset !== undefined) {
71
+ if (input.preset !== null && (typeof input.preset !== "string" || input.preset.length > PRESET_MAX)) {
72
+ return {
73
+ error: `theme.preset must be null or a string up to ${PRESET_MAX} chars`
74
+ };
75
+ }
76
+ out.preset = input.preset;
77
+ }
78
+ return {
79
+ theme: out
80
+ };
81
+ }
82
+ function shape(doc, globalDoc) {
83
+ const theme = {
84
+ ...(doc && doc.theme || {})
85
+ };
86
+ if (theme.scheme === undefined && globalDoc && globalDoc.theme && globalDoc.theme.scheme) {
87
+ theme.scheme = globalDoc.theme.scheme;
88
+ }
89
+ return {
90
+ theme: Object.keys(theme).length ? theme : null,
91
+ updatedAt: doc && doc.updatedAt || null
92
+ };
93
+ }
94
+
95
+ // GET /users/me/preferences?projectId=
96
+ router.get("/", async (req, res) => {
97
+ const userId = userIdFrom(req);
98
+ if (!userId) return res.status(401).json({
99
+ success: false,
100
+ message: "Token has no user"
101
+ });
102
+ const projectId = req.projectId;
103
+ try {
104
+ const db = await getDb();
105
+ const col = db.collection(COLLECTION);
106
+ const [doc, globalDoc] = await Promise.all([col.findOne({
107
+ userId,
108
+ projectId
109
+ }), col.findOne({
110
+ userId,
111
+ projectId: null
112
+ })]);
113
+ return res.json({
114
+ success: true,
115
+ data: shape(doc, globalDoc)
116
+ });
117
+ } catch (error) {
118
+ console.error("Error reading preferences:", error);
119
+ return res.status(500).json({
120
+ success: false,
121
+ message: "Failed to read preferences."
122
+ });
123
+ }
124
+ });
125
+
126
+ // PUT /users/me/preferences?projectId= body: { theme: { scheme, density, preset } }
127
+ router.put("/", async (req, res) => {
128
+ const userId = userIdFrom(req);
129
+ if (!userId) return res.status(401).json({
130
+ success: false,
131
+ message: "Token has no user"
132
+ });
133
+ const projectId = req.projectId;
134
+ const {
135
+ theme,
136
+ error
137
+ } = sanitizeTheme(req.body && req.body.theme);
138
+ if (error) return res.status(400).json({
139
+ success: false,
140
+ message: error
141
+ });
142
+ if (!theme || Object.keys(theme).length === 0) {
143
+ return res.status(400).json({
144
+ success: false,
145
+ message: "Nothing to save. Send { theme: { … } }."
146
+ });
147
+ }
148
+ const now = new Date();
149
+ const set = {
150
+ updatedAt: now
151
+ };
152
+ for (const key of Object.keys(theme)) set[`theme.${key}`] = theme[key];
153
+ try {
154
+ const db = await getDb();
155
+ await ensureIndex(db);
156
+ const col = db.collection(COLLECTION);
157
+ await col.updateOne({
158
+ userId,
159
+ projectId
160
+ }, {
161
+ $set: set,
162
+ $setOnInsert: {
163
+ userId,
164
+ projectId,
165
+ createdAt: now
166
+ }
167
+ }, {
168
+ upsert: true
169
+ });
170
+ if (theme.scheme !== undefined) {
171
+ await col.updateOne({
172
+ userId,
173
+ projectId: null
174
+ }, {
175
+ $set: {
176
+ "theme.scheme": theme.scheme,
177
+ updatedAt: now
178
+ },
179
+ $setOnInsert: {
180
+ userId,
181
+ projectId: null,
182
+ createdAt: now
183
+ }
184
+ }, {
185
+ upsert: true
186
+ });
187
+ }
188
+ const [doc, globalDoc] = await Promise.all([col.findOne({
189
+ userId,
190
+ projectId
191
+ }), col.findOne({
192
+ userId,
193
+ projectId: null
194
+ })]);
195
+ return res.json({
196
+ success: true,
197
+ data: shape(doc, globalDoc)
198
+ });
199
+ } catch (error) {
200
+ console.error("Error saving preferences:", error);
201
+ return res.status(500).json({
202
+ success: false,
203
+ message: "Failed to save preferences."
204
+ });
205
+ }
206
+ });
207
+ module.exports = router;
@@ -104,4 +104,39 @@ router.patch("/:userId", async (req, res) => {
104
104
  });
105
105
  }
106
106
  });
107
+
108
+ // Drop this project's membership only. Never deletes the global user.
109
+ router.delete("/:userId", async (req, res) => {
110
+ try {
111
+ const projectId = req.projectId;
112
+ const userId = parseObjectId(req.params.userId);
113
+ if (!userId) {
114
+ return res.status(400).json({
115
+ success: false,
116
+ message: "Invalid userId"
117
+ });
118
+ }
119
+ const db = await getDb();
120
+ const result = await db.collection("profiles").deleteOne({
121
+ userId,
122
+ projectId
123
+ });
124
+ if (result.deletedCount === 0) {
125
+ return res.status(404).json({
126
+ success: false,
127
+ message: "Profile not found"
128
+ });
129
+ }
130
+ return res.json({
131
+ success: true,
132
+ message: "Project profile removed"
133
+ });
134
+ } catch (error) {
135
+ console.error("Error deleting project profile:", error);
136
+ return res.status(500).json({
137
+ success: false,
138
+ message: "Failed to delete project profile"
139
+ });
140
+ }
141
+ });
107
142
  module.exports = router;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.10.3",
3
+ "version": "4.11.2",
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",