Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(analytics): anonymous self-host onboarding source beacon (MUL-3708) (#4691)
Naiyuan Qing63eb6f73ad8f
diff --git a/.env.example b/.env.exampleindex 296898eec6..8f77e8cfbf 100644--- a/.env.example+++ b/.env.example@@ -302,3 +302,17 @@ POSTHOG_HOST=https://us.i.posthog.comANALYTICS_ENVIRONMENT=# Force the no-op client even when POSTHOG_API_KEY is set (CI / opt-out).ANALYTICS_DISABLED=++# Self-host onboarding source beacon (MUL-3708).+# A *production* self-host (APP_ENV=production with a real, non-localhost,+# non-*.multica.ai app URL) anonymously reports the onboarding "how did you+# hear about us" channel the user picks, so Multica can see the self-host+# source distribution. It sends ONLY: the chosen channel enum value(s) and+# two per-instance salted hashes (a one-way uid hash + an instance hash).+# It NEVER sends user id / email / name / workspace / org / domain / role /+# use_case / the free-text "other" answer / IP. Reporting is fire-and-forget+# and never blocks onboarding.+# To disable it, set ANALYTICS_DISABLED=true (that turns off all telemetry,+# which on self-host is only this beacon). Advanced/testing only: override+# the ingest base URL (defaults to Multica's public API).+MULTICA_SOURCE_BEACON_URL=diff --git a/SELF_HOSTING.md b/SELF_HOSTING.mdindex e3eb55e2b3..2ddf4e826b 100644--- a/SELF_HOSTING.md+++ b/SELF_HOSTING.md@@ -388,6 +388,25 @@ If you already have a `pg_cron` job in production, the safe sequence to retire iExternal cron / systemd timer / Kubernetes `CronJob` setups that call `SELECT rollup_task_usage_hourly()` directly can be retired the same way — once `sys_cron_executions` shows steady SUCCESS rows from the in-process scheduler, the external job is redundant and can be removed.+## Telemetry & Privacy++Your self-host instance ships **no** product analytics to Multica by default —+`POSTHOG_API_KEY` is empty, so the analytics client is a no-op.++The one exception is a tiny, anonymous **onboarding source beacon**: when a+user picks "how did you hear about Multica?" during onboarding, a *production*+instance reports only that channel choice (e.g. `social_youtube`) plus two+one-way per-instance hashes, so we can see where self-host users come from. It+**never** sends your users' identities, emails, names, workspaces,+organizations, domains, roles, use-cases, the free-text "other" answer, or IP+addresses, and a failed report never blocks onboarding. The onboarding source+step shows a short notice about this on self-host.++To turn it off, set `ANALYTICS_DISABLED=true` (on self-host that is the only+outbound telemetry). Full details — exactly what is and isn't sent, and how+the production/official distinction is made — are in+[`docs/analytics.md`](docs/analytics.md#self-host-onboarding-source-beacon-mul-3708).+## Stopping ServicesIf you installed via the install script:diff --git a/docs/analytics.md b/docs/analytics.mdindex fdfe47bece..4f860aeb56 100644--- a/docs/analytics.md+++ b/docs/analytics.md@@ -52,6 +52,53 @@ defaults guarantee this:self-hosts' blank server config also disables frontend event shippingautomatically — no separate frontend opt-out plumbing required.+### Self-host onboarding source beacon (MUL-3708)++There is exactly **one** thing a self-host instance ships to Multica's own+analytics, independent of the PostHog key above: the anonymous onboarding+**source** ("how did you hear about us") channel.++- **Why.** The PostHog `onboarding_questionnaire_submitted` event never+ reaches us from self-host (no key → NoopClient), so the self-host source+ distribution is otherwise invisible. This beacon recovers just that one+ dimension.+- **What fires it.** When a user first fills in their source, the server+ POSTs once to Multica's public, write-only ingest+ (`POST /api/telemetry/self-host-source`). It is **not** a background job,+ reads no history, and a failed send never blocks onboarding. See+ `server/internal/sourcebeacon`.+- **Who fires it.** Only a **production self-host**:+ `sourcebeacon.ShouldSend` requires `environment == production`, a non-empty+ non-localhost app host (`MULTICA_APP_URL` → `FRONTEND_ORIGIN`), and a host+ that is **not** `multica.ai` / any `*.multica.ai` (so official prod,+ staging, preview and internal envs never fire — they keep their normal+ PostHog capture). Judging by the app/frontend host, not the backend URL,+ is deliberate: the official cloud reliably configures its frontend domain+ even when `MULTICA_PUBLIC_URL` is unset (see+ `TestGetConfigOmitsCloudDaemonSetupWithoutPublicURL`), so keying on the+ backend URL would misclassify official as self-host.+- **What is sent.** Only `{ v, channels[], uid_hash, instance_hash }`:+ - `channels[]` — the source enum value(s) (`social_youtube`, … `other`).+ - `uid_hash = sha256(instance_salt + user_id)`, `instance_hash =+ sha256(instance_salt)`, both truncated. `instance_salt`+ (`system_settings.instance_salt`) never leaves the box, so Multica+ cannot reverse a hash to a `user_id`, and the same user on two instances+ hashes differently.+- **What is never sent.** Real `user_id` / email / name / workspace / org /+ domain / `role` / `use_case` / the `source_other` free-text / IP. The+ ingest rejects any payload carrying an unknown field.+- **How to disable.** Set `ANALYTICS_DISABLED=true` (the first gate in+ `ShouldSend`). On self-host that is the only outbound telemetry, so it is+ the off switch.+- **Where it lands.** One PostHog event per channel,+ `self_host_source_channel`, with `deployment: self_host`, a deterministic+ event `uuid` (PostHog dedups, best-effort), and+ `$process_person_profile: false` (no PostHog person is created for the+ anonymous hash). A deliberately distinct event name from+ `onboarding_questionnaire_submitted` so it never pollutes the official+ onboarding funnel; compare the two series side by side, split by+ `deployment`.+## Architecture```@@ -415,15 +462,19 @@ not have a workspace yet.Fires on the first PatchOnboarding that transitions the user'squestionnaire JSONB from "at least one slot empty" to "all three-filled" (team_size, role, use_case). Revisions past that point don't-re-emit — the funnel counts users, not edits.+filled" (source, role, use_case). Revisions past that point don't+re-emit — the funnel counts users, not edits. See+`OnboardingQuestionnaireSubmitted` in `server/internal/analytics/events.go`.| Property | Type | Description ||---|---|---|-| `team_size` | string | `solo` / `team` / `other`. |-| `role` | string | `developer` / `product_lead` / `writer` / `founder` / `other`. |-| `use_case` | string | `coding` / `planning` / `writing_research` / `explore` / `other`. |-| `team_size_has_other` | bool | `true` when the user filled the Q1 free-text escape. |+| `source` | string[] | Acquisition channels (`friends_colleagues` / `search` / `social_youtube` / `ai_assistant` / … / `other`). Array for back-compat; the UI commits one element. |+| `role` | string | `engineer` / `product` / `founder` / `writer` / … / `other`. |+| `use_case` | string[] | `ship_code` / `manage_team` / `plan_research` / … / `other`. Multi-select. |+| `source_skipped` | bool | `true` when the user explicitly skipped Q1. |+| `role_skipped` | bool | Ditto Q2. |+| `use_case_skipped` | bool | Ditto Q3. |+| `source_has_other` | bool | `true` when the user filled the Q1 free-text escape. || `role_has_other` | bool | Ditto Q2. || `use_case_has_other` | bool | Ditto Q3. |@@ -432,9 +483,14 @@ change answers before submitting again):| Property | Type | Description ||---|---|---|-| `team_size` | string | Mirrors the event property for cohort queries. |+| `source` | string[] | Mirrors the event property for cohort queries. || `role` | string | Same. |-| `use_case` | string | Same. |+| `use_case` | string[] | Same. |++> Note: the self-reported `source` here is per-user and only reaches PostHog+> from deployments with a configured key. Self-host source is recovered+> separately and anonymously via the `self_host_source_channel` beacon — see+> "Self-host onboarding source beacon" above.`distinct_id` is the user's id. No workspace_id — the questionnaire isper-user, not per-workspace.diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex d8cc9b2677..e4347f57a8 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -42,6 +42,10 @@ export interface AppConfigResponse {daemon_server_url?: string;daemon_app_url?: string;workspace_creation_disabled?: boolean;+ // True only on a production self-host that ships the anonymous onboarding+ // source beacon (MUL-3708). Drives the source-step notice. Omitted by+ // official cloud / older servers; treat absent as false.+ self_host_source_notice?: boolean;}// ---------------------------------------------------------------------------@@ -182,6 +186,7 @@ export const AppConfigSchema = z.object({daemon_server_url: OptionalStringSchema,daemon_app_url: OptionalStringSchema,workspace_creation_disabled: BooleanWithDefaultSchema(false).optional(),+ self_host_source_notice: BooleanWithDefaultSchema(false).optional(),}).loose();export const EMPTY_APP_CONFIG: AppConfigResponse = {@@ -192,6 +197,7 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {daemon_server_url: "",daemon_app_url: "",workspace_creation_disabled: false,+ self_host_source_notice: false,};export const CommentSchema = z.object({diff --git a/packages/core/config/index.ts b/packages/core/config/index.tsindex 005f3cbfa1..54f44ce461 100644--- a/packages/core/config/index.ts+++ b/packages/core/config/index.ts@@ -15,11 +15,17 @@ interface ConfigState {// must be hidden. Defaults to false so unknown / older servers behave like// the managed-cloud case.workspaceCreationDisabled: boolean;+ // Self-host onboarding source beacon (MUL-3708): true only on a production+ // self-host that will ship the anonymous source channel. Drives the+ // "anonymous collection" notice on the onboarding source step. Defaults to+ // false so official cloud / unknown servers show nothing.+ selfHostSourceNotice: boolean;setCdnConfig: (config: { cdnDomain: string; cdnSigned?: boolean }) => void;setAuthConfig: (config: {allowSignup: boolean;googleClientId?: string;workspaceCreationDisabled?: boolean;+ selfHostSourceNotice?: boolean;}) => void;setDaemonConfig: (config: {daemonServerUrl?: string;@@ -35,9 +41,14 @@ export const configStore = createStore<ConfigState>((set) => ({daemonServerUrl: "",daemonAppUrl: "",workspaceCreationDisabled: false,+ selfHostSourceNotice: false,setCdnConfig: ({ cdnDomain, cdnSigned = false }) => set({ cdnDomain, cdnSigned }),- setAuthConfig: ({ allowSignup, googleClientId = "", workspaceCreationDisabled = false }) =>- set({ allowSignup, googleClientId, workspaceCreationDisabled }),+ setAuthConfig: ({+ allowSignup,+ googleClientId = "",+ workspaceCreationDisabled = false,+ selfHostSourceNotice = false,+ }) => set({ allowSignup, googleClientId, workspaceCreationDisabled, selfHostSourceNotice }),setDaemonConfig: ({ daemonServerUrl = "", daemonAppUrl = "" }) =>set({ daemonServerUrl, daemonAppUrl }),}));diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex 4269a7f673..ad042edce0 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -62,6 +62,7 @@ export function AuthInitializer({// Old servers omit this field — treat that as "creation allowed"// (the managed-cloud default) rather than blocking the UI.workspaceCreationDisabled: cfg.workspace_creation_disabled === true,+ selfHostSourceNotice: cfg.self_host_source_notice === true,});configStore.getState().setDaemonConfig({daemonServerUrl: cfg.daemon_server_url,diff --git a/packages/views/locales/en/onboarding.json b/packages/views/locales/en/onboarding.jsonindex badd0ed107..e99e456949 100644--- a/packages/views/locales/en/onboarding.json+++ b/packages/views/locales/en/onboarding.json@@ -66,7 +66,8 @@"event_conference": "Conference / meetup","dont_remember": "Don't remember","other": "Other",- "other_placeholder": "e.g. a podcast I listen to"+ "other_placeholder": "e.g. a podcast I listen to",+ "self_host_notice": "Anonymous: we only collect the source you pick, to understand where people hear about Multica. We never send your name, email, organization info, or any free-text."},"role": {"question": "Which best describes you?",diff --git a/packages/views/locales/ja/onboarding.json b/packages/views/locales/ja/onboarding.jsonindex 47d339e13d..74e8773747 100644--- a/packages/views/locales/ja/onboarding.json+++ b/packages/views/locales/ja/onboarding.json@@ -66,7 +66,8 @@"dont_remember": "覚えていない","other": "その他","other_placeholder": "例: よく聴くポッドキャスト",- "social_github": "GitHub"+ "social_github": "GitHub",+ "self_host_notice": "匿名で集計します: 選択した流入チャネルのみを収集し、ユーザーが Multica をどこで知ったかを把握するために使います。氏名・メールアドレス・組織情報・自由記述は送信しません。"},"role": {"question": "あなたに最も近いのはどれですか?",diff --git a/packages/views/locales/ko/onboarding.json b/packages/views/locales/ko/onboarding.jsonindex 870018ec4e..4ea86cfd06 100644--- a/packages/views/locales/ko/onboarding.json+++ b/packages/views/locales/ko/onboarding.json@@ -66,7 +66,8 @@"event_conference": "컨퍼런스 / 밋업","dont_remember": "기억나지 않음","other": "기타",- "other_placeholder": "예: 자주 듣는 팟캐스트"+ "other_placeholder": "예: 자주 듣는 팟캐스트",+ "self_host_notice": "익명 집계: 선택하신 유입 경로만 수집하여 사용자가 Multica를 어디서 알게 되었는지 파악하는 데 사용합니다. 이름, 이메일, 조직 정보나 자유 입력 내용은 전송하지 않습니다."},"role": {"question": "어떤 역할에 가장 가까우신가요?",diff --git a/packages/views/locales/zh-Hans/onboarding.json b/packages/views/locales/zh-Hans/onboarding.jsonindex fdd2d760da..3742e0176e 100644--- a/packages/views/locales/zh-Hans/onboarding.json+++ b/packages/views/locales/zh-Hans/onboarding.json@@ -66,7 +66,8 @@"event_conference": "线下活动 / Meetup","dont_remember": "想不起来了","other": "其他",- "other_placeholder": "例如:一档播客"+ "other_placeholder": "例如:一档播客",+ "self_host_notice": "匿名统计:我们只会收集你选择的来源渠道,用于了解用户从哪里认识 Multica。不包含你的身份信息、邮箱、组织信息或自由文本内容。"},"role": {"question": "你是什么角色?",diff --git a/packages/views/onboarding/steps/step-question.tsx b/packages/views/onboarding/steps/step-question.tsxindex fdf20e833d..8f1f577b1e 100644--- a/packages/views/onboarding/steps/step-question.tsx+++ b/packages/views/onboarding/steps/step-question.tsx@@ -55,11 +55,15 @@ export function StepQuestion({onSkip,onBack,multiSelect = false,+ notice,}: {step: OnboardingStep;number: number;eyebrow?: string;question: string;+ /** Optional sub-question note rendered under the heading (e.g. the+ * self-host anonymous-collection disclosure on the source step). */+ notice?: ReactNode;options: readonly QuestionOption[];selectedSlugs: readonly string[];otherValue: string;@@ -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}diff --git a/packages/views/onboarding/steps/step-source.test.tsx b/packages/views/onboarding/steps/step-source.test.tsxindex 447834127e..0905f9b61a 100644--- a/packages/views/onboarding/steps/step-source.test.tsx+++ b/packages/views/onboarding/steps/step-source.test.tsx@@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach } from "vitest";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import type { QuestionnaireAnswers } from "@multica/core/onboarding";+import { configStore } from "@multica/core/config";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../locales/en/common.json";import enOnboarding from "../../locales/en/onboarding.json";@@ -42,7 +43,11 @@ function renderStep(answers: QuestionnaireAnswers = EMPTY) {}describe("StepSource (single-select primary source)", () => {- beforeEach(() => vi.restoreAllMocks());+ beforeEach(() => {+ vi.restoreAllMocks();+ // Default: not a self-host that ships the source beacon, so no notice.+ configStore.setState({ selfHostSourceNotice: false });+ });it("clicking a non-Other option writes a one-element source array", async () => {const user = userEvent.setup();@@ -106,6 +111,36 @@ describe("StepSource (single-select primary source)", () => {expect(onChange).toHaveBeenLastCalledWith({ source_other: "x" });});+ it("shows the anonymous-collection notice only on a self-host that ships the beacon", () => {+ // Official cloud / default: no notice.+ const { unmount } = render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <StepSource+ answers={EMPTY}+ onChange={vi.fn()}+ onAdvance={vi.fn()}+ onSkip={vi.fn()}+ />+ </I18nProvider>,+ );+ expect(screen.queryByText(/we only collect the source you pick/i)).toBeNull();+ unmount();++ // Production self-host: notice shown.+ configStore.setState({ selfHostSourceNotice: true });+ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <StepSource+ answers={EMPTY}+ onChange={vi.fn()}+ onAdvance={vi.fn()}+ onSkip={vi.fn()}+ />+ </I18nProvider>,+ );+ expect(screen.getByText(/we only collect the source you pick/i)).toBeInTheDocument();+ });+it("switching away from Other clears source_other so a stale value can't leak", async () => {const user = userEvent.setup();const { onChange } = renderStep({diff --git a/packages/views/onboarding/steps/step-source.tsx b/packages/views/onboarding/steps/step-source.tsxindex fa9476fff1..a1a30ff739 100644--- a/packages/views/onboarding/steps/step-source.tsx+++ b/packages/views/onboarding/steps/step-source.tsx@@ -18,6 +18,7 @@ import {YouTubeIcon,GitHubIcon,} from "../components/brand-icons";+import { useConfigStore } from "@multica/core/config";import { StepQuestion, type QuestionOption } from "./step-question";import { useT } from "../../i18n";@@ -39,6 +40,10 @@ export function StepSource({onBack?: () => void;}) {const { t } = useT("onboarding");+ // Self-host onboarding source beacon (MUL-3708): a production self-host+ // anonymously reports the chosen channel to Multica, so disclose it here.+ // The flag is true only on those deployments; official cloud shows nothing.+ const showSelfHostNotice = useConfigStore((s) => s.selfHostSourceNotice);const options: QuestionOption[] = [{ slug: "friends_colleagues", icon: <Users className="h-4 w-4" />, label: t(($) => $.questions.source.friends_colleagues) },@@ -83,6 +88,7 @@ export function StepSource({number={1}eyebrow={t(($) => $.questions.eyebrow_about_you)}question={t(($) => $.questions.source.question)}+ notice={showSelfHostNotice ? t(($) => $.questions.source.self_host_notice) : undefined}options={options}selectedSlugs={selected}otherValue={answers.source_other ?? ""}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 62d2e57bf6..b6e9f61799 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/sourcebeacon""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"@@ -204,6 +205,30 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.WebhookIPRateLimiter = handler.NewRedisWebhookIPRateLimiter(rdb, handler.DefaultWebhookIPRateLimit())}+ // Self-host onboarding source beacon (MUL-3708). Enabled only on a+ // production self-host (sourcebeacon.ShouldSendFromEnv, judged by the+ // deployment's own app/frontend host). The salt is the per-instance+ // secret from system_settings so the hashes it ships can't be reversed+ // to a user_id. A load failure / missing salt leaves it disabled. The+ // upstream defaults to Multica's public API; MULTICA_SOURCE_BEACON_URL+ // overrides it (used by tests / staging).+ beaconEnabled := sourcebeacon.ShouldSendFromEnv()+ var beaconSalt string+ if beaconEnabled {+ // Only the rare production self-host needs the salt — skip the+ // construction-time DB call entirely otherwise (this also keeps the+ // router constructible with a nil pool in routing-only tests).+ // Bounded ctx so a stalled DB cannot slow startup.+ saltCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ beaconSalt = loadInstanceSalt(saltCtx, pool)+ cancel()+ }+ h.SourceBeacon = sourcebeacon.NewSender(sourcebeacon.SenderConfig{+ Enabled: beaconEnabled,+ Salt: beaconSalt,+ UpstreamURL: os.Getenv("MULTICA_SOURCE_BEACON_URL"),+ })+// Channel engine (MUL-3620): the platform-agnostic inbound runtime.// Built UNCONDITIONALLY — it drives any channel.Channel, not just// Feishu, so it must not depend on the Lark master key (a future@@ -583,6 +608,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)+ sourceBeaconRL := middleware.RateLimit(rdb, envPositiveInt("RATE_LIMIT_SOURCE_BEACON", 30), 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)@@ -610,6 +636,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// HandleCloudBillingStripeWebhook for the rationale).r.Post("/api/webhooks/stripe", h.HandleCloudBillingStripeWebhook)+ // Self-host onboarding source beacon ingest (MUL-3708). Public,+ // write-only, unauthenticated by design: self-host instances hold no+ // Multica credential. The payload is anonymous (channel enums + two+ // per-instance hashes only); abuse is bounded by the per-IP limiter, a+ // 4 KiB body cap, the channel allowlist, and strict unknown-field+ // rejection in the handler.+ r.With(sourceBeaconRL).Post("/api/telemetry/self-host-source", h.HandleSelfHostSourceBeacon)+// Daemon API routes (require daemon token or valid user token)r.Route("/api/daemon", func(r chi.Router) {r.Use(middleware.DaemonAuth(queries, patCache, daemonTokenCache, cloudPATVerifier))@@ -1310,3 +1344,26 @@ func cloudRuntimeFleetURLFromEnv() string {}return strings.TrimSpace(os.Getenv("MULTICA_FLEET_URL"))}++// loadInstanceSalt returns the per-instance secret used by the self-host+// source beacon (MUL-3708), seeding the singleton row defensively in case+// the migration's seed was skipped. Returns "" on any error — the beacon+// treats an empty salt as "disabled", so a DB hiccup degrades to no+// telemetry rather than crashing boot.+func loadInstanceSalt(ctx context.Context, pool *pgxpool.Pool) string {+ // Routing-only tests construct the router with a nil pool; the beacon is+ // disabled there anyway, so there is nothing to load.+ if pool == nil {+ return ""+ }+ if _, err := pool.Exec(ctx, `INSERT INTO system_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING`); err != nil {+ slog.Warn("sourcebeacon: ensure system_settings row failed; beacon disabled", "error", err)+ return ""+ }+ var salt string+ if err := pool.QueryRow(ctx, `SELECT instance_salt FROM system_settings WHERE id = 1`).Scan(&salt); err != nil {+ slog.Warn("sourcebeacon: load instance_salt failed; beacon disabled", "error", err)+ return ""+ }+ return salt+}diff --git a/server/internal/analytics/client.go b/server/internal/analytics/client.goindex de0a5dfb15..e4e860ade6 100644--- a/server/internal/analytics/client.go+++ b/server/internal/analytics/client.go@@ -25,6 +25,12 @@ type Event struct {// Name of the event (e.g. "signup", "workspace_created").Name string+ // UUID, when non-empty, is sent as PostHog's top-level event `uuid`.+ // PostHog deduplicates events sharing a uuid (best-effort), so a+ // deterministic uuid makes re-sends idempotent. Empty → PostHog assigns+ // its own (the default for every existing event).+ UUID string+// DistinctID identifies the person this event belongs to. For logged-in// users this is user.id; for anonymous events it should be the anon_id// that was previously used on the frontend so identity merging works.diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.goindex 5a8fbdbd2e..071409d8a8 100644--- a/server/internal/analytics/events.go+++ b/server/internal/analytics/events.go@@ -27,6 +27,13 @@ const (EventContactSalesSubmitted = "contact_sales_submitted"EventSquadCreated = "squad_created"EventAutopilotCreated = "autopilot_created"+ // EventSelfHostSourceChannel is the self-host onboarding source beacon+ // event (MUL-3708). One event per (instance, user, channel), carrying+ // only the channel + anonymous per-instance hashes — never identity.+ // Deliberately a distinct name from onboarding_questionnaire_submitted+ // so it never pollutes the official onboarding funnel; analysts compare+ // the two series side by side, split by the deployment property.+ EventSelfHostSourceChannel = "self_host_source_channel")const EventSchemaVersion = 2@@ -470,6 +477,27 @@ func OnboardingQuestionnaireSubmitted(userID string, source []string, role strin}}+// SelfHostSourceChannel builds the self-host onboarding source beacon event+// (MUL-3708) for one channel. The caller supplies the deterministic event+// uuid (from sourcebeacon.EventUUID) because analytics must not import+// sourcebeacon. distinct_id carries a ":" so the PostHog client never derives+// a user_id from it, and $process_person_profile=false keeps the anonymous+// hash from spawning a PostHog person. Carries no identity — only the channel+// plus the per-instance hashes.+func SelfHostSourceChannel(instanceHash, uidHash, channel, eventUUID string) Event {+ return Event{+ Name: EventSelfHostSourceChannel,+ DistinctID: "selfhost:" + uidHash,+ UUID: eventUUID,+ Properties: map[string]any{+ "source": channel,+ "deployment": "self_host",+ "instance_hash": instanceHash,+ "$process_person_profile": false,+ },+ }+}+// AgentCreated fires whenever a new agent is added to a workspace — not// just inside onboarding. `isFirstAgentInWorkspace` lets the funnel// isolate the Step 4 signal from later agent additions.diff --git a/server/internal/analytics/posthog.go b/server/internal/analytics/posthog.goindex d6e162447e..d4006d8dbe 100644--- a/server/internal/analytics/posthog.go+++ b/server/internal/analytics/posthog.go@@ -156,6 +156,10 @@ type captureItem struct {DistinctID string `json:"distinct_id"`Properties map[string]any `json:"properties"`Timestamp string `json:"timestamp"`+ // UUID is PostHog's top-level event id; set only when the caller+ // supplied a deterministic one (for dedup). Omitted otherwise so+ // PostHog assigns its own, preserving existing behaviour.+ UUID string `json:"uuid,omitempty"`}func (c *PostHogClient) send(batch []Event) {@@ -187,6 +191,7 @@ func (c *PostHogClient) send(batch []Event) {DistinctID: e.DistinctID,Properties: props,Timestamp: e.Timestamp.UTC().Format(time.RFC3339Nano),+ UUID: e.UUID,})}diff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 3eb2d509da..d58f44ca67 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -44,6 +44,13 @@ type AppConfig struct {PosthogKey string `json:"posthog_key"`PosthogHost string `json:"posthog_host"`AnalyticsEnvironment string `json:"analytics_environment"`++ // SelfHostSourceNotice is true when this deployment will ship the+ // anonymous onboarding source beacon (MUL-3708) — i.e. a production+ // self-host. The onboarding source step shows the "anonymous+ // collection" notice only when this is true. Omitted (false) for the+ // common official-cloud case so responses stay identical there.+ SelfHostSourceNotice bool `json:"self_host_source_notice,omitempty"`}// GetConfig is mounted on the public (unauthenticated) route group because@@ -62,6 +69,11 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {config.CdnSigned = h.CFSigner != nilconfig.DaemonServerURL, config.DaemonAppURL = daemonSetupURLsFromEnv()+ // Mirror the source-beacon enablement so the onboarding source step+ // shows the anonymous-collection notice exactly when (and only when)+ // this deployment will actually ship the beacon. Nil-safe.+ config.SelfHostSourceNotice = h.SourceBeacon.Enabled()+// Re-read from env on every request so operators can rotate keys via// secret refresh without a server restart.if v := os.Getenv("ANALYTICS_DISABLED"); v != "true" && v != "1" {diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 0b6afb4b39..d5afb63b79 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -28,6 +28,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/sourcebeacon""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -136,6 +137,11 @@ type Handler struct {WebhookRateLimiter WebhookRateLimiterWebhookIPRateLimiter WebhookRateLimiterCloudRuntime cloudRuntimeProxy+ // SourceBeacon ships the self-host onboarding source beacon (MUL-3708).+ // Nil-safe: nil / disabled is a silent no-op, so tests and official+ // cloud / non-production deployments need no wiring. Set post-New in+ // cmd/server/router.go.+ SourceBeacon *sourcebeacon.Sender// Lark integration. All three are nil when the Lark master key// (MULTICA_LARK_SECRET_KEY) is unset; the corresponding HTTP// handlers return 503 in that case so a misconfigured self-hostdiff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.goindex b05f820edf..c1386f9a23 100644--- a/server/internal/handler/onboarding.go+++ b/server/internal/handler/onboarding.go@@ -265,6 +265,18 @@ func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {var after questionnaireAnswers_ = json.Unmarshal(user.OnboardingQuestionnaire, &after)++ // Self-host onboarding source beacon (MUL-3708). Fire once, when the+ // user first fills in their acquisition source. A production self-host+ // server ships the anonymous channel(s) to Multica's public ingest;+ // official cloud / non-production / disabled deployments are a silent+ // no-op (gated inside MaybeSend). Fire-and-forget — never blocks+ // onboarding, and re-sends are idempotent via the deterministic event+ // uuid, so the simple "newly non-empty" trigger is safe.+ if len(after.Source) > 0 && len(before.Source) == 0 {+ h.SourceBeacon.MaybeSend(userID, []string(after.Source))+ }+if after.complete() && !before.complete() {obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingQuestionnaireSubmitted(userID,diff --git a/server/internal/handler/source_telemetry.go b/server/internal/handler/source_telemetry.gonew file mode 100644index 0000000000..1da376e286--- /dev/null+++ b/server/internal/handler/source_telemetry.go@@ -0,0 +1,73 @@+package handler++import (+ "encoding/json"+ "net/http"++ "github.com/multica-ai/multica/server/internal/analytics"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/sourcebeacon"+)++// HandleSelfHostSourceBeacon ingests the self-host onboarding source beacon+// (MUL-3708). It is mounted PUBLIC and unauthenticated by design: self-host+// instances hold no Multica credential, so the data is treated as a coarse+// directional signal, not a trusted count. Abuse is bounded by the per-IP+// rate limiter (router), the tiny body cap, the channel allowlist, and+// strict unknown-field rejection.+//+// The payload is anonymous by construction — only channel enums plus two+// per-instance hashes. DisallowUnknownFields means any stray identity field+// (email, source_other, …) is rejected rather than logged or forwarded.+//+// Each valid channel becomes one PostHog event with a deterministic uuid+// (PostHog dedups on uuid) and $process_person_profile=false (so the+// anonymous uid_hash never spawns a PostHog person). On the official cloud+// this lands in the configured PostHog; on a self-host instance the same+// route exists but is unused (its analytics client is a no-op).+func (h *Handler) HandleSelfHostSourceBeacon(w http.ResponseWriter, r *http.Request) {+ r.Body = http.MaxBytesReader(w, r.Body, sourcebeacon.MaxBodyBytes)++ dec := json.NewDecoder(r.Body)+ dec.DisallowUnknownFields()+ var p sourcebeacon.Payload+ if err := dec.Decode(&p); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ // Reject trailing data / a second JSON value in the body.+ if dec.More() {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ if p.V != sourcebeacon.SchemaVersion {+ writeError(w, http.StatusBadRequest, "unsupported schema version")+ return+ }+ if !sourcebeacon.IsValidHash(p.UIDHash) || !sourcebeacon.IsValidHash(p.InstanceHash) {+ writeError(w, http.StatusBadRequest, "invalid hash")+ return+ }++ channels := sourcebeacon.FilterValidChannels(p.Channels)+ if len(channels) == 0 {+ writeError(w, http.StatusBadRequest, "no valid channels")+ return+ }++ for _, ch := range channels {+ ev := analytics.SelfHostSourceChannel(+ p.InstanceHash,+ p.UIDHash,+ ch,+ sourcebeacon.EventUUID(p.InstanceHash, p.UIDHash, ch),+ )+ // RecordEvent (not a naked Capture) so the event also increments the+ // Prometheus counter via IncForEvent. Not IsMetricsOnly, so it still+ // ships to PostHog. m==nil-safe (tests / metrics-disabled deploys).+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, ev)+ }++ w.WriteHeader(http.StatusNoContent)+}diff --git a/server/internal/handler/source_telemetry_test.go b/server/internal/handler/source_telemetry_test.gonew file mode 100644index 0000000000..c6e6e18290--- /dev/null+++ b/server/internal/handler/source_telemetry_test.go@@ -0,0 +1,129 @@+package handler++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/sourcebeacon"+)++// captureRecorder is a fake analytics.Client that records every captured+// event for assertions.+type captureRecorder struct{ events []analytics.Event }++func (c *captureRecorder) Capture(e analytics.Event) { c.events = append(c.events, e) }+func (c *captureRecorder) Close() {}++func postBeacon(t *testing.T, h *Handler, body string) *httptest.ResponseRecorder {+ t.Helper()+ req := httptest.NewRequest(http.MethodPost, "/api/telemetry/self-host-source", strings.NewReader(body))+ rec := httptest.NewRecorder()+ h.HandleSelfHostSourceBeacon(rec, req)+ return rec+}++func TestSelfHostSourceBeacon_ValidPayload(t *testing.T) {+ rec := &captureRecorder{}+ h := &Handler{Analytics: rec}+ uid := sourcebeacon.HashUID("salt", "user-1")+ inst := sourcebeacon.HashInstance("salt")++ resp := postBeacon(t, h, `{"v":1,"channels":["social_youtube","search"],"uid_hash":"`+uid+`","instance_hash":"`+inst+`"}`)++ if resp.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want 204; body=%s", resp.Code, resp.Body.String())+ }+ if len(rec.events) != 2 {+ t.Fatalf("captured %d events, want 2", len(rec.events))+ }+ for i, ch := range []string{"social_youtube", "search"} {+ e := rec.events[i]+ if e.Name != analytics.EventSelfHostSourceChannel {+ t.Errorf("event[%d].Name = %q", i, e.Name)+ }+ if e.DistinctID != "selfhost:"+uid {+ t.Errorf("event[%d].DistinctID = %q", i, e.DistinctID)+ }+ if !strings.Contains(e.DistinctID, ":") {+ t.Errorf("distinct_id must contain ':' to suppress user_id derivation")+ }+ if e.UUID != sourcebeacon.EventUUID(inst, uid, ch) {+ t.Errorf("event[%d].UUID = %q, want deterministic", i, e.UUID)+ }+ if e.Properties["source"] != ch {+ t.Errorf("event[%d].source = %v, want %q", i, e.Properties["source"], ch)+ }+ if e.Properties["deployment"] != "self_host" {+ t.Errorf("event[%d].deployment = %v", i, e.Properties["deployment"])+ }+ if e.Properties["instance_hash"] != inst {+ t.Errorf("event[%d].instance_hash = %v", i, e.Properties["instance_hash"])+ }+ if v, ok := e.Properties["$process_person_profile"].(bool); !ok || v {+ t.Errorf("event[%d] must set $process_person_profile=false, got %v", i, e.Properties["$process_person_profile"])+ }+ }+}++func TestSelfHostSourceBeacon_DropsUnknownChannelsKeepsValid(t *testing.T) {+ rec := &captureRecorder{}+ h := &Handler{Analytics: rec}+ uid := sourcebeacon.HashUID("salt", "u")+ inst := sourcebeacon.HashInstance("salt")++ resp := postBeacon(t, h, `{"v":1,"channels":["bogus","search"],"uid_hash":"`+uid+`","instance_hash":"`+inst+`"}`)+ if resp.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want 204", resp.Code)+ }+ if len(rec.events) != 1 || rec.events[0].Properties["source"] != "search" {+ t.Fatalf("expected only the valid channel captured, got %d events", len(rec.events))+ }+}++func TestSelfHostSourceBeacon_Rejections(t *testing.T) {+ uid := sourcebeacon.HashUID("salt", "u")+ inst := sourcebeacon.HashInstance("salt")+ cases := []struct {+ name string+ body string+ }{+ // The privacy red-line: any extra field (identity / source_other /+ // anything) is rejected, never logged or forwarded.+ {"unknown field", `{"v":1,"channels":["search"],"uid_hash":"` + uid + `","instance_hash":"` + inst + `","email":"[email protected]"}`},+ {"source_other field", `{"v":1,"channels":["other"],"uid_hash":"` + uid + `","instance_hash":"` + inst + `","source_other":"a podcast"}`},+ {"wrong version", `{"v":2,"channels":["search"],"uid_hash":"` + uid + `","instance_hash":"` + inst + `"}`},+ {"all invalid channels", `{"v":1,"channels":["nope"],"uid_hash":"` + uid + `","instance_hash":"` + inst + `"}`},+ {"empty channels", `{"v":1,"channels":[],"uid_hash":"` + uid + `","instance_hash":"` + inst + `"}`},+ {"invalid uid hash", `{"v":1,"channels":["search"],"uid_hash":"NOT-HEX","instance_hash":"` + inst + `"}`},+ {"malformed json", `{"v":1,`},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ rec := &captureRecorder{}+ h := &Handler{Analytics: rec}+ resp := postBeacon(t, h, tc.body)+ if resp.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400; body=%s", resp.Code, resp.Body.String())+ }+ if len(rec.events) != 0 {+ t.Fatalf("rejected payload must capture 0 events, got %d", len(rec.events))+ }+ })+ }+}++func TestSelfHostSourceBeacon_OversizedBody(t *testing.T) {+ rec := &captureRecorder{}+ h := &Handler{Analytics: rec}+ big := strings.Repeat("a", sourcebeacon.MaxBodyBytes+1)+ resp := postBeacon(t, h, `{"v":1,"channels":["search"],"uid_hash":"`+big+`","instance_hash":"x"}`)+ if resp.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400 for oversized body", resp.Code)+ }+ if len(rec.events) != 0 {+ t.Fatal("oversized body must capture 0 events")+ }+}diff --git a/server/internal/metrics/business_events.go b/server/internal/metrics/business_events.goindex aaf6295663..eb67942353 100644--- a/server/internal/metrics/business_events.go+++ b/server/internal/metrics/business_events.go@@ -61,6 +61,7 @@ type businessEventMetrics struct {cloudRuntimeRequestDurationSecs *prometheus.HistogramVecfeedbackSubmitted *prometheus.CounterVeccontactSalesSubmitted *prometheus.CounterVec+ selfHostSourceChannel *prometheus.CounterVec}func newBusinessEventMetrics() *businessEventMetrics {@@ -192,6 +193,10 @@ func newBusinessEventMetrics() *businessEventMetrics {Name: "multica_contact_sales_submitted_total",Help: "Total contact-sales inquiries submitted.",}, metricLabels("multica_contact_sales_submitted_total")),+ selfHostSourceChannel: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_self_host_source_channel_total",+ Help: "Total self-host onboarding source channel reports received (MUL-3708), by source.",+ }, metricLabels("multica_self_host_source_channel_total")),}}@@ -231,6 +236,7 @@ func (e *businessEventMetrics) collectors() []prometheus.Collector {e.cloudRuntimeRequestDurationSecs,e.feedbackSubmitted,e.contactSalesSubmitted,+ e.selfHostSourceChannel,}}@@ -348,6 +354,8 @@ func (m *BusinessMetrics) IncForEvent(ev analytics.Event) {).Inc()case analytics.EventContactSalesSubmitted:m.events.contactSalesSubmitted.WithLabelValues(NormalizeContactSalesSource(stringProp(ev.Properties, "form_source"))).Inc()+ case analytics.EventSelfHostSourceChannel:+ m.events.selfHostSourceChannel.WithLabelValues(NormalizeSourceChannel(stringProp(ev.Properties, "source"))).Inc()default:// agent_task_* lifecycle telemetry is recorded straight to Prometheus// via the typed BusinessMetrics.RecordTask* methods (they takediff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex 73aab0bfb6..ab0b2e1874 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -135,6 +135,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {exerciseEvent(m, analytics.EventAutopilotRunFailed, map[string]any{"cadence": "manual", "trigger_kind": "manual"})exerciseEvent(m, analytics.EventFeedbackSubmitted, map[string]any{"kind": "general", "platform": "web"})exerciseEvent(m, analytics.EventContactSalesSubmitted, map[string]any{"form_source": "page"})+ exerciseEvent(m, analytics.EventSelfHostSourceChannel, map[string]any{"source": "social_youtube"})// Direct Record* helpers (no PostHog event source).m.RecordAutopilotRunSkipped("manual", "throttled")diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex 8b0564a957..b26761ec15 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -82,6 +82,7 @@ var businessMetricLabels = map[string][]string{"multica_cloudruntime_request_duration_seconds": {labelOp},"multica_feedback_submitted_total": {labelKind, labelPlatform},"multica_contact_sales_submitted_total": {labelSource},+ "multica_self_host_source_channel_total": {labelSource},}var forbiddenMetricLabels = map[string]struct{}{diff --git a/server/internal/metrics/labels_pr3.go b/server/internal/metrics/labels_pr3.goindex 2e086534a2..9b6bc6b770 100644--- a/server/internal/metrics/labels_pr3.go+++ b/server/internal/metrics/labels_pr3.go@@ -3,6 +3,8 @@ package metricsimport ("encoding/json""strings"++ "github.com/multica-ai/multica/server/internal/sourcebeacon")// PR3 normalizers. All inputs go through fixed allow-lists so a misbehaving@@ -394,3 +396,13 @@ func NormalizeFeedbackKind(value string) string {func NormalizeContactSalesSource(value string) string {return normalizeFromAllowList(value, knownContactSalesSources, "other")}++// NormalizeSourceChannel bounds the self-host source beacon's `source`+// label to the onboarding channel allowlist (anything else → "other"),+// reusing sourcebeacon's single Go-side allowlist rather than a third copy.+func NormalizeSourceChannel(value string) string {+ if sourcebeacon.IsValidChannel(value) {+ return value+ }+ return "other"+}diff --git a/server/internal/sourcebeacon/sender.go b/server/internal/sourcebeacon/sender.gonew file mode 100644index 0000000000..f204db0b72--- /dev/null+++ b/server/internal/sourcebeacon/sender.go@@ -0,0 +1,117 @@+package sourcebeacon++import (+ "bytes"+ "context"+ "encoding/json"+ "log/slog"+ "net/http"+ "strings"+ "time"+)++const (+ // defaultUpstreamURL is Multica's public API base; the beacon path is+ // appended. Overridable via MULTICA_SOURCE_BEACON_URL.+ defaultUpstreamURL = "https://api.multica.ai"+ beaconPath = "/api/telemetry/self-host-source"+ sendTimeout = 5 * time.Second+)++// Sender ships the onboarding source beacon from a production self-host+// server. A disabled or salt-less Sender is a silent no-op. The zero value+// is not usable; build one with NewSender.+type Sender struct {+ enabled bool+ salt string+ endpoint string+ httpClient *http.Client+}++// SenderConfig configures NewSender.+type SenderConfig struct {+ // Enabled is the ShouldSend decision for this deployment. Typically+ // sourcebeacon.ShouldSendFromEnv().+ Enabled bool+ // Salt is the per-instance secret (system_settings.instance_salt). When+ // empty the Sender is forced off — we never ship un-salted hashes.+ Salt string+ // UpstreamURL overrides the public API base (default api.multica.ai).+ UpstreamURL string+ // HTTPClient overrides the default short-timeout client (tests inject a+ // stub).+ HTTPClient *http.Client+}++// NewSender returns a configured Sender. It is enabled only when both+// cfg.Enabled and a non-empty salt are present.+func NewSender(cfg SenderConfig) *Sender {+ base := strings.TrimRight(strings.TrimSpace(cfg.UpstreamURL), "/")+ if base == "" {+ base = defaultUpstreamURL+ }+ hc := cfg.HTTPClient+ if hc == nil {+ hc = &http.Client{Timeout: sendTimeout}+ }+ return &Sender{+ enabled: cfg.Enabled && strings.TrimSpace(cfg.Salt) != "",+ salt: cfg.Salt,+ endpoint: base + beaconPath,+ httpClient: hc,+ }+}++// Enabled reports whether this Sender will actually ship beacons. Nil-safe+// so the /api/config notice flag and the onboarding hook can call it+// without guarding.+func (s *Sender) Enabled() bool {+ return s != nil && s.enabled+}++// MaybeSend fires one fire-and-forget beacon for the user's selected+// channels. It is a no-op when disabled, when userID is empty, or when no+// channel is valid. It never blocks the caller and never surfaces an error+// — onboarding must not depend on telemetry succeeding.+func (s *Sender) MaybeSend(userID string, channels []string) {+ if !s.Enabled() || strings.TrimSpace(userID) == "" {+ return+ }+ valid := FilterValidChannels(channels)+ if len(valid) == 0 {+ return+ }+ payload := Payload{+ V: SchemaVersion,+ Channels: valid,+ UIDHash: HashUID(s.salt, userID),+ InstanceHash: HashInstance(s.salt),+ }+ go s.post(payload)+}++func (s *Sender) post(payload Payload) {+ body, err := json.Marshal(payload)+ if err != nil {+ slog.Warn("sourcebeacon: marshal payload failed", "error", err)+ return+ }+ // Detached context: the originating request has already returned, so we+ // must not inherit its (now-cancelled) context.+ ctx, cancel := context.WithTimeout(context.Background(), sendTimeout)+ defer cancel()+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.endpoint, bytes.NewReader(body))+ if err != nil {+ slog.Warn("sourcebeacon: build request failed", "error", err)+ return+ }+ req.Header.Set("Content-Type", "application/json")+ resp, err := s.httpClient.Do(req)+ if err != nil {+ // Loss is acceptable for this coarse signal; log at debug so a flaky+ // network doesn't spam self-host logs.+ slog.Debug("sourcebeacon: send failed (ignored)", "error", err)+ return+ }+ _ = resp.Body.Close()+}diff --git a/server/internal/sourcebeacon/sourcebeacon.go b/server/internal/sourcebeacon/sourcebeacon.gonew file mode 100644index 0000000000..ae43f7dd32--- /dev/null+++ b/server/internal/sourcebeacon/sourcebeacon.go@@ -0,0 +1,246 @@+// Package sourcebeacon implements the self-host onboarding source beacon+// (MUL-3708).+//+// Goal: let Multica see the anonymous "where did you hear about us"+// (onboarding source) distribution from production self-hosted instances —+// which today is invisible because self-host runs with no PostHog key and+// ships nothing.+//+// Shape: this is NOT a background telemetry pipeline. When a user fills in+// their onboarding source, a production self-host *server* fires one+// fire-and-forget HTTP beacon to Multica's public, write-only ingest. The+// official cloud keeps its existing PostHog capture unchanged and never+// fires the beacon.+//+// Privacy contract — only ever leaves a self-host instance:+// - the selected source channel enum value(s);+// - uid_hash = sha256(instance_salt + user_id), truncated;+// - instance_hash = sha256(instance_salt), truncated.+//+// The instance_salt is a per-instance secret that never leaves the box, so+// Multica cannot reverse a hash back to a user_id, and the same user on two+// different self-host instances hashes differently (no cross-instance+// correlation). Real user_id / email / name / workspace / org / domain /+// role / use_case / team_size and the source_other free-text are NEVER+// part of the payload.+package sourcebeacon++import (+ "crypto/sha256"+ "encoding/hex"+ "net/url"+ "os"+ "strings"++ "github.com/google/uuid"++ "github.com/multica-ai/multica/server/internal/analytics"+)++// SchemaVersion is the wire version of the beacon payload. Bump only with a+// matching ingest change.+const SchemaVersion = 1++// MaxChannelsPerRequest caps how many channels a single beacon may carry.+// The source enum has 13 members; the cap is headroom + an abuse bound on+// the public ingest.+const MaxChannelsPerRequest = 16++// MaxBodyBytes bounds the ingest request body. The payload is a tiny fixed+// JSON; 4 KiB is ~10x the realistic ceiling and keeps the public endpoint+// from being used as bulk storage.+const MaxBodyBytes = 4 << 10++// Payload is the exact, closed shape accepted by the public ingest. The+// ingest decodes it with DisallowUnknownFields, so any extra field (e.g. a+// leaked email or source_other) is rejected outright.+type Payload struct {+ V int `json:"v"`+ Channels []string `json:"channels"`+ UIDHash string `json:"uid_hash"`+ InstanceHash string `json:"instance_hash"`+}++// validChannels mirrors the `Source` enum in+// packages/core/onboarding/types.ts. Keep the two in sync — there is no+// shared source of truth across the Go/TS boundary yet (known tech debt).+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": {},+}++// IsValidChannel reports whether c is a known source channel enum value.+func IsValidChannel(c string) bool {+ _, ok := validChannels[c]+ return ok+}++// FilterValidChannels drops unknown channels, de-duplicates, and caps the+// result at MaxChannelsPerRequest. Used on both the sending and receiving+// side (defense in depth).+func FilterValidChannels(in []string) []string {+ out := make([]string, 0, len(in))+ seen := make(map[string]struct{}, len(in))+ for _, c := range in {+ if !IsValidChannel(c) {+ continue+ }+ if _, dup := seen[c]; dup {+ continue+ }+ seen[c] = struct{}{}+ out = append(out, c)+ if len(out) >= MaxChannelsPerRequest {+ break+ }+ }+ return out+}++// HashUID returns the truncated sha256 of (instance_salt + user_id). The+// salt stays on the instance, so this is one-way for Multica.+func HashUID(salt, userID string) string {+ sum := sha256.Sum256([]byte(salt + userID))+ return hex.EncodeToString(sum[:])[:32]+}++// HashInstance returns the truncated sha256 of the instance_salt. Stable per+// instance; used for grouping and the dedup key.+func HashInstance(salt string) string {+ sum := sha256.Sum256([]byte(salt))+ return hex.EncodeToString(sum[:])[:32]+}++// IsValidHash bounds an inbound hash to lowercase hex of a sane length. The+// sender always emits 32 hex chars; the range stays lenient so a future+// truncation change doesn't break ingest.+func IsValidHash(s string) bool {+ if len(s) < 16 || len(s) > 64 {+ return false+ }+ for i := 0; i < len(s); i++ {+ c := s[i]+ if (c < '0' || c > '9') && (c < 'a' || c > 'f') {+ return false+ }+ }+ return true+}++// beaconNamespace is a fixed namespace for deriving deterministic event+// UUIDs (UUIDv5). Stable across releases — changing it would break PostHog+// dedup for already-ingested events.+var beaconNamespace = uuid.MustParse("b1e7c0de-5a17-4f05-9c0a-5e1f0a7d3c21")++// EventUUID is the deterministic PostHog event uuid for one+// (instance_hash, uid_hash, channel) tuple. Re-sending the same tuple+// yields the same uuid, so PostHog deduplicates it (best-effort) — the+// reason the dedup key includes channel: a multi-select user produces one+// stable event per channel.+func EventUUID(instanceHash, uidHash, channel string) string {+ return uuid.NewSHA1(beaconNamespace, []byte(instanceHash+":"+uidHash+":"+channel)).String()+}++// ShouldSendInput is the explicit (testable) input to ShouldSend.+type ShouldSendInput struct {+ AnalyticsDisabled bool+ // Environment is the normalized value from analytics.EnvironmentFromEnv+ // ("production" / "staging" / "dev").+ Environment string+ // AppHost is the canonical host of the deployment's own frontend/app+ // URL (MULTICA_APP_URL, falling back to FRONTEND_ORIGIN).+ AppHost string+}++// ShouldSend decides whether THIS deployment should emit the beacon. It is+// fail-closed: anything ambiguous returns false. We judge by the+// deployment's own frontend/app host — NOT the backend URL — because the+// official cloud reliably configures its frontend domain even when+// MULTICA_PUBLIC_URL is unset (there is a regression test for exactly that),+// so keying on the backend URL would misclassify official as self-host and+// pollute production analytics.+func ShouldSend(in ShouldSendInput) bool {+ if in.AnalyticsDisabled {+ return false+ }+ if in.Environment != "production" {+ return false+ }+ if isLocalHost(in.AppHost) {+ return false+ }+ if isManagedHost(in.AppHost) {+ return false+ }+ return true+}++// ShouldSendFromEnv evaluates ShouldSend against the process environment.+func ShouldSendFromEnv() bool {+ return ShouldSend(ShouldSendInput{+ AnalyticsDisabled: analyticsDisabled(),+ Environment: analytics.EnvironmentFromEnv(),+ AppHost: AppHostFromEnv(),+ })+}++// AppHostFromEnv resolves the deployment's frontend/app host the same way+// /api/config's official-cloud check does: MULTICA_APP_URL, then+// FRONTEND_ORIGIN.+func AppHostFromEnv() string {+ if h := canonicalHost(os.Getenv("MULTICA_APP_URL")); h != "" {+ return h+ }+ return canonicalHost(os.Getenv("FRONTEND_ORIGIN"))+}++func analyticsDisabled() bool {+ v := os.Getenv("ANALYTICS_DISABLED")+ return v == "true" || v == "1"+}++// canonicalHost extracts a lowercased, port-stripped hostname from a URL or+// bare host string. Empty on parse failure.+func canonicalHost(raw string) string {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return ""+ }+ if !strings.Contains(raw, "://") {+ raw = "//" + raw+ }+ u, err := url.Parse(raw)+ if err != nil {+ return ""+ }+ return strings.TrimSuffix(strings.ToLower(u.Hostname()), ".")+}++func isLocalHost(host string) bool {+ switch host {+ case "", "localhost", "127.0.0.1", "::1":+ return true+ }+ return strings.HasSuffix(host, ".localhost")+}++// isManagedHost reports whether host belongs to Multica's managed cloud.+// Matches multica.ai and ANY *.multica.ai subdomain so official prod,+// staging, preview, and internal envs are all excluded without enumerating+// each one — no self-host can live on a multica.ai subdomain, so the suffix+// match is safe. (This is intentionally broader than the exact-host+// isOfficialCloudDaemonConfig check, which serves a different purpose.)+func isManagedHost(host string) bool {+ return host == "multica.ai" || strings.HasSuffix(host, ".multica.ai")+}diff --git a/server/internal/sourcebeacon/sourcebeacon_test.go b/server/internal/sourcebeacon/sourcebeacon_test.gonew file mode 100644index 0000000000..d105c14a3a--- /dev/null+++ b/server/internal/sourcebeacon/sourcebeacon_test.go@@ -0,0 +1,193 @@+package sourcebeacon++import (+ "encoding/json"+ "io"+ "net/http"+ "testing"+ "time"+)++func TestShouldSend(t *testing.T) {+ cases := []struct {+ name string+ in ShouldSendInput+ want bool+ }{+ {"production self-host", ShouldSendInput{Environment: "production", AppHost: "acme.example.com"}, true},+ {"analytics disabled", ShouldSendInput{AnalyticsDisabled: true, Environment: "production", AppHost: "acme.example.com"}, false},+ {"not production", ShouldSendInput{Environment: "staging", AppHost: "acme.example.com"}, false},+ {"dev", ShouldSendInput{Environment: "dev", AppHost: "acme.example.com"}, false},+ {"localhost", ShouldSendInput{Environment: "production", AppHost: "localhost"}, false},+ {"empty host", ShouldSendInput{Environment: "production", AppHost: ""}, false},+ {"official multica.ai", ShouldSendInput{Environment: "production", AppHost: "multica.ai"}, false},+ {"official app subdomain", ShouldSendInput{Environment: "production", AppHost: "app.multica.ai"}, false},+ {"official staging subdomain", ShouldSendInput{Environment: "production", AppHost: "staging.multica.ai"}, false},+ {"official api subdomain", ShouldSendInput{Environment: "production", AppHost: "api.multica.ai"}, false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := ShouldSend(tc.in); got != tc.want {+ t.Fatalf("ShouldSend(%+v) = %v, want %v", tc.in, got, tc.want)+ }+ })+ }+}++func TestCanonicalHost(t *testing.T) {+ cases := map[string]string{+ "https://acme.example.com": "acme.example.com",+ "http://localhost:3000": "localhost",+ "acme.example.com": "acme.example.com",+ "https://APP.MULTICA.AI/path": "app.multica.ai",+ "": "",+ "https://acme.example.com:8443": "acme.example.com",+ }+ for raw, want := range cases {+ if got := canonicalHost(raw); got != want {+ t.Errorf("canonicalHost(%q) = %q, want %q", raw, got, want)+ }+ }+}++func TestHashingIsDeterministicAndSalted(t *testing.T) {+ uid1 := HashUID("salt-a", "user-1")+ if uid1 != HashUID("salt-a", "user-1") {+ t.Fatal("HashUID not deterministic")+ }+ if len(uid1) != 32 {+ t.Fatalf("uid hash length = %d, want 32", len(uid1))+ }+ // Different salt (different instance) → different hash for same user.+ if uid1 == HashUID("salt-b", "user-1") {+ t.Fatal("same user across different salts must hash differently")+ }+ // Different user, same salt → different hash.+ if uid1 == HashUID("salt-a", "user-2") {+ t.Fatal("different users must hash differently")+ }+ // instance hash is stable and distinct from a uid hash.+ if HashInstance("salt-a") != HashInstance("salt-a") {+ t.Fatal("HashInstance not deterministic")+ }+ if HashInstance("salt-a") == uid1 {+ t.Fatal("instance hash must differ from uid hash")+ }+}++func TestEventUUIDDeterministicPerChannel(t *testing.T) {+ a := EventUUID("inst", "uid", "social_youtube")+ if a != EventUUID("inst", "uid", "social_youtube") {+ t.Fatal("EventUUID not deterministic")+ }+ if a == EventUUID("inst", "uid", "search") {+ t.Fatal("different channels must yield different event uuids")+ }+ if a == EventUUID("inst2", "uid", "social_youtube") {+ t.Fatal("different instances must yield different event uuids")+ }+ if len(a) != 36 { // canonical UUID string+ t.Fatalf("event uuid not canonical: %q", a)+ }+}++func TestFilterValidChannels(t *testing.T) {+ got := FilterValidChannels([]string{"social_youtube", "bogus", "search", "social_youtube", "", "other"})+ want := []string{"social_youtube", "search", "other"}+ if len(got) != len(want) {+ t.Fatalf("FilterValidChannels = %v, want %v", got, want)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("FilterValidChannels = %v, want %v", got, want)+ }+ }+ if len(FilterValidChannels([]string{"nope", "also_nope"})) != 0 {+ t.Fatal("all-invalid input must yield empty slice")+ }+}++func TestIsValidHash(t *testing.T) {+ if !IsValidHash(HashUID("s", "u")) {+ t.Fatal("a real hash must validate")+ }+ for _, bad := range []string{"", "xyz", "SHORT", "ABCDEF0123456789", "g123456789012345"} {+ if IsValidHash(bad) {+ t.Errorf("IsValidHash(%q) = true, want false", bad)+ }+ }+}++// roundTripFunc adapts a function to http.RoundTripper.+type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func TestSenderEnabledGating(t *testing.T) {+ if NewSender(SenderConfig{Enabled: false, Salt: "s"}).Enabled() {+ t.Fatal("Enabled:false must be disabled")+ }+ if NewSender(SenderConfig{Enabled: true, Salt: ""}).Enabled() {+ t.Fatal("empty salt must be disabled")+ }+ if !NewSender(SenderConfig{Enabled: true, Salt: "s"}).Enabled() {+ t.Fatal("enabled + salt must be enabled")+ }+ var nilSender *Sender+ if nilSender.Enabled() {+ t.Fatal("nil sender must be disabled")+ }+}++func TestSenderMaybeSendPostsPayload(t *testing.T) {+ got := make(chan Payload, 1)+ gotURL := make(chan string, 1)+ client := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ body, _ := io.ReadAll(r.Body)+ var p Payload+ _ = json.Unmarshal(body, &p)+ got <- p+ gotURL <- r.URL.String()+ return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody}, nil+ })}+ s := NewSender(SenderConfig{Enabled: true, Salt: "salt-x", UpstreamURL: "https://ingest.example", HTTPClient: client})++ s.MaybeSend("user-1", []string{"social_youtube", "bogus", "search"})++ select {+ case p := <-got:+ if p.V != SchemaVersion {+ t.Errorf("v = %d, want %d", p.V, SchemaVersion)+ }+ wantChannels := []string{"social_youtube", "search"}+ if len(p.Channels) != len(wantChannels) {+ t.Fatalf("channels = %v, want %v", p.Channels, wantChannels)+ }+ if p.UIDHash != HashUID("salt-x", "user-1") || p.InstanceHash != HashInstance("salt-x") {+ t.Error("payload hashes do not match expected salt hashing")+ }+ if u := <-gotURL; u != "https://ingest.example/api/telemetry/self-host-source" {+ t.Errorf("url = %q", u)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("expected a beacon POST, got none")+ }+}++func TestSenderMaybeSendNoOpCases(t *testing.T) {+ calls := make(chan struct{}, 1)+ client := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ calls <- struct{}{}+ return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody}, nil+ })}+ s := NewSender(SenderConfig{Enabled: true, Salt: "salt-x", HTTPClient: client})++ s.MaybeSend("user-1", []string{"bogus"}) // no valid channel+ s.MaybeSend("", []string{"search"}) // no user id++ select {+ case <-calls:+ t.Fatal("no beacon should have been sent")+ case <-time.After(150 * time.Millisecond):+ }+}diff --git a/server/migrations/128_system_settings_instance_salt.down.sql b/server/migrations/128_system_settings_instance_salt.down.sqlnew file mode 100644index 0000000000..1e2a497b7d--- /dev/null+++ b/server/migrations/128_system_settings_instance_salt.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS system_settings;diff --git a/server/migrations/128_system_settings_instance_salt.up.sql b/server/migrations/128_system_settings_instance_salt.up.sqlnew file mode 100644index 0000000000..5ea94f6f4f--- /dev/null+++ b/server/migrations/128_system_settings_instance_salt.up.sql@@ -0,0 +1,22 @@+-- Singleton per-deployment settings row. Currently holds the+-- instance_salt used by the self-host onboarding source beacon+-- (server/internal/sourcebeacon): uid_hash = sha256(instance_salt||user_id)+-- and instance_hash = sha256(instance_salt) are computed locally and+-- shipped to Multica's public ingest. The salt never leaves the instance,+-- so Multica cannot reverse a hash back to a user_id, and the same user on+-- two different self-host instances produces different hashes.+--+-- The salt is generated once, here, with pgcrypto's gen_random_bytes+-- (the "pgcrypto" extension is enabled in 001_init). Each deployment that+-- runs this migration gets its own random salt; the official cloud also+-- gets one but never sends a beacon, so its salt is simply unused.+--+-- Single-row table guarded by the id=1 CHECK, mirroring the+-- task_usage_hourly_rollup_state singleton pattern already in the schema.+CREATE TABLE system_settings (+ id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),+ instance_salt TEXT NOT NULL DEFAULT encode(gen_random_bytes(32), 'hex'),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++INSERT INTO system_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING;