Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0c73bf2cdc | |||
| 2c7b5dfd02 | |||
| 5d5db4e766 | |||
| e5dccf1664 | |||
| bfafecedc7 |
@@ -1 +1 @@
|
||||
{".":"3.45.11"}
|
||||
{".":"3.45.12"}
|
||||
|
||||
@@ -5,6 +5,16 @@ All notable changes to PicPeak will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [3.45.12](https://github.com/PicPeak/picpeak/compare/v3.45.11...v3.45.12) (2026-08-02)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **security:** authz/ownership gaps (token binding, auth revocation, feedback/customer ownership, token logging) (stable) ([#951](https://github.com/PicPeak/picpeak/issues/951)) ([5d5db4e](https://github.com/PicPeak/picpeak/commit/5d5db4e766eee23a6678b399cdb9cc449fcea198))
|
||||
* **security:** neutralize spreadsheet formulas in all CSV/export cell-writers (CSV injection cluster) ([#949](https://github.com/PicPeak/picpeak/issues/949)) ([e5dccf1](https://github.com/PicPeak/picpeak/commit/e5dccf166419bb571b052990aada14801e16ac79))
|
||||
* **security:** redact gallery share tokens from analytics tracking (GHSA-7m6c) (stable) ([#953](https://github.com/PicPeak/picpeak/issues/953)) ([2c7b5df](https://github.com/PicPeak/picpeak/commit/2c7b5dfd020ac1fb2acdb7667998b2f373ce99d9))
|
||||
* **security:** unauth share_token leak (HIGH) + restore path-traversal, logo file-read (stable) ([#947](https://github.com/PicPeak/picpeak/issues/947)) ([bfafece](https://github.com/PicPeak/picpeak/commit/bfafecedc755790374565281287b9777ae0f5315))
|
||||
|
||||
## [3.45.11](https://github.com/PicPeak/picpeak/compare/v3.45.10...v3.45.11) (2026-08-01)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* GHSA-2qc2 / GHSA-32h4 / GHSA-3335 — feedback moderation, deletion, and the
|
||||
* pending-moderation list are by-feedback-id (or global) and lacked ownership
|
||||
* scoping, so a restricted editor could act on / enumerate feedback for events
|
||||
* it does not own. super_admin keeps global access.
|
||||
*/
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-fbown-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'fbown-test-secret';
|
||||
process.env.STORAGE_PATH = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-fbown-storage-'));
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const bcrypt = require('bcrypt');
|
||||
const { bootCrmDb, seedMinimal, assignAdminRole, mintAdminToken } = require('../integration/helpers/crmDb');
|
||||
|
||||
describe('feedback ownership scoping', () => {
|
||||
let db; let cleanup; let app;
|
||||
let superTok; let editorTok; let editorId;
|
||||
let foreignFeedbackId;
|
||||
|
||||
const auth = (req, tok) => req.set('Authorization', `Bearer ${tok}`);
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
const { adminId: superId } = await seedMinimal(db);
|
||||
await assignAdminRole(db, superId, 'super_admin');
|
||||
superTok = mintAdminToken(superId);
|
||||
|
||||
const ins = await db('admin_users').insert({
|
||||
username: 'editor', email: 'editor@example.com',
|
||||
password_hash: await bcrypt.hash('x', 4), must_change_password: false, created_at: new Date(),
|
||||
}).returning('id');
|
||||
editorId = ins[0]?.id ?? ins[0];
|
||||
await assignAdminRole(db, editorId, 'editor');
|
||||
editorTok = mintAdminToken(editorId);
|
||||
|
||||
// Event owned by super_admin (NOT the editor).
|
||||
const ev = await db('events').insert({
|
||||
slug: 'fbown-foreign', event_type: 'wedding', event_name: 'Foreign',
|
||||
event_date: '2026-08-01', host_email: 'h@e.com', admin_email: 'a@e.com',
|
||||
password_hash: 'x', share_link: '/g/fbown/s', share_token: 'fbown-share',
|
||||
expires_at: new Date(Date.now() + 7 * 864e5).toISOString(),
|
||||
is_active: 1, is_archived: 0, is_draft: 0, created_by: superId,
|
||||
created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const eventId = ev[0]?.id ?? ev[0];
|
||||
const ph = await db('photos').insert({
|
||||
event_id: eventId, filename: 'p.jpg', path: 'fbown-foreign/p.jpg', type: 'individual',
|
||||
uploaded_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
const photoId = ph[0]?.id ?? ph[0];
|
||||
const fb = await db('photo_feedback').insert({
|
||||
photo_id: photoId, event_id: eventId, feedback_type: 'comment',
|
||||
comment_text: 'hi', is_approved: 0, is_hidden: 0, created_at: new Date().toISOString(),
|
||||
}).returning('id');
|
||||
foreignFeedbackId = fb[0]?.id ?? fb[0];
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/admin/feedback', require('../../src/routes/adminFeedback'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
it('editor cannot moderate feedback on an event it does not own (404)', async () => {
|
||||
const res = await auth(request(app).put(`/api/admin/feedback/feedback/${foreignFeedbackId}/approve`), editorTok);
|
||||
expect(res.status).toBe(404);
|
||||
const row = await db('photo_feedback').where({ id: foreignFeedbackId }).first();
|
||||
expect([false, 0]).toContain(row.is_approved); // untouched
|
||||
});
|
||||
|
||||
it('editor cannot delete foreign feedback, row survives', async () => {
|
||||
const res = await auth(request(app).delete(`/api/admin/feedback/feedback/${foreignFeedbackId}`), editorTok);
|
||||
// Denied either at the events.delete permission layer (editor lacks it →
|
||||
// 403) or the ownership layer (404) — both must leave the row intact.
|
||||
expect([403, 404]).toContain(res.status);
|
||||
expect(await db('photo_feedback').where({ id: foreignFeedbackId }).first()).toBeDefined();
|
||||
});
|
||||
|
||||
it('editor sees no foreign feedback in pending-moderation', async () => {
|
||||
const res = await auth(request(app).get('/api/admin/feedback/feedback/pending-moderation'), editorTok);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.find((f) => f.id === foreignFeedbackId)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('super_admin CAN moderate and see it', async () => {
|
||||
const pending = await auth(request(app).get('/api/admin/feedback/feedback/pending-moderation'), superTok);
|
||||
expect(pending.body.find((f) => f.id === foreignFeedbackId)).toBeDefined();
|
||||
const res = await auth(request(app).put(`/api/admin/feedback/feedback/${foreignFeedbackId}/approve`), superTok);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* GHSA-rh8r-7x3h-36rv — the unauthenticated GET /api/gallery/resolve/:identifier
|
||||
* must NOT return a gallery's secret share_token (nor the share links that
|
||||
* embed it) for a bare *slug* lookup. Slugs appear in gallery URLs and are
|
||||
* guessable; handing back the secret turns a known slug into share-link
|
||||
* access to a no-password gallery. The token is only returned when the caller
|
||||
* resolved via the token / full share link (i.e. already holds it).
|
||||
*/
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-resolve-')), 'db.sqlite',
|
||||
);
|
||||
process.env.JWT_SECRET = process.env.JWT_SECRET || 'resolve-test-secret';
|
||||
process.env.STORAGE_PATH = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-resolve-storage-'));
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const { bootCrmDb, seedMinimal } = require('../integration/helpers/crmDb');
|
||||
|
||||
const SLUG = 'resolve-test-event';
|
||||
const SHARE_TOKEN = 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6';
|
||||
|
||||
describe('GET /api/gallery/resolve/:identifier (GHSA-rh8r)', () => {
|
||||
let db; let cleanup; let app;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ db, cleanup } = await bootCrmDb());
|
||||
await seedMinimal(db);
|
||||
await db('events').insert({
|
||||
slug: SLUG,
|
||||
event_type: 'wedding',
|
||||
event_name: 'Resolve Test',
|
||||
event_date: '2026-08-01',
|
||||
host_email: 'h@example.com',
|
||||
admin_email: 'a@example.com',
|
||||
password_hash: 'x',
|
||||
share_link: `/gallery/${SLUG}/${SHARE_TOKEN}`,
|
||||
share_token: SHARE_TOKEN,
|
||||
require_password: 0, // no-password → the token IS the access credential
|
||||
expires_at: new Date(Date.now() + 7 * 864e5).toISOString(),
|
||||
is_active: 1, is_archived: 0, is_draft: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use('/api/gallery', require('../../src/routes/gallery'));
|
||||
}, 120000);
|
||||
|
||||
afterAll(async () => { if (cleanup) await cleanup(); });
|
||||
|
||||
it('does NOT leak the share_token (or share links) for a bare slug lookup', async () => {
|
||||
const res = await request(app).get(`/api/gallery/resolve/${SLUG}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.slug).toBe(SLUG);
|
||||
expect(res.body.matchType).toBe('slug');
|
||||
// The secret must be absent — and must not sneak out via the share links.
|
||||
expect(res.body.token).toBeUndefined();
|
||||
expect(res.body.share_link).toBeUndefined();
|
||||
expect(res.body.share_url).toBeUndefined();
|
||||
expect(JSON.stringify(res.body)).not.toContain(SHARE_TOKEN);
|
||||
});
|
||||
|
||||
it('DOES return the token when the caller already resolved via the token', async () => {
|
||||
const res = await request(app).get(`/api/gallery/resolve/${SHARE_TOKEN}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.token).toBe(SHARE_TOKEN);
|
||||
expect(res.body.matchType).toMatch(/token/);
|
||||
});
|
||||
|
||||
it('does NOT leak the token via SQL LIKE wildcards in the link_partial fallback', async () => {
|
||||
// Before the escaping fix, an anonymous request of 32 underscores matched
|
||||
// any share_link ending in a 32-char token (`_` = single-char wildcard),
|
||||
// resolved as matchType 'link_partial', and handed back the bearer token.
|
||||
// The share_token here has no underscores, so an escaped LIKE must miss.
|
||||
const res = await request(app).get(`/api/gallery/resolve/${'_'.repeat(SHARE_TOKEN.length)}`);
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body.token).toBeUndefined();
|
||||
expect(JSON.stringify(res.body)).not.toContain(SHARE_TOKEN);
|
||||
});
|
||||
});
|
||||
@@ -99,10 +99,22 @@ describe('resolveLogoFile', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('treats absolute paths as-is when they exist', async () => {
|
||||
it('rejects an absolute path OUTSIDE the storage roots (GHSA-c7x5)', async () => {
|
||||
// The raw-absolute candidate was an arbitrary-file-read primitive
|
||||
// (logo_path: '/etc/passwd' → rasterised into a PDF). Absolute paths
|
||||
// outside the storage roots are now dropped even if they exist.
|
||||
existsSpy.mockImplementation((p) => p === '/abs/path/logo.png');
|
||||
getAppSetting.mockResolvedValue(null);
|
||||
const out = await resolveLogoFile({ logo_path: '/abs/path/logo.png' });
|
||||
expect(out).toBe('/abs/path/logo.png');
|
||||
expect(out).toBeNull();
|
||||
});
|
||||
|
||||
it('still accepts an absolute path INSIDE the storage root', async () => {
|
||||
// The legitimate case: multer stores the uploaded logo under
|
||||
// storage/uploads/logos with an absolute path — that stays resolvable.
|
||||
existsSpy.mockImplementation((p) => p === '/app/storage/uploads/logos/logo.png');
|
||||
getAppSetting.mockResolvedValue(null);
|
||||
const out = await resolveLogoFile({ logo_path: '/app/storage/uploads/logos/logo.png' });
|
||||
expect(out).toBe('/app/storage/uploads/logos/logo.png');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "3.45.11",
|
||||
"version": "3.45.12",
|
||||
"description": "Backend for PicPeak event photo sharing platform",
|
||||
"main": "server.js",
|
||||
"engines": {
|
||||
|
||||
@@ -3,6 +3,7 @@ const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
async function photoAuth(req, res, next) {
|
||||
@@ -89,7 +90,33 @@ async function photoAuth(req, res, next) {
|
||||
|
||||
// Check if it's an admin token (admins can view all photos)
|
||||
if (decoded.type === 'admin') {
|
||||
// For both thumbnails and photos with admin token, allow access
|
||||
// Enforce the same revocation / session-cutoff invalidation that
|
||||
// adminAuth does — otherwise a validly-signed admin JWT keeps
|
||||
// serving photos after logout, password change, or explicit
|
||||
// revocation (GHSA-x55x).
|
||||
if (await isTokenRevoked(decoded)) {
|
||||
return res.status(401).json({ error: 'Session expired' });
|
||||
}
|
||||
// adminAuth also (a) rejects tokens for a now-deactivated admin and
|
||||
// (b) rejects any token minted before the admin's last password
|
||||
// change. Token revocation alone doesn't cover those, so without
|
||||
// these two checks a stale or pre-password-change admin token still
|
||||
// fetches every photo.
|
||||
const admin = await db('admin_users')
|
||||
.where({ id: decoded.id, is_active: formatBoolean(true) })
|
||||
.select('id', 'password_changed_at')
|
||||
.first();
|
||||
if (!admin) {
|
||||
return res.status(401).json({ error: 'Session expired' });
|
||||
}
|
||||
if (admin.password_changed_at) {
|
||||
const passwordChangedSeconds = Math.floor(
|
||||
new Date(admin.password_changed_at).getTime() / 1000
|
||||
);
|
||||
if (decoded.iat < passwordChangedSeconds) {
|
||||
return res.status(401).json({ error: 'Session expired' });
|
||||
}
|
||||
}
|
||||
return next();
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
@@ -8,7 +8,7 @@ const { endSession } = require('../middleware/sessionTimeout');
|
||||
const { validatePasswordStrength } = require('../utils/passwordGenerator');
|
||||
const { handleAsync, validateRequest, successResponse } = require('../utils/routeHelpers');
|
||||
const { NotFoundError, ConflictError, ValidationError } = require('../utils/errors');
|
||||
const { setAdminAuthCookie } = require('../utils/tokenUtils');
|
||||
const { setAdminAuthCookie, clearAdminAuthCookie } = require('../utils/tokenUtils');
|
||||
const { IDENTITY_PRESERVING_NORMALIZE_EMAIL } = require('../utils/emailNormalization');
|
||||
const mfaService = require('../services/mfaService');
|
||||
const router = express.Router();
|
||||
@@ -168,12 +168,21 @@ router.post('/change-password', [
|
||||
|
||||
// Logout
|
||||
router.post('/logout', adminAuth, handleAsync(async (req, res) => {
|
||||
// Get token from header
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
// Use the token adminAuth actually authenticated with (req.token) — it may
|
||||
// have come from the admin_token cookie, not the Authorization header. The
|
||||
// old header-only read skipped revocation entirely for cookie-based logout,
|
||||
// leaving the JWT valid until expiry while reporting a successful logout.
|
||||
const token = req.token;
|
||||
if (token) {
|
||||
// End the session
|
||||
// End the in-memory session AND revoke the JWT (GHSA-cjqh) — the token
|
||||
// is otherwise valid until expiry, so photoAuth/adminAuth would keep
|
||||
// honouring it after logout. isTokenRevoked() checks this store.
|
||||
endSession(token);
|
||||
const { revokeToken } = require('../utils/tokenRevocation');
|
||||
await revokeToken(token, 'logout');
|
||||
}
|
||||
// Clear the auth cookie so the browser stops sending the (now revoked) JWT.
|
||||
clearAdminAuthCookie(res);
|
||||
|
||||
// Log activity
|
||||
await logActivity('admin_logout',
|
||||
|
||||
@@ -11,6 +11,8 @@ const { body, param, query } = require('express-validator');
|
||||
const { adminAuth } = require('../middleware/auth');
|
||||
const { requirePermission } = require('../middleware/permissions');
|
||||
const { requireFeatureFlag } = require('../middleware/requireFeatureFlag');
|
||||
const { filterOwnedEventIds } = require('../middleware/ownership');
|
||||
const { db } = require('../database/db');
|
||||
|
||||
// Hour-entry routes are gated by the hoursLogging master so a direct API hit
|
||||
// can't read/edit/delete/bill logged hours while the feature is off (the
|
||||
@@ -528,9 +530,45 @@ router.put('/:id/events', [
|
||||
body('event_ids.*').isInt({ min: 1 }),
|
||||
], handleAsync(async (req, res) => {
|
||||
validateRequest(req);
|
||||
const customerId = parseInt(req.params.id, 10);
|
||||
const submitted = req.body.event_ids.map(Number);
|
||||
|
||||
// The customer's CURRENT assignments. The "Manage galleries" dialog submits
|
||||
// the full initial list back — including any events owned by OTHER admins —
|
||||
// so we need this to tell "retain an existing foreign assignment" apart from
|
||||
// "newly grant a foreign event".
|
||||
const existingEventIds = (await db('event_customer_assignments')
|
||||
.where('customer_account_id', customerId)
|
||||
.pluck('event_id')).map(Number);
|
||||
const existingSet = new Set(existingEventIds);
|
||||
|
||||
// Events the caller may act on (GHSA-xr6x). A denied id is only acceptable
|
||||
// when the customer ALREADY has that assignment (a foreign event the caller
|
||||
// is merely keeping); a denied id that isn't already assigned is a fresh
|
||||
// attempt to mint access to a foreign/nonexistent event → reject.
|
||||
const { allowed } = await filterOwnedEventIds(req.admin, submitted);
|
||||
const allowedSet = new Set(allowed.map(Number));
|
||||
const illegalNew = submitted.filter((id) => !allowedSet.has(id) && !existingSet.has(id));
|
||||
if (illegalNew.length) {
|
||||
return res.status(403).json({ error: 'One or more events are not yours to assign' });
|
||||
}
|
||||
|
||||
// setAssignmentsForCustomer replaces the FULL assignment list, deleting any
|
||||
// existing row not in the submitted set. A restricted admin must not be able
|
||||
// to revoke another admin's customer↔event links that way, so always retain
|
||||
// the customer's existing assignments to events the caller does NOT own —
|
||||
// regardless of whether the client echoed them back. super_admin owns
|
||||
// everything, so nothing is force-preserved for them.
|
||||
let finalEventIds = allowed.map(Number);
|
||||
if (req.admin.roleName !== 'super_admin' && existingEventIds.length) {
|
||||
const { allowed: ownedExisting } = await filterOwnedEventIds(req.admin, existingEventIds);
|
||||
const ownedExistingSet = new Set(ownedExisting.map(Number));
|
||||
const foreignExisting = existingEventIds.filter((id) => !ownedExistingSet.has(id));
|
||||
finalEventIds = [...new Set([...finalEventIds, ...foreignExisting])];
|
||||
}
|
||||
const result = await customerAccountsService.setAssignmentsForCustomer(
|
||||
parseInt(req.params.id, 10),
|
||||
req.body.event_ids,
|
||||
customerId,
|
||||
finalEventIds,
|
||||
req.admin.id,
|
||||
);
|
||||
successResponse(res, result);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const express = require('express');
|
||||
const { neutralizeSpreadsheetFormula } = require('../utils/spreadsheetSafe');
|
||||
const router = express.Router();
|
||||
const { adminAuth } = require('../middleware/auth');
|
||||
const { requirePermission } = require('../middleware/permissions');
|
||||
@@ -164,6 +165,24 @@ router.get('/events/:eventId/feedback',
|
||||
}
|
||||
);
|
||||
|
||||
// Ownership guard for by-feedback-id routes (GHSA-2qc2 / GHSA-32h4). These
|
||||
// take a :feedbackId (not :eventId), so requireEventOwnership can't apply —
|
||||
// resolve the feedback's event and enforce the same rule (super_admin sees
|
||||
// all; others need to own the event, or it's ownerless/legacy). Returns
|
||||
// false and sends a 404 (not 403 — don't leak which feedback ids exist)
|
||||
// when the caller may not act on it.
|
||||
async function assertOwnsFeedback(req, res, feedbackId) {
|
||||
if (req.admin.roleName === 'super_admin') return true;
|
||||
const fb = await db('photo_feedback').where('id', feedbackId).first('event_id');
|
||||
if (!fb) { res.status(404).json({ error: 'Feedback not found' }); return false; }
|
||||
const event = await db('events').where('id', fb.event_id).first('created_by');
|
||||
if (event && event.created_by && event.created_by !== req.admin.id) {
|
||||
res.status(404).json({ error: 'Feedback not found' });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Moderate feedback (approve/hide/reject)
|
||||
router.put('/feedback/:feedbackId/:action',
|
||||
adminAuth,
|
||||
@@ -171,11 +190,12 @@ router.put('/feedback/:feedbackId/:action',
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { feedbackId, action } = req.params;
|
||||
|
||||
|
||||
if (!['approve', 'hide', 'reject'].includes(action)) {
|
||||
return res.status(400).json({ error: 'Invalid action' });
|
||||
}
|
||||
|
||||
if (!(await assertOwnsFeedback(req, res, feedbackId))) return;
|
||||
|
||||
await feedbackService.moderateFeedback(feedbackId, action, req.admin.id);
|
||||
|
||||
res.json({ success: true });
|
||||
@@ -193,7 +213,8 @@ router.delete('/feedback/:feedbackId',
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { feedbackId } = req.params;
|
||||
|
||||
if (!(await assertOwnsFeedback(req, res, feedbackId))) return;
|
||||
|
||||
await feedbackService.deleteFeedback(feedbackId, req.admin.id);
|
||||
|
||||
res.json({ success: true });
|
||||
@@ -347,7 +368,15 @@ router.get('/feedback/pending-moderation',
|
||||
requirePermission('events.view'),
|
||||
async (req, res) => {
|
||||
try {
|
||||
const pending = await feedbackService.getPendingModeration();
|
||||
// Scope to the caller's owned events unless super_admin (GHSA-3335).
|
||||
let ownedEventIds = null;
|
||||
if (req.admin.roleName !== 'super_admin') {
|
||||
const rows = await db('events')
|
||||
.where((q) => q.whereNull('created_by').orWhere('created_by', req.admin.id))
|
||||
.select('id');
|
||||
ownedEventIds = rows.map((r) => r.id);
|
||||
}
|
||||
const pending = await feedbackService.getPendingModeration(null, ownedEventIds);
|
||||
res.json(pending);
|
||||
} catch (error) {
|
||||
logger.error('Error getting pending moderation:', error);
|
||||
@@ -450,11 +479,13 @@ function convertToCSV(data) {
|
||||
const value = row[header];
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'boolean') return value ? 'yes' : 'no';
|
||||
if (typeof value === 'string'
|
||||
&& (value.includes(',') || value.includes('"') || value.includes('\n') || value.includes('\r'))) {
|
||||
return `"${value.replace(/"/g, '""')}"`;
|
||||
// Formula-neutralize user-controlled cells (guest_name/comment_text)
|
||||
// before quoting — quoting alone doesn't stop `=cmd()` (GHSA-3cw3).
|
||||
const neutralized = neutralizeSpreadsheetFormula(value);
|
||||
if (neutralized.includes(',') || neutralized.includes('"') || neutralized.includes('\n') || neutralized.includes('\r')) {
|
||||
return `"${neutralized.replace(/"/g, '""')}"`;
|
||||
}
|
||||
return value;
|
||||
return neutralized;
|
||||
}).join(',');
|
||||
});
|
||||
|
||||
|
||||
@@ -39,8 +39,13 @@ function serializeGuest(row) {
|
||||
};
|
||||
}
|
||||
|
||||
const { neutralizeSpreadsheetFormula } = require('../utils/spreadsheetSafe');
|
||||
|
||||
function escapeCsvCell(value) {
|
||||
const str = value == null ? '' : String(value);
|
||||
// Neutralize spreadsheet formulas FIRST (a `=cmd()` guest name executes on
|
||||
// open — RFC-4180 quoting doesn't stop it), then quote-wrap (GHSA-wc99 /
|
||||
// GHSA-f4fp).
|
||||
const str = neutralizeSpreadsheetFormula(value);
|
||||
if (/[,"\n\r]/.test(str)) {
|
||||
return `"${str.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
@@ -502,6 +502,15 @@ router.get('/export', adminAuth, requirePermission('settings.view'), async (req,
|
||||
/**
|
||||
* Helper function to convert data to CSV
|
||||
*/
|
||||
const { neutralizeSpreadsheetFormula } = require('../utils/spreadsheetSafe');
|
||||
|
||||
function csvCell(value) {
|
||||
// Formula-neutralize, then RFC-4180 quote (the previous join('') did
|
||||
// neither — GHSA-37p4).
|
||||
const s = neutralizeSpreadsheetFormula(value);
|
||||
return /[,"\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||
}
|
||||
|
||||
function convertToCSV(data) {
|
||||
// Simplified CSV conversion for security logs
|
||||
const headers = ['timestamp', 'event_type', 'client_ip', 'details'];
|
||||
@@ -511,8 +520,8 @@ function convertToCSV(data) {
|
||||
log.client_ip,
|
||||
JSON.stringify(log.details || {})
|
||||
]);
|
||||
|
||||
return [headers.join(','), ...rows.map(row => row.join(','))].join('\n');
|
||||
|
||||
return [headers.join(','), ...rows.map(row => row.map(csvCell).join(','))].join('\n');
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
@@ -84,9 +84,20 @@ router.get('/resolve/:identifier', handleAsync(async (req, res) => {
|
||||
}
|
||||
|
||||
const { event, matchType, shareToken } = result;
|
||||
const linkVariants = await buildShareLinkVariants({ slug: event.slug, shareToken });
|
||||
const requiresPassword = !(event.require_password === false || event.require_password === 0 || event.require_password === '0');
|
||||
|
||||
// The share_token is a bearer secret. Only return it (and the share
|
||||
// links/URLs that embed it) when the caller already proved they hold it —
|
||||
// i.e. they resolved via the token or the full share link. A bare *slug*
|
||||
// lookup (slugs appear in gallery URLs and are guessable) must NOT hand
|
||||
// back the secret, or an anonymous caller could turn a known slug into
|
||||
// share-link access to a no-password gallery (GHSA-rh8r).
|
||||
const callerHasToken = matchType !== 'slug';
|
||||
if (!callerHasToken) {
|
||||
return res.json({ slug: event.slug, matchType, requires_password: requiresPassword });
|
||||
}
|
||||
|
||||
const linkVariants = await buildShareLinkVariants({ slug: event.slug, shareToken });
|
||||
res.json({
|
||||
slug: event.slug,
|
||||
token: shareToken,
|
||||
|
||||
@@ -338,6 +338,14 @@ router.get('/:slug/secure-download/:photoId/:token',
|
||||
return res.status(403).json({ error: 'Invalid or expired token' });
|
||||
}
|
||||
|
||||
// Bind the token to the photo it was minted for (GHSA-crxv) — the
|
||||
// /secure serve route does this, but secure-download did not, so a
|
||||
// token minted for photo A could download photo B (incl. a hidden one).
|
||||
const tokenPhotoId = Number(tokenValidation.data?.photoId);
|
||||
if (!Number.isInteger(tokenPhotoId) || tokenPhotoId !== Number(photoId)) {
|
||||
return res.status(403).json({ error: 'Token not valid for this photo' });
|
||||
}
|
||||
|
||||
// Verify photo exists
|
||||
const photo = await db('photos')
|
||||
.where({ id: photoId, event_id: req.event.id })
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const archiver = require('archiver');
|
||||
const { neutralizeSpreadsheetFormula } = require('../utils/spreadsheetSafe');
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
@@ -261,12 +262,13 @@ function convertToCSV(data) {
|
||||
|
||||
const csvRows = data.map(row => {
|
||||
return headers.map(header => {
|
||||
const value = row[header];
|
||||
// Escape quotes and wrap in quotes if contains comma
|
||||
if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
|
||||
// Formula-neutralize before quoting (guest_name/comment_text are
|
||||
// user-controlled); the old check didn't even escape \n/\r (GHSA-q82f).
|
||||
const value = neutralizeSpreadsheetFormula(row[header]);
|
||||
if (value.includes(',') || value.includes('"') || value.includes('\n') || value.includes('\r')) {
|
||||
return `"${value.replace(/"/g, '""')}"`;
|
||||
}
|
||||
return value || '';
|
||||
return value;
|
||||
}).join(',');
|
||||
});
|
||||
|
||||
|
||||
@@ -400,7 +400,7 @@ class FeedbackService {
|
||||
/**
|
||||
* Get feedback requiring moderation
|
||||
*/
|
||||
async getPendingModeration(eventId = null) {
|
||||
async getPendingModeration(eventId = null, ownedEventIds = null) {
|
||||
try {
|
||||
let query = db('photo_feedback')
|
||||
.join('photos', 'photo_feedback.photo_id', 'photos.id')
|
||||
@@ -408,9 +408,13 @@ class FeedbackService {
|
||||
.where('photo_feedback.is_approved', false)
|
||||
.where('photo_feedback.is_hidden', false)
|
||||
.where('photo_feedback.feedback_type', 'comment');
|
||||
|
||||
|
||||
if (eventId) {
|
||||
query = query.where('photo_feedback.event_id', eventId);
|
||||
} else if (Array.isArray(ownedEventIds)) {
|
||||
// Scope to the caller's owned events (GHSA-3335) — an empty set
|
||||
// matches nothing, so a restricted admin sees only their own.
|
||||
query = query.whereIn('photo_feedback.event_id', ownedEventIds.length ? ownedEventIds : [-1]);
|
||||
}
|
||||
|
||||
const pending = await query
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
const archiver = require('archiver');
|
||||
const { PassThrough } = require('stream');
|
||||
const { XmpGenerator } = require('./xmpGenerator');
|
||||
const { neutralizeSpreadsheetFormula } = require('../utils/spreadsheetSafe');
|
||||
const { db } = require('../database/db');
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
@@ -162,7 +163,10 @@ class PhotoExportService {
|
||||
|
||||
const csvContent = [
|
||||
headers.join(','),
|
||||
...rows.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
|
||||
// Formula-neutralize each cell before quoting — filenames/categories
|
||||
// are user-controlled, and quoting alone doesn't stop `=cmd()`
|
||||
// execution (GHSA-5364).
|
||||
...rows.map(row => row.map(cell => `"${neutralizeSpreadsheetFormula(cell).replace(/"/g, '""')}"`).join(','))
|
||||
].join('\n');
|
||||
|
||||
return {
|
||||
|
||||
@@ -1047,7 +1047,9 @@ async function sendQuote(id, adminId) {
|
||||
});
|
||||
|
||||
try {
|
||||
await logActivity('quote_sent', { quoteId: id, token }, null, `admin:${adminId}`);
|
||||
// Do NOT log the raw bearer token — it grants quote actions and the
|
||||
// activity log is readable later (GHSA-prch). The quoteId is the audit key.
|
||||
await logActivity('quote_sent', { quoteId: id }, null, `admin:${adminId}`);
|
||||
} catch (_) {}
|
||||
|
||||
// Fire the quote.sent workflow trigger (best-effort; emit is fail-closed when
|
||||
@@ -1272,7 +1274,8 @@ async function recordResponse({ token, action, ip, tosAccepted }) {
|
||||
});
|
||||
|
||||
try {
|
||||
await logActivity(`quote_${newStatus}`, { quoteId: quote.id, token: tokenRow.token }, null, 'customer:public');
|
||||
// Raw bearer token must not reach the activity log (GHSA-prch).
|
||||
await logActivity(`quote_${newStatus}`, { quoteId: quote.id }, null, 'customer:public');
|
||||
} catch (_) {}
|
||||
|
||||
// Defer the workflow emit until the 15-min toggle window locks — so accepting
|
||||
|
||||
@@ -12,6 +12,15 @@ const backupManifest = require('./backupManifest');
|
||||
const S3StorageAdapter = require('./storage/s3Storage');
|
||||
const { queueEmail } = require('./emailProcessor');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
|
||||
// A manifest is attacker-influenceable (hand-crafted backup). Reject any
|
||||
// entry path that would resolve OUTSIDE its intended base directory
|
||||
// (traversal / absolute path) before any fs write. The target may not exist
|
||||
// yet, so resolve rather than realpath (GHSA-fm58).
|
||||
function pathEscapes(baseDir, candidate) {
|
||||
const rel = path.relative(path.resolve(baseDir), path.resolve(candidate));
|
||||
return !rel || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel);
|
||||
}
|
||||
const { formatBytes } = require('../utils/formatBytes');
|
||||
const os = require('os');
|
||||
|
||||
@@ -771,7 +780,14 @@ class RestoreService {
|
||||
for (const file of filesToDownload) {
|
||||
const s3Key = path.posix.join(prefix, file.path);
|
||||
const localFilePath = path.join(localPath, file.path);
|
||||
|
||||
|
||||
// Containment guard (GHSA-fm58): reject a manifest path that would
|
||||
// write outside the download staging dir.
|
||||
if (pathEscapes(localPath, localFilePath)) {
|
||||
this.log('error', `Refusing unsafe manifest path on download: ${file.path}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await fs.mkdir(path.dirname(localFilePath), { recursive: true });
|
||||
|
||||
try {
|
||||
@@ -1204,6 +1220,14 @@ END $$;`
|
||||
const sourcePath = path.join(backupPath, file.path);
|
||||
const targetPath = path.join(storagePath, file.path);
|
||||
|
||||
// Containment guard (GHSA-fm58): a crafted manifest path like
|
||||
// `../../etc/cron.d/x` would otherwise escape the storage root and
|
||||
// overwrite arbitrary files. Skip any entry that escapes.
|
||||
if (pathEscapes(backupPath, sourcePath) || pathEscapes(storagePath, targetPath)) {
|
||||
errors.push(`Refusing unsafe manifest path: ${file.path}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if source file exists
|
||||
try {
|
||||
await fs.access(sourcePath);
|
||||
@@ -1375,6 +1399,15 @@ END $$;`
|
||||
|
||||
for (const file of filesToVerify) {
|
||||
const filePath = path.join(storagePath, file.path);
|
||||
// Same containment guard as performFilesRestore: a traversal
|
||||
// manifest entry (e.g. `../../etc/passwd`) was skipped during the
|
||||
// restore, so it must not be fs.access'd/hashed here either —
|
||||
// otherwise an existing outside file makes the skipped entry look
|
||||
// "verified" (and we'd read an arbitrary file off disk).
|
||||
if (pathEscapes(storagePath, filePath)) {
|
||||
verification.errors.push(`Refusing unsafe manifest path on verification: ${file.path}`);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await fs.access(filePath);
|
||||
|
||||
|
||||
@@ -159,7 +159,16 @@ const resolveShareIdentifier = async (identifier) => {
|
||||
return { event, matchType: 'link', shareToken: getEventShareToken(event) };
|
||||
}
|
||||
|
||||
event = await baseQuery.clone().where('share_link', 'like', `%/${trimmed}`).first();
|
||||
// GHSA-rh8r hardening: `trimmed` is attacker-controlled, so escape LIKE
|
||||
// wildcards (`%`, `_`, and the escape char itself) before embedding it.
|
||||
// Otherwise an anonymous `/resolve/________…________` (32 underscores)
|
||||
// matches ANY share_link via single-char wildcards, resolves as
|
||||
// matchType 'link_partial', and the /resolve route hands back the
|
||||
// gallery's bearer token — reopening the very hole the token-withholding
|
||||
// fix closed. Explicit ESCAPE clause because SQLite has no default LIKE
|
||||
// escape character (Postgres defaults to backslash, but we set it for both).
|
||||
const likeTail = `%/${trimmed.replace(/[\\%_]/g, (c) => `\\${c}`)}`;
|
||||
event = await baseQuery.clone().whereRaw('share_link LIKE ? ESCAPE \'\\\'', [likeTail]).first();
|
||||
if (event) {
|
||||
return { event, matchType: 'link_partial', shareToken: getEventShareToken(event) };
|
||||
}
|
||||
|
||||
@@ -57,18 +57,34 @@ function generateCandidates(raw, storageRoot) {
|
||||
if (!value) return [];
|
||||
const stripped = value.replace(/^\/+/, '');
|
||||
const baseName = path.basename(value);
|
||||
const cwdStorage = path.join(process.cwd(), 'storage');
|
||||
// Build candidate set; dedup at the end so we don't stat the same
|
||||
// file twice when the inputs overlap.
|
||||
const candidates = [
|
||||
path.isAbsolute(value) ? value : null,
|
||||
// Keep the raw absolute value as a candidate so a legitimate multer path
|
||||
// (branding_logo_path is stored absolute) or an absolute logo inside a
|
||||
// non-standard storage subdir still resolves. The containment filter
|
||||
// below is what enforces safety — it drops this candidate when it points
|
||||
// outside the storage roots, so `/etc/passwd` is still rejected.
|
||||
...(path.isAbsolute(value) ? [value] : []),
|
||||
path.join(storageRoot, stripped),
|
||||
path.join(storageRoot, 'uploads', 'logos', baseName),
|
||||
path.join(storageRoot, 'branding', baseName),
|
||||
path.join(process.cwd(), 'storage', stripped),
|
||||
path.join(process.cwd(), 'storage', 'uploads', 'logos', baseName),
|
||||
path.join(process.cwd(), 'storage', 'branding', baseName),
|
||||
].filter(Boolean);
|
||||
return [...new Set(candidates)];
|
||||
path.join(cwdStorage, stripped),
|
||||
path.join(cwdStorage, 'uploads', 'logos', baseName),
|
||||
path.join(cwdStorage, 'branding', baseName),
|
||||
];
|
||||
// GHSA-c7x5: only read logo files INSIDE the storage roots. An admin-set
|
||||
// logo_path of `/etc/passwd` was previously rasterised into a PDF; the
|
||||
// filter below drops any candidate (including the raw absolute one and any
|
||||
// `..`-escaping stripped path) that resolves outside the roots. baseName-
|
||||
// based candidates are inherently contained.
|
||||
const roots = [path.resolve(storageRoot), path.resolve(cwdStorage)];
|
||||
const contained = candidates.filter((c) => {
|
||||
const r = path.resolve(c);
|
||||
return roots.some((root) => r === root || r.startsWith(root + path.sep));
|
||||
});
|
||||
return [...new Set(contained)];
|
||||
}
|
||||
|
||||
function pickExisting(candidates) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "picpeak-frontend",
|
||||
"private": true,
|
||||
"version": "3.45.11",
|
||||
"version": "3.45.12",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -3,7 +3,7 @@ import { BrowserRouter as Router, Routes, Route, Navigate, useParams } from 'rea
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { ToastContainer } from 'react-toastify';
|
||||
import 'react-toastify/dist/ReactToastify.css';
|
||||
import { analyticsService } from './services/analytics.service';
|
||||
import { analyticsService, AnalyticsRouteTracker } from './services/analytics.service';
|
||||
|
||||
import { GalleryAuthProvider, MaintenanceProvider } from './contexts';
|
||||
import { ThemeProvider } from './contexts/ThemeContext';
|
||||
@@ -115,8 +115,10 @@ function AnalyticsBootstrap() {
|
||||
provider: 'rybbit',
|
||||
hostUrl: settings.rybbit_url,
|
||||
websiteId: settings.rybbit_website_id,
|
||||
autoTrack: true,
|
||||
doNotTrack: true,
|
||||
// Mask every /gallery/* path (they embed the share token) so Rybbit's
|
||||
// auto-tracked page views never carry the secret (GHSA-7m6c).
|
||||
maskPatterns: ['/gallery/**'],
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -138,7 +140,9 @@ function AnalyticsBootstrap() {
|
||||
provider: 'umami',
|
||||
hostUrl: settings.umami_url,
|
||||
websiteId: settings.umami_website_id,
|
||||
autoTrack: true,
|
||||
// autoTrack omitted → data-auto-track="false": Umami must NOT read the
|
||||
// raw window.location (token leak). Page views come from the manual,
|
||||
// sanitized AnalyticsRouteTracker instead (GHSA-7m6c).
|
||||
doNotTrack: true,
|
||||
});
|
||||
return;
|
||||
@@ -151,7 +155,7 @@ function AnalyticsBootstrap() {
|
||||
provider: 'umami',
|
||||
hostUrl: envUmamiUrl,
|
||||
websiteId: envUmamiWebsiteId,
|
||||
autoTrack: true,
|
||||
// autoTrack omitted → data-auto-track="false" (see above, GHSA-7m6c).
|
||||
doNotTrack: true,
|
||||
});
|
||||
}
|
||||
@@ -194,6 +198,7 @@ function App() {
|
||||
<DynamicFavicon />
|
||||
<RobotsMetaTags />
|
||||
<Router>
|
||||
<AnalyticsRouteTracker />
|
||||
<MaintenanceWrapper>
|
||||
<SkipLink />
|
||||
<Routes>
|
||||
|
||||
@@ -29,6 +29,9 @@ interface RybbitInitConfig extends BaseInitConfig {
|
||||
provider: 'rybbit';
|
||||
websiteId: string;
|
||||
hostUrl: string;
|
||||
// URL path patterns whose value must never reach the collector (they embed
|
||||
// the gallery share token). Rendered into Rybbit's data-mask-patterns.
|
||||
maskPatterns?: string[];
|
||||
}
|
||||
|
||||
interface CustomInitConfig extends BaseInitConfig {
|
||||
@@ -56,7 +59,7 @@ declare global {
|
||||
};
|
||||
rybbit?: {
|
||||
event: (eventName: string, eventData?: any) => void;
|
||||
pageview?: () => void;
|
||||
pageview?: (path?: string) => void;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -85,7 +88,12 @@ class AnalyticsService {
|
||||
script.defer = true;
|
||||
script.src = `${config.hostUrl.replace(/\/+$/, '')}/script.js`;
|
||||
script.setAttribute('data-website-id', config.websiteId);
|
||||
if (config.autoTrack === false) script.setAttribute('data-auto-track', 'false');
|
||||
// Auto-track OFF by default (GHSA-7m6c): Umami's auto page-view capture
|
||||
// reads window.location verbatim, so a gallery URL /gallery/:slug/:token
|
||||
// would ship the secret share token to the analytics collector. Page
|
||||
// views are fired manually through trackPageView(), which redacts the
|
||||
// token. Only an explicit autoTrack:true opts back into raw capture.
|
||||
if (config.autoTrack !== true) script.setAttribute('data-auto-track', 'false');
|
||||
if (config.doNotTrack !== false) script.setAttribute('data-do-not-track', 'true');
|
||||
if (config.domains?.length) script.setAttribute('data-domains', config.domains.join(','));
|
||||
document.head.appendChild(script);
|
||||
@@ -100,6 +108,16 @@ class AnalyticsService {
|
||||
script.defer = true;
|
||||
script.src = `${config.hostUrl.replace(/\/+$/, '')}/api/script.js`;
|
||||
script.setAttribute('data-site-id', config.websiteId);
|
||||
// GHSA-7m6c: Rybbit auto-tracks page views (initial load + SPA route
|
||||
// changes) reading window.location, so a gallery URL would ship the raw
|
||||
// share token. Unlike Umami we CAN'T fix this with a manual tracker —
|
||||
// the initial-load pageview fires before any of our code runs. Instead
|
||||
// use Rybbit's native data-mask-patterns, which replaces matching paths
|
||||
// with the pattern string in analytics, stripping the token on every
|
||||
// auto-tracked pageview including the first.
|
||||
if (config.maskPatterns?.length) {
|
||||
script.setAttribute('data-mask-patterns', JSON.stringify(config.maskPatterns));
|
||||
}
|
||||
document.head.appendChild(script);
|
||||
} else if (config.provider === 'custom') {
|
||||
// The admin-pasted HTML is sanitised server-side (see
|
||||
@@ -148,13 +166,35 @@ class AnalyticsService {
|
||||
// 'none' / 'custom' / unloaded → silently ignore.
|
||||
}
|
||||
|
||||
// Redact secrets from a URL before it reaches the analytics collector
|
||||
// (GHSA-7m6c): drop the query string entirely and replace token-looking
|
||||
// path segments (long hex / opaque IDs — e.g. the gallery share token in
|
||||
// /gallery/:slug/:token) with a placeholder. Failing safe: on any parse
|
||||
// issue return just the pathname without the query.
|
||||
private sanitizeTrackedUrl(url: string): string {
|
||||
try {
|
||||
const pathOnly = url.split('?')[0].split('#')[0];
|
||||
return pathOnly
|
||||
.split('/')
|
||||
.map((seg) =>
|
||||
/^[0-9a-fA-F]{16,}$/.test(seg) || /^[A-Za-z0-9_-]{20,}$/.test(seg) ? '[redacted]' : seg)
|
||||
.join('/');
|
||||
} catch {
|
||||
return url.split('?')[0];
|
||||
}
|
||||
}
|
||||
|
||||
trackPageView(url?: string, referrer?: string) {
|
||||
if (!this.initialized) return;
|
||||
if (this.provider === 'umami' && typeof window !== 'undefined' && window.umami) {
|
||||
window.umami.trackView(url, referrer, this.websiteId || undefined);
|
||||
} else if (this.provider === 'rybbit' && typeof window !== 'undefined' && window.rybbit?.pageview) {
|
||||
window.rybbit.pageview();
|
||||
}
|
||||
// Only Umami is manually tracked here: its auto-track is disabled (so the
|
||||
// raw token URL never hits the collector) and this sanitized call is the
|
||||
// ONLY page-view source. Rybbit keeps its own auto-tracking with
|
||||
// data-mask-patterns doing the redaction, so a manual call would
|
||||
// double-count — skip it. 'none'/'custom' have no page-view API.
|
||||
if (this.provider !== 'umami' || typeof window === 'undefined' || !window.umami) return;
|
||||
const raw = url ?? window.location.pathname;
|
||||
const safe = this.sanitizeTrackedUrl(raw);
|
||||
window.umami.trackView(safe, referrer, this.websiteId || undefined);
|
||||
}
|
||||
|
||||
// Gallery-specific tracking events
|
||||
@@ -209,3 +249,13 @@ export const useAnalytics = () => {
|
||||
|
||||
return analyticsService;
|
||||
};
|
||||
|
||||
// Renderless component that drives manual page-view tracking. MUST be mounted
|
||||
// INSIDE <Router> (useLocation needs router context) — that's why the
|
||||
// AnalyticsBootstrap init, which lives outside the Router, can't do this
|
||||
// itself. Without a mounted caller trackPageView never fires and Umami — whose
|
||||
// auto-track we deliberately disable — records nothing.
|
||||
export const AnalyticsRouteTracker = (): null => {
|
||||
useAnalytics();
|
||||
return null;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user