Files
openmotion/tracking/browser.ts
open-design-crew[bot] 3b56272dfe [OPEND-5496][OPEND-5807] feat(tracking): cloud allowlist, per-user identity, and dual-write Tracert telemetry (#1130)
* [OPEND-5496] feat(cloud-tracking): add cloud allowlist, cloud_web channel, and monetization attribution

* test(studio): assert resolution gate attribution payload in AssetComposer

* fix(cloud-tracking): address Looper review (restore tests, rotate entry_id, deploy env, docs)

* fix(studio): pass native job.model.modelId for failure-gate attribution

* feat(tracking): add Tracert v0.6.0 dual reporting, canonical user identity, and env-only PostHog config

Integrate @powerformer/tracert@0.6.0 alongside existing PostHog telemetry for both Studio browser and cloud API server reporting while keeping self-hosted deployments strictly opt-in with zero hardcoded tokens.

- Add shared runtime tracking config validation and CSP-safe HTML injection so Studio hydrates tracking config in 0 RTT when enabled and skips downloading the lazy Tracert chunk when OPENMOTION_TRACERT_SPM_A is unset.
- Dual-write closed-schema Studio events and server-side account_sign_in_result across PostHog and Tracert using identical event_id and occurred_at values, keeping auto-collection plugins disabled and registering graceful TracertNode shutdown.
- Align browser and server user identity on AMR appUserId (falling back to local user.id only when self-hosted), attach workspace_id/workspace_role/plan_tier as user context, preserve anonymous device_id across passive signed-out reloads, and rotate identity on explicit sign-out.
- Remove hardcoded PostHog credentials in shared/tracking-config.json so standalone tracking is strictly env-driven.
- Allowlist only the SHA-256 digest of the SDK's default public Collector endpoint in bundled Studio JS assets in .github/scripts/motion-scan.mjs.

* fix(tracking): preserve equivalent Tracert init loads, clear expired SDK identity, and drain PostHog queues on shutdown

* fix(tracking): propagate render telemetryOptOut, isolate browser queue across identity changes, and wire production identity sync

* fix(tracking): isolate identity sync module and guard non-browser tracking init

---------

Co-authored-by: qiqi <qiqi@qiqideMBP.lan>
Co-authored-by: 罗高 <luogao@users.noreply.github.com>
2026-11-26 19:28:11 +08:00

31 lines
1.7 KiB
TypeScript

import { createTracker } from './core.ts';
import type { Registry } from './core.ts';
export function createBrowserTracking<const R extends Registry>(options: {
endpoint: string;
registry: R;
enabled: boolean;
flushIntervalMs?: number;
isEnabled?: () => boolean;
getDeviceId?: () => string | null | undefined;
}) {
const endpoint = new URL(options.endpoint, window.location.href);
if (endpoint.origin !== window.location.origin || endpoint.username || endpoint.password) throw new Error('SAME_ORIGIN_REQUIRED');
const context = new URLSearchParams(window.location.search).get('tracking_context');
if (context && /^[0-9a-f-]{36}$/i.test(context)) endpoint.searchParams.set('context', context);
const tracking = createTracker({ ...options, entrypoint: 'studio', send: async (events, signal) => {
if (signal.aborted) return 'drop';
try {
const rawDeviceId = options.getDeviceId?.();
const deviceId = typeof rawDeviceId === 'string' && rawDeviceId.trim() ? rawDeviceId.trim() : undefined;
const response = await fetch(endpoint, { method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json' },
body: JSON.stringify(deviceId ? { events, device_id: deviceId } : { events }), keepalive: true, signal: AbortSignal.any([signal, AbortSignal.timeout(1000)]) });
if (signal.aborted) return 'drop';
if (!response.ok) return response.status >= 500 || response.status === 429 ? 'retry' : 'drop';
const receipt = await response.json() as { enabled?: boolean };
if (receipt.enabled === false) tracking.setEnabled(false);
return 'accepted';
} catch { return signal.aborted ? 'drop' : 'retry'; }
} });
return tracking;
}