1+ import fs from "fs"
12import path from "path"
23import { rm } from "node:fs/promises"
34import { createHash } from "crypto"
45import { Global } from "../../global"
56import { Filesystem } from "../../util/filesystem"
7+ import { Auth } from "../../auth"
68import { AltimateApi } from "@/altimate/api/client"
79import { 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 */
2428export 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 - 9 a - f ] { 8 } - [ 0 - 9 a - f ] { 4 } - [ 0 - 9 a - f ] { 4 } - [ 0 - 9 a - f ] { 4 } - [ 0 - 9 a - 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 }
0 commit comments