Files
conversation-history/SquareMCP/2026-06-09-mysql-backed-tracking-links.md

6.5 KiB

MySQL-Backed Tracking Links

Date: 2026-06-09 Project: SquareMCP / Lodge Brothers Beta Status: Proposed implementation Related: 2026-06-09-lodge-brothers-eng-review, 2026-06-09-lodge-brothers-beta-design, 2026-06-09-marketplace-release-checklist


Why This Is Needed

The Lodge Brothers plan currently treats Redis as the source of truth for each UTM redirect:

tracking token -> customer, draft, destination URL

That makes every published link dependent on the Redis key remaining available. If Redis restarts, evicts the key, or is temporarily unavailable, SquareMCP no longer knows where /t/:token should send the visitor.

MySQL should hold the durable tracking-link record. Redis can remain an optional fast path for click counters and analytics.


Repository Investigation

No prior implementation of tracking_links, utm_token, or GET /t/:token exists in the current repository, branches, or Git history. The feature appears in planning notes only.

MySQL itself is already proven in production because the same pool backs authentication, OAuth, billing, usage, and invoices. This feature does not require a new database service.


Proposed Data Model

Add the table in initDatabase() in src/db.ts, following the repository's existing CREATE TABLE IF NOT EXISTS convention:

CREATE TABLE IF NOT EXISTS tracking_links (
  token           VARCHAR(43) PRIMARY KEY,
  customer_id     VARCHAR(255) NOT NULL,
  draft_id        INT NULL,
  destination_url VARCHAR(2048) NOT NULL,
  click_count     BIGINT UNSIGNED NOT NULL DEFAULT 0,
  expires_at      TIMESTAMP NULL,
  created_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_customer_created (customer_id, created_at),
  INDEX idx_draft (draft_id)
)

Use customer_id consistently. The Lodge Brothers engineering review currently mixes tenant_id and customer_id.

Generate tokens with cryptographically secure randomness, for example:

crypto.randomBytes(24).toString('base64url')

Redirect Flow

GET /t/:token
  -> validate token format
  -> SELECT destination_url, expires_at FROM tracking_links WHERE token = ?
  -> return 404 for unknown or expired token
  -> validate destination protocol is http: or https:
  -> return 302 immediately
  -> record the click without making redirect success depend on analytics

The essential rule is:

MySQL determines where the visitor goes. Analytics failure must not break the link.

Redis may increment a fast counter, but the redirect should still work if Redis is down.

For durable counting, either:

  1. Increment tracking_links.click_count asynchronously in MySQL, or
  2. Increment Redis and periodically flush counts to MySQL.

For the Lodge Brothers beta, option 1 is simpler and sufficient. At expected pilot volume, one asynchronous MySQL update per click is acceptable.


When a draft is approved for publishing:

  1. Validate the configured destination URL.
  2. Generate a secure token.
  3. Insert the tracking record into MySQL.
  4. Build https://hermes.squaremcp.com/t/{token}.
  5. Add that link to the Facebook post.
  6. Store the token on the draft or in a publish-attempt record.

Do not publish the social post unless the tracking-link insert succeeds. Otherwise the post may contain a dead URL.


Destination Validation

Tracking links are an open-redirect surface. Before inserting a record:

  • Parse with new URL(destinationUrl).
  • Allow only http: and https:.
  • Reject credentials embedded in the URL.
  • Enforce a maximum length.
  • Consider a domain allowlist for the beta if Alex always links to a known Lodge Brothers or mortgage domain.

The public redirect route must never accept the destination URL from the request. It must only redirect to a value previously stored by authenticated server-side code.


Files To Add Or Change

Recommended structure:

  • src/db.ts

    • Create tracking_links table.
  • src/tracking-links.ts

    • createTrackingLink()
    • getTrackingLink()
    • recordTrackingClick()
    • URL and token validation
  • src/index.ts

    • Public GET /t/:token route.
    • Keep the route outside requireAuth; visitors clicking social posts will not be logged in.
  • src/tracking-links.test.ts

    • Unit tests for creation, lookup, expiration, validation, and click recording.
  • Route test

    • Use Supertest with mocked tracking-link functions to verify 302, 404, expiration, and analytics-failure behavior.

Required Tests

  • Valid token returns 302 with the stored destination.
  • Unknown token returns 404.
  • Expired token returns 404 or 410 consistently.
  • Non-HTTP destination is rejected during creation.
  • Malformed token is rejected without querying the database.
  • Redis unavailable does not prevent redirect.
  • Click-recording failure does not prevent redirect.
  • Token collisions retry safely.
  • Bot traffic policy is explicit and tested if bot filtering remains in scope.

Likely Causes Of A Failed First Attempt

A previous attempt is not present in this repository, but these are the likely failure modes:

  1. A standalone SQL migration was created without a migration runner.
  2. Redis was used as the only source of truth.
  3. The redirect route was accidentally protected by requireAuth.
  4. The ingress or public hostname did not route /t/* to Hermes.
  5. Link creation happened after publishing, producing dead links on insert failure.
  6. Destination validation rejected or malformed real URLs.
  7. Analytics writes were awaited before redirecting, so an outage broke navigation.
  8. The feature was tested locally but not against https://hermes.squaremcp.com/t/{token}.

Implementation Estimate

A production-quality beta implementation is approximately half a day:

  • Schema and tracking-link functions: 1 hour
  • Public redirect and publish integration: 1-2 hours
  • Validation, expiration, and graceful failure: 1 hour
  • Tests and deployed ingress verification: 1-2 hours

The tracking redirect is not the most complex part of the Lodge Brothers beta. Durable WhatsApp approval processing and partial Facebook/Instagram publish recovery require more design work.


Acceptance Criteria

  • A tracking link survives Redis restart or outage.
  • A visitor always reaches the stored destination while MySQL is available.
  • Analytics failure never changes redirect behavior.
  • Every destination was inserted by authenticated server-side code and passed URL validation.
  • A deployed end-to-end test confirms the public Hermes hostname serves /t/:token correctly.