powr-sdk-api 4.12.0 → 4.13.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.
@@ -22,6 +22,7 @@ const ratingsRoutes = require('./ratings');
22
22
  const usersRoutes = require('./users');
23
23
  const waitlistsRoutes = require('./waitlists');
24
24
  const activitiesRoutes = require('./activities');
25
+ const trackRoutes = require('./track');
25
26
  const authRoutes = require('./auth');
26
27
  const loginCodeRoutes = require('./loginCode');
27
28
  const slidesRoutes = require('./slides');
@@ -53,6 +54,7 @@ const createPowrRoutes = (options = {}) => {
53
54
  router.use('/users', verifyTokenOrServiceKey, usersRoutes);
54
55
  router.use('/waitlists', verifyToken, waitlistsRoutes);
55
56
  router.use('/activities', verifyToken, activitiesRoutes);
57
+ router.use('/track', verifyToken, trackRoutes);
56
58
  router.use('/slides', verifyToken, slidesRoutes);
57
59
  router.use('/notifications', verifyToken, notificationsRoutes);
58
60
  router.use('/profiles', verifyTokenOrServiceKey, profilesRoutes);
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ const express = require("express");
4
+ const router = express.Router();
5
+ const {
6
+ getDb
7
+ } = require("../services/mongo");
8
+ const {
9
+ PAGEVIEW_TTL_SECONDS,
10
+ buildPageview
11
+ } = require("../utils/track");
12
+ let indexesPromise = null;
13
+ function ensurePageviewIndexes(db) {
14
+ if (!indexesPromise) {
15
+ const col = db.collection("pageviews");
16
+ indexesPromise = Promise.all([col.createIndex({
17
+ createdAt: 1
18
+ }, {
19
+ expireAfterSeconds: PAGEVIEW_TTL_SECONDS,
20
+ name: "pageviews_ttl_30d"
21
+ }), col.createIndex({
22
+ projectId: 1,
23
+ createdAt: -1
24
+ }, {
25
+ name: "pageviews_project_recent"
26
+ })]).catch(error => {
27
+ indexesPromise = null;
28
+ throw error;
29
+ });
30
+ }
31
+ return indexesPromise;
32
+ }
33
+ router.post("/", async (req, res) => {
34
+ try {
35
+ const built = buildPageview({
36
+ projectId: req.projectId,
37
+ user: req.user,
38
+ body: req.body
39
+ });
40
+ if (!built.ok) {
41
+ return res.status(built.status).json({
42
+ success: false,
43
+ message: built.message
44
+ });
45
+ }
46
+ const db = await getDb();
47
+ await ensurePageviewIndexes(db);
48
+ const result = await db.collection("pageviews").insertOne(built.doc);
49
+ return res.status(201).json({
50
+ success: true,
51
+ id: result.insertedId
52
+ });
53
+ } catch (error) {
54
+ console.error("Error creating pageview:", error);
55
+ return res.status(500).json({
56
+ success: false,
57
+ message: "Failed to record page view."
58
+ });
59
+ }
60
+ });
61
+ module.exports = router;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+
3
+ const PAGEVIEW_TTL_SECONDS = 30 * 24 * 60 * 60;
4
+ const MAX_PATH = 300;
5
+ const MAX_SESSION = 64;
6
+ function stripQueryAndHash(value) {
7
+ const raw = String(value || "").trim();
8
+ if (!raw) return "";
9
+ const noHash = raw.split("#")[0];
10
+ return noHash.split("?")[0].trim();
11
+ }
12
+ function asPath(value) {
13
+ const stripped = stripQueryAndHash(value);
14
+ if (!stripped) return "";
15
+ try {
16
+ if (/^https?:\/\//i.test(stripped)) {
17
+ const url = new URL(stripped);
18
+ return url.pathname || "/";
19
+ }
20
+ } catch {
21
+ return "";
22
+ }
23
+ if (!stripped.startsWith("/")) return "";
24
+ return stripped.slice(0, MAX_PATH);
25
+ }
26
+ function asReferrer(value) {
27
+ const stripped = stripQueryAndHash(value);
28
+ if (!stripped) return null;
29
+ try {
30
+ if (/^https?:\/\//i.test(stripped)) {
31
+ const url = new URL(stripped);
32
+ const path = `${url.origin}${url.pathname || "/"}`;
33
+ return path.slice(0, MAX_PATH);
34
+ }
35
+ } catch {
36
+ return null;
37
+ }
38
+ if (!stripped.startsWith("/")) return null;
39
+ return stripped.slice(0, MAX_PATH);
40
+ }
41
+ function asSession(value) {
42
+ const raw = String(value || "").trim();
43
+ if (!/^[A-Za-z0-9_-]{8,64}$/.test(raw)) return "";
44
+ return raw.slice(0, MAX_SESSION);
45
+ }
46
+ function actorId(user) {
47
+ if (user && user.impersonatedBy) return String(user.impersonatedBy);
48
+ if (user && user.powrId) return String(user.powrId);
49
+ return "";
50
+ }
51
+
52
+ /**
53
+ * One page view. Drops query, hash, and every field that is not page / session / referrer.
54
+ * Login As stores the admin (impersonatedBy), not the person being viewed.
55
+ */
56
+ function buildPageview({
57
+ projectId,
58
+ user,
59
+ body
60
+ }) {
61
+ const page = asPath(body && body.page);
62
+ const session = asSession(body && body.session);
63
+ const userId = actorId(user);
64
+ const project = String(projectId || "").trim();
65
+ if (!project) {
66
+ return {
67
+ ok: false,
68
+ status: 400,
69
+ message: "projectId is required"
70
+ };
71
+ }
72
+ if (!userId) {
73
+ return {
74
+ ok: false,
75
+ status: 401,
76
+ message: "Sign in required"
77
+ };
78
+ }
79
+ if (!page) {
80
+ return {
81
+ ok: false,
82
+ status: 400,
83
+ message: "page is required"
84
+ };
85
+ }
86
+ if (!session) {
87
+ return {
88
+ ok: false,
89
+ status: 400,
90
+ message: "session is required"
91
+ };
92
+ }
93
+ const doc = {
94
+ projectId: project,
95
+ userId,
96
+ page,
97
+ session,
98
+ createdAt: new Date()
99
+ };
100
+ const referrer = asReferrer(body && body.referrer);
101
+ if (referrer) doc.referrer = referrer;
102
+ return {
103
+ ok: true,
104
+ doc
105
+ };
106
+ }
107
+ module.exports = {
108
+ PAGEVIEW_TTL_SECONDS,
109
+ buildPageview
110
+ };
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+
3
+ const {
4
+ buildPageview,
5
+ PAGEVIEW_TTL_SECONDS
6
+ } = require("./track");
7
+ const projectId = "507f1f77bcf86cd799439011";
8
+ const member = "aaaaaaaaaaaaaaaaaaaaaaaa";
9
+ const admin = "bbbbbbbbbbbbbbbbbbbbbbbb";
10
+ function view(body, user) {
11
+ return buildPageview({
12
+ projectId,
13
+ user: user || {
14
+ powrId: member
15
+ },
16
+ body
17
+ });
18
+ }
19
+ describe("buildPageview", () => {
20
+ it("keeps page, session, referrer, and project", () => {
21
+ const result = view({
22
+ page: "/desk?token=secret",
23
+ session: "sess_abc123",
24
+ referrer: "https://excelrs.dev/start?utm=1#x",
25
+ phone: "9304251332",
26
+ body: "form text"
27
+ });
28
+ expect(result.ok).toBe(true);
29
+ expect(result.doc.projectId).toBe(projectId);
30
+ expect(result.doc.userId).toBe(member);
31
+ expect(result.doc.page).toBe("/desk");
32
+ expect(result.doc.session).toBe("sess_abc123");
33
+ expect(result.doc.referrer).toBe("https://excelrs.dev/start");
34
+ expect(result.doc.phone).toBeUndefined();
35
+ expect(result.doc.body).toBeUndefined();
36
+ expect(result.doc.createdAt).toBeInstanceOf(Date);
37
+ });
38
+ it("stores the admin when Login As is active", () => {
39
+ const result = view({
40
+ page: "/home",
41
+ session: "sess_abc123"
42
+ }, {
43
+ powrId: member,
44
+ impersonatedBy: admin
45
+ });
46
+ expect(result.doc.userId).toBe(admin);
47
+ });
48
+ it("rejects a missing page and a short session", () => {
49
+ expect(view({
50
+ session: "sess_abc123"
51
+ }).status).toBe(400);
52
+ expect(view({
53
+ page: "/home",
54
+ session: "short"
55
+ }).status).toBe(400);
56
+ });
57
+ it("drops a referrer that is not a path or url", () => {
58
+ const result = view({
59
+ page: "/home",
60
+ session: "sess_abc123",
61
+ referrer: "not a url"
62
+ });
63
+ expect(result.doc.referrer).toBeUndefined();
64
+ });
65
+ });
66
+ describe("pageview ttl", () => {
67
+ it("expires after 30 days", () => {
68
+ expect(PAGEVIEW_TTL_SECONDS).toBe(30 * 24 * 60 * 60);
69
+ });
70
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.12.0",
3
+ "version": "4.13.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",