Files
openmotion/shared/tracking-runtime-config.ts
open-design-crew[bot] 6aab6c517a [OPEND-5751] feat(auth): bring Google One Tap (#1047) to main (#1131)
* feat(auth): integrate Google One Tap across cloud backend, Studio web, and desktop handoff (#1047)

* feat(auth): integrate Google One Tap across cloud backend, desktop handoff, and studio web

* fix(auth): address L1 review findings for One Tap S2S, desktop handoff, and cloud tracking

* fix(auth): resolve all round-2 L1 review blockers for Google One Tap

* fix(motion): harden One Tap K8s egress, atomic provenance, post-commit logout barrier, consent, tracking retry, and loopback CSP

* fix(motion): propagate AMR sessionProof across One Tap, OIDC, and desktop handoff-ticket flows

* fix(motion): close R4 L1 blockers (post-proof logout barrier, upgrade-handoff 503 fail-closed, atomic getdel, server consent cookie)

* fix(motion): enforce One Tap logout revocation inside resolveBrowserSession and block unbound Pricing redirect on active-session 401/403

* fix(motion): align One Tap binding revocation TTL to full 7-day session lifetime and keep upgrade-handoff 401 fail-closed on reload

* fix(motion): fail closed on Redis/DB errors in One Tap revocation check and never downgrade expired om_session on upgrade-handoff

* fix(motion): retain One Tap revocation binding for full session TTL and bind upgrade-handoff 503 retries to requireAuth/expectedAppUserId

* fix(motion): cryptographically bind upgrade-handoff 503 retries to originating session before DB/AMR enrichment

* fix(motion): bind signed-in PricingEntry and 503 reload cookie to originating session/account and guard readSessionProof errors

* fix(motion): redirect unbound upgrade-handoff 503 via same-origin 303 to session-bound URL so F5 reloads never lose binding

* fix(k8s): align AMR One Tap internal URL and NetworkPolicy with nexu namespace

* fix(ci): narrow desktop-handoff union types and remove false-positive secret/internal-link hits in One Tap files

* fix(studio): align One Tap 2s delay, SHOW-04 reload recovery, and ERR-06/07 failure CTA

* fix(studio): align One Tap banned account copy with standalone login page (OPEND-5763)

* fix(auth): address PR #1047 review findings (upgrade-handoff recovery, CSP, unified tracking privacy & rate limit, source scan)

* fix(auth): gate upgrade-handoff on isOneTapConfigured, decouple tracking toggle from deviceIdConsented, and bound logout-epoch map

* fix(ci): resolve backend typecheck, dock short-host floor, ci-scope, and source privacy scan

(cherry picked from commit 19a75ca0ec)

* test(mcp): expect the connected-environment line appended to server instructions

initialize instructions, but the registry discovery test still compared the
whole string against the registry-only guide.

* test(auth): isolate One Tap route tests from the runner's telemetry opt-out

CI exports OPENMOTION_TELEMETRY=0 for the cloud job, which disables the
PostHog dispatcher and locks tracking preferences, so the One Tap tracking
cases failed only in CI. Clear OPENMOTION_TELEMETRY and DO_NOT_TRACK for the
suite and restore them afterwards.

Ported onto main without #1066. Adaptations to main: logout keeps main's
server-side OIDC end-session and never returns endSessionUrl, so the
od_onetap_suppress post-logout redirect hint and OIDC_POST_LOGOUT_REDIRECT_URI
are dropped (client-side One Tap suppression still runs on confirmed sign-out)
and main's oidcIdTokenCacheKey replaces the separate id_token store. Browser
telemetry stays on main's createCloudTracking pipeline with deployment-locked
preferences; the separate PostHog dispatcher and per-user tracking toggle are
dropped, while attested app_user_id filtering, the tracking attestation cookie
and device-ID consent are added to main's /motion-api/tracking (createApiApp
accepts an optional cloudTracking handle for tests). The upgrade-handoff link
builder moves into main's buildSubscriptionUrl, and the desktop loopback
response deferral follows main's nullable-server attempt lifecycle.

---------

Co-authored-by: heggria <bshengtao@gmail.com>
(cherry picked from commit 4616728e07)

* fix(studio): report the One Tap document CSP instead of enforcing it

main serves Studio documents without a CSP and still embeds third-party
frames that the One Tap allowlist does not cover (for example external
playable games such as littleprince.dev in the game catalog). Enforcing
frame-src would block them. GIS does not need a CSP, so ship the policy
as Content-Security-Policy-Report-Only and keep Permissions-Policy and
COOP enforced; enforce the CSP once every embedded frame source is listed.

* fix(auth): keep main's tracking identity and optional One Tap manifest refs

- /motion-api/tracking no longer stamps the session app_user_id onto
  events that did not carry one; those events stay installation-scoped
  exactly as on main. Attested One Tap attribution is unchanged.
- deploy/k8s: the One Tap internal URL/token refs are optional so
  clusters without One Tap still start (the API already fails closed),
  and the ingress no longer adds a configuration-snippet, which default
  ingress-nginx admission rejects and which duplicated headers the API
  already sets on Studio documents.

* fix(studio): create the browser tracker on first use

AccountSettings now imports googleOneTap, which imports the Studio
tracking module. That module created the browser tracker and attached
window/document listeners at import time, so node-environment suites
that reach AccountSettings (compositionStackExport, agentToolsExport,
PropertyPanel, AssetsTab and others) failed with 'window is not
defined'. Create the tracker and its flush listeners on first use;
nothing can be pending before then, so browser behavior is unchanged.

* refactor(tracking): drop the unused sender channel option

No caller sets the PostHog sender's channel since the cloud API hands
browser batches to the cloud tracking pipeline, so the option only
suggested a cloud path that does not exist. Sender events keep the
standalone channel.

* refactor(auth): share the metrics consent cookie contract

The device-ID consent cookie name and its granted/denied values were
spelled separately in the auth routes, the tracking API and the tests.
Export them from the session module next to the other auth cookies and
use the shared constants everywhere, so the One Tap attribution gate and
the consent writer cannot drift apart.

* fix(tracking): use the session app user id before AMR enrichment

Signed-in browser tracking batches looked up the AMR identity for every
request even though the session membership already carries the projected
AMR app user id. Attribute from the membership first and call
verifyAndEnrichAuthContext only for sessions without a projected app user
id. A failed fallback still treats the batch as guest telemetry.

* fix(auth): render upgrade notices with the design system

The billing handoff notice pages carried their own dark-only palette and
button styles. Load the shared /design-system/ui.css on a data-motion-ui
root instead, so the pages follow the system light/dark preference, and
render the actions as ui-button / ui-button--primary controls. Only page
layout stays local and it references design-system tokens.

The notice CSP now allows the same-origin stylesheet and the fonts its
@font-face rules load (style-src 'self' 'unsafe-inline'; font-src 'self')
and keeps default-src 'none' for everything else.

* fix(auth): honor One Tap session proof expiry

The One Tap exchange stored AMR's session proof for the full Motion
session lifetime and ignored sessionProofExpiresAt, so an expired proof
kept being sent to the handoff-ticket endpoint and every rejection showed
the retryable 503 page, which retrying can never fix.

Store the proof for at most the time AMR advertises, capped by the
session lifetime; an unparseable expiry falls back to the session
lifetime and an expiry in the past stores no proof. When the handoff
ticket is rejected terminally (401 SESSION_PROOF_INVALID for an invalid,
expired or mismatched proof, or 404 USER_NOT_FOUND), drop the stored
proof and return the existing REAUTH_REQUIRED fresh sign-in path. A
banned or frozen account (403 ACCOUNT_BANNED / ACCOUNT_FROZEN) gets the
403 account notice. Network failures, timeouts, 5xx responses and a 401
without a proof code (internal token rejected) keep the session-bound
retry page and the stored proof.

* refactor(auth): stop issuing the tracking attestation cookie

The signed om_track_att cookie let /motion-api/tracking accept a
browser-supplied app_user_id that the server had attested. Since the
merge with the cloud tracking overhaul the endpoint resolves the user
from the live session and rejects any packet that carries a user id, so
nothing reads the cookie any more. Stop setting it on OIDC callback, One
Tap sign-in, desktop handoff and /auth/me, and remove its signing
helpers. The derived secret stays: it still binds upgrade-handoff retry
URLs to the originating session.

* refactor(auth): share one OpenDesign handoff URL guard

The browser upgrade handoff and the desktop Pricing handoff each carried
a line-for-line copy of the check that decides whether an AMR-issued
handoff URL may be followed. Export isSafeOpenDesignHandoffUrl from the
desktop handoff module next to the other handoff helpers and use it from
both. The rules are unchanged: no control characters or credentials, an
origin from OPENDESIGN_API_URL, OPENDESIGN_CONSOLE_URL or
OPENDESIGN_PRICING_URL, and https unless one of those is configured as
http. Add unit coverage for the shared guard.

* refactor(auth): share the One Tap session proof cache key

Session revocation deleted the stored AMR session proof through a string
literal while the auth routes built the same key with a local helper.
Export oneTapSessionProofCacheKey from the session module beside the
other One Tap cache keys and use it for saving, reading and deleting the
proof and in the route tests.

* refactor(auth): drop the unwired One Tap telemetry hook

AuthRoutesDeps.onOneTapTelemetry was called from seven places in the One
Tap exchange, but no caller ever supplied it and the onetap_* events are
registered with the Studio as their only producer, which already reports
them from the browser. Remove the field and its call sites.

* refactor(auth): remove the dormant device-ID consent path

No product surface ever granted the metrics consent, so the consent
route, shared cookie constants and Studio consent reader only kept an
unreachable device-ID forwarding branch alive.

- Delete POST /motion-api/tracking/consent and shared/metrics-consent.ts;
  the tracking route is back to main's shape.
- The One Tap attribution sanitizer now always drops odDeviceId and
  odDeviceIdConsent, whatever the client claims.
- Studio no longer reads od_device_id from the URL, localStorage or the
  od_attr cookie, never persists it and never sends it in odEntry;
  ref, UTM and other od_* attribution are unchanged.

* refactor(studio): reuse the shared plan-tier normalizer

onetap_login_success normalized planTier with a local copy of the
tier list. Use normalizeDesktopHandoffPlanTier from
shared/desktop-auth-handoff.ts instead so Studio, the desktop shell and
the server share one tier list. Output is unchanged: the five tiers
map to themselves and anything else maps to 'unknown'.

---------

Co-authored-by: open-design-crew[bot] <299007234+open-design-crew[bot]@users.noreply.github.com>
Co-authored-by: heggria <bshengtao@gmail.com>
2026-11-26 20:40:12 -08:00

357 lines
12 KiB
TypeScript

export const TRACKING_RUNTIME_CONFIG_ELEMENT_ID = 'openmotion-tracking-config' as const;
export const TRACKING_RUNTIME_CONFIG_PLACEHOLDER = '<!-- openmotion:tracking-config -->' as const;
/**
* Cloud production allowlist for browser-originated Studio events.
*
* Shared strictly across PostHog and Tracert so dual-reporting maintains 1:1 event parity while
* cutting high-volume editor micro-interactions (playback, shortcuts, audio_fx_*), internal SDK/GSAP
* shadow diagnostics, and card-level gallery impressions.
*
* Set `OPENMOTION_CLOUD_TRACKING_FULL=1` on the API server to bypass the allowlist on both sinks
* during diagnostics.
*/
export const CLOUD_ALLOWED_STUDIO_EVENTS: ReadonlySet<string> = new Set([
// Active baseline, navigation & monetization pre-funnel
'page_view',
'studio_load_result',
'provider_setup_opened',
'ui_click',
'surface_view',
'entitlement_refresh_result',
// Google One Tap sign-in funnel (one attempt per guest page load, then a single outcome)
'onetap_prompt_attempt',
'onetap_prompt_observed',
'onetap_credential_received',
'onetap_login_success',
'onetap_login_failed',
// Template, Skill & MCP discovery/adoption
'template_search_result',
'template_search_handoff_result',
'template_filter_result',
'template_guide_interaction',
'template_instruction_copy_result',
'template_project_result',
'resource_download_result',
'skill_search_result',
'skill_instruction_copy_result',
'mcp_copy_result',
// Media generation, assets, settings, projects & brand kits
'asset_generation_submit_result',
'asset_update_result',
'provider_setting_result',
'agent_setting_result',
'project_manage_result',
'version_history_result',
'brand_kit_create_result',
'brand_kit_import_result',
'brand_kit_instruction_copy_result',
'brand_kit_action_result',
// Low-frequency editor & export outcomes + feedback
'studio_edit_result',
'studio_asset_import_result',
'studio_export_request_result',
'studio_export_result',
'studio_io_result',
'studio_feedback',
'diagnostic_export_result',
// Critical reliability guardrails
'crash',
'unhandled_error',
'unhandled_promise_rejection',
'save_failure',
'commit_transaction_failed',
]);
/** High-volume card-level `surface_view` areas dropped in cloud production. */
export const CLOUD_BLOCKED_SURFACE_AREAS: ReadonlySet<string> = new Set([
'template_card',
'template_series_card',
]);
export function isCloudFullTrackingEnabled(env?: Readonly<Record<string, string | undefined>>): boolean {
const fullFlag = (env?.OPENMOTION_CLOUD_TRACKING_FULL ?? '').trim().toLowerCase();
return fullFlag === '1' || fullFlag === 'true';
}
export function isCloudBrowserEventAllowed(
raw: unknown,
env?: Readonly<Record<string, string | undefined>>,
): boolean {
if (isCloudFullTrackingEnabled(env)) return true;
if (!raw || typeof raw !== 'object') return false;
const record = raw as { event?: unknown; properties?: unknown };
if (typeof record.event !== 'string' || !CLOUD_ALLOWED_STUDIO_EVENTS.has(record.event)) {
return false;
}
if (record.event === 'surface_view' && record.properties && typeof record.properties === 'object') {
const area = (record.properties as { area?: unknown }).area;
if (typeof area === 'string' && CLOUD_BLOCKED_SURFACE_AREAS.has(area)) {
return false;
}
}
return true;
}
export type TracertEnvironment = 'prod' | 'test';
export type TrackingLockReason = 'environment' | 'cloud' | null;
export interface BrowserTracertConfig {
readonly spmA: string | number;
readonly endpoint?: string;
readonly environment: TracertEnvironment;
readonly appVersion?: string;
}
export interface BrowserTrackingRuntimeConfig {
readonly enabled: boolean;
readonly posthogEnabled: boolean;
readonly allowlistEnabled: boolean;
readonly locked: boolean;
readonly reason: TrackingLockReason;
readonly tracert: BrowserTracertConfig | null;
}
export interface BrowserTracertInput {
readonly spmA?: string | number | null;
readonly endpoint?: string | null;
readonly environment?: string | null;
readonly appVersion?: string | null;
}
export interface BrowserTrackingRuntimeInput {
readonly posthogEnabled: boolean;
readonly allowlistEnabled?: boolean;
readonly locked?: boolean;
readonly reason?: TrackingLockReason;
readonly tracert?: BrowserTracertInput | BrowserTracertConfig | null;
}
interface DocumentLike {
getElementById(id: string): { textContent: string | null } | null;
}
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
const POSITIVE_INT_PATTERN = /^[1-9]\d*$/;
const MAX_SPM_A_LENGTH = 256;
const MAX_APP_VERSION_LENGTH = 128;
function trimOptional(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
/**
* Validates Tracert `spmA` (positive safe integer or non-empty string up to 256 chars).
* Pure positive integer strings normalize to numbers to match the Collector schema.
*/
export function parseTracertSpmA(raw: unknown): string | number | null {
if (typeof raw === 'number') {
return Number.isSafeInteger(raw) && raw > 0 ? raw : null;
}
const value = trimOptional(raw);
if (!value || value.length > MAX_SPM_A_LENGTH) return null;
if (POSITIVE_INT_PATTERN.test(value)) {
const numeric = Number(value);
if (Number.isSafeInteger(numeric) && numeric > 0) return numeric;
}
return value;
}
/**
* Validates an optional Tracert collector endpoint override.
* - `undefined`: omitted (SDK uses its default public collector endpoint).
* - `string`: validated HTTPS URL, loopback HTTP URL (local tests), or same-origin path (e.g. `/t/events`).
* - `null`: malformed non-empty value (caller must fail closed).
*/
export function parseTracertEndpoint(raw: unknown): string | null | undefined {
if (raw === undefined || raw === null) return undefined;
if (typeof raw !== 'string') return null;
const value = raw.trim();
if (!value) return undefined;
if (/\s/.test(value)) return null;
if (value.startsWith('/')) {
if (value.startsWith('//') || value.includes('?') || value.includes('#')) return null;
return value;
}
let parsed: URL;
try {
parsed = new URL(value);
} catch {
return null;
}
if (parsed.username || parsed.password || parsed.search || parsed.hash) return null;
const isHttps = parsed.protocol === 'https:';
const isLoopbackHttp = parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase());
if (!isHttps && !isLoopbackHttp) return null;
return parsed.toString();
}
/**
* Maps OpenMotion environment labels (`production` / `development` / `test` / `prod`)
* into the closed set accepted by `@powerformer/tracert` (`prod` | `test`).
*/
export function normalizeTracertEnvironment(
raw: unknown,
fallback: TracertEnvironment = 'prod',
): TracertEnvironment {
const value = trimOptional(raw)?.toLowerCase();
if (!value) return fallback;
if (value === 'prod' || value === 'production') return 'prod';
if (value === 'test' || value === 'development' || value === 'dev' || value === 'staging') return 'test';
return fallback;
}
/**
* Produces a validated browser Tracert config, or `null` when unconfigured or invalid.
* Self-hosted deployments without `OPENMOTION_TRACERT_SPM_A` stay completely disabled.
*/
export function buildBrowserTracertConfig(
input: BrowserTracertInput | BrowserTracertConfig | null | undefined,
): BrowserTracertConfig | null {
if (!input) return null;
const spmA = parseTracertSpmA(input.spmA);
if (spmA === null) return null;
const endpoint = parseTracertEndpoint(input.endpoint);
if (endpoint === null) return null;
const environment = normalizeTracertEnvironment(input.environment, 'prod');
const rawVersion = trimOptional(input.appVersion);
const appVersion = rawVersion && rawVersion.length <= MAX_APP_VERSION_LENGTH ? rawVersion : undefined;
return Object.freeze({
spmA,
...(endpoint ? { endpoint } : {}),
environment,
...(appVersion ? { appVersion } : {}),
});
}
export function buildBrowserTrackingRuntimeConfig(
input: BrowserTrackingRuntimeInput,
): BrowserTrackingRuntimeConfig {
const posthogEnabled = Boolean(input.posthogEnabled);
const tracert = buildBrowserTracertConfig(input.tracert);
const enabled = posthogEnabled || tracert !== null;
const allowlistEnabled = enabled && Boolean(input.allowlistEnabled);
const locked = input.locked ?? true;
const reason: TrackingLockReason =
input.reason === 'environment' || input.reason === 'cloud' ? input.reason : null;
return Object.freeze({
enabled,
posthogEnabled,
allowlistEnabled,
locked,
reason,
tracert,
});
}
function escapeJsonForHtmlScript(value: unknown): string {
return JSON.stringify(value)
.replaceAll('<', '\\u003c')
.replaceAll('>', '\\u003e')
.replaceAll('&', '\\u0026')
.replaceAll('\u2028', '\\u2028')
.replaceAll('\u2029', '\\u2029');
}
/**
* Serializes a CSP-safe `<script type="application/json">` tag for Studio HTML.
* Returns empty string when telemetry is disabled so self-hosted HTML stays untouched.
*/
export function serializeTrackingRuntimeConfigTag(
config: BrowserTrackingRuntimeConfig | null,
): string {
if (!config || !config.enabled) return '';
const payload = escapeJsonForHtmlScript(config);
return `<script type="application/json" id="${TRACKING_RUNTIME_CONFIG_ELEMENT_ID}">${payload}</script>`;
}
export function injectTrackingRuntimeConfigIntoHtml(
html: string,
config: BrowserTrackingRuntimeConfig | null,
): string {
const tag = serializeTrackingRuntimeConfigTag(config);
if (html.includes(TRACKING_RUNTIME_CONFIG_PLACEHOLDER)) {
return html.replace(TRACKING_RUNTIME_CONFIG_PLACEHOLDER, () => tag);
}
if (!tag) return html;
const headCloseIndex = html.search(/<\/head>/i);
if (headCloseIndex === -1) return `${tag}${html}`;
return `${html.slice(0, headCloseIndex)}${tag}\n${html.slice(headCloseIndex)}`;
}
/**
* Parses either an HTML-injected payload or a `/motion-api/tracking` JSON response.
* Remains backwards-compatible with minimal `{ enabled: boolean }` responses.
*/
export function parseTrackingRuntimeConfigResponse(
raw: unknown,
): BrowserTrackingRuntimeConfig | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const record = raw as Record<string, unknown>;
if (typeof record.enabled !== 'boolean') return null;
const locked = typeof record.locked === 'boolean' ? record.locked : true;
const reason: TrackingLockReason =
record.reason === 'environment' || record.reason === 'cloud' ? record.reason : null;
const posthogEnabled =
typeof record.posthogEnabled === 'boolean' ? record.posthogEnabled : true;
const allowlistEnabled =
typeof record.allowlistEnabled === 'boolean' ? record.allowlistEnabled : false;
if (!record.enabled) {
return Object.freeze({
enabled: false,
posthogEnabled,
allowlistEnabled: false,
locked,
reason,
tracert: null,
});
}
const tracertRaw =
record.tracert && typeof record.tracert === 'object' && !Array.isArray(record.tracert)
? (record.tracert as BrowserTracertInput)
: null;
const tracert = buildBrowserTracertConfig(tracertRaw);
const enabled = posthogEnabled || tracert !== null;
return Object.freeze({
enabled,
posthogEnabled,
allowlistEnabled: enabled && allowlistEnabled,
locked,
reason,
tracert,
});
}
export function readTrackingRuntimeConfigFromDocument(
doc?: DocumentLike | null,
): BrowserTrackingRuntimeConfig | null {
const target =
doc !== undefined
? doc
: typeof globalThis !== 'undefined' && 'document' in globalThis
? ((globalThis as { document?: DocumentLike }).document ?? null)
: null;
if (!target || typeof target.getElementById !== 'function') return null;
try {
const el = target.getElementById(TRACKING_RUNTIME_CONFIG_ELEMENT_ID);
const text = el?.textContent?.trim();
if (!text) return null;
return parseTrackingRuntimeConfigResponse(JSON.parse(text));
} catch {
return null;
}
}