Skills › HyperFrames › media-use › telemetry.mjs
telemetry.mjs
253 lines · skills/media-use/scripts/lib/telemetry.mjs at a595755
1// Usage tracking shares the CLI and Studio identity. Properties stay coarse and
2// never carry intent text, file names, or paths.
4import { createHash, randomUUID } from "node:crypto";
5import * as fs from "node:fs";
6import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7import { homedir } from "node:os";
8import { dirname, join } from "node:path";
9import { withFileLock } from "./config-lock.mjs";
10import { globalMediaDir } from "./media-home.mjs";
12const POSTHOG_API_KEY = "phc_zjjbX0PnWxERXrMHhkEJWj9A9BhGVLRReICgsfTMmpx";
13const POSTHOG_HOST = "https://us.i.posthog.com";
14const TIMEOUT_MS = 1500;
15let identifiedAccount = false;
16let warnedNonDefaultHost = false;
18function isTestOrCiContext() {
19 return (
20 process.env.CI === "true" ||
21 process.env.CI === "1" ||
22 process.env.NODE_ENV === "test" ||
23 process.env.NODE_ENV === "development"
24 );
25}
27function posthogHost() {
28 const override = process.env.MEDIA_USE_TELEMETRY_HOST;
29 if (override && !warnedNonDefaultHost && !isTestOrCiContext()) {
30 warnedNonDefaultHost = true;
31 console.error(
32 `media-use: telemetry is redirected to a non-default host via MEDIA_USE_TELEMETRY_HOST (${override}) — unset it unless this is intentional.`,
33 );
34 }
35 return override || POSTHOG_HOST;
36}
38/** True when telemetry must NOT be sent (opt-out envs, CI, dev, shared config). */
39export function optedOut() {
40 return (
41 // `hyperframes telemetry disable` writes telemetryEnabled: false to the
42 // shared config; one opt-out must cover the CLI and the media-use scripts.
43 readSharedConfig().telemetryEnabled === false ||
44 process.env.HYPERFRAMES_NO_TELEMETRY === "1" ||
45 process.env.DO_NOT_TRACK === "1" ||
46 process.env.CI === "true" ||
47 process.env.CI === "1" ||
48 process.env.NODE_ENV === "development"
49 );
50}
52// Read and write the shared config so media-use keeps one identity per install.
53// Until the CLI seeds HYPERFRAMES_CONFIG_DIR's copy, ~/.hyperframes' own still holds the opt-out.
54function sharedConfigPath() {
55 const home = join(homedir(), ".hyperframes", "config.json");
56 const dir = process.env.HYPERFRAMES_CONFIG_DIR;
57 if (!dir) return home;
58 const file = join(dir, "config.json");
59 return existsSync(file) || !existsSync(home) ? file : home;
60}
62function readSharedConfig() {
63 try {
64 const file = sharedConfigPath();
65 if (existsSync(file)) {
66 const parsed = JSON.parse(readFileSync(file, "utf8"));
67 if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
68 }
69 } catch {
70 // unreadable config → treat as empty; never throw
71 }
72 return {};
73}
75// Best effort: skipped when the lock cannot be taken or the file cannot be read, never written unlocked.
76function updateSharedConfig(patch) {
77 const file = sharedConfigPath();
78 mkdirSync(dirname(file), { recursive: true });
79 try {
80 withFileLock(`${file}.lock`, fs, () => {
81 let config = {};
82 try {
83 config = JSON.parse(readFileSync(file, "utf8"));
84 } catch (error) {
85 if (error.code !== "ENOENT") return;
86 }
87 if (!config || typeof config !== "object" || Array.isArray(config)) return;
88 const tmp = `${file}.${process.pid}.tmp`;
89 writeFileSync(tmp, JSON.stringify({ ...config, ...patch }, null, 2) + "\n", { mode: 0o600 });
90 renameSync(tmp, file);
91 });
92 } catch {}
93}
95// Adopt a pre-existing media-use-only id (~/.media/anon-id from before this
96// change) so upgraders keep their PostHog persona instead of resetting to a new
97// one — otherwise cross-surface continuity would start over on upgrade.
98function legacyMediaAnonId() {
99 try {
100 const file = join(globalMediaDir(), "anon-id");
101 if (existsSync(file)) {
102 const id = readFileSync(file, "utf8").trim();
103 if (id) return id;
104 }
105 } catch {
106 // ignore
107 }
108 return null;
109}
111// Stable per-machine id from the shared config; seeds it (adopting a legacy
112// media-use id when present) if absent.
113function anonymousId() {
114 try {
115 const config = readSharedConfig();
116 if (typeof config.anonymousId === "string" && config.anonymousId.trim()) {
117 return config.anonymousId.trim();
118 }
119 const id = legacyMediaAnonId() || randomUUID();
120 updateSharedConfig({ anonymousId: id });
121 return id;
122 } catch {
123 return "anon"; // best-effort; a shared bucket is fine if the fs is read-only
124 }
125}
127// The HyperFrames user id for a HeyGen username: the same sha256-derived UUID
128// the CLI (auth/telemetryIdentity.ts), web app and Desktop key PostHog on.
129const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
131export function heygenUserId(username) {
132 if (UUID_PATTERN.test(username)) return username;
133 const hash = createHash("sha256").update(username).digest();
134 hash[6] = (hash[6] & 0x0f) | 0x50;
135 hash[8] = (hash[8] & 0x3f) | 0x80;
136 const hex = hash.toString("hex");
137 return [
138 hex.slice(0, 8),
139 hex.slice(8, 12),
140 hex.slice(12, 16),
141 hex.slice(16, 20),
142 hex.slice(20, 32),
143 ].join("-");
144}
146// The signed-in HeyGen account, keyed like the CLI's own identify call: the
147// username's user id, else the lowercased email (lowercased so different stored
148// casing never splits one person). `heygen_username` is the cross-project join
149// column for the Snowflake event table.
150function heygenAccount() {
151 const root = process.env.HYPERFRAMES_CONFIG_DIR || join(homedir(), ".hyperframes");
152 const file = join(root, ...(process.env.HYPERFRAMES_ENV === "dev" ? ["dev"] : []), "credentials");
153 try {
154 if (!existsSync(file)) return null;
155 const raw = readFileSync(file, "utf8").trim();
156 if (!raw.startsWith("{")) return null;
157 const parsed = JSON.parse(raw);
158 if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
159 if (!parsed.api_key && !parsed.oauth) return null;
160 const user = parsed.user;
161 if (!user || typeof user !== "object" || Array.isArray(user)) return null;
162 const email =
163 typeof user.email === "string" && user.email.trim() ? user.email.trim().toLowerCase() : null;
164 const username =
165 typeof user.username === "string" && user.username.trim() ? user.username : null;
166 const traits = {};
167 if (email) traits.email = email;
168 if (username) traits.heygen_username = username;
169 if (username) return { distinctId: heygenUserId(username), traits };
170 if (email) return { distinctId: email, traits };
171 return null;
172 } catch {
173 return null;
174 }
175}
177function showTelemetryNotice() {
178 if (optedOut()) return;
179 try {
180 const config = readSharedConfig();
181 // Shared with the CLI (config.telemetryNoticeShown): shown once per person
182 // across surfaces, not once per tool.
183 if (config.telemetryNoticeShown === true) return;
184 console.error(
185 [
186 "media-use sends usage telemetry: media type, resolution source, and provider; never intent text, file names, or paths.",
187 "If you sign in to HeyGen, usage links to your account (email and username). Opt out with HYPERFRAMES_NO_TELEMETRY=1 or DO_NOT_TRACK=1.",
188 ].join("\n"),
189 );
190 updateSharedConfig({ telemetryNoticeShown: true });
191 } catch {
192 // notice is best-effort; never surface into the command
193 }
194}
196async function postBatch(batch) {
197 try {
198 await fetch(`${posthogHost()}/batch/`, {
199 method: "POST",
200 headers: { "Content-Type": "application/json", Connection: "close" },
201 body: JSON.stringify({ api_key: POSTHOG_API_KEY, batch }),
202 signal: AbortSignal.timeout(TIMEOUT_MS),
203 });
204 } catch {
205 // telemetry is best-effort; never surface into the command
206 }
207}
209async function postEvent(event, properties, distinctId) {
210 await postBatch([
211 {
212 event,
213 properties: { ...properties, surface: "media-use", $ip: null },
214 distinct_id: distinctId,
215 timestamp: new Date().toISOString(),
216 },
217 ]);
218}
220async function identifyAccount(anonId, account) {
221 if (optedOut() || identifiedAccount || !account) return;
222 identifiedAccount = true;
223 await postEvent(
224 "$identify",
225 { $anon_distinct_id: anonId, $set: account.traits },
226 account.distinctId,
227 );
228}
230/**
231 * Fire-and-forget a single event to PostHog. Best-effort: awaited with a short
232 * timeout so a short-lived script flushes before exit, but any failure (offline,
233 * opted out) is swallowed. `properties` must be non-PII (no intent/paths).
234 */
235export async function track(event, properties = {}) {
236 if (optedOut()) return;
237 showTelemetryNotice();
238 const anonId = anonymousId();
239 const account = heygenAccount();
240 await identifyAccount(anonId, account);
241 const username = account?.traits.heygen_username;
242 if (!username) return postEvent(event, properties, anonId);
243 await postEvent(event, { ...properties, heygen_username: username }, heygenUserId(username));
244}
246export function __anonymousIdForTest() {
247 return anonymousId();
248}
250export function __resetTelemetryForTest() {
251 identifiedAccount = false;
252 warnedNonDefaultHost = false;
253}