Skip to content

Commit d275dec

Browse files
fix: telemetry identity follows credential changes from any path
Resolve the credential like the provider (file, else the auth-store key); notice sign-in, sign-out and key changes on disk at the next flush; attribute a batch to the identity it was tracked under; drop the cache on a 401 or 403; never cache an answer for a credential that changed mid-flight. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE
1 parent fc4f80c commit d275dec

6 files changed

Lines changed: 230 additions & 25 deletions

File tree

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

Lines changed: 73 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import fs from "fs"
12
import path from "path"
23
import { rm } from "node:fs/promises"
34
import { createHash } from "crypto"
45
import { Global } from "../../global"
56
import { Filesystem } from "../../util/filesystem"
7+
import { Auth } from "../../auth"
68
import { AltimateApi } from "@/altimate/api/client"
79
import { Log } from "@/altimate/util/log"
810

@@ -17,23 +19,63 @@ const log = Log.create({ service: "telemetry-identity" })
1719
* the same call the workspace client makes) and hands telemetry a ``user_id`` and ``tenant``
1820
* to stamp on every event. No email, hashed or not, leaves the client.
1921
*
20-
* The result is cached at ``~/.altimate/telemetry-identity.json`` under a fingerprint of the
21-
* credential, so a process only hits the network when the credential changed. Every failure
22-
* resolves to ``undefined``: telemetry must never block or break on identity.
22+
* The credential is the one the Altimate provider uses: ``~/.altimate/altimate.json`` first,
23+
* else the ``altimate-backend`` entry of the auth store (a key entered in the TUI). The result
24+
* is cached at ``~/.altimate/telemetry-identity.json`` under a fingerprint of the credential, so
25+
* a process only hits the network when the credential changed. Every failure resolves to
26+
* ``undefined``: telemetry must never block or break on identity.
2327
*/
2428
export namespace TelemetryIdentity {
2529
export type Identity = { user_id: string; tenant: string }
2630

31+
type Credential = { altimateUrl: string; altimateInstanceName: string; altimateApiKey: string }
2732
type Cached = Identity & { fingerprint: string }
2833

2934
const REQUEST_TIMEOUT_MS = 10_000
3035
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
36+
const AUTH_STORE_KEY = "altimate-backend"
3137

3238
export function cachePath(): string {
3339
return path.join(Global.Path.home, ".altimate", "telemetry-identity.json")
3440
}
3541

36-
function fingerprint(c: { altimateUrl: string; altimateInstanceName: string; altimateApiKey: string }): string {
42+
/** The credential the Altimate provider would use, or undefined when signed out. */
43+
export async function loadCredential(): Promise<Credential | undefined> {
44+
try {
45+
if (await AltimateApi.isConfigured()) {
46+
const c = await AltimateApi.getCredentials()
47+
return {
48+
altimateUrl: c.altimateUrl,
49+
altimateInstanceName: c.altimateInstanceName,
50+
altimateApiKey: c.altimateApiKey,
51+
}
52+
}
53+
const auth = await Auth.get(AUTH_STORE_KEY)
54+
if (auth?.type === "api") return AltimateApi.parseAltimateKey(auth.key) ?? undefined
55+
return undefined
56+
} catch {
57+
return undefined
58+
}
59+
}
60+
61+
/**
62+
* A cheap stamp of the two credential files (mtime and size), so a flush can notice that a
63+
* sign-in, sign-out or key change happened on disk, in this thread or another, without
64+
* reading or parsing anything.
65+
*/
66+
export function credentialStamp(): string {
67+
const stamp = (p: string) => {
68+
try {
69+
const s = fs.statSync(p)
70+
return `${s.mtimeMs}:${s.size}`
71+
} catch {
72+
return "absent"
73+
}
74+
}
75+
return `${stamp(AltimateApi.credentialsPath())}|${stamp(Auth.filepath())}`
76+
}
77+
78+
function fingerprint(c: Credential): string {
3779
return createHash("sha256")
3880
.update(`${c.altimateUrl}\n${c.altimateInstanceName}\n${c.altimateApiKey}`)
3981
.digest("hex")
@@ -54,11 +96,11 @@ export namespace TelemetryIdentity {
5496
}
5597
}
5698

57-
/** The cached identity, if it belongs to the credential currently on disk. No network. */
99+
/** The cached identity, if it belongs to the credential currently in use. No network. */
58100
export async function cached(): Promise<Identity | undefined> {
59101
try {
60-
if (!(await AltimateApi.isConfigured())) return undefined
61-
const creds = await AltimateApi.getCredentials()
102+
const creds = await loadCredential()
103+
if (!creds) return undefined
62104
const hit = await readCache()
63105
if (!hit || hit.fingerprint !== fingerprint(creds)) return undefined
64106
return { user_id: hit.user_id, tenant: hit.tenant }
@@ -70,22 +112,31 @@ export namespace TelemetryIdentity {
70112
/**
71113
* Resolve the signed-in user. Uses the cache when the credential has not changed; otherwise
72114
* asks the backend and caches the answer. ``refresh`` forces the request (after a sign-in).
115+
* A backend rejection (401 or 403) drops the cache for that credential; a transient failure
116+
* keeps it. The answer is written and returned only if the same credential is still in use.
73117
*/
74118
export async function resolve(opts: { refresh?: boolean } = {}): Promise<Identity | undefined> {
75119
try {
76-
if (!(await AltimateApi.isConfigured())) {
120+
const creds = await loadCredential()
121+
if (!creds) {
77122
await clear()
78123
return undefined
79124
}
80-
const creds = await AltimateApi.getCredentials()
81125
const fp = fingerprint(creds)
82126
if (!opts.refresh) {
83127
const hit = await readCache()
84128
if (hit && hit.fingerprint === fp) return { user_id: hit.user_id, tenant: hit.tenant }
85129
}
86-
const user = await fetchMe(creds)
87-
if (!user) return undefined
88-
const identity: Identity = { user_id: user, tenant: creds.altimateInstanceName }
130+
const answer = await fetchMe(creds)
131+
if (answer.kind === "rejected") {
132+
const hit = await readCache()
133+
if (hit && hit.fingerprint === fp) await clear()
134+
return undefined
135+
}
136+
if (answer.kind !== "ok") return undefined
137+
const now = await loadCredential()
138+
if (!now || fingerprint(now) !== fp) return undefined
139+
const identity: Identity = { user_id: answer.uuid, tenant: creds.altimateInstanceName }
89140
try {
90141
await Filesystem.writeJson(cachePath(), { ...identity, fingerprint: fp } satisfies Cached, 0o600)
91142
} catch (err) {
@@ -107,7 +158,9 @@ export namespace TelemetryIdentity {
107158
}
108159
}
109160

110-
async function fetchMe(c: { altimateUrl: string; altimateInstanceName: string; altimateApiKey: string }) {
161+
type Answer = { kind: "ok"; uuid: string } | { kind: "rejected" } | { kind: "error" }
162+
163+
async function fetchMe(c: Credential): Promise<Answer> {
111164
const controller = new AbortController()
112165
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
113166
try {
@@ -120,9 +173,14 @@ export namespace TelemetryIdentity {
120173
},
121174
signal: controller.signal,
122175
})
123-
if (!res.ok) return undefined
176+
if (res.status === 401 || res.status === 403) return { kind: "rejected" }
177+
if (!res.ok) return { kind: "error" }
124178
const body = (await res.json()) as { uuid?: unknown }
125-
return typeof body?.uuid === "string" && UUID.test(body.uuid) ? body.uuid.toLowerCase() : undefined
179+
return typeof body?.uuid === "string" && UUID.test(body.uuid)
180+
? { kind: "ok", uuid: body.uuid.toLowerCase() }
181+
: { kind: "error" }
182+
} catch {
183+
return { kind: "error" }
126184
} finally {
127185
clearTimeout(timeout)
128186
}

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

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1859,6 +1859,11 @@ export namespace Telemetry {
18591859
// resolution started under credential A must not land after a sign-in installed B, nor after
18601860
// shutdown() cleared the state. shutdown() and every new resolution bump it.
18611861
let identityGeneration = 0
1862+
// altimate_change — stamp of the credential files when the current identity was resolved; a
1863+
// flush that sees a different stamp re-resolves, so a sign-in, sign-out or key change made on
1864+
// disk by any path (manual file edit, the TUI, another thread's auth flow) is picked up within
1865+
// one flush interval instead of at the next process start.
1866+
let identityStamp = ""
18621867
let machineId = ""
18631868
let sessionId = ""
18641869
let projectId = ""
@@ -1927,7 +1932,16 @@ export namespace Telemetry {
19271932
return { iKey, endpoint: `${base}v2/track` }
19281933
}
19291934

1930-
function toAppInsightsEnvelopes(events: Event[], cfg: AppInsightsConfig): object[] {
1935+
// altimate_change — `ids` lets a caller build envelopes for a machine and identity other than
1936+
// the module's current state (the opt-out marker runs while telemetry is disabled and must not
1937+
// touch the state an enabled init may be using concurrently).
1938+
function toAppInsightsEnvelopes(
1939+
events: Event[],
1940+
cfg: AppInsightsConfig,
1941+
ids?: { machineId: string; identity: TelemetryIdentity.Identity | undefined },
1942+
): object[] {
1943+
const mid = ids ? ids.machineId : machineId
1944+
const who = ids ? ids.identity : identity
19311945
// Process-level client, read live from the env flag (defaults to "cli") so events
19321946
// emitted before any prompt runs — startup, connection setup, standalone CLI
19331947
// subcommands — are labelled correctly instead of stuck at a hardcoded default.
@@ -1944,10 +1958,10 @@ export namespace Telemetry {
19441958
cli_version: InstallationVersion,
19451959
source: clientSource,
19461960
project_id: fields.project_id ?? projectId,
1947-
...(machineId && { machine_id: machineId }),
1961+
...(mid && { machine_id: mid }),
19481962
// altimate_change — the backend user uuid and tenant when signed in to Altimate, so a CLI
19491963
// row joins the PostHog person and the backend record for the same account.
1950-
...(identity && { user_id: identity.user_id, tenant: identity.tenant }),
1964+
...(who && { user_id: who.user_id, tenant: who.tenant }),
19511965
// altimate_change — groups every event from one process launch. The onboarding funnel
19521966
// spans the TUI main thread and the server worker, and most of it runs before any chat
19531967
// session exists, so `session_id` is empty for the first half and real for the second —
@@ -1975,7 +1989,7 @@ export namespace Telemetry {
19751989
// altimate_change start — the backend user uuid when signed in, else the machine id.
19761990
// Anonymous machines each keep a distinct identity (the random machine UUID, already a
19771991
// custom property) instead of sharing ai.user.id="". No email, hashed or not, is sent.
1978-
"ai.user.id": identity?.user_id || machineId || "",
1992+
"ai.user.id": who?.user_id || mid || "",
19791993
// altimate_change end
19801994
"ai.cloud.role": "altimate",
19811995
"ai.application.ver": InstallationVersion,
@@ -2121,15 +2135,20 @@ export namespace Telemetry {
21212135
// process (the browser login flow saves the credential while telemetry is already running).
21222136
function resolveIdentity(opts: { refresh?: boolean } = {}): Promise<void> {
21232137
const generation = ++identityGeneration
2138+
identityStamp = TelemetryIdentity.credentialStamp()
21242139
return TelemetryIdentity.resolve(opts)
21252140
.then((resolved) => {
21262141
if (generation === identityGeneration) identity = resolved
21272142
})
21282143
.catch(() => {})
21292144
}
21302145

2131-
/** Re-resolve who the machine is signed in as; clears it when no credential is stored. */
2146+
/** Re-resolve who the machine is signed in as; clears it when no credential is stored. Events
2147+
* already buffered are flushed under the identity they were tracked with first, and events
2148+
* tracked while the new answer is pending carry no account rather than the previous one. */
21322149
export async function refreshIdentity(): Promise<void> {
2150+
await flush()
2151+
identity = undefined
21332152
await resolveIdentity({ refresh: true })
21342153
}
21352154

@@ -2330,6 +2349,19 @@ export namespace Telemetry {
23302349
}
23312350

23322351
async function doFlush(timeoutMs: number) {
2352+
// altimate_change start — this batch is attributed to the identity in force when it is sent,
2353+
// captured before the credential check below can start replacing it; then notice a credential
2354+
// change on disk and re-resolve (cheap: two stats, and the cache answers unless the key changed).
2355+
const who = identity
2356+
const mid = machineId
2357+
if (enabled) {
2358+
const stamp = TelemetryIdentity.credentialStamp()
2359+
if (stamp !== identityStamp) {
2360+
identity = undefined
2361+
void resolveIdentity()
2362+
}
2363+
}
2364+
// altimate_change end
23332365
if (!enabled || buffer.length === 0 || !appInsights) return
23342366

23352367
const events = buffer.splice(0, buffer.length)
@@ -2353,7 +2385,7 @@ export namespace Telemetry {
23532385
const response = await fetch(appInsights.endpoint, {
23542386
method: "POST",
23552387
headers: { "Content-Type": "application/json" },
2356-
body: JSON.stringify(toAppInsightsEnvelopes(events, appInsights)),
2388+
body: JSON.stringify(toAppInsightsEnvelopes(events, appInsights, { machineId: mid, identity: who })),
23572389
signal: controller.signal,
23582390
})
23592391
if (!response.ok) {

‎packages/opencode/src/auth/index.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@ export const OAUTH_DUMMY_KEY = "opencode-oauth-dummy-key"
1212

1313
const file = path.join(Global.Path.data, "auth.json")
1414

15+
// altimate_change start — telemetry identity stats this file to notice a sign-in or sign-out made
16+
// through the TUI without parsing the store on every flush.
17+
export function filepath(): string {
18+
return file
19+
}
20+
// altimate_change end
21+
1522
const fail = (message: string) => (cause: unknown) => new AuthError({ message, cause })
1623

1724
export class Oauth extends Schema.Class<Oauth>("OAuth")({

0 commit comments

Comments
 (0)