powr-sdk-api 4.9.5 → 4.10.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.
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+
3
+ const jwt = require("jsonwebtoken");
4
+ const {
5
+ ObjectId
6
+ } = require("mongodb");
7
+ const {
8
+ config
9
+ } = require("../config");
10
+ const {
11
+ getDb
12
+ } = require("../services/mongo");
13
+ const {
14
+ coercePhoneForStorage,
15
+ getPhoneLookupVariants
16
+ } = require("../utils/phone");
17
+ function readBearer(req) {
18
+ const authHeader = req.headers.authorization;
19
+ if (!authHeader) return null;
20
+ return authHeader.startsWith("Bearer ") ? authHeader.slice(7) : authHeader;
21
+ }
22
+ function decodeToken(token) {
23
+ try {
24
+ return jwt.verify(token, config.jwtToken);
25
+ } catch (error) {
26
+ if (error.name !== "TokenExpiredError") throw error;
27
+ const decoded = jwt.verify(token, config.jwtToken, {
28
+ ignoreExpiration: true
29
+ });
30
+ if (decoded.userId && !decoded.phone_number && !decoded.mobile) {
31
+ const expired = new Error("Token expired");
32
+ expired.status = 401;
33
+ throw expired;
34
+ }
35
+ return decoded;
36
+ }
37
+ }
38
+ async function findOrCreateByPhone(db, decoded) {
39
+ const raw = decoded.phone_number || decoded.mobile || decoded.phoneNumber;
40
+ if (!raw) {
41
+ const err = new Error("Token has no phone number");
42
+ err.status = 400;
43
+ throw err;
44
+ }
45
+ const stored = coercePhoneForStorage(raw) || String(raw).trim();
46
+ const variants = getPhoneLookupVariants(raw);
47
+ const user = await db.collection("users").findOne({
48
+ phoneNumber: {
49
+ $in: variants.length ? variants : [stored]
50
+ }
51
+ });
52
+ if (user) return user;
53
+ const digits = String(stored).replace(/\D/g, "") || Date.now().toString();
54
+ const doc = {
55
+ fullName: decoded.fullName || "User",
56
+ email: "",
57
+ phoneNumber: stored,
58
+ username: `phone_${digits}`,
59
+ createdAt: new Date(),
60
+ createdFrom: "issue-login-code"
61
+ };
62
+ const inserted = await db.collection("users").insertOne(doc);
63
+ return {
64
+ _id: inserted.insertedId,
65
+ ...doc
66
+ };
67
+ }
68
+ async function loadPowrUser(decoded) {
69
+ const db = await getDb();
70
+ if (decoded.userId) {
71
+ const user = await db.collection("users").findOne({
72
+ _id: new ObjectId(decoded.userId)
73
+ });
74
+ if (!user) {
75
+ const err = new Error("User not found");
76
+ err.status = 401;
77
+ throw err;
78
+ }
79
+ return user;
80
+ }
81
+ return findOrCreateByPhone(db, decoded);
82
+ }
83
+ async function resolvePowrUserFromToken(req, res, next) {
84
+ try {
85
+ const token = readBearer(req);
86
+ if (!token) {
87
+ return res.status(401).json({
88
+ success: false,
89
+ message: "No authorization token provided."
90
+ });
91
+ }
92
+ const decoded = decodeToken(token);
93
+ const user = await loadPowrUser(decoded);
94
+ req.user = {
95
+ powrId: user._id,
96
+ fullName: user.fullName,
97
+ access: decoded.access
98
+ };
99
+ req.powrUser = user;
100
+ return next();
101
+ } catch (error) {
102
+ return res.status(error.status || 401).json({
103
+ success: false,
104
+ message: error.message || "Invalid token"
105
+ });
106
+ }
107
+ }
108
+ module.exports = {
109
+ resolvePowrUserFromToken,
110
+ loadPowrUser,
111
+ decodeToken
112
+ };
@@ -20,6 +20,7 @@ const usersRoutes = require('./users');
20
20
  const waitlistsRoutes = require('./waitlists');
21
21
  const activitiesRoutes = require('./activities');
22
22
  const authRoutes = require('./auth');
23
+ const loginCodeRoutes = require('./loginCode');
23
24
  const slidesRoutes = require('./slides');
24
25
  const notificationsRoutes = require('./notifications');
25
26
  const profilesRoutes = require('./profiles');
