Skip to content

Commit 3032626

Browse files
fix: opt-out marker reads the machine id bounded and leaves telemetry state alone
readExistingMachineId() shares the regular-file, size-cap and UUID checks of the minting read; the envelope builder takes the machine id and identity as arguments so recordOptOut() never mutates module state an enabled init may use. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE
1 parent a0fbcf8 commit 3032626

4 files changed

Lines changed: 46 additions & 19 deletions

File tree

‎packages/opencode/src/altimate/telemetry/index.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1944,7 +1944,16 @@ export namespace Telemetry {
19441944
return { iKey, endpoint: `${base}v2/track` }
19451945
}
19461946

1947-
function toAppInsightsEnvelopes(events: Event[], cfg: AppInsightsConfig): object[] {
1947+
// altimate_change — `ids` lets a caller build envelopes for a machine and identity other than
1948+
// the module's current state (the opt-out marker runs while telemetry is disabled and must not
1949+
// touch the state an enabled init may be using concurrently).
1950+
function toAppInsightsEnvelopes(
1951+
events: Event[],
1952+
cfg: AppInsightsConfig,
1953+
ids?: { machineId: string; identity: TelemetryIdentity.Identity | undefined },
1954+
): object[] {
1955+
const mid = ids ? ids.machineId : machineId
1956+
const who = ids ? ids.identity : identity
19481957
// Process-level client, read live from the env flag (defaults to "cli") so events
19491958
// emitted before any prompt runs — startup, connection setup, standalone CLI
19501959
// subcommands — are labelled correctly instead of stuck at a hardcoded default.
@@ -1961,10 +1970,10 @@ export namespace Telemetry {
19611970
cli_version: InstallationVersion,
19621971
source: clientSource,
19631972
project_id: fields.project_id ?? projectId,
1964-
...(machineId && { machine_id: machineId }),
1973+
...(mid && { machine_id: mid }),
19651974
// altimate_change — the backend user uuid and tenant when signed in to Altimate, so a CLI
19661975
// row joins the PostHog person and the backend record for the same account.
1967-
...(identity && { user_id: identity.user_id, tenant: identity.tenant }),
1976+
...(who && { user_id: who.user_id, tenant: who.tenant }),
19681977
// altimate_change — groups every event from one process launch. The onboarding funnel
19691978
// spans the TUI main thread and the server worker, and most of it runs before any chat
19701979
// session exists, so `session_id` is empty for the first half and real for the second —
@@ -1992,7 +2001,7 @@ export namespace Telemetry {
19922001
// altimate_change start — the backend user uuid when signed in, else the machine id.
19932002
// Anonymous machines each keep a distinct identity (the random machine UUID, already a
19942003
// custom property) instead of sharing ai.user.id="". No email, hashed or not, is sent.
1995-
"ai.user.id": identity?.user_id || machineId || "",
2004+
"ai.user.id": who?.user_id || mid || "",
19962005
// altimate_change end
19972006
"ai.cloud.role": "altimate",
19982007
"ai.application.ver": InstallationVersion,
@@ -2185,14 +2194,11 @@ export namespace Telemetry {
21852194
const explicit = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
21862195
const cfg = parseConnectionString(explicit ?? DEFAULT_CONNECTION_STRING)
21872196
if (!cfg) return
2188-
machineId = id
2189-
identity = await TelemetryIdentity.cached()
21902197
const envelopes = toAppInsightsEnvelopes(
21912198
[{ type: "telemetry_opted_out", timestamp: Date.now(), opt_out_source: source }],
21922199
cfg,
2200+
{ machineId: id, identity: await TelemetryIdentity.cached() },
21932201
)
2194-
machineId = ""
2195-
identity = undefined
21962202
const controller = new AbortController()
21972203
const timeout = setTimeout(() => controller.abort(), OPT_OUT_TIMEOUT_MS)
21982204
try {
@@ -2208,8 +2214,6 @@ export namespace Telemetry {
22082214
}
22092215
} catch {
22102216
// The opt-out path never surfaces: a missed marker only means one more attempt next launch.
2211-
machineId = ""
2212-
identity = undefined
22132217
}
22142218
}
22152219
// altimate_change end

‎packages/opencode/src/altimate/telemetry/opt-out.ts‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "fs"
22
import path from "path"
33
import { Global } from "../../global"
4+
import { readExistingMachineId } from "@/altimate/util/machine-id"
45

56
/**
67
* The marker that says this machine already sent its final ``telemetry_opted_out`` event.
@@ -16,8 +17,6 @@ import { Global } from "../../global"
1617
* id lives in.
1718
*/
1819
export namespace OptOutMarker {
19-
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
20-
2120
function dir(): string {
2221
return path.join(Global.Path.home, ".altimate")
2322
}
@@ -27,14 +26,9 @@ export namespace OptOutMarker {
2726
}
2827

2928
/** The machine id minted by an earlier telemetry-enabled run, if any. Never mints one: a machine
30-
* that never sent telemetry has nothing to mark. */
29+
* that never sent telemetry has nothing to mark. Bounded and symlink-safe, like the minting read. */
3130
export function readMachineId(): string | undefined {
32-
try {
33-
const raw = fs.readFileSync(path.join(dir(), "machine-id"), "utf8").trim()
34-
return UUID.test(raw) ? raw : undefined
35-
} catch {
36-
return undefined
37-
}
31+
return readExistingMachineId(path.join(dir(), "machine-id")) || undefined
3832
}
3933

4034
export function exists(): boolean {

‎packages/opencode/src/altimate/util/machine-id.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,24 @@ function readCappedUtf8(idPath: string): string {
5454
* @param machineIdPath Override path (for tests). Defaults to `~/.altimate/machine-id`.
5555
* @returns A v4 UUID string, or `""` if the value is invalid or unreadable.
5656
*/
57+
/**
58+
* Read an existing machine id without minting one. Same regular-file, size-cap and UUID
59+
* checks as {@link getOrCreateMachineId}; returns `""` when the file is absent, unreadable,
60+
* not a regular file, oversized or not a UUID. For callers that must not create a machine
61+
* identity as a side effect (the telemetry opt-out marker).
62+
*/
63+
export function readExistingMachineId(machineIdPath?: string): string {
64+
const idPath = machineIdPath ?? path.join(os.homedir(), ".altimate", "machine-id")
65+
try {
66+
const stat = fs.lstatSync(idPath)
67+
if (!stat.isFile() || stat.size > MAX_BYTES) return ""
68+
const raw = readCappedUtf8(idPath)
69+
return UUID_RE.test(raw) ? raw : ""
70+
} catch {
71+
return ""
72+
}
73+
}
74+
5775
export function getOrCreateMachineId(machineIdPath?: string): string {
5876
const idPath = machineIdPath ?? path.join(os.homedir(), ".altimate", "machine-id")
5977

‎packages/opencode/test/altimate/telemetry/opt-out.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,17 @@ describe("telemetry opt-out marker", () => {
138138
expect(existsSync(path.join(home, ".altimate", "machine-id"))).toBe(false)
139139
})
140140

141+
test("a corrupt or oversized machine-id file sends nothing", async () => {
142+
mkdirSync(path.join(home, ".altimate"), { recursive: true })
143+
writeFileSync(path.join(home, ".altimate", "machine-id"), "not-a-uuid\n" + "x".repeat(4096))
144+
process.env.ALTIMATE_TELEMETRY_DISABLED = "1"
145+
await Telemetry.shutdown()
146+
await Telemetry.init()
147+
await new Promise((r) => setTimeout(r, 150))
148+
expect(trackPosts()).toHaveLength(0)
149+
expect(OptOutMarker.exists()).toBe(false)
150+
})
151+
141152
test("the marker is written only once the sink accepted the event", async () => {
142153
writeMachineId()
143154
process.env.OPENCODE_DISABLE_TELEMETRY = "true"

0 commit comments

Comments
 (0)