Files
openmotion/tracking/core.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

146 lines
8.5 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { validHostContext } from './host.ts';
import type { HostContext } from './host.ts';
export type Rule = 'project_id' | 'uuid' | 'code' | 'slug' | 'text' | 'timestamp' | 'boolean' | 'integer' | readonly string[] | { readonly min: number; readonly max: number };
export type Registry = Record<string, { fields: Record<string, Rule>; required: readonly string[] }>;
export type Fields = Record<string, string | number | boolean>;
type RuleValue<R> = R extends readonly string[] ? R[number] : R extends 'boolean' ? boolean : R extends 'integer' | { readonly min: number; readonly max: number } ? number : string;
export type EventFields<S extends Registry[string]> =
{ [K in S['required'][number]]: K extends keyof S['fields'] ? RuleValue<S['fields'][K]> : never } &
{ [K in Exclude<keyof S['fields'], S['required'][number]>]?: RuleValue<S['fields'][K]> };
export type Entry = 'mcp' | 'studio' | 'webmcp' | 'installer' | 'worker';
export type PendingEvent = {
event: string; event_id: string; occurred_at: string; entrypoint: Entry;
device_timezone: string | null; utc_offset_minutes: number; properties: Fields;
host_context?: HostContext;
};
export type Receipt = 'accepted' | 'retry' | 'drop';
export const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const code = /^[A-Za-z0-9_.-]{1,128}$/;
// A catalogue resource id: letters, digits and single hyphens between them, at most 64 characters.
// No dots, slashes, spaces or underscores, so a path, URL, file name or title cannot pass.
export const slug = /^(?=.{1,64}$)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/;
// The only free-text rule: a settled search-box value, trimmed, 1–100 characters, no control characters.
// Register it on a field only when the product decision to collect that text is explicit.
export const text = (value: string) => value.length >= 1 && value.length <= 100 && value === value.trim() && !/[\u0000-\u001f\u007f]/.test(value);
export function validField(rule: Rule, value: unknown): value is string | number | boolean {
if (Array.isArray(rule)) return typeof value === 'string' && rule.includes(value);
if (typeof rule === 'object' && 'min' in rule) return typeof value === 'number' && Number.isFinite(value) && value >= rule.min && value <= rule.max;
if (rule === 'boolean') return typeof value === 'boolean';
if (rule === 'integer') return Number.isSafeInteger(value) && Number(value) >= 0 && Number(value) <= 86_400_000;
if (rule === 'text') return typeof value === 'string' && text(value);
if (rule === 'timestamp') return typeof value === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(value) && Number.isFinite(Date.parse(value));
if (rule === 'project_id') return typeof value === 'string' && (value === 'project' || uuid.test(value));
return typeof value === 'string' && (rule === 'uuid' ? uuid : rule === 'slug' ? slug : code).test(value);
}
export function deviceContext() {
return { device_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || null,
utc_offset_minutes: -new Date().getTimezoneOffset() };
}
export function validProperties(registry: Registry, event: string, raw: unknown): raw is Fields {
if (!Object.hasOwn(registry, event) || !raw || typeof raw !== 'object' || Array.isArray(raw)) return false;
const spec = registry[event], values = raw as Fields;
if (spec.required.some(key => !Object.hasOwn(values, key))) return false;
return Object.entries(values).every(([key, value]) => {
if (!Object.hasOwn(spec.fields, key)) return false;
return validField(spec.fields[key], value);
});
}
export function validPending(registry: Registry, value: unknown): value is PendingEvent {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const e = value as PendingEvent;
if (Object.keys(e).some(k => !['event','event_id','occurred_at','entrypoint','device_timezone','utc_offset_minutes','properties','host_context'].includes(k))) return false;
if (e.host_context !== undefined && !validHostContext(e.host_context)) return false;
if (typeof e.occurred_at !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(e.occurred_at)) return false;
const time = Date.parse(e.occurred_at), age = Date.now() - time;
if (!uuid.test(e.event_id) || !Number.isFinite(time) || age < -300_000 || age > 86_400_000) return false;
if (!['mcp','studio','webmcp','installer','worker'].includes(e.entrypoint)) return false;
if (!Number.isInteger(e.utc_offset_minutes) || Math.abs(e.utc_offset_minutes) > 840) return false;
if (e.device_timezone !== null) {
if (typeof e.device_timezone !== 'string' || e.device_timezone.length > 64) return false;
try { new Intl.DateTimeFormat('en', { timeZone: e.device_timezone }); } catch { return false; }
}
return validProperties(registry, e.event, e.properties) && JSON.stringify(e).length <= 4096;
}
export function createTracker<const R extends Registry>(options: {
registry: R; entrypoint: Entry; enabled: boolean;
send: (events: readonly PendingEvent[], signal: AbortSignal) => Promise<Receipt>;
maxQueue?: number; flushIntervalMs?: number; isEnabled?: () => boolean;
}) {
let enabled = options.enabled, queue: PendingEvent[] = [], timer: ReturnType<typeof setTimeout> | undefined;
let inFlight: Promise<Receipt | 'disabled' | 'empty'> | undefined, controller: AbortController | undefined;
const seen = new Set<string>(), maxQueue = options.maxQueue ?? 64;
let failures = 0, epoch = 0;
function discard() {
epoch += 1;
queue = [];
seen.clear();
failures = 0;
if (timer) clearTimeout(timer);
timer = undefined;
const activeController = controller;
controller = undefined;
inFlight = undefined;
activeController?.abort();
}
function active() {
let allowed = enabled;
try { allowed = allowed && (options.isEnabled?.() ?? true); } catch { allowed = false; }
if (!allowed) discard();
return allowed;
}
function schedule() {
if (!active() || timer || options.flushIntervalMs === 0) return;
timer = setTimeout(() => { timer = undefined; void flush(); }, Math.min(60_000, (options.flushIntervalMs ?? 1000) * 2 ** failures));
(timer as unknown as { unref?: () => void }).unref?.();
}
function ingest(raw: unknown) {
if (!active()) return 'disabled';
if (!validPending(options.registry, raw)) return 'invalid';
if (seen.has(raw.event_id)) return 'duplicate';
if (queue.length >= maxQueue) return 'full';
queue.push(structuredClone(raw)); seen.add(raw.event_id);
// shortcut: process-local queue and dedup; add durable storage only if crash recovery is required.
if (seen.size > 2048) seen.delete(seen.values().next().value!);
schedule(); return 'queued';
}
function track<E extends keyof R & string>(event: E, properties: EventFields<R[E]>, eventId: string = crypto.randomUUID(), entrypoint: Entry = options.entrypoint, host?: HostContext) {
if (!active()) return 'disabled';
try { return ingest({ event, properties, event_id: eventId, occurred_at: new Date().toISOString(),
entrypoint, ...deviceContext(), ...(host ? { host_context: host } : {}) }); } catch { return 'invalid'; }
}
function setEnabled(next: boolean) {
enabled = next;
if (!next) discard();
}
function flush(): Promise<Receipt | 'disabled' | 'empty'> {
if (!active()) return Promise.resolve('disabled');
if (inFlight) return inFlight;
if (!queue.length) return Promise.resolve('empty');
if (timer) clearTimeout(timer); timer = undefined;
queue = queue.filter(event => Date.now() - Date.parse(event.occurred_at) <= 86_400_000);
if (!queue.length) return Promise.resolve('empty');
const flushEpoch = epoch;
const snapshot = queue.slice(0, 16), request = new AbortController(); controller = request;
const run = (async () => {
let receipt: Receipt;
try { receipt = await options.send(snapshot, request.signal); } catch { receipt = request.signal.aborted ? 'drop' : 'retry'; }
if (flushEpoch !== epoch) return 'drop' as const;
if (!active()) return 'disabled' as const;
failures = receipt === 'retry' ? Math.min(6, failures + 1) : 0;
if (receipt !== 'retry') { const ids = new Set(snapshot.map(e => e.event_id)); queue = queue.filter(e => !ids.has(e.event_id)); }
return receipt;
})().finally(() => {
if (inFlight === run) {
inFlight = undefined;
controller = undefined;
}
if (flushEpoch === epoch && queue.length) schedule();
});
inFlight = run;
return run;
}
return { track, ingest, flush, setEnabled, reset: discard, enabled: active, pending: () => queue.length,
close: () => { setEnabled(false); } };
}