@paubox/tracking
v0.7.1
Published
HIPAA-compliant first-party analytics snippet for Paubox products
Readme
@paubox/tracking
HIPAA-compliant first-party analytics for Paubox products.
This repo ships:
@paubox/tracking— a TypeScript snippet library (ESM + CJS) that instruments Next.js pages with page views, click events, time-on-page, and login events.dist/pb.js— the same library as a self-contained IIFE bundle for<script>-tag installs on properties that are not Paubox-built React apps. Served bypaubox_tracking_apiat/tracking/pb.js.paubox-next-integration/— ready-to-copy files forpaubox-next: the ingest API route, database schema, PII scrubber, rate limiter, and the CSM Administrator analytics dashboard.hubspot-integration/— the snippet installed on the HubSpot marketing site, kept here because HubSpot CMS pages live in no repository.
Where it is installed
| Property | Platform | Surface | Install |
| --- | --- | --- | --- |
| next.paubox.com | Next.js | dashboard, auth, forms, … | npm package + PauboxAnalyticsProvider |
| www.paubox.com | HubSpot CMS | marketing | hubspot-integration/snippet.html in Site header HTML |
| docs.paubox.com | Mintlify | docs | paubox-analytics.js in the pb_mintlify repo |
The authenticated app tracks by default (product telemetry on a contractual
surface). The two public properties store nothing and send nothing until the
visitor accepts analytics cookies, and their stored IPs are truncated. See
identity-stitching-review.md for why activity
is not linked across these properties.
Why first-party?
Third-party analytics tools cannot receive PHI under HIPAA without a signed BAA and rigorous data-handling controls. Paubox Dashboard pages may contain PHI in URL paths. This system keeps all data inside Paubox-owned infrastructure: an encrypted AWS RDS PostgreSQL instance with AES-256 at rest and TLS 1.3 in transit.
Repository layout
paubox-tracking/
├── src/ # @paubox/tracking library source
│ ├── index.ts # public exports
│ ├── types.ts # shared TypeScript interfaces
│ ├── tracker.ts # event queue + flush logic
│ ├── session.ts # anon_id, session_id, session count
│ ├── page-view.ts # route-change listener (Next router or history shim)
│ ├── history-router.ts # History API -> Next-router-shaped adapter
│ ├── click-tracker.ts # document-level delegated click listener
│ ├── time-on-page.ts # Page Visibility API timer
│ ├── login-meta.ts # login success/failure helpers
│ ├── attribution.ts # UTM allow-list + referrer host (public surfaces)
│ ├── consent.ts # consent state, GPC/DNT detection
│ ├── browser.ts # IIFE entry -> window.PauboxTracking
│ └── PauboxAnalyticsProvider.tsx # React provider component
│
├── hubspot-integration/ # Snippet + install steps for www.paubox.com
│ ├── README.md
│ └── snippet.html
│
└── paubox-next-integration/ # Files to copy into paubox-next
├── migrations/
│ └── 001_analytics_events.sql
├── src/
│ ├── components/PauboxAnalytics/index.tsx
│ ├── lib/analytics/ # db, scrub, bot-filter, rate-limit, queries
│ ├── pages/api/analytics/event.ts
│ ├── pages/api/admin/analytics/
│ └── views/Admin/Analytics/
├── routePolicy.patch.ts
└── sidebarOptions.patch.tsGetting started
Prerequisites
- Node.js 18+
- npm 9+
Install
npm installBuild the library
npm run build # outputs dist/ (ESM + CJS + .d.ts)
npm run dev # watch modeTest
npm testLint
npm run lintType-check
npm run typecheckUsing the script-tag bundle (HubSpot, Mintlify)
npm run build emits dist/pb.js alongside the ESM/CJS library: a minified,
self-contained IIFE with no React or Next imports. paubox_tracking_api bakes it
into its container image and serves it, so instrumented properties load it from the
same origin they post events to.
<script src="https://apx.paubox.com/tracking/pb.js" async></script>Then, once loaded:
window.PauboxTracking.init({
endpoint: 'https://apx.paubox.com/tracking/api/analytics/event',
surface: 'marketing',
consent: 'required',
autocapture: true,
});
// Call when the visitor accepts analytics cookies.
window.PauboxTracking.grantConsent();window.PauboxTracking exposes init, track, flush, grantConsent,
revokeConsent, consentState, and destroy. init is idempotent, so a snippet
included twice — or re-executed by a client-side router, as Mintlify does — will not
double-count.
Navigation is picked up through createHistoryRouter(), which patches
pushState/replaceState and listens for popstate, presenting the same interface
the Next.js router does. That is why attachPageViewListener and
attachTimeOnPageListener are shared unchanged between both installs.
Two delivery paths exist: /tracking/pb.js is a moving alias with a 5-minute TTL,
and /tracking/{version}/pb.js is immutable and cached for a year. Prefer the alias
unless you specifically need to pin a build.
See hubspot-integration/ for the marketing-site snippet and paubox-analytics.js
in the pb_mintlify repo for the docs site.
Using the library in paubox-next
1. Install the package
Until published to a registry, install as a local path dependency:
# from paubox-next directory
npm install ../paubox-tracking2. Add the provider to _app.tsx
import { PauboxAnalytics } from 'components/PauboxAnalytics';
// Inside the provider tree, after Auth0Provider and Core:
<PauboxAnalytics>
{children}
</PauboxAnalytics>PauboxAnalytics reads user.sub from useAuth0() and customer.id from useCustomer(), then passes them to the tracker automatically.
3. Instrument click targets
Add data-pb-track to any element you want to capture clicks on:
<button data-pb-track="send_email_btn">Send</button>
<a data-pb-track="nav_compose" href="/compose">Compose</a>Clicks on elements without this attribute are silently ignored.
4. Copy integration files
Copy the contents of paubox-next-integration/ into the corresponding paths in paubox-next. Apply the two small edits described in routePolicy.patch.ts and sidebarOptions.patch.ts.
5. Run the database migration
psql $ANALYTICS_DATABASE_URL -f paubox-next-integration/migrations/001_analytics_events.sql6. Set environment variables
# .env.local in paubox-next
ANALYTICS_DATABASE_URL=postgresql://user:pass@host/analytics?sslmode=verify-fullData collected
| Category | What is stored |
|---|---|
| Page views | URL path (no query string, no hash), surface, timestamp |
| Time on page | Total duration ms, visible (tab-active) ms |
| Clicks | data-pb-track label, element tag, href path |
| Sessions | Session count per user, session ID per browser session |
| Login events | Success/failure, Auth0 error code on failure |
| Login metadata | City, region, country (IP-derived at ingest); browser, OS, device type (UA-derived at ingest) |
| Identity | Auth0 sub (opaque string) — never email, name, or picture |
| Org context | Paubox customer.id (integer) |
| Attribution (public surfaces only) | utm_source, utm_medium, utm_campaign, utm_term, utm_content, gclid, msclkid, and the referring host — never a full referrer URL |
Never stored: full URLs, query strings, email addresses, names, profile data, mouse positions, screen recordings.
Autocapture records structural descriptors only (tag, name, aria-label, form name,
button text). It never reads an input's value. Add data-pb-no-capture to an
element or form to exclude it entirely.
Differences on public surfaces (marketing, docs)
- Consent required.
init({ consent: 'required' })writes nothing to the device and sends nothing untilgrantConsent(). Events buffer in memory (capped) meanwhile; the identifiers are ephemeral until consent, at which point they are persisted and the buffer is back-filled so the visit is not split. - GPC and DNT are honoured regardless of the consent mode, and cannot be
overridden by a later
grantConsent()call. - IPs are truncated to /24 (IPv4) or /48 (IPv6) before storage, after the geo lookup, so city and region still resolve.
- No
user_idorcustomer_id. These visitors are anonymous, and their activity is not linked to product accounts — seeidentity-stitching-review.md.
Security & HIPAA notes
- Encryption at rest: AES-256 via AWS RDS storage encryption (KMS customer-managed key)
- Encryption in transit: TLS 1.2 minimum; connection string requires
sslmode=verify-full - PII scrubbing: ingest route scans
page_pathandpropertiesfor email, SSN, and credit card patterns and redacts before storage - Attribution allow-list: enforced on the client and again at ingest.
propertiesis free-form and the endpoint is public, so the browser-side list constrains our own snippet, not a hand-built POST - Bot filtering:
isbotpackage drops known crawler User-Agents before any DB write - Rate limiting: per-IP sliding window,
ANALYTICS_MAX_EVENTS_PER_MINUTE(default 600); always responds 204 (never reveals limit state). Because rejections are invisible to the client, alert onanalytics_requests_rejected_total{reason="rate_limited"} - Retention:
ANALYTICS_RETENTION_DAYS(default 395); a background sweeper deletes older events in batches - Access control: analytics data is readable only by
super_adminusers via the CSM Administrator dashboard - Origin allow-list:
ANALYTICS_ALLOWED_ORIGINSmust name every instrumented property. The service's CORS layer is broader (any*.paubox.com/*.paubox.net), so a new property passes CORS and is then silently dropped until it is listed
License
Apache 2.0 — see LICENSE.
