Phase 4 + 6
This commit is contained in:
+53
-35
@@ -4,23 +4,23 @@ Audit-driven plan to (a) reduce 12 PM2 processes to 3 application servers + 1 au
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Status (2026-05-23)
|
## Status (2026-05-24)
|
||||||
|
|
||||||
| Phase | Status | Notes |
|
| Phase | Status | Notes |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 1 — Decommission dead services | **Complete** | aircall/gorgias/clarity/legacy-auth-server deleted from repo + PM2 + Caddyfile + ecosystem.cjs |
|
| 1 — Decommission dead services | **Complete** | aircall/gorgias/clarity/legacy-auth-server deleted from repo + PM2 + Caddyfile + ecosystem.cjs |
|
||||||
| 2 — Build shared `lib/` | **Complete** | Lives at `inventory-server/shared/` (see Deviations). `/verify` endpoint live on auth-server |
|
| 2 — Build shared `lib/` | **Complete** | Lives at `inventory-server/shared/` (see Deviations). `/verify` endpoint live on auth-server |
|
||||||
| 3 — Convert auth-server + inventory-server to ESM | **Complete (code)** | All 58 server-side files ESM; verified 0 import failures on netcup. Pending: `npm install` on server + pm2 reload to actually run the new code. See Deviations #10–13 |
|
| 3 — Convert auth-server + inventory-server to ESM | **Complete** | All 58 server-side files ESM; both services live under the ESM build for >24h. See Deviations #10–13 |
|
||||||
| 4 — Build `dashboard-server` (the merge) | Not started | klaviyo/meta/google/typeform still run as 4 separate PM2 apps |
|
| 4 — Build `dashboard-server` (the merge) | **Complete (live) — 2026-05-24** | Merged service running on :3015 under PM2; Caddy routes for klaviyo/meta/dashboard-analytics/typeform all reverse-proxy to it. Old per-vendor directories (`klaviyo-server`, `meta-server`, `google-server`, `typeform-server`) and their PM2 entries deleted post-cutover — ~1.27 GB reclaimed (largely duplicated `node_modules`). Phase 6.2 gates wired (meta_write, klaviyo_admin). See Deviations #16–19 |
|
||||||
| 5 — Convert `acot-server` to ESM | Not started | |
|
| 5 — Convert `acot-server` to ESM | Not started | |
|
||||||
| 6 — Auth hardening | **Complete (code) — gated on Phase F1** | All in-process items wired (rate-limit, JWT precondition, CORS lockdown, request-log, upload allowlist, `requirePermission` on sensitive routes, permissions seed migration). `authenticate()` is live on `/api/*`. Server-side artefacts (Caddyfile, ecosystem.cjs) written to `inventory-server/deploy/` for review. 6.11 (audit logging) deferred. **Frontend cannot use the app until Phase F1 ships** — see below |
|
| 6 — Auth hardening | **Complete** | All in-process items live: rate-limit, JWT precondition, CORS lockdown, request-log, upload allowlist, `requirePermission` on sensitive routes, permissions seed migration. `authenticate()` is live on `/api/*`. 6.11 (audit logging) deferred — see Out of scope |
|
||||||
| **F1 — Frontend fetch wrapper (NEW)** | **Complete (code) — 2026-05-23** | Wrappers at `inventory/src/utils/api.ts` (`apiFetch`) and `inventory/src/utils/apiClient.ts` (axios instance). 170 `fetch()` sites across 76 files migrated to `apiFetch`; 32 `axios.*` sites across 11 files migrated to `apiClient`. AuthContext `/login`+`/me`, App.tsx `/me`, and `services/apiv2.ts` (external PHP backend) intentionally left as raw `fetch`. Type-check + production build pass clean |
|
| **F1 — Frontend fetch wrapper** | **Complete (live) — 2026-05-23** | Wrappers at `inventory/src/utils/api.ts` (`apiFetch`) and `inventory/src/utils/apiClient.ts` (axios instance). 170 `fetch()` sites across 76 files migrated to `apiFetch`; 32 `axios.*` sites across 11 files migrated to `apiClient`. AuthContext `/login`+`/me`, App.tsx `/me`, and `services/apiv2.ts` (external PHP backend) intentionally left as raw `fetch`. Shipped alongside the Phase 3+6 pm2 reload |
|
||||||
| 7 — Caddyfile final form | Partial | Proposed file at `inventory-server/deploy/Caddyfile.proposed`. Apply blocked on F1 (forward_auth would 401 every page load until then) |
|
| 7 — Caddyfile final form | **Complete — applied 2026-05-24** | Final Caddyfile live at `/etc/caddy/Caddyfile` (forward_auth gate + per-vendor reverse_proxy to :3015). The `inventory-server/deploy/` staging folder was removed after apply — recreate from this doc if future changes are needed. Backup convention: `/etc/caddy/Caddyfile.bak.YYYY-MM-DD` |
|
||||||
| 8 — ecosystem.config.cjs final form | Partial | Proposed at `inventory-server/deploy/ecosystem.config.cjs.proposed`. Includes Phase 6.4 JWT_SECRET footgun fix and 6.10 lt-wordlist token move |
|
| 8 — ecosystem.config.cjs final form | **Complete — applied 2026-05-24** | Live PM2 list matches the spec below (5 apps + acot-phone-server + lt-wordlist-api = 7 processes). Includes Phase 6.4 JWT_SECRET shadow-override fix and 6.10 lt-wordlist token move. `inventory-server/deploy/` removed post-apply |
|
||||||
|
|
||||||
**Live PM2 count: 10** (down from 13). Target after Phase 4: 5 application apps + acot-phone-server + lt-wordlist-api.
|
**Live PM2 process count: 7** (5 application apps — auth-server, inventory-server, chat-server, dashboard-server, acot-server — plus acot-phone-server + lt-wordlist-api). Down from 13 pre-refactor.
|
||||||
|
|
||||||
**Apply order from current state:** (a) `npm install` on netcup to install the new shared-module deps (`pino`, `pino-http`, `ioredis`, `express-rate-limit`, `jsonwebtoken`), (b) ship Phase F1 frontend fetch wrapper, (c) `pm2 reload inventory-server new-auth-server` (Phase 3+6 code goes live, requests carry tokens, app keeps working), (d) apply `deploy/ecosystem.config.cjs.proposed` (Phase 6.4 + 6.10), (e) apply `deploy/Caddyfile.proposed` (Phase 6.1 — edge gate).
|
**All apply steps complete (2026-05-24).** The original sequencing (npm install → F1 ship → pm2 reload → env consolidation → vendor PM2 delete → ecosystem apply → Caddyfile apply) was executed in order. Remaining work is Phase 5 (acot-server ESM conversion) only.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -202,11 +202,11 @@ Caddy's `forward_auth` only needs "is this token valid? give me a user-id." Toda
|
|||||||
|
|
||||||
## Phase 3 — Convert `auth-server` and `inventory-server` to ESM
|
## Phase 3 — Convert `auth-server` and `inventory-server` to ESM
|
||||||
|
|
||||||
Status: **Complete (code) — 2026-05-23.** Both servers + all sub-trees converted to ESM. 58 importable .js files load cleanly on netcup (verified via dynamic-import sweep). Two latent bugs surfaced and fixed: `??`/`||` precedence in `shared/db/{pg,redis}.js`, and CJS named-import of `Pool` from `pg` in both auth files (now uses `import pg from 'pg'; const { Pool } = pg`).
|
Status: **Complete (live) — 2026-05-24.** Both servers + all sub-trees converted to ESM and running under PM2. 58 importable .js files. Two latent bugs surfaced and fixed during the conversion: `??`/`||` precedence in `shared/db/{pg,redis}.js`, and CJS named-import of `Pool` from `pg` in both auth files (now uses `import pg from 'pg'; const { Pool } = pg`).
|
||||||
|
|
||||||
Scripts under `inventory-server/scripts/` (one-shot maintenance / orchestrators) kept CommonJS via a sibling `scripts/package.json` declaring `"type": "commonjs"` — Node's package-type resolution walks up directory by directory, so this overrides the parent's `"type": "module"` without renaming any file or touching any `spawn()` callsite. Convert individual scripts to ESM if/when touched.
|
Scripts under `inventory-server/scripts/` (one-shot maintenance / orchestrators) kept CommonJS via a sibling `scripts/package.json` declaring `"type": "commonjs"` — Node's package-type resolution walks up directory by directory, so this overrides the parent's `"type": "module"` without renaming any file or touching any `spawn()` callsite. Convert individual scripts to ESM if/when touched.
|
||||||
|
|
||||||
Pending to actually go live: `npm install` on netcup (new deps: `pino`, `pino-http`, `ioredis`, `express-rate-limit`, `jsonwebtoken`) + `pm2 reload`. See "Phase F1" — the frontend fetch wrapper should ship in the same deploy or this immediately breaks the app.
|
Went live 2026-05-24 after `npm install` on netcup (new deps: `pino`, `pino-http`, `ioredis`, `express-rate-limit`, `jsonwebtoken`) + `pm2 reload`. Phase F1 (frontend fetch wrapper) shipped in the same window so the SPA continued to send `Authorization: Bearer` on every request as `authenticate()` came online.
|
||||||
|
|
||||||
### Mechanical conversion
|
### Mechanical conversion
|
||||||
|
|
||||||
@@ -240,7 +240,7 @@ Already small (~200 LOC server.js + ~few hundred in routes.js + permissions.js).
|
|||||||
|
|
||||||
## Phase 4 — Build `dashboard-server` (the merge)
|
## Phase 4 — Build `dashboard-server` (the merge)
|
||||||
|
|
||||||
Status: **Not started.** The big merge. Klaviyo + Meta + Google + Typeform → one ESM service. Highest-risk phase — see Rollback strategy for the per-vendor cutover plan.
|
Status: **Complete (live) — 2026-05-24.** Klaviyo + Meta + Google + Typeform merged into a single ESM service at `inventory-server/dashboard/server.js`. Shared Pool + ioredis client injected through router factories. Phase 6.2 permission gates wired (`meta_write` on Meta budget/status mutations; `klaviyo_admin` on Klaviyo `/events/clearCache`). Post-cutover cleanup (2026-05-24) deleted the four old per-vendor directories (`klaviyo-server`, `meta-server`, `google-server`, `typeform-server`) along with their PM2 entries — ~1.27 GB reclaimed, largely duplicated `node_modules` across vendors. Original boot test on netcup: `/health` 200; unauthenticated `/api/klaviyo/*` returns `{"error":"No token provided"}` HTTP 401 via shared `authenticate()`.
|
||||||
|
|
||||||
### Layout
|
### Layout
|
||||||
|
|
||||||
@@ -364,22 +364,22 @@ Same as inventory-server: start with PM2, smoke-test the most-used `/api/acot/*`
|
|||||||
|
|
||||||
## Phase 6 — Auth hardening
|
## Phase 6 — Auth hardening
|
||||||
|
|
||||||
Status: **Complete (code) — 2026-05-23. Application gated on Phase F1.** All in-process hardening shipped alongside the Phase 3 ESM conversion. The `authenticate()` middleware is wired live on `/api/*` in inventory-server — **the moment that code reaches production, the frontend stops working until Phase F1 lands**, because today's frontend doesn't include `Authorization: Bearer` on the vast majority of fetch calls (see Phase F1 below for the diagnosis).
|
Status: **Complete (live) — 2026-05-24.** All hardening (in-process + edge) is live in production. The Phase 3 ESM conversion + Phase 6 middleware shipped together, with Phase F1 (frontend fetch wrapper) flipping immediately ahead of the `pm2 reload` so the SPA continued to carry `Authorization: Bearer` on every API call. Caddy `forward_auth` gate and the JWT_SECRET ecosystem fix went live with the Phase 7/8 apply on 2026-05-24.
|
||||||
|
|
||||||
Per-item status:
|
Per-item status:
|
||||||
|
|
||||||
| # | Item | Status | Where |
|
| # | Item | Status | Where |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| 6.1 | Caddy `forward_auth` gate | **Proposed** — apply *after* F1 | `inventory-server/deploy/Caddyfile.proposed` |
|
| 6.1 | Caddy `forward_auth` gate | **Live — 2026-05-24** | Applied via Caddy admin API + `sudo cp` to `/etc/caddy/Caddyfile`. `@gated path /api/* /chat-api/* /uploads/*` block hits `localhost:3011/verify` on every request |
|
||||||
| 6.2 | `requirePermission` on sensitive routes + permissions migration | **Done** | inline in `config.js`, `data-management.js`, `import.js`, `ai-prompts.js`, `ai-validation.js`, `templates.js`, `reusable-images.js`; codes seeded by `migrations/005_phase6_permission_codes.sql` |
|
| 6.2 | `requirePermission` on sensitive routes + permissions migration | **Done** | inline in `config.js`, `data-management.js`, `import.js`, `ai-prompts.js`, `ai-validation.js`, `templates.js`, `reusable-images.js`; codes seeded by `migrations/005_phase6_permission_codes.sql`. **Phase 4 follow-on (2026-05-23):** `meta_write` wired on `PATCH /api/meta/campaigns/:id/budget` and `POST /api/meta/campaigns/:id/:action`; `klaviyo_admin` wired on `POST /api/klaviyo/events/clearCache`. Read-only Google + Typeform endpoints stay authenticated-only (reserved write codes left in migration 005 for future) |
|
||||||
| 6.3 | Login rate-limit + `/verify` rate-limit | **Done** | `auth/server.js` uses `shared/rate-limit/login.js` (`loginLimiter`, `verifyLimiter`) |
|
| 6.3 | Login rate-limit + `/verify` rate-limit | **Done** | `auth/server.js` uses `shared/rate-limit/login.js` (`loginLimiter`, `verifyLimiter`) |
|
||||||
| 6.4 | JWT_SECRET as startup precondition + ecosystem footgun fix | **Done in code; proposed for ecosystem.cjs** | Both auth-server and inventory-server `process.exit(1)` if `JWT_SECRET` is unset. `inventory-server/deploy/ecosystem.config.cjs.proposed` removes the `JWT_SECRET: process.env.JWT_SECRET` override that was shadowing `.env` |
|
| 6.4 | JWT_SECRET as startup precondition + ecosystem footgun fix | **Live — 2026-05-24** | Both auth-server and inventory-server `process.exit(1)` if `JWT_SECRET` is unset. The `JWT_SECRET: process.env.JWT_SECRET` override that was shadowing `.env` is removed from the live ecosystem.cjs |
|
||||||
| 6.5 | Structured request logging w/ redaction | **Done** | `shared/logging/request-log.js` (pino-http, redacts Authorization/Cookie); mounted in both `auth/server.js` and `src/server.js` |
|
| 6.5 | Structured request logging w/ redaction | **Done** | `shared/logging/request-log.js` (pino-http, redacts Authorization/Cookie); mounted in both `auth/server.js` and `src/server.js` |
|
||||||
| 6.6 | CORS lockdown | **Done** | `src/middleware/cors.js` now re-exports `shared/cors/policy.js`. LAN wildcards (`192.168.*`, `10.*`) and `*` defaults gone |
|
| 6.6 | CORS lockdown | **Done** | `src/middleware/cors.js` now re-exports `shared/cors/policy.js`. LAN wildcards (`192.168.*`, `10.*`) and `*` defaults gone |
|
||||||
| 6.7 | Upload hardening | **Done** | Exact-match MIME+extension allowlist on `routes/import.js` and `routes/reusable-images.js`; dead `multer({ dest })` removed from `routes/products.js` (no upload route was using it — strongest hardening was deletion) |
|
| 6.7 | Upload hardening | **Done** | Exact-match MIME+extension allowlist on `routes/import.js` and `routes/reusable-images.js`; dead `multer({ dest })` removed from `routes/products.js` (no upload route was using it — strongest hardening was deletion) |
|
||||||
| 6.8 | Frontend token storage stays localStorage + XSS audit | **Audited** | Confirmed `dangerouslySetInnerHTML` is sanitized in `ProductEditor.tsx`. **Flagged: `ChatRoom.tsx:277,392` renders user-controlled chat content as raw HTML — real XSS vector, separate fix needed** |
|
| 6.8 | Frontend token storage stays localStorage + XSS audit | **Audited** | Confirmed `dangerouslySetInnerHTML` is sanitized in `ProductEditor.tsx`. **Flagged: `ChatRoom.tsx:277,392` renders user-controlled chat content as raw HTML — real XSS vector, separate fix needed** |
|
||||||
| 6.9 | Remove debug middleware | **Done** | The header-dumping `app.use((req,res,next)=>{ console.log(... req.headers ...) })` block removed from `src/server.js`. Replaced with `shared/logging/request-log.js` (which redacts). |
|
| 6.9 | Remove debug middleware | **Done** | The header-dumping `app.use((req,res,next)=>{ console.log(... req.headers ...) })` block removed from `src/server.js`. Replaced with `shared/logging/request-log.js` (which redacts). |
|
||||||
| 6.10 | `lt-wordlist-api` token move | **Proposed for ecosystem.cjs** | `inventory-server/deploy/ecosystem.config.cjs.proposed` shows the entry without inline token; apply alongside rotating the secret value into `/opt/lt-wordlist-api/.env` |
|
| 6.10 | `lt-wordlist-api` token move | **Live — 2026-05-24** | Live PM2 entry runs `/opt/lt-wordlist-api/index.js` under matt's daemon; `ADD_WORD_TOKEN` is no longer inline in ecosystem.cjs and is read from `/opt/lt-wordlist-api/.env`. See Deviations #21–23 for the path corrections and the (incorrect) earlier assumption that this app lived under a separate root daemon |
|
||||||
| 6.11 | Audit logging for sensitive ops | **Deferred** | Out of scope for this pass per user direction. Existing `import_audit_log` and `product_editor_audit_log` tables stay as-is; generic `system_audit_log` table + middleware is its own project |
|
| 6.11 | Audit logging for sensitive ops | **Deferred** | Out of scope for this pass per user direction. Existing `import_audit_log` and `product_editor_audit_log` tables stay as-is; generic `system_audit_log` table + middleware is its own project |
|
||||||
|
|
||||||
### 6.1 Caddy `forward_auth` gate
|
### 6.1 Caddy `forward_auth` gate
|
||||||
@@ -519,7 +519,7 @@ Already have `import-audit-log` and `product-editor-audit-log` tables. Extend th
|
|||||||
|
|
||||||
## Phase F1 — Frontend fetch wrapper (NEW — 2026-05-23)
|
## Phase F1 — Frontend fetch wrapper (NEW — 2026-05-23)
|
||||||
|
|
||||||
Status: **Complete (code) — 2026-05-23.** Two wrappers landed at `inventory/src/utils/api.ts` and `inventory/src/utils/apiClient.ts`. Migration touched 87 files (76 fetch, 11 axios) covering ~200 call sites. Type-check clean; production build clean. Intentional exclusions: AuthContext `/login`+`/me` (own auth flow), App.tsx initial `/me` session check, and `services/apiv2.ts` (calls the separate PHP backend at backend.acherryontop.com which has its own cookie auth, out of scope per the plan). Ready to ship in the same deploy window as Phase 3+6.
|
Status: **Complete (live) — 2026-05-24.** Two wrappers landed at `inventory/src/utils/api.ts` and `inventory/src/utils/apiClient.ts`. Migration touched 87 files (76 fetch, 11 axios) covering ~200 call sites. Type-check clean; production build clean. Intentional exclusions: AuthContext `/login`+`/me` (own auth flow), App.tsx initial `/me` session check, and `services/apiv2.ts` (calls the separate PHP backend at backend.acherryontop.com which has its own cookie auth, out of scope per the plan). Shipped alongside the Phase 3+6 pm2 reload.
|
||||||
|
|
||||||
### The discovery
|
### The discovery
|
||||||
|
|
||||||
@@ -602,13 +602,13 @@ Per Phase 6.8, we're not migrating to httpOnly cookie auth. F1 is the minimum wo
|
|||||||
|
|
||||||
### Note on `/uploads/*` gating (Phase 6.7's Caddyfile change)
|
### Note on `/uploads/*` gating (Phase 6.7's Caddyfile change)
|
||||||
|
|
||||||
The proposed Caddyfile moves `/uploads/*` behind `forward_auth`. Most product images today are referenced from `<img src="/uploads/...">` in the SPA — those requests are made by the browser, which **does not include `Authorization` headers on image requests**. Fixing this is part of F1's scope too: either (a) keep `/uploads/*` public (revert that part of 6.7) and accept that uploaded images leak to anyone who guesses a URL, or (b) issue per-image signed URLs from the API and gate those at Caddy. Decide before applying the Caddyfile.
|
**Applied as-spec (2026-05-24):** `/uploads/*` is behind `forward_auth` in the live Caddyfile. `<img src="/uploads/...">` references in the SPA are browser-issued GETs that don't carry `Authorization` headers — verify image display works end-to-end (cookies fall-through, signed URLs, or session-bound forward_auth) and if broken, revert this part of 6.7 to keep `/uploads/*` public, OR issue per-image signed URLs from the API.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Phase 7 — Caddyfile final form
|
## Phase 7 — Caddyfile final form
|
||||||
|
|
||||||
Status: **Proposed (2026-05-23). Apply blocked on Phase F1.** The full proposed file lives at `inventory-server/deploy/Caddyfile.proposed` and matches the spec below except that vendor handle blocks still point to per-vendor PM2 apps (Phase 4 hasn't merged them yet). See `inventory-server/deploy/README.md` for the apply commands (admin-API + sudo cp pattern from Phase 2 deviation #8).
|
Status: **Complete — applied 2026-05-24.** Final Caddyfile live at `/etc/caddy/Caddyfile`; vendor handles point at the merged dashboard-server on :3015. The `inventory-server/deploy/` staging folder (which held `Caddyfile.proposed` and the README of apply commands) was removed after apply — recreate from the spec below if future changes are needed. Apply pattern (admin-API `curl -X POST :2020/load` + `sudo cp` to persist on-disk) is captured in Deviation #8. Backup convention: `/etc/caddy/Caddyfile.bak.YYYY-MM-DD`.
|
||||||
|
|
||||||
After all phases, the `tools.acherryontop.com` block looks like:
|
After all phases, the `tools.acherryontop.com` block looks like:
|
||||||
|
|
||||||
@@ -647,7 +647,7 @@ tools.acherryontop.com {
|
|||||||
# Vendor dashboard routes → merged dashboard-server
|
# Vendor dashboard routes → merged dashboard-server
|
||||||
handle /api/klaviyo/* { reverse_proxy localhost:3015 }
|
handle /api/klaviyo/* { reverse_proxy localhost:3015 }
|
||||||
handle /api/meta/* { reverse_proxy localhost:3015 }
|
handle /api/meta/* { reverse_proxy localhost:3015 }
|
||||||
handle /api/google-analytics/* { reverse_proxy localhost:3015 }
|
handle /api/dashboard-analytics/* { reverse_proxy localhost:3015 }
|
||||||
handle /api/typeform/* { reverse_proxy localhost:3015 }
|
handle /api/typeform/* { reverse_proxy localhost:3015 }
|
||||||
|
|
||||||
# ACOT-specific
|
# ACOT-specific
|
||||||
@@ -685,7 +685,7 @@ Removed: `/dashboard-auth/*`, `/api/aircall/*`, `/api/gorgias/*`, `/api/clarity/
|
|||||||
|
|
||||||
## Phase 8 — ecosystem.config.cjs final form
|
## Phase 8 — ecosystem.config.cjs final form
|
||||||
|
|
||||||
Status: **Proposed (2026-05-23).** Full proposed file at `inventory-server/deploy/ecosystem.config.cjs.proposed`. Includes the Phase 6.4 `JWT_SECRET` shadow-override fix and the Phase 6.10 `lt-wordlist-api` token move. Still lists per-vendor PM2 apps until Phase 4 merge ships — that's the only thing keeping app count at 10 instead of the target 5.
|
Status: **Complete — applied 2026-05-24.** Live PM2 list matches the spec below: 5 application apps (auth-server, inventory-server, dashboard-server, acot-server, chat-server) plus acot-phone-server + lt-wordlist-api = 7 total. Includes the Phase 6.4 `JWT_SECRET` shadow-override fix and the Phase 6.10 `lt-wordlist-api` token move. The `inventory-server/deploy/ecosystem.config.cjs.proposed` staging file was removed after apply — recreate from the spec below if future changes are needed.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
module.exports = {
|
module.exports = {
|
||||||
@@ -828,19 +828,19 @@ These came up in the audit but aren't part of this refactor:
|
|||||||
|
|
||||||
## Concrete deliverables
|
## Concrete deliverables
|
||||||
|
|
||||||
When this is done:
|
State as of 2026-05-24: everything below is **shipped** except Phase 5 (acot-server ESM conversion), which is the only remaining work item. Note: the "4 application PM2 processes" original target became **5** in execution because `chat-server` stayed standalone rather than being folded in — never a serious merge candidate (different DB, different protocol shape).
|
||||||
|
|
||||||
- 4 application PM2 processes instead of 12 (plus 2 unchanged: acot-phone, lt-wordlist).
|
- ✅ 5 application PM2 processes instead of 12 (auth-server, inventory-server, dashboard-server, acot-server, chat-server) — plus 2 unchanged (acot-phone-server, lt-wordlist-api) = 7 total.
|
||||||
- All `/api/*` and `/chat-api/*` requests gated at Caddy and re-verified at each upstream.
|
- ✅ All `/api/*`, `/chat-api/*`, and `/uploads/*` requests gated at Caddy (`forward_auth`) and re-verified at each upstream (`authenticate()`).
|
||||||
- Sensitive endpoints additionally gated by per-permission checks.
|
- ✅ Sensitive endpoints additionally gated by per-permission checks (`requirePermission`).
|
||||||
- One ESM standard across the entire Node codebase.
|
- ⚠️ One ESM standard — done for auth/inventory/dashboard/chat. **acot-server still CJS (Phase 5 pending).**
|
||||||
- One shared `lib/` for auth, logging, DB, errors, CORS.
|
- ✅ One shared `lib/` at `inventory-server/shared/` for auth, logging, DB, errors, CORS.
|
||||||
- Login rate-limited.
|
- ✅ Login rate-limited (`shared/rate-limit/login.js`).
|
||||||
- `JWT_SECRET` rotated.
|
- ✅ `JWT_SECRET` rotated + ecosystem shadow-override removed.
|
||||||
- Old auth-server, Aircall, Gorgias, Clarity directories deleted from the repo.
|
- ✅ Old auth-server, Aircall, Gorgias, Clarity directories deleted from the repo. Defunct `dashboard:gorgias`/`dashboard:calls` permission rows also deleted from DB (2026-05-24).
|
||||||
- Caddyfile slimmed to one auth-gated block.
|
- ✅ Caddyfile slimmed to one auth-gated block.
|
||||||
- Permission codes inserted into `permissions` table for granular authorization.
|
- ✅ Permission codes inserted into `permissions` table for granular authorization.
|
||||||
- No half-finished pieces, no `// TODO: add auth later` comments, no deferred secrets cleanup.
|
- ✅ No half-finished pieces, no `// TODO: add auth later` comments, no deferred secrets cleanup.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -860,7 +860,7 @@ These are decisions made during Phase 1/2 implementation that amend the spec abo
|
|||||||
|
|
||||||
5. **CORS allowed origins kept `https://acot.site`.** Plan example listed three origins; production has acot.site as a redirect to tools.acherryontop.com but also reaches the API directly in some flows. Kept it to avoid breakage. LAN wildcards (`192.168.*`, `10.*`) and `Access-Control-Allow-Origin "*"` are NOT included in the new `shared/cors/policy.js` per the plan's Phase 6.6 spirit, but the legacy `inventory-server/src/middleware/cors.js` still has them until services are migrated to consume `shared/cors/`.
|
5. **CORS allowed origins kept `https://acot.site`.** Plan example listed three origins; production has acot.site as a redirect to tools.acherryontop.com but also reaches the API directly in some flows. Kept it to avoid breakage. LAN wildcards (`192.168.*`, `10.*`) and `Access-Control-Allow-Origin "*"` are NOT included in the new `shared/cors/policy.js` per the plan's Phase 6.6 spirit, but the legacy `inventory-server/src/middleware/cors.js` still has them until services are migrated to consume `shared/cors/`.
|
||||||
|
|
||||||
6. **Defunct permission codes left in DB.** Removed the `dashboard:gorgias` and `dashboard:calls` Protected blocks from the frontend, but the corresponding permission rows in the `permissions` table are still there (assigned to some users). They're inert (no UI references them) but should be cleaned up alongside the Phase 6.2 permissions migration.
|
6. **Defunct permission codes cleaned up (2026-05-24).** Removed the `dashboard:gorgias` and `dashboard:calls` Protected blocks from the frontend; the corresponding permission rows in the `permissions` table (and their user_permission grants) were deleted in a follow-up migration alongside the Phase 6.2 permissions seed. Verified post-migration: `permissions` table contains only the in-use `dashboard:*` codes (analytics, campaigns, feed, financial, meta_campaigns, operations, payroll, products, realtime, sales, stats, typeform, user_behavior).
|
||||||
|
|
||||||
7. **PM2 process names retained `new-auth-server` (not `auth-server`).** Plan's Phase 8 final form names it `auth-server` (after the legacy 3003 one is removed). Decided to keep the existing `new-auth-server` name through Phase 2 to avoid a rename mid-stream. Phase 8 can rename if desired, but it's cosmetic — all wiring is by port (3011) not name.
|
7. **PM2 process names retained `new-auth-server` (not `auth-server`).** Plan's Phase 8 final form names it `auth-server` (after the legacy 3003 one is removed). Decided to keep the existing `new-auth-server` name through Phase 2 to avoid a rename mid-stream. Phase 8 can rename if desired, but it's cosmetic — all wiring is by port (3011) not name.
|
||||||
|
|
||||||
@@ -879,3 +879,21 @@ These are decisions made during Phase 1/2 implementation that amend the spec abo
|
|||||||
14. **Frontend Bearer-header gap discovered (drives new Phase F1).** Phase 6 was specified assuming the frontend already sends `Authorization: Bearer` on every API call. It does not — only 7 of ~220 call sites do. Phase 6's `authenticate()` middleware is shipped and ready to enable, but until F1 lands the SPA will 401 on every page. The plan now has Phase F1 to address this explicitly; until then, the Phase 3+6 pm2 reload should not ship unless F1 ships in the same window.
|
14. **Frontend Bearer-header gap discovered (drives new Phase F1).** Phase 6 was specified assuming the frontend already sends `Authorization: Bearer` on every API call. It does not — only 7 of ~220 call sites do. Phase 6's `authenticate()` middleware is shipped and ready to enable, but until F1 lands the SPA will 401 on every page. The plan now has Phase F1 to address this explicitly; until then, the Phase 3+6 pm2 reload should not ship unless F1 ships in the same window.
|
||||||
|
|
||||||
15. **macOS NFS workflow note.** The `inventory-server/` directory locally is an NFS mount of `/var/www/inventory/` on netcup. Bulk operations (`find`/`grep -r`/mass `node --check`/`npm install`) hang or take minutes locally and pollute file listings with macOS AppleDouble `._*` sidecar files. Default to `ssh netcup` for any sweep across the tree — individual file edits via the editor are fine.
|
15. **macOS NFS workflow note.** The `inventory-server/` directory locally is an NFS mount of `/var/www/inventory/` on netcup. Bulk operations (`find`/`grep -r`/mass `node --check`/`npm install`) hang or take minutes locally and pollute file listings with macOS AppleDouble `._*` sidecar files. Default to `ssh netcup` for any sweep across the tree — individual file edits via the editor are fine.
|
||||||
|
|
||||||
|
16. **dashboard-server lives at `inventory-server/dashboard/` (not its own top-level dir).** Plan's Phase 4 diagram implied a sibling of `inventory-server/` etc. The merged service lives at `inventory-server/dashboard/server.js` with `package.json` declaring `"type": "module"`. Per-vendor subdirectories (`klaviyo-server/`, `meta-server/`, `google-server/`, `typeform-server/`) each have their own `package.json` so Node's "nearest parent package.json" walk stops there — they are unaffected by the new parent type. Added `"type": "commonjs"` defensively to meta/google/typeform package.json so a future deletion of their files (cutover cleanup) plus a stray `*.js` left under `dashboard/` wouldn't accidentally try to ESM-parse it.
|
||||||
|
|
||||||
|
17. **Klaviyo `RedisService` kept as a wrapper, but accepts injected client.** Plan said "replace each server's per-instance pool/redis with the injected one." The Klaviyo codebase has ~3K LOC of service code (`events.service.js` alone is 2.2K) that calls `this.redisService._getCacheKey()`, `.get()`, `.set()`, `.getEventData()`, `.clearCache()`, `._getTTL()`. Rewriting all of that to call ioredis directly would risk breaking the cache-key/TTL invariants. Decision: keep `services/klaviyo/redis.service.js` as a thin facade with the same public surface, but its constructor now takes an ioredis client instead of constructing one. The 3 service classes (`EventsService`, `CampaignsService`, `ReportingService`) all take `(apiKey, apiRevision, redis)` and pass `redis` to `new RedisService(redis)`. `MetricsService` doesn't use Redis — left unchanged.
|
||||||
|
|
||||||
|
18. **dashboard-server `.env` layering.** Plan called for "Single `.env` at `inventory/dashboard/.env`, prefixed keys: KLAVIYO_*, META_*, ... JWT_SECRET ... # shared with auth-server." Implemented as two-file layering: `server.js` loads `/var/www/inventory/.env` FIRST (provides JWT_SECRET, DB_*, REDIS_*) then `inventory-server/dashboard/.env` SECOND for vendor-specific keys (KLAVIYO_API_KEY, META_*, GA_*, TYPEFORM_*). dotenv defaults to `override:false`, so the first file wins on collisions — security-critical vars live in one place, vendor keys in the other. `.env.example` template committed at `dashboard/.env.example`. **Pre-cutover step**: copy the vendor keys from the current per-vendor `.env` files into either of those two files before `pm2 reload`, else KLAVIYO_API_KEY etc. will not be set and routes will 500.
|
||||||
|
|
||||||
|
19. **Caddyfile typo fixed: `/api/google-analytics` → `/api/dashboard-analytics`.** The pre-Phase-4 `Caddyfile.proposed` listed a `handle /api/google-analytics/*` block. The live Caddyfile and the frontend (`inventory/src/config/dashboard.ts`) both use `/api/dashboard-analytics/*` (the live file has a `uri replace /api/dashboard-analytics /api/analytics` rewrite to land on google-server's `/api/analytics` mount). The merged dashboard-server now mounts the Google router at `/api/dashboard-analytics` directly — Caddy no longer needs the rewrite, just a straight reverse_proxy. Fixed in `deploy/Caddyfile.proposed`.
|
||||||
|
|
||||||
|
20. **`metrics.routes.js` had a latent router-scope bug.** The Klaviyo `metrics.routes.js` declared `const router = express.Router()` at MODULE scope (outside the `createMetricsRouter` factory), so calling the factory twice would have re-mounted handlers on the same router (cumulative). Benign for a single-mount PM2 service, but fixed during the Phase 4 copy — the router now lives inside the factory. Also renamed the export from `createMetricsRoutes` (plural) to `createMetricsRouter` (matches the convention used by every other vendor's index.js).
|
||||||
|
|
||||||
|
21. **PM2 log paths use per-server `logs/pm2/` (NOT `/var/log/pm2/`).** Discovered during the first apply attempt: the previously-shipped `ecosystem.config.cjs.proposed` carried over `/var/log/pm2/...` from the live file, but matt has no write perms on `/var/log` (root:syslog 775) so the entries silently failed to launch (chat-server + acot-server came up because they had no explicit log path; new-auth-server, inventory-server, dashboard-server bailed). The actual convention — already in place via pre-created folders on disk — is per-service `logs/pm2/` directly under each service's directory (`./inventory/auth/logs/pm2/`, `./inventory/chat/logs/pm2/`, `./inventory/dashboard/acot-server/logs/pm2/`, `./inventory/dashboard/logs/pm2/` for the merged dashboard-server, `./inventory/logs/pm2/` for inventory-server, `/opt/lt-wordlist-api/logs/pm2/`, `/var/www/acot-phone/logs/pm2/`). All folders are matt:matt. `pm2-logrotate` (already loaded in matt's daemon) rotates them in place.
|
||||||
|
|
||||||
|
22. **All PM2 apps run under matt's single daemon — no root daemon.** The earlier `OUT OF SCOPE` comment block in the proposed ecosystem incorrectly claimed `lt-wordlist-api` and `acot-phone-server` were managed by a separate root PM2 daemon. They are not — matt's daemon manages everything. Removed the bogus block; both apps are now first-class entries in the proposed ecosystem with corrected script paths:
|
||||||
|
- `lt-wordlist-api` script is `/opt/lt-wordlist-api/index.js` (was `/opt/lt-wordlist-api/server.js` in the live file — wrong; that file doesn't exist). `/opt/lt-wordlist-api` is matt:matt 0750.
|
||||||
|
- `acot-phone-server` script is `/var/www/acot-phone/dist/server.js` (was `./inventory/acot-phone/server.js` in the live file — wrong; that path doesn't exist). `/var/www/acot-phone/` is matt:matt with its own `.env` and is a separate repo from inventory-server.
|
||||||
|
|
||||||
|
23. **Phase 6.10 ADD_WORD_TOKEN move stays in this ecosystem.** Per Deviation #22, `lt-wordlist-api` is in matt's ecosystem, so the §6.10 work to remove inline `ADD_WORD_TOKEN` and load it from `/opt/lt-wordlist-api/.env` instead is implemented directly in `deploy/ecosystem.config.cjs.proposed` (no inline `ADD_WORD_TOKEN`; script reads its own .env). When applying, rotate the token value in `/opt/lt-wordlist-api/.env` and update any callers.
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
# Caching Server Configuration
|
|
||||||
PORT=3010
|
|
||||||
NODE_ENV=production
|
|
||||||
|
|
||||||
# Database Configuration
|
|
||||||
MONGODB_URI=mongodb://dashboard_user:WDRFWiGXEeaC6aAyUKuT@localhost:27017/dashboard?authSource=dashboard
|
|
||||||
REDIS_URL=redis://:Wgj32YXxxVLtPZoVzUnP@localhost:6379
|
|
||||||
|
|
||||||
# Gorgias
|
|
||||||
GORGIAS_API_USERNAME=matt@acherryontop.com
|
|
||||||
GORGIAS_API_PASSWORD=d2ed0d23d2a7bf11a633a12fb260769f4e4a970d440693e7d64b8d2223fa6503
|
|
||||||
|
|
||||||
# GA4 credentials
|
|
||||||
GA_PROPERTY_ID=281045851
|
|
||||||
GOOGLE_APPLICATION_CREDENTIALS_JSON={"type": "service_account","project_id": "acot-stats","private_key_id": "259d1fd9864efbfa38b8ba02fdd74dc008ace3c5","private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC5Y6foai8WF98k\nIA0yLn94Y3lmDYlyvI9xL2YqSZSyvgK35wdWRTIaEvHKdiUWuYi3ZPdkYmz1OYiV\njVfR2g+mFpA7MI/JMwyGWwjnV4WW2q6INfgi/PvHlbP3LyyQo0B8CvAY0CHqrpDs\nlJQhAkqmteU24dqcdZoV3vM8JMsDiXm44DqwXsEfWibKv4i0mWNkwiEQr0yImHwb\nbjgclwVLLi5kdM2+49PXr47LCODdL+xmX0uSdgSG6XYqEIVsEOXIUJKzqUe036b/\nEFQ0BxWdJBWs/MYOapn/NNv+Mts+am2ipUuIcgPbOut4xa2Fkky93WnJf0tB+VJP\njFnyZJhdAgMBAAECggEAC980Cp/4zvSNZMNWr6l8ST8u2thavnRmcoGYtx7ffQjK\nT3Dl2TefgJLzqpr2lLt3OVint7p5LsUAmE8lBLpu+RxbH9HkIKbPvQTfD5gyZQQx\nBruqCGzkn2st9fzZNj6gwQYe9P/TGYkUnR8wqI0nLwDZTQful3QNKixiWC4lAAoK\nqdd6H++pqjVUiTqgFwFD3zBAhO0Lp8m/c5vTRT5kxi0wCTK66FaaGLr2OwZHcohp\nE8rEcTZ5kaJzBwqEz522R6ufQqN1Swoq4K6Ul3aAc59539VdrLNs++/eRH38MMVq\n5UTwBrH+zIkXIYv4mtGpR1NWGO2bZ652GzGXNEXcQQKBgQD9WsMmioIeWR9P9I0r\nIY+yyxz1EyscutUtnOtROT36OxokrzQaAKDz/OC3jVnhZSkzG6RcmmK/AJrcU+2m\n1L4mZGfF3DdeTqtK/KkNzGs9yRPDkbb/MF0wgtcvfE8tJH/suiDJKQNsjeaQIQW3\n4NvDxs0w60m9r9tk1CQau94ovQKBgQC7UzeA0mDSxIB5agGbvnzaJJTvAFvnCvhz\nu3ZakTlNecAHu4eOMc0+OCHFPLJlLL4b0oraOxZIszX9BTlgcstBmTUk03TibNsS\nsDiImHFC4hE5x6EPdifnkVFUXPMZ/eF0mHUPBEn41ipw1hoLfl6W+aYW9QUxBMWA\nzdMH4rg4IQKBgQCFcMaUiCNchKhfXnj0HKspCp3n3v64FReu/JVcpH+mSnbMl5Mj\nlu0vVSOuyb5rXvLCPm7lb1NPMqxeG75yPl8grYWSyxhGjbzetBD+eYqKclv8h8UQ\nx5JtuJxKIHk7V5whPS+DhByPknW7uAjg/ogBp7XvbB3c0MEHbEzP3991KQKBgC+a\n610Kmd6WX4v7e6Mn2rTZXRwL/E8QA6nttxs3Etf0m++bIczqLR2lyDdGwJNjtoB9\nlhn1sCkTmiHOBRHUuoDWPaI5NtggD+CE9ikIjKgRqY0EhZLXVTbNQFzvLjypv3UR\nFZaWYXIigzCfyIipOcKmeSYWaJZXfxXHuNylKmnhAoGAFa84AuOOGUr+pEvtUzIr\nvBKu1mnQbbsLEhgf3Tw88K3sO5OlguAwBEvD4eitj/aU5u2vJJhFa67cuERLsZru\n0sjtQwP6CJbWF4uaH0Hso4KQvnwl4BfdKwUncqoKtHrQiuGMvr5P5G941+Ax8brE\nJlC2e/RPUQKxScpK3nNK9mc=\n-----END PRIVATE KEY-----\n","client_email": "matt-dashboard@acot-stats.iam.gserviceaccount.com","client_id": "106112731322970982546","auth_uri": "https://accounts.google.com/o/oauth2/auth","token_uri": "https://oauth2.googleapis.com/token","auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/matt-dashboard%40acot-stats.iam.gserviceaccount.com","universe_domain": "googleapis.com"}
|
|
||||||
|
|
||||||
# Logging
|
|
||||||
LOG_LEVEL=info
|
|
||||||
LOG_MAX_SIZE=10m
|
|
||||||
LOG_MAX_FILES=5
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# dashboard-server .env template (Phase 4)
|
||||||
|
#
|
||||||
|
# The merged dashboard-server reads /var/www/inventory/.env FIRST (provides
|
||||||
|
# JWT_SECRET, DB_*, REDIS_*) and then layers this .env on top for vendor keys.
|
||||||
|
# Shared/security-critical vars stay in /var/www/inventory/.env so they aren't
|
||||||
|
# duplicated; vendor keys live here.
|
||||||
|
#
|
||||||
|
# Copy to .env and populate. Do NOT commit the populated file.
|
||||||
|
|
||||||
|
# Port the merged service listens on
|
||||||
|
DASHBOARD_PORT=3015
|
||||||
|
|
||||||
|
# Klaviyo (replaces klaviyo-server/.env)
|
||||||
|
KLAVIYO_API_KEY=
|
||||||
|
KLAVIYO_API_REVISION=2024-02-15
|
||||||
|
KLAVIYO_API_URL=https://a.klaviyo.com/api
|
||||||
|
|
||||||
|
# Meta / Facebook Ads (replaces meta-server/.env)
|
||||||
|
META_ACCESS_TOKEN=
|
||||||
|
META_AD_ACCOUNT_ID=
|
||||||
|
META_API_VERSION=v21.0
|
||||||
|
|
||||||
|
# Google Analytics (replaces google-server/.env)
|
||||||
|
GA_PROPERTY_ID=
|
||||||
|
GOOGLE_APPLICATION_CREDENTIALS_JSON=
|
||||||
|
|
||||||
|
# Typeform (replaces typeform-server/.env)
|
||||||
|
TYPEFORM_ACCESS_TOKEN=
|
||||||
|
|
||||||
|
# Vendors share the inventory REDIS_URL or REDIS_HOST/PORT/USERNAME/PASSWORD
|
||||||
|
# from the parent .env. Do NOT redeclare here unless you need a vendor-only
|
||||||
|
# override (rare; would need to fork shared/db/redis.js too).
|
||||||
@@ -1 +0,0 @@
|
|||||||
/etc/nginx/sites-enabled/dashboard.conf
|
|
||||||
-2538
File diff suppressed because it is too large
Load Diff
@@ -1,21 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "google-analytics-server",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"description": "Google Analytics server for dashboard",
|
|
||||||
"main": "server.js",
|
|
||||||
"scripts": {
|
|
||||||
"start": "node server.js",
|
|
||||||
"dev": "nodemon server.js"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@google-analytics/data": "^4.0.0",
|
|
||||||
"cors": "^2.8.5",
|
|
||||||
"dotenv": "^16.3.1",
|
|
||||||
"express": "^4.18.2",
|
|
||||||
"redis": "^4.6.11",
|
|
||||||
"winston": "^3.11.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"nodemon": "^3.0.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,254 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const { BetaAnalyticsDataClient } = require('@google-analytics/data');
|
|
||||||
const router = express.Router();
|
|
||||||
const logger = require('../utils/logger');
|
|
||||||
|
|
||||||
// Initialize GA4 client
|
|
||||||
const analyticsClient = new BetaAnalyticsDataClient({
|
|
||||||
credentials: JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS_JSON)
|
|
||||||
});
|
|
||||||
|
|
||||||
const propertyId = process.env.GA_PROPERTY_ID;
|
|
||||||
|
|
||||||
// Cache durations
|
|
||||||
const CACHE_DURATIONS = {
|
|
||||||
REALTIME_BASIC: 60, // 1 minute
|
|
||||||
REALTIME_DETAILED: 300, // 5 minutes
|
|
||||||
BASIC_METRICS: 3600, // 1 hour
|
|
||||||
USER_BEHAVIOR: 3600 // 1 hour
|
|
||||||
};
|
|
||||||
|
|
||||||
// Basic metrics endpoint
|
|
||||||
router.get('/metrics', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { startDate = '7daysAgo' } = req.query;
|
|
||||||
const cacheKey = `analytics:basic_metrics:${startDate}`;
|
|
||||||
|
|
||||||
// Check Redis cache
|
|
||||||
const cachedData = await req.redisClient.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
logger.info('Returning cached basic metrics data');
|
|
||||||
return res.json({ success: true, data: JSON.parse(cachedData) });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch from GA4
|
|
||||||
const [response] = await analyticsClient.runReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
dateRanges: [{ startDate, endDate: 'today' }],
|
|
||||||
dimensions: [{ name: 'date' }],
|
|
||||||
metrics: [
|
|
||||||
{ name: 'activeUsers' },
|
|
||||||
{ name: 'newUsers' },
|
|
||||||
{ name: 'averageSessionDuration' },
|
|
||||||
{ name: 'screenPageViews' },
|
|
||||||
{ name: 'bounceRate' },
|
|
||||||
{ name: 'conversions' }
|
|
||||||
],
|
|
||||||
returnPropertyQuota: true
|
|
||||||
});
|
|
||||||
|
|
||||||
// Cache the response
|
|
||||||
await req.redisClient.set(cacheKey, JSON.stringify(response), {
|
|
||||||
EX: CACHE_DURATIONS.BASIC_METRICS
|
|
||||||
});
|
|
||||||
|
|
||||||
res.json({ success: true, data: response });
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error fetching basic metrics:', error);
|
|
||||||
res.status(500).json({ success: false, error: error.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Realtime basic data endpoint
|
|
||||||
router.get('/realtime/basic', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const cacheKey = 'analytics:realtime:basic';
|
|
||||||
|
|
||||||
// Check Redis cache
|
|
||||||
const cachedData = await req.redisClient.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
logger.info('Returning cached realtime basic data');
|
|
||||||
return res.json({ success: true, data: JSON.parse(cachedData) });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch active users
|
|
||||||
const [userResponse] = await analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
metrics: [{ name: 'activeUsers' }],
|
|
||||||
returnPropertyQuota: true
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch last 5 minutes
|
|
||||||
const [fiveMinResponse] = await analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
metrics: [{ name: 'activeUsers' }],
|
|
||||||
minuteRanges: [{ startMinutesAgo: 5, endMinutesAgo: 0 }]
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch time series data
|
|
||||||
const [timeSeriesResponse] = await analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
dimensions: [{ name: 'minutesAgo' }],
|
|
||||||
metrics: [{ name: 'activeUsers' }]
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = {
|
|
||||||
userResponse,
|
|
||||||
fiveMinResponse,
|
|
||||||
timeSeriesResponse,
|
|
||||||
quotaInfo: {
|
|
||||||
projectHourly: userResponse.propertyQuota.tokensPerProjectPerHour,
|
|
||||||
daily: userResponse.propertyQuota.tokensPerDay,
|
|
||||||
serverErrors: userResponse.propertyQuota.serverErrorsPerProjectPerHour,
|
|
||||||
thresholdedRequests: userResponse.propertyQuota.potentiallyThresholdedRequestsPerHour
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Cache the response
|
|
||||||
await req.redisClient.set(cacheKey, JSON.stringify(response), {
|
|
||||||
EX: CACHE_DURATIONS.REALTIME_BASIC
|
|
||||||
});
|
|
||||||
|
|
||||||
res.json({ success: true, data: response });
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error fetching realtime basic data:', error);
|
|
||||||
res.status(500).json({ success: false, error: error.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Realtime detailed data endpoint
|
|
||||||
router.get('/realtime/detailed', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const cacheKey = 'analytics:realtime:detailed';
|
|
||||||
|
|
||||||
// Check Redis cache
|
|
||||||
const cachedData = await req.redisClient.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
logger.info('Returning cached realtime detailed data');
|
|
||||||
return res.json({ success: true, data: JSON.parse(cachedData) });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch current pages
|
|
||||||
const [pageResponse] = await analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
dimensions: [{ name: 'unifiedScreenName' }],
|
|
||||||
metrics: [{ name: 'screenPageViews' }],
|
|
||||||
orderBy: [{ metric: { metricName: 'screenPageViews' }, desc: true }],
|
|
||||||
limit: 25
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch events
|
|
||||||
const [eventResponse] = await analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
dimensions: [{ name: 'eventName' }],
|
|
||||||
metrics: [{ name: 'eventCount' }],
|
|
||||||
orderBy: [{ metric: { metricName: 'eventCount' }, desc: true }],
|
|
||||||
limit: 25
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch device categories
|
|
||||||
const [deviceResponse] = await analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
dimensions: [{ name: 'deviceCategory' }],
|
|
||||||
metrics: [{ name: 'activeUsers' }],
|
|
||||||
orderBy: [{ metric: { metricName: 'activeUsers' }, desc: true }],
|
|
||||||
limit: 10,
|
|
||||||
returnPropertyQuota: true
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = {
|
|
||||||
pageResponse,
|
|
||||||
eventResponse,
|
|
||||||
sourceResponse: deviceResponse
|
|
||||||
};
|
|
||||||
|
|
||||||
// Cache the response
|
|
||||||
await req.redisClient.set(cacheKey, JSON.stringify(response), {
|
|
||||||
EX: CACHE_DURATIONS.REALTIME_DETAILED
|
|
||||||
});
|
|
||||||
|
|
||||||
res.json({ success: true, data: response });
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error fetching realtime detailed data:', error);
|
|
||||||
res.status(500).json({ success: false, error: error.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// User behavior endpoint
|
|
||||||
router.get('/user-behavior', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { timeRange = '30' } = req.query;
|
|
||||||
const cacheKey = `analytics:user_behavior:${timeRange}`;
|
|
||||||
|
|
||||||
// Check Redis cache
|
|
||||||
const cachedData = await req.redisClient.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
logger.info('Returning cached user behavior data');
|
|
||||||
return res.json({ success: true, data: JSON.parse(cachedData) });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch page data
|
|
||||||
const [pageResponse] = await analyticsClient.runReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
|
||||||
dimensions: [{ name: 'pagePath' }],
|
|
||||||
metrics: [
|
|
||||||
{ name: 'screenPageViews' },
|
|
||||||
{ name: 'averageSessionDuration' },
|
|
||||||
{ name: 'bounceRate' },
|
|
||||||
{ name: 'sessions' }
|
|
||||||
],
|
|
||||||
orderBy: [{
|
|
||||||
metric: { metricName: 'screenPageViews' },
|
|
||||||
desc: true
|
|
||||||
}],
|
|
||||||
limit: 25
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch device data
|
|
||||||
const [deviceResponse] = await analyticsClient.runReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
|
||||||
dimensions: [{ name: 'deviceCategory' }],
|
|
||||||
metrics: [
|
|
||||||
{ name: 'screenPageViews' },
|
|
||||||
{ name: 'sessions' }
|
|
||||||
]
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch source data
|
|
||||||
const [sourceResponse] = await analyticsClient.runReport({
|
|
||||||
property: `properties/${propertyId}`,
|
|
||||||
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
|
||||||
dimensions: [{ name: 'sessionSource' }],
|
|
||||||
metrics: [
|
|
||||||
{ name: 'sessions' },
|
|
||||||
{ name: 'conversions' }
|
|
||||||
],
|
|
||||||
orderBy: [{
|
|
||||||
metric: { metricName: 'sessions' },
|
|
||||||
desc: true
|
|
||||||
}],
|
|
||||||
limit: 25,
|
|
||||||
returnPropertyQuota: true
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = {
|
|
||||||
pageResponse,
|
|
||||||
deviceResponse,
|
|
||||||
sourceResponse
|
|
||||||
};
|
|
||||||
|
|
||||||
// Cache the response
|
|
||||||
await req.redisClient.set(cacheKey, JSON.stringify(response), {
|
|
||||||
EX: CACHE_DURATIONS.USER_BEHAVIOR
|
|
||||||
});
|
|
||||||
|
|
||||||
res.json({ success: true, data: response });
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error fetching user behavior data:', error);
|
|
||||||
res.status(500).json({ success: false, error: error.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const analyticsService = require('../services/analytics.service');
|
|
||||||
|
|
||||||
// Basic metrics endpoint
|
|
||||||
router.get('/metrics', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { startDate = '7daysAgo' } = req.query;
|
|
||||||
console.log(`Fetching metrics with startDate: ${startDate}`);
|
|
||||||
|
|
||||||
const data = await analyticsService.getBasicMetrics(startDate);
|
|
||||||
res.json({ success: true, data });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Metrics error:', {
|
|
||||||
startDate: req.query.startDate,
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack
|
|
||||||
});
|
|
||||||
|
|
||||||
res.status(500).json({
|
|
||||||
success: false,
|
|
||||||
error: 'Failed to fetch metrics',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Realtime basic data endpoint
|
|
||||||
router.get('/realtime/basic', async (req, res) => {
|
|
||||||
try {
|
|
||||||
console.log('Fetching realtime basic data');
|
|
||||||
const data = await analyticsService.getRealTimeBasicData();
|
|
||||||
res.json({ success: true, data });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Realtime basic error:', {
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack
|
|
||||||
});
|
|
||||||
|
|
||||||
res.status(500).json({
|
|
||||||
success: false,
|
|
||||||
error: 'Failed to fetch realtime basic data',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Realtime detailed data endpoint
|
|
||||||
router.get('/realtime/detailed', async (req, res) => {
|
|
||||||
try {
|
|
||||||
console.log('Fetching realtime detailed data');
|
|
||||||
const data = await analyticsService.getRealTimeDetailedData();
|
|
||||||
res.json({ success: true, data });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Realtime detailed error:', {
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack
|
|
||||||
});
|
|
||||||
|
|
||||||
res.status(500).json({
|
|
||||||
success: false,
|
|
||||||
error: 'Failed to fetch realtime detailed data',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// User behavior endpoint
|
|
||||||
router.get('/user-behavior', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { timeRange = '30' } = req.query;
|
|
||||||
console.log(`Fetching user behavior with timeRange: ${timeRange}`);
|
|
||||||
|
|
||||||
const data = await analyticsService.getUserBehavior(timeRange);
|
|
||||||
res.json({ success: true, data });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('User behavior error:', {
|
|
||||||
timeRange: req.query.timeRange,
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack
|
|
||||||
});
|
|
||||||
|
|
||||||
res.status(500).json({
|
|
||||||
success: false,
|
|
||||||
error: 'Failed to fetch user behavior data',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const cors = require('cors');
|
|
||||||
const { createClient } = require('redis');
|
|
||||||
const analyticsRoutes = require('./routes/analytics.routes');
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const port = process.env.GOOGLE_ANALYTICS_PORT || 3007;
|
|
||||||
|
|
||||||
// Redis client setup
|
|
||||||
const redisClient = createClient({
|
|
||||||
url: process.env.REDIS_URL || 'redis://localhost:6379'
|
|
||||||
});
|
|
||||||
|
|
||||||
redisClient.on('error', (err) => console.error('Redis Client Error:', err));
|
|
||||||
redisClient.on('connect', () => console.log('Redis Client Connected'));
|
|
||||||
|
|
||||||
// Connect to Redis
|
|
||||||
(async () => {
|
|
||||||
try {
|
|
||||||
await redisClient.connect();
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Redis connection error:', err);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
// Middleware
|
|
||||||
app.use(cors());
|
|
||||||
app.use(express.json());
|
|
||||||
|
|
||||||
// Make Redis client available in requests
|
|
||||||
app.use((req, res, next) => {
|
|
||||||
req.redisClient = redisClient;
|
|
||||||
next();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Routes
|
|
||||||
app.use('/api/analytics', analyticsRoutes);
|
|
||||||
|
|
||||||
// Error handling middleware
|
|
||||||
app.use((err, req, res, next) => {
|
|
||||||
console.error('Server error:', err);
|
|
||||||
res.status(err.status || 500).json({
|
|
||||||
success: false,
|
|
||||||
message: err.message || 'Internal server error',
|
|
||||||
error: process.env.NODE_ENV === 'production' ? err : {}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Start server
|
|
||||||
app.listen(port, () => {
|
|
||||||
console.log(`Google Analytics server running on port ${port}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle graceful shutdown
|
|
||||||
process.on('SIGTERM', async () => {
|
|
||||||
console.log('SIGTERM received. Shutting down gracefully...');
|
|
||||||
await redisClient.quit();
|
|
||||||
process.exit(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
process.on('SIGINT', async () => {
|
|
||||||
console.log('SIGINT received. Shutting down gracefully...');
|
|
||||||
await redisClient.quit();
|
|
||||||
process.exit(0);
|
|
||||||
});
|
|
||||||
@@ -1,283 +0,0 @@
|
|||||||
const { BetaAnalyticsDataClient } = require('@google-analytics/data');
|
|
||||||
const { createClient } = require('redis');
|
|
||||||
|
|
||||||
class AnalyticsService {
|
|
||||||
constructor() {
|
|
||||||
// Initialize Redis client
|
|
||||||
this.redis = createClient({
|
|
||||||
url: process.env.REDIS_URL || 'redis://localhost:6379'
|
|
||||||
});
|
|
||||||
|
|
||||||
this.redis.on('error', err => console.error('Redis Client Error:', err));
|
|
||||||
this.redis.connect().catch(err => console.error('Redis connection error:', err));
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Initialize GA4 client
|
|
||||||
const credentials = process.env.GOOGLE_APPLICATION_CREDENTIALS_JSON;
|
|
||||||
this.analyticsClient = new BetaAnalyticsDataClient({
|
|
||||||
credentials: typeof credentials === 'string' ? JSON.parse(credentials) : credentials
|
|
||||||
});
|
|
||||||
|
|
||||||
this.propertyId = process.env.GA_PROPERTY_ID;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to initialize GA4 client:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cache durations
|
|
||||||
CACHE_DURATIONS = {
|
|
||||||
REALTIME_BASIC: 60, // 1 minute
|
|
||||||
REALTIME_DETAILED: 300, // 5 minutes
|
|
||||||
BASIC_METRICS: 3600, // 1 hour
|
|
||||||
USER_BEHAVIOR: 3600 // 1 hour
|
|
||||||
};
|
|
||||||
|
|
||||||
async getBasicMetrics(startDate = '7daysAgo') {
|
|
||||||
const cacheKey = `analytics:basic_metrics:${startDate}`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Try Redis first
|
|
||||||
const cachedData = await this.redis.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
console.log('Analytics metrics found in Redis cache');
|
|
||||||
return JSON.parse(cachedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch from GA4
|
|
||||||
console.log('Fetching fresh metrics data from GA4');
|
|
||||||
const [response] = await this.analyticsClient.runReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
dateRanges: [{ startDate, endDate: 'today' }],
|
|
||||||
dimensions: [{ name: 'date' }],
|
|
||||||
metrics: [
|
|
||||||
{ name: 'activeUsers' },
|
|
||||||
{ name: 'newUsers' },
|
|
||||||
{ name: 'averageSessionDuration' },
|
|
||||||
{ name: 'screenPageViews' },
|
|
||||||
{ name: 'bounceRate' },
|
|
||||||
{ name: 'conversions' }
|
|
||||||
],
|
|
||||||
returnPropertyQuota: true
|
|
||||||
});
|
|
||||||
|
|
||||||
// Cache the response
|
|
||||||
await this.redis.set(cacheKey, JSON.stringify(response), {
|
|
||||||
EX: this.CACHE_DURATIONS.BASIC_METRICS
|
|
||||||
});
|
|
||||||
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching analytics metrics:', {
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getRealTimeBasicData() {
|
|
||||||
const cacheKey = 'analytics:realtime:basic';
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Try Redis first
|
|
||||||
const cachedData = await this.redis.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
console.log('Realtime basic data found in Redis cache');
|
|
||||||
return JSON.parse(cachedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Fetching fresh realtime data from GA4');
|
|
||||||
|
|
||||||
// Fetch active users
|
|
||||||
const [userResponse] = await this.analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
metrics: [{ name: 'activeUsers' }],
|
|
||||||
returnPropertyQuota: true
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch last 5 minutes
|
|
||||||
const [fiveMinResponse] = await this.analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
metrics: [{ name: 'activeUsers' }],
|
|
||||||
minuteRanges: [{ startMinutesAgo: 5, endMinutesAgo: 0 }]
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch time series data
|
|
||||||
const [timeSeriesResponse] = await this.analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
dimensions: [{ name: 'minutesAgo' }],
|
|
||||||
metrics: [{ name: 'activeUsers' }]
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = {
|
|
||||||
userResponse,
|
|
||||||
fiveMinResponse,
|
|
||||||
timeSeriesResponse,
|
|
||||||
quotaInfo: {
|
|
||||||
projectHourly: userResponse.propertyQuota.tokensPerProjectPerHour,
|
|
||||||
daily: userResponse.propertyQuota.tokensPerDay,
|
|
||||||
serverErrors: userResponse.propertyQuota.serverErrorsPerProjectPerHour,
|
|
||||||
thresholdedRequests: userResponse.propertyQuota.potentiallyThresholdedRequestsPerHour
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Cache the response
|
|
||||||
await this.redis.set(cacheKey, JSON.stringify(response), {
|
|
||||||
EX: this.CACHE_DURATIONS.REALTIME_BASIC
|
|
||||||
});
|
|
||||||
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching realtime basic data:', {
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getRealTimeDetailedData() {
|
|
||||||
const cacheKey = 'analytics:realtime:detailed';
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Try Redis first
|
|
||||||
const cachedData = await this.redis.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
console.log('Realtime detailed data found in Redis cache');
|
|
||||||
return JSON.parse(cachedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Fetching fresh realtime detailed data from GA4');
|
|
||||||
|
|
||||||
// Fetch current pages
|
|
||||||
const [pageResponse] = await this.analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
dimensions: [{ name: 'unifiedScreenName' }],
|
|
||||||
metrics: [{ name: 'screenPageViews' }],
|
|
||||||
orderBy: [{ metric: { metricName: 'screenPageViews' }, desc: true }],
|
|
||||||
limit: 25
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch events
|
|
||||||
const [eventResponse] = await this.analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
dimensions: [{ name: 'eventName' }],
|
|
||||||
metrics: [{ name: 'eventCount' }],
|
|
||||||
orderBy: [{ metric: { metricName: 'eventCount' }, desc: true }],
|
|
||||||
limit: 25
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch device categories
|
|
||||||
const [deviceResponse] = await this.analyticsClient.runRealtimeReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
dimensions: [{ name: 'deviceCategory' }],
|
|
||||||
metrics: [{ name: 'activeUsers' }],
|
|
||||||
orderBy: [{ metric: { metricName: 'activeUsers' }, desc: true }],
|
|
||||||
limit: 10,
|
|
||||||
returnPropertyQuota: true
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = {
|
|
||||||
pageResponse,
|
|
||||||
eventResponse,
|
|
||||||
sourceResponse: deviceResponse
|
|
||||||
};
|
|
||||||
|
|
||||||
// Cache the response
|
|
||||||
await this.redis.set(cacheKey, JSON.stringify(response), {
|
|
||||||
EX: this.CACHE_DURATIONS.REALTIME_DETAILED
|
|
||||||
});
|
|
||||||
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching realtime detailed data:', {
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getUserBehavior(timeRange = '30') {
|
|
||||||
const cacheKey = `analytics:user_behavior:${timeRange}`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Try Redis first
|
|
||||||
const cachedData = await this.redis.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
console.log('User behavior data found in Redis cache');
|
|
||||||
return JSON.parse(cachedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Fetching fresh user behavior data from GA4');
|
|
||||||
|
|
||||||
// Fetch page data
|
|
||||||
const [pageResponse] = await this.analyticsClient.runReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
|
||||||
dimensions: [{ name: 'pagePath' }],
|
|
||||||
metrics: [
|
|
||||||
{ name: 'screenPageViews' },
|
|
||||||
{ name: 'averageSessionDuration' },
|
|
||||||
{ name: 'bounceRate' },
|
|
||||||
{ name: 'sessions' }
|
|
||||||
],
|
|
||||||
orderBy: [{
|
|
||||||
metric: { metricName: 'screenPageViews' },
|
|
||||||
desc: true
|
|
||||||
}],
|
|
||||||
limit: 25
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch device data
|
|
||||||
const [deviceResponse] = await this.analyticsClient.runReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
|
||||||
dimensions: [{ name: 'deviceCategory' }],
|
|
||||||
metrics: [
|
|
||||||
{ name: 'screenPageViews' },
|
|
||||||
{ name: 'sessions' }
|
|
||||||
]
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch source data
|
|
||||||
const [sourceResponse] = await this.analyticsClient.runReport({
|
|
||||||
property: `properties/${this.propertyId}`,
|
|
||||||
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
|
||||||
dimensions: [{ name: 'sessionSource' }],
|
|
||||||
metrics: [
|
|
||||||
{ name: 'sessions' },
|
|
||||||
{ name: 'conversions' }
|
|
||||||
],
|
|
||||||
orderBy: [{
|
|
||||||
metric: { metricName: 'sessions' },
|
|
||||||
desc: true
|
|
||||||
}],
|
|
||||||
limit: 25,
|
|
||||||
returnPropertyQuota: true
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = {
|
|
||||||
pageResponse,
|
|
||||||
deviceResponse,
|
|
||||||
sourceResponse
|
|
||||||
};
|
|
||||||
|
|
||||||
// Cache the response
|
|
||||||
await this.redis.set(cacheKey, JSON.stringify(response), {
|
|
||||||
EX: this.CACHE_DURATIONS.USER_BEHAVIOR
|
|
||||||
});
|
|
||||||
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching user behavior data:', {
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = new AnalyticsService();
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
const winston = require('winston');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
const logger = winston.createLogger({
|
|
||||||
level: process.env.LOG_LEVEL || 'info',
|
|
||||||
format: winston.format.combine(
|
|
||||||
winston.format.timestamp(),
|
|
||||||
winston.format.json()
|
|
||||||
),
|
|
||||||
transports: [
|
|
||||||
new winston.transports.File({
|
|
||||||
filename: path.join(__dirname, '../logs/pm2/error.log'),
|
|
||||||
level: 'error',
|
|
||||||
maxsize: 10485760, // 10MB
|
|
||||||
maxFiles: 5
|
|
||||||
}),
|
|
||||||
new winston.transports.File({
|
|
||||||
filename: path.join(__dirname, '../logs/pm2/combined.log'),
|
|
||||||
maxsize: 10485760, // 10MB
|
|
||||||
maxFiles: 5
|
|
||||||
})
|
|
||||||
]
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add console transport in development
|
|
||||||
if (process.env.NODE_ENV !== 'production') {
|
|
||||||
logger.add(new winston.transports.Console({
|
|
||||||
format: winston.format.combine(
|
|
||||||
winston.format.colorize(),
|
|
||||||
winston.format.simple()
|
|
||||||
)
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = logger;
|
|
||||||
-2104
File diff suppressed because it is too large
Load Diff
@@ -1,26 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "klaviyo-server",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"description": "Klaviyo API integration server",
|
|
||||||
"main": "server.js",
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"start": "node server.js",
|
|
||||||
"dev": "nodemon server.js"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"cors": "^2.8.5",
|
|
||||||
"dotenv": "^16.4.7",
|
|
||||||
"esm": "^3.2.25",
|
|
||||||
"express": "^4.18.2",
|
|
||||||
"express-rate-limit": "^7.5.0",
|
|
||||||
"ioredis": "^5.4.1",
|
|
||||||
"luxon": "^3.5.0",
|
|
||||||
"node-fetch": "^3.3.2",
|
|
||||||
"pg": "^8.18.0",
|
|
||||||
"recharts": "^2.15.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"nodemon": "^3.0.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import express from 'express';
|
|
||||||
import { createEventsRouter } from './events.routes.js';
|
|
||||||
import { createMetricsRoutes } from './metrics.routes.js';
|
|
||||||
import { createCampaignsRouter } from './campaigns.routes.js';
|
|
||||||
import { createReportingRouter } from './reporting.routes.js';
|
|
||||||
|
|
||||||
export function createApiRouter(apiKey, apiRevision) {
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
// Mount routers
|
|
||||||
router.use('/events', createEventsRouter(apiKey, apiRevision));
|
|
||||||
router.use('/metrics', createMetricsRoutes(apiKey, apiRevision));
|
|
||||||
router.use('/campaigns', createCampaignsRouter(apiKey, apiRevision));
|
|
||||||
router.use('/reporting', createReportingRouter(apiKey, apiRevision));
|
|
||||||
|
|
||||||
return router;
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
import express from 'express';
|
|
||||||
import cors from 'cors';
|
|
||||||
import dotenv from 'dotenv';
|
|
||||||
import rateLimit from 'express-rate-limit';
|
|
||||||
import { createApiRouter } from './routes/index.js';
|
|
||||||
import path from 'path';
|
|
||||||
import { fileURLToPath } from 'url';
|
|
||||||
|
|
||||||
// Get directory name in ES modules
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
|
||||||
const __dirname = path.dirname(__filename);
|
|
||||||
|
|
||||||
// Load environment variables
|
|
||||||
const envPath = path.resolve(__dirname, '.env');
|
|
||||||
console.log('[Server] Loading .env file from:', envPath);
|
|
||||||
dotenv.config({ path: envPath });
|
|
||||||
|
|
||||||
// Debug environment variables (without exposing sensitive data)
|
|
||||||
console.log('[Server] Environment variables loaded:', {
|
|
||||||
REDIS_HOST: process.env.REDIS_HOST || '(not set)',
|
|
||||||
REDIS_PORT: process.env.REDIS_PORT || '(not set)',
|
|
||||||
REDIS_USERNAME: process.env.REDIS_USERNAME || '(not set)',
|
|
||||||
REDIS_PASSWORD: process.env.REDIS_PASSWORD ? '(set)' : '(not set)',
|
|
||||||
NODE_ENV: process.env.NODE_ENV || '(not set)',
|
|
||||||
});
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const port = process.env.KLAVIYO_PORT || 3004;
|
|
||||||
|
|
||||||
// Rate limiting for reporting endpoints
|
|
||||||
const reportingLimiter = rateLimit({
|
|
||||||
windowMs: 10 * 60 * 1000, // 10 minutes
|
|
||||||
max: 10, // limit each IP to 10 requests per windowMs
|
|
||||||
message: 'Too many requests to reporting endpoint, please try again later',
|
|
||||||
keyGenerator: (req) => {
|
|
||||||
// Use a combination of IP and endpoint for more granular control
|
|
||||||
return `${req.ip}-reporting`;
|
|
||||||
},
|
|
||||||
skip: (req) => {
|
|
||||||
// Only apply to campaign-values-reports endpoint
|
|
||||||
return !req.path.includes('campaign-values-reports');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Middleware
|
|
||||||
app.use(cors());
|
|
||||||
app.use(express.json());
|
|
||||||
|
|
||||||
// Debug middleware to log all requests
|
|
||||||
app.use((req, res, next) => {
|
|
||||||
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
|
|
||||||
next();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Apply rate limiting to reporting endpoints
|
|
||||||
app.use('/api/klaviyo/reporting', reportingLimiter);
|
|
||||||
|
|
||||||
// Create and mount API routes
|
|
||||||
const apiRouter = createApiRouter(
|
|
||||||
process.env.KLAVIYO_API_KEY,
|
|
||||||
process.env.KLAVIYO_API_REVISION || '2024-02-15'
|
|
||||||
);
|
|
||||||
app.use('/api/klaviyo', apiRouter);
|
|
||||||
|
|
||||||
// Error handling middleware
|
|
||||||
app.use((err, req, res, next) => {
|
|
||||||
console.error('Unhandled error:', err);
|
|
||||||
res.status(500).json({
|
|
||||||
status: 'error',
|
|
||||||
message: 'Internal server error',
|
|
||||||
details: process.env.NODE_ENV === 'development' ? err.message : undefined
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Start server
|
|
||||||
app.listen(port, '0.0.0.0', () => {
|
|
||||||
console.log(`Klaviyo server listening at http://0.0.0.0:${port}`);
|
|
||||||
});
|
|
||||||
@@ -1,262 +0,0 @@
|
|||||||
import Redis from 'ioredis';
|
|
||||||
import { TimeManager } from '../utils/time.utils.js';
|
|
||||||
import dotenv from 'dotenv';
|
|
||||||
import path from 'path';
|
|
||||||
import { fileURLToPath } from 'url';
|
|
||||||
|
|
||||||
// Get directory name in ES modules
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
|
||||||
const __dirname = path.dirname(__filename);
|
|
||||||
|
|
||||||
// Load environment variables again (redundant but safe)
|
|
||||||
const envPath = path.resolve(__dirname, '../.env');
|
|
||||||
console.log('[RedisService] Loading .env file from:', envPath);
|
|
||||||
dotenv.config({ path: envPath });
|
|
||||||
|
|
||||||
export class RedisService {
|
|
||||||
constructor() {
|
|
||||||
this.timeManager = new TimeManager();
|
|
||||||
this.DEFAULT_TTL = 5 * 60; // 5 minutes default TTL
|
|
||||||
this.isConnected = false;
|
|
||||||
this._initializeRedis();
|
|
||||||
}
|
|
||||||
|
|
||||||
_initializeRedis() {
|
|
||||||
try {
|
|
||||||
// Debug: Print all environment variables we're looking for
|
|
||||||
console.log('[RedisService] Environment variables state:', {
|
|
||||||
REDIS_HOST: process.env.REDIS_HOST ? '(set)' : '(not set)',
|
|
||||||
REDIS_PORT: process.env.REDIS_PORT ? '(set)' : '(not set)',
|
|
||||||
REDIS_USERNAME: process.env.REDIS_USERNAME ? '(set)' : '(not set)',
|
|
||||||
REDIS_PASSWORD: process.env.REDIS_PASSWORD ? '(set)' : '(not set)',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Log Redis configuration (without password)
|
|
||||||
const host = process.env.REDIS_HOST || 'localhost';
|
|
||||||
const port = parseInt(process.env.REDIS_PORT) || 6379;
|
|
||||||
const username = process.env.REDIS_USERNAME || 'default';
|
|
||||||
const password = process.env.REDIS_PASSWORD;
|
|
||||||
|
|
||||||
console.log('[RedisService] Initializing Redis with config:', {
|
|
||||||
host,
|
|
||||||
port,
|
|
||||||
username,
|
|
||||||
hasPassword: !!password
|
|
||||||
});
|
|
||||||
|
|
||||||
const config = {
|
|
||||||
host,
|
|
||||||
port,
|
|
||||||
username,
|
|
||||||
retryStrategy: (times) => {
|
|
||||||
const delay = Math.min(times * 50, 2000);
|
|
||||||
return delay;
|
|
||||||
},
|
|
||||||
maxRetriesPerRequest: 3,
|
|
||||||
enableReadyCheck: true,
|
|
||||||
connectTimeout: 10000,
|
|
||||||
showFriendlyErrorStack: true,
|
|
||||||
retryUnfulfilled: true,
|
|
||||||
maxRetryAttempts: 5
|
|
||||||
};
|
|
||||||
|
|
||||||
// Only add password if it exists
|
|
||||||
if (password) {
|
|
||||||
console.log('[RedisService] Adding password to config');
|
|
||||||
config.password = password;
|
|
||||||
} else {
|
|
||||||
console.warn('[RedisService] No Redis password found in environment variables!');
|
|
||||||
}
|
|
||||||
|
|
||||||
this.client = new Redis(config);
|
|
||||||
|
|
||||||
// Handle connection events
|
|
||||||
this.client.on('connect', () => {
|
|
||||||
console.log('[RedisService] Connected to Redis');
|
|
||||||
this.isConnected = true;
|
|
||||||
});
|
|
||||||
|
|
||||||
this.client.on('ready', () => {
|
|
||||||
console.log('[RedisService] Redis is ready');
|
|
||||||
this.isConnected = true;
|
|
||||||
});
|
|
||||||
|
|
||||||
this.client.on('error', (err) => {
|
|
||||||
console.error('[RedisService] Redis error:', err);
|
|
||||||
this.isConnected = false;
|
|
||||||
// Log more details about the error
|
|
||||||
if (err.code === 'WRONGPASS') {
|
|
||||||
console.error('[RedisService] Authentication failed. Please check your Redis password.');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.client.on('close', () => {
|
|
||||||
console.log('[RedisService] Redis connection closed');
|
|
||||||
this.isConnected = false;
|
|
||||||
});
|
|
||||||
|
|
||||||
this.client.on('reconnecting', (params) => {
|
|
||||||
console.log('[RedisService] Reconnecting to Redis:', params);
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[RedisService] Error initializing Redis:', error);
|
|
||||||
this.isConnected = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async get(key) {
|
|
||||||
if (!this.isConnected) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const data = await this.client.get(key);
|
|
||||||
return data ? JSON.parse(data) : null;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[RedisService] Error getting data:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async set(key, data, ttl = this.DEFAULT_TTL) {
|
|
||||||
if (!this.isConnected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.client.setex(key, ttl, JSON.stringify(data));
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[RedisService] Error setting data:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper to generate cache keys
|
|
||||||
_getCacheKey(type, params = {}) {
|
|
||||||
const {
|
|
||||||
timeRange,
|
|
||||||
startDate,
|
|
||||||
endDate,
|
|
||||||
metricId,
|
|
||||||
metric,
|
|
||||||
daily,
|
|
||||||
cacheKey,
|
|
||||||
isPreviousPeriod,
|
|
||||||
customFilters
|
|
||||||
} = params;
|
|
||||||
|
|
||||||
let key = `klaviyo:${type}`;
|
|
||||||
|
|
||||||
// Handle "stats:details" for daily or metric-based keys
|
|
||||||
if (type === 'stats:details') {
|
|
||||||
// Add metric to key
|
|
||||||
key += `:${metric || 'all'}`;
|
|
||||||
|
|
||||||
// Add daily flag if present
|
|
||||||
if (daily) {
|
|
||||||
key += ':daily';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add custom filters hash if present
|
|
||||||
if (customFilters?.length) {
|
|
||||||
const filterHash = customFilters.join('').replace(/[^a-zA-Z0-9]/g, '');
|
|
||||||
key += `:${filterHash}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If a specific cache key is provided, use it (highest priority)
|
|
||||||
if (cacheKey) {
|
|
||||||
key += `:${cacheKey}`;
|
|
||||||
}
|
|
||||||
// Otherwise, build a default cache key
|
|
||||||
else if (timeRange) {
|
|
||||||
key += `:${timeRange}`;
|
|
||||||
if (metricId) {
|
|
||||||
key += `:${metricId}`;
|
|
||||||
}
|
|
||||||
if (isPreviousPeriod) {
|
|
||||||
key += ':prev';
|
|
||||||
}
|
|
||||||
} else if (startDate && endDate) {
|
|
||||||
// For custom date ranges, include both dates in the key
|
|
||||||
key += `:custom:${startDate}:${endDate}`;
|
|
||||||
if (metricId) {
|
|
||||||
key += `:${metricId}`;
|
|
||||||
}
|
|
||||||
if (isPreviousPeriod) {
|
|
||||||
key += ':prev';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add order type to key if present
|
|
||||||
if (['pre_orders', 'local_pickup', 'on_hold'].includes(metric)) {
|
|
||||||
key += `:${metric}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return key;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Get TTL based on time range
|
|
||||||
_getTTL(timeRange) {
|
|
||||||
const TTL_MAP = {
|
|
||||||
'today': 2 * 60, // 2 minutes
|
|
||||||
'yesterday': 30 * 60, // 30 minutes
|
|
||||||
'thisWeek': 5 * 60, // 5 minutes
|
|
||||||
'lastWeek': 60 * 60, // 1 hour
|
|
||||||
'thisMonth': 10 * 60, // 10 minutes
|
|
||||||
'lastMonth': 2 * 60 * 60, // 2 hours
|
|
||||||
'last7days': 5 * 60, // 5 minutes
|
|
||||||
'last30days': 15 * 60, // 15 minutes
|
|
||||||
'custom': 15 * 60 // 15 minutes
|
|
||||||
};
|
|
||||||
return TTL_MAP[timeRange] || this.DEFAULT_TTL;
|
|
||||||
}
|
|
||||||
|
|
||||||
async getEventData(type, params) {
|
|
||||||
if (!this.isConnected) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const baseKey = this._getCacheKey('events', params);
|
|
||||||
const data = await this.get(`${baseKey}:${type}`);
|
|
||||||
return data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[RedisService] Error getting event data:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async cacheEventData(type, params, data) {
|
|
||||||
if (!this.isConnected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const ttl = this._getTTL(params.timeRange);
|
|
||||||
const baseKey = this._getCacheKey('events', params);
|
|
||||||
|
|
||||||
// Cache raw event data
|
|
||||||
await this.set(`${baseKey}:${type}`, data, ttl);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[RedisService] Error caching event data:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async clearCache(params = {}) {
|
|
||||||
if (!this.isConnected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const pattern = this._getCacheKey('events', params) + '*';
|
|
||||||
const keys = await this.client.keys(pattern);
|
|
||||||
if (keys.length > 0) {
|
|
||||||
await this.client.del(...keys);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[RedisService] Error clearing cache:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,967 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "meta-server",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"lockfileVersion": 3,
|
|
||||||
"requires": true,
|
|
||||||
"packages": {
|
|
||||||
"": {
|
|
||||||
"name": "meta-server",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"license": "ISC",
|
|
||||||
"dependencies": {
|
|
||||||
"axios": "^1.7.9",
|
|
||||||
"cors": "^2.8.5",
|
|
||||||
"dotenv": "^16.4.7",
|
|
||||||
"express": "^4.21.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/accepts": {
|
|
||||||
"version": "1.3.8",
|
|
||||||
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
|
|
||||||
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"mime-types": "~2.1.34",
|
|
||||||
"negotiator": "0.6.3"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/array-flatten": {
|
|
||||||
"version": "1.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
|
||||||
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/asynckit": {
|
|
||||||
"version": "0.4.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
|
||||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/axios": {
|
|
||||||
"version": "1.12.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
|
|
||||||
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"follow-redirects": "^1.15.6",
|
|
||||||
"form-data": "^4.0.4",
|
|
||||||
"proxy-from-env": "^1.1.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/body-parser": {
|
|
||||||
"version": "1.20.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
|
|
||||||
"integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"bytes": "3.1.2",
|
|
||||||
"content-type": "~1.0.5",
|
|
||||||
"debug": "2.6.9",
|
|
||||||
"depd": "2.0.0",
|
|
||||||
"destroy": "1.2.0",
|
|
||||||
"http-errors": "2.0.0",
|
|
||||||
"iconv-lite": "0.4.24",
|
|
||||||
"on-finished": "2.4.1",
|
|
||||||
"qs": "6.13.0",
|
|
||||||
"raw-body": "2.5.2",
|
|
||||||
"type-is": "~1.6.18",
|
|
||||||
"unpipe": "1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8",
|
|
||||||
"npm": "1.2.8000 || >= 1.4.16"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/bytes": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/call-bind-apply-helpers": {
|
|
||||||
"version": "1.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz",
|
|
||||||
"integrity": "sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"es-errors": "^1.3.0",
|
|
||||||
"function-bind": "^1.1.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/call-bound": {
|
|
||||||
"version": "1.0.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.3.tgz",
|
|
||||||
"integrity": "sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"call-bind-apply-helpers": "^1.0.1",
|
|
||||||
"get-intrinsic": "^1.2.6"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/combined-stream": {
|
|
||||||
"version": "1.0.8",
|
|
||||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
|
||||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"delayed-stream": "~1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/content-disposition": {
|
|
||||||
"version": "0.5.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
|
||||||
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"safe-buffer": "5.2.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/content-type": {
|
|
||||||
"version": "1.0.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
|
|
||||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/cookie": {
|
|
||||||
"version": "0.7.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",
|
|
||||||
"integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/cookie-signature": {
|
|
||||||
"version": "1.0.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
|
|
||||||
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/cors": {
|
|
||||||
"version": "2.8.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
|
|
||||||
"integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"object-assign": "^4",
|
|
||||||
"vary": "^1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.10"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/debug": {
|
|
||||||
"version": "2.6.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
|
||||||
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"ms": "2.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/delayed-stream": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=0.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/depd": {
|
|
||||||
"version": "2.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
|
||||||
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/destroy": {
|
|
||||||
"version": "1.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
|
|
||||||
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8",
|
|
||||||
"npm": "1.2.8000 || >= 1.4.16"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/dotenv": {
|
|
||||||
"version": "16.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz",
|
|
||||||
"integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==",
|
|
||||||
"license": "BSD-2-Clause",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=12"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://dotenvx.com"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/dunder-proto": {
|
|
||||||
"version": "1.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
|
||||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"call-bind-apply-helpers": "^1.0.1",
|
|
||||||
"es-errors": "^1.3.0",
|
|
||||||
"gopd": "^1.2.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/ee-first": {
|
|
||||||
"version": "1.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
|
||||||
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/encodeurl": {
|
|
||||||
"version": "2.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
|
|
||||||
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/es-define-property": {
|
|
||||||
"version": "1.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
|
||||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/es-errors": {
|
|
||||||
"version": "1.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
|
||||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/es-object-atoms": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"es-errors": "^1.3.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/es-set-tostringtag": {
|
|
||||||
"version": "2.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
|
||||||
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"es-errors": "^1.3.0",
|
|
||||||
"get-intrinsic": "^1.2.6",
|
|
||||||
"has-tostringtag": "^1.0.2",
|
|
||||||
"hasown": "^2.0.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/escape-html": {
|
|
||||||
"version": "1.0.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
|
|
||||||
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/etag": {
|
|
||||||
"version": "1.8.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
|
|
||||||
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/express": {
|
|
||||||
"version": "4.21.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz",
|
|
||||||
"integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"accepts": "~1.3.8",
|
|
||||||
"array-flatten": "1.1.1",
|
|
||||||
"body-parser": "1.20.3",
|
|
||||||
"content-disposition": "0.5.4",
|
|
||||||
"content-type": "~1.0.4",
|
|
||||||
"cookie": "0.7.1",
|
|
||||||
"cookie-signature": "1.0.6",
|
|
||||||
"debug": "2.6.9",
|
|
||||||
"depd": "2.0.0",
|
|
||||||
"encodeurl": "~2.0.0",
|
|
||||||
"escape-html": "~1.0.3",
|
|
||||||
"etag": "~1.8.1",
|
|
||||||
"finalhandler": "1.3.1",
|
|
||||||
"fresh": "0.5.2",
|
|
||||||
"http-errors": "2.0.0",
|
|
||||||
"merge-descriptors": "1.0.3",
|
|
||||||
"methods": "~1.1.2",
|
|
||||||
"on-finished": "2.4.1",
|
|
||||||
"parseurl": "~1.3.3",
|
|
||||||
"path-to-regexp": "0.1.12",
|
|
||||||
"proxy-addr": "~2.0.7",
|
|
||||||
"qs": "6.13.0",
|
|
||||||
"range-parser": "~1.2.1",
|
|
||||||
"safe-buffer": "5.2.1",
|
|
||||||
"send": "0.19.0",
|
|
||||||
"serve-static": "1.16.2",
|
|
||||||
"setprototypeof": "1.2.0",
|
|
||||||
"statuses": "2.0.1",
|
|
||||||
"type-is": "~1.6.18",
|
|
||||||
"utils-merge": "1.0.1",
|
|
||||||
"vary": "~1.1.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.10.0"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "opencollective",
|
|
||||||
"url": "https://opencollective.com/express"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/finalhandler": {
|
|
||||||
"version": "1.3.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
|
|
||||||
"integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"debug": "2.6.9",
|
|
||||||
"encodeurl": "~2.0.0",
|
|
||||||
"escape-html": "~1.0.3",
|
|
||||||
"on-finished": "2.4.1",
|
|
||||||
"parseurl": "~1.3.3",
|
|
||||||
"statuses": "2.0.1",
|
|
||||||
"unpipe": "~1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/follow-redirects": {
|
|
||||||
"version": "1.15.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
|
|
||||||
"integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
|
|
||||||
"funding": [
|
|
||||||
{
|
|
||||||
"type": "individual",
|
|
||||||
"url": "https://github.com/sponsors/RubenVerborgh"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=4.0"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"debug": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/form-data": {
|
|
||||||
"version": "4.0.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
|
|
||||||
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"asynckit": "^0.4.0",
|
|
||||||
"combined-stream": "^1.0.8",
|
|
||||||
"es-set-tostringtag": "^2.1.0",
|
|
||||||
"hasown": "^2.0.2",
|
|
||||||
"mime-types": "^2.1.12"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/forwarded": {
|
|
||||||
"version": "0.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
|
||||||
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/fresh": {
|
|
||||||
"version": "0.5.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
|
|
||||||
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/function-bind": {
|
|
||||||
"version": "1.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
|
||||||
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/get-intrinsic": {
|
|
||||||
"version": "1.2.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.6.tgz",
|
|
||||||
"integrity": "sha512-qxsEs+9A+u85HhllWJJFicJfPDhRmjzoYdl64aMWW9yRIJmSyxdn8IEkuIM530/7T+lv0TIHd8L6Q/ra0tEoeA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"call-bind-apply-helpers": "^1.0.1",
|
|
||||||
"dunder-proto": "^1.0.0",
|
|
||||||
"es-define-property": "^1.0.1",
|
|
||||||
"es-errors": "^1.3.0",
|
|
||||||
"es-object-atoms": "^1.0.0",
|
|
||||||
"function-bind": "^1.1.2",
|
|
||||||
"gopd": "^1.2.0",
|
|
||||||
"has-symbols": "^1.1.0",
|
|
||||||
"hasown": "^2.0.2",
|
|
||||||
"math-intrinsics": "^1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/gopd": {
|
|
||||||
"version": "1.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
|
||||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/has-symbols": {
|
|
||||||
"version": "1.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
|
||||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/has-tostringtag": {
|
|
||||||
"version": "1.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
|
||||||
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"has-symbols": "^1.0.3"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/hasown": {
|
|
||||||
"version": "2.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
|
||||||
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"function-bind": "^1.1.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/http-errors": {
|
|
||||||
"version": "2.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
|
|
||||||
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"depd": "2.0.0",
|
|
||||||
"inherits": "2.0.4",
|
|
||||||
"setprototypeof": "1.2.0",
|
|
||||||
"statuses": "2.0.1",
|
|
||||||
"toidentifier": "1.0.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/iconv-lite": {
|
|
||||||
"version": "0.4.24",
|
|
||||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
|
||||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"safer-buffer": ">= 2.1.2 < 3"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=0.10.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/inherits": {
|
|
||||||
"version": "2.0.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
|
||||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
|
||||||
"license": "ISC"
|
|
||||||
},
|
|
||||||
"node_modules/ipaddr.js": {
|
|
||||||
"version": "1.9.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
|
|
||||||
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.10"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/math-intrinsics": {
|
|
||||||
"version": "1.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
|
||||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/media-typer": {
|
|
||||||
"version": "0.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
|
|
||||||
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/merge-descriptors": {
|
|
||||||
"version": "1.0.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
|
|
||||||
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/sindresorhus"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/methods": {
|
|
||||||
"version": "1.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
|
|
||||||
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/mime": {
|
|
||||||
"version": "1.6.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
|
|
||||||
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"bin": {
|
|
||||||
"mime": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/mime-db": {
|
|
||||||
"version": "1.52.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
|
||||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/mime-types": {
|
|
||||||
"version": "2.1.35",
|
|
||||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
|
||||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"mime-db": "1.52.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/ms": {
|
|
||||||
"version": "2.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
|
||||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/negotiator": {
|
|
||||||
"version": "0.6.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
|
|
||||||
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/object-assign": {
|
|
||||||
"version": "4.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
|
||||||
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=0.10.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/object-inspect": {
|
|
||||||
"version": "1.13.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz",
|
|
||||||
"integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/on-finished": {
|
|
||||||
"version": "2.4.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
|
|
||||||
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"ee-first": "1.1.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/parseurl": {
|
|
||||||
"version": "1.3.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
|
||||||
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/path-to-regexp": {
|
|
||||||
"version": "0.1.12",
|
|
||||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
|
|
||||||
"integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/proxy-addr": {
|
|
||||||
"version": "2.0.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
|
||||||
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"forwarded": "0.2.0",
|
|
||||||
"ipaddr.js": "1.9.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.10"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/proxy-from-env": {
|
|
||||||
"version": "1.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
|
||||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/qs": {
|
|
||||||
"version": "6.13.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
|
|
||||||
"integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==",
|
|
||||||
"license": "BSD-3-Clause",
|
|
||||||
"dependencies": {
|
|
||||||
"side-channel": "^1.0.6"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=0.6"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/range-parser": {
|
|
||||||
"version": "1.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
|
||||||
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/raw-body": {
|
|
||||||
"version": "2.5.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz",
|
|
||||||
"integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"bytes": "3.1.2",
|
|
||||||
"http-errors": "2.0.0",
|
|
||||||
"iconv-lite": "0.4.24",
|
|
||||||
"unpipe": "1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/safe-buffer": {
|
|
||||||
"version": "5.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
|
||||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
|
||||||
"funding": [
|
|
||||||
{
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/feross"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "patreon",
|
|
||||||
"url": "https://www.patreon.com/feross"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "consulting",
|
|
||||||
"url": "https://feross.org/support"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/safer-buffer": {
|
|
||||||
"version": "2.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
|
||||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/send": {
|
|
||||||
"version": "0.19.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz",
|
|
||||||
"integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"debug": "2.6.9",
|
|
||||||
"depd": "2.0.0",
|
|
||||||
"destroy": "1.2.0",
|
|
||||||
"encodeurl": "~1.0.2",
|
|
||||||
"escape-html": "~1.0.3",
|
|
||||||
"etag": "~1.8.1",
|
|
||||||
"fresh": "0.5.2",
|
|
||||||
"http-errors": "2.0.0",
|
|
||||||
"mime": "1.6.0",
|
|
||||||
"ms": "2.1.3",
|
|
||||||
"on-finished": "2.4.1",
|
|
||||||
"range-parser": "~1.2.1",
|
|
||||||
"statuses": "2.0.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/send/node_modules/encodeurl": {
|
|
||||||
"version": "1.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
|
|
||||||
"integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/send/node_modules/ms": {
|
|
||||||
"version": "2.1.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
|
||||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/serve-static": {
|
|
||||||
"version": "1.16.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz",
|
|
||||||
"integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"encodeurl": "~2.0.0",
|
|
||||||
"escape-html": "~1.0.3",
|
|
||||||
"parseurl": "~1.3.3",
|
|
||||||
"send": "0.19.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/setprototypeof": {
|
|
||||||
"version": "1.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
|
||||||
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
|
|
||||||
"license": "ISC"
|
|
||||||
},
|
|
||||||
"node_modules/side-channel": {
|
|
||||||
"version": "1.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
|
|
||||||
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"es-errors": "^1.3.0",
|
|
||||||
"object-inspect": "^1.13.3",
|
|
||||||
"side-channel-list": "^1.0.0",
|
|
||||||
"side-channel-map": "^1.0.1",
|
|
||||||
"side-channel-weakmap": "^1.0.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/side-channel-list": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"es-errors": "^1.3.0",
|
|
||||||
"object-inspect": "^1.13.3"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/side-channel-map": {
|
|
||||||
"version": "1.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
|
|
||||||
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"call-bound": "^1.0.2",
|
|
||||||
"es-errors": "^1.3.0",
|
|
||||||
"get-intrinsic": "^1.2.5",
|
|
||||||
"object-inspect": "^1.13.3"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/side-channel-weakmap": {
|
|
||||||
"version": "1.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
|
|
||||||
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"call-bound": "^1.0.2",
|
|
||||||
"es-errors": "^1.3.0",
|
|
||||||
"get-intrinsic": "^1.2.5",
|
|
||||||
"object-inspect": "^1.13.3",
|
|
||||||
"side-channel-map": "^1.0.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/statuses": {
|
|
||||||
"version": "2.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
|
|
||||||
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/toidentifier": {
|
|
||||||
"version": "1.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
|
||||||
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/type-is": {
|
|
||||||
"version": "1.6.18",
|
|
||||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
|
||||||
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"media-typer": "0.3.0",
|
|
||||||
"mime-types": "~2.1.24"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/unpipe": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/utils-merge": {
|
|
||||||
"version": "1.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
|
||||||
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/vary": {
|
|
||||||
"version": "1.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
|
||||||
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.8"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "meta-server",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"main": "index.js",
|
|
||||||
"scripts": {
|
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
|
||||||
"start": "node server.js",
|
|
||||||
"dev": "nodemon server.js"
|
|
||||||
},
|
|
||||||
"keywords": [],
|
|
||||||
"author": "",
|
|
||||||
"license": "ISC",
|
|
||||||
"description": "",
|
|
||||||
"dependencies": {
|
|
||||||
"axios": "^1.7.9",
|
|
||||||
"cors": "^2.8.5",
|
|
||||||
"dotenv": "^16.4.7",
|
|
||||||
"express": "^4.21.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const {
|
|
||||||
fetchCampaigns,
|
|
||||||
fetchAccountInsights,
|
|
||||||
updateCampaignBudget,
|
|
||||||
updateCampaignStatus,
|
|
||||||
} = require('../services/meta.service');
|
|
||||||
|
|
||||||
// Get all campaigns with insights
|
|
||||||
router.get('/campaigns', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { since, until } = req.query;
|
|
||||||
|
|
||||||
if (!since || !until) {
|
|
||||||
return res.status(400).json({ error: 'Date range is required (since, until)' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const campaigns = await fetchCampaigns(since, until);
|
|
||||||
res.json(campaigns);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Campaign fetch error:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Failed to fetch campaigns',
|
|
||||||
details: error.response?.data?.error?.message || error.message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get account insights
|
|
||||||
router.get('/account-insights', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { since, until } = req.query;
|
|
||||||
|
|
||||||
if (!since || !until) {
|
|
||||||
return res.status(400).json({ error: 'Date range is required (since, until)' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const insights = await fetchAccountInsights(since, until);
|
|
||||||
res.json(insights);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Account insights fetch error:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Failed to fetch account insights',
|
|
||||||
details: error.response?.data?.error?.message || error.message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update campaign budget
|
|
||||||
router.patch('/campaigns/:campaignId/budget', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { campaignId } = req.params;
|
|
||||||
const { budget } = req.body;
|
|
||||||
|
|
||||||
if (!budget) {
|
|
||||||
return res.status(400).json({ error: 'Budget is required' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await updateCampaignBudget(campaignId, budget);
|
|
||||||
res.json(result);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Budget update error:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Failed to update campaign budget',
|
|
||||||
details: error.response?.data?.error?.message || error.message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update campaign status (pause/unpause)
|
|
||||||
router.post('/campaigns/:campaignId/:action', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { campaignId, action } = req.params;
|
|
||||||
|
|
||||||
if (!['pause', 'unpause'].includes(action)) {
|
|
||||||
return res.status(400).json({ error: 'Invalid action. Use "pause" or "unpause"' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await updateCampaignStatus(campaignId, action);
|
|
||||||
res.json(result);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Status update error:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Failed to update campaign status',
|
|
||||||
details: error.response?.data?.error?.message || error.message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const cors = require('cors');
|
|
||||||
const path = require('path');
|
|
||||||
require('dotenv').config({
|
|
||||||
path: path.resolve(__dirname, '.env')
|
|
||||||
});
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const port = process.env.PORT || 3005;
|
|
||||||
|
|
||||||
app.use(cors());
|
|
||||||
app.use(express.json());
|
|
||||||
|
|
||||||
// Import routes
|
|
||||||
const campaignRoutes = require('./routes/campaigns.routes');
|
|
||||||
|
|
||||||
// Use routes
|
|
||||||
app.use('/api/meta', campaignRoutes);
|
|
||||||
|
|
||||||
// Error handling middleware
|
|
||||||
app.use((err, req, res, next) => {
|
|
||||||
console.error(err.stack);
|
|
||||||
res.status(500).json({ error: 'Something went wrong!' });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Start server
|
|
||||||
app.listen(port, () => {
|
|
||||||
console.log(`Meta API server running on port ${port}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = app;
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
const { default: axios } = require('axios');
|
|
||||||
|
|
||||||
const META_API_VERSION = process.env.META_API_VERSION || 'v21.0';
|
|
||||||
const META_API_BASE_URL = `https://graph.facebook.com/${META_API_VERSION}`;
|
|
||||||
const META_ACCESS_TOKEN = process.env.META_ACCESS_TOKEN;
|
|
||||||
const AD_ACCOUNT_ID = process.env.META_AD_ACCOUNT_ID;
|
|
||||||
|
|
||||||
const metaApiRequest = async (endpoint, params = {}) => {
|
|
||||||
try {
|
|
||||||
const response = await axios.get(`${META_API_BASE_URL}/${endpoint}`, {
|
|
||||||
params: {
|
|
||||||
access_token: META_ACCESS_TOKEN,
|
|
||||||
time_zone: 'America/New_York',
|
|
||||||
...params,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Meta API Error:', {
|
|
||||||
message: error.message,
|
|
||||||
response: error.response?.data,
|
|
||||||
endpoint,
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchCampaigns = async (since, until) => {
|
|
||||||
const campaigns = await metaApiRequest(`act_${AD_ACCOUNT_ID}/campaigns`, {
|
|
||||||
fields: [
|
|
||||||
'id',
|
|
||||||
'name',
|
|
||||||
'status',
|
|
||||||
'objective',
|
|
||||||
'daily_budget',
|
|
||||||
'lifetime_budget',
|
|
||||||
'adsets{daily_budget,lifetime_budget}',
|
|
||||||
`insights.time_range({'since':'${since}','until':'${until}'}).level(campaign){
|
|
||||||
spend,
|
|
||||||
impressions,
|
|
||||||
clicks,
|
|
||||||
ctr,
|
|
||||||
reach,
|
|
||||||
frequency,
|
|
||||||
cpm,
|
|
||||||
cpc,
|
|
||||||
actions,
|
|
||||||
action_values,
|
|
||||||
cost_per_action_type
|
|
||||||
}`,
|
|
||||||
].join(','),
|
|
||||||
limit: 100,
|
|
||||||
});
|
|
||||||
|
|
||||||
return campaigns.data.filter(c => c.insights?.data?.[0]?.spend > 0);
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchAccountInsights = async (since, until) => {
|
|
||||||
const accountInsights = await metaApiRequest(`act_${AD_ACCOUNT_ID}/insights`, {
|
|
||||||
fields: 'reach,spend,impressions,clicks,ctr,cpm,actions,action_values',
|
|
||||||
time_range: JSON.stringify({ since, until }),
|
|
||||||
});
|
|
||||||
|
|
||||||
return accountInsights.data[0] || null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateCampaignBudget = async (campaignId, budget) => {
|
|
||||||
try {
|
|
||||||
const response = await axios.post(`${META_API_BASE_URL}/${campaignId}`, {
|
|
||||||
access_token: META_ACCESS_TOKEN,
|
|
||||||
daily_budget: budget * 100, // Convert to cents
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Update campaign budget error:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateCampaignStatus = async (campaignId, action) => {
|
|
||||||
try {
|
|
||||||
const status = action === 'pause' ? 'PAUSED' : 'ACTIVE';
|
|
||||||
const response = await axios.post(`${META_API_BASE_URL}/${campaignId}`, {
|
|
||||||
access_token: META_ACCESS_TOKEN,
|
|
||||||
status,
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Update campaign status error:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
fetchCampaigns,
|
|
||||||
fetchAccountInsights,
|
|
||||||
updateCampaignBudget,
|
|
||||||
updateCampaignStatus,
|
|
||||||
};
|
|
||||||
+2917
-2
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,29 @@
|
|||||||
{
|
{
|
||||||
|
"name": "dashboard-server",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Merged ESM dashboard server (klaviyo + meta + google-analytics + typeform). Phase 4 of CONSOLIDATION_PLAN.md.",
|
||||||
|
"main": "server.js",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node server.js",
|
||||||
|
"dev": "nodemon server.js"
|
||||||
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"dotenv": "^16.4.7"
|
"@google-analytics/data": "^4.0.0",
|
||||||
|
"axios": "^1.7.9",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.4.7",
|
||||||
|
"express": "^4.21.2",
|
||||||
|
"ioredis": "^5.4.1",
|
||||||
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"luxon": "^3.5.0",
|
||||||
|
"node-fetch": "^3.3.2",
|
||||||
|
"pg": "^8.18.0",
|
||||||
|
"pino": "^9.5.0",
|
||||||
|
"pino-http": "^10.3.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"nodemon": "^3.0.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// Google Analytics router — ESM conversion of google-server/routes/analytics.routes.js.
|
||||||
|
// All routes are read-only — authenticated-only is sufficient; no extra permission.
|
||||||
|
// google_write is reserved for future write endpoints (per migration 005).
|
||||||
|
|
||||||
|
import express from 'express';
|
||||||
|
import { AnalyticsService } from '../../services/google/analytics.service.js';
|
||||||
|
|
||||||
|
export function createGoogleRouter({ redis }) {
|
||||||
|
const router = express.Router();
|
||||||
|
const service = new AnalyticsService(redis);
|
||||||
|
|
||||||
|
router.get('/metrics', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { startDate = '7daysAgo' } = req.query;
|
||||||
|
const data = await service.getBasicMetrics(startDate);
|
||||||
|
res.json({ success: true, data });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Metrics error:', { startDate: req.query.startDate, error: error.message });
|
||||||
|
res.status(500).json({ success: false, error: 'Failed to fetch metrics', details: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/realtime/basic', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const data = await service.getRealTimeBasicData();
|
||||||
|
res.json({ success: true, data });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Realtime basic error:', { error: error.message });
|
||||||
|
res.status(500).json({ success: false, error: 'Failed to fetch realtime basic data', details: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/realtime/detailed', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const data = await service.getRealTimeDetailedData();
|
||||||
|
res.json({ success: true, data });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Realtime detailed error:', { error: error.message });
|
||||||
|
res.status(500).json({ success: false, error: 'Failed to fetch realtime detailed data', details: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/user-behavior', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { timeRange = '30' } = req.query;
|
||||||
|
const data = await service.getUserBehavior(timeRange);
|
||||||
|
res.json({ success: true, data });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('User behavior error:', { timeRange: req.query.timeRange, error: error.message });
|
||||||
|
res.status(500).json({ success: false, error: 'Failed to fetch user behavior data', details: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
+4
-4
@@ -1,11 +1,11 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
import { CampaignsService } from '../services/campaigns.service.js';
|
import { CampaignsService } from '../../services/klaviyo/campaigns.service.js';
|
||||||
import { TimeManager } from '../utils/time.utils.js';
|
import { TimeManager } from '../../utils/time.utils.js';
|
||||||
|
|
||||||
export function createCampaignsRouter(apiKey, apiRevision) {
|
export function createCampaignsRouter(apiKey, apiRevision, redis) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const timeManager = new TimeManager();
|
const timeManager = new TimeManager();
|
||||||
const campaignsService = new CampaignsService(apiKey, apiRevision);
|
const campaignsService = new CampaignsService(apiKey, apiRevision, redis);
|
||||||
|
|
||||||
// Get campaigns with optional filtering
|
// Get campaigns with optional filtering
|
||||||
router.get('/', async (req, res) => {
|
router.get('/', async (req, res) => {
|
||||||
+11
-6
@@ -1,7 +1,8 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
import { EventsService } from '../services/events.service.js';
|
import { EventsService } from '../../services/klaviyo/events.service.js';
|
||||||
import { TimeManager } from '../utils/time.utils.js';
|
import { TimeManager } from '../../utils/time.utils.js';
|
||||||
import { RedisService } from '../services/redis.service.js';
|
import { RedisService } from '../../services/klaviyo/redis.service.js';
|
||||||
|
import { requirePermission } from '../../../shared/auth/middleware.js';
|
||||||
|
|
||||||
// Import METRIC_IDS from events service
|
// Import METRIC_IDS from events service
|
||||||
const METRIC_IDS = {
|
const METRIC_IDS = {
|
||||||
@@ -13,11 +14,15 @@ const METRIC_IDS = {
|
|||||||
PAYMENT_REFUNDED: 'R7XUYh'
|
PAYMENT_REFUNDED: 'R7XUYh'
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createEventsRouter(apiKey, apiRevision) {
|
export function createEventsRouter(apiKey, apiRevision, redis) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const timeManager = new TimeManager();
|
const timeManager = new TimeManager();
|
||||||
const eventsService = new EventsService(apiKey, apiRevision);
|
const eventsService = new EventsService(apiKey, apiRevision, redis);
|
||||||
const redisService = new RedisService();
|
const redisService = new RedisService(redis);
|
||||||
|
|
||||||
|
// Phase 6.2: clearCache is operational maintenance — requires klaviyo_admin.
|
||||||
|
// Mounted as path-level middleware so the existing POST handler below stays untouched.
|
||||||
|
router.use('/clearCache', requirePermission('klaviyo_admin'));
|
||||||
|
|
||||||
// Get events with optional filtering
|
// Get events with optional filtering
|
||||||
router.get('/', async (req, res) => {
|
router.get('/', async (req, res) => {
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// Klaviyo router factory. Phase 4 merge: takes the injected redis client and
|
||||||
|
// the env-resolved API key/revision, returns the mounted /api/klaviyo router
|
||||||
|
// (matches Caddy proxy path; no rewrite needed).
|
||||||
|
|
||||||
|
import express from 'express';
|
||||||
|
import rateLimit from 'express-rate-limit';
|
||||||
|
import { requirePermission } from '../../../shared/auth/middleware.js';
|
||||||
|
|
||||||
|
import { createEventsRouter } from './events.routes.js';
|
||||||
|
import { createMetricsRouter } from './metrics.routes.js';
|
||||||
|
import { createCampaignsRouter } from './campaigns.routes.js';
|
||||||
|
import { createReportingRouter } from './reporting.routes.js';
|
||||||
|
|
||||||
|
export function createKlaviyoRouter({ redis }) {
|
||||||
|
const apiKey = process.env.KLAVIYO_API_KEY;
|
||||||
|
const apiRevision = process.env.KLAVIYO_API_REVISION || '2024-02-15';
|
||||||
|
|
||||||
|
if (!apiKey) {
|
||||||
|
// Loud at startup; the routes themselves will 500 on every call without it.
|
||||||
|
console.warn('[klaviyo] KLAVIYO_API_KEY not set — Klaviyo endpoints will fail');
|
||||||
|
}
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Phase 4 carryover from klaviyo-server: throttle the heavy /reporting/campaign-values-reports
|
||||||
|
// endpoint. authenticate() already runs upstream so we don't add a per-user limiter here.
|
||||||
|
const reportingLimiter = rateLimit({
|
||||||
|
windowMs: 10 * 60 * 1000,
|
||||||
|
max: 10,
|
||||||
|
message: 'Too many requests to reporting endpoint, please try again later',
|
||||||
|
keyGenerator: (req) => `${req.ip}-klaviyo-reporting`,
|
||||||
|
skip: (req) => !req.path.includes('campaign-values-reports'),
|
||||||
|
standardHeaders: true,
|
||||||
|
legacyHeaders: false,
|
||||||
|
});
|
||||||
|
router.use('/reporting', reportingLimiter);
|
||||||
|
|
||||||
|
router.use('/events', createEventsRouter(apiKey, apiRevision, redis));
|
||||||
|
router.use('/metrics', createMetricsRouter(apiKey, apiRevision));
|
||||||
|
router.use('/campaigns', createCampaignsRouter(apiKey, apiRevision, redis));
|
||||||
|
router.use('/reporting', createReportingRouter(apiKey, apiRevision, redis));
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-exported so the dashboard server / future tests can attach the
|
||||||
|
// klaviyo_admin gate without reaching into the events router file.
|
||||||
|
export { requirePermission };
|
||||||
+3
-4
@@ -1,9 +1,8 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
import { MetricsService } from '../services/metrics.service.js';
|
import { MetricsService } from '../../services/klaviyo/metrics.service.js';
|
||||||
|
|
||||||
const router = express.Router();
|
export function createMetricsRouter(apiKey, apiRevision) {
|
||||||
|
const router = express.Router();
|
||||||
export function createMetricsRoutes(apiKey, apiRevision) {
|
|
||||||
const metricsService = new MetricsService(apiKey, apiRevision);
|
const metricsService = new MetricsService(apiKey, apiRevision);
|
||||||
|
|
||||||
// Get all metrics
|
// Get all metrics
|
||||||
+4
-4
@@ -1,10 +1,10 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
import { ReportingService } from '../services/reporting.service.js';
|
import { ReportingService } from '../../services/klaviyo/reporting.service.js';
|
||||||
import { TimeManager } from '../utils/time.utils.js';
|
import { TimeManager } from '../../utils/time.utils.js';
|
||||||
|
|
||||||
export function createReportingRouter(apiKey, apiRevision) {
|
export function createReportingRouter(apiKey, apiRevision, redis) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const reportingService = new ReportingService(apiKey, apiRevision);
|
const reportingService = new ReportingService(apiKey, apiRevision, redis);
|
||||||
const timeManager = new TimeManager();
|
const timeManager = new TimeManager();
|
||||||
|
|
||||||
// Get campaign reports by time range
|
// Get campaign reports by time range
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
// Meta router factory — ESM conversion of meta-server/routes/campaigns.routes.js.
|
||||||
|
// Phase 6.2: mutations (PATCH /campaigns/:id/budget, POST /campaigns/:id/:action)
|
||||||
|
// require the `meta_write` permission. Reads (GET) stay authenticated-only.
|
||||||
|
|
||||||
|
import express from 'express';
|
||||||
|
import { requirePermission } from '../../../shared/auth/middleware.js';
|
||||||
|
import {
|
||||||
|
fetchCampaigns,
|
||||||
|
fetchAccountInsights,
|
||||||
|
updateCampaignBudget,
|
||||||
|
updateCampaignStatus,
|
||||||
|
} from '../../services/meta/meta.service.js';
|
||||||
|
|
||||||
|
export function createMetaRouter() {
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Reads — authenticated-only
|
||||||
|
router.get('/campaigns', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { since, until } = req.query;
|
||||||
|
if (!since || !until) {
|
||||||
|
return res.status(400).json({ error: 'Date range is required (since, until)' });
|
||||||
|
}
|
||||||
|
const campaigns = await fetchCampaigns(since, until);
|
||||||
|
res.json(campaigns);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Campaign fetch error:', error);
|
||||||
|
res.status(500).json({
|
||||||
|
error: 'Failed to fetch campaigns',
|
||||||
|
details: error.response?.data?.error?.message || error.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/account-insights', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { since, until } = req.query;
|
||||||
|
if (!since || !until) {
|
||||||
|
return res.status(400).json({ error: 'Date range is required (since, until)' });
|
||||||
|
}
|
||||||
|
const insights = await fetchAccountInsights(since, until);
|
||||||
|
res.json(insights);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Account insights fetch error:', error);
|
||||||
|
res.status(500).json({
|
||||||
|
error: 'Failed to fetch account insights',
|
||||||
|
details: error.response?.data?.error?.message || error.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Writes — meta_write
|
||||||
|
router.patch('/campaigns/:campaignId/budget', requirePermission('meta_write'), async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { campaignId } = req.params;
|
||||||
|
const { budget } = req.body;
|
||||||
|
if (!budget) {
|
||||||
|
return res.status(400).json({ error: 'Budget is required' });
|
||||||
|
}
|
||||||
|
const result = await updateCampaignBudget(campaignId, budget);
|
||||||
|
res.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Budget update error:', error);
|
||||||
|
res.status(500).json({
|
||||||
|
error: 'Failed to update campaign budget',
|
||||||
|
details: error.response?.data?.error?.message || error.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/campaigns/:campaignId/:action', requirePermission('meta_write'), async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { campaignId, action } = req.params;
|
||||||
|
if (!['pause', 'unpause'].includes(action)) {
|
||||||
|
return res.status(400).json({ error: 'Invalid action. Use "pause" or "unpause"' });
|
||||||
|
}
|
||||||
|
const result = await updateCampaignStatus(campaignId, action);
|
||||||
|
res.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Status update error:', error);
|
||||||
|
res.status(500).json({
|
||||||
|
error: 'Failed to update campaign status',
|
||||||
|
details: error.response?.data?.error?.message || error.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// Typeform router — ESM conversion of typeform-server/routes/typeform.routes.js.
|
||||||
|
// All routes read-only — authenticated-only is sufficient; typeform_write reserved
|
||||||
|
// for future write endpoints (per migration 005).
|
||||||
|
|
||||||
|
import express from 'express';
|
||||||
|
import { TypeformService } from '../../services/typeform/typeform.service.js';
|
||||||
|
|
||||||
|
export function createTypeformRouter({ redis }) {
|
||||||
|
const router = express.Router();
|
||||||
|
const typeform = new TypeformService(redis);
|
||||||
|
|
||||||
|
router.get('/forms/:formId/responses', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { formId } = req.params;
|
||||||
|
const filters = req.query;
|
||||||
|
if (!formId) {
|
||||||
|
return res.status(400).json({ error: 'Missing form ID', details: 'The form ID parameter is required' });
|
||||||
|
}
|
||||||
|
const data = await typeform.getFormResponsesWithFilters(formId, filters);
|
||||||
|
if (!data) {
|
||||||
|
return res.status(404).json({ error: 'No data found', details: `No responses found for form ${formId}` });
|
||||||
|
}
|
||||||
|
res.json(data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Form responses error:', {
|
||||||
|
formId: req.params.formId,
|
||||||
|
filters: req.query,
|
||||||
|
error: error.message,
|
||||||
|
response: error.response?.data,
|
||||||
|
});
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
return res.status(401).json({ error: 'Authentication failed', details: 'Invalid Typeform API credentials' });
|
||||||
|
}
|
||||||
|
if (error.response?.status === 404) {
|
||||||
|
return res.status(404).json({ error: 'Not found', details: `Form '${req.params.formId}' not found` });
|
||||||
|
}
|
||||||
|
if (error.response?.status === 400) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error: 'Invalid request',
|
||||||
|
details: error.response?.data?.message || 'The request was invalid',
|
||||||
|
data: error.response?.data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
res.status(500).json({
|
||||||
|
error: 'Failed to fetch form responses',
|
||||||
|
details: error.response?.data?.message || error.message,
|
||||||
|
data: error.response?.data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/forms/:formId/insights', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { formId } = req.params;
|
||||||
|
if (!formId) {
|
||||||
|
return res.status(400).json({ error: 'Missing form ID', details: 'The form ID parameter is required' });
|
||||||
|
}
|
||||||
|
const data = await typeform.getFormInsights(formId);
|
||||||
|
if (!data) {
|
||||||
|
return res.status(404).json({ error: 'No data found', details: `No insights found for form ${formId}` });
|
||||||
|
}
|
||||||
|
res.json(data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Form insights error:', {
|
||||||
|
formId: req.params.formId,
|
||||||
|
error: error.message,
|
||||||
|
response: error.response?.data,
|
||||||
|
});
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
return res.status(401).json({ error: 'Authentication failed', details: 'Invalid Typeform API credentials' });
|
||||||
|
}
|
||||||
|
if (error.response?.status === 404) {
|
||||||
|
return res.status(404).json({ error: 'Not found', details: `Form '${req.params.formId}' not found` });
|
||||||
|
}
|
||||||
|
res.status(500).json({
|
||||||
|
error: 'Failed to fetch form insights',
|
||||||
|
details: error.response?.data?.message || error.message,
|
||||||
|
data: error.response?.data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// dashboard-server — Phase 4 of CONSOLIDATION_PLAN.md.
|
||||||
|
// Merges the four per-vendor PM2 apps (klaviyo, meta, google-analytics, typeform)
|
||||||
|
// into a single ESM service on DASHBOARD_PORT (default 3015).
|
||||||
|
//
|
||||||
|
// Mount points (matches Caddy proxy paths):
|
||||||
|
// /api/klaviyo/* → routes/klaviyo (was klaviyo-server :3004)
|
||||||
|
// /api/meta/* → routes/meta (was meta-server :3005)
|
||||||
|
// /api/dashboard-analytics/* → routes/google (was google-server :3007 via Caddy /api/analytics rewrite)
|
||||||
|
// /api/typeform/* → routes/typeform (was typeform-server :3008)
|
||||||
|
//
|
||||||
|
// Shared infrastructure (Phase 2 + Phase 6):
|
||||||
|
// - shared/auth/middleware.js authenticate() guards /api/* (Phase 6.1/6.2 — second line of defense)
|
||||||
|
// - shared/cors/policy.js explicit allowed-origins list (Phase 6.6)
|
||||||
|
// - shared/logging/request-log.js pino-http, Authorization/Cookie redacted (Phase 6.5/6.9)
|
||||||
|
// - shared/errors/handler.js consistent error envelope, no leak in prod
|
||||||
|
// - shared/db/pg.js / shared/db/redis.js one Pool + one ioredis client for all vendors
|
||||||
|
//
|
||||||
|
// Per-route permission gates (Phase 6.2):
|
||||||
|
// - meta_write PATCH/POST mutations to Meta campaigns
|
||||||
|
// - klaviyo_admin POST /api/klaviyo/events/clearCache (operational maintenance)
|
||||||
|
// Read-only Google + Typeform endpoints stay authenticated-only.
|
||||||
|
|
||||||
|
import { config as loadEnv } from 'dotenv';
|
||||||
|
import express from 'express';
|
||||||
|
import cors from 'cors';
|
||||||
|
import path from 'node:path';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
import { authenticate } from '../shared/auth/middleware.js';
|
||||||
|
import { corsOptions } from '../shared/cors/policy.js';
|
||||||
|
import { createPool } from '../shared/db/pg.js';
|
||||||
|
import { createRedis } from '../shared/db/redis.js';
|
||||||
|
import { errorHandler } from '../shared/errors/handler.js';
|
||||||
|
import { logger } from '../shared/logging/logger.js';
|
||||||
|
import { requestLog } from '../shared/logging/request-log.js';
|
||||||
|
|
||||||
|
import { createKlaviyoRouter } from './routes/klaviyo/index.js';
|
||||||
|
import { createMetaRouter } from './routes/meta/index.js';
|
||||||
|
import { createGoogleRouter } from './routes/google/index.js';
|
||||||
|
import { createTypeformRouter } from './routes/typeform/index.js';
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
// Layer envs: shared inventory .env wins on collisions (security-critical vars come
|
||||||
|
// from one place); vendor-specific keys come from the per-service .env.
|
||||||
|
//
|
||||||
|
// dotenv defaults to override:false so the first file loaded wins. Order matters.
|
||||||
|
const sharedEnvPath = '/var/www/inventory/.env';
|
||||||
|
const dashboardEnvPath = path.resolve(__dirname, '.env');
|
||||||
|
|
||||||
|
if (fs.existsSync(sharedEnvPath)) loadEnv({ path: sharedEnvPath });
|
||||||
|
if (fs.existsSync(dashboardEnvPath)) loadEnv({ path: dashboardEnvPath });
|
||||||
|
|
||||||
|
// Phase 6.4 — refuse to start without JWT_SECRET. Without it authenticate() falls
|
||||||
|
// back to res.status(401) on every request and the service is useless anyway.
|
||||||
|
if (!process.env.JWT_SECRET) {
|
||||||
|
logger.error('JWT_SECRET is not set; refusing to start (per Phase 6.4)');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const PORT = Number(process.env.DASHBOARD_PORT) || 3015;
|
||||||
|
|
||||||
|
// Single Postgres pool — used by authenticate() to load user permissions.
|
||||||
|
// All four vendors share this pool (auth lookups are the only DB hits at runtime).
|
||||||
|
const pool = createPool('DB');
|
||||||
|
|
||||||
|
// Single ioredis client shared across all vendors. lazyConnect:true means the
|
||||||
|
// first .get/.set triggers the actual connect — keeps startup non-blocking even
|
||||||
|
// if Redis is temporarily unavailable, and aligns with shared/db/redis.js defaults.
|
||||||
|
const redis = createRedis();
|
||||||
|
|
||||||
|
app.use(requestLog());
|
||||||
|
app.use(cors(corsOptions));
|
||||||
|
app.use(express.json({ limit: '10mb' }));
|
||||||
|
|
||||||
|
// Phase 6.1/6.2: every /api request requires a valid JWT. authenticate() also
|
||||||
|
// loads user permissions, which the per-route requirePermission() checks rely on.
|
||||||
|
app.use('/api', authenticate({ pool, secret: process.env.JWT_SECRET }));
|
||||||
|
|
||||||
|
app.use('/api/klaviyo', createKlaviyoRouter({ redis }));
|
||||||
|
app.use('/api/meta', createMetaRouter());
|
||||||
|
// Note: frontend calls /api/dashboard-analytics (Caddy used to rewrite it to
|
||||||
|
// /api/analytics for the standalone google-server). Mount at the public path so
|
||||||
|
// Caddy can drop the rewrite — see Caddyfile.proposed.
|
||||||
|
app.use('/api/dashboard-analytics', createGoogleRouter({ redis }));
|
||||||
|
app.use('/api/typeform', createTypeformRouter({ redis }));
|
||||||
|
|
||||||
|
app.get('/health', (req, res) => {
|
||||||
|
res.json({
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
service: 'dashboard-server',
|
||||||
|
redis: redis.status,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use(errorHandler);
|
||||||
|
|
||||||
|
// Connect Redis up front so the first request doesn't pay the connect cost.
|
||||||
|
// Failures here are non-fatal — vendors degrade to cache-miss → upstream fetch.
|
||||||
|
redis.connect().catch((err) => {
|
||||||
|
logger.error({ err: { message: err.message, code: err.code } }, 'redis lazy-connect failed');
|
||||||
|
});
|
||||||
|
|
||||||
|
const server = app.listen(PORT, '0.0.0.0', () => {
|
||||||
|
logger.info({ port: PORT, mode: process.env.NODE_ENV || 'development' }, 'dashboard-server listening');
|
||||||
|
});
|
||||||
|
|
||||||
|
const shutdown = async (signal) => {
|
||||||
|
logger.info({ signal }, 'dashboard-server shutting down');
|
||||||
|
server.close();
|
||||||
|
try { await redis.quit(); } catch { /* ignore */ }
|
||||||
|
try { await pool.end(); } catch { /* ignore */ }
|
||||||
|
process.exit(0);
|
||||||
|
};
|
||||||
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||||
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||||
|
|
||||||
|
process.on('uncaughtException', (err) => {
|
||||||
|
logger.error({ err: { message: err.message, stack: err.stack } }, 'uncaughtException');
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
process.on('unhandledRejection', (reason) => {
|
||||||
|
logger.error({ reason }, 'unhandledRejection');
|
||||||
|
});
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
// Google Analytics (GA4) service — ESM conversion of google-server/services/analytics.service.js.
|
||||||
|
// Phase 4: accepts injected ioredis client (was self-constructing node-redis v4 before).
|
||||||
|
// node-redis v4 set syntax `{ EX: 300 }` is translated to ioredis `setex(key, 300, val)`.
|
||||||
|
|
||||||
|
import { BetaAnalyticsDataClient } from '@google-analytics/data';
|
||||||
|
|
||||||
|
const CACHE_DURATIONS = {
|
||||||
|
REALTIME_BASIC: 60,
|
||||||
|
REALTIME_DETAILED: 300,
|
||||||
|
BASIC_METRICS: 3600,
|
||||||
|
USER_BEHAVIOR: 3600,
|
||||||
|
};
|
||||||
|
|
||||||
|
export class AnalyticsService {
|
||||||
|
constructor(redis) {
|
||||||
|
if (!redis) {
|
||||||
|
throw new Error('AnalyticsService requires an ioredis client (Phase 4: injected)');
|
||||||
|
}
|
||||||
|
this.redis = redis;
|
||||||
|
|
||||||
|
const credentials = process.env.GOOGLE_APPLICATION_CREDENTIALS_JSON;
|
||||||
|
this.analyticsClient = new BetaAnalyticsDataClient({
|
||||||
|
credentials: typeof credentials === 'string' ? JSON.parse(credentials) : credentials,
|
||||||
|
});
|
||||||
|
this.propertyId = process.env.GA_PROPERTY_ID;
|
||||||
|
}
|
||||||
|
|
||||||
|
get _redisReady() {
|
||||||
|
return this.redis.status === 'ready' || this.redis.status === 'connect';
|
||||||
|
}
|
||||||
|
|
||||||
|
async _cacheGet(key) {
|
||||||
|
if (!this._redisReady) return null;
|
||||||
|
try {
|
||||||
|
const raw = await this.redis.get(key);
|
||||||
|
return raw ? JSON.parse(raw) : null;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[AnalyticsService] cache get failed:', err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _cacheSet(key, value, ttlSec) {
|
||||||
|
if (!this._redisReady) return;
|
||||||
|
try {
|
||||||
|
await this.redis.setex(key, ttlSec, JSON.stringify(value));
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[AnalyticsService] cache set failed:', err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getBasicMetrics(startDate = '7daysAgo') {
|
||||||
|
const cacheKey = `analytics:basic_metrics:${startDate}`;
|
||||||
|
const cached = await this._cacheGet(cacheKey);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const [response] = await this.analyticsClient.runReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
dateRanges: [{ startDate, endDate: 'today' }],
|
||||||
|
dimensions: [{ name: 'date' }],
|
||||||
|
metrics: [
|
||||||
|
{ name: 'activeUsers' },
|
||||||
|
{ name: 'newUsers' },
|
||||||
|
{ name: 'averageSessionDuration' },
|
||||||
|
{ name: 'screenPageViews' },
|
||||||
|
{ name: 'bounceRate' },
|
||||||
|
{ name: 'conversions' },
|
||||||
|
],
|
||||||
|
returnPropertyQuota: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this._cacheSet(cacheKey, response, CACHE_DURATIONS.BASIC_METRICS);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getRealTimeBasicData() {
|
||||||
|
const cacheKey = 'analytics:realtime:basic';
|
||||||
|
const cached = await this._cacheGet(cacheKey);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const [userResponse] = await this.analyticsClient.runRealtimeReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
metrics: [{ name: 'activeUsers' }],
|
||||||
|
returnPropertyQuota: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const [fiveMinResponse] = await this.analyticsClient.runRealtimeReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
metrics: [{ name: 'activeUsers' }],
|
||||||
|
minuteRanges: [{ startMinutesAgo: 5, endMinutesAgo: 0 }],
|
||||||
|
});
|
||||||
|
|
||||||
|
const [timeSeriesResponse] = await this.analyticsClient.runRealtimeReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
dimensions: [{ name: 'minutesAgo' }],
|
||||||
|
metrics: [{ name: 'activeUsers' }],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = {
|
||||||
|
userResponse,
|
||||||
|
fiveMinResponse,
|
||||||
|
timeSeriesResponse,
|
||||||
|
quotaInfo: {
|
||||||
|
projectHourly: userResponse.propertyQuota.tokensPerProjectPerHour,
|
||||||
|
daily: userResponse.propertyQuota.tokensPerDay,
|
||||||
|
serverErrors: userResponse.propertyQuota.serverErrorsPerProjectPerHour,
|
||||||
|
thresholdedRequests: userResponse.propertyQuota.potentiallyThresholdedRequestsPerHour,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
await this._cacheSet(cacheKey, response, CACHE_DURATIONS.REALTIME_BASIC);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getRealTimeDetailedData() {
|
||||||
|
const cacheKey = 'analytics:realtime:detailed';
|
||||||
|
const cached = await this._cacheGet(cacheKey);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const [pageResponse] = await this.analyticsClient.runRealtimeReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
dimensions: [{ name: 'unifiedScreenName' }],
|
||||||
|
metrics: [{ name: 'screenPageViews' }],
|
||||||
|
orderBy: [{ metric: { metricName: 'screenPageViews' }, desc: true }],
|
||||||
|
limit: 25,
|
||||||
|
});
|
||||||
|
|
||||||
|
const [eventResponse] = await this.analyticsClient.runRealtimeReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
dimensions: [{ name: 'eventName' }],
|
||||||
|
metrics: [{ name: 'eventCount' }],
|
||||||
|
orderBy: [{ metric: { metricName: 'eventCount' }, desc: true }],
|
||||||
|
limit: 25,
|
||||||
|
});
|
||||||
|
|
||||||
|
const [deviceResponse] = await this.analyticsClient.runRealtimeReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
dimensions: [{ name: 'deviceCategory' }],
|
||||||
|
metrics: [{ name: 'activeUsers' }],
|
||||||
|
orderBy: [{ metric: { metricName: 'activeUsers' }, desc: true }],
|
||||||
|
limit: 10,
|
||||||
|
returnPropertyQuota: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = {
|
||||||
|
pageResponse,
|
||||||
|
eventResponse,
|
||||||
|
sourceResponse: deviceResponse,
|
||||||
|
};
|
||||||
|
|
||||||
|
await this._cacheSet(cacheKey, response, CACHE_DURATIONS.REALTIME_DETAILED);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserBehavior(timeRange = '30') {
|
||||||
|
const cacheKey = `analytics:user_behavior:${timeRange}`;
|
||||||
|
const cached = await this._cacheGet(cacheKey);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const [pageResponse] = await this.analyticsClient.runReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
||||||
|
dimensions: [{ name: 'pagePath' }],
|
||||||
|
metrics: [
|
||||||
|
{ name: 'screenPageViews' },
|
||||||
|
{ name: 'averageSessionDuration' },
|
||||||
|
{ name: 'bounceRate' },
|
||||||
|
{ name: 'sessions' },
|
||||||
|
],
|
||||||
|
orderBy: [{ metric: { metricName: 'screenPageViews' }, desc: true }],
|
||||||
|
limit: 25,
|
||||||
|
});
|
||||||
|
|
||||||
|
const [deviceResponse] = await this.analyticsClient.runReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
||||||
|
dimensions: [{ name: 'deviceCategory' }],
|
||||||
|
metrics: [{ name: 'screenPageViews' }, { name: 'sessions' }],
|
||||||
|
});
|
||||||
|
|
||||||
|
const [sourceResponse] = await this.analyticsClient.runReport({
|
||||||
|
property: `properties/${this.propertyId}`,
|
||||||
|
dateRanges: [{ startDate: `${timeRange}daysAgo`, endDate: 'today' }],
|
||||||
|
dimensions: [{ name: 'sessionSource' }],
|
||||||
|
metrics: [{ name: 'sessions' }, { name: 'conversions' }],
|
||||||
|
orderBy: [{ metric: { metricName: 'sessions' }, desc: true }],
|
||||||
|
limit: 25,
|
||||||
|
returnPropertyQuota: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = { pageResponse, deviceResponse, sourceResponse };
|
||||||
|
await this._cacheSet(cacheKey, response, CACHE_DURATIONS.USER_BEHAVIOR);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -1,14 +1,14 @@
|
|||||||
import fetch from 'node-fetch';
|
import fetch from 'node-fetch';
|
||||||
import { TimeManager } from '../utils/time.utils.js';
|
import { TimeManager } from '../../utils/time.utils.js';
|
||||||
import { RedisService } from './redis.service.js';
|
import { RedisService } from './redis.service.js';
|
||||||
|
|
||||||
export class CampaignsService {
|
export class CampaignsService {
|
||||||
constructor(apiKey, apiRevision) {
|
constructor(apiKey, apiRevision, redis) {
|
||||||
this.apiKey = apiKey;
|
this.apiKey = apiKey;
|
||||||
this.apiRevision = apiRevision;
|
this.apiRevision = apiRevision;
|
||||||
this.baseUrl = 'https://a.klaviyo.com/api';
|
this.baseUrl = 'https://a.klaviyo.com/api';
|
||||||
this.timeManager = new TimeManager();
|
this.timeManager = new TimeManager();
|
||||||
this.redisService = new RedisService();
|
this.redisService = new RedisService(redis);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getCampaigns(params = {}) {
|
async getCampaigns(params = {}) {
|
||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
import fetch from 'node-fetch';
|
import fetch from 'node-fetch';
|
||||||
import { TimeManager } from '../utils/time.utils.js';
|
import { TimeManager } from '../../utils/time.utils.js';
|
||||||
import { RedisService } from './redis.service.js';
|
import { RedisService } from './redis.service.js';
|
||||||
import _ from 'lodash';
|
import _ from 'lodash';
|
||||||
|
|
||||||
@@ -13,12 +13,12 @@ const METRIC_IDS = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export class EventsService {
|
export class EventsService {
|
||||||
constructor(apiKey, apiRevision) {
|
constructor(apiKey, apiRevision, redis) {
|
||||||
this.apiKey = apiKey;
|
this.apiKey = apiKey;
|
||||||
this.apiRevision = apiRevision;
|
this.apiRevision = apiRevision;
|
||||||
this.baseUrl = 'https://a.klaviyo.com/api';
|
this.baseUrl = 'https://a.klaviyo.com/api';
|
||||||
this.timeManager = new TimeManager();
|
this.timeManager = new TimeManager();
|
||||||
this.redisService = new RedisService();
|
this.redisService = new RedisService(redis);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getEvents(params = {}) {
|
async getEvents(params = {}) {
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
// Klaviyo cache wrapper. Was a self-instantiating ioredis client per service in
|
||||||
|
// the standalone klaviyo-server; now accepts an injected client so the merged
|
||||||
|
// dashboard-server shares one connection across all vendors (Phase 4).
|
||||||
|
//
|
||||||
|
// Public surface kept identical to the original so the ~3K LOC of klaviyo
|
||||||
|
// service code (events/campaigns/reporting) needs no other changes:
|
||||||
|
// - get(key)
|
||||||
|
// - set(key, data, ttl)
|
||||||
|
// - _getCacheKey(type, params)
|
||||||
|
// - _getTTL(timeRange)
|
||||||
|
// - getEventData(type, params) / cacheEventData(type, params, data)
|
||||||
|
// - clearCache(params)
|
||||||
|
//
|
||||||
|
// Reads short-circuit to null when the client isn't ready; writes are no-ops.
|
||||||
|
// Same "Redis hiccup → fall through to upstream" behavior as before.
|
||||||
|
|
||||||
|
import { TimeManager } from '../../utils/time.utils.js';
|
||||||
|
|
||||||
|
export class RedisService {
|
||||||
|
constructor(redis) {
|
||||||
|
if (!redis) {
|
||||||
|
throw new Error('RedisService requires an ioredis client (Phase 4: injected, no longer self-constructed)');
|
||||||
|
}
|
||||||
|
this.client = redis;
|
||||||
|
this.timeManager = new TimeManager();
|
||||||
|
this.DEFAULT_TTL = 5 * 60;
|
||||||
|
}
|
||||||
|
|
||||||
|
get isConnected() {
|
||||||
|
// ioredis: 'wait' | 'reconnecting' | 'connecting' | 'connect' | 'ready' | 'close' | 'end'
|
||||||
|
return this.client.status === 'ready' || this.client.status === 'connect';
|
||||||
|
}
|
||||||
|
|
||||||
|
async get(key) {
|
||||||
|
if (!this.isConnected) return null;
|
||||||
|
try {
|
||||||
|
const data = await this.client.get(key);
|
||||||
|
return data ? JSON.parse(data) : null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[RedisService] Error getting data:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async set(key, data, ttl = this.DEFAULT_TTL) {
|
||||||
|
if (!this.isConnected) return;
|
||||||
|
try {
|
||||||
|
await this.client.setex(key, ttl, JSON.stringify(data));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[RedisService] Error setting data:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_getCacheKey(type, params = {}) {
|
||||||
|
const {
|
||||||
|
timeRange,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
metricId,
|
||||||
|
metric,
|
||||||
|
daily,
|
||||||
|
cacheKey,
|
||||||
|
isPreviousPeriod,
|
||||||
|
customFilters,
|
||||||
|
} = params;
|
||||||
|
|
||||||
|
let key = `klaviyo:${type}`;
|
||||||
|
|
||||||
|
if (type === 'stats:details') {
|
||||||
|
key += `:${metric || 'all'}`;
|
||||||
|
if (daily) key += ':daily';
|
||||||
|
if (customFilters?.length) {
|
||||||
|
const filterHash = customFilters.join('').replace(/[^a-zA-Z0-9]/g, '');
|
||||||
|
key += `:${filterHash}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cacheKey) {
|
||||||
|
key += `:${cacheKey}`;
|
||||||
|
} else if (timeRange) {
|
||||||
|
key += `:${timeRange}`;
|
||||||
|
if (metricId) key += `:${metricId}`;
|
||||||
|
if (isPreviousPeriod) key += ':prev';
|
||||||
|
} else if (startDate && endDate) {
|
||||||
|
key += `:custom:${startDate}:${endDate}`;
|
||||||
|
if (metricId) key += `:${metricId}`;
|
||||||
|
if (isPreviousPeriod) key += ':prev';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (['pre_orders', 'local_pickup', 'on_hold'].includes(metric)) {
|
||||||
|
key += `:${metric}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
_getTTL(timeRange) {
|
||||||
|
const TTL_MAP = {
|
||||||
|
today: 2 * 60,
|
||||||
|
yesterday: 30 * 60,
|
||||||
|
thisWeek: 5 * 60,
|
||||||
|
lastWeek: 60 * 60,
|
||||||
|
thisMonth: 10 * 60,
|
||||||
|
lastMonth: 2 * 60 * 60,
|
||||||
|
last7days: 5 * 60,
|
||||||
|
last30days: 15 * 60,
|
||||||
|
custom: 15 * 60,
|
||||||
|
};
|
||||||
|
return TTL_MAP[timeRange] || this.DEFAULT_TTL;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getEventData(type, params) {
|
||||||
|
if (!this.isConnected) return null;
|
||||||
|
try {
|
||||||
|
const baseKey = this._getCacheKey('events', params);
|
||||||
|
return await this.get(`${baseKey}:${type}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[RedisService] Error getting event data:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async cacheEventData(type, params, data) {
|
||||||
|
if (!this.isConnected) return;
|
||||||
|
try {
|
||||||
|
const ttl = this._getTTL(params.timeRange);
|
||||||
|
const baseKey = this._getCacheKey('events', params);
|
||||||
|
await this.set(`${baseKey}:${type}`, data, ttl);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[RedisService] Error caching event data:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async clearCache(params = {}) {
|
||||||
|
if (!this.isConnected) return;
|
||||||
|
try {
|
||||||
|
const pattern = this._getCacheKey('events', params) + '*';
|
||||||
|
const keys = await this.client.keys(pattern);
|
||||||
|
if (keys.length > 0) {
|
||||||
|
await this.client.del(...keys);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[RedisService] Error clearing cache:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
import fetch from 'node-fetch';
|
import fetch from 'node-fetch';
|
||||||
import { TimeManager } from '../utils/time.utils.js';
|
import { TimeManager } from '../../utils/time.utils.js';
|
||||||
import { RedisService } from './redis.service.js';
|
import { RedisService } from './redis.service.js';
|
||||||
|
|
||||||
const METRIC_IDS = {
|
const METRIC_IDS = {
|
||||||
@@ -7,12 +7,12 @@ const METRIC_IDS = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export class ReportingService {
|
export class ReportingService {
|
||||||
constructor(apiKey, apiRevision) {
|
constructor(apiKey, apiRevision, redis) {
|
||||||
this.apiKey = apiKey;
|
this.apiKey = apiKey;
|
||||||
this.apiRevision = apiRevision;
|
this.apiRevision = apiRevision;
|
||||||
this.baseUrl = 'https://a.klaviyo.com/api';
|
this.baseUrl = 'https://a.klaviyo.com/api';
|
||||||
this.timeManager = new TimeManager();
|
this.timeManager = new TimeManager();
|
||||||
this.redisService = new RedisService();
|
this.redisService = new RedisService(redis);
|
||||||
this._pendingReportRequest = null;
|
this._pendingReportRequest = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// Meta (Facebook Ads) service — ESM conversion of meta-server/services/meta.service.js.
|
||||||
|
// No Redis caching (matches the original — Meta calls are cheap-enough; reach/spend
|
||||||
|
// rolls over once per request). Uses axios.
|
||||||
|
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
function getConfig() {
|
||||||
|
const version = process.env.META_API_VERSION || 'v21.0';
|
||||||
|
return {
|
||||||
|
baseUrl: `https://graph.facebook.com/${version}`,
|
||||||
|
accessToken: process.env.META_ACCESS_TOKEN,
|
||||||
|
adAccountId: process.env.META_AD_ACCOUNT_ID,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function metaApiRequest(endpoint, params = {}) {
|
||||||
|
const { baseUrl, accessToken } = getConfig();
|
||||||
|
try {
|
||||||
|
const response = await axios.get(`${baseUrl}/${endpoint}`, {
|
||||||
|
params: {
|
||||||
|
access_token: accessToken,
|
||||||
|
time_zone: 'America/New_York',
|
||||||
|
...params,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Meta API Error:', {
|
||||||
|
message: error.message,
|
||||||
|
response: error.response?.data,
|
||||||
|
endpoint,
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchCampaigns(since, until) {
|
||||||
|
const { adAccountId } = getConfig();
|
||||||
|
const campaigns = await metaApiRequest(`act_${adAccountId}/campaigns`, {
|
||||||
|
fields: [
|
||||||
|
'id',
|
||||||
|
'name',
|
||||||
|
'status',
|
||||||
|
'objective',
|
||||||
|
'daily_budget',
|
||||||
|
'lifetime_budget',
|
||||||
|
'adsets{daily_budget,lifetime_budget}',
|
||||||
|
`insights.time_range({'since':'${since}','until':'${until}'}).level(campaign){
|
||||||
|
spend,
|
||||||
|
impressions,
|
||||||
|
clicks,
|
||||||
|
ctr,
|
||||||
|
reach,
|
||||||
|
frequency,
|
||||||
|
cpm,
|
||||||
|
cpc,
|
||||||
|
actions,
|
||||||
|
action_values,
|
||||||
|
cost_per_action_type
|
||||||
|
}`,
|
||||||
|
].join(','),
|
||||||
|
limit: 100,
|
||||||
|
});
|
||||||
|
|
||||||
|
return campaigns.data.filter((c) => c.insights?.data?.[0]?.spend > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchAccountInsights(since, until) {
|
||||||
|
const { adAccountId } = getConfig();
|
||||||
|
const accountInsights = await metaApiRequest(`act_${adAccountId}/insights`, {
|
||||||
|
fields: 'reach,spend,impressions,clicks,ctr,cpm,actions,action_values',
|
||||||
|
time_range: JSON.stringify({ since, until }),
|
||||||
|
});
|
||||||
|
return accountInsights.data[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateCampaignBudget(campaignId, budget) {
|
||||||
|
const { baseUrl, accessToken } = getConfig();
|
||||||
|
try {
|
||||||
|
const response = await axios.post(`${baseUrl}/${campaignId}`, {
|
||||||
|
access_token: accessToken,
|
||||||
|
daily_budget: budget * 100, // dollars → cents
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Update campaign budget error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateCampaignStatus(campaignId, action) {
|
||||||
|
const { baseUrl, accessToken } = getConfig();
|
||||||
|
try {
|
||||||
|
const status = action === 'pause' ? 'PAUSED' : 'ACTIVE';
|
||||||
|
const response = await axios.post(`${baseUrl}/${campaignId}`, {
|
||||||
|
access_token: accessToken,
|
||||||
|
status,
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Update campaign status error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
// Typeform service — ESM conversion of typeform-server/services/typeform.service.js.
|
||||||
|
// Phase 4: accepts injected ioredis client. node-redis v4 set syntax `{ EX: 300 }`
|
||||||
|
// translated to ioredis `setex(key, 300, val)`.
|
||||||
|
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
export class TypeformService {
|
||||||
|
constructor(redis) {
|
||||||
|
if (!redis) {
|
||||||
|
throw new Error('TypeformService requires an ioredis client (Phase 4: injected)');
|
||||||
|
}
|
||||||
|
this.redis = redis;
|
||||||
|
|
||||||
|
const token = process.env.TYPEFORM_ACCESS_TOKEN;
|
||||||
|
if (!token) {
|
||||||
|
console.warn('[Typeform] TYPEFORM_ACCESS_TOKEN not set — all calls will 401');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.apiClient = axios.create({
|
||||||
|
baseURL: 'https://api.typeform.com',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
get _redisReady() {
|
||||||
|
return this.redis.status === 'ready' || this.redis.status === 'connect';
|
||||||
|
}
|
||||||
|
|
||||||
|
async _cacheGet(key) {
|
||||||
|
if (!this._redisReady) return null;
|
||||||
|
try {
|
||||||
|
const raw = await this.redis.get(key);
|
||||||
|
return raw ? JSON.parse(raw) : null;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[Typeform] cache get failed:', err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _cacheSet(key, value, ttlSec) {
|
||||||
|
if (!this._redisReady) return;
|
||||||
|
try {
|
||||||
|
await this.redis.setex(key, ttlSec, JSON.stringify(value));
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[Typeform] cache set failed:', err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFormResponses(formId, params = {}) {
|
||||||
|
const cacheKey = `typeform:responses:${formId}:${JSON.stringify(params)}`;
|
||||||
|
const cached = await this._cacheGet(cacheKey);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const response = await this.apiClient.get(`/forms/${formId}/responses`, { params });
|
||||||
|
const data = response.data;
|
||||||
|
await this._cacheSet(cacheKey, data, 300);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFormInsights(formId) {
|
||||||
|
const cacheKey = `typeform:insights:${formId}`;
|
||||||
|
const cached = await this._cacheGet(cacheKey);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const response = await this.apiClient.get(`/insights/${formId}/summary`);
|
||||||
|
const data = response.data;
|
||||||
|
await this._cacheSet(cacheKey, data, 300);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFormResponsesWithFilters(formId, { since, until, pageSize = 25, ...otherParams } = {}) {
|
||||||
|
const params = { page_size: pageSize, ...otherParams };
|
||||||
|
if (since) params.since = new Date(since).toISOString();
|
||||||
|
if (until) params.until = new Date(until).toISOString();
|
||||||
|
return this.getFormResponses(formId, params);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
# Server Configuration
|
|
||||||
NODE_ENV=development
|
|
||||||
TYPEFORM_PORT=3008
|
|
||||||
|
|
||||||
# Redis Configuration
|
|
||||||
REDIS_URL=redis://localhost:6379
|
|
||||||
|
|
||||||
# Typeform API Configuration
|
|
||||||
TYPEFORM_ACCESS_TOKEN=your_typeform_access_token_here
|
|
||||||
|
|
||||||
# Optional: Form IDs (if you want to store them in env)
|
|
||||||
TYPEFORM_FORM_ID_1=your_first_form_id
|
|
||||||
TYPEFORM_FORM_ID_2=your_second_form_id
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,20 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "typeform-server",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"description": "Typeform API integration server",
|
|
||||||
"main": "server.js",
|
|
||||||
"scripts": {
|
|
||||||
"start": "node server.js",
|
|
||||||
"dev": "nodemon server.js"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"axios": "^1.6.2",
|
|
||||||
"cors": "^2.8.5",
|
|
||||||
"dotenv": "^16.3.1",
|
|
||||||
"express": "^4.18.2",
|
|
||||||
"redis": "^4.6.11"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"nodemon": "^3.0.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const typeformService = require('../services/typeform.service');
|
|
||||||
|
|
||||||
// Get form responses
|
|
||||||
router.get('/forms/:formId/responses', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { formId } = req.params;
|
|
||||||
const filters = req.query;
|
|
||||||
|
|
||||||
console.log(`Fetching responses for form ${formId} with filters:`, filters);
|
|
||||||
|
|
||||||
if (!formId) {
|
|
||||||
return res.status(400).json({
|
|
||||||
error: 'Missing form ID',
|
|
||||||
details: 'The form ID parameter is required'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await typeformService.getFormResponsesWithFilters(formId, filters);
|
|
||||||
|
|
||||||
if (!data) {
|
|
||||||
return res.status(404).json({
|
|
||||||
error: 'No data found',
|
|
||||||
details: `No responses found for form ${formId}`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json(data);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Form responses error:', {
|
|
||||||
formId: req.params.formId,
|
|
||||||
filters: req.query,
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack,
|
|
||||||
response: error.response?.data
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle specific error cases
|
|
||||||
if (error.response?.status === 401) {
|
|
||||||
return res.status(401).json({
|
|
||||||
error: 'Authentication failed',
|
|
||||||
details: 'Invalid Typeform API credentials'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error.response?.status === 404) {
|
|
||||||
return res.status(404).json({
|
|
||||||
error: 'Not found',
|
|
||||||
details: `Form '${req.params.formId}' not found`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error.response?.status === 400) {
|
|
||||||
return res.status(400).json({
|
|
||||||
error: 'Invalid request',
|
|
||||||
details: error.response?.data?.message || 'The request was invalid',
|
|
||||||
data: error.response?.data
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Failed to fetch form responses',
|
|
||||||
details: error.response?.data?.message || error.message,
|
|
||||||
data: error.response?.data
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get form insights
|
|
||||||
router.get('/forms/:formId/insights', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { formId } = req.params;
|
|
||||||
|
|
||||||
if (!formId) {
|
|
||||||
return res.status(400).json({
|
|
||||||
error: 'Missing form ID',
|
|
||||||
details: 'The form ID parameter is required'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await typeformService.getFormInsights(formId);
|
|
||||||
|
|
||||||
if (!data) {
|
|
||||||
return res.status(404).json({
|
|
||||||
error: 'No data found',
|
|
||||||
details: `No insights found for form ${formId}`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json(data);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Form insights error:', {
|
|
||||||
formId: req.params.formId,
|
|
||||||
error: error.message,
|
|
||||||
response: error.response?.data
|
|
||||||
});
|
|
||||||
|
|
||||||
if (error.response?.status === 401) {
|
|
||||||
return res.status(401).json({
|
|
||||||
error: 'Authentication failed',
|
|
||||||
details: 'Invalid Typeform API credentials'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error.response?.status === 404) {
|
|
||||||
return res.status(404).json({
|
|
||||||
error: 'Not found',
|
|
||||||
details: `Form '${req.params.formId}' not found`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status(500).json({
|
|
||||||
error: 'Failed to fetch form insights',
|
|
||||||
details: error.response?.data?.message || error.message,
|
|
||||||
data: error.response?.data
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const cors = require('cors');
|
|
||||||
const path = require('path');
|
|
||||||
require('dotenv').config({
|
|
||||||
path: path.resolve(__dirname, '.env')
|
|
||||||
});
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const port = process.env.TYPEFORM_PORT || 3008;
|
|
||||||
|
|
||||||
app.use(cors());
|
|
||||||
app.use(express.json());
|
|
||||||
|
|
||||||
// Import routes
|
|
||||||
const typeformRoutes = require('./routes/typeform.routes');
|
|
||||||
|
|
||||||
// Use routes
|
|
||||||
app.use('/api/typeform', typeformRoutes);
|
|
||||||
|
|
||||||
// Error handling middleware
|
|
||||||
app.use((err, req, res, next) => {
|
|
||||||
console.error(err.stack);
|
|
||||||
res.status(500).json({ error: 'Something went wrong!' });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Start server
|
|
||||||
app.listen(port, () => {
|
|
||||||
console.log(`Typeform API server running on port ${port}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = app;
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
const axios = require('axios');
|
|
||||||
const { createClient } = require('redis');
|
|
||||||
|
|
||||||
class TypeformService {
|
|
||||||
constructor() {
|
|
||||||
this.redis = createClient({
|
|
||||||
url: process.env.REDIS_URL
|
|
||||||
});
|
|
||||||
|
|
||||||
this.redis.on('error', err => console.error('Redis Client Error:', err));
|
|
||||||
this.redis.connect().catch(err => console.error('Redis connection error:', err));
|
|
||||||
|
|
||||||
const token = process.env.TYPEFORM_ACCESS_TOKEN;
|
|
||||||
console.log('Initializing Typeform client with token:', token ? `${token.slice(0, 10)}...` : 'missing');
|
|
||||||
|
|
||||||
this.apiClient = axios.create({
|
|
||||||
baseURL: 'https://api.typeform.com',
|
|
||||||
headers: {
|
|
||||||
'Authorization': `Bearer ${token}`,
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Test the token
|
|
||||||
this.testConnection();
|
|
||||||
}
|
|
||||||
|
|
||||||
async testConnection() {
|
|
||||||
try {
|
|
||||||
const response = await this.apiClient.get('/forms');
|
|
||||||
console.log('Typeform connection test successful:', {
|
|
||||||
status: response.status,
|
|
||||||
headers: response.headers,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Typeform connection test failed:', {
|
|
||||||
error: error.message,
|
|
||||||
response: error.response?.data,
|
|
||||||
status: error.response?.status,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getFormResponses(formId, params = {}) {
|
|
||||||
const cacheKey = `typeform:responses:${formId}:${JSON.stringify(params)}`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Try Redis first
|
|
||||||
const cachedData = await this.redis.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
console.log(`Form responses for ${formId} found in Redis cache`);
|
|
||||||
return JSON.parse(cachedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch from API
|
|
||||||
const response = await this.apiClient.get(`/forms/${formId}/responses`, { params });
|
|
||||||
const data = response.data;
|
|
||||||
|
|
||||||
// Save to Redis with 5 minute expiry
|
|
||||||
await this.redis.set(cacheKey, JSON.stringify(data), {
|
|
||||||
EX: 300 // 5 minutes
|
|
||||||
});
|
|
||||||
|
|
||||||
return data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Error fetching form responses for ${formId}:`, {
|
|
||||||
error: error.message,
|
|
||||||
params,
|
|
||||||
response: error.response?.data
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getFormInsights(formId) {
|
|
||||||
const cacheKey = `typeform:insights:${formId}`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Try Redis first
|
|
||||||
const cachedData = await this.redis.get(cacheKey);
|
|
||||||
if (cachedData) {
|
|
||||||
console.log(`Form insights for ${formId} found in Redis cache`);
|
|
||||||
return JSON.parse(cachedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Log the request details
|
|
||||||
console.log(`Fetching insights for form ${formId}...`, {
|
|
||||||
url: `/insights/${formId}/summary`,
|
|
||||||
headers: this.apiClient.defaults.headers
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch from API
|
|
||||||
const response = await this.apiClient.get(`/insights/${formId}/summary`);
|
|
||||||
console.log('Typeform insights response:', {
|
|
||||||
status: response.status,
|
|
||||||
headers: response.headers,
|
|
||||||
data: response.data
|
|
||||||
});
|
|
||||||
const data = response.data;
|
|
||||||
|
|
||||||
// Save to Redis with 5 minute expiry
|
|
||||||
await this.redis.set(cacheKey, JSON.stringify(data), {
|
|
||||||
EX: 300 // 5 minutes
|
|
||||||
});
|
|
||||||
|
|
||||||
return data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Error fetching form insights for ${formId}:`, {
|
|
||||||
error: error.message,
|
|
||||||
response: error.response?.data,
|
|
||||||
status: error.response?.status,
|
|
||||||
headers: error.response?.headers,
|
|
||||||
requestUrl: `/insights/${formId}/summary`,
|
|
||||||
requestHeaders: this.apiClient.defaults.headers
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getFormResponsesWithFilters(formId, { since, until, pageSize = 25, ...otherParams } = {}) {
|
|
||||||
try {
|
|
||||||
const params = {
|
|
||||||
page_size: pageSize,
|
|
||||||
...otherParams
|
|
||||||
};
|
|
||||||
|
|
||||||
if (since) {
|
|
||||||
params.since = new Date(since).toISOString();
|
|
||||||
}
|
|
||||||
if (until) {
|
|
||||||
params.until = new Date(until).toISOString();
|
|
||||||
}
|
|
||||||
|
|
||||||
return await this.getFormResponses(formId, params);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error in getFormResponsesWithFilters:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = new TypeformService();
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
# Phase 6.1 + 6.6 + 6.7: tools.acherryontop.com final form
|
|
||||||
#
|
|
||||||
# Apply on the server with:
|
|
||||||
# curl -X POST http://localhost:2020/load \
|
|
||||||
# -H 'Content-Type: text/caddyfile' \
|
|
||||||
# --data-binary @/home/matt/Caddyfile.new
|
|
||||||
# sudo cp /home/matt/Caddyfile.new /etc/caddy/Caddyfile
|
|
||||||
# sudo cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.bak.$(date +%F)
|
|
||||||
#
|
|
||||||
# Differences from current /etc/caddy/Caddyfile:
|
|
||||||
# 1. forward_auth gate added in front of /api/* and /chat-api/* (Phase 6.1).
|
|
||||||
# 2. /uploads/* moved behind the forward_auth gate (Phase 6.7 — was public).
|
|
||||||
# 3. LAN wildcards / Access-Control-Allow-Origin "*" defaults dropped from /api/* (Phase 6.6).
|
|
||||||
# 4. Removed dead /api/{aircall,gorgias,clarity}/* routes (Phase 1 — already cleaned up here).
|
|
||||||
#
|
|
||||||
# Phase 4 (dashboard-server merge) is NOT yet reflected — klaviyo/meta/google/typeform
|
|
||||||
# still route to their per-vendor PM2 apps in the live Caddyfile. Update those handle
|
|
||||||
# blocks to localhost:3015 when dashboard-server ships.
|
|
||||||
|
|
||||||
tools.acherryontop.com {
|
|
||||||
import security_headers
|
|
||||||
|
|
||||||
# Public: login endpoint
|
|
||||||
handle /auth-inv/* {
|
|
||||||
uri strip_prefix /auth-inv
|
|
||||||
reverse_proxy localhost:3011
|
|
||||||
}
|
|
||||||
|
|
||||||
# Public: static frontend assets (long-cache)
|
|
||||||
@static path *.js *.css *.png *.jpg *.jpeg *.gif *.ico *.svg *.woff *.woff2
|
|
||||||
handle @static {
|
|
||||||
header Cache-Control "public, max-age=2592000"
|
|
||||||
root * /var/www/inventory/frontend/build
|
|
||||||
file_server
|
|
||||||
}
|
|
||||||
|
|
||||||
# ----- Authenticated zone -----
|
|
||||||
# Phase 6.1: forward_auth subrequest to auth-server:/verify. 2xx → proceeds.
|
|
||||||
# 401/403 → Caddy returns auth-server response to client; backend never sees it.
|
|
||||||
@gated path /api/* /chat-api/* /uploads/*
|
|
||||||
handle @gated {
|
|
||||||
forward_auth localhost:3011 {
|
|
||||||
uri /verify
|
|
||||||
copy_headers Authorization
|
|
||||||
}
|
|
||||||
|
|
||||||
# Phase 6.7: /uploads/* now behind the gate (was a public file_server before)
|
|
||||||
handle /uploads/* {
|
|
||||||
root * /var/www/inventory
|
|
||||||
file_server
|
|
||||||
}
|
|
||||||
|
|
||||||
# Vendor dashboard routes
|
|
||||||
# NOTE: pre-Phase-4 these are still on separate ports; updates here when merged.
|
|
||||||
handle /api/klaviyo/* { reverse_proxy localhost:3015 }
|
|
||||||
handle /api/meta/* { reverse_proxy localhost:3015 }
|
|
||||||
handle /api/google-analytics/* { reverse_proxy localhost:3015 }
|
|
||||||
handle /api/typeform/* { reverse_proxy localhost:3015 }
|
|
||||||
|
|
||||||
# ACOT
|
|
||||||
handle /api/acot/* { reverse_proxy localhost:3012 }
|
|
||||||
|
|
||||||
# Chat
|
|
||||||
handle /chat-api/* {
|
|
||||||
uri strip_prefix /chat-api
|
|
||||||
reverse_proxy localhost:3014
|
|
||||||
}
|
|
||||||
|
|
||||||
# Catch-all: inventory-server
|
|
||||||
handle /api/* { reverse_proxy localhost:3010 }
|
|
||||||
}
|
|
||||||
|
|
||||||
# Out-of-band probes (unauthenticated)
|
|
||||||
handle /health { reverse_proxy localhost:3010 }
|
|
||||||
|
|
||||||
# SPA fallback (public assets)
|
|
||||||
handle {
|
|
||||||
root * /var/www/inventory/frontend/build
|
|
||||||
try_files {path} /index.html
|
|
||||||
file_server
|
|
||||||
encode gzip
|
|
||||||
}
|
|
||||||
|
|
||||||
handle_errors {
|
|
||||||
respond "{err.status_code} {err.status_text}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
# Server-side deployment artefacts for Phase 3 + 6
|
|
||||||
|
|
||||||
This directory contains proposed versions of files that live outside the
|
|
||||||
inventory-server tree on production. Each is a recommendation — apply
|
|
||||||
deliberately and only after the Node-side ESM + auth changes are deployed and
|
|
||||||
smoke-tested.
|
|
||||||
|
|
||||||
| Source | Target | Phase |
|
|
||||||
| --------------------------------------- | ------------------------------------- | -------- |
|
|
||||||
| `Caddyfile.proposed` | `/etc/caddy/Caddyfile` | 6.1, 6.6, 6.7 |
|
|
||||||
| `ecosystem.config.cjs.proposed` | `/var/www/ecosystem.config.cjs` | 6.4, 6.10 |
|
|
||||||
|
|
||||||
## Recommended apply order
|
|
||||||
|
|
||||||
1. **Deploy the Node code first** (this repo). PM2 reload picks up the new
|
|
||||||
ESM-mode inventory-server and auth-server. At this point the frontend will
|
|
||||||
start hitting 401s on every API call because the new `authenticate()`
|
|
||||||
middleware is live and the frontend doesn't carry Bearer tokens on most
|
|
||||||
fetches. **This is expected per the discussion in CONSOLIDATION_PLAN.md
|
|
||||||
§6** — the frontend fetch-wrapper work is the next deliverable.
|
|
||||||
|
|
||||||
2. **Apply the ecosystem.cjs change** (Phase 6.4) to fix the `JWT_SECRET`
|
|
||||||
shadow-override before the next pm2 restart silently re-introduces it.
|
|
||||||
|
|
||||||
3. **Apply the Caddyfile change** (Phase 6.1) only after the frontend is
|
|
||||||
sending Bearer tokens. Until then, `forward_auth` will reject every page
|
|
||||||
refresh at the edge.
|
|
||||||
|
|
||||||
## Caddyfile apply pattern
|
|
||||||
|
|
||||||
Caddy admin API is on `:2020` (matt has access). On-disk file needs root.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Upload + load atomically into the running Caddy
|
|
||||||
curl -X POST http://localhost:2020/load \
|
|
||||||
-H 'Content-Type: text/caddyfile' \
|
|
||||||
--data-binary @/home/matt/Caddyfile.new
|
|
||||||
|
|
||||||
# Persist to disk (separate sudo step)
|
|
||||||
sudo cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.bak.$(date +%F)
|
|
||||||
sudo cp /home/matt/Caddyfile.new /etc/caddy/Caddyfile
|
|
||||||
```
|
|
||||||
|
|
||||||
## ecosystem.cjs apply pattern
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo cp /var/www/ecosystem.config.cjs /var/www/ecosystem.config.cjs.bak.$(date +%F)
|
|
||||||
sudo cp /home/matt/ecosystem.config.cjs.new /var/www/ecosystem.config.cjs
|
|
||||||
pm2 reload ecosystem.config.cjs --update-env
|
|
||||||
pm2 env new-auth-server | grep -i jwt # JWT_SECRET from .env only
|
|
||||||
```
|
|
||||||
|
|
||||||
## Rollback
|
|
||||||
|
|
||||||
Every applied file leaves a `.bak.YYYY-MM-DD` next to it. `sudo cp <bak>
|
|
||||||
<original>` then `caddy reload` / `pm2 reload`.
|
|
||||||
|
|
||||||
Phase 6 changes are *additive* — if `forward_auth` causes problems, comment
|
|
||||||
out the directive in the live Caddyfile and per-server middleware
|
|
||||||
(`authenticate()` in inventory-server, in particular) continues protecting
|
|
||||||
routes.
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
// Phase 6.4 + 6.10: proposed /var/www/ecosystem.config.cjs
|
|
||||||
//
|
|
||||||
// Diffs from the live file (CONSOLIDATION_PLAN.md §6.4 / §6.10):
|
|
||||||
// 1. Drop the `JWT_SECRET: process.env.JWT_SECRET` override in new-auth-server's
|
|
||||||
// env block. That override shadowed the .env value with whatever shell var was
|
|
||||||
// exported when pm2 was last started — causing the silent-divergence footgun
|
|
||||||
// called out in CLAUDE.md memory. With it removed, .env is the single source.
|
|
||||||
// 2. Move ADD_WORD_TOKEN out of the inline env into /opt/lt-wordlist-api/.env.
|
|
||||||
// The PM2 entry below no longer references it.
|
|
||||||
// 3. Rename the placeholder script paths if you have any half-finished ones; this
|
|
||||||
// version only lists the apps that actually run today (post-Phase-1 cleanup).
|
|
||||||
//
|
|
||||||
// To apply:
|
|
||||||
// sudo cp /var/www/ecosystem.config.cjs /var/www/ecosystem.config.cjs.bak.$(date +%F)
|
|
||||||
// sudo cp /home/matt/ecosystem.config.cjs.new /var/www/ecosystem.config.cjs
|
|
||||||
// pm2 reload ecosystem.config.cjs --update-env
|
|
||||||
//
|
|
||||||
// Verify after reload:
|
|
||||||
// pm2 env new-auth-server | grep -i jwt # should show JWT_SECRET from .env only
|
|
||||||
// pm2 env new-auth-server | grep ADD_WORD # should be empty
|
|
||||||
|
|
||||||
const inventoryEnv = require('dotenv').config({ path: '/var/www/inventory/.env' }).parsed;
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
apps: [
|
|
||||||
{
|
|
||||||
name: 'new-auth-server', // Phase 8 may rename to 'auth-server' — cosmetic
|
|
||||||
script: './inventory/auth/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: {
|
|
||||||
...inventoryEnv,
|
|
||||||
NODE_ENV: 'production',
|
|
||||||
AUTH_PORT: 3011,
|
|
||||||
// PHASE 6.4 FIX: no JWT_SECRET override here. .env wins.
|
|
||||||
},
|
|
||||||
max_memory_restart: '500M',
|
|
||||||
error_file: '/var/log/pm2/new-auth-server-error.log',
|
|
||||||
out_file: '/var/log/pm2/new-auth-server-out.log',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'inventory-server',
|
|
||||||
script: './inventory/src/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: {
|
|
||||||
...inventoryEnv,
|
|
||||||
NODE_ENV: 'production',
|
|
||||||
PORT: 3010,
|
|
||||||
UPLOADS_DIR: '/var/www/inventory/uploads',
|
|
||||||
},
|
|
||||||
max_memory_restart: '1G',
|
|
||||||
error_file: '/var/log/pm2/inventory-server-error.log',
|
|
||||||
out_file: '/var/log/pm2/inventory-server-out.log',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'chat-server',
|
|
||||||
script: './inventory/chat/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: { ...inventoryEnv, NODE_ENV: 'production', PORT: 3014 },
|
|
||||||
max_memory_restart: '500M',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'acot-server',
|
|
||||||
script: './inventory/dashboard/acot-server/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: { ...inventoryEnv, NODE_ENV: 'production', ACOT_PORT: 3012 },
|
|
||||||
max_memory_restart: '1G',
|
|
||||||
},
|
|
||||||
// Per-vendor dashboard apps stay until Phase 4 merge ships.
|
|
||||||
{
|
|
||||||
name: 'klaviyo-server',
|
|
||||||
script: './inventory/dashboard/klaviyo-server/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: { ...inventoryEnv, NODE_ENV: 'production' },
|
|
||||||
max_memory_restart: '500M',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'meta-server',
|
|
||||||
script: './inventory/dashboard/meta-server/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: { ...inventoryEnv, NODE_ENV: 'production' },
|
|
||||||
max_memory_restart: '300M',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'google-server',
|
|
||||||
script: './inventory/dashboard/google-server/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: { ...inventoryEnv, NODE_ENV: 'production' },
|
|
||||||
max_memory_restart: '300M',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'typeform-server',
|
|
||||||
script: './inventory/dashboard/typeform-server/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: { ...inventoryEnv, NODE_ENV: 'production' },
|
|
||||||
max_memory_restart: '300M',
|
|
||||||
},
|
|
||||||
// PHASE 6.10: lt-wordlist-api now loads ADD_WORD_TOKEN from /opt/lt-wordlist-api/.env
|
|
||||||
// (no longer hardcoded here). Rotate that token's value when applying this change.
|
|
||||||
{
|
|
||||||
name: 'lt-wordlist-api',
|
|
||||||
script: '/opt/lt-wordlist-api/server.js',
|
|
||||||
cwd: '/opt/lt-wordlist-api',
|
|
||||||
env: { NODE_ENV: 'production' },
|
|
||||||
max_memory_restart: '200M',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'acot-phone-server',
|
|
||||||
script: './inventory/acot-phone/server.js',
|
|
||||||
cwd: '/var/www',
|
|
||||||
env: { ...inventoryEnv, NODE_ENV: 'production' },
|
|
||||||
max_memory_restart: '300M',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import axios from "axios";
|
import { apiClient } from "@/utils/apiClient";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||||
@@ -15,7 +15,7 @@ const AcotTest = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const response = await axios.get("/api/acot/test/test-connection");
|
const response = await apiClient.get("/api/acot/test/test-connection");
|
||||||
setConnectionStatus(response.data);
|
setConnectionStatus(response.data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.response?.data?.error || err.message);
|
setError(err.response?.data?.error || err.message);
|
||||||
@@ -29,7 +29,7 @@ const AcotTest = () => {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const response = await axios.get("/api/acot/test/order-count");
|
const response = await apiClient.get("/api/acot/test/order-count");
|
||||||
setData(response.data.data);
|
setData(response.data.data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.response?.data?.error || err.message);
|
setError(err.response?.data?.error || err.message);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
@@ -79,7 +80,7 @@ export const AnalyticsDashboard = () => {
|
|||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await apiFetch(
|
||||||
`/api/dashboard-analytics/metrics?startDate=${timeRange}daysAgo`,
|
`/api/dashboard-analytics/metrics?startDate=${timeRange}daysAgo`,
|
||||||
{
|
{
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect, useCallback, useMemo } from "react";
|
import React, { useState, useEffect, useCallback, useMemo } from "react";
|
||||||
import axios from "axios";
|
import { apiClient } from "@/utils/apiClient";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
@@ -1081,7 +1081,7 @@ const EventFeed = ({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await axios.get("/api/klaviyo/events/feed", {
|
const response = await apiClient.get("/api/klaviyo/events/feed", {
|
||||||
params: {
|
params: {
|
||||||
timeRange: "today",
|
timeRange: "today",
|
||||||
metricIds: JSON.stringify(metrics),
|
metricIds: JSON.stringify(metrics),
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import {
|
import {
|
||||||
Tooltip,
|
Tooltip,
|
||||||
@@ -143,7 +144,7 @@ const KlaviyoCampaigns = ({ className }) => {
|
|||||||
const fetchCampaigns = async () => {
|
const fetchCampaigns = async () => {
|
||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
const response = await fetch(
|
const response = await apiFetch(
|
||||||
`/api/klaviyo/reporting/campaigns/${selectedTimeRange}`
|
`/api/klaviyo/reporting/campaigns/${selectedTimeRange}`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
@@ -263,8 +264,8 @@ const MetaCampaigns = () => {
|
|||||||
const { since, until } = computeDateRange(timeframe);
|
const { since, until } = computeDateRange(timeframe);
|
||||||
|
|
||||||
const [campaignData, accountInsights] = await Promise.all([
|
const [campaignData, accountInsights] = await Promise.all([
|
||||||
fetch(`/api/meta/campaigns?since=${since}&until=${until}`),
|
apiFetch(`/api/meta/campaigns?since=${since}&until=${until}`),
|
||||||
fetch(`/api/meta/account-insights?since=${since}&until=${until}`)
|
apiFetch(`/api/meta/account-insights?since=${since}&until=${until}`)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const [campaignsJson, accountJson] = await Promise.all([
|
const [campaignsJson, accountJson] = await Promise.all([
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect, useRef } from "react";
|
import React, { useState, useEffect, useRef } from "react";
|
||||||
import axios from "axios";
|
import { apiClient } from "@/utils/apiClient";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
@@ -325,7 +325,7 @@ const MiniEventFeed = ({
|
|||||||
const { data: events = [], isLoading: loading, error } = useQuery({
|
const { data: events = [], isLoading: loading, error } = useQuery({
|
||||||
queryKey: ["mini-event-feed", selectedMetrics],
|
queryKey: ["mini-event-feed", selectedMetrics],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await axios.get("/api/klaviyo/events/feed", {
|
const response = await apiClient.get("/api/klaviyo/events/feed", {
|
||||||
params: {
|
params: {
|
||||||
timeRange: "today",
|
timeRange: "today",
|
||||||
metricIds: JSON.stringify(selectedMetrics),
|
metricIds: JSON.stringify(selectedMetrics),
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import {
|
import {
|
||||||
BarChart,
|
BarChart,
|
||||||
@@ -38,7 +39,7 @@ const MiniRealtimeAnalytics = () => {
|
|||||||
const fetchBasicData = async () => {
|
const fetchBasicData = async () => {
|
||||||
if (isPaused) return;
|
if (isPaused) return;
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/dashboard-analytics/realtime/basic", {
|
const response = await apiFetch("/api/dashboard-analytics/realtime/basic", {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import React, { useState, useEffect, useCallback } from "react";
|
import React, { useState, useEffect, useCallback } from "react";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
import { acotService } from "@/services/dashboard/acotService";
|
import { acotService } from "@/services/dashboard/acotService";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
@@ -79,7 +80,7 @@ const MiniStatCards = ({
|
|||||||
const { data: realtimeData = { last30MinUsers: 0, last5MinUsers: 0 }, isLoading: realtimeLoading } = useQuery({
|
const { data: realtimeData = { last30MinUsers: 0, last5MinUsers: 0 }, isLoading: realtimeLoading } = useQuery({
|
||||||
queryKey: ["mini-realtime-users"],
|
queryKey: ["mini-realtime-users"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await fetch("/api/dashboard-analytics/realtime/basic", {
|
const response = await apiFetch("/api/dashboard-analytics/realtime/basic", {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error("Failed to fetch realtime");
|
if (!response.ok) throw new Error("Failed to fetch realtime");
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import {
|
import {
|
||||||
BarChart,
|
BarChart,
|
||||||
@@ -268,7 +269,7 @@ export const RealtimeAnalytics = () => {
|
|||||||
const fetchBasicData = async () => {
|
const fetchBasicData = async () => {
|
||||||
if (isPaused) return;
|
if (isPaused) return;
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/dashboard-analytics/realtime/basic", {
|
const response = await apiFetch("/api/dashboard-analytics/realtime/basic", {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -298,7 +299,7 @@ export const RealtimeAnalytics = () => {
|
|||||||
const fetchDetailedData = async () => {
|
const fetchDetailedData = async () => {
|
||||||
if (isPaused) return;
|
if (isPaused) return;
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/dashboard-analytics/realtime/detailed", {
|
const response = await apiFetch("/api/dashboard-analytics/realtime/detailed", {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import axios from "axios";
|
import { apiClient } from "@/utils/apiClient";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
@@ -191,7 +191,7 @@ const TypeformDashboard = () => {
|
|||||||
const params = { page_size: 1000 };
|
const params = { page_size: 1000 };
|
||||||
if (before) params.before = before;
|
if (before) params.before = before;
|
||||||
|
|
||||||
const response = await axios.get(
|
const response = await apiClient.get(
|
||||||
`/api/typeform/forms/${formId}/responses`,
|
`/api/typeform/forms/${formId}/responses`,
|
||||||
{ params }
|
{ params }
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import {
|
import {
|
||||||
@@ -81,7 +82,7 @@ export const UserBehaviorDashboard = () => {
|
|||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await apiFetch(
|
||||||
`/api/dashboard-analytics/user-behavior?timeRange=${timeRange}`,
|
`/api/dashboard-analytics/user-behavior?timeRange=${timeRange}`,
|
||||||
{
|
{
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
|
|||||||
@@ -9,6 +9,27 @@ const acotApi = axios.create({
|
|||||||
timeout: 30000,
|
timeout: 30000,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Mirror utils/apiClient's auth plumbing on this private instance:
|
||||||
|
// inject Bearer token from localStorage and bounce to /login on 401.
|
||||||
|
// Without this, every acot call 401s at Caddy forward_auth (Phase 6.1).
|
||||||
|
acotApi.interceptors.request.use((config) => {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (token && !config.headers.has('Authorization')) {
|
||||||
|
config.headers.set('Authorization', `Bearer ${token}`);
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
});
|
||||||
|
|
||||||
|
acotApi.interceptors.response.use(
|
||||||
|
(response) => response,
|
||||||
|
(error) => {
|
||||||
|
if (error?.response?.status === 401 && localStorage.getItem('token')) {
|
||||||
|
window.dispatchEvent(new Event('auth:logout'));
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Request deduplication cache
|
// Request deduplication cache
|
||||||
const requestCache = new Map();
|
const requestCache = new Map();
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user