@@ -34,6 +35,7 @@ const createPowrRoutes = (options = {}) => {
34
35
 
35
36
  // Use the dedicated projectId injection middleware
36
37
  router.use(injectProjectId(options));
38
+ router.use('/auth', loginCodeRoutes);
37
39
  router.use('/auth', authRoutes);
38
40
  router.use('/comments', verifyToken, commentsRoutes);
39
41
  router.use('/files', verifyToken, filesRoutes);
@@ -0,0 +1,140 @@
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 {
11
+ generateJWTToken,
12
+ generateRefreshToken
13
+ } = require("../middleware/jwtToken");
14
+ const {
15
+ resolvePowrUserFromToken
16
+ } = require("../middleware/resolvePowrUserFromToken");
17
+ const {
18
+ getClientIp
19
+ } = require("../utils/getClientIp");
20
+ const {
21
+ issueLoginCode,
22
+ consumeLoginCode
23
+ } = require("../services/loginCodes");
24
+ const router = express.Router();
25
+ async function sessionPayload(req, user, projectId) {
26
+ const db = await getDb();
27
+ let profile = await db.collection("profiles").findOne({
28
+ userId: user._id,
29
+ projectId
30
+ });
31
+ const now = new Date();
32
+ if (profile) {
33
+ await db.collection("profiles").updateOne({
34
+ _id: profile._id
35
+ }, {
36
+ $set: {
37
+ lastActiveAt: now,
38
+ lastActiveFrom: getClientIp(req)
39
+ }
40
+ });
41
+ } else if (projectId) {
42
+ const newProfile = {
43
+ userId: user._id,
44
+ projectId,
45
+ access: 1,
46
+ createdAt: now,
47
+ lastActiveAt: now,
48
+ lastActiveFrom: getClientIp(req)
49
+ };
50
+ const inserted = await db.collection("profiles").insertOne(newProfile);
51
+ profile = {
52
+ _id: inserted.insertedId,
53
+ ...newProfile
54
+ };
55
+ }
56
+ const token = generateJWTToken(user, profile);
57
+ const refreshToken = generateRefreshToken(user);
58
+ await db.collection("users").updateOne({
59
+ _id: user._id
60
+ }, {
61
+ $set: {
62
+ refreshToken
63
+ }
64
+ });
65
+ const {
66
+ password,
67
+ refreshToken: _rt,
68
+ ...safe
69
+ } = user;
70
+ let extra = {};
71
+ if (profile) {
72
+ const {
73
+ _id,
74
+ userId,
75
+ projectId: _p,
76
+ createdAt,
77
+ updatedAt,
78
+ lastActiveAt,
79
+ lastActiveFrom,
80
+ ...profileData
81
+ } = profile;
82
+ extra = profileData;
83
+ }
84
+ return {
85
+ success: true,
86
+ message: "Login successful",
87
+ user: {
88
+ ...safe,
89
+ ...extra,
90
+ powrId: user._id
91
+ },
92
+ token,
93
+ refreshToken
94
+ };
95
+ }
96
+ router.post("/issue-login-code", resolvePowrUserFromToken, async (req, res) => {
97
+ try {
98
+ const issued = await issueLoginCode({
99
+ userId: req.user.powrId,
100
+ projectId: req.projectId
101
+ });
102
+ return res.json({
103
+ success: true,
104
+ loginId: issued.loginId,
105
+ expiresAt: issued.expiresAt
106
+ });
107
+ } catch (error) {
108
+ return res.status(error.status || 500).json({
109
+ success: false,
110
+ message: error.message || "Failed to issue login code"
111
+ });
112
+ }
113
+ });
114
+ router.post("/login-with-code", async (req, res) => {
115
+ try {
116
+ const {
117
+ loginId
118
+ } = req.body || {};
119
+ const projectId = req.projectId;
120
+ const row = await consumeLoginCode(loginId, projectId);
121
+ const db = await getDb();
122
+ const user = await db.collection("users").findOne({
123
+ _id: new ObjectId(row.userId)
124
+ });
125
+ if (!user) {
126
+ return res.status(400).json({
127
+ success: false,
128
+ message: "User not found"
129
+ });
130
+ }
131
+ const payload = await sessionPayload(req, user, projectId);
132
+ return res.json(payload);
133
+ } catch (error) {
134
+ return res.status(error.status || 500).json({
135
+ success: false,
136
+ message: error.message || "Failed to login with code"
137
+ });
138
+ }
139
+ });
140
+ module.exports = router;
@@ -164,20 +164,27 @@ router.put("/:id", verifyToken, async (req, res) => {
164
164
  });
165
165
  }
166
166
 
