cfw-mailbox-open-tracking
GitHub用于开发和维护邮件打开追踪扩展,涵盖像素Token、HMAC签名、公开路由、发送状态及隐私规则等功能的实现与测试。
Trigger Scenarios
Install
npx skills add Prastavna/cfw-mailbox --skill cfw-mailbox-open-tracking -g -y
SKILL.md
Frontmatter
{
"name": "cfw-mailbox-open-tracking",
"license": "Apache-2.0",
"description": "Work on the cfw-mailbox Open Tracking extension. Use for pixel tokens, HMAC signing\/verification, the public \/t\/ route, open counts, the composer tracking switch, sent-message status, TRACKING_SECRET, Access\/Bot Fight rules for the pixel, privacy, or tracking tests."
}
cfw-mailbox Open Tracking
An optional, per-user extension that records when a recipient's mail app fetches an image from a message the user chose to track. It is deliberately approximate: proxies may fetch images on delivery, and many clients block images until the reader asks for them.
Key files
extensions/tracking/pixel.ts token sign/verify, URL, 1×1 GIF, response headers
extensions/tracking/route.ts public GET/HEAD /t/ handler
extensions/tracking/routes.ts /api/extensions/tracking settings
workers/index.ts dispatches /t/* before the React Router fallback
workers/api/index.ts send route: checks settings, picks the origin
workers/mailbox/MailboxDO.ts sendDraft, deliver, recordOpen, migration 10
workers/email/outbound.ts withTrackingPixel + buildEmail injection
shared/api.ts OpenTracking, DraftFields.trackOpens, SendResult.tracking
shared/extensions.ts TrackingSettings
app/components/extensions/
TrackingSettingsDialog.tsx on/off and “track by default”
app/components/mail/compose/
ComposeWindow.tsx “Track opens” switch, saved with the draft
app/components/mail/ThreadView.tsx open status line on sent messages
app/lib/extensions.ts useTrackingReady, settings hooks
test/tracking.test.ts token, send, pixel, cleanup and migration tests
e2e/tracking.spec.ts settings, composer and status E2E
Data model (mailbox migration 10)
messages.track_opens— the composer's saved preference for the draft. It is not evidence that a message was sent with tracking.messages.tracking_origin— set only when a tracked send is queued. This is the markergetThreaduses; it is cleared bycancelSendand by a permanent send failure, but the preference is kept.message_opens— one row per message:first_opened_at,last_opened_at,open_count. No IP, no user agent.- An
AFTER DELETE ON messagestrigger removes the open row; do not rely on foreign-key enforcement.
MessageDetail.openTracking is non-null only when tracking_origin is set and
the message carries SENT. A tracked but unopened message is
{ opens: 0, firstOpenedAt: null, lastOpenedAt: null }.
Send path
- The composer saves
trackOpenswith the draft (DraftFields/DraftDetail), so cancel-send, scheduled-send edits and reopening keep the choice. POST /api/mailboxes/:id/drafts/:draftId/sendloads the draft and, whentrackOpensis true, checks the caller's tracking settings. Tracking is enabled only if the extension is on andTRACKING_SECRETis set. The public origin comes fromAPP_ORIGINor the send request's origin.- If the draft asks for tracking but it is unavailable, the message is sent
untracked and
SendResult.trackingis"off"; the composer shows a notice. Do not fail the send or silently drop it. MailboxDO.sendDraftrejects tracking whenhtml_bodyis blank, writes onlytracking_origin(never overwritetrack_opens), and returnstracking: "on" | "off".deliversigns the token and putstrackingUrlonOutgoingMessage.buildEmailprepends the image to the HTML. The stored draft, thread HTML, plain-text part and mbox export never contain the pixel.- On success,
tracking_originstays. On a retry it stays. On a permanent failure orcancelSend, it is cleared.
Token and pixel
- Input:
v1:<mailboxId>:<messageId>. - Token: HMAC-SHA256 with
TRACKING_SECRET, truncated to 16 bytes and base64url-encoded (22 chars). Deterministic, so retries reuse it. - URL:
<origin>/t/<mailboxId>/<messageId>.<token>.gif. verifyTrackingTokenrecomputes the token and compares in constant time-ish fashion. It does not use WebCrypto's truncated-HMACverify(it rejects truncated signatures).- The route:
- accepts
GET(records) andHEAD(no record), returns 405 otherwise; - requires
TRACKING_SECRETand a valid token; every invalid case returns the same GIF so there is no enumeration oracle; - verifies the HMAC before calling
getMailbox, so an invented URL cannot instantiate arbitrary Durable Objects; - rate-limits by
CF-Connecting-IPwithTRACK_LIMITER; if the limiter throws or refuses, record nothing and still return the image; - returns the image first and records via
ctx.waitUntil; - sets
Cache-Control: private, no-store,CDN-Cache-Control: no-store,Referrer-Policy: no-referrer,X-Content-Type-Options: nosniff, andCross-Origin-Resource-Policy: cross-origin(the app-wide default issame-origin, so this must be set explicitly).
- accepts
recordOpenignores drafts/untracked messages, debounces repeat fetches for 60 seconds, upsertsmessage_opens, and broadcaststhreads.changedso an open tab refreshes.
Settings and UI
GET/PUT /api/extensions/tracking returns { enabled, trackByDefault, ready }.
ready means the server has a valid TRACKING_SECRET; it is not a user
setting. Settings live in registry.user_extensions with id tracking.
The launcher tile opens TrackingSettingsDialog. The composer shows the switch
only when useTrackingReady() is true; a new draft follows trackByDefault,
an existing draft keeps its saved choice. The conversation shows
“Tracking on · no open recorded yet” or “Open recorded · fetched N× · 2h ago”.
Use formatRelativeShort; formatMessageDate is too long for that line.
Deployment requirements
The pixel must be reachable by recipients' mail clients:
- Access — add a Bypass policy for
/t/*only. One-click Access may not support path scoping; if not, use a custom domain and keep the app protected. - Bot Fight Mode — free Bot Fight Mode applies to all traffic and cannot be
path-exempted with a WAF Skip rule. Disable it for the zone, or use Super Bot
Fight Mode with a Skip rule for
/t. - Secrets/vars —
TRACKING_SECRETis required;APP_ORIGINis optional and defaults to the send request's origin. RotatingTRACKING_SECRETinvalidates pixel URLs in already-sent mail. - Limits —
TRACK_LIMITERis 120 requests/minute/IP by default.
Reliability caveats
- Apple Mail Privacy Protection and Gmail's image proxy may fetch the image on delivery, producing false opens.
- Outlook and many clients block remote images, producing false negatives.
- Corporate scanners may prefetch the URL.
- Therefore the UI says “no open recorded”, never “not opened”, and the docs call the count approximate. Do not present it as a delivery or read receipt.
Testing
test/tracking.test.tscovers token round trips/tampering, pixel injection, settings, tracking on/off, empty HTML, cancel-send, permanent failure, debounce, HEAD, invalid tokens, draft messages, delete-trigger cleanup and the v9→v10 migration.- Use
handleTracking(request, env, ctx)with a fakewaitUntilto awaitrecordOpendeterministically. - Inspect DO SQL with
runInDurableObject; backdatelast_opened_atto test the debounce window. e2e/tracking.spec.tsis serial because settings belong to the single dev user; reset withPUT /api/extensions/tracking { enabled: false }inbeforeEach.- The local send simulator does not expose the sent HTML; assert the pixel URL
in Vitest from the captured
OutgoingMessage.
Pitfalls
- Do not inject the pixel into
html_body; onlybuildEmailmay add it. - Do not overwrite
track_opensinsendDraft; it is the draft preference. - Do not call
getMailboxbefore verifying the token. - Do not reuse
rateLimit()fromworkers/api/common.tson the public route: it throwsHttpError, which becomes a 500 outside Hono. - Do not add
ON DELETE CASCADEand assume it runs; keep the delete trigger. - Do not add the pixel to plain text or rewrite links in v1.
- If you add columns, append a migration; never edit migration 10 after it has shipped.
Version History
- d9871cd Current 2026-12-01 07:51


