Repository navigation
Releases
Releases · arousi/track-email-template
v0.2.0
What's Changed in v0.2.0
1. HMAC-Signed Click-Tracking Redirects (POST /sign-link & GET /c/<tag>)
- Added
POST /sign-link(protected bySTATS_TOKEN) to generate HMAC-SHA256 signed tracking URLs (/c/<tag>?url=...&sig=...). - Added
GET /c/<tag>to verify the signature (preventing open-redirect abuse), log clicks in the newclicksD1 table, send a first-click alert viaWEBHOOK_URL, and redirect (302) to the destination URL.
2. Unopened Follow-Up Reminders (Daily Cron Trigger)
- Added
triggers.crons: ["0 9 * * *"]and ascheduled()handler that checkssent_emailsolder thanFOLLOWUP_DAYS(default4) with zero non-sender-echoopens and zero clicks. - Sends one follow-up reminder via
WEBHOOK_URLand marksreminded_atin D1 so each application is reminded only once.
3. Interactive Telegram Bot Commands (POST /telegram-webhook)
- Added
/telegram-webhook(authorized against the configuredchat_id) supporting:/recent— last 5 sent emails with open and click counts/unopened— sent emails with 0 non-sender-echoopens and 0 clicks/stats <tag>— detailed breakdown for a specific tag
4. High-Interest Re-open Alerts & Proxy Detection
- Added
YahooMailProxy(yahoo-proxy) alongsidegmail-proxy,apple-prefetch,scanner, andsender-echo. - Added a second alert when non-
sender-echoopens reach 3 (High interest (3 opens)), helping spot internal forwarding.
5. Searchable Dashboard & CSV Export (GET /dashboard)
- Added instant client-side search/filtering, a
Clickscolumn, and a one-click Export CSV button (GET /dashboard?format=csv).
Upgrade Notes (from v0.1 / v0.2)
- Run
npm run db:migrate:remote(orALTER TABLE sent_emails ADD COLUMN reminded_at TEXT;+schema.sqlfor existing databases). - Run
npm run deployand optionally register/telegram-webhookvia Telegram'ssetWebhookAPI.
Architecture Overview
track-email-template runs as a single zero-dependency Cloudflare Worker (src/index.js, type: module) backed by Cloudflare D1 (DB binding, email-tracker-db), custom domain TLS routing (custom_domain: true), and a daily Cron Trigger (0 9 * * *).
- Non-Blocking Edge Telemetry (
ctx.waitUntil): Open pixel (GET /p/<tag>.png) and click redirect (GET /c/<tag>) handlers immediately return the 67-byte 1×1 transparent PNG or302redirect while deferring D1 inserts and webhook notifications toctx.waitUntil(...). - Client & Proxy Classification (
classifyClient): Inspects theUser-Agentheader (truncated to 300 characters) and categorizes traffic intogmail-proxy(GoogleImageProxy),yahoo-proxy(YahooMailProxy),apple-prefetch(AppleMailPrivacyProtectionorMozilla/5.0+CFNetwork),scanner(empty UA or bot/crawler/preview regex), orhuman. Opens arriving within15_000ms (ECHO_WINDOW_MS) ofsent_atare reclassified assender-echoto suppress self-open alerts. - Multi-Provider Webhook Alerts (
sendWebhookMessage): Automatically formats outbound alerts for Telegram (api.telegram.org), Discord (discord.com/api/webhooks/), or generic JSON webhooks (WEBHOOK_URL). Alerts trigger on the 1st non-sender-echoopen, 3rd non-sender-echoopen (HIGH_INTEREST_THRESHOLD = 3), 1st click per tag, and daily unopened follow-up sweeps (FOLLOWUP_DAYS, default4).
Endpoint Reference
| Method & Path | Auth | Behavior |
|---|---|---|
GET /health |
None | Liveness probe returning {"ok": true}. |
GET /p/<tag>.png |
None | Matches ^/p/([a-zA-Z0-9_-]{1,64})\.png$. Serves a 67-byte 1×1 transparent PNG with Cache-Control: no-store, no-cache, must-revalidate, max-age=0 (Pragma: no-cache, Expires: 0) and logs the open + client_type asynchronously. |
POST /sign-link |
STATS_TOKEN |
Accepts {"tag", "url"} (TAG_RE + http(s)://), signs ${tag}:${targetUrl} with HMAC-SHA256 via crypto.subtle, and returns {"ok": true, "click_url": ".../c/<tag>?url=...&sig=..."}. |
GET /c/<tag>?url=...&sig=... |
HMAC-SHA256 sig |
Matches ^/c/([a-zA-Z0-9_-]{1,64})$. Verifies STATS_TOKEN is configured, url is http(s)://, and sig matches the 32-char hex HMAC-SHA256 digest (400 / 403 on failure). Logs click asynchronously and responds with 302 redirect. |
POST /sent |
STATS_TOKEN |
Accepts {"tag", "recipient", "subject", "sent_at?"} and upserts into sent_emails (ON CONFLICT(tag) DO UPDATE). |
GET /stats[?tag=<tag>] |
STATS_TOKEN |
Queries sent_emails, opens, and clicks in parallel (Promise.all), returning JSON with sent, open_count, human_open_count, click_count, opens, and clicks (latest 50 sent / 100 opens / 100 clicks when unfiltered). |
GET /dashboard[?format=csv] |
STATS_TOKEN |
Renders a searchable HTML table of the latest 150 sent_emails with aggregated open, human-open, and click counts, or downloads email-tracker-export.csv when format=csv. |
POST /telegram-webhook |
Authorized chat_id |
Handles Telegram bot commands /recent, /unopened, and /stats <tag> when message.chat.id matches TELEGRAM_CHAT_ID or the chat_id in WEBHOOK_URL. |
D1 Persistence (schema.sql)
Three SQLite tables with indexed tag lookups (idx_opens_tag, idx_clicks_tag):
sent_emails:id,tag(UNIQUE),recipient,subject,sent_at,reminded_at.opens:id,tag,opened_at,user_agent,client_type(default'unknown').clicks:id,tag,url,clicked_at,user_agent,client_type(default'unknown').
Security Notes
- Token Scoping: All management and analytics endpoints (
/sign-link,/sent,/stats,/dashboard) requireSTATS_TOKENviaAuthorization: Bearer <token>or?token=<token>. - Open-Redirect Prevention:
GET /c/<tag>enforceshttp(s)://scheme validation and verifies the Web Crypto HMAC-SHA256 signature over${tag}:${targetUrl}keyed bySTATS_TOKEN, returning403 Forbiddenfor tampered or unsigned URLs. - Input & Output Hardening: Tags are constrained to
^[a-zA-Z0-9_-]{1,64}$,User-Agentstrings are capped at 300 characters, all D1 queries use parameterized.bind(...)statements,/dashboardescapes HTML viaescHtml(), and CSV export quotes and escapes cells viacsvCell(). - Telegram Chat Isolation:
/telegram-webhooksilently ignores updates ({"ok": true}) unlessmessage.chat.idmatches the configuredTELEGRAM_CHAT_IDorWEBHOOK_URLchat_id.
v0.2
What's Changed in v0.2
Proxy & Client Classification
- Added Yahoo Mail image proxy detection (
YahooMailProxy→yahoo-proxy), alongsidegmail-proxy(GoogleImageProxy),apple-prefetch,scanner, andsender-echo(15-second post-send grace window).
Privacy-First Template Cleanup
- Removed
country(request.cf.country) collection fromschema.sql,src/index.js(recordOpen,sendWebhookAlert,GET /stats), andREADME.mdso the public template stores only minimal engagement metadata (tag,opened_at,user_agent,client_type).
Upgrade Notes (from v0.1)
- Existing
v0.1D1 databases already have thecountrycolumn; either leave it unused or recreate theopenstable using the updatedschema.sql. - Run
npm run deployafter pullingv0.2.
v0.1
Initial v0.1 release:
- 1x1 transparent PNG tracking pixel (GET /p/.png) with Cloudflare D1 storage
- Client classification (human, gmail-proxy, apple-prefetch, scanner, sender-echo)
- Token-protected POST /sent registration, GET /stats JSON API, and GET /dashboard HTML view
- Optional first-open webhook alerts for Telegram, Discord, and Slack
- Agent-ready package.json, npm scripts, AGENTS.md, and Cloudflare DNS/Email Routing guide
- One-click Deploy to Cloudflare button