powr-sdk-api 4.11.0 → 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.
@@ -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");
@@ -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);
@@ -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"];
@@ -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.0",
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",