Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(platform): DataFast revenue attribution on Stripe Checkout (#13288)

Ubbe3417f13447b8
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
index 1c611d86cc..265fa58a04 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
@@ -589,6 +589,55 @@ def test_update_subscription_tier_creates_checkout(
assert response.json()["url"] == "https://checkout.stripe.com/pay/cs_test_abc"
+def test_update_subscription_tier_forwards_datafast_headers(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """DataFast attribution headers are forwarded to create_subscription_checkout."""
+ mock_user = Mock()
+ mock_user.subscription_tier = SubscriptionTier.BASIC
+
+ async def mock_feature_enabled(*args, **kwargs):
+ return True
+
+ mocker.patch(
+ "backend.api.features.v1.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ )
+ mocker.patch(
+ "backend.api.features.v1.is_feature_enabled",
+ side_effect=mock_feature_enabled,
+ )
+ mocker.patch(
+ "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ new_callable=AsyncMock,
+ return_value=False,
+ )
+ mock_checkout = mocker.patch(
+ "backend.api.features.v1.create_subscription_checkout",
+ new_callable=AsyncMock,
+ return_value="https://checkout.stripe.com/pay/cs_test_abc",
+ )
+
+ response = client.post(
+ "/credits/subscription",
+ json={
+ "tier": "PRO",
+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",
+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",
+ },
+ headers={
+ "X-Datafast-Visitor-Id": "vis_1",
+ "X-Datafast-Session-Id": "ses_1",
+ },
+ )
+
+ assert response.status_code == 200
+ assert mock_checkout.await_args.kwargs["datafast_visitor_id"] == "vis_1"
+ assert mock_checkout.await_args.kwargs["datafast_session_id"] == "ses_1"
+
+
def test_update_subscription_tier_forwards_yearly_billing_cycle(
client: fastapi.testclient.TestClient,
mocker: pytest_mock.MockFixture,
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 9442ea93d2..0cefee83a0 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -16,6 +16,7 @@ from fastapi import (
Body,
Depends,
File,
+ Header,
HTTPException,
Path,
Query,
@@ -638,10 +639,22 @@ async def get_user_credits(
dependencies=[Security(requires_user)],
)
async def request_top_up(
- request: RequestTopUp, user_id: Annotated[str, Security(get_user_id)]
+ request: RequestTopUp,
+ user_id: Annotated[str, Security(get_user_id)],
+ x_datafast_visitor_id: Annotated[
+ str | None, Header(include_in_schema=False)
+ ] = None,
+ x_datafast_session_id: Annotated[
+ str | None, Header(include_in_schema=False)
+ ] = None,
):
user_credit_model = await get_user_credit_model(user_id)
- checkout_url = await user_credit_model.top_up_intent(user_id, request.credit_amount)
+ checkout_url = await user_credit_model.top_up_intent(
+ user_id,
+ request.credit_amount,
+ datafast_visitor_id=x_datafast_visitor_id,
+ datafast_session_id=x_datafast_session_id,
+ )
return {"checkout_url": checkout_url}
@@ -1006,6 +1019,12 @@ async def get_subscription_status(
async def update_subscription_tier(
request: SubscriptionTierRequest,
user_id: Annotated[str, Security(get_user_id)],
+ x_datafast_visitor_id: Annotated[
+ str | None, Header(include_in_schema=False)
+ ] = None,
+ x_datafast_session_id: Annotated[
+ str | None, Header(include_in_schema=False)
+ ] = None,
) -> SubscriptionStatusResponse:
# Pydantic validates tier is one of BASIC/PRO/MAX/BUSINESS via Literal type.
tier = SubscriptionTier(request.tier)
@@ -1263,6 +1282,8 @@ async def update_subscription_tier(
success_url=request.success_url,
cancel_url=request.cancel_url,
billing_cycle=request.billing_cycle,
+ datafast_visitor_id=x_datafast_visitor_id,
+ datafast_session_id=x_datafast_session_id,
)
except ValueError as e:
raise HTTPException(status_code=422, detail=str(e))
diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.py
index 51e6434ab0..331f757cff 100644
--- a/autogpt_platform/backend/backend/api/features/v1_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_test.py
@@ -1,7 +1,7 @@
import json
from datetime import datetime, timezone
from io import BytesIO
-from unittest.mock import AsyncMock, Mock, patch
+from unittest.mock import ANY, AsyncMock, Mock, patch
import fastapi
import fastapi.testclient
@@ -367,6 +367,37 @@ def test_request_top_up(
)
+def test_request_top_up_forwards_datafast_headers(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """DataFast attribution headers are forwarded to top_up_intent."""
+ mock_credit_model = Mock()
+ mock_credit_model.top_up_intent = AsyncMock(
+ return_value="https://checkout.example.com/session123"
+ )
+ mocker.patch(
+ "backend.api.features.v1.get_user_credit_model",
+ return_value=mock_credit_model,
+ )
+
+ response = client.post(
+ "/credits",
+ json={"credit_amount": 500},
+ headers={
+ "X-Datafast-Visitor-Id": "vis_1",
+ "X-Datafast-Session-Id": "ses_1",
+ },
+ )
+
+ assert response.status_code == 200
+ mock_credit_model.top_up_intent.assert_awaited_once_with(
+ ANY,
+ 500,
+ datafast_visitor_id="vis_1",
+ datafast_session_id="ses_1",
+ )
+
+
def test_get_auto_top_up(
mocker: pytest_mock.MockFixture,
snapshot: Snapshot,
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index a49340d077..39edfe0161 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -96,6 +96,48 @@ class InvoiceListItem(BaseModel):
invoice_pdf_url: str | None = None
+# Stripe rejects metadata values longer than 500 chars with an
+# invalid_request_error. DataFast IDs are short, but the values arrive from a
+# client-controlled header, so we validate them to keep attribution strictly
+# best-effort: a malformed ID must never break Checkout.
+_STRIPE_METADATA_VALUE_MAX_LEN = 500
+
+
+def _sanitize_datafast_id(value: str | None) -> str | None:
+ """Validate a client-supplied DataFast ID for use as Stripe metadata.
+
+ Returns the trimmed value, or None when it is blank, contains control
+ characters, or exceeds Stripe's metadata limit. An invalid ID is dropped
+ rather than truncated — a partial ID is useless for attribution and would
+ only pollute the Checkout metadata.
+ """
+ if not value:
+ return None
+ normalized = value.strip()
+ if not normalized or len(normalized) > _STRIPE_METADATA_VALUE_MAX_LEN:
+ return None
+ if any(ord(ch) < 0x20 for ch in normalized):
+ return None
+ return normalized
+
+
+def _datafast_metadata(
+ visitor_id: str | None, session_id: str | None
+) -> dict[str, str]:
+ """Build Stripe metadata for DataFast revenue attribution.
+
+ Only includes IDs that are actually present (and valid) so we never send the
+ literal string "None" or a value Stripe would reject. Returns an empty dict
+ when neither is set, which Stripe accepts as "no metadata".
+ """
+ metadata: dict[str, str] = {}
+ if visitor := _sanitize_datafast_id(visitor_id):
+ metadata["datafast_visitor_id"] = visitor
+ if session := _sanitize_datafast_id(session_id):
+ metadata["datafast_session_id"] = session
+ return metadata
+
+
class UserCreditBase(ABC):
@abstractmethod
async def get_credits(self, user_id: str) -> int:
@@ -230,13 +272,21 @@ class UserCreditBase(ABC):
pass
@abstractmethod
- async def top_up_intent(self, user_id: str, amount: int) -> str:
+ async def top_up_intent(
+ self,
+ user_id: str,
+ amount: int,
+ datafast_visitor_id: str | None = None,
+ datafast_session_id: str | None = None,
+ ) -> str:
"""
Create a payment intent to top up the credits for the user.
Args:
user_id (str): The user ID.
amount (int): The amount of credits to top up.
+ datafast_visitor_id (str | None): DataFast visitor ID for attribution.
+ datafast_session_id (str | None): DataFast session ID for attribution.
Returns:
str: The redirect url to the payment page.
@@ -1060,7 +1110,13 @@ class UserCredit(UserCreditBase):
},
)
- async def top_up_intent(self, user_id: str, amount: int) -> str:
+ async def top_up_intent(
+ self,
+ user_id: str,
+ amount: int,
+ datafast_visitor_id: str | None = None,
+ datafast_session_id: str | None = None,
+ ) -> str:
if amount < 500 or amount % 100 != 0:
raise ValueError(
f"Top up amount must be at least 500 credits and multiple of 100 but is {amount}"
@@ -1115,6 +1171,7 @@ class UserCredit(UserCreditBase):
automatic_tax={"enabled": True},
billing_address_collection="auto",
customer_update={"address": "auto"},
+ metadata=_datafast_metadata(datafast_visitor_id, datafast_session_id),
)
await self._add_transaction(
@@ -2389,6 +2446,8 @@ async def create_subscription_checkout(
success_url: str,
cancel_url: str,
billing_cycle: BillingCycle = "monthly",
+ datafast_visitor_id: str | None = None,
+ datafast_session_id: str | None = None,
) -> str:
"""Create a Stripe Checkout Session for a subscription. Returns the redirect URL."""
price_id = await get_subscription_price_id(tier, billing_cycle)
@@ -2396,6 +2455,7 @@ async def create_subscription_checkout(
raise ValueError(f"Subscription not available for tier {tier.value}")
customer_id = await get_stripe_customer_id(user_id)
await _expire_open_subscription_sessions(customer_id)
+ datafast = _datafast_metadata(datafast_visitor_id, datafast_session_id)
session = await run_in_threadpool(
stripe.checkout.Session.create,
customer=customer_id,
@@ -2408,12 +2468,14 @@ async def create_subscription_checkout(
"user_id": user_id,
"tier": tier.value,
"billing_cycle": billing_cycle,
+ **datafast,
}
},
allow_promotion_codes=True,
automatic_tax={"enabled": True},
billing_address_collection="auto",
customer_update={"address": "auto"},
+ metadata=datafast,
)
if not session.url:
# An empty checkout URL for a paid upgrade is always an error; surfacing it
diff --git a/autogpt_platform/backend/backend/data/credit_metadata_test.py b/autogpt_platform/backend/backend/data/credit_metadata_test.py
index 81643def4b..0d8ed51384 100644
--- a/autogpt_platform/backend/backend/data/credit_metadata_test.py
+++ b/autogpt_platform/backend/backend/data/credit_metadata_test.py
@@ -8,12 +8,17 @@ to raw SQL queries with JSONB columns.
# type: ignore
from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from prisma.enums import CreditTransactionType
+from prisma.enums import CreditTransactionType, SubscriptionTier
from prisma.models import CreditTransaction, UserBalance
-from backend.data.credit import UserCredit
+from backend.data.credit import (
+ UserCredit,
+ _datafast_metadata,
+ create_subscription_checkout,
+)
from backend.data.user import DEFAULT_USER_ID
from backend.util.json import SafeJson
@@ -139,3 +144,113 @@ async def test_enable_transaction_metadata_serialization(setup_test_user):
assert metadata_dict["complex_data"]["array"] == [1, 2, 3]
assert metadata_dict["complex_data"]["boolean"] is True
assert metadata_dict["complex_data"]["null_value"] is None
+
+
+def test_datafast_metadata_includes_only_present_ids():
+ assert _datafast_metadata("vis_1", "ses_1") == {
+ "datafast_visitor_id": "vis_1",
+ "datafast_session_id": "ses_1",
+ }
+
+
+def test_datafast_metadata_drops_none_values():
+ assert _datafast_metadata("vis_1", None) == {"datafast_visitor_id": "vis_1"}
+ assert _datafast_metadata(None, None) == {}
+
+
+def test_datafast_metadata_drops_invalid_values():
+ # Oversized values are dropped entirely (a truncated ID is useless for
+ # attribution), not truncated.
+ assert _datafast_metadata("v" * 600, None) == {}
+ # Whitespace is stripped; values that are blank or contain control
+ # characters are dropped so they can never break Checkout.
+ assert _datafast_metadata(" vis_1 ", "\x00bad") == {
+ "datafast_visitor_id": "vis_1"
+ }
+ assert _datafast_metadata(" ", "ses_1") == {"datafast_session_id": "ses_1"}
+
+
+async def test_top_up_intent_attaches_datafast_metadata():
+ """top_up_intent threads DataFast IDs into the Checkout session metadata."""
+ mock_session = MagicMock()
+ mock_session.id = "cs_test_topup"
+ mock_session.url = "https://checkout.stripe.com/c/cs_test_topup"
+ create_mock = MagicMock(return_value=mock_session)
+ credit_system = UserCredit()
+ with (
+ patch(
+ "backend.data.credit.get_stripe_customer_id",
+ new_callable=AsyncMock,
+ return_value="cus_123",
+ ),
+ patch(
+ "backend.data.credit.get_feature_flag_value",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
+ patch(
+ "backend.data.credit.stripe.checkout.Session.create",
+ new=create_mock,
+ ),
+ patch.object(credit_system, "_add_transaction", new_callable=AsyncMock),
+ ):
+ await credit_system.top_up_intent(
+ user_id="user-1",
+ amount=500,
+ datafast_visitor_id="vis_1",
+ datafast_session_id="ses_1",
+ )
+
+ assert create_mock.call_args.kwargs["metadata"] == {
+ "datafast_visitor_id": "vis_1",
+ "datafast_session_id": "ses_1",
+ }
+
+
+async def test_create_subscription_checkout_attaches_datafast_metadata():
+ """create_subscription_checkout threads DataFast IDs into both the session
+ metadata and the subscription_data metadata while keeping user_id."""
+ mock_session = MagicMock()
+ mock_session.url = "https://checkout.stripe.com/pay/cs_test_sub"
+ create_mock = MagicMock(return_value=mock_session)
+ with (
+ patch(
+ "backend.data.credit.get_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value="price_pro_monthly",
+ ),
+ patch(
+ "backend.data.credit.get_stripe_customer_id",
+ new_callable=AsyncMock,
+ return_value="cus_123",
+ ),
+ patch(
+ "backend.data.credit._expire_open_subscription_sessions",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "backend.data.credit.stripe.checkout.Session.create",
+ new=create_mock,
+ ),
+ ):
+ url = await create_subscription_checkout(
+ user_id="user-1",
+ tier=SubscriptionTier.PRO,
+ success_url="https://app.example.com/success",
+ cancel_url="https://app.example.com/cancel",
+ datafast_visitor_id="vis_1",
+ datafast_session_id="ses_1",
+ )
+
+ assert url == "https://checkout.stripe.com/pay/cs_test_sub"
+ kwargs = create_mock.call_args.kwargs
+ assert kwargs["metadata"] == {
+ "datafast_visitor_id": "vis_1",
+ "datafast_session_id": "ses_1",
+ }
+ sub_metadata = kwargs["subscription_data"]["metadata"]
+ assert sub_metadata["user_id"] == "user-1"
+ assert sub_metadata["datafast_visitor_id"] == "vis_1"
+ assert sub_metadata["datafast_session_id"] == "ses_1"
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/datafast-attribution.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/datafast-attribution.test.tsx
new file mode 100644
index 0000000000..37698863c1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/datafast-attribution.test.tsx
@@ -0,0 +1,89 @@
+/**
+ * Page-level integration test for DataFast attribution on the credit top-up.
+ *
+ * The credit top-up flows through `usePostV1RequestCreditTopUp` →
+ * `customMutator`, which attaches the DataFast headers returned by
+ * `getDatafastAttribution()` (read from the `datafast_visitor_id` /
+ * `datafast_session_id` cookies). MSW intercepts the outgoing POST so we can
+ * assert which headers were attached.
+ *
+ * We drive the real BalanceCard UI (Add credits → amount input → Continue to
+ * checkout) rather than calling the hook directly, and stub `document.cookie`
+ * the same way the datafast-attribution unit test does.
+ *
+ * Redirect guard: the POST handler returns `{ checkout_url: null }` so the
+ * hook treats it as a non-redirect error and never sets
+ * `window.location.href` — the request (and its headers) is still captured.
+ */
+
+import { fireEvent } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { server } from "@/mocks/mock-server";
+import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+
+import { BalanceCard } from "../components/AutomationCreditsTab/BalanceCard/BalanceCard";
+
+function stubCookies(value: string) {
+ vi.spyOn(document, "cookie", "get").mockReturnValue(value);
+}
+
+async function submitTopUp() {
+ fireEvent.click(await screen.findByRole("button", { name: /add credits/i }));
+
+ const amountInput = screen.getByPlaceholderText(/amount/i);
+ fireEvent.change(amountInput, { target: { value: "20" } });
+
+ const continueButton = await screen.findByRole("button", {
+ name: /continue to checkout/i,
+ });
+ await waitFor(() =>
+ expect(continueButton.hasAttribute("disabled")).toBe(false),
+ );
+ fireEvent.click(continueButton);
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("DataFast attribution on credit top-up", () => {
+ it("attaches the DataFast headers when the attribution cookies are present", async () => {
+ stubCookies("datafast_visitor_id=vis_1; datafast_session_id=ses_1");
+
+ const captured: { headers: Headers | null } = { headers: null };
+ server.use(
+ http.get("*/api/credits", () => HttpResponse.json({ credits: 1000 })),
+ http.post("*/api/credits", async ({ request }) => {
+ captured.headers = request.headers;
+ return HttpResponse.json({ checkout_url: null });
+ }),
+ );
+
+ render(<BalanceCard />);
+ await submitTopUp();
+
+ await waitFor(() => expect(captured.headers).not.toBeNull());
+ expect(captured.headers?.get("X-Datafast-Visitor-Id")).toBe("vis_1");
+ expect(captured.headers?.get("X-Datafast-Session-Id")).toBe("ses_1");
+ });
+
+ it("omits the DataFast headers when no attribution cookies exist", async () => {
+ stubCookies("");
+
+ const captured: { headers: Headers | null } = { headers: null };
+ server.use(
+ http.get("*/api/credits", () => HttpResponse.json({ credits: 1000 })),
+ http.post("*/api/credits", async ({ request }) => {
+ captured.headers = request.headers;
+ return HttpResponse.json({ checkout_url: null });
+ }),
+ );
+
+ render(<BalanceCard />);
+ await submitTopUp();
+
+ await waitFor(() => expect(captured.headers).not.toBeNull());
+ expect(captured.headers?.get("X-Datafast-Visitor-Id")).toBeNull();
+ expect(captured.headers?.get("X-Datafast-Session-Id")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
index f4c6656f29..ddbf53a1a6 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
@@ -6,6 +6,7 @@ import {
import * as Sentry from "@sentry/nextjs";
import { getSystemHeaders } from "@/lib/impersonation";
+import { getDatafastAttribution } from "@/services/analytics/datafast-attribution";
import { environment } from "@/services/environment";
import { transformDates } from "./date-transformer";
@@ -72,6 +73,7 @@ export const customMutator = async <
}
}
Object.assign(headers, getSystemHeaders());
+ Object.assign(headers, getDatafastAttribution());
}
const isFormData = data instanceof FormData;
diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
index e088c12680..b480695263 100644
--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
@@ -194,6 +194,27 @@ describe("proxy route — handler pass-through", () => {
expect(sentHeaders.get("baggage")).toBe("sentry-trace_id=abc123");
});
+ it("forwards allowlisted DataFast attribution headers", async () => {
+ vi.mocked(fetch).mockResolvedValue(
+ new Response("{}", {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+
+ const req = new NextRequest("https://app.test/api/proxy/api/v1/items", {
+ headers: {
+ "x-datafast-visitor-id": "visitor-123",
+ "x-datafast-session-id": "session-456",
+ },
+ });
+ await GET(req, makeParams(["api", "v1", "items"]));
+
+ const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;
+ expect(sentHeaders.get("x-datafast-visitor-id")).toBe("visitor-123");
+ expect(sentHeaders.get("x-datafast-session-id")).toBe("session-456");
+ });
+
it("omits Authorization header when no token is available", async () => {
vi.mocked(getServerAuthToken).mockResolvedValueOnce(null);
vi.mocked(fetch).mockResolvedValue(
diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
index 95a0ed6045..68f022cd25 100644
--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
@@ -25,6 +25,8 @@ const FORWARDED_REQUEST_HEADERS: ReadonlyArray<string> = [
API_KEY_HEADER_NAME.toLowerCase(),
"sentry-trace",
"baggage",
+ "x-datafast-visitor-id",
+ "x-datafast-session-id",
];
// Browsers advertise `zstd` in Accept-Encoding, but undici (Node 22's fetch)
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
index 98178a5c19..32fc0ee399 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
@@ -3,6 +3,7 @@ import { ImpersonationState } from "@/lib/impersonation";
import { getWebSocketToken } from "@/lib/supabase/actions";
import { ensureSupabaseClient } from "@/lib/supabase/hooks/helpers";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
+import { getDatafastAttribution } from "@/services/analytics/datafast-attribution";
import { environment } from "@/services/environment";
import { Key, storage } from "@/services/storage/local-storage";
import * as Sentry from "@sentry/nextjs";
@@ -889,6 +890,8 @@ export default class BackendAPI {
headers[IMPERSONATION_HEADER_NAME] = impersonatedUserId;
}
+ Object.assign(headers, getDatafastAttribution());
+
const response = await fetch(url, {
method,
headers,
diff --git a/autogpt_platform/frontend/src/services/analytics/datafast-attribution.test.ts b/autogpt_platform/frontend/src/services/analytics/datafast-attribution.test.ts
new file mode 100644
index 0000000000..9ca560ef04
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/datafast-attribution.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { getDatafastAttribution } from "./datafast-attribution";
+
+function setCookie(value: string) {
+ vi.spyOn(document, "cookie", "get").mockReturnValue(value);
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("getDatafastAttribution", () => {
+ it("returns both header values when both cookies are present", () => {
+ setCookie("datafast_visitor_id=vis_1; datafast_session_id=ses_1");
+ expect(getDatafastAttribution()).toEqual({
+ "X-Datafast-Visitor-Id": "vis_1",
+ "X-Datafast-Session-Id": "ses_1",
+ });
+ });
+
+ it("includes only the cookies that are present", () => {
+ setCookie("datafast_visitor_id=vis_1");
+ expect(getDatafastAttribution()).toEqual({
+ "X-Datafast-Visitor-Id": "vis_1",
+ });
+ });
+
+ it("returns an empty object when no DataFast cookies exist", () => {
+ setCookie("other=1");
+ expect(getDatafastAttribution()).toEqual({});
+ });
+
+ it("does not throw on a malformed percent-encoded unrelated cookie", () => {
+ setCookie("other=%E0%A4%A; datafast_visitor_id=vis_1");
+ expect(() => getDatafastAttribution()).not.toThrow();
+ expect(getDatafastAttribution()).toEqual({
+ "X-Datafast-Visitor-Id": "vis_1",
+ });
+ });
+
+ it("skips a DataFast cookie whose own value is malformed", () => {
+ setCookie("datafast_visitor_id=%E0%A4%A; datafast_session_id=ses_1");
+ expect(() => getDatafastAttribution()).not.toThrow();
+ expect(getDatafastAttribution()).toEqual({
+ "X-Datafast-Session-Id": "ses_1",
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/datafast-attribution.ts b/autogpt_platform/frontend/src/services/analytics/datafast-attribution.ts
new file mode 100644
index 0000000000..0542978fac
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/datafast-attribution.ts
@@ -0,0 +1,30 @@
+const COOKIE_TO_HEADER = {
+ datafast_visitor_id: "X-Datafast-Visitor-Id",
+ datafast_session_id: "X-Datafast-Session-Id",
+} as const;
+
+// Reads the DataFast attribution cookies (set client-side by the DataFast
+// script) and maps them to request headers. Best-effort: returns only the
+// cookies that exist, and {} during SSR. Never throws.
+export function getDatafastAttribution(): Record<string, string> {
+ if (typeof document === "undefined") return {};
+
+ const jar = new Map(
+ document.cookie.split("; ").map((part) => {
+ const eq = part.indexOf("=");
+ return eq === -1 ? [part, ""] : [part.slice(0, eq), part.slice(eq + 1)];
+ }) as [string, string][],
+ );
+
+ const headers: Record<string, string> = {};
+ for (const [cookie, header] of Object.entries(COOKIE_TO_HEADER)) {
+ const rawValue = jar.get(cookie);
+ if (!rawValue) continue;
+ try {
+ headers[header] = decodeURIComponent(rawValue);
+ } catch {
+ // Best-effort: ignore a malformed percent-encoded value rather than throw.
+ }
+ }
+ return headers;
+}