GoodAnalytics.Core.Tracking.ReferralCookie (GoodAnalytics v0.1.1)

Copy Markdown View Source

Signs, verifies, and manages the _ga_ref referral attribution cookie.

The cookie payload carries partner context as a signed token that prevents client-side tampering while remaining readable by the JS snippet (the cookie is NOT HttpOnly).

Tokens are workspace-scoped: the workspace_id is embedded in the signed payload so a token minted for workspace A cannot be replayed against workspace B's attribution data.

Summary

Functions

Returns the cookie name.

Returns the cookie options for Plug.Conn.put_resp_cookie/4.

Returns the default max-age in seconds.

Normalizes referral attribution context into the canonical map shape used by the redirect flow, beacon, plug, and event recorder.

Reads and verifies the referral cookie from a Plug conn.

Sets the referral cookie on a Plug conn with signed referral context.

Signs a referral attribution context into a cookie-safe token.

Verifies a signed referral cookie token and returns the attribution context.

Verifies a token and validates it belongs to the given workspace.

Functions

max_age()

Returns the default max-age in seconds.

normalize(partner_id, referral_link_id, referral_click_id, opts \\ %{})

Normalizes referral attribution context into the canonical map shape used by the redirect flow, beacon, plug, and event recorder.

read_from_conn(conn)

Reads and verifies the referral cookie from a Plug conn.

Returns {:ok, context} or {:error, reason}.

set_on_conn(conn, context)

Sets the referral cookie on a Plug conn with signed referral context.

sign(context)

Signs a referral attribution context into a cookie-safe token.

The context map must include:

  • :partner_id — the credited partner UUID
  • :referral_link_id — the referral link UUID
  • :referral_click_id — the click UUID from this referral touch
  • :workspace_id — the workspace this token is scoped to

An optional :issued_at unix timestamp is preserved if present (used when re-signing an existing cookie to extend its TTL without resetting the original attribution time). When absent, the current time is used.

verify(token)

Verifies a signed referral cookie token and returns the attribution context.

Returns {:ok, context} with a normalized referral attribution map, or {:error, reason} for invalid, expired, or tampered tokens.

Handles tokens signed before workspace_id was added (backward compatibility).

verify(token, workspace_id)

Verifies a token and validates it belongs to the given workspace.

Returns {:error, :workspace_mismatch} if the token's workspace doesn't match. Legacy tokens without a workspace_id (minted before this feature) are treated as absent and return {:ok, %{}} rather than blocking attribution.