powr-sdk-api 4.10.3 → 4.11.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,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");
@@ -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;
@@ -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.10.3",
3
+ "version": "4.11.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",