Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(self-host): collect anonymous source channels mul-3878 (#4741)
Naiyuan Qing26142d74aa13
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 837fd667b6..75a38d005c 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -231,11 +231,11 @@ S3 の前段に CloudFront を置く場合、3 つの変数が適用されます## 使用量分析-デフォルトでは、サーバーは Multica の公式 PostHog インスタンスにレポートします。オプトアウトするには `ANALYTICS_DISABLED=true` を設定してください。+デフォルトでは、サーバーは製品分析イベントを Multica の公式 PostHog インスタンスにレポートします。PostHog イベント送信を無効にするには `ANALYTICS_DISABLED=true` を設定してください。| 変数 | デフォルト | 説明 ||---|---|---|-| `ANALYTICS_DISABLED` | `false` | バックエンド分析を完全に無効にするには `true` に設定 |+| `ANALYTICS_DISABLED` | `false` | バックエンドの PostHog 分析イベントを無効にするには `true` に設定 || `POSTHOG_API_KEY` | 組み込みのデフォルトキー | 自身の PostHog インスタンスを指す場合に設定 || `POSTHOG_HOST` | `https://us.i.posthog.com` | PostHog をセルフホストする場合は自身のホストに変更 |diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex aecca0ff84..22bcfaceef 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -231,11 +231,11 @@ S3 앞에 CloudFront를 두는 경우 세 가지 변수가 적용됩니다: `CLO## 사용량 분석-기본적으로 서버는 Multica의 공식 PostHog 인스턴스로 보고합니다. 옵트아웃하려면 `ANALYTICS_DISABLED=true`로 설정하세요.+기본적으로 서버는 제품 분석 이벤트를 Multica의 공식 PostHog 인스턴스로 보고합니다. PostHog 이벤트 전송을 비활성화하려면 `ANALYTICS_DISABLED=true`로 설정하세요.| 변수 | 기본값 | 설명 ||---|---|---|-| `ANALYTICS_DISABLED` | `false` | 백엔드 분석을 완전히 비활성화하려면 `true`로 설정 |+| `ANALYTICS_DISABLED` | `false` | 백엔드 PostHog 분석 이벤트를 비활성화하려면 `true`로 설정 || `POSTHOG_API_KEY` | 내장 기본 키 | 자신의 PostHog 인스턴스를 가리킬 때 설정 || `POSTHOG_HOST` | `https://us.i.posthog.com` | PostHog를 자체 호스팅하는 경우 자신의 호스트로 변경 |diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex a29dd9526a..3c2684b6d7 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -233,11 +233,11 @@ The [GitHub PR ↔ issue integration](/github-integration) needs two variables.## Usage analytics-By default, the server reports to Multica's official PostHog instance. To opt out, set `ANALYTICS_DISABLED=true`.+By default, the server reports product analytics events to Multica's official PostHog instance. To disable PostHog event shipping, set `ANALYTICS_DISABLED=true`.| Variable | Default | Description ||---|---|---|-| `ANALYTICS_DISABLED` | `false` | Set `true` to disable backend analytics entirely |+| `ANALYTICS_DISABLED` | `false` | Set `true` to disable backend PostHog analytics events || `POSTHOG_API_KEY` | built-in default key | Set when pointing at your own PostHog instance || `POSTHOG_HOST` | `https://us.i.posthog.com` | Change to your own host if you self-host PostHog |diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 76214b0e80..1dfcc11c63 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -236,11 +236,11 @@ API 返回的 `download_url` 在未配置 CloudFront 签名时会指向 `GET /ap## 用量统计-默认上报到 Multica 官方 PostHog 实例。不想上报就把 `ANALYTICS_DISABLED=true`。+默认会把产品分析事件上报到 Multica 官方 PostHog 实例。要关闭 PostHog 事件上报,请设置 `ANALYTICS_DISABLED=true`。| 环境变量 | 默认值 | 说明 ||---|---|---|-| `ANALYTICS_DISABLED` | `false` | 设 `true` 完全关闭后端上报 |+| `ANALYTICS_DISABLED` | `false` | 设 `true` 关闭后端 PostHog 分析事件 || `POSTHOG_API_KEY` | 内置默认 key | 换成你自己的 PostHog 实例时填 || `POSTHOG_HOST` | `https://us.i.posthog.com` | 自建 PostHog 的话改成你自己的地址 |diff --git a/docs/analytics.md b/docs/analytics.mdindex fdfe47bece..64ffe9cb05 100644--- a/docs/analytics.md+++ b/docs/analytics.md@@ -22,7 +22,7 @@ See [MUL-1122](https://github.com/multica-ai/multica) for the design context.## Configuration-All analytics shipping is toggled by environment variables (see `.env.example`):+PostHog analytics shipping is toggled by environment variables (see `.env.example`):| Variable | Meaning | Default ||---|---|---|@@ -32,7 +32,7 @@ All analytics shipping is toggled by environment variables (see `.env.example`):| `ANALYTICS_DISABLED` | Set to `true`/`1` to force the no-op client even when `POSTHOG_API_KEY` is set. | `""` |Local dev and self-hosted instances run with `POSTHOG_API_KEY=""`, so **no-events leave the process unless the operator explicitly opts in**.+PostHog events leave the process unless the operator explicitly opts in**.### Self-hosted instancesdiff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex cda1e69025..c495e0bb2f 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -416,6 +416,7 @@ describe("AppConfigSchema cdn_signed drift", () => {const parsed = AppConfigSchema.parse({ cdn_signed: true });expect(parsed.cdn_signed).toBe(true);});+});describe("InboxUnreadSummarySchema", () => {diff --git a/packages/core/onboarding/index.ts b/packages/core/onboarding/index.tsindex 34b867ba6c..799dfa636d 100644--- a/packages/core/onboarding/index.ts+++ b/packages/core/onboarding/index.ts@@ -16,6 +16,14 @@ export {needsSourceBackfill,SOURCE_BACKFILL_MAX_DISMISSALS,} from "./needs-backfill";+export {+ OFFICIAL_MULTICA_API_URL,+ currentApiBaseUrl,+ isOfficialMulticaApiUrl,+ isSelfHostedApiBaseUrl,+ normalizeApiBaseUrl,+ shouldShowSourceChannelReporting,+} from "./source-reporting";export { recommendTemplate, type AgentTemplateId } from "./recommend-template";export {useWelcomeStore,diff --git a/packages/core/onboarding/source-reporting.test.ts b/packages/core/onboarding/source-reporting.test.tsnew file mode 100644index 0000000000..25127dbdef--- /dev/null+++ b/packages/core/onboarding/source-reporting.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import {+ OFFICIAL_MULTICA_API_URL,+ isOfficialMulticaApiUrl,+ isSelfHostedApiBaseUrl,+ normalizeApiBaseUrl,+ shouldShowSourceChannelReporting,+} from "./source-reporting";++describe("source channel API-url detection", () => {+ it("treats only the official API URL as official", () => {+ expect(isOfficialMulticaApiUrl(OFFICIAL_MULTICA_API_URL)).toBe(true);+ expect(isOfficialMulticaApiUrl("https://api.multica.ai/")).toBe(true);+ expect(isOfficialMulticaApiUrl("https://api.example.com")).toBe(false);+ expect(isOfficialMulticaApiUrl("https://multica.ai")).toBe(false);+ expect(isOfficialMulticaApiUrl("http://api.multica.ai")).toBe(false);+ });++ it("normalizes harmless URL drift before comparing", () => {+ expect(normalizeApiBaseUrl(" https://API.MULTICA.AI/ ")).toBe(+ OFFICIAL_MULTICA_API_URL,+ );+ expect(normalizeApiBaseUrl("https://api.multica.ai?x=1#hash")).toBe(+ OFFICIAL_MULTICA_API_URL,+ );+ });++ it("shows source reporting only for non-official API URLs", () => {+ expect(isSelfHostedApiBaseUrl(OFFICIAL_MULTICA_API_URL)).toBe(false);+ expect(isSelfHostedApiBaseUrl("https://api.customer.example")).toBe(true);+ expect(shouldShowSourceChannelReporting(OFFICIAL_MULTICA_API_URL)).toBe(+ false,+ );+ expect(shouldShowSourceChannelReporting("https://api.customer.example")).toBe(+ true,+ );+ });+});diff --git a/packages/core/onboarding/source-reporting.ts b/packages/core/onboarding/source-reporting.tsnew file mode 100644index 0000000000..48a0db479f--- /dev/null+++ b/packages/core/onboarding/source-reporting.ts@@ -0,0 +1,46 @@+import { api } from "../api";++export const OFFICIAL_MULTICA_API_URL = "https://api.multica.ai";++export function normalizeApiBaseUrl(value: string | null | undefined): string {+ const raw = value?.trim();+ if (!raw) return "";+ try {+ const url = new URL(raw);+ url.search = "";+ url.hash = "";+ url.pathname = url.pathname.replace(/\/+$/, "");+ return url.toString().replace(/\/+$/, "");+ } catch {+ return "";+ }+}++export function isOfficialMulticaApiUrl(+ apiBaseUrl: string | null | undefined,+): boolean {+ return normalizeApiBaseUrl(apiBaseUrl) === OFFICIAL_MULTICA_API_URL;+}++export function isSelfHostedApiBaseUrl(+ apiBaseUrl: string | null | undefined,+): boolean {+ return !isOfficialMulticaApiUrl(apiBaseUrl);+}++export function currentApiBaseUrl(): string {+ const configured = api.getBaseUrl?.();+ if (typeof configured === "string" && configured.trim() !== "") {+ return configured;+ }+ if (typeof window !== "undefined") {+ return window.location.origin;+ }+ return "";+}++export function shouldShowSourceChannelReporting(+ apiBaseUrl = currentApiBaseUrl(),+): boolean {+ return isSelfHostedApiBaseUrl(apiBaseUrl);+}diff --git a/packages/core/onboarding/types.ts b/packages/core/onboarding/types.tsindex 0da5e3d1ee..dbf1c8f906 100644--- a/packages/core/onboarding/types.ts+++ b/packages/core/onboarding/types.ts@@ -84,6 +84,7 @@ export interface QuestionnaireAnswers {source: Source[];source_other: string | null;source_skipped: boolean;+ source_domain_consent: boolean;role: Role | null;role_other: string | null;role_skipped: boolean;diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsxindex 210d754268..ae535be22e 100644--- a/packages/core/platform/core-provider.tsx+++ b/packages/core/platform/core-provider.tsx@@ -6,6 +6,7 @@ import { installFreezeWatchdog } from "../diagnostics/freeze-watchdog";import { setApiInstance, setSchemaLogger } from "../api";import { createAuthStore, registerAuthStore } from "../auth";import { createChatStore, registerChatStore } from "../chat";+import { shouldShowSourceChannelReporting } from "../onboarding/source-reporting";import {I18nProvider,LocaleAdapterProvider,@@ -43,6 +44,10 @@ function initCore(});setApiInstance(api);setSchemaLogger(createLogger("api-schema"));+ console.info(+ "[Multica] self-hosted API:",+ shouldShowSourceChannelReporting(),+ );// In token mode, hydrate token from storage.if (!cookieAuth) {diff --git a/packages/views/locales/en/onboarding.json b/packages/views/locales/en/onboarding.jsonindex badd0ed107..77c8b2d5e1 100644--- a/packages/views/locales/en/onboarding.json+++ b/packages/views/locales/en/onboarding.json@@ -49,6 +49,12 @@"submit": "Submit","hint_ready": "Looks good. Hit Submit when you're ready."},+ "source_reporting": {+ "description": "Help us understand how you heard about Multica. No extra information is sent.",+ "domain": {+ "label": "Allow sending domain"+ }+ },"questions": {"eyebrow_about_you": "About you","source": {diff --git a/packages/views/locales/ja/onboarding.json b/packages/views/locales/ja/onboarding.jsonindex 47d339e13d..72bc9f4ecf 100644--- a/packages/views/locales/ja/onboarding.json+++ b/packages/views/locales/ja/onboarding.json@@ -49,6 +49,12 @@"submit": "送信","hint_ready": "OK です。準備ができたら送信を押してください。"},+ "source_reporting": {+ "description": "Multica をどこで知ったかを教えてください。追加情報は送信されません。",+ "domain": {+ "label": "ドメインの送信を許可"+ }+ },"questions": {"eyebrow_about_you": "あなたについて","source": {diff --git a/packages/views/locales/ko/onboarding.json b/packages/views/locales/ko/onboarding.jsonindex 40e38a45fd..43e9796ae1 100644--- a/packages/views/locales/ko/onboarding.json+++ b/packages/views/locales/ko/onboarding.json@@ -49,6 +49,12 @@"submit": "제출","hint_ready": "좋습니다. 준비되면 제출을 눌러주세요."},+ "source_reporting": {+ "description": "Multica를 어디서 알게 되었는지 이해하는 데 도움이 됩니다. 추가 정보는 전송되지 않습니다.",+ "domain": {+ "label": "도메인 전송 허용"+ }+ },"questions": {"eyebrow_about_you": "내 정보","source": {diff --git a/packages/views/locales/zh-Hans/onboarding.json b/packages/views/locales/zh-Hans/onboarding.jsonindex fdd2d760da..416c1029d4 100644--- a/packages/views/locales/zh-Hans/onboarding.json+++ b/packages/views/locales/zh-Hans/onboarding.json@@ -49,6 +49,12 @@"submit": "提交","hint_ready": "看起来不错,准备好就点提交。"},+ "source_reporting": {+ "description": "帮助我们了解你从哪里知道 Multica,不会发送额外信息。",+ "domain": {+ "label": "允许发送域名"+ }+ },"questions": {"eyebrow_about_you": "关于你","source": {diff --git a/packages/views/onboarding/onboarding-flow.tsx b/packages/views/onboarding/onboarding-flow.tsxindex 30d9436451..15575c0f5e 100644--- a/packages/views/onboarding/onboarding-flow.tsx+++ b/packages/views/onboarding/onboarding-flow.tsx@@ -29,6 +29,7 @@ const EMPTY_QUESTIONNAIRE: QuestionnaireAnswers = {source: [],source_other: null,source_skipped: false,+ source_domain_consent: true,role: null,role_other: null,role_skipped: false,@@ -71,6 +72,7 @@ function mergeQuestionnaire(return {...merged,source: coerceToArray<QuestionnaireAnswers["source"][number]>(raw.source),+ source_domain_consent: raw.source_domain_consent !== false,use_case: coerceToArray<QuestionnaireAnswers["use_case"][number]>(raw.use_case,),diff --git a/packages/views/onboarding/source-backfill-merge.test.ts b/packages/views/onboarding/source-backfill-merge.test.tsindex 32f611501f..f6e1b0b513 100644--- a/packages/views/onboarding/source-backfill-merge.test.ts+++ b/packages/views/onboarding/source-backfill-merge.test.ts@@ -16,6 +16,7 @@ describe("mergedQuestionnairePatch", () => {source: ["search"],source_other: null,source_skipped: false,+ source_domain_consent: true,});expect(out.source).toEqual(["search"]);expect(out.role).toBe("engineer");@@ -33,6 +34,7 @@ describe("mergedQuestionnairePatch", () => {source: ["friends_colleagues"],source_other: null,source_skipped: false,+ source_domain_consent: true,});expect(out.source_skipped).toBe(false);expect(out.role).toBe("founder");@@ -48,6 +50,7 @@ describe("mergedQuestionnairePatch", () => {source: [],source_other: null,source_skipped: true,+ source_domain_consent: true,});expect(out.source).toEqual([]);expect(out.source_skipped).toBe(true);@@ -55,6 +58,16 @@ describe("mergedQuestionnairePatch", () => {expect(out.use_case).toEqual(["plan_research"]);});+ it("preserves an explicit plaintext-domain opt-out", () => {+ const out = mergedQuestionnairePatch(null, {+ source: ["search"],+ source_other: null,+ source_skipped: false,+ source_domain_consent: false,+ });+ expect(out.source_domain_consent).toBe(false);+ });+it("coerces legacy single-string use_case into a one-element array", () => {const stored: Record<string, unknown> = {role: "engineer",@@ -64,6 +77,7 @@ describe("mergedQuestionnairePatch", () => {source: ["search"],source_other: null,source_skipped: false,+ source_domain_consent: true,});expect(out.use_case).toEqual(["ship_code"]);});@@ -73,6 +87,7 @@ describe("mergedQuestionnairePatch", () => {source: ["search"],source_other: null,source_skipped: false,+ source_domain_consent: true,});expect(out.role).toBeNull();expect(out.role_other).toBeNull();@@ -94,6 +109,7 @@ describe("mergedQuestionnairePatch", () => {source: [],source_other: null,source_skipped: false,+ source_domain_consent: true,});expect(out.role).toBeNull();expect(out.role_other).toBeNull();@@ -109,6 +125,7 @@ describe("mergedQuestionnairePatch", () => {source: ["search"],source_other: null,source_skipped: false,+ source_domain_consent: true,});expect(out.version).toBe(2);});diff --git a/packages/views/onboarding/source-backfill-merge.ts b/packages/views/onboarding/source-backfill-merge.tsindex 0a97b5a7c1..0139cda665 100644--- a/packages/views/onboarding/source-backfill-merge.ts+++ b/packages/views/onboarding/source-backfill-merge.ts@@ -23,7 +23,7 @@ export function mergedQuestionnairePatch(stored: Record<string, unknown> | null | undefined,sourcePatch: Pick<QuestionnaireAnswers,- "source" | "source_other" | "source_skipped"+ "source" | "source_other" | "source_skipped" | "source_domain_consent">,): QuestionnaireAnswers {const raw = (stored ?? {}) as Record<string, unknown>;@@ -31,6 +31,7 @@ export function mergedQuestionnairePatch(source: sourcePatch.source,source_other: sourcePatch.source_other,source_skipped: sourcePatch.source_skipped,+ source_domain_consent: sourcePatch.source_domain_consent !== false,role: coerceRole(raw.role),role_other: coerceString(raw.role_other),role_skipped: coerceBool(raw.role_skipped),diff --git a/packages/views/onboarding/source-backfill-modal.test.tsx b/packages/views/onboarding/source-backfill-modal.test.tsxindex 8ef72e0a2d..48275a5a12 100644--- a/packages/views/onboarding/source-backfill-modal.test.tsx+++ b/packages/views/onboarding/source-backfill-modal.test.tsx@@ -1,6 +1,7 @@import { act, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ApiClient, setApiInstance } from "@multica/core/api";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../locales/en/common.json";import enOnboarding from "../locales/en/onboarding.json";@@ -82,6 +83,7 @@ beforeEach(() => {mockSaveQuestionnaire.mockReset();mockSaveQuestionnaire.mockResolvedValue(undefined);mockCaptureEvent.mockReset();+ setApiInstance(new ApiClient("https://api.multica.ai"));setUser(null);wipeDismissCounters();mockPrefersReducedMotion(true);@@ -134,6 +136,32 @@ describe("SourceBackfillModal", () => {expect(mockCaptureEvent).toHaveBeenCalledWith("source_backfill_shown");});+ it("shows reporting controls after a source is selected on a non-official API URL", async () => {+ setApiInstance(new ApiClient("https://api.customer.example"));+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: { source: [] },+ });+ const user = userEvent.setup();+ renderModal();+ expect(+ screen.queryByText(+ "Help us understand how you heard about Multica. No extra information is sent.",+ ),+ ).not.toBeInTheDocument();+ await user.click(await screen.findByText("Friends or colleagues"));++ expect(+ screen.getByText(+ "Help us understand how you heard about Multica. No extra information is sent.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("switch", { name: /allow sending domain/i }),+ ).toBeChecked();+ });+it("Submit PATCHes the merged questionnaire preserving role / use_case", async () => {setUser({id: "u1",@@ -158,6 +186,7 @@ describe("SourceBackfillModal", () => {const sent = mockSaveQuestionnaire.mock.calls[0]![0];expect(sent.source).toEqual(["friends_colleagues"]);expect(sent.source_skipped).toBe(false);+ expect(sent.source_domain_consent).toBe(true);expect(sent.role).toBe("engineer");expect(sent.use_case).toEqual(["ship_code", "plan_research"]);expect(sent.version).toBe(2);@@ -167,6 +196,34 @@ describe("SourceBackfillModal", () => {);});+ it("persists false when the user disables plaintext domain reporting", async () => {+ setApiInstance(new ApiClient("https://api.customer.example"));+ setUser({+ id: "u1",+ onboarded_at: "2026-01-01T00:00:00Z",+ onboarding_questionnaire: {+ source: [],+ role: "engineer",+ use_case: ["ship_code"],+ version: 2,+ },+ });+ const user = userEvent.setup();+ renderModal();+ await user.click(await screen.findByText("Friends or colleagues"));+ await user.click(+ screen.getByRole("switch", { name: /allow sending domain/i }),+ );+ await user.click(screen.getByRole("button", { name: "Submit" }));++ await waitFor(() => {+ expect(mockSaveQuestionnaire).toHaveBeenCalledTimes(1);+ });+ expect(mockSaveQuestionnaire.mock.calls[0]![0].source_domain_consent).toBe(+ false,+ );+ });+it("Skip PATCHes source_skipped=true preserving role / use_case", async () => {setUser({id: "u1",@@ -189,6 +246,7 @@ describe("SourceBackfillModal", () => {const sent = mockSaveQuestionnaire.mock.calls[0]![0];expect(sent.source).toEqual([]);expect(sent.source_skipped).toBe(true);+ expect(sent.source_domain_consent).toBe(true);expect(sent.role).toBe("founder");expect(sent.use_case).toEqual(["manage_team"]);expect(mockCaptureEvent).toHaveBeenCalledWith("source_backfill_skipped");diff --git a/packages/views/onboarding/source-backfill-modal.tsx b/packages/views/onboarding/source-backfill-modal.tsxindex 39532aeccc..95268572bd 100644--- a/packages/views/onboarding/source-backfill-modal.tsx+++ b/packages/views/onboarding/source-backfill-modal.tsx@@ -16,6 +16,7 @@ import { useAuthStore } from "@multica/core/auth";import {needsSourceBackfill,saveQuestionnaire,+ shouldShowSourceChannelReporting,type QuestionnaireAnswers,type Source,} from "@multica/core/onboarding";@@ -37,17 +38,19 @@ import {IconOtherOptionCard,} from "./components/icon-option-card";import type { QuestionOption } from "./steps/step-question";+import { SourceReportingControls } from "./source-reporting-controls";import { mergedQuestionnairePatch } from "./source-backfill-merge";import { useSourceBackfillDismissCount } from "./source-backfill-dismiss";import { useT } from "../i18n";const EMPTY_BACKFILL: Pick<QuestionnaireAnswers,- "source" | "source_other" | "source_skipped"+ "source" | "source_other" | "source_skipped" | "source_domain_consent"> = {source: [],source_other: null,source_skipped: false,+ source_domain_consent: true,};/**@@ -162,6 +165,7 @@ function SourceBackfillDialogBody({onComplete: () => void;}) {const { t } = useT("onboarding");+ const showSourceReporting = shouldShowSourceChannelReporting();const [answers, setAnswers] = useState(EMPTY_BACKFILL);const [busy, setBusy] = useState(false);@@ -203,6 +207,7 @@ function SourceBackfillDialogBody({// HDYHAU prompts (Fairing, Recast, HockeyStack) and gives the team// clean channel weights without splitting users across N buckets.const pickedSlug: string | null = answers.source[0] ?? null;+ const domainConsent = answers.source_domain_consent !== false;const otherOption = options.find((o) => o.isOther) ?? null;const otherSelected = pickedSlug === otherOption?.slug;const otherFilled = (answers.source_other ?? "").trim().length > 0;@@ -225,6 +230,7 @@ function SourceBackfillDialogBody({// type immediately. A previous text value would be misleading.source_other: a.source[0] === "other" ? a.source_other : null,source_skipped: false,+ source_domain_consent: a.source_domain_consent !== false,}));return;}@@ -234,6 +240,7 @@ function SourceBackfillDialogBody({source: [slug],source_other: null,source_skipped: false,+ source_domain_consent: a.source_domain_consent !== false,}));},[],@@ -258,6 +265,7 @@ function SourceBackfillDialogBody({source: answers.source,source_other: answers.source_other,source_skipped: false,+ source_domain_consent: domainConsent,}),);captureEvent("source_backfill_submitted", {@@ -269,7 +277,7 @@ function SourceBackfillDialogBody({setBusy(false);toast.error(err instanceof Error ? err.message : "Failed to save");}- }, [canSubmit, answers.source, answers.source_other, onComplete]);+ }, [canSubmit, answers.source, answers.source_other, domainConsent, onComplete]);const skip = useCallback(async () => {if (busy) return;@@ -282,6 +290,7 @@ function SourceBackfillDialogBody({source: [],source_other: null,source_skipped: true,+ source_domain_consent: domainConsent,}),);captureEvent("source_backfill_skipped");@@ -290,11 +299,11 @@ function SourceBackfillDialogBody({setBusy(false);toast.error(err instanceof Error ? err.message : "Failed to save");}- }, [busy, onComplete]);+ }, [busy, domainConsent, onComplete]);return (- <DialogContent className="sm:max-w-2xl p-0 gap-0 overflow-hidden">- <div className="px-6 pt-6 pb-2">+ <DialogContent className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl">+ <div className="shrink-0 px-6 pt-6 pb-2"><div className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground">{t(($) => $.source_backfill.eyebrow)}</div>@@ -306,39 +315,55 @@ function SourceBackfillDialogBody({</p></div>- <fieldset- role="radiogroup"- aria-label={t(($) => $.questions.source.question)}- className="m-0 grid grid-cols-1 gap-2 p-0 px-6 pt-4 sm:grid-cols-2"- >- {options.map((option) =>- option.isOther ? (- <IconOtherOptionCard- key={option.slug}- icon={option.icon}- label={option.label}- selected={otherSelected}- onSelect={() => handleSelect(option)}- otherValue={answers.source_other ?? ""}- onOtherChange={handleOtherChange}- onConfirm={submit}- placeholder={t(($) => $.questions.source.other_placeholder)}- mode="radio"- />- ) : (- <IconOptionCard- key={option.slug}- icon={option.icon}- label={option.label}- selected={pickedSlug === option.slug}- onSelect={() => handleSelect(option)}- mode="radio"+ <div className="min-h-0 overflow-y-auto px-6 pt-4 pb-4">+ <fieldset+ role="radiogroup"+ aria-label={t(($) => $.questions.source.question)}+ className="m-0 grid grid-cols-1 gap-2 p-0 sm:grid-cols-2"+ >+ {options.map((option) =>+ option.isOther ? (+ <IconOtherOptionCard+ key={option.slug}+ icon={option.icon}+ label={option.label}+ selected={otherSelected}+ onSelect={() => handleSelect(option)}+ otherValue={answers.source_other ?? ""}+ onOtherChange={handleOtherChange}+ onConfirm={submit}+ placeholder={t(($) => $.questions.source.other_placeholder)}+ mode="radio"+ />+ ) : (+ <IconOptionCard+ key={option.slug}+ icon={option.icon}+ label={option.label}+ selected={pickedSlug === option.slug}+ onSelect={() => handleSelect(option)}+ mode="radio"+ />+ ),+ )}+ </fieldset>++ {showSourceReporting && pickedSlug !== null ? (+ <div className="pt-4">+ <SourceReportingControls+ domainConsent={domainConsent}+ onDomainConsentChange={(enabled) =>+ setAnswers((a) => ({+ ...a,+ source_domain_consent: enabled,+ }))+ }/>- ),- )}- </fieldset>+ </div>+ ) : null}+ </div>- <div className="mt-4 flex flex-wrap items-center justify-end gap-x-4 gap-y-2 border-t bg-muted/40 px-6 py-3">+ <div className="flex shrink-0 flex-wrap items-center justify-end gap-x-4 gap-y-2 border-t bg-muted/40 px-6 py-3"><spanaria-live="polite"className="mr-auto text-xs text-muted-foreground"diff --git a/packages/views/onboarding/source-reporting-controls.tsx b/packages/views/onboarding/source-reporting-controls.tsxnew file mode 100644index 0000000000..0ee4e3fe7a--- /dev/null+++ b/packages/views/onboarding/source-reporting-controls.tsx@@ -0,0 +1,45 @@+"use client";++import { useId } from "react";+import { Switch } from "@multica/ui/components/ui/switch";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";++export function SourceReportingControls({+ domainConsent,+ onDomainConsentChange,+ className,+}: {+ domainConsent: boolean;+ onDomainConsentChange: (enabled: boolean) => void;+ className?: string;+}) {+ const { t } = useT("onboarding");+ const labelId = useId();++ return (+ <section+ className={cn(+ "rounded-lg border bg-muted/30 p-4",+ className,+ )}+ >+ <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-3">+ <p className="min-w-0 flex-1 basis-64 text-sm leading-relaxed text-muted-foreground">+ {t(($) => $.source_reporting.description)}+ </p>++ <div className="flex shrink-0 items-center gap-3">+ <div id={labelId} className="text-sm font-medium text-foreground">+ {t(($) => $.source_reporting.domain.label)}+ </div>+ <Switch+ checked={domainConsent}+ onCheckedChange={onDomainConsentChange}+ aria-labelledby={labelId}+ />+ </div>+ </div>+ </section>+ );+}diff --git a/packages/views/onboarding/steps/step-question.tsx b/packages/views/onboarding/steps/step-question.tsxindex fdf20e833d..33aaa1ade0 100644--- a/packages/views/onboarding/steps/step-question.tsx+++ b/packages/views/onboarding/steps/step-question.tsx@@ -55,11 +55,14 @@ export function StepQuestion({onSkip,onBack,multiSelect = false,+ notice,+ afterOptions,}: {step: OnboardingStep;number: number;eyebrow?: string;question: string;+ notice?: ReactNode;options: readonly QuestionOption[];selectedSlugs: readonly string[];otherValue: string;@@ -73,6 +76,7 @@ export function StepQuestion({onSkip: () => void;onBack?: () => void;multiSelect?: boolean;+ afterOptions?: ReactNode;}) {const { t } = useT("onboarding");const [pendingOther, setPendingOther] = useState(false);@@ -170,6 +174,12 @@ export function StepQuestion({{question}</h1>+ {notice ? (+ <p className="mt-3 max-w-[640px] text-sm leading-relaxed text-muted-foreground">+ {notice}+ </p>+ ) : null}+<fieldsetrole={multiSelect ? "group" : "radiogroup"}aria-label={question}@@ -202,6 +212,12 @@ export function StepQuestion({)}</fieldset>+ {afterOptions ? (+ <div className="mt-6">+ {afterOptions}+ </div>+ ) : null}+<div className="mt-8 flex flex-wrap items-center justify-end gap-x-4 gap-y-2"><spanaria-live="polite"diff --git a/packages/views/onboarding/steps/step-role.test.tsx b/packages/views/onboarding/steps/step-role.test.tsxindex 0215927db9..855157c1a1 100644--- a/packages/views/onboarding/steps/step-role.test.tsx+++ b/packages/views/onboarding/steps/step-role.test.tsx@@ -13,6 +13,7 @@ const EMPTY: QuestionnaireAnswers = {source: [],source_other: null,source_skipped: false,+ source_domain_consent: true,role: null,role_other: null,role_skipped: false,diff --git a/packages/views/onboarding/steps/step-source.test.tsx b/packages/views/onboarding/steps/step-source.test.tsxindex 447834127e..6b6ee14a9d 100644--- a/packages/views/onboarding/steps/step-source.test.tsx+++ b/packages/views/onboarding/steps/step-source.test.tsx@@ -1,6 +1,7 @@import { describe, expect, it, vi, beforeEach } from "vitest";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";+import { ApiClient, setApiInstance } from "@multica/core/api";import type { QuestionnaireAnswers } from "@multica/core/onboarding";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../locales/en/common.json";@@ -13,6 +14,7 @@ const EMPTY: QuestionnaireAnswers = {source: [],source_other: null,source_skipped: false,+ source_domain_consent: true,role: null,role_other: null,role_skipped: false,@@ -42,7 +44,10 @@ function renderStep(answers: QuestionnaireAnswers = EMPTY) {}describe("StepSource (single-select primary source)", () => {- beforeEach(() => vi.restoreAllMocks());+ beforeEach(() => {+ vi.restoreAllMocks();+ setApiInstance(new ApiClient("https://api.multica.ai"));+ });it("clicking a non-Other option writes a one-element source array", async () => {const user = userEvent.setup();@@ -54,11 +59,47 @@ describe("StepSource (single-select primary source)", () => {source: ["social_linkedin"],source_other: null,source_skipped: false,+ source_domain_consent: true,});// A click only records — it must NOT auto-advance.expect(onAdvance).not.toHaveBeenCalled();});+ it("shows reporting controls after a source is selected on a non-official API URL", () => {+ setApiInstance(new ApiClient("https://api.customer.example"));++ renderStep({+ ...EMPTY,+ source: ["social_linkedin"],+ });++ expect(+ screen.getByText(+ "Help us understand how you heard about Multica. No extra information is sent.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("switch", { name: /allow sending domain/i }),+ ).toBeChecked();+ });++ it("lets the user disable plaintext domain reporting", async () => {+ setApiInstance(new ApiClient("https://api.customer.example"));+ const user = userEvent.setup();+ const { onChange } = renderStep({+ ...EMPTY,+ source: ["search"],+ });++ await user.click(+ screen.getByRole("switch", { name: /allow sending domain/i }),+ );++ expect(onChange).toHaveBeenLastCalledWith({+ source_domain_consent: false,+ });+ });+it("picking a second option replaces the first (no stacking)", async () => {const user = userEvent.setup();const { onChange } = renderStep({@@ -72,6 +113,7 @@ describe("StepSource (single-select primary source)", () => {source: ["social_x"],source_other: null,source_skipped: false,+ source_domain_consent: true,});});@@ -99,6 +141,7 @@ describe("StepSource (single-select primary source)", () => {source: ["other"],source_other: null,source_skipped: false,+ source_domain_consent: true,});const input = await screen.findByPlaceholderText(/podcast/i);@@ -120,6 +163,7 @@ describe("StepSource (single-select primary source)", () => {source: ["social_linkedin"],source_other: null,source_skipped: false,+ source_domain_consent: true,});});});diff --git a/packages/views/onboarding/steps/step-source.tsx b/packages/views/onboarding/steps/step-source.tsxindex fa9476fff1..f6190d8c23 100644--- a/packages/views/onboarding/steps/step-source.tsx+++ b/packages/views/onboarding/steps/step-source.tsx@@ -9,7 +9,11 @@ import {Newspaper,Users,} from "lucide-react";-import type { QuestionnaireAnswers, Source } from "@multica/core/onboarding";+import {+ shouldShowSourceChannelReporting,+ type QuestionnaireAnswers,+ type Source,+} from "@multica/core/onboarding";import {GoogleIcon,LinkedInIcon,@@ -18,6 +22,7 @@ import {YouTubeIcon,GitHubIcon,} from "../components/brand-icons";+import { SourceReportingControls } from "../source-reporting-controls";import { StepQuestion, type QuestionOption } from "./step-question";import { useT } from "../../i18n";@@ -39,6 +44,7 @@ export function StepSource({onBack?: () => void;}) {const { t } = useT("onboarding");+ const showSourceReporting = shouldShowSourceChannelReporting();const options: QuestionOption[] = [{ slug: "friends_colleagues", icon: <Users className="h-4 w-4" />, label: t(($) => $.questions.source.friends_colleagues) },@@ -63,6 +69,7 @@ export function StepSource({// HDYHAU prompts (Fairing, Recast, HockeyStack) and keeps channel// weights clean for analytics.const selected: readonly string[] = answers.source?.[0] ? [answers.source[0]] : [];+ const domainConsent = answers.source_domain_consent !== false;const pick = (slug: string) => {const typed = slug as Source;@@ -74,6 +81,7 @@ export function StepSource({// their input.source_other: typed === "other" ? answers.source_other : null,source_skipped: false,+ source_domain_consent: domainConsent,});};@@ -95,6 +103,16 @@ export function StepSource({onSkip();}}onBack={onBack}+ afterOptions={+ showSourceReporting && selected.length > 0 ? (+ <SourceReportingControls+ domainConsent={domainConsent}+ onDomainConsentChange={(enabled) =>+ onChange({ source_domain_consent: enabled })+ }+ />+ ) : null+ }/>);}diff --git a/packages/views/onboarding/steps/step-use-case.test.tsx b/packages/views/onboarding/steps/step-use-case.test.tsxindex 00c8894699..c65cfb004b 100644--- a/packages/views/onboarding/steps/step-use-case.test.tsx+++ b/packages/views/onboarding/steps/step-use-case.test.tsx@@ -13,6 +13,7 @@ const EMPTY: QuestionnaireAnswers = {source: [],source_other: null,source_skipped: false,+ source_domain_consent: true,role: null,role_other: null,role_skipped: false,diff --git a/server/cmd/server/metrics_test.go b/server/cmd/server/metrics_test.goindex 5e06c99978..183ae1eba8 100644--- a/server/cmd/server/metrics_test.go+++ b/server/cmd/server/metrics_test.go@@ -3,6 +3,7 @@ package mainimport ("net/http""net/http/httptest"+ "strings""testing""github.com/multica-ai/multica/server/internal/analytics"@@ -21,3 +22,19 @@ func TestMainRouterDoesNotExposePrometheusMetrics(t *testing.T) {t.Fatalf("main API /metrics status = %d, want %d", rec.Code, http.StatusNotFound)}}++func TestRouterExposesSourceChannelIngest(t *testing.T) {+ router := NewRouter(nil, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil)++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(+ http.MethodPost,+ "/api/acquisition/self-host-source",+ strings.NewReader(`{}`),+ )+ router.ServeHTTP(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("source channel ingest status = %d, want %d", rec.Code, http.StatusBadRequest)+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 3f71b970bd..aebc3e60f2 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -31,6 +31,7 @@ import ("github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/realtime""github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/sourcechannel""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/internal/util/secretbox"@@ -175,6 +176,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus}h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)h.Metrics = opts.BusinessMetrics+ if pool != nil {+ if reporter, err := sourcechannel.NewSender(queries, sourcechannel.SenderConfig{}); err != nil {+ slog.Warn("source channel reporter disabled", "error", err)+ } else {+ h.SourceChannelReporter = reporter+ slog.Info("source channel reporter enabled")+ }+ }if opts.FeatureFlags != nil {h.DaemonFeatureFlags = featureflagdispatch.NewEvaluator(opts.FeatureFlags)}@@ -602,6 +611,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusauthRL := middleware.RateLimit(rdb, envPositiveInt("RATE_LIMIT_AUTH", 5), time.Minute, trustedProxies)authVerifyRL := middleware.RateLimit(rdb, envPositiveInt("RATE_LIMIT_AUTH_VERIFY", 20), time.Minute, trustedProxies)contactSalesRL := middleware.RateLimit(rdb, envPositiveInt("RATE_LIMIT_CONTACT_SALES", 5), time.Hour, trustedProxies)+ selfHostSourceRL := middleware.RateLimit(rdb, 60, time.Minute, trustedProxies)r.With(authRL).Post("/auth/send-code", h.SendCode)r.With(authVerifyRL).Post("/auth/verify-code", h.VerifyCode)r.With(authRL).Post("/auth/google", h.GoogleLogin)@@ -609,6 +619,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Public APIr.Get("/api/config", h.GetConfig)+ r.With(selfHostSourceRL).Post("/api/acquisition/self-host-source", h.RecordSelfHostSourceChannel)r.With(contactSalesRL).Post("/api/contact-sales", h.CreateContactSales)// Webhook ingress for autopilots. Outside the authenticated group ondiff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 1d97efc3ce..21d739266c 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -103,6 +103,10 @@ type RuntimeProfileRefreshNotifier interface {NotifyRuntimeProfilesChanged(workspaceID, profileID string)}+type SourceChannelReporter interface {+ ReportSelfHostSourceChannel(userID, channel, sourceOther, apiBaseURL string, includeDomain bool)+}+type Handler struct {Queries *db.QueriesDB dbExecutor@@ -125,6 +129,7 @@ type Handler struct {Storage storage.StorageCFSigner *auth.CloudFrontSignerAnalytics analytics.Client+ SourceChannelReporter SourceChannelReporter// Metrics is the shared business-metrics collector built by main.go.// May be nil in tests / self-hosted with the metrics listener disabled;// every Record* method is nil-safe and obsmetrics.RecordEvent treats adiff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.goindex b05f820edf..b8f17e3580 100644--- a/server/internal/handler/onboarding.go+++ b/server/internal/handler/onboarding.go@@ -13,6 +13,7 @@ import ("github.com/multica-ai/multica/server/internal/logger"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/sourcechannel"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -170,16 +171,17 @@ func (s *stringOrSlice) UnmarshalJSON(data []byte) error {}type questionnaireAnswers struct {- Source stringOrSlice `json:"source"`- SourceOther string `json:"source_other"`- SourceSkipped bool `json:"source_skipped"`- Role string `json:"role"`- RoleOther string `json:"role_other"`- RoleSkipped bool `json:"role_skipped"`- UseCase stringOrSlice `json:"use_case"`- UseCaseOther string `json:"use_case_other"`- UseCaseSkipped bool `json:"use_case_skipped"`- Version int `json:"version"`+ Source stringOrSlice `json:"source"`+ SourceOther string `json:"source_other"`+ SourceSkipped bool `json:"source_skipped"`+ SourceDomainConsent bool `json:"source_domain_consent"`+ Role string `json:"role"`+ RoleOther string `json:"role_other"`+ RoleSkipped bool `json:"role_skipped"`+ UseCase stringOrSlice `json:"use_case"`+ UseCaseOther string `json:"use_case_other"`+ UseCaseSkipped bool `json:"use_case_skipped"`+ Version int `json:"version"`}func (q questionnaireAnswers) sourceResolved() bool {@@ -234,8 +236,10 @@ func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {// we should, never twice for the same transition.var before questionnaireAnswersbeforeRaw := []byte("{}")+ beforeOnboarded := falseif beforeUser, err := h.Queries.GetUser(r.Context(), parseUUID(userID)); err == nil {beforeRaw = beforeUser.OnboardingQuestionnaire+ beforeOnboarded = beforeUser.OnboardedAt.Valid_ = json.Unmarshal(beforeRaw, &before)}// firstTouch is true when the user has never written any@@ -265,6 +269,7 @@ func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {var after questionnaireAnswers_ = json.Unmarshal(user.OnboardingQuestionnaire, &after)+ h.reportSelfHostSourceChannelIfNeeded(r, userID, before, after, beforeOnboarded)if after.complete() && !before.complete() {obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingQuestionnaireSubmitted(userID,@@ -283,6 +288,22 @@ func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, userToResponse(user))}+func (h *Handler) reportSelfHostSourceChannelIfNeeded(r *http.Request, userID string, before, after questionnaireAnswers, beforeOnboarded bool) {+ if h.SourceChannelReporter == nil || len(after.Source) == 0 {+ return+ }+ channel := strings.TrimSpace(after.Source[0])+ if channel == "" {+ return+ }++ questionnaireJustCompleted := after.complete() && !before.complete()+ backfillSubmitted := beforeOnboarded && len(before.Source) == 0 && !before.SourceSkipped && len(after.Source) > 0+ if questionnaireJustCompleted || backfillSubmitted {+ h.SourceChannelReporter.ReportSelfHostSourceChannel(userID, channel, after.SourceOther, sourcechannel.ReportingAPIBaseURL(r), after.SourceDomainConsent)+ }+}+type joinCloudWaitlistRequest struct {Email string `json:"email"`Reason string `json:"reason"`diff --git a/server/internal/handler/onboarding_test.go b/server/internal/handler/onboarding_test.goindex d047b56a57..32dc402e16 100644--- a/server/internal/handler/onboarding_test.go+++ b/server/internal/handler/onboarding_test.go@@ -44,6 +44,214 @@ func newWaitlistRequest(userID string, body map[string]string) *http.Request {return req}+type recordedSourceChannelReport struct {+ userID string+ channel string+ sourceOther string+ apiBaseURL string+ includeDomain bool+}++type recordingSourceChannelReporter struct {+ calls []recordedSourceChannelReport+}++func (r *recordingSourceChannelReporter) ReportSelfHostSourceChannel(userID, channel, sourceOther, apiBaseURL string, includeDomain bool) {+ r.calls = append(r.calls, recordedSourceChannelReport{userID: userID, channel: channel, sourceOther: sourceOther, apiBaseURL: apiBaseURL, includeDomain: includeDomain})+}++func installRecordingSourceChannelReporter(t *testing.T) *recordingSourceChannelReporter {+ t.Helper()+ recorder := &recordingSourceChannelReporter{}+ prev := testHandler.SourceChannelReporter+ testHandler.SourceChannelReporter = recorder+ t.Cleanup(func() { testHandler.SourceChannelReporter = prev })+ return recorder+}++func newPatchOnboardingRequest(userID string, questionnaire string) *http.Request {+ body := map[string]json.RawMessage{+ "questionnaire": json.RawMessage(questionnaire),+ }+ var buf bytes.Buffer+ json.NewEncoder(&buf).Encode(body)+ req := httptest.NewRequest(http.MethodPatch, "/api/me/onboarding", &buf)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-User-ID", userID)+ return req+}++func TestPatchOnboardingReportsSelfHostSourceWhenQuestionnaireCompletes(t *testing.T) {+ userID := newWaitlistTestUser(t, "[email protected]")+ recorder := installRecordingSourceChannelReporter(t)++ w := httptest.NewRecorder()+ testHandler.PatchOnboarding(w, newPatchOnboardingRequest(userID, `{+ "source": ["search"],+ "source_other": null,+ "source_skipped": false,+ "source_domain_consent": true,+ "version": 2+ }`))+ if w.Code != http.StatusOK {+ t.Fatalf("source-only patch: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if len(recorder.calls) != 0 {+ t.Fatalf("source-only patch should not report before questionnaire completion, got %+v", recorder.calls)+ }++ w = httptest.NewRecorder()+ testHandler.PatchOnboarding(w, newPatchOnboardingRequest(userID, `{+ "source": ["search"],+ "source_other": null,+ "source_skipped": false,+ "source_domain_consent": true,+ "role": "engineer",+ "role_other": null,+ "role_skipped": false,+ "use_case": ["ship_code"],+ "use_case_other": null,+ "use_case_skipped": false,+ "version": 2+ }`))+ if w.Code != http.StatusOK {+ t.Fatalf("complete patch: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if len(recorder.calls) != 1 {+ t.Fatalf("complete patch should report once, got %+v", recorder.calls)+ }+ if recorder.calls[0].userID != userID || recorder.calls[0].channel != "search" {+ t.Fatalf("unexpected report: %+v", recorder.calls[0])+ }+ if !recorder.calls[0].includeDomain {+ t.Fatalf("expected plaintext domain consent to be forwarded")+ }++ w = httptest.NewRecorder()+ testHandler.PatchOnboarding(w, newPatchOnboardingRequest(userID, `{+ "source": ["search"],+ "source_other": null,+ "source_skipped": false,+ "source_domain_consent": true,+ "role": "engineer",+ "role_other": null,+ "role_skipped": false,+ "use_case": ["ship_code"],+ "use_case_other": null,+ "use_case_skipped": false,+ "version": 2+ }`))+ if w.Code != http.StatusOK {+ t.Fatalf("unchanged complete patch: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if len(recorder.calls) != 1 {+ t.Fatalf("unchanged complete patch should not report again, got %+v", recorder.calls)+ }+}++func TestPatchOnboardingReportsSelfHostSourceWithoutPlaintextDomain(t *testing.T) {+ userID := newWaitlistTestUser(t, "[email protected]")+ recorder := installRecordingSourceChannelReporter(t)++ w := httptest.NewRecorder()+ testHandler.PatchOnboarding(w, newPatchOnboardingRequest(userID, `{+ "source": ["search"],+ "source_other": null,+ "source_skipped": false,+ "source_domain_consent": false,+ "role": "engineer",+ "role_other": null,+ "role_skipped": false,+ "use_case": ["ship_code"],+ "use_case_other": null,+ "use_case_skipped": false,+ "version": 2+ }`))+ if w.Code != http.StatusOK {+ t.Fatalf("complete patch: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if len(recorder.calls) != 1 {+ t.Fatalf("complete patch should report once, got %+v", recorder.calls)+ }+ if recorder.calls[0].includeDomain {+ t.Fatalf("expected plaintext domain consent to be false")+ }+}++func TestPatchOnboardingReportsSelfHostSourceOtherText(t *testing.T) {+ userID := newWaitlistTestUser(t, "[email protected]")+ recorder := installRecordingSourceChannelReporter(t)++ w := httptest.NewRecorder()+ testHandler.PatchOnboarding(w, newPatchOnboardingRequest(userID, `{+ "source": ["other"],+ "source_other": "a podcast",+ "source_skipped": false,+ "source_domain_consent": true,+ "role": "engineer",+ "role_other": null,+ "role_skipped": false,+ "use_case": ["ship_code"],+ "use_case_other": null,+ "use_case_skipped": false,+ "version": 2+ }`))+ if w.Code != http.StatusOK {+ t.Fatalf("complete other patch: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if len(recorder.calls) != 1 {+ t.Fatalf("complete other patch should report once, got %+v", recorder.calls)+ }+ if recorder.calls[0].userID != userID || recorder.calls[0].channel != "other" || recorder.calls[0].sourceOther != "a podcast" {+ t.Fatalf("unexpected report: %+v", recorder.calls[0])+ }+}++func TestPatchOnboardingReportsSelfHostSourceForBackfillSubmit(t *testing.T) {+ userID := newWaitlistTestUser(t, "[email protected]")+ if _, err := testPool.Exec(context.Background(), `+ UPDATE "user"+ SET onboarded_at = now(),+ onboarding_questionnaire = $2::jsonb+ WHERE id = $1+ `, userID, `{+ "role": "engineer",+ "role_other": null,+ "role_skipped": false,+ "use_case": ["ship_code"],+ "use_case_other": null,+ "use_case_skipped": false,+ "version": 2+ }`); err != nil {+ t.Fatalf("seed onboarded user: %v", err)+ }+ recorder := installRecordingSourceChannelReporter(t)++ w := httptest.NewRecorder()+ testHandler.PatchOnboarding(w, newPatchOnboardingRequest(userID, `{+ "source": ["blog_newsletter"],+ "source_other": null,+ "source_skipped": false,+ "source_domain_consent": true,+ "role": "engineer",+ "role_other": null,+ "role_skipped": false,+ "use_case": ["ship_code"],+ "use_case_other": null,+ "use_case_skipped": false,+ "version": 2+ }`))+ if w.Code != http.StatusOK {+ t.Fatalf("backfill patch: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if len(recorder.calls) != 1 {+ t.Fatalf("backfill patch should report once, got %+v", recorder.calls)+ }+ if recorder.calls[0].userID != userID || recorder.calls[0].channel != "blog_newsletter" {+ t.Fatalf("unexpected report: %+v", recorder.calls[0])+ }+}+func TestJoinCloudWaitlistRecordsEmailAndReason(t *testing.T) {userID := newWaitlistTestUser(t, "[email protected]")diff --git a/server/internal/handler/self_host_source_channel.go b/server/internal/handler/self_host_source_channel.gonew file mode 100644index 0000000000..df6791713d--- /dev/null+++ b/server/internal/handler/self_host_source_channel.go@@ -0,0 +1,95 @@+package handler++import (+ "encoding/json"+ "io"+ "log/slog"+ "net/http"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/sourcechannel"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const selfHostSourceChannelBodyLimit = 4 * 1024++// RecordSelfHostSourceChannel receives the anonymous source-channel report+// posted by self-hosted Multica instances. The payload deliberately excludes+// account/profile/workspace data; only a fixed channel enum, optional+// "other" text, an optional reporting domain, and dedupe hashes are accepted.+func (h *Handler) RecordSelfHostSourceChannel(w http.ResponseWriter, r *http.Request) {+ r.Body = http.MaxBytesReader(w, r.Body, selfHostSourceChannelBodyLimit)+ dec := json.NewDecoder(r.Body)+ dec.DisallowUnknownFields()++ var req sourcechannel.Report+ if err := dec.Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if err := dec.Decode(&struct{}{}); err != io.EOF {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ channel := sourcechannel.NormalizeChannel(req.Channel)+ instanceHash := sourcechannel.NormalizeHash(req.InstanceHash)+ subjectHash := sourcechannel.NormalizeHash(req.SubjectHash)+ sourceOther := sourcechannel.NormalizeSourceOther(channel, req.SourceOther)+ domain := ""+ if req.Domain != nil {+ domain = sourcechannel.NormalizeDomain(*req.Domain)+ }+ domainMD5 := sourcechannel.NormalizeHash(req.DomainMD5)+ if req.SchemaVersion != sourcechannel.SchemaVersion {+ writeError(w, http.StatusBadRequest, "unsupported schema_version")+ return+ }+ if !sourcechannel.ValidChannel(channel) {+ writeError(w, http.StatusBadRequest, "invalid channel")+ return+ }+ if !sourcechannel.ValidHash(instanceHash) {+ writeError(w, http.StatusBadRequest, "invalid instance_hash")+ return+ }+ if !sourcechannel.ValidHash(subjectHash) {+ writeError(w, http.StatusBadRequest, "invalid subject_hash")+ return+ }+ if req.Domain != nil && (domain == "" || sourcechannel.IsOfficialMulticaAPIURL(domain)) {+ writeError(w, http.StatusBadRequest, "invalid domain")+ return+ }+ if domainMD5 == "" || !sourcechannel.ValidDomainMD5(domainMD5) {+ writeError(w, http.StatusBadRequest, "invalid domain_md5")+ return+ }+ if domain != "" && domainMD5 != sourcechannel.DomainMD5(domain) {+ writeError(w, http.StatusBadRequest, "invalid domain_md5")+ return+ }++ params := db.UpsertSelfHostSourceChannelParams{+ SchemaVersion: int32(req.SchemaVersion),+ Channel: channel,+ InstanceHash: instanceHash,+ SubjectHash: subjectHash,+ DomainMd5: pgtype.Text{String: domainMD5, Valid: true},+ }+ if domain != "" {+ params.Domain = pgtype.Text{String: domain, Valid: true}+ }+ if sourceOther != "" {+ params.SourceOther = pgtype.Text{String: sourceOther, Valid: true}+ }+ _, err := h.Queries.UpsertSelfHostSourceChannel(r.Context(), params)+ if err != nil {+ slog.Warn("self-host source channel upsert failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to record source channel")+ return+ }++ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})+}diff --git a/server/internal/handler/self_host_source_channel_test.go b/server/internal/handler/self_host_source_channel_test.gonew file mode 100644index 0000000000..e31076f587--- /dev/null+++ b/server/internal/handler/self_host_source_channel_test.go@@ -0,0 +1,190 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/sourcechannel"+)++func TestRecordSelfHostSourceChannelUpsertsByAnonymousSubject(t *testing.T) {+ instanceHash := strings.Repeat("a", 64)+ subjectHash := strings.Repeat("b", 64)+ t.Cleanup(func() {+ testPool.Exec(context.Background(),+ `DELETE FROM self_host_source_channel WHERE instance_hash = $1 AND subject_hash = $2`,+ instanceHash,+ subjectHash,+ )+ })++ postSourceReport(t, sourcechannel.Report{+ SchemaVersion: sourcechannel.SchemaVersion,+ Channel: "other",+ InstanceHash: instanceHash,+ SubjectHash: subjectHash,+ SourceOther: " a podcast ",+ Domain: stringPtr("example.com"),+ DomainMD5: sourcechannel.DomainMD5("example.com"),+ })+ postSourceReport(t, sourcechannel.Report{+ SchemaVersion: sourcechannel.SchemaVersion,+ Channel: "search",+ InstanceHash: instanceHash,+ SubjectHash: subjectHash,+ Domain: stringPtr("example.com"),+ DomainMD5: sourcechannel.DomainMD5("example.com"),+ })++ var (+ channel string+ sourceOther pgtype.Text+ domain pgtype.Text+ domainMD5 pgtype.Text+ reportCount int+ )+ if err := testPool.QueryRow(context.Background(), `+ SELECT channel, source_other, domain, domain_md5, report_count+ FROM self_host_source_channel+ WHERE instance_hash = $1 AND subject_hash = $2+ `, instanceHash, subjectHash).Scan(&channel, &sourceOther, &domain, &domainMD5, &reportCount); err != nil {+ t.Fatalf("load source channel row: %v", err)+ }+ if channel != "search" {+ t.Fatalf("channel: want latest value search, got %q", channel)+ }+ if sourceOther.Valid {+ t.Fatalf("source_other should clear when latest channel is not other, got %q", sourceOther.String)+ }+ if !domain.Valid || domain.String != "example.com" {+ t.Fatalf("domain: want example.com, got %+v", domain)+ }+ if !domainMD5.Valid || domainMD5.String != sourcechannel.DomainMD5("example.com") {+ t.Fatalf("domain_md5: want %q, got %+v", sourcechannel.DomainMD5("example.com"), domainMD5)+ }+ if reportCount != 2 {+ t.Fatalf("report_count: want 2, got %d", reportCount)+ }+}++func TestRecordSelfHostSourceChannelStoresOtherText(t *testing.T) {+ instanceHash := strings.Repeat("c", 64)+ subjectHash := strings.Repeat("d", 64)+ t.Cleanup(func() {+ testPool.Exec(context.Background(),+ `DELETE FROM self_host_source_channel WHERE instance_hash = $1 AND subject_hash = $2`,+ instanceHash,+ subjectHash,+ )+ })++ postSourceReport(t, sourcechannel.Report{+ SchemaVersion: sourcechannel.SchemaVersion,+ Channel: "other",+ InstanceHash: instanceHash,+ SubjectHash: subjectHash,+ SourceOther: " private free text ",+ Domain: stringPtr("example.com"),+ DomainMD5: sourcechannel.DomainMD5("example.com"),+ })++ var sourceOther pgtype.Text+ if err := testPool.QueryRow(context.Background(), `+ SELECT source_other+ FROM self_host_source_channel+ WHERE instance_hash = $1 AND subject_hash = $2+ `, instanceHash, subjectHash).Scan(&sourceOther); err != nil {+ t.Fatalf("load source_other: %v", err)+ }+ if !sourceOther.Valid || sourceOther.String != "private free text" {+ t.Fatalf("source_other: want trimmed text, got %+v", sourceOther)+ }+}++func TestRecordSelfHostSourceChannelRejectsInvalidDomainHash(t *testing.T) {+ payload := sourcechannel.Report{+ SchemaVersion: sourcechannel.SchemaVersion,+ Channel: "search",+ InstanceHash: strings.Repeat("e", 64),+ SubjectHash: strings.Repeat("f", 64),+ Domain: stringPtr("example.com"),+ DomainMD5: sourcechannel.DomainMD5("other.example"),+ }+ body, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal report: %v", err)+ }+ req := httptest.NewRequest(http.MethodPost, "/api/acquisition/self-host-source", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()++ testHandler.RecordSelfHostSourceChannel(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for invalid domain_md5, got %d: %s", w.Code, w.Body.String())+ }+}++func TestRecordSelfHostSourceChannelAcceptsHashOnlyDomain(t *testing.T) {+ instanceHash := strings.Repeat("1", 64)+ subjectHash := strings.Repeat("2", 64)+ t.Cleanup(func() {+ testPool.Exec(context.Background(),+ `DELETE FROM self_host_source_channel WHERE instance_hash = $1 AND subject_hash = $2`,+ instanceHash,+ subjectHash,+ )+ })++ postSourceReport(t, sourcechannel.Report{+ SchemaVersion: sourcechannel.SchemaVersion,+ Channel: "search",+ InstanceHash: instanceHash,+ SubjectHash: subjectHash,+ Domain: nil,+ DomainMD5: sourcechannel.DomainMD5("example.com"),+ })++ var (+ domain pgtype.Text+ domainMD5 pgtype.Text+ )+ if err := testPool.QueryRow(context.Background(), `+ SELECT domain, domain_md5+ FROM self_host_source_channel+ WHERE instance_hash = $1 AND subject_hash = $2+ `, instanceHash, subjectHash).Scan(&domain, &domainMD5); err != nil {+ t.Fatalf("load source channel row: %v", err)+ }+ if domain.Valid {+ t.Fatalf("domain should be NULL when plaintext domain is omitted, got %+v", domain)+ }+ if !domainMD5.Valid || domainMD5.String != sourcechannel.DomainMD5("example.com") {+ t.Fatalf("domain_md5: want %q, got %+v", sourcechannel.DomainMD5("example.com"), domainMD5)+ }+}++func postSourceReport(t *testing.T, payload sourcechannel.Report) {+ t.Helper()+ body, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal report: %v", err)+ }+ req := httptest.NewRequest(http.MethodPost, "/api/acquisition/self-host-source", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()++ testHandler.RecordSelfHostSourceChannel(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("RecordSelfHostSourceChannel: expected 200, got %d: %s", w.Code, w.Body.String())+ }+}++func stringPtr(s string) *string {+ return &s+}diff --git a/server/internal/sourcechannel/sender.go b/server/internal/sourcechannel/sender.gonew file mode 100644index 0000000000..e14f807011--- /dev/null+++ b/server/internal/sourcechannel/sender.go@@ -0,0 +1,182 @@+package sourcechannel++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/hex"+ "encoding/json"+ "errors"+ "io"+ "log/slog"+ "net/http"+ "strings"+ "sync"+ "time"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const (+ ReportPath = "/api/acquisition/self-host-source"+ // Temporary validation target for the dev/staging rollout of #4741.+ sourceChannelReportAPIURL = "https://multica-api.copilothub.ai"+ systemSaltKey = "self_host_source_channel_salt"+ defaultTimeout = 3 * time.Second+)++type settingStore interface {+ GetOrCreateSystemSetting(ctx context.Context, arg db.GetOrCreateSystemSettingParams) (string, error)+}++type SenderConfig struct {+ HTTPClient *http.Client+ Timeout time.Duration+ Logger *slog.Logger+}++type Sender struct {+ settings settingStore+ client *http.Client+ endpoint string+ timeout time.Duration+ logger *slog.Logger++ mu sync.RWMutex+ salt string+}++func NewSender(settings settingStore, cfg SenderConfig) (*Sender, error) {+ if settings == nil {+ return nil, errors.New("sourcechannel: settings store is nil")+ }+ client := cfg.HTTPClient+ if client == nil {+ client = http.DefaultClient+ }+ timeout := cfg.Timeout+ if timeout <= 0 {+ timeout = defaultTimeout+ }+ logger := cfg.Logger+ if logger == nil {+ logger = slog.Default()+ }+ return &Sender{+ settings: settings,+ client: client,+ endpoint: sourceChannelReportAPIURL + ReportPath,+ timeout: timeout,+ logger: logger,+ }, nil+}++func MustNewSender(settings settingStore, cfg SenderConfig) *Sender {+ s, err := NewSender(settings, cfg)+ if err != nil {+ panic(err)+ }+ return s+}++func (s *Sender) ReportSelfHostSourceChannel(userID, channel, sourceOther, apiBaseURL string, includeDomain bool) {+ if s == nil {+ return+ }+ userID = strings.TrimSpace(userID)+ channel = NormalizeChannel(channel)+ if userID == "" || !ValidChannel(channel) {+ return+ }+ domain := NormalizeDomain(apiBaseURL)+ if !ShouldReportAPIBaseURL(apiBaseURL) {+ return+ }+ sourceOther = NormalizeSourceOther(channel, sourceOther)+ go s.report(context.Background(), userID, channel, sourceOther, domain, includeDomain)+}++func (s *Sender) report(parent context.Context, userID, channel, sourceOther, domain string, includeDomain bool) {+ ctx, cancel := context.WithTimeout(parent, s.timeout)+ defer cancel()++ salt, err := s.instanceSalt(ctx)+ if err != nil {+ s.logger.Debug("self-host source channel: salt unavailable", "error", err)+ return+ }++ var plainDomain *string+ if includeDomain {+ plainDomain = &domain+ }+ payload := Report{+ SchemaVersion: SchemaVersion,+ Channel: channel,+ InstanceHash: InstanceHash(salt),+ SubjectHash: SubjectHash(salt, userID),+ SourceOther: sourceOther,+ Domain: plainDomain,+ DomainMD5: DomainMD5(domain),+ }+ body, err := json.Marshal(payload)+ if err != nil {+ s.logger.Debug("self-host source channel: encode failed", "error", err)+ return+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.endpoint, bytes.NewReader(body))+ if err != nil {+ s.logger.Debug("self-host source channel: request build failed", "error", err)+ return+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("User-Agent", "multica-self-host-source/1")++ resp, err := s.client.Do(req)+ if err != nil {+ s.logger.Debug("self-host source channel: post failed", "error", err)+ return+ }+ defer resp.Body.Close()+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1024))+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ s.logger.Debug("self-host source channel: non-2xx response", "status", resp.StatusCode)+ }+}++func (s *Sender) instanceSalt(ctx context.Context) (string, error) {+ s.mu.RLock()+ if s.salt != "" {+ defer s.mu.RUnlock()+ return s.salt, nil+ }+ s.mu.RUnlock()++ s.mu.Lock()+ defer s.mu.Unlock()+ if s.salt != "" {+ return s.salt, nil+ }+ candidate, err := randomSalt()+ if err != nil {+ return "", err+ }+ salt, err := s.settings.GetOrCreateSystemSetting(ctx, db.GetOrCreateSystemSettingParams{+ Key: systemSaltKey,+ Value: candidate,+ })+ if err != nil {+ return "", err+ }+ s.salt = strings.TrimSpace(salt)+ return s.salt, nil+}++func randomSalt() (string, error) {+ b := make([]byte, 32)+ if _, err := rand.Read(b); err != nil {+ return "", err+ }+ return hex.EncodeToString(b), nil+}diff --git a/server/internal/sourcechannel/sender_test.go b/server/internal/sourcechannel/sender_test.gonew file mode 100644index 0000000000..0c584d77ce--- /dev/null+++ b/server/internal/sourcechannel/sender_test.go@@ -0,0 +1,193 @@+package sourcechannel++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "strings"+ "testing"+ "time"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type fakeSettingStore struct {+ value string+}++func (f fakeSettingStore) GetOrCreateSystemSetting(context.Context, db.GetOrCreateSystemSettingParams) (string, error) {+ return f.value, nil+}++type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {+ return f(req)+}++func recordingClient(t *testing.T, got chan<- Report) *http.Client {+ t.Helper()+ return &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ if req.Method != http.MethodPost {+ t.Errorf("method: want POST, got %s", req.Method)+ }+ if req.URL.String() != sourceChannelReportAPIURL+ReportPath {+ t.Errorf("url: want %s, got %s", sourceChannelReportAPIURL+ReportPath, req.URL.String())+ }+ var payload Report+ if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {+ t.Errorf("decode payload: %v", err)+ }+ got <- payload+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: make(http.Header),+ Body: io.NopCloser(strings.NewReader("")),+ Request: req,+ }, nil+ }),+ }+}++func TestSenderReportsChannelOtherTextAndAnonymousHashes(t *testing.T) {+ got := make(chan Report, 1)+ sender := MustNewSender(fakeSettingStore{value: strings.Repeat("f", 64)}, SenderConfig{+ HTTPClient: recordingClient(t, got),+ Timeout: time.Second,+ })+ sender.ReportSelfHostSourceChannel("user-123", "Other", " a podcast ", "https://Example.com:443/path", true)++ select {+ case payload := <-got:+ if payload.SchemaVersion != SchemaVersion {+ t.Fatalf("schema_version: want %d, got %d", SchemaVersion, payload.SchemaVersion)+ }+ if payload.Channel != "other" {+ t.Fatalf("channel: want other, got %q", payload.Channel)+ }+ if payload.SourceOther != "a podcast" {+ t.Fatalf("source_other: want trimmed text, got %q", payload.SourceOther)+ }+ if payload.Domain == nil || *payload.Domain != "example.com" {+ t.Fatalf("domain: want example.com, got %+v", payload.Domain)+ }+ if payload.DomainMD5 != DomainMD5("example.com") {+ t.Fatalf("domain_md5: want %q, got %q", DomainMD5("example.com"), payload.DomainMD5)+ }+ if !ValidHash(payload.InstanceHash) || !ValidHash(payload.SubjectHash) {+ t.Fatalf("hashes should be 64-char lowercase hex: %+v", payload)+ }+ if payload.SubjectHash == "user-123" || strings.Contains(payload.SubjectHash, "user-123") {+ t.Fatalf("subject_hash leaked raw user id: %q", payload.SubjectHash)+ }+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for source channel report")+ }+}++func TestSenderCanReportDomainHashWithoutPlaintextDomain(t *testing.T) {+ got := make(chan Report, 1)+ sender := MustNewSender(fakeSettingStore{value: strings.Repeat("f", 64)}, SenderConfig{+ HTTPClient: recordingClient(t, got),+ Timeout: time.Second,+ })+ sender.ReportSelfHostSourceChannel("user-123", "search", "", "https://Example.com:443/path", false)++ select {+ case payload := <-got:+ if payload.Domain != nil {+ t.Fatalf("domain: want nil when plaintext consent is false, got %+v", payload.Domain)+ }+ if payload.DomainMD5 != DomainMD5("example.com") {+ t.Fatalf("domain_md5: want %q, got %q", DomainMD5("example.com"), payload.DomainMD5)+ }+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for source channel report")+ }+}++func TestSenderDropsUnknownChannel(t *testing.T) {+ got := make(chan struct{}, 1)+ sender := MustNewSender(fakeSettingStore{value: strings.Repeat("f", 64)}, SenderConfig{+ HTTPClient: &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ got <- struct{}{}+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: make(http.Header),+ Body: io.NopCloser(strings.NewReader("")),+ Request: req,+ }, nil+ }),+ },+ Timeout: 50 * time.Millisecond,+ })+ sender.ReportSelfHostSourceChannel("user-123", "private_text", "text", "example.com", true)++ select {+ case <-got:+ t.Fatal("unexpected report for invalid channel")+ case <-time.After(100 * time.Millisecond):+ }+}++func TestSenderDropsOfficialMulticaAPIURL(t *testing.T) {+ got := make(chan struct{}, 1)+ sender := MustNewSender(fakeSettingStore{value: strings.Repeat("f", 64)}, SenderConfig{+ HTTPClient: &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ got <- struct{}{}+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: make(http.Header),+ Body: io.NopCloser(strings.NewReader("")),+ Request: req,+ }, nil+ }),+ },+ Timeout: 50 * time.Millisecond,+ })+ sender.ReportSelfHostSourceChannel("user-123", "search", "", OfficialMulticaAPIURL, true)++ select {+ case <-got:+ t.Fatal("unexpected report for official Multica domain")+ case <-time.After(100 * time.Millisecond):+ }+}++func TestDomainHelpers(t *testing.T) {+ tests := []struct {+ raw string+ want string+ }{+ {raw: "https://Example.com:443/path?q=1", want: "example.com"},+ {raw: "api.customer.example.", want: "api.customer.example"},+ {raw: "backend:8080", want: "backend"},+ {raw: "[::1]:8080", want: "::1"},+ {raw: "", want: ""},+ }+ for _, tt := range tests {+ if got := NormalizeDomain(tt.raw); got != tt.want {+ t.Fatalf("NormalizeDomain(%q) = %q, want %q", tt.raw, got, tt.want)+ }+ }++ if !IsOfficialMulticaAPIURL(OfficialMulticaAPIURL) {+ t.Fatalf("%s should be official", OfficialMulticaAPIURL)+ }+ if IsOfficialMulticaAPIURL("http://api.multica.ai") {+ t.Fatal("http://api.multica.ai should not be official")+ }+ if IsOfficialMulticaAPIURL("https://multica.ai") {+ t.Fatal("https://multica.ai should not be the official API")+ }+ if !ShouldReportAPIBaseURL("https://api.customer.example") {+ t.Fatal("customer API URL should report")+ }+ if got := DomainMD5("Example.com"); got != "5ababd603b22780302dd8d83498e5172" {+ t.Fatalf("DomainMD5 = %q", got)+ }+}diff --git a/server/internal/sourcechannel/sourcechannel.go b/server/internal/sourcechannel/sourcechannel.gonew file mode 100644index 0000000000..4e9544a95a--- /dev/null+++ b/server/internal/sourcechannel/sourcechannel.go@@ -0,0 +1,177 @@+package sourcechannel++import (+ "crypto/md5"+ "crypto/sha256"+ "encoding/hex"+ "net"+ "net/http"+ "net/url"+ "os"+ "regexp"+ "strings"+)++const SchemaVersion = 1+const SourceOtherMaxRunes = 512+const DomainMaxLength = 255+const OfficialMulticaAPIURL = "https://api.multica.ai"+const officialMulticaAPIHost = "api.multica.ai"++type Report struct {+ SchemaVersion int `json:"schema_version"`+ Channel string `json:"channel"`+ InstanceHash string `json:"instance_hash"`+ SubjectHash string `json:"subject_hash"`+ SourceOther string `json:"source_other,omitempty"`+ Domain *string `json:"domain"`+ DomainMD5 string `json:"domain_md5"`+}++var validChannels = map[string]struct{}{+ "friends_colleagues": {},+ "search": {},+ "social_x": {},+ "social_linkedin": {},+ "social_youtube": {},+ "social_github": {},+ "social_other": {},+ "blog_newsletter": {},+ "ai_assistant": {},+ "from_work": {},+ "event_conference": {},+ "dont_remember": {},+ "other": {},+}++var hashPattern = regexp.MustCompile(`^[0-9a-f]{64}$`)+var md5Pattern = regexp.MustCompile(`^[0-9a-f]{32}$`)++func NormalizeChannel(channel string) string {+ return strings.ToLower(strings.TrimSpace(channel))+}++func ValidChannel(channel string) bool {+ _, ok := validChannels[NormalizeChannel(channel)]+ return ok+}++func NormalizeHash(hash string) string {+ return strings.ToLower(strings.TrimSpace(hash))+}++func ValidHash(hash string) bool {+ return hashPattern.MatchString(NormalizeHash(hash))+}++func ValidDomainMD5(hash string) bool {+ return md5Pattern.MatchString(NormalizeHash(hash))+}++func NormalizeSourceOther(channel, sourceOther string) string {+ if NormalizeChannel(channel) != "other" {+ return ""+ }+ sourceOther = strings.TrimSpace(sourceOther)+ if sourceOther == "" {+ return ""+ }+ runes := []rune(sourceOther)+ if len(runes) > SourceOtherMaxRunes {+ sourceOther = string(runes[:SourceOtherMaxRunes])+ }+ return sourceOther+}++func ReportingAPIBaseURL(r *http.Request) string {+ if base := strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")); base != "" {+ return base+ }+ if r == nil {+ return ""+ }+ return r.Host+}++func ShouldReportAPIBaseURL(apiBaseURL string) bool {+ domain := NormalizeDomain(apiBaseURL)+ return domain != "" && !IsOfficialMulticaAPIURL(apiBaseURL)+}++func NormalizeDomain(raw string) string {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return ""+ }+ if strings.Contains(raw, "://") {+ if u, err := url.Parse(raw); err == nil {+ raw = u.Host+ }+ } else if u, err := url.Parse("//" + raw); err == nil {+ raw = u.Host+ }+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return ""+ }+ if host, _, err := net.SplitHostPort(raw); err == nil {+ raw = host+ } else if strings.Count(raw, ":") == 1 {+ if host, _, err := net.SplitHostPort(raw); err == nil {+ raw = host+ } else if i := strings.LastIndex(raw, ":"); i > 0 {+ raw = raw[:i]+ }+ }+ raw = strings.Trim(raw, "[]")+ raw = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(raw)), ".")+ if raw == "" || len(raw) > DomainMaxLength {+ return ""+ }+ return raw+}++func IsOfficialMulticaAPIURL(apiBaseURL string) bool {+ raw := strings.TrimSpace(apiBaseURL)+ if raw == "" {+ return false+ }+ if strings.Contains(raw, "://") {+ u, err := url.Parse(raw)+ if err != nil {+ return false+ }+ path := strings.TrimRight(u.EscapedPath(), "/")+ return u.Scheme == "https" &&+ strings.EqualFold(u.Hostname(), officialMulticaAPIHost) &&+ (u.Port() == "" || u.Port() == "443") &&+ path == ""+ }+ return NormalizeDomain(raw) == officialMulticaAPIHost+}++func DomainMD5(domain string) string {+ domain = NormalizeDomain(domain)+ if domain == "" {+ return ""+ }+ sum := md5.Sum([]byte(domain))+ return hex.EncodeToString(sum[:])+}++func InstanceHash(salt string) string {+ return hashHex(salt, "instance", "multica")+}++func SubjectHash(salt, userID string) string {+ return hashHex(salt, "subject", userID)+}++func hashHex(parts ...string) string {+ h := sha256.New()+ for _, part := range parts {+ h.Write([]byte(part))+ h.Write([]byte{0})+ }+ return hex.EncodeToString(h.Sum(nil))+}diff --git a/server/migrations/128_self_host_source_channel.down.sql b/server/migrations/128_self_host_source_channel.down.sqlnew file mode 100644index 0000000000..88b84c54ad--- /dev/null+++ b/server/migrations/128_self_host_source_channel.down.sql@@ -0,0 +1,2 @@+DROP TABLE IF EXISTS self_host_source_channel;+DROP TABLE IF EXISTS system_setting;diff --git a/server/migrations/128_self_host_source_channel.up.sql b/server/migrations/128_self_host_source_channel.up.sqlnew file mode 100644index 0000000000..5f757928b3--- /dev/null+++ b/server/migrations/128_self_host_source_channel.up.sql@@ -0,0 +1,37 @@+CREATE TABLE system_setting (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE TABLE self_host_source_channel (+ instance_hash TEXT NOT NULL CHECK (instance_hash ~ '^[0-9a-f]{64}$'),+ subject_hash TEXT NOT NULL CHECK (subject_hash ~ '^[0-9a-f]{64}$'),+ channel TEXT NOT NULL CHECK (channel IN (+ 'friends_colleagues',+ 'search',+ 'social_x',+ 'social_linkedin',+ 'social_youtube',+ 'social_github',+ 'social_other',+ 'blog_newsletter',+ 'ai_assistant',+ 'from_work',+ 'event_conference',+ 'dont_remember',+ 'other'+ )),+ schema_version INTEGER NOT NULL DEFAULT 1 CHECK (schema_version > 0),+ first_received_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_received_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ report_count INTEGER NOT NULL DEFAULT 1 CHECK (report_count > 0),+ PRIMARY KEY (instance_hash, subject_hash)+);++CREATE INDEX idx_self_host_source_channel_channel+ ON self_host_source_channel(channel);++CREATE INDEX idx_self_host_source_channel_last_received_at+ ON self_host_source_channel(last_received_at DESC);diff --git a/server/migrations/129_self_host_source_other.down.sql b/server/migrations/129_self_host_source_other.down.sqlnew file mode 100644index 0000000000..81e81e8fec--- /dev/null+++ b/server/migrations/129_self_host_source_other.down.sql@@ -0,0 +1,5 @@+ALTER TABLE self_host_source_channel+ DROP CONSTRAINT IF EXISTS self_host_source_channel_source_other_check;++ALTER TABLE self_host_source_channel+ DROP COLUMN IF EXISTS source_other;diff --git a/server/migrations/129_self_host_source_other.up.sql b/server/migrations/129_self_host_source_other.up.sqlnew file mode 100644index 0000000000..b734173493--- /dev/null+++ b/server/migrations/129_self_host_source_other.up.sql@@ -0,0 +1,10 @@+ALTER TABLE self_host_source_channel+ ADD COLUMN source_other TEXT,+ ADD CONSTRAINT self_host_source_channel_source_other_check+ CHECK (+ source_other IS NULL+ OR (+ channel = 'other'+ AND char_length(source_other) <= 512+ )+ );diff --git a/server/migrations/130_self_host_source_domain.down.sql b/server/migrations/130_self_host_source_domain.down.sqlnew file mode 100644index 0000000000..5d5d6e6418--- /dev/null+++ b/server/migrations/130_self_host_source_domain.down.sql@@ -0,0 +1,7 @@+DROP INDEX IF EXISTS idx_self_host_source_channel_domain_md5;++ALTER TABLE self_host_source_channel+ DROP CONSTRAINT IF EXISTS self_host_source_channel_domain_md5_check,+ DROP CONSTRAINT IF EXISTS self_host_source_channel_domain_check,+ DROP COLUMN IF EXISTS domain_md5,+ DROP COLUMN IF EXISTS domain;diff --git a/server/migrations/130_self_host_source_domain.up.sql b/server/migrations/130_self_host_source_domain.up.sqlnew file mode 100644index 0000000000..f328de8261--- /dev/null+++ b/server/migrations/130_self_host_source_domain.up.sql@@ -0,0 +1,10 @@+ALTER TABLE self_host_source_channel+ ADD COLUMN domain TEXT,+ ADD COLUMN domain_md5 TEXT,+ ADD CONSTRAINT self_host_source_channel_domain_check+ CHECK (domain IS NULL OR char_length(domain) <= 255),+ ADD CONSTRAINT self_host_source_channel_domain_md5_check+ CHECK (domain_md5 IS NULL OR domain_md5 ~ '^[0-9a-f]{32}$');++CREATE INDEX idx_self_host_source_channel_domain_md5+ ON self_host_source_channel(domain_md5);diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex ecd37d0cbb..4389c19f82 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -697,6 +697,19 @@ type RuntimeProfile struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type SelfHostSourceChannel struct {+ InstanceHash string `json:"instance_hash"`+ SubjectHash string `json:"subject_hash"`+ Channel string `json:"channel"`+ SchemaVersion int32 `json:"schema_version"`+ FirstReceivedAt pgtype.Timestamptz `json:"first_received_at"`+ LastReceivedAt pgtype.Timestamptz `json:"last_received_at"`+ ReportCount int32 `json:"report_count"`+ SourceOther pgtype.Text `json:"source_other"`+ Domain pgtype.Text `json:"domain"`+ DomainMd5 pgtype.Text `json:"domain_md5"`+}+type Skill struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`@@ -767,6 +780,13 @@ type SysCronExecution struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type SystemSetting struct {+ Key string `json:"key"`+ Value string `json:"value"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type TaskMessage struct {ID pgtype.UUID `json:"id"`TaskID pgtype.UUID `json:"task_id"`diff --git a/server/pkg/db/generated/self_host_source_channel.sql.go b/server/pkg/db/generated/self_host_source_channel.sql.gonew file mode 100644index 0000000000..1f5193069f--- /dev/null+++ b/server/pkg/db/generated/self_host_source_channel.sql.go@@ -0,0 +1,71 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: self_host_source_channel.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const upsertSelfHostSourceChannel = `-- name: UpsertSelfHostSourceChannel :one+INSERT INTO self_host_source_channel (+ schema_version,+ channel,+ instance_hash,+ subject_hash,+ source_other,+ domain,+ domain_md5+) VALUES (+ $1, $2, $3, $4, $5, $6, $7+)+ON CONFLICT (instance_hash, subject_hash) DO UPDATE SET+ schema_version = EXCLUDED.schema_version,+ channel = EXCLUDED.channel,+ source_other = EXCLUDED.source_other,+ domain = EXCLUDED.domain,+ domain_md5 = EXCLUDED.domain_md5,+ last_received_at = now(),+ report_count = self_host_source_channel.report_count + 1+RETURNING instance_hash, subject_hash, channel, schema_version, first_received_at, last_received_at, report_count, source_other, domain, domain_md5+`++type UpsertSelfHostSourceChannelParams struct {+ SchemaVersion int32 `json:"schema_version"`+ Channel string `json:"channel"`+ InstanceHash string `json:"instance_hash"`+ SubjectHash string `json:"subject_hash"`+ SourceOther pgtype.Text `json:"source_other"`+ Domain pgtype.Text `json:"domain"`+ DomainMd5 pgtype.Text `json:"domain_md5"`+}++func (q *Queries) UpsertSelfHostSourceChannel(ctx context.Context, arg UpsertSelfHostSourceChannelParams) (SelfHostSourceChannel, error) {+ row := q.db.QueryRow(ctx, upsertSelfHostSourceChannel,+ arg.SchemaVersion,+ arg.Channel,+ arg.InstanceHash,+ arg.SubjectHash,+ arg.SourceOther,+ arg.Domain,+ arg.DomainMd5,+ )+ var i SelfHostSourceChannel+ err := row.Scan(+ &i.InstanceHash,+ &i.SubjectHash,+ &i.Channel,+ &i.SchemaVersion,+ &i.FirstReceivedAt,+ &i.LastReceivedAt,+ &i.ReportCount,+ &i.SourceOther,+ &i.Domain,+ &i.DomainMd5,+ )+ return i, err+}diff --git a/server/pkg/db/generated/system_setting.sql.go b/server/pkg/db/generated/system_setting.sql.gonew file mode 100644index 0000000000..71294e7d6b--- /dev/null+++ b/server/pkg/db/generated/system_setting.sql.go@@ -0,0 +1,30 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: system_setting.sql++package db++import (+ "context"+)++const getOrCreateSystemSetting = `-- name: GetOrCreateSystemSetting :one+INSERT INTO system_setting (key, value)+VALUES ($1, $2)+ON CONFLICT (key) DO UPDATE+SET value = system_setting.value+RETURNING value+`++type GetOrCreateSystemSettingParams struct {+ Key string `json:"key"`+ Value string `json:"value"`+}++func (q *Queries) GetOrCreateSystemSetting(ctx context.Context, arg GetOrCreateSystemSettingParams) (string, error) {+ row := q.db.QueryRow(ctx, getOrCreateSystemSetting, arg.Key, arg.Value)+ var value string+ err := row.Scan(&value)+ return value, err+}diff --git a/server/pkg/db/queries/self_host_source_channel.sql b/server/pkg/db/queries/self_host_source_channel.sqlnew file mode 100644index 0000000000..ae01bf11ea--- /dev/null+++ b/server/pkg/db/queries/self_host_source_channel.sql@@ -0,0 +1,21 @@+-- name: UpsertSelfHostSourceChannel :one+INSERT INTO self_host_source_channel (+ schema_version,+ channel,+ instance_hash,+ subject_hash,+ source_other,+ domain,+ domain_md5+) VALUES (+ $1, $2, $3, $4, sqlc.narg('source_other'), sqlc.narg('domain'), sqlc.narg('domain_md5')+)+ON CONFLICT (instance_hash, subject_hash) DO UPDATE SET+ schema_version = EXCLUDED.schema_version,+ channel = EXCLUDED.channel,+ source_other = EXCLUDED.source_other,+ domain = EXCLUDED.domain,+ domain_md5 = EXCLUDED.domain_md5,+ last_received_at = now(),+ report_count = self_host_source_channel.report_count + 1+RETURNING *;diff --git a/server/pkg/db/queries/system_setting.sql b/server/pkg/db/queries/system_setting.sqlnew file mode 100644index 0000000000..044d3cbbc9--- /dev/null+++ b/server/pkg/db/queries/system_setting.sql@@ -0,0 +1,6 @@+-- name: GetOrCreateSystemSetting :one+INSERT INTO system_setting (key, value)+VALUES ($1, $2)+ON CONFLICT (key) DO UPDATE+SET value = system_setting.value+RETURNING value;