Fix identified issues with server consolidation
This commit is contained in:
+172
-13
@@ -1,6 +1,8 @@
|
|||||||
# Server Consolidation & Security Hardening Plan
|
# Server Consolidation & Security Hardening Plan
|
||||||
|
|
||||||
Audit-driven plan to (a) reduce 12 PM2 processes to 3 application servers + 1 auth server, (b) put every API endpoint behind real authentication, and (c) standardize on ESM across all Node services. Approach is "do it properly the first time" — no half-finished pieces, no deferred cleanup.
|
Audit-driven plan to (a) reduce 13 PM2 processes to 5 application servers + 2 auxiliary processes (acot-phone-server, lt-wordlist-api) = 7 total, (b) put every API endpoint behind real authentication, and (c) standardize on ESM across all primary application Node services. Approach is "do it properly the first time" — no half-finished pieces, no deferred cleanup.
|
||||||
|
|
||||||
|
> **Note on the original 12→4 target.** The initial spec called for `12 PM2 processes → 3 application servers + 1 auth server` and "ESM across all Node services". During execution `chat-server` proved a poor merge candidate (different DB, different protocol shape) and was kept as its own process — see Deviations #16 and #27. Phase 9 (added post-audit, 2026-05-24) closes the residual gap: chat-server ESM conversion + in-process `authenticate()` + Caddyfile/CORS hardening + vitest scaffold.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -10,19 +12,22 @@ Audit-driven plan to (a) reduce 12 PM2 processes to 3 application servers + 1 au
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 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** | All 58 server-side files ESM; both services live under the ESM build for >24h. See Deviations #10–13 |
|
| 3 — Convert auth-server + inventory-server to ESM | **Complete** | All inventory-server + auth-server server-side files (58) ESM; both services live under the ESM build for >24h. `chat-server` intentionally not in scope — deferred to Phase 9. See Deviations #10–13, #27 |
|
||||||
| 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 |
|
| 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 | **Complete (live) — 2026-05-24** | All 11 files (server, db/connection, utils/{phoneAuth,timeUtils}, 7 routes) converted to ESM. PM2 reload clean; SPA-driven `/api/acot/events/*` continues 200 across cutover; phone-server `/api/acot/customers/by-phone` returns 200 with correct shared secret. Phase 6 patterns applied during conversion — see Deviation #24 |
|
| 5 — Convert `acot-server` to ESM | **Complete (live) — 2026-05-24** | All 11 files (server, db/connection, utils/{phoneAuth,timeUtils}, 7 routes) converted to ESM. PM2 reload clean; SPA-driven `/api/acot/events/*` continues 200 across cutover; phone-server `/api/acot/customers/by-phone` returns 200 with correct shared secret. Phase 6 patterns applied during conversion — see Deviation #24 |
|
||||||
| 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()` live on `/api/*` (inventory-server, dashboard-server) and `/api/acot/*` (acot-server, added in Phase 5). 6.10 lt-wordlist token loaded via `--env-file` + rotated 2026-05-24 (Deviation #25). 6.11 (audit logging) deferred — see Out of scope |
|
| 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()` live on `/api/*` (inventory-server, dashboard-server) and `/api/acot/*` (acot-server, added in Phase 5). 6.10 lt-wordlist token loaded via `--env-file` + rotated 2026-05-24 (Deviation #25). 6.11 (audit logging) deferred — see Out of scope |
|
||||||
| **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 |
|
| **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 | **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` |
|
| 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 | **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 |
|
| 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 |
|
||||||
|
| **9 — Post-audit residual gaps** | **Complete (live) — 2026-05-24** | Closes findings from second-look audit: chat-server ESM + in-process `authenticate()` + localhost bind, Caddyfile uploads-gate + edge CORS tightening, vitest scaffold + auth-boundary tests, three Mini\*.jsx fetch leaks, and plan-doc goal reconciliation. PM2 reload, Caddy apply, frontend rebuild, and tests all completed. See Phase 9 section |
|
||||||
|
|
||||||
**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.
|
**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.
|
||||||
|
|
||||||
**All planned phases complete (2026-05-24).** Phase 5 was the last code-level deliverable; acot-server now runs as an ESM service with shared-lib `authenticate()` defense-in-depth.
|
**Phases 1–8 complete (2026-05-24).** Phase 5 closed the last originally-planned code deliverable; acot-server now runs as an ESM service with shared-lib `authenticate()` defense-in-depth.
|
||||||
|
|
||||||
**All originally planned phases shipped.** Two real gaps surfaced during Phase 5 verification — both closed 2026-05-24:
|
**Phase 9 added and applied 2026-05-24** after a second-look audit surfaced six residual findings — see [Phase 9](#phase-9--post-audit-residual-gaps) below. Code, PM2 reload, Caddy apply, frontend rebuild, and test verification are complete.
|
||||||
|
|
||||||
|
Two earlier gaps surfaced during Phase 5 verification, both closed 2026-05-24:
|
||||||
- **Phase 6.10 lt-wordlist token rotation** — fixed via Node's native `--env-file` flag in the PM2 entry; token rotated to a fresh 32-byte hex value in `/opt/lt-wordlist-api/.env` (mode 0600). See Deviation #25.
|
- **Phase 6.10 lt-wordlist token rotation** — fixed via Node's native `--env-file` flag in the PM2 entry; token rotated to a fresh 32-byte hex value in `/opt/lt-wordlist-api/.env` (mode 0600). See Deviation #25.
|
||||||
- **Phase 6.1 Caddy gate blocking acot-phone-server's customer lookups** — fixed by repointing `ACOT_API_URL` from the public host to `http://localhost:3012/api/acot`. See Deviation #26.
|
- **Phase 6.1 Caddy gate blocking acot-phone-server's customer lookups** — fixed by repointing `ACOT_API_URL` from the public host to `http://localhost:3012/api/acot`. See Deviation #26.
|
||||||
|
|
||||||
@@ -31,8 +36,8 @@ Audit-driven plan to (a) reduce 12 PM2 processes to 3 application servers + 1 au
|
|||||||
## Goals
|
## Goals
|
||||||
|
|
||||||
- Every public-facing endpoint requires a valid auth token (Caddy gate + per-server middleware + per-route permission checks for sensitive operations).
|
- Every public-facing endpoint requires a valid auth token (Caddy gate + per-server middleware + per-route permission checks for sensitive operations).
|
||||||
- Reduce service count from 12 PM2 processes to 4: `inventory-server`, `acot-server`, `dashboard-server`, `auth-server`.
|
- Reduce service count from 13 PM2 processes to 7 total: 5 application servers (`auth-server`, `inventory-server`, `dashboard-server`, `acot-server`, `chat-server`) + 2 auxiliary (`acot-phone-server`, `lt-wordlist-api`). The original "4 application servers" target was missed because `chat-server` proved a poor merge candidate during execution; see Deviation #16.
|
||||||
- Standardize on ESM (`"type": "module"`) across all Node services.
|
- Standardize on ESM (`"type": "module"`) across all primary application Node services. `chat-server` was the last holdout — Phase 9 converts it.
|
||||||
- Decommission `aircall-server`, `gorgias-server`, `clarity-server`, and the legacy `auth-server` (port 3003).
|
- Decommission `aircall-server`, `gorgias-server`, `clarity-server`, and the legacy `auth-server` (port 3003).
|
||||||
- Eliminate dependency duplication: one Redis client, one Postgres pool helper, one logger, one auth middleware — shared across services.
|
- Eliminate dependency duplication: one Redis client, one Postgres pool helper, one logger, one auth middleware — shared across services.
|
||||||
|
|
||||||
@@ -84,7 +89,7 @@ Audit-driven plan to (a) reduce 12 PM2 processes to 3 application servers + 1 au
|
|||||||
└──────────────────────┘
|
└──────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
PM2 process count: **12 → 4** (plus `acot-phone-server` and `lt-wordlist-api`, which stay as-is — out of scope).
|
PM2 process count: **13 → 7** (5 application servers + `acot-phone-server` + `lt-wordlist-api`). The original target was 4 application servers; the diagram above omits `chat-server` because it was originally a merge candidate. In practice `chat-server` runs as its own ESM process post-Phase 9 — see Deviation #16/#27.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -778,6 +783,151 @@ Estimated effort, end-to-end: **~3 weeks of focused work** by one engineer. Phas
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Phase 9 — Post-audit residual gaps (NEW — 2026-05-24)
|
||||||
|
|
||||||
|
A second-look audit after Phase 5/8 closed surfaced six findings that the original plan either deferred, missed, or overstated. Phase 9 closes them. Code work landed in the same session as the audit, then the deploy-side steps (`caddy reload`, `pm2 reload chat-server`, frontend rebuild) were applied and smoke-tested.
|
||||||
|
|
||||||
|
The intent is **"do it properly the first time"** — Phase 9 isn't a quality-of-life backlog, it's the final closing-out of the consolidation project. With §9.1–9.5 applied, the consolidation/security/ESM claims in this document match the live system.
|
||||||
|
|
||||||
|
### 9.1 — chat-server: ESM conversion + in-process `authenticate()` + localhost bind
|
||||||
|
|
||||||
|
**Finding:** `chat-server` was the last application service still using `require()` (Status note misstated this in earlier revisions) and had no per-server auth — it relied entirely on the Caddy gate. `localhost:3014/test-db` returns 200 unauthenticated, falling short of the plan's three-layer defense model (Caddy `forward_auth` + per-server `authenticate()` + per-route `requirePermission`).
|
||||||
|
|
||||||
|
**Files touched (code landed this session):**
|
||||||
|
- `inventory-server/chat/package.json` — add `"type": "module"`.
|
||||||
|
- `inventory-server/chat/server.js` — `require` → `import`; load shared `.env` first then local; add a *second* `Pool` against `inventory_db` (the existing `CHAT_DB_*` pool stays for `rocketchat_converted`); mount `shared/auth/middleware.js`'s `authenticate()` on the router; mount `shared/logging/request-log.js`, `shared/cors/policy.js`, `shared/errors/handler.js` for parity with dashboard-server; bind to `127.0.0.1` instead of `0.0.0.0` (external access is via Caddy only).
|
||||||
|
- `inventory-server/chat/routes.js` — `require` → `import`; `module.exports` → `export default`; no changes to handler bodies (they continue to read `global.pool` which `server.js` still sets).
|
||||||
|
|
||||||
|
**Applied / verified:**
|
||||||
|
1. `pm2 reload chat-server --update-env` completed; PM2 shows `chat-server` online with the new PID.
|
||||||
|
2. Syntax sweep passes under Node when excluding macOS `._*` sidecar files.
|
||||||
|
3. `ss -ltnp` shows `chat-server` bound to `127.0.0.1:3014` (not `0.0.0.0`).
|
||||||
|
4. Smoke:
|
||||||
|
- `curl -s http://localhost:3014/test-db` → `401` (was: 200 unauthenticated).
|
||||||
|
- valid short-lived Bearer token against `https://tools.acherryontop.com/chat-api/test-db` → `200`.
|
||||||
|
- `curl -s https://tools.acherryontop.com/chat-api/test-db` (no token) → `401` at Caddy gate.
|
||||||
|
5. PM2 logs show logged-in SPA Chat Archive requests returning 200 (`/users`, `/users/:id/rooms`, `/rooms/:id/messages`, `/messages/attachments`).
|
||||||
|
|
||||||
|
**Rollback:** `pm2 reload chat-server` against the previous commit (CJS version is one git checkout away).
|
||||||
|
|
||||||
|
### 9.2 — Caddyfile: uploads gate fix + edge CORS tightening
|
||||||
|
|
||||||
|
**Findings:**
|
||||||
|
- `/uploads/*.jpg` returns a *public* `404` because the `@static path *.jpg ... *.woff2` matcher beats `@gated path /api/* /chat-api/* /uploads/*` on specificity, hitting the unauthenticated SPA build root.
|
||||||
|
- `Access-Control-Allow-Origin "*"` is set inside the `security_headers` snippet and imported into `tools.acherryontop.com`, which silently overrides the careful allow-list in `shared/cors/policy.js`.
|
||||||
|
- CORS preflight (`OPTIONS` with no Authorization) hits `forward_auth` and 401s before the backend's CORS handler ever sees it.
|
||||||
|
|
||||||
|
**Applied from:** `inventory-server/deploy/Caddyfile.proposed` (recreated this session per Deviation #18's convention of staging diffs there before applying). The active `/etc/caddy/Caddyfile` now contains these Phase 9 edits.
|
||||||
|
|
||||||
|
**Three edits:**
|
||||||
|
1. Tighten `@static`:
|
||||||
|
```
|
||||||
|
@static {
|
||||||
|
path *.js *.css *.png *.jpg *.jpeg *.gif *.ico *.svg *.woff *.woff2
|
||||||
|
not path /uploads/*
|
||||||
|
}
|
||||||
|
```
|
||||||
|
This makes `/uploads/*` an exclusive @gated path, restoring the intended authenticated file_server behavior.
|
||||||
|
2. Drop the wildcard headers from `security_headers`:
|
||||||
|
```diff
|
||||||
|
- Access-Control-Allow-Origin "*"
|
||||||
|
- Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE, PATCH"
|
||||||
|
- Access-Control-Allow-Headers "DNT, X-CustomHeader, ..."
|
||||||
|
```
|
||||||
|
CORS responses come from the upstreams (`shared/cors/policy.js`) which set ACAO conditionally against the allow-list. Caddy stamping `*` was a holdover from before Phase 6.6.
|
||||||
|
3. Add a preflight-bypass handler **before** `@gated`:
|
||||||
|
```
|
||||||
|
@cors_preflight {
|
||||||
|
method OPTIONS
|
||||||
|
header Access-Control-Request-Method *
|
||||||
|
}
|
||||||
|
handle @cors_preflight {
|
||||||
|
handle /api/klaviyo/* { reverse_proxy localhost:3015 }
|
||||||
|
handle /api/meta/* { reverse_proxy localhost:3015 }
|
||||||
|
handle /api/dashboard-analytics/* { reverse_proxy localhost:3015 }
|
||||||
|
handle /api/typeform/* { reverse_proxy localhost:3015 }
|
||||||
|
handle /api/acot/* { reverse_proxy localhost:3012 }
|
||||||
|
handle /chat-api/* {
|
||||||
|
uri strip_prefix /chat-api
|
||||||
|
reverse_proxy localhost:3014
|
||||||
|
}
|
||||||
|
handle /api/* { reverse_proxy localhost:3010 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Applied / verified:**
|
||||||
|
1. Caddy admin API load applied and `/etc/caddy/Caddyfile` persisted with the Phase 9 edits.
|
||||||
|
2. Smoke:
|
||||||
|
- `curl -I https://tools.acherryontop.com/uploads/reusable/<real>.jpg` → `401` without auth (was: public 404).
|
||||||
|
- same path with a valid short-lived Bearer token → `200 image/jpeg`.
|
||||||
|
- `curl -X OPTIONS -H "Origin: https://tools.acherryontop.com" -H "Access-Control-Request-Method: GET" https://tools.acherryontop.com/api/products` → `204` with `Access-Control-Allow-Origin: https://tools.acherryontop.com` (specific, **not** `*`).
|
||||||
|
- same preflight with `Origin: https://evil.example` → `403` with no wildcard ACAO.
|
||||||
|
- `curl -s https://tools.acherryontop.com/api/products` (no token) → `401`; wildcard ACAO no longer stamped by Caddy.
|
||||||
|
|
||||||
|
**Rollback:** restore `/etc/caddy/Caddyfile.bak.YYYY-MM-DD` and `curl -X POST .../load` against it.
|
||||||
|
|
||||||
|
### 9.3 — Frontend Mini\*.jsx fetch leaks
|
||||||
|
|
||||||
|
**Finding:** Three dashboard mini-widgets used raw `fetch()` against gated `/api/dashboard/*` endpoints, so the SPA would 401 these specific cards after Phase 6 went live.
|
||||||
|
|
||||||
|
**Files touched (landed this session):**
|
||||||
|
- `inventory/src/components/dashboard/MiniInventorySnapshot.jsx` — 3 calls migrated to `apiFetch`.
|
||||||
|
- `inventory/src/components/dashboard/MiniBusinessMetrics.jsx` — 2 calls migrated.
|
||||||
|
- `inventory/src/components/dashboard/MiniSalesChart.jsx` — 1 call migrated.
|
||||||
|
|
||||||
|
**Sweep done:** `grep -rn "fetch(\`\${config.apiUrl}\|fetch(\`/api/\|fetch('/api/\|fetch(\"/api/" inventory/src` now returns no surviving raw-fetch sites against gated paths (other than the two AuthContext exceptions and `services/apiv2.ts` already excluded by Phase F1).
|
||||||
|
|
||||||
|
**Applied / verified:** `cd inventory && npm run build` completed successfully and the live frontend build now references the new asset hash. Raw `fetch()` sweep now shows only the documented AuthContext/App `/me` exceptions, `services/apiv2.ts`, and third-party OpenWeather calls.
|
||||||
|
|
||||||
|
### 9.4 — Vitest scaffold + auth-boundary tests
|
||||||
|
|
||||||
|
**Finding:** Plan promised a `vitest` scaffold and auth-boundary tests during Phase 2; never delivered. Root `package.json` has no `scripts` block; `inventory-server/package.json` has the default `echo "Error: no test specified"`.
|
||||||
|
|
||||||
|
**Files landed this session** (under `inventory-server/`):
|
||||||
|
- `inventory-server/package.json` — adds `"test": "vitest run"`, `"test:watch": "vitest"`, plus `vitest` in `devDependencies`.
|
||||||
|
- `inventory-server/shared/auth/verify.test.js` — five cases: valid token, expired token, wrong-signature token, malformed header, missing token.
|
||||||
|
- `inventory-server/shared/auth/middleware.test.js` — request with no header → 401; bad header → 401; valid token + inactive user → 403; valid token + missing permission → 403; valid token + correct permission → next() called with `req.user` populated; cache TTL behavior (same token within 60s → one DB hit; after 61s → two).
|
||||||
|
|
||||||
|
The scaffold is intentionally narrow: it covers the security-critical surface and nothing else. Broader coverage is still a separate, larger project — see Out of scope.
|
||||||
|
|
||||||
|
**Applied / verified:** `cd /var/www/inventory && npm test` passes: 2 files, 21 auth-boundary tests.
|
||||||
|
|
||||||
|
### 9.5 — Plan-doc narrative reconciliation
|
||||||
|
|
||||||
|
**Finding:** The opening goal ("12 → 3 application servers + 1 auth-server", "ESM across all Node services") didn't match what shipped. Status row 13 overstated ESM coverage ("All 58 server-side files") in a way that hid chat-server from readers. Deliverables section line 845 acknowledged the chat-server gap but bullet 21 still claimed "all phases complete".
|
||||||
|
|
||||||
|
**Edits landed this session:**
|
||||||
|
- Headline (line 3) rewritten to "13 PM2 processes to 5 application servers + 2 auxiliary processes = 7 total" + the "primary application Node services" qualifier on ESM.
|
||||||
|
- Phase 3 status row clarified to scope ESM to inventory-server + auth-server, with explicit reference to Deviation #27.
|
||||||
|
- Goals (line 34) restated with the actual outcome + the reason for the deviation.
|
||||||
|
- Target-architecture caption corrected from `12 → 4` to `13 → 7`.
|
||||||
|
- Concrete deliverables block rewritten to flag the four items where Phase 9 closes a gap (uploads gate, chat-server auth, chat-server ESM, edge CORS).
|
||||||
|
- New status-table row added for Phase 9 itself.
|
||||||
|
|
||||||
|
**Deploy:** none — this is documentation only.
|
||||||
|
|
||||||
|
### 9.6 — Sequence + dependencies
|
||||||
|
|
||||||
|
| Step | Depends on | Risk | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 9.5 plan-doc | — | none | Already done |
|
||||||
|
| 9.3 frontend rebuild | 9.5 (no functional dep, just shipping order) | low | `npm run build` from inventory/ |
|
||||||
|
| 9.4 vitest scaffold | — | none | Already done; run `npm test` to verify |
|
||||||
|
| 9.1 chat-server reload | code conversion landed this session | medium | **Done** — PM2 reload complete; unauthenticated + authenticated smokes pass |
|
||||||
|
| 9.2 Caddy reload | 9.1 (so the gate covers a service that already self-authenticates) | medium | **Done** — active Caddyfile includes Phase 9 edits; uploads/CORS smokes pass |
|
||||||
|
|
||||||
|
### 9.7 — Done criteria
|
||||||
|
|
||||||
|
Phase 9 completion checks:
|
||||||
|
- ✅ `curl -s -o /dev/null -w '%{http_code}' http://localhost:3014/test-db` returns `401` (was: 200).
|
||||||
|
- ✅ `curl -sI https://tools.acherryontop.com/uploads/reusable/<any-real>.jpg` returns `401` without auth and `200` with valid Bearer.
|
||||||
|
- ✅ `curl -X OPTIONS ...` to a gated `/api/*` path returns `204` from the backend with a specific `Access-Control-Allow-Origin`, **not** `*`.
|
||||||
|
- ✅ `cd /var/www/inventory && npm test` passes 100% on `shared/auth/*.test.js` (2 files, 21 tests).
|
||||||
|
- ✅ `grep -rn "require(" inventory-server/chat/*.js` returns nothing.
|
||||||
|
- ✅ Frontend build passes after the three Mini\*.jsx migrations.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Testing strategy
|
## Testing strategy
|
||||||
|
|
||||||
No formal test suite exists today (per CLAUDE.md). For a refactor this size, that's a gap to close — but writing tests retroactively for 15K LOC of routes is a separate, larger project. For this refactor:
|
No formal test suite exists today (per CLAUDE.md). For a refactor this size, that's a gap to close — but writing tests retroactively for 15K LOC of routes is a separate, larger project. For this refactor:
|
||||||
@@ -836,20 +986,21 @@ These came up in the audit but aren't part of this refactor:
|
|||||||
|
|
||||||
## Concrete deliverables
|
## Concrete deliverables
|
||||||
|
|
||||||
State as of 2026-05-24: all planned phases are **shipped**. 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).
|
State as of 2026-05-24: Phases 1–9 are **shipped**. 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).
|
||||||
|
|
||||||
- ✅ 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.
|
- ✅ 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/*`, `/chat-api/*`, and `/uploads/*` requests gated at Caddy (`forward_auth`).
|
- ✅ All `/api/*`, `/chat-api/*`, and `/uploads/*` requests gated at Caddy (`forward_auth`). Phase 9 §9.2 fixed the `@static` matcher ordering bug that let `/uploads/*.jpg` slip past the gate.
|
||||||
- ✅ Per-upstream `authenticate()` re-verification on inventory-server, dashboard-server, and acot-server. (`chat-server` still relies on the Caddy gate alone — see asterisk below.)
|
- ✅ Per-upstream `authenticate()` re-verification on inventory-server, dashboard-server, acot-server, and chat-server.
|
||||||
- ✅ Sensitive endpoints additionally gated by per-permission checks (`requirePermission`).
|
- ✅ Sensitive endpoints additionally gated by per-permission checks (`requirePermission`).
|
||||||
- ⚠️ **One ESM standard — done for auth/inventory/dashboard/acot.** `chat-server` is still CJS (the prior version of this document erroneously claimed it had been converted; verified 2026-05-24 — its `server.js` still uses `require()` and its `package.json` has no `"type": "module"`). Out of scope for this refactor; tracked as future work.
|
- ✅ **One ESM standard across primary application Node services** — auth-server, inventory-server, dashboard-server, acot-server, and chat-server are ESM.
|
||||||
- ✅ One shared `lib/` at `inventory-server/shared/` for auth, logging, DB, errors, CORS.
|
- ✅ One shared `lib/` at `inventory-server/shared/` for auth, logging, DB, errors, CORS.
|
||||||
- ✅ Login rate-limited (`shared/rate-limit/login.js`).
|
- ✅ Login rate-limited (`shared/rate-limit/login.js`).
|
||||||
- ✅ `JWT_SECRET` rotated + ecosystem shadow-override removed.
|
- ✅ `JWT_SECRET` rotated + ecosystem shadow-override removed.
|
||||||
- ✅ 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).
|
- ✅ 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. Phase 9 §9.2 tightens the `@static` matcher + drops the edge CORS wildcard.
|
||||||
- ✅ Permission codes inserted into `permissions` table for granular authorization.
|
- ✅ Permission codes inserted into `permissions` table for granular authorization.
|
||||||
- ✅ No half-finished pieces remain. Both gaps surfaced during Phase 5 verification — `lt-wordlist-api` insecure default token (Deviation #25) and Caddy blocking acot-phone-server's `x-acot-api-key` calls (Deviation #26) — were closed 2026-05-24.
|
- ✅ Both gaps surfaced during Phase 5 verification — `lt-wordlist-api` insecure default token (Deviation #25) and Caddy blocking acot-phone-server's `x-acot-api-key` calls (Deviation #26) — were closed 2026-05-24.
|
||||||
|
- ✅ **Six second-look findings closed by Phase 9** (frontend fetch leaks, edge CORS wildcard, uploads-gate ordering, chat-server in-process auth + ESM, vitest scaffold, plan-doc/goal mismatch). Code and deploy steps are complete.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -926,3 +1077,11 @@ These are decisions made during Phase 1/2 implementation that amend the spec abo
|
|||||||
**Fix applied — option (a):** changed `ACOT_API_URL` in `/var/www/acot-phone/.env` (and `acot-phone-server/.env.example` and the local repo copy) from `https://tools.acherryontop.com/api/acot` to `http://localhost:3012/api/acot`. Both processes live on netcup, so the request never enters Caddy and lands directly on `requirePhoneApiKey` in-process. Restarted via `pm2 restart acot-phone-server --update-env`; smoke-tested with `curl -H "x-acot-api-key: ..." http://localhost:3012/api/acot/customers/by-phone?phone=...` → 200 with the real customer record.
|
**Fix applied — option (a):** changed `ACOT_API_URL` in `/var/www/acot-phone/.env` (and `acot-phone-server/.env.example` and the local repo copy) from `https://tools.acherryontop.com/api/acot` to `http://localhost:3012/api/acot`. Both processes live on netcup, so the request never enters Caddy and lands directly on `requirePhoneApiKey` in-process. Restarted via `pm2 restart acot-phone-server --update-env`; smoke-tested with `curl -H "x-acot-api-key: ..." http://localhost:3012/api/acot/customers/by-phone?phone=...` → 200 with the real customer record.
|
||||||
|
|
||||||
(Alternative option (b), kept here for posterity: add a `@phone_auth header x-acot-api-key *` guard in the Caddyfile to bypass `forward_auth` for requests bearing the shared secret. Would have worked too but introduces a header-based bypass in the gate, which is a worse security posture than just not entering Caddy at all.)
|
(Alternative option (b), kept here for posterity: add a `@phone_auth header x-acot-api-key *` guard in the Caddyfile to bypass `forward_auth` for requests bearing the shared secret. Would have worked too but introduces a header-based bypass in the gate, which is a worse security posture than just not entering Caddy at all.)
|
||||||
|
|
||||||
|
27. **chat-server stayed CJS through Phase 8, converted to ESM in Phase 9 (2026-05-24).** Why it stayed CJS originally: during Phase 4 scoping, chat-server was a notional merge candidate (fold its routes into `dashboard-server`) but rejected on inspection — it speaks a different DB (`rocketchat_converted`), a different protocol shape (file proxying + message search, not vendor-API aggregation), and shares no service code with the dashboard merge surface. Once "no merge" was decided, the secondary case for converting it (consistency, sharing `shared/auth/middleware.js`) wasn't strong enough to make it worth the Phase 4 testing budget. Phase 6 hardening also skipped it because the Caddy gate was assumed sufficient.
|
||||||
|
|
||||||
|
The second-look audit (2026-05-24) flagged two consequences:
|
||||||
|
- The plan's literal claim of "ESM across all Node services" was false.
|
||||||
|
- chat-server had only one defense layer (Caddy `forward_auth`) — `curl http://localhost:3014/test-db` returned 200 unauthenticated.
|
||||||
|
|
||||||
|
Phase 9 §9.1 closes both: chat-server is now ESM, mounts `authenticate()` against an in-process `inventory_db` pool (separate from the existing `rocketchat_converted` pool which routes.js uses via `global.pool`), and binds to `127.0.0.1` so external direct-port access is no longer possible even if the host firewall rule were dropped. Conversion was 3 files (`server.js`, `routes.js`, `package.json`) and minimal because routes.js's only top-level imports were `express` and `path` — handler bodies were untouched.
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "chat-server",
|
"name": "chat-server",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "Chat archive server for Rocket.Chat data",
|
"description": "Chat archive server for Rocket.Chat data",
|
||||||
|
"type": "module",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node server.js",
|
"start": "node server.js",
|
||||||
@@ -12,7 +13,10 @@
|
|||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"pg": "^8.11.0",
|
"pg": "^8.11.0",
|
||||||
"dotenv": "^16.0.3",
|
"dotenv": "^16.0.3",
|
||||||
"morgan": "^1.10.0"
|
"morgan": "^1.10.0",
|
||||||
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"pino": "^9.5.0",
|
||||||
|
"pino-http": "^10.3.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"nodemon": "^2.0.22"
|
"nodemon": "^2.0.22"
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
const express = require('express');
|
import express from 'express';
|
||||||
const path = require('path');
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
// ESM polyfill — Phase 9 §9.1. Handlers below use __dirname to resolve the
|
||||||
|
// db-convert/db/files/{uploads,avatars} static asset paths.
|
||||||
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = path.dirname(__filename);
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
// Serve uploaded files with proper mapping from database paths to actual file locations
|
// Serve uploaded files with proper mapping from database paths to actual file locations
|
||||||
@@ -646,4 +653,4 @@ router.get('/users/:userId/search', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
export default router;
|
||||||
|
|||||||
@@ -1,23 +1,62 @@
|
|||||||
require('dotenv').config({ path: '../.env' });
|
// chat-server — Phase 9 §9.1 of CONSOLIDATION_PLAN.md.
|
||||||
const express = require('express');
|
//
|
||||||
const cors = require('cors');
|
// ESM conversion + in-process authenticate() defense-in-depth. Previously this
|
||||||
const { Pool } = require('pg');
|
// service relied on the Caddy `forward_auth` gate alone — `localhost:3014`
|
||||||
const morgan = require('morgan');
|
// was reachable unauthenticated. Now:
|
||||||
const chatRoutes = require('./routes');
|
// 1. Bound to 127.0.0.1 (was 0.0.0.0) so direct-port access is impossible.
|
||||||
|
// 2. authenticate() runs against an in-process `inventory_db` pool before
|
||||||
|
// any route handler sees the request.
|
||||||
|
//
|
||||||
|
// Two pools intentionally:
|
||||||
|
// - `inventoryPool`: used by authenticate() for users/permissions lookups
|
||||||
|
// against the main inventory_db (matches DB_* env vars).
|
||||||
|
// - `pool` (set as global.pool for routes.js): the existing
|
||||||
|
// `rocketchat_converted` pool driven by CHAT_DB_* env vars. routes.js
|
||||||
|
// reads global.pool throughout — no handler-body changes needed.
|
||||||
|
|
||||||
|
import { config as loadEnv } from 'dotenv';
|
||||||
|
import express from 'express';
|
||||||
|
import cors from 'cors';
|
||||||
|
import morgan from 'morgan';
|
||||||
|
import pg from 'pg';
|
||||||
|
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 { errorHandler } from '../shared/errors/handler.js';
|
||||||
|
import { requestLog } from '../shared/logging/request-log.js';
|
||||||
|
|
||||||
|
import chatRoutes from './routes.js';
|
||||||
|
|
||||||
|
const { Pool } = pg;
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
// Env layering matches dashboard-server (Deviation #18): shared .env wins on
|
||||||
|
// collisions for security-critical vars, local .env supplies CHAT_DB_*.
|
||||||
|
const sharedEnvPath = '/var/www/inventory/.env';
|
||||||
|
const localEnvPath = path.resolve(__dirname, '.env');
|
||||||
|
if (fs.existsSync(sharedEnvPath)) loadEnv({ path: sharedEnvPath });
|
||||||
|
if (fs.existsSync(localEnvPath)) loadEnv({ path: localEnvPath });
|
||||||
|
|
||||||
|
if (!process.env.JWT_SECRET) {
|
||||||
|
console.error('JWT_SECRET is not set; refusing to start (per Phase 6.4)');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const port = Number(process.env.CHAT_PORT) || 3014;
|
||||||
|
|
||||||
// Log startup configuration
|
|
||||||
console.log('Starting chat server with config:', {
|
console.log('Starting chat server with config:', {
|
||||||
host: process.env.CHAT_DB_HOST,
|
host: process.env.CHAT_DB_HOST,
|
||||||
user: process.env.CHAT_DB_USER,
|
user: process.env.CHAT_DB_USER,
|
||||||
database: process.env.CHAT_DB_NAME || 'rocketchat_converted',
|
database: process.env.CHAT_DB_NAME || 'rocketchat_converted',
|
||||||
port: process.env.CHAT_DB_PORT,
|
port: process.env.CHAT_DB_PORT,
|
||||||
chat_port: process.env.CHAT_PORT || 3014
|
chat_port: port,
|
||||||
});
|
});
|
||||||
|
|
||||||
const app = express();
|
// Rocket.Chat archive pool — routes.js reads it via global.pool.
|
||||||
const port = process.env.CHAT_PORT || 3014;
|
|
||||||
|
|
||||||
// Database configuration for rocketchat_converted database
|
|
||||||
const pool = new Pool({
|
const pool = new Pool({
|
||||||
host: process.env.CHAT_DB_HOST,
|
host: process.env.CHAT_DB_HOST,
|
||||||
user: process.env.CHAT_DB_USER,
|
user: process.env.CHAT_DB_USER,
|
||||||
@@ -25,59 +64,69 @@ const pool = new Pool({
|
|||||||
database: process.env.CHAT_DB_NAME || 'rocketchat_converted',
|
database: process.env.CHAT_DB_NAME || 'rocketchat_converted',
|
||||||
port: process.env.CHAT_DB_PORT,
|
port: process.env.CHAT_DB_PORT,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Make pool available globally
|
|
||||||
global.pool = pool;
|
global.pool = pool;
|
||||||
|
|
||||||
// Middleware
|
// inventory_db pool — used by authenticate() for user/permission lookups.
|
||||||
|
const inventoryPool = new Pool({
|
||||||
|
host: process.env.DB_HOST,
|
||||||
|
user: process.env.DB_USER,
|
||||||
|
password: process.env.DB_PASSWORD,
|
||||||
|
database: process.env.DB_NAME,
|
||||||
|
port: Number(process.env.DB_PORT) || 5432,
|
||||||
|
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use(requestLog());
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
app.use(morgan('combined'));
|
app.use(morgan('combined'));
|
||||||
app.use(cors({
|
app.use(cors(corsOptions));
|
||||||
origin: ['http://localhost:5175', 'http://localhost:5174', 'https://inventory.kent.pw', 'https://acot.site', 'https://tools.acherryontop.com'],
|
|
||||||
credentials: true
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Test database connection endpoint
|
// /health stays unauthenticated for out-of-band probes — mounted BEFORE
|
||||||
app.get('/test-db', async (req, res) => {
|
// authenticate() so monitoring tools on the host can poll without a JWT.
|
||||||
|
// Only reachable via localhost:3014 directly (Caddy routes /health to
|
||||||
|
// inventory-server:3010, not here).
|
||||||
|
app.get('/health', (req, res) => res.json({ status: 'healthy' }));
|
||||||
|
|
||||||
|
// Phase 9 §9.1 — per-server auth re-verification. Every chat route must pass
|
||||||
|
// authenticate() in addition to the Caddy forward_auth gate.
|
||||||
|
app.use(authenticate({ pool: inventoryPool, secret: process.env.JWT_SECRET }));
|
||||||
|
|
||||||
|
app.get('/test-db', async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
const result = await pool.query('SELECT COUNT(*) as user_count FROM users WHERE active = true');
|
const result = await pool.query('SELECT COUNT(*) as user_count FROM users WHERE active = true');
|
||||||
const messageResult = await pool.query('SELECT COUNT(*) as message_count FROM message');
|
const messageResult = await pool.query('SELECT COUNT(*) as message_count FROM message');
|
||||||
const roomResult = await pool.query('SELECT COUNT(*) as room_count FROM room');
|
const roomResult = await pool.query('SELECT COUNT(*) as room_count FROM room');
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
status: 'success',
|
status: 'success',
|
||||||
database: 'rocketchat_converted',
|
database: 'rocketchat_converted',
|
||||||
stats: {
|
stats: {
|
||||||
active_users: parseInt(result.rows[0].user_count),
|
active_users: parseInt(result.rows[0].user_count, 10),
|
||||||
total_messages: parseInt(messageResult.rows[0].message_count),
|
total_messages: parseInt(messageResult.rows[0].message_count, 10),
|
||||||
total_rooms: parseInt(roomResult.rows[0].room_count)
|
total_rooms: parseInt(roomResult.rows[0].room_count, 10),
|
||||||
}
|
},
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Database test error:', error);
|
|
||||||
res.status(500).json({
|
|
||||||
status: 'error',
|
|
||||||
error: 'Database connection failed',
|
|
||||||
details: error.message
|
|
||||||
});
|
});
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Mount all routes from routes.js
|
|
||||||
app.use('/', chatRoutes);
|
app.use('/', chatRoutes);
|
||||||
|
|
||||||
// Health check endpoint
|
app.use(errorHandler);
|
||||||
app.get('/health', (req, res) => {
|
|
||||||
res.json({ status: 'healthy' });
|
// Phase 9 §9.1 — bind to 127.0.0.1. Caddy reverse_proxy targets localhost:3014
|
||||||
|
// already; this closes the gap where unauthenticated direct-port access from
|
||||||
|
// any host on the network was possible.
|
||||||
|
const server = app.listen(port, '127.0.0.1', () => {
|
||||||
|
console.log(`Chat server running on 127.0.0.1:${port}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Error handling middleware
|
const shutdown = async (signal) => {
|
||||||
app.use((err, req, res, next) => {
|
console.log(`chat-server shutting down (${signal})`);
|
||||||
console.error(err.stack);
|
server.close();
|
||||||
res.status(500).json({ error: 'Something broke!' });
|
try { await pool.end(); } catch { /* ignore */ }
|
||||||
});
|
try { await inventoryPool.end(); } catch { /* ignore */ }
|
||||||
|
process.exit(0);
|
||||||
// Start server
|
};
|
||||||
app.listen(port, () => {
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||||
console.log(`Chat server running on port ${port}`);
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||||
});
|
|
||||||
|
|||||||
@@ -0,0 +1,200 @@
|
|||||||
|
# Caddyfile — Phase 9 §9.2 proposed form.
|
||||||
|
#
|
||||||
|
# Three changes vs. /etc/caddy/Caddyfile (2026-05-24):
|
||||||
|
# 1. @static matcher now explicitly excludes /uploads/* — without this, an
|
||||||
|
# uploaded *.jpg matched @static before @gated and slipped past the
|
||||||
|
# forward_auth gate, hitting the SPA build root and returning a public 404.
|
||||||
|
# 2. The security_headers snippet no longer sets Access-Control-Allow-* —
|
||||||
|
# the upstreams' shared/cors/policy.js is the single source of truth for
|
||||||
|
# CORS responses (Phase 6.6).
|
||||||
|
# 3. New @cors_preflight handler punts OPTIONS preflights past forward_auth
|
||||||
|
# so the upstream's CORS middleware can answer them (preflights have no
|
||||||
|
# Authorization header, so they 401'd at the gate previously).
|
||||||
|
#
|
||||||
|
# Apply via the staged-cutover convention in Deviation #8:
|
||||||
|
# scp this file to netcup:/home/matt/Caddyfile.new
|
||||||
|
# curl --silent -X POST -H "Content-Type: text/caddyfile" \
|
||||||
|
# --data-binary @/home/matt/Caddyfile.new http://localhost:2020/load
|
||||||
|
# # ...smoke-test, then persist:
|
||||||
|
# sudo cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.bak.YYYY-MM-DD
|
||||||
|
# sudo cp /home/matt/Caddyfile.new /etc/caddy/Caddyfile
|
||||||
|
{
|
||||||
|
admin :2020
|
||||||
|
}
|
||||||
|
(security_headers) {
|
||||||
|
header {
|
||||||
|
X-Content-Type-Options "nosniff"
|
||||||
|
X-Frame-Options "SAMEORIGIN"
|
||||||
|
X-XSS-Protection "1; mode=block"
|
||||||
|
Strict-Transport-Security "max-age=31536000; includeSubDomains"
|
||||||
|
Referrer-Policy "strict-origin-when-cross-origin"
|
||||||
|
# Phase 9 §9.2: CORS headers removed. Upstreams set ACAO conditionally
|
||||||
|
# via shared/cors/policy.js; Caddy stamping `*` here was overriding it.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files.acot.site {
|
||||||
|
reverse_proxy localhost:8060
|
||||||
|
}
|
||||||
|
pbx.acot.site {
|
||||||
|
@ws path /ws
|
||||||
|
handle @ws {
|
||||||
|
reverse_proxy 127.0.0.1:8088
|
||||||
|
}
|
||||||
|
handle {
|
||||||
|
reverse_proxy 127.0.0.1:8080 {
|
||||||
|
header_up Host {host}
|
||||||
|
header_down Location http://127.0.0.1:8080 https://pbx.acot.site
|
||||||
|
header_down Location http://pbx.acot.site:8080 https://pbx.acot.site
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
turn.acot.site {
|
||||||
|
respond 404
|
||||||
|
}
|
||||||
|
freescout.acot.site {
|
||||||
|
root * /var/www/freescout/public
|
||||||
|
encode gzip
|
||||||
|
php_fastcgi unix//run/php/php8.3-fpm.sock
|
||||||
|
file_server
|
||||||
|
# Deny access to dotfiles
|
||||||
|
@dotfiles path */.*
|
||||||
|
respond @dotfiles 403
|
||||||
|
}
|
||||||
|
phone.acot.site {
|
||||||
|
reverse_proxy 127.0.0.1:3020
|
||||||
|
encode gzip
|
||||||
|
}
|
||||||
|
crafty.acot.site {
|
||||||
|
reverse_proxy localhost:8443 {
|
||||||
|
header_up X-Forwarded-Proto https
|
||||||
|
header_up X-Forwarded-Port 443
|
||||||
|
header_up Host {host}
|
||||||
|
transport http {
|
||||||
|
tls_insecure_skip_verify
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cronicle.acot.site {
|
||||||
|
reverse_proxy localhost:3100 {
|
||||||
|
header_up X-Forwarded-Proto https
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inventory.acot.site, acot.site {
|
||||||
|
redir https://tools.acherryontop.com{uri} permanent
|
||||||
|
}
|
||||||
|
tools.acherryontop.com {
|
||||||
|
import security_headers
|
||||||
|
|
||||||
|
# Public: login endpoint
|
||||||
|
handle /auth-inv/* {
|
||||||
|
uri strip_prefix /auth-inv
|
||||||
|
reverse_proxy localhost:3011
|
||||||
|
}
|
||||||
|
|
||||||
|
# Phase 9 §9.2 — CORS preflight bypass.
|
||||||
|
# Browsers send OPTIONS preflights without Authorization, so forward_auth
|
||||||
|
# 401s them. Route preflights straight to the upstream which runs
|
||||||
|
# shared/cors/policy.js and answers correctly. Must come before @static
|
||||||
|
# and @gated so OPTIONS to *.jpg paths under /uploads/* also work if any
|
||||||
|
# frontend ever XHRs an upload URL.
|
||||||
|
@cors_preflight {
|
||||||
|
method OPTIONS
|
||||||
|
header Access-Control-Request-Method *
|
||||||
|
}
|
||||||
|
handle @cors_preflight {
|
||||||
|
handle /api/klaviyo/* {
|
||||||
|
reverse_proxy localhost:3015
|
||||||
|
}
|
||||||
|
handle /api/meta/* {
|
||||||
|
reverse_proxy localhost:3015
|
||||||
|
}
|
||||||
|
handle /api/dashboard-analytics/* {
|
||||||
|
reverse_proxy localhost:3015
|
||||||
|
}
|
||||||
|
handle /api/typeform/* {
|
||||||
|
reverse_proxy localhost:3015
|
||||||
|
}
|
||||||
|
handle /api/acot/* {
|
||||||
|
reverse_proxy localhost:3012
|
||||||
|
}
|
||||||
|
handle /chat-api/* {
|
||||||
|
uri strip_prefix /chat-api
|
||||||
|
reverse_proxy localhost:3014
|
||||||
|
}
|
||||||
|
handle /api/* {
|
||||||
|
reverse_proxy localhost:3010
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Public: static frontend assets (long-cache).
|
||||||
|
# Phase 9 §9.2: `not path /uploads/*` ensures uploaded images never get
|
||||||
|
# served from the SPA build root — they must go through @gated below.
|
||||||
|
@static {
|
||||||
|
path *.js *.css *.png *.jpg *.jpeg *.gif *.ico *.svg *.woff *.woff2
|
||||||
|
not path /uploads/*
|
||||||
|
}
|
||||||
|
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).
|
||||||
|
# Phase 9 §9.2 closes the static-matcher bypass that made this ineffective.
|
||||||
|
handle /uploads/* {
|
||||||
|
root * /var/www/inventory
|
||||||
|
file_server
|
||||||
|
}
|
||||||
|
# Phase 4: merged dashboard-server (klaviyo + meta + google + typeform).
|
||||||
|
handle /api/klaviyo/* {
|
||||||
|
reverse_proxy localhost:3015
|
||||||
|
}
|
||||||
|
handle /api/meta/* {
|
||||||
|
reverse_proxy localhost:3015
|
||||||
|
}
|
||||||
|
handle /api/dashboard-analytics/* {
|
||||||
|
reverse_proxy localhost:3015
|
||||||
|
}
|
||||||
|
handle /api/typeform/* {
|
||||||
|
reverse_proxy localhost:3015
|
||||||
|
}
|
||||||
|
# ACOT
|
||||||
|
handle /api/acot/* {
|
||||||
|
reverse_proxy localhost:3012
|
||||||
|
}
|
||||||
|
# Chat (Phase 9 §9.1 — chat-server now has its own authenticate() too)
|
||||||
|
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}"
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+1439
-1
File diff suppressed because it is too large
Load Diff
@@ -13,7 +13,8 @@
|
|||||||
"prod:logs": "pm2 logs inventory-server",
|
"prod:logs": "pm2 logs inventory-server",
|
||||||
"prod:status": "pm2 status inventory-server",
|
"prod:status": "pm2 status inventory-server",
|
||||||
"setup": "mkdir -p logs uploads",
|
"setup": "mkdir -p logs uploads",
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -43,6 +44,7 @@
|
|||||||
"uuid": "^9.0.1"
|
"uuid": "^9.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"nodemon": "^3.0.2"
|
"nodemon": "^3.0.2",
|
||||||
|
"vitest": "^2.1.9"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
// Phase 9 §9.4 — vitest scaffold + auth-boundary tests.
|
||||||
|
//
|
||||||
|
// Covers shared/auth/middleware.js. Mocks the Postgres pool with a thin
|
||||||
|
// in-memory fake — no real DB required.
|
||||||
|
|
||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
import { authenticate, requirePermission } from './middleware.js';
|
||||||
|
|
||||||
|
const SECRET = 'test-secret-please-do-not-use-in-prod';
|
||||||
|
|
||||||
|
function makeFakePool(users, permissions = {}) {
|
||||||
|
const calls = { count: 0 };
|
||||||
|
return {
|
||||||
|
calls,
|
||||||
|
query: vi.fn(async (sql, params) => {
|
||||||
|
calls.count += 1;
|
||||||
|
if (sql.includes('FROM users WHERE id')) {
|
||||||
|
const user = users[params[0]];
|
||||||
|
return { rows: user ? [user] : [] };
|
||||||
|
}
|
||||||
|
if (sql.includes('FROM permissions')) {
|
||||||
|
return { rows: (permissions[params[0]] || []).map((code) => ({ code })) };
|
||||||
|
}
|
||||||
|
return { rows: [] };
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeReq(authHeader) {
|
||||||
|
return { headers: authHeader ? { authorization: authHeader } : {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeRes() {
|
||||||
|
const res = {};
|
||||||
|
res.status = vi.fn(() => res);
|
||||||
|
res.json = vi.fn(() => res);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('authenticate middleware', () => {
|
||||||
|
let activeUser;
|
||||||
|
let inactiveUser;
|
||||||
|
let validToken;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
activeUser = { id: 1, username: 'alice', email: 'a@x', is_admin: false, is_active: true };
|
||||||
|
inactiveUser = { id: 2, username: 'bob', email: 'b@x', is_admin: false, is_active: false };
|
||||||
|
validToken = jwt.sign({ userId: 1 }, SECRET, { expiresIn: '1h' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 401 when no Authorization header is present', async () => {
|
||||||
|
const pool = makeFakePool({ 1: activeUser });
|
||||||
|
const mw = authenticate({ pool, secret: SECRET });
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
await mw(makeReq(), res, next);
|
||||||
|
expect(res.status).toHaveBeenCalledWith(401);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 401 when Authorization is not Bearer', async () => {
|
||||||
|
const pool = makeFakePool({ 1: activeUser });
|
||||||
|
const mw = authenticate({ pool, secret: SECRET });
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
await mw(makeReq('Basic abc'), res, next);
|
||||||
|
expect(res.status).toHaveBeenCalledWith(401);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 401 when token is malformed', async () => {
|
||||||
|
const pool = makeFakePool({ 1: activeUser });
|
||||||
|
const mw = authenticate({ pool, secret: SECRET });
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
await mw(makeReq('Bearer not-a-jwt'), res, next);
|
||||||
|
expect(res.status).toHaveBeenCalledWith(401);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 403 when the user is inactive', async () => {
|
||||||
|
const inactiveToken = jwt.sign({ userId: 2 }, SECRET, { expiresIn: '1h' });
|
||||||
|
const pool = makeFakePool({ 2: inactiveUser });
|
||||||
|
const mw = authenticate({ pool, secret: SECRET });
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
await mw(makeReq(`Bearer ${inactiveToken}`), res, next);
|
||||||
|
expect(res.status).toHaveBeenCalledWith(403);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls next() and populates req.user for a valid token + active user', async () => {
|
||||||
|
const pool = makeFakePool({ 1: activeUser }, { 1: ['products:read'] });
|
||||||
|
const mw = authenticate({ pool, secret: SECRET });
|
||||||
|
const req = makeReq(`Bearer ${validToken}`);
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
await mw(req, res, next);
|
||||||
|
expect(next).toHaveBeenCalledOnce();
|
||||||
|
expect(req.user).toBeDefined();
|
||||||
|
expect(req.user.id).toBe(1);
|
||||||
|
expect(req.user.permissions).toEqual(['products:read']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('caches the user lookup — same token within TTL → one DB hit', async () => {
|
||||||
|
const pool = makeFakePool({ 1: activeUser }, { 1: [] });
|
||||||
|
const mw = authenticate({ pool, secret: SECRET });
|
||||||
|
const next = vi.fn();
|
||||||
|
await mw(makeReq(`Bearer ${validToken}`), makeRes(), next);
|
||||||
|
await mw(makeReq(`Bearer ${validToken}`), makeRes(), next);
|
||||||
|
// Two queries on first hit (user + permissions), zero on the second
|
||||||
|
expect(pool.calls.count).toBe(2);
|
||||||
|
expect(next).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refetches after TTL expiry', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const pool = makeFakePool({ 1: activeUser }, { 1: [] });
|
||||||
|
const mw = authenticate({ pool, secret: SECRET });
|
||||||
|
const next = vi.fn();
|
||||||
|
await mw(makeReq(`Bearer ${validToken}`), makeRes(), next);
|
||||||
|
expect(pool.calls.count).toBe(2);
|
||||||
|
vi.advanceTimersByTime(61_000);
|
||||||
|
await mw(makeReq(`Bearer ${validToken}`), makeRes(), next);
|
||||||
|
expect(pool.calls.count).toBe(4);
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('requirePermission middleware', () => {
|
||||||
|
it('returns 401 when req.user is missing', () => {
|
||||||
|
const mw = requirePermission('products:write');
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
mw({}, res, next);
|
||||||
|
expect(res.status).toHaveBeenCalledWith(401);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls next() for admin users regardless of code', () => {
|
||||||
|
const mw = requirePermission('products:write');
|
||||||
|
const next = vi.fn();
|
||||||
|
mw({ user: { is_admin: true, permissions: [] } }, makeRes(), next);
|
||||||
|
expect(next).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls next() when user has the required permission', () => {
|
||||||
|
const mw = requirePermission('products:write');
|
||||||
|
const next = vi.fn();
|
||||||
|
mw({ user: { is_admin: false, permissions: ['products:write'] } }, makeRes(), next);
|
||||||
|
expect(next).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 403 when user lacks the required permission', () => {
|
||||||
|
const mw = requirePermission('products:write');
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
mw({ user: { is_admin: false, permissions: ['products:read'] } }, res, next);
|
||||||
|
expect(res.status).toHaveBeenCalledWith(403);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// Phase 9 §9.4 — vitest scaffold + auth-boundary tests.
|
||||||
|
//
|
||||||
|
// Covers the security-critical surface in shared/auth/verify.js. Five cases
|
||||||
|
// per the original Phase 2 testing-scaffold spec.
|
||||||
|
|
||||||
|
import { describe, it, expect, beforeAll } from 'vitest';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
import { extractBearerToken, verifyToken, TokenError } from './verify.js';
|
||||||
|
|
||||||
|
const SECRET = 'test-secret-please-do-not-use-in-prod';
|
||||||
|
const WRONG_SECRET = 'a-different-secret';
|
||||||
|
|
||||||
|
let validToken;
|
||||||
|
let expiredToken;
|
||||||
|
let wrongSigToken;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
validToken = jwt.sign({ userId: 42, username: 'alice' }, SECRET, { expiresIn: '1h' });
|
||||||
|
expiredToken = jwt.sign({ userId: 42, username: 'alice' }, SECRET, { expiresIn: '-1s' });
|
||||||
|
wrongSigToken = jwt.sign({ userId: 42, username: 'alice' }, WRONG_SECRET, { expiresIn: '1h' });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('extractBearerToken', () => {
|
||||||
|
it('returns token from a well-formed Bearer header', () => {
|
||||||
|
expect(extractBearerToken('Bearer abc.def.ghi')).toBe('abc.def.ghi');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws TokenError(missing) when no header is provided', () => {
|
||||||
|
expect(() => extractBearerToken(undefined)).toThrow(TokenError);
|
||||||
|
try { extractBearerToken(undefined); } catch (err) { expect(err.code).toBe('missing'); }
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws TokenError(malformed) when header is not Bearer-prefixed', () => {
|
||||||
|
expect(() => extractBearerToken('Basic abc')).toThrow(TokenError);
|
||||||
|
try { extractBearerToken('Basic abc'); } catch (err) { expect(err.code).toBe('malformed'); }
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws TokenError(malformed) when Bearer header has empty token', () => {
|
||||||
|
expect(() => extractBearerToken('Bearer ')).toThrow(TokenError);
|
||||||
|
try { extractBearerToken('Bearer '); } catch (err) { expect(err.code).toBe('malformed'); }
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws TokenError(missing) when header is not a string', () => {
|
||||||
|
expect(() => extractBearerToken(null)).toThrow(TokenError);
|
||||||
|
expect(() => extractBearerToken(42)).toThrow(TokenError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('verifyToken', () => {
|
||||||
|
it('returns decoded payload for a valid token', () => {
|
||||||
|
const decoded = verifyToken(validToken, SECRET);
|
||||||
|
expect(decoded.userId).toBe(42);
|
||||||
|
expect(decoded.username).toBe('alice');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws TokenError(expired) for an expired token', () => {
|
||||||
|
expect(() => verifyToken(expiredToken, SECRET)).toThrow(TokenError);
|
||||||
|
try { verifyToken(expiredToken, SECRET); } catch (err) { expect(err.code).toBe('expired'); }
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws TokenError(invalid) for a wrong-signature token', () => {
|
||||||
|
expect(() => verifyToken(wrongSigToken, SECRET)).toThrow(TokenError);
|
||||||
|
try { verifyToken(wrongSigToken, SECRET); } catch (err) { expect(err.code).toBe('invalid'); }
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws TokenError(invalid) for malformed JWT', () => {
|
||||||
|
expect(() => verifyToken('not-a-jwt', SECRET)).toThrow(TokenError);
|
||||||
|
try { verifyToken('not-a-jwt', SECRET); } catch (err) { expect(err.code).toBe('invalid'); }
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws TokenError(misconfigured) when secret is missing', () => {
|
||||||
|
expect(() => verifyToken(validToken, undefined)).toThrow(TokenError);
|
||||||
|
try { verifyToken(validToken, undefined); } catch (err) { expect(err.code).toBe('misconfigured'); }
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -32,13 +32,81 @@ router.get('/brands', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Get all products with pagination, filtering, and sorting
|
// Get all products with pagination, filtering, and sorting
|
||||||
|
// Whitelist of allowed sort keys → SQL column expressions. Used to gate
|
||||||
|
// `?sort=` against direct interpolation into ORDER BY (the previous code
|
||||||
|
// dropped req.query.sort straight into the query string — SQL injection sink).
|
||||||
|
// Keys are the camelCase identifiers the frontend ProductMetricColumnKey union
|
||||||
|
// emits. Anything not in the map falls back to `p.title`.
|
||||||
|
const SORT_COLUMN_MAP = {
|
||||||
|
pid: 'p.pid',
|
||||||
|
title: 'p.title',
|
||||||
|
sku: 'p.sku',
|
||||||
|
barcode: 'p.barcode',
|
||||||
|
brand: 'p.brand',
|
||||||
|
line: 'p.line',
|
||||||
|
subline: 'p.subline',
|
||||||
|
artist: 'p.artist',
|
||||||
|
vendor: 'p.vendor',
|
||||||
|
vendorReference: 'p.vendor_reference',
|
||||||
|
notionsReference: 'p.notions_reference',
|
||||||
|
harmonizedTariffCode: 'p.harmonized_tariff_code',
|
||||||
|
countryOfOrigin: 'p.country_of_origin',
|
||||||
|
location: 'p.location',
|
||||||
|
moq: 'p.moq',
|
||||||
|
weight: 'p.weight',
|
||||||
|
rating: 'p.rating',
|
||||||
|
reviews: 'p.reviews',
|
||||||
|
baskets: 'p.baskets',
|
||||||
|
notifies: 'p.notifies',
|
||||||
|
preorderCount: 'p.preorder_count',
|
||||||
|
notionsInvCount: 'p.notions_inv_count',
|
||||||
|
dateCreated: 'p.created_at',
|
||||||
|
dateLastSold: 'p.date_last_sold',
|
||||||
|
stock: 'p.stock_quantity',
|
||||||
|
stockQuantity: 'p.stock_quantity',
|
||||||
|
price: 'p.price',
|
||||||
|
costPrice: 'p.cost_price',
|
||||||
|
totalSold: 'p.total_sold',
|
||||||
|
// product_metrics columns (current schema names; camelCase aliases the
|
||||||
|
// frontend uses are mapped to the canonical SQL column)
|
||||||
|
dailySalesAvg: 'pm.avg_sales_per_day_30d',
|
||||||
|
weeklySalesAvg: 'pm.sales_7d',
|
||||||
|
monthlySalesAvg: 'pm.avg_sales_per_month_30d',
|
||||||
|
margin: 'pm.margin_30d',
|
||||||
|
gmroi: 'pm.gmroi_30d',
|
||||||
|
gmroi30d: 'pm.gmroi_30d',
|
||||||
|
inventoryValue: 'pm.current_stock_cost',
|
||||||
|
costOfGoodsSold: 'pm.cogs_30d',
|
||||||
|
grossProfit: 'pm.profit_30d',
|
||||||
|
turnoverRate: 'pm.stockturn_30d',
|
||||||
|
stockturn30d: 'pm.stockturn_30d',
|
||||||
|
leadTime: 'pm.config_lead_time',
|
||||||
|
currentLeadTime: 'pm.config_lead_time',
|
||||||
|
targetLeadTime: 'pm.config_lead_time',
|
||||||
|
stockCoverage: 'pm.stock_cover_in_days',
|
||||||
|
daysOfStock: 'pm.stock_cover_in_days',
|
||||||
|
reorderPoint: 'pm.replenishment_units',
|
||||||
|
safetyStock: 'pm.config_safety_stock',
|
||||||
|
abcClass: 'pm.abc_class',
|
||||||
|
status: 'pm.status',
|
||||||
|
ageDays: 'pm.age_days',
|
||||||
|
sales7d: 'pm.sales_7d',
|
||||||
|
sales30d: 'pm.sales_30d',
|
||||||
|
sales365d: 'pm.sales_365d',
|
||||||
|
revenue7d: 'pm.revenue_7d',
|
||||||
|
revenue30d: 'pm.revenue_30d',
|
||||||
|
revenue365d: 'pm.revenue_365d',
|
||||||
|
sellThrough30d: 'pm.sell_through_30d',
|
||||||
|
salesGrowth30dVsPrev: 'pm.sales_growth_30d_vs_prev',
|
||||||
|
};
|
||||||
|
|
||||||
router.get('/', async (req, res) => {
|
router.get('/', async (req, res) => {
|
||||||
const pool = req.app.locals.pool;
|
const pool = req.app.locals.pool;
|
||||||
try {
|
try {
|
||||||
const page = parseInt(req.query.page) || 1;
|
const page = parseInt(req.query.page) || 1;
|
||||||
const limit = parseInt(req.query.limit) || 50;
|
const limit = parseInt(req.query.limit) || 50;
|
||||||
const offset = (page - 1) * limit;
|
const offset = (page - 1) * limit;
|
||||||
const sortColumn = req.query.sort || 'title';
|
const sortColumn = SORT_COLUMN_MAP[req.query.sort] || 'p.title';
|
||||||
const sortDirection = req.query.order === 'desc' ? 'DESC' : 'ASC';
|
const sortDirection = req.query.order === 'desc' ? 'DESC' : 'ASC';
|
||||||
|
|
||||||
const conditions = ['p.visible = true'];
|
const conditions = ['p.visible = true'];
|
||||||
@@ -120,30 +188,28 @@ router.get('/', async (req, res) => {
|
|||||||
paramCounter++;
|
paramCounter++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle numeric filters with operators
|
// Handle numeric filters with operators. Mapped to current product_metrics
|
||||||
|
// column names; frontend keys (camelCase) preserved for compatibility.
|
||||||
const numericFields = {
|
const numericFields = {
|
||||||
stock: 'p.stock_quantity',
|
stock: 'p.stock_quantity',
|
||||||
price: 'p.price',
|
price: 'p.price',
|
||||||
costPrice: 'p.cost_price',
|
costPrice: 'p.cost_price',
|
||||||
dailySalesAvg: 'pm.daily_sales_avg',
|
dailySalesAvg: 'pm.avg_sales_per_day_30d',
|
||||||
weeklySalesAvg: 'pm.weekly_sales_avg',
|
weeklySalesAvg: 'pm.sales_7d',
|
||||||
monthlySalesAvg: 'pm.monthly_sales_avg',
|
monthlySalesAvg: 'pm.avg_sales_per_month_30d',
|
||||||
avgQuantityPerOrder: 'pm.avg_quantity_per_order',
|
margin: 'pm.margin_30d',
|
||||||
numberOfOrders: 'pm.number_of_orders',
|
gmroi: 'pm.gmroi_30d',
|
||||||
margin: 'pm.avg_margin_percent',
|
inventoryValue: 'pm.current_stock_cost',
|
||||||
gmroi: 'pm.gmroi',
|
costOfGoodsSold: 'pm.cogs_30d',
|
||||||
inventoryValue: 'pm.inventory_value',
|
grossProfit: 'pm.profit_30d',
|
||||||
costOfGoodsSold: 'pm.cost_of_goods_sold',
|
turnoverRate: 'pm.stockturn_30d',
|
||||||
grossProfit: 'pm.gross_profit',
|
leadTime: 'pm.config_lead_time',
|
||||||
turnoverRate: 'pm.turnover_rate',
|
currentLeadTime: 'pm.config_lead_time',
|
||||||
leadTime: 'pm.current_lead_time',
|
targetLeadTime: 'pm.config_lead_time',
|
||||||
currentLeadTime: 'pm.current_lead_time',
|
stockCoverage: 'pm.stock_cover_in_days',
|
||||||
targetLeadTime: 'pm.target_lead_time',
|
daysOfStock: 'pm.stock_cover_in_days',
|
||||||
stockCoverage: 'pm.days_of_inventory',
|
reorderPoint: 'pm.replenishment_units',
|
||||||
daysOfStock: 'pm.days_of_inventory',
|
safetyStock: 'pm.config_safety_stock',
|
||||||
weeksOfStock: 'pm.weeks_of_inventory',
|
|
||||||
reorderPoint: 'pm.reorder_point',
|
|
||||||
safetyStock: 'pm.safety_stock',
|
|
||||||
// Add new numeric fields
|
// Add new numeric fields
|
||||||
preorderCount: 'p.preorder_count',
|
preorderCount: 'p.preorder_count',
|
||||||
notionsInvCount: 'p.notions_inv_count',
|
notionsInvCount: 'p.notions_inv_count',
|
||||||
@@ -267,88 +333,33 @@ router.get('/', async (req, res) => {
|
|||||||
'SELECT DISTINCT COALESCE(brand, \'Unbranded\') as brand FROM products WHERE visible = true ORDER BY brand'
|
'SELECT DISTINCT COALESCE(brand, \'Unbranded\') as brand FROM products WHERE visible = true ORDER BY brand'
|
||||||
);
|
);
|
||||||
|
|
||||||
// Main query with all fields
|
// Main query with all fields. Aliases new product_metrics column names back to
|
||||||
|
// the legacy names the frontend ProductRow type still uses — same pattern as the
|
||||||
|
// /:id detail route below.
|
||||||
const query = `
|
const query = `
|
||||||
WITH RECURSIVE
|
SELECT
|
||||||
category_path AS (
|
|
||||||
SELECT
|
|
||||||
c.cat_id,
|
|
||||||
c.name,
|
|
||||||
c.parent_id,
|
|
||||||
c.name::text as path
|
|
||||||
FROM categories c
|
|
||||||
WHERE c.parent_id IS NULL
|
|
||||||
|
|
||||||
UNION ALL
|
|
||||||
|
|
||||||
SELECT
|
|
||||||
c.cat_id,
|
|
||||||
c.name,
|
|
||||||
c.parent_id,
|
|
||||||
(cp.path || ' > ' || c.name)::text
|
|
||||||
FROM categories c
|
|
||||||
JOIN category_path cp ON c.parent_id = cp.cat_id
|
|
||||||
),
|
|
||||||
product_thresholds AS (
|
|
||||||
SELECT
|
|
||||||
p.pid,
|
|
||||||
COALESCE(
|
|
||||||
(SELECT overstock_days FROM stock_thresholds st
|
|
||||||
WHERE st.category_id IN (
|
|
||||||
SELECT pc.cat_id
|
|
||||||
FROM product_categories pc
|
|
||||||
WHERE pc.pid = p.pid
|
|
||||||
)
|
|
||||||
AND (st.vendor = p.vendor OR st.vendor IS NULL)
|
|
||||||
ORDER BY st.vendor IS NULL
|
|
||||||
LIMIT 1),
|
|
||||||
(SELECT overstock_days FROM stock_thresholds st
|
|
||||||
WHERE st.category_id IS NULL
|
|
||||||
AND (st.vendor = p.vendor OR st.vendor IS NULL)
|
|
||||||
ORDER BY st.vendor IS NULL
|
|
||||||
LIMIT 1),
|
|
||||||
90
|
|
||||||
) as target_days
|
|
||||||
FROM products p
|
|
||||||
),
|
|
||||||
product_leaf_categories AS (
|
|
||||||
SELECT DISTINCT pc.cat_id
|
|
||||||
FROM product_categories pc
|
|
||||||
WHERE NOT EXISTS (
|
|
||||||
SELECT 1
|
|
||||||
FROM categories child
|
|
||||||
JOIN product_categories child_pc ON child.cat_id = child_pc.cat_id
|
|
||||||
WHERE child.parent_id = pc.cat_id
|
|
||||||
AND child_pc.pid = pc.pid
|
|
||||||
)
|
|
||||||
)
|
|
||||||
SELECT
|
|
||||||
p.*,
|
p.*,
|
||||||
COALESCE(p.brand, 'Unbranded') as brand,
|
COALESCE(p.brand, 'Unbranded') as brand,
|
||||||
string_agg(DISTINCT (c.cat_id || ':' || c.name), ',') as categories,
|
string_agg(DISTINCT (c.cat_id || ':' || c.name), ',') as categories,
|
||||||
pm.daily_sales_avg,
|
pm.avg_sales_per_day_30d AS daily_sales_avg,
|
||||||
pm.weekly_sales_avg,
|
pm.sales_7d AS weekly_sales_avg,
|
||||||
pm.monthly_sales_avg,
|
pm.avg_sales_per_month_30d AS monthly_sales_avg,
|
||||||
pm.avg_quantity_per_order,
|
pm.date_first_sold AS first_sale_date,
|
||||||
pm.number_of_orders,
|
pm.date_last_sold AS last_sale_date,
|
||||||
pm.first_sale_date,
|
pm.stock_cover_in_days AS days_of_inventory,
|
||||||
pm.last_sale_date,
|
pm.replenishment_units AS reorder_point,
|
||||||
pm.days_of_inventory,
|
pm.config_safety_stock AS safety_stock,
|
||||||
pm.weeks_of_inventory,
|
pm.margin_30d AS avg_margin_percent,
|
||||||
pm.reorder_point,
|
CAST(pm.lifetime_revenue AS DECIMAL(15,3)) as total_revenue,
|
||||||
pm.safety_stock,
|
CAST(pm.current_stock_cost AS DECIMAL(15,3)) as inventory_value,
|
||||||
pm.avg_margin_percent,
|
CAST(pm.cogs_30d AS DECIMAL(15,3)) as cost_of_goods_sold,
|
||||||
CAST(pm.total_revenue AS DECIMAL(15,3)) as total_revenue,
|
CAST(pm.profit_30d AS DECIMAL(15,3)) as gross_profit,
|
||||||
CAST(pm.inventory_value AS DECIMAL(15,3)) as inventory_value,
|
pm.gmroi_30d AS gmroi,
|
||||||
CAST(pm.cost_of_goods_sold AS DECIMAL(15,3)) as cost_of_goods_sold,
|
|
||||||
CAST(pm.gross_profit AS DECIMAL(15,3)) as gross_profit,
|
|
||||||
pm.gmroi,
|
|
||||||
pm.avg_lead_time_days,
|
pm.avg_lead_time_days,
|
||||||
pm.last_purchase_date,
|
pm.date_last_received AS last_received_date,
|
||||||
pm.last_received_date,
|
|
||||||
pm.abc_class,
|
pm.abc_class,
|
||||||
pm.stock_status,
|
pm.status AS stock_status,
|
||||||
pm.turnover_rate,
|
pm.stockturn_30d AS turnover_rate,
|
||||||
p.date_last_sold
|
p.date_last_sold
|
||||||
FROM products p
|
FROM products p
|
||||||
LEFT JOIN product_metrics pm ON p.pid = pm.pid
|
LEFT JOIN product_metrics pm ON p.pid = pm.pid
|
||||||
@@ -389,12 +400,12 @@ router.get('/trending', async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
// First check if we have any data
|
// First check if we have any data
|
||||||
const { rows } = await pool.query(`
|
const { rows } = await pool.query(`
|
||||||
SELECT COUNT(*) as count,
|
SELECT COUNT(*) as count,
|
||||||
MAX(total_revenue) as max_revenue,
|
MAX(lifetime_revenue) as max_revenue,
|
||||||
MAX(daily_sales_avg) as max_daily_sales,
|
MAX(avg_sales_per_day_30d) as max_daily_sales,
|
||||||
COUNT(DISTINCT pid) as products_with_metrics
|
COUNT(DISTINCT pid) as products_with_metrics
|
||||||
FROM product_metrics
|
FROM product_metrics
|
||||||
WHERE total_revenue > 0 OR daily_sales_avg > 0
|
WHERE lifetime_revenue > 0 OR avg_sales_per_day_30d > 0
|
||||||
`);
|
`);
|
||||||
console.log('Product metrics stats:', rows[0]);
|
console.log('Product metrics stats:', rows[0]);
|
||||||
|
|
||||||
@@ -403,25 +414,24 @@ router.get('/trending', async (req, res) => {
|
|||||||
return res.json([]);
|
return res.json([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get trending products
|
// Get trending products. growth_rate uses sales_growth_30d_vs_prev — a
|
||||||
|
// pre-computed % delta of the last 30d window vs the prior 30d window.
|
||||||
|
// (The old formula compared a per-day rate against a 7-day total, which
|
||||||
|
// mixed units and produced nonsense after the metrics-schema rename.)
|
||||||
const { rows: trendingProducts } = await pool.query(`
|
const { rows: trendingProducts } = await pool.query(`
|
||||||
SELECT
|
SELECT
|
||||||
p.pid,
|
p.pid,
|
||||||
p.sku,
|
p.sku,
|
||||||
p.title,
|
p.title,
|
||||||
COALESCE(pm.daily_sales_avg, 0) as daily_sales_avg,
|
COALESCE(pm.avg_sales_per_day_30d, 0) as daily_sales_avg,
|
||||||
COALESCE(pm.weekly_sales_avg, 0) as weekly_sales_avg,
|
COALESCE(pm.sales_7d, 0) as weekly_sales_avg,
|
||||||
CASE
|
COALESCE(pm.sales_growth_30d_vs_prev, 0) as growth_rate,
|
||||||
WHEN pm.weekly_sales_avg > 0 AND pm.daily_sales_avg > 0
|
COALESCE(pm.lifetime_revenue, 0) as total_revenue
|
||||||
THEN ((pm.daily_sales_avg - pm.weekly_sales_avg) / pm.weekly_sales_avg) * 100
|
|
||||||
ELSE 0
|
|
||||||
END as growth_rate,
|
|
||||||
COALESCE(pm.total_revenue, 0) as total_revenue
|
|
||||||
FROM products p
|
FROM products p
|
||||||
INNER JOIN product_metrics pm ON p.pid = pm.pid
|
INNER JOIN product_metrics pm ON p.pid = pm.pid
|
||||||
WHERE (pm.total_revenue > 0 OR pm.daily_sales_avg > 0)
|
WHERE (pm.lifetime_revenue > 0 OR pm.avg_sales_per_day_30d > 0)
|
||||||
AND p.visible = true
|
AND p.visible = true
|
||||||
ORDER BY growth_rate DESC
|
ORDER BY growth_rate DESC NULLS LAST
|
||||||
LIMIT 50
|
LIMIT 50
|
||||||
`);
|
`);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
|
||||||
|
// Exclude macOS AppleDouble sidecar files (`._*.js`) that get created when
|
||||||
|
// editing through the NFS mount from macOS. See Deviation #15 in
|
||||||
|
// CONSOLIDATION_PLAN.md — these aren't real tests, but vitest's default file
|
||||||
|
// glob picks them up and fails the suite when rollup tries to parse them.
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
include: ['**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts}'],
|
||||||
|
exclude: [
|
||||||
|
'**/node_modules/**',
|
||||||
|
'**/dist/**',
|
||||||
|
'**/build/**',
|
||||||
|
'**/._*',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -4,6 +4,7 @@ import { TrendingUp, DollarSign, Percent, Briefcase } from "lucide-react";
|
|||||||
import { DashboardMultiStatCardMini } from "@/components/dashboard/shared";
|
import { DashboardMultiStatCardMini } from "@/components/dashboard/shared";
|
||||||
import { acotService } from "@/services/dashboard/acotService";
|
import { acotService } from "@/services/dashboard/acotService";
|
||||||
import config from "@/config";
|
import config from "@/config";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
|
|
||||||
const fmtK = (value) => {
|
const fmtK = (value) => {
|
||||||
if (!value && value !== 0) return "$0";
|
if (!value && value !== 0) return "$0";
|
||||||
@@ -56,7 +57,7 @@ const MiniBusinessMetrics = () => {
|
|||||||
const { data: forecastData, isLoading: forecastLoading } = useQuery({
|
const { data: forecastData, isLoading: forecastLoading } = useQuery({
|
||||||
queryKey: ["mini-forecast-30d"],
|
queryKey: ["mini-forecast-30d"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await fetch(`${config.apiUrl}/dashboard/forecast/metrics`);
|
const response = await apiFetch(`${config.apiUrl}/dashboard/forecast/metrics`);
|
||||||
if (!response.ok) throw new Error("Failed to fetch forecast");
|
if (!response.ok) throw new Error("Failed to fetch forecast");
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
@@ -67,7 +68,7 @@ const MiniBusinessMetrics = () => {
|
|||||||
const { data: yearData, isLoading: yearLoading } = useQuery({
|
const { data: yearData, isLoading: yearLoading } = useQuery({
|
||||||
queryKey: ["mini-year-estimate"],
|
queryKey: ["mini-year-estimate"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await fetch(`${config.apiUrl}/dashboard/year-revenue-estimate`);
|
const response = await apiFetch(`${config.apiUrl}/dashboard/year-revenue-estimate`);
|
||||||
if (!response.ok) throw new Error("Failed to fetch year estimate");
|
if (!response.ok) throw new Error("Failed to fetch year estimate");
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { Truck, Warehouse, ShoppingBag, AlertTriangle } from "lucide-react";
|
|||||||
import { DashboardMultiStatCardMini } from "@/components/dashboard/shared";
|
import { DashboardMultiStatCardMini } from "@/components/dashboard/shared";
|
||||||
import { acotService } from "@/services/dashboard/acotService";
|
import { acotService } from "@/services/dashboard/acotService";
|
||||||
import config from "@/config";
|
import config from "@/config";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
|
|
||||||
const fmtCurrency = (value) => {
|
const fmtCurrency = (value) => {
|
||||||
if (!value && value !== 0) return "$0";
|
if (!value && value !== 0) return "$0";
|
||||||
@@ -30,7 +31,7 @@ const MiniInventorySnapshot = () => {
|
|||||||
const { data: stockData, isLoading: stockLoading } = useQuery({
|
const { data: stockData, isLoading: stockLoading } = useQuery({
|
||||||
queryKey: ["mini-stock-metrics"],
|
queryKey: ["mini-stock-metrics"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await fetch(`${config.apiUrl}/dashboard/stock/metrics`);
|
const response = await apiFetch(`${config.apiUrl}/dashboard/stock/metrics`);
|
||||||
if (!response.ok) throw new Error("Failed to fetch stock metrics");
|
if (!response.ok) throw new Error("Failed to fetch stock metrics");
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
@@ -41,7 +42,7 @@ const MiniInventorySnapshot = () => {
|
|||||||
const { data: replenishData, isLoading: replenishLoading } = useQuery({
|
const { data: replenishData, isLoading: replenishLoading } = useQuery({
|
||||||
queryKey: ["mini-replenish-metrics"],
|
queryKey: ["mini-replenish-metrics"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await fetch(`${config.apiUrl}/dashboard/replenishment/metrics`);
|
const response = await apiFetch(`${config.apiUrl}/dashboard/replenishment/metrics`);
|
||||||
if (!response.ok) throw new Error("Failed to fetch replenishment");
|
if (!response.ok) throw new Error("Failed to fetch replenishment");
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
@@ -52,7 +53,7 @@ const MiniInventorySnapshot = () => {
|
|||||||
const { data: overstockData, isLoading: overstockLoading } = useQuery({
|
const { data: overstockData, isLoading: overstockLoading } = useQuery({
|
||||||
queryKey: ["mini-overstock-metrics"],
|
queryKey: ["mini-overstock-metrics"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await fetch(`${config.apiUrl}/dashboard/overstock/metrics`);
|
const response = await apiFetch(`${config.apiUrl}/dashboard/overstock/metrics`);
|
||||||
if (!response.ok) throw new Error("Failed to fetch overstock");
|
if (!response.ok) throw new Error("Failed to fetch overstock");
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { AlertCircle, PiggyBank, ShoppingCart } from "lucide-react";
|
|||||||
import { formatCurrency } from "./SalesChart.jsx";
|
import { formatCurrency } from "./SalesChart.jsx";
|
||||||
import { PHASE_CONFIG, PHASE_KEYS_WITH_UNKNOWN as PHASE_KEYS } from "@/utils/lifecyclePhases";
|
import { PHASE_CONFIG, PHASE_KEYS_WITH_UNKNOWN as PHASE_KEYS } from "@/utils/lifecyclePhases";
|
||||||
import config from "@/config";
|
import config from "@/config";
|
||||||
|
import { apiFetch } from "@/utils/api";
|
||||||
import {
|
import {
|
||||||
DashboardStatCardMini,
|
DashboardStatCardMini,
|
||||||
DashboardStatCardMiniSkeleton,
|
DashboardStatCardMiniSkeleton,
|
||||||
@@ -85,7 +86,7 @@ const MiniSalesChart = ({ className = "" }) => {
|
|||||||
startDate: thirtyDaysAgo.toISOString(),
|
startDate: thirtyDaysAgo.toISOString(),
|
||||||
endDate: now.toISOString(),
|
endDate: now.toISOString(),
|
||||||
});
|
});
|
||||||
const response = await fetch(`${config.apiUrl}/dashboard/sales/metrics?${params}`);
|
const response = await apiFetch(`${config.apiUrl}/dashboard/sales/metrics?${params}`);
|
||||||
if (!response.ok) throw new Error("Failed to fetch sales metrics");
|
if (!response.ok) throw new Error("Failed to fetch sales metrics");
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
|
|||||||
+2
-1
@@ -20,6 +20,7 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
|
import { AuthedImage } from "@/components/ui/authed-image";
|
||||||
import { useState, useMemo } from "react";
|
import { useState, useMemo } from "react";
|
||||||
|
|
||||||
interface ReusableImage {
|
interface ReusableImage {
|
||||||
@@ -248,7 +249,7 @@ export const ProductCard = ({
|
|||||||
className="group relative aspect-square border rounded-lg overflow-hidden cursor-pointer hover:ring-2 hover:ring-primary"
|
className="group relative aspect-square border rounded-lg overflow-hidden cursor-pointer hover:ring-2 hover:ring-primary"
|
||||||
onClick={() => handleAddReusableImage(image.image_url)}
|
onClick={() => handleAddReusableImage(image.image_url)}
|
||||||
>
|
>
|
||||||
<img
|
<AuthedImage
|
||||||
src={image.image_url}
|
src={image.image_url}
|
||||||
alt={image.name}
|
alt={image.name}
|
||||||
className="w-full h-full object-cover"
|
className="w-full h-full object-cover"
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ import {
|
|||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useDropzone } from "react-dropzone";
|
import { useDropzone } from "react-dropzone";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { AuthedImage } from "@/components/ui/authed-image";
|
||||||
|
|
||||||
interface FieldOption {
|
interface FieldOption {
|
||||||
label: string;
|
label: string;
|
||||||
@@ -512,8 +513,8 @@ export function ReusableImageManagement() {
|
|||||||
header: "Thumbnail",
|
header: "Thumbnail",
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<div className="flex items-center justify-center">
|
<div className="flex items-center justify-center">
|
||||||
<img
|
<AuthedImage
|
||||||
src={row.getValue("image_url") as string}
|
src={row.getValue("image_url") as string}
|
||||||
alt={row.getValue("name") as string}
|
alt={row.getValue("name") as string}
|
||||||
className="w-10 h-10 object-contain border rounded"
|
className="w-10 h-10 object-contain border rounded"
|
||||||
/>
|
/>
|
||||||
@@ -707,8 +708,8 @@ export function ReusableImageManagement() {
|
|||||||
<div className="flex justify-center p-4">
|
<div className="flex justify-center p-4">
|
||||||
{previewImage && (
|
{previewImage && (
|
||||||
<div className="bg-checkerboard rounded-md overflow-hidden">
|
<div className="bg-checkerboard rounded-md overflow-hidden">
|
||||||
<img
|
<AuthedImage
|
||||||
src={previewImage.image_url}
|
src={previewImage.image_url}
|
||||||
alt={previewImage.name}
|
alt={previewImage.name}
|
||||||
className="max-h-[500px] max-w-full object-contain"
|
className="max-h-[500px] max-w-full object-contain"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { useEffect, useState, type ImgHTMLAttributes } from 'react';
|
||||||
|
import { apiFetch } from '@/utils/api';
|
||||||
|
|
||||||
|
// Browsers cannot attach Authorization headers to <img src="..."> requests, but
|
||||||
|
// Caddy's forward_auth gate (Phase 6.7 / 9.2) demands a Bearer on /uploads/*.
|
||||||
|
// AuthedImage fetches gated URLs through apiFetch (which adds the Bearer), then
|
||||||
|
// renders the bytes via an object URL. Non-gated URLs (CDN, external) pass
|
||||||
|
// straight through to a plain <img>.
|
||||||
|
|
||||||
|
const GATED_PATH_PATTERN = /\/uploads\//;
|
||||||
|
|
||||||
|
function needsAuth(src: string | undefined): boolean {
|
||||||
|
if (!src) return false;
|
||||||
|
return GATED_PATH_PATTERN.test(src);
|
||||||
|
}
|
||||||
|
|
||||||
|
// /uploads/* URLs are stored absolute in the DB (https://tools.acherryontop.com/...).
|
||||||
|
// Strip the origin so the request goes through the vite dev proxy in dev and stays
|
||||||
|
// same-origin in prod — either way no CORS preflight on the fetch.
|
||||||
|
function toFetchUrl(src: string): string {
|
||||||
|
try {
|
||||||
|
const parsed = new URL(src, window.location.origin);
|
||||||
|
return parsed.pathname + parsed.search;
|
||||||
|
} catch {
|
||||||
|
return src;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuthedImageProps = ImgHTMLAttributes<HTMLImageElement> & { src?: string };
|
||||||
|
|
||||||
|
export function AuthedImage({ src, alt, ...rest }: AuthedImageProps) {
|
||||||
|
const [resolvedSrc, setResolvedSrc] = useState<string | undefined>(
|
||||||
|
needsAuth(src) ? undefined : src,
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!needsAuth(src)) {
|
||||||
|
setResolvedSrc(src);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let objectUrl: string | undefined;
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const res = await apiFetch(toFetchUrl(src!));
|
||||||
|
if (!res.ok) {
|
||||||
|
if (!cancelled) setResolvedSrc(undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const blob = await res.blob();
|
||||||
|
if (cancelled) return;
|
||||||
|
objectUrl = URL.createObjectURL(blob);
|
||||||
|
setResolvedSrc(objectUrl);
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) setResolvedSrc(undefined);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||||
|
};
|
||||||
|
}, [src]);
|
||||||
|
|
||||||
|
return <img src={resolvedSrc} alt={alt} {...rest} />;
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user