167
- // Update user
168
- const normalizedPhone = phoneNumber && !String(phoneNumber).includes("@") ? coercePhoneForStorage(phoneNumber) : phoneNumber;
169
- if (phoneNumber && !String(phoneNumber).includes("@") && !normalizedPhone) {
170
- return res.status(400).json({
171
- success: false,
172
- message: "Invalid phone number"
173
- });
174
- }
167
+ // Only set contact fields when a real value is provided.
168
+ // Ignore undefined AND null so `{ access }` or `{ phoneNumber: null }` cannot wipe phone/email.
175
169
  const updateData = {
176
- ...userData,
177
- phoneNumber: normalizedPhone,
178
- email,
179
170
  updatedAt: new Date()
180
171
  };
172
+ for (const [key, value] of Object.entries(userData || {})) {
173
+ if (value !== undefined) updateData[key] = value;
174
+ }
175
+ if (typeof phoneNumber === "string") {
176
+ const normalizedPhone = !phoneNumber.includes("@") ? coercePhoneForStorage(phoneNumber) : phoneNumber;
177
+ if (phoneNumber && !phoneNumber.includes("@") && !normalizedPhone) {
178
+ return res.status(400).json({
179
+ success: false,
180
+ message: "Invalid phone number"
181
+ });
182
+ }
183
+ updateData.phoneNumber = normalizedPhone;
184
+ }
185
+ if (typeof email === "string") {
186
+ updateData.email = email;
187
+ }
181
188
  await db.collection("users").updateOne({
182
189
  _id: new ObjectId(id)
183
190
  }, {
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const {
5
+ ObjectId
6
+ } = require("mongodb");
7
+ const {
8
+ getDb
9
+ } = require("./mongo");
10
+ const COLLECTION = "loginCodes";
11
+ const TTL_SECONDS = 120;
12
+ function hashLoginId(loginId) {
13
+ return crypto.createHash("sha256").update(String(loginId), "utf8").digest("hex");
14
+ }
15
+ async function codes() {
16
+ const db = await getDb();
17
+ return db.collection(COLLECTION);
18
+ }
19
+ async function issueLoginCode({
20
+ userId,
21
+ projectId
22
+ }) {
23
+ const loginId = crypto.randomBytes(32).toString("hex");
24
+ const now = new Date();
25
+ const expiresAt = new Date(now.getTime() + TTL_SECONDS * 1000);
26
+ await (await codes()).insertOne({
27
+ loginIdHash: hashLoginId(loginId),
28
+ userId: typeof userId === "string" ? new ObjectId(userId) : userId,
29
+ projectId: projectId || null,
30
+ createdAt: now,
31
+ expiresAt,
32
+ usedAt: null
33
+ });
34
+ return {
35
+ loginId,
36
+ expiresAt
37
+ };
38
+ }
39
+ async function consumeLoginCode(loginId, projectId) {
40
+ if (!loginId) {
41
+ const err = new Error("loginId is required");
42
+ err.status = 400;
43
+ throw err;
44
+ }
45
+ const col = await codes();
46
+ const doc = await col.findOne({
47
+ loginIdHash: hashLoginId(loginId),
48
+ usedAt: null
49
+ });
50
+ if (!doc || doc.expiresAt && doc.expiresAt < new Date()) {
51
+ const err = new Error("Invalid or expired loginId");
52
+ err.status = 400;
53
+ throw err;
54
+ }
55
+ if (projectId && doc.projectId && String(doc.projectId) !== String(projectId)) {
56
+ const err = new Error("loginId is for a different app");
57
+ err.status = 400;
58
+ throw err;
59
+ }
60
+ const used = await col.updateOne({
61
+ _id: doc._id,
62
+ usedAt: null
63
+ }, {
64
+ $set: {
65
+ usedAt: new Date()
66
+ }
67
+ });
68
+ if (used.modifiedCount !== 1) {
69
+ const err = new Error("loginId already used");
70
+ err.status = 400;
71
+ throw err;
72
+ }
73
+ return doc;
74
+ }
75
+ module.exports = {
76
+ issueLoginCode,
77
+ consumeLoginCode,
78
+ TTL_SECONDS
79
+ };
package/package.json CHANGED
@@ -1,74 +1,74 @@
1
- {
2
- "name": "powr-sdk-api",
3
- "version": "4.9.5",
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
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "files": [
8
- "dist",
9
- "README.md"
10
- ],
11
- "scripts": {
12
- "test": "jest --passWithNoTests",
13
- "lint": "eslint .",
14
- "build": "babel src -d dist",
15
- "prepare": "npm run build",
16
- "prepublishOnly": "npm run test"
17
- },
18
- "keywords": [
19
- "api",
20
- "express",
21
- "nextjs",
22
- "middleware",
23
- "error-handling",
24
- "response-formatting",
25
- "logging",
26
- "swagger",
27
- "documentation",
28
- "optional-dependencies",
29
- "modular",
30
- "framework-agnostic"
31
- ],
32
- "author": "Lawazia Tech",
33
- "license": "ISC",
34
- "repository": {
35
- "type": "git",
36
- "url": "git+https://github.com/powrstack/powr-sdk-api.git"
37
- },
38
- "bugs": {
39
- "url": "https://github.com/powrstack/powr-sdk-api/issues"
40
- },
41
- "homepage": "https://github.com/powrstack/powr-sdk-api#readme",
42
- "dependencies": {
43
- "libphonenumber-js": "^1.12.9"
44
- },
45
- "optionalDependencies": {
46
- "@aws-sdk/client-s3": "^3.787.0",
47
- "@google-cloud/storage": "^7.16.0",
48
- "axios": "^1.6.0",
49
- "bcrypt": "^5.1.1",
50
- "cron-parser": "^4.9.0",
51
- "date-fns": "^4.1.0",
52
- "express": "^4.18.2",
53
- "jsonwebtoken": "^9.0.2",
54
- "mongodb": "^6.3.0",
55
- "multer": "^1.4.5-lts.1",
56
- "nodemailer": "^6.10.0",
57
- "swagger-jsdoc": "^6.2.8",
58
- "winston": "^3.17.0"
59
- },
60
- "devDependencies": {
61
- "@babel/cli": "^7.23.9",
62
- "@babel/core": "^7.24.0",
63
- "@babel/preset-env": "^7.24.0",
64
- "@types/express": "^4.17.21",
65
- "@types/swagger-jsdoc": "^6.0.4",
66
- "@types/swagger-ui-express": "^4.1.6",
67
- "eslint": "^8.57.0",
68
- "jest": "^29.7.0",
69
- "typescript": "^5.3.3"
70
- },
71
- "engines": {
72
- "node": ">=14.0.0"
73
- }
74
- }
1
+ {
2
+ "name": "powr-sdk-api",
3
+ "version": "4.10.0",
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
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist",
9
+ "README.md"
10
+ ],
11
+ "scripts": {
12
+ "test": "jest --passWithNoTests",
13
+ "lint": "eslint .",
14
+ "build": "babel src -d dist",
15
+ "prepare": "npm run build",
16
+ "prepublishOnly": "npm run test"
17
+ },
18
+ "keywords": [
19
+ "api",
20
+ "express",
21
+ "nextjs",
22
+ "middleware",
23
+ "error-handling",
24
+ "response-formatting",
25
+ "logging",
26
+ "swagger",
27
+ "documentation",
28
+ "optional-dependencies",
29
+ "modular",
30
+ "framework-agnostic"
31
+ ],
32
+ "author": "Lawazia Tech",
33
+ "license": "ISC",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/powrstack/powr-sdk-api.git"
37
+ },
38
+ "bugs": {
39
+ "url": "https://github.com/powrstack/powr-sdk-api/issues"
40
+ },
41
+ "homepage": "https://github.com/powrstack/powr-sdk-api#readme",
42
+ "dependencies": {
43
+ "libphonenumber-js": "^1.12.9"
44
+ },
45
+ "optionalDependencies": {
46
+ "@aws-sdk/client-s3": "^3.787.0",
47
+ "@google-cloud/storage": "^7.16.0",
48
+ "axios": "^1.6.0",
49
+ "bcrypt": "^5.1.1",
50
+ "cron-parser": "^4.9.0",
51
+ "date-fns": "^4.1.0",
52
+ "express": "^4.18.2",
53
+ "jsonwebtoken": "^9.0.2",
54
+ "mongodb": "^6.3.0",
55
+ "multer": "^1.4.5-lts.1",
56
+ "nodemailer": "^6.10.0",
57
+ "swagger-jsdoc": "^6.2.8",
58
+ "winston": "^3.17.0"
59
+ },
60
+ "devDependencies": {
61
+ "@babel/cli": "^7.23.9",
62
+ "@babel/core": "^7.24.0",
63
+ "@babel/preset-env": "^7.24.0",
64
+ "@types/express": "^4.17.21",
65
+ "@types/swagger-jsdoc": "^6.0.4",
66
+ "@types/swagger-ui-express": "^4.1.6",
67
+ "eslint": "^8.57.0",
68
+ "jest": "^29.7.0",
69
+ "typescript": "^5.3.3"
70
+ },
71
+ "engines": {
72
+ "node": ">=14.0.0"
73
+ }
74
+ }