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

83 lines
5.2 KiB
TypeScript

import assert from 'node:assert/strict';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { transport } from './http.ts';
// Run only in a child process against an extracted package; never contact a collector.
const [root, mode] = process.argv.slice(2);
assert(root && ['test', 'stable', 'local'].includes(mode));
for (const key of ['OPENMOTION_TELEMETRY', 'DO_NOT_TRACK', 'OPENMOTION_POSTHOG_HOST', 'OPENMOTION_POSTHOG_KEY', 'OPENMOTION_POSTHOG_TOKEN']) delete process.env[key];
process.env.OPENMOTION_POSTHOG_HOST = 'https://us.i.posthog.com';
process.env.OPENMOTION_POSTHOG_KEY = 'phc_testPackageSyntheticToken123456';
process.env.OPENMOTION_TRACKING_ENV = 'test'; process.env.OPENMOTION_TRACKING_TEST_RUN_ID = crypto.randomUUID();
const directory = await mkdtemp(path.join(tmpdir(), 'motion-tracking-package-'));
process.env.MOTION_DATA_DIR = directory;
const load = (file: string) => import(pathToFileURL(path.join(root, file)).href);
const { createAppTracking, trackingLocked } = await load('shared/tracking.ts');
const { handler } = await load('server.ts'), { WorkspaceStore } = await load('workspace.ts');
const { deviceContext } = await load('tracking/core.ts');
const packet = () => ({ event: 'ui_click', event_id: crypto.randomUUID(), occurred_at: new Date().toISOString(), entrypoint: 'studio',
...deviceContext(), properties: { page_name: 'home', area: 'workspace', element: 'new_creation' } });
const bodies: any[] = [];
globalThis.fetch = async (_url, init) => { bodies.push(JSON.parse(String(init?.body))); return Response.json({ status: 'Ok' }); };
const runtimes: any[] = [];
try {
for (const entry of ['mcp', 'worker']) runtimes.push(await createAppTracking(directory, entry));
const request = transport(new WorkspaceStore(directory), { tracking: runtimes[1] }, handler);
const set = (enabled: boolean) => request('/motion-api/tracking/preferences', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled }) });
const send = () => request('/motion-api/tracking', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ events: [packet()] }) });
assert.equal(trackingLocked(), false);
const status = await (await request('/motion-api/tracking/preferences')).json();
assert.deepEqual(status, { enabled: true, preference: true, locked: false, reason: null });
assert.equal((await send()).status, 200); await runtimes[1].flush();
for (let cycle = 0; cycle < 2; cycle++) {
for (const runtime of runtimes) runtime.ingest(packet());
assert.equal((await set(false)).status, 200);
for (const runtime of runtimes) {
assert.equal(runtime.enabled(), false);
assert.equal(runtime.pending(), 0); assert.equal(runtime.ingest(packet()), 'disabled');
assert.equal(await runtime.flush(), 'disabled');
}
const before = bodies.length;
await send(); assert.equal(bodies.length, before);
const restarted = await createAppTracking(directory, 'mcp'); runtimes.push(restarted);
assert.equal(restarted.enabled(), false);
assert.equal((await set(true)).status, 200);
for (const runtime of runtimes) {
assert.equal(runtime.ingest(packet()), 'queued'); assert.equal(await runtime.flush(), 'accepted');
}
assert.equal(bodies.length, before + runtimes.length);
}
assert.equal(new Set(bodies.flatMap(body => body.batch.map((event: any) => event.properties.installation_id))).size, 1);
const properties = bodies.flatMap(body => body.batch.map((event: any) => event.properties));
assert(properties.every((value: any) => value.distinct_id === value.installation_id));
assert(properties.every((value: any) => value.device_id_source === 'platform'
? /^omd_[0-9a-f]{64}$/.test(value.device_id)
: value.device_id_source === 'unavailable' && value.device_id === 'unknown'));
if (process.getuid) {
const { editorDirectory, ensureEditor } = await load('editor-runtime.ts');
const { data, runtime } = await editorDirectory(directory);
const registry = { service: 'opendesign-editor', protocol: 1, version: mode === 'test' ? '0.6.4' : '0.6.4-test.8',
build: 'fixture', instanceId: crypto.randomUUID(), pid: process.pid, dataDirectory: data,
endpoint: 'http://127.0.0.1:4173/', token: 'a'.repeat(64) };
const registryFile = path.join(runtime, 'runtime.json');
await writeFile(registryFile, JSON.stringify(registry));
const before = await readFile(registryFile, 'utf8');
globalThis.fetch = async url => {
assert.equal(new URL(String(url)).pathname, '/editor-api/health');
return Response.json({ ...registry, mcp: { protocol: 1, tools: ['motion_get_project'] } });
};
const editor = await ensureEditor(directory, 'motion_get_project');
assert.equal(editor.version, registry.version);
assert.equal(await readFile(registryFile, 'utf8'), before);
}
console.log(JSON.stringify({ version: JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')).version,
policy: mode, captured_requests: bodies.length, external_requests: 0, passed: true }));
} finally {
for (const runtime of runtimes) runtime.close();
await rm(directory, { recursive: true, force: true });
}