@@ -25,173 +25,173 @@ const log = Log.create({ service: "telemetry-identity" })
2525 * a process only hits the network when the credential changed. Every failure resolves to
2626 * ``undefined``: telemetry must never block or break on identity.
2727 */
28- export namespace TelemetryIdentity {
29- export type Identity = { user_id : string ; tenant : string }
28+ export type Identity = { user_id : string ; tenant : string }
3029
31- type Credential = { altimateUrl : string ; altimateInstanceName : string ; altimateApiKey : string }
32- type Cached = Identity & { fingerprint : string }
30+ type Credential = { altimateUrl : string ; altimateInstanceName : string ; altimateApiKey : string }
31+ type Cached = Identity & { fingerprint : string }
3332
34- const REQUEST_TIMEOUT_MS = 10_000
35- 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"
33+ const REQUEST_TIMEOUT_MS = 10_000
34+ 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
35+ const AUTH_STORE_KEY = "altimate-backend"
3736
38- export function cachePath ( ) : string {
39- return path . join ( Global . Path . home , ".altimate" , "telemetry-identity.json" )
40- }
37+ export function cachePath ( ) : string {
38+ return path . join ( Global . Path . home , ".altimate" , "telemetry-identity.json" )
39+ }
40+
41+ /** True when a credential is in use (file or auth store), whatever its validity. */
42+ export async function hasCredential ( ) : Promise < boolean > {
43+ return ( await loadCredential ( ) ) !== undefined
44+ }
4145
42- /** True when a credential is in use (file or auth store), whatever its validity. */
43- export async function hasCredential ( ) : Promise < boolean > {
44- return ( await loadCredential ( ) ) !== undefined
46+ /** The credential the Altimate provider would use, or undefined when signed out. */
47+ export async function loadCredential ( ) : Promise < Credential | undefined > {
48+ try {
49+ if ( await AltimateApi . isConfigured ( ) ) {
50+ const c = await AltimateApi . getCredentials ( )
51+ return {
52+ altimateUrl : c . altimateUrl ,
53+ altimateInstanceName : c . altimateInstanceName ,
54+ altimateApiKey : c . altimateApiKey ,
55+ }
56+ }
57+ const auth = await Auth . get ( AUTH_STORE_KEY )
58+ if ( auth ?. type === "api" ) {
59+ const parsed = AltimateApi . parseAltimateKey ( auth . key )
60+ // Same normalisation as getCredentials(): a trailing slash would yield "//users/me".
61+ return parsed ? { ...parsed , altimateUrl : parsed . altimateUrl . replace ( / \/ + $ / , "" ) } : undefined
62+ }
63+ return undefined
64+ } catch {
65+ return undefined
4566 }
67+ }
4668
47- /** The credential the Altimate provider would use, or undefined when signed out. */
48- export async function loadCredential ( ) : Promise < Credential | undefined > {
69+ /**
70+ * A cheap stamp of the two credential files (mtime and size), so a flush can notice that a
71+ * sign-in, sign-out or key change happened on disk, in this thread or another, without
72+ * reading or parsing anything.
73+ */
74+ export function credentialStamp ( ) : string {
75+ const stamp = ( p : string ) => {
4976 try {
50- if ( await AltimateApi . isConfigured ( ) ) {
51- const c = await AltimateApi . getCredentials ( )
52- return {
53- altimateUrl : c . altimateUrl ,
54- altimateInstanceName : c . altimateInstanceName ,
55- altimateApiKey : c . altimateApiKey ,
56- }
57- }
58- const auth = await Auth . get ( AUTH_STORE_KEY )
59- if ( auth ?. type === "api" ) {
60- const parsed = AltimateApi . parseAltimateKey ( auth . key )
61- // Same normalisation as getCredentials(): a trailing slash would yield "//users/me".
62- return parsed ? { ...parsed , altimateUrl : parsed . altimateUrl . replace ( / \/ + $ / , "" ) } : undefined
63- }
64- return undefined
77+ const s = fs . statSync ( p )
78+ return `${ s . mtimeMs } :${ s . size } `
6579 } catch {
66- return undefined
80+ return "absent"
6781 }
6882 }
83+ return `${ stamp ( AltimateApi . credentialsPath ( ) ) } |${ stamp ( Auth . filepath ( ) ) } `
84+ }
6985
70- /**
71- * A cheap stamp of the two credential files (mtime and size), so a flush can notice that a
72- * sign-in, sign-out or key change happened on disk, in this thread or another, without
73- * reading or parsing anything.
74- */
75- export function credentialStamp ( ) : string {
76- const stamp = ( p : string ) => {
77- try {
78- const s = fs . statSync ( p )
79- return `${ s . mtimeMs } :${ s . size } `
80- } catch {
81- return "absent"
82- }
83- }
84- return `${ stamp ( AltimateApi . credentialsPath ( ) ) } |${ stamp ( Auth . filepath ( ) ) } `
86+ function fingerprint ( c : Credential ) : string {
87+ return createHash ( "sha256" )
88+ . update ( `${ c . altimateUrl } \n${ c . altimateInstanceName } \n${ c . altimateApiKey } ` )
89+ . digest ( "hex" )
90+ . slice ( 0 , 16 )
91+ }
92+
93+ async function readCache ( ) : Promise < Cached | undefined > {
94+ try {
95+ const p = cachePath ( )
96+ if ( ! ( await Filesystem . exists ( p ) ) ) return undefined
97+ const raw = JSON . parse ( await Filesystem . readText ( p ) ) as Partial < Cached >
98+ if ( typeof raw . fingerprint !== "string" || typeof raw . user_id !== "string" || typeof raw . tenant !== "string" )
99+ return undefined
100+ if ( ! UUID . test ( raw . user_id ) ) return undefined
101+ return { fingerprint : raw . fingerprint , user_id : raw . user_id , tenant : raw . tenant }
102+ } catch {
103+ return undefined
85104 }
105+ }
86106
87- function fingerprint ( c : Credential ) : string {
88- return createHash ( "sha256" )
89- . update ( `${ c . altimateUrl } \n${ c . altimateInstanceName } \n${ c . altimateApiKey } ` )
90- . digest ( "hex" )
91- . slice ( 0 , 16 )
107+ /** The cached identity, if it belongs to the credential currently in use. No network. */
108+ export async function cached ( ) : Promise < Identity | undefined > {
109+ try {
110+ const creds = await loadCredential ( )
111+ if ( ! creds ) return undefined
112+ const hit = await readCache ( )
113+ if ( ! hit || hit . fingerprint !== fingerprint ( creds ) ) return undefined
114+ return { user_id : hit . user_id , tenant : hit . tenant }
115+ } catch {
116+ return undefined
92117 }
118+ }
93119
94- async function readCache ( ) : Promise < Cached | undefined > {
95- try {
96- const p = cachePath ( )
97- if ( ! ( await Filesystem . exists ( p ) ) ) return undefined
98- const raw = JSON . parse ( await Filesystem . readText ( p ) ) as Partial < Cached >
99- if ( typeof raw . fingerprint !== "string" || typeof raw . user_id !== "string" || typeof raw . tenant !== "string" )
100- return undefined
101- if ( ! UUID . test ( raw . user_id ) ) return undefined
102- return { fingerprint : raw . fingerprint , user_id : raw . user_id , tenant : raw . tenant }
103- } catch {
120+ /**
121+ * Resolve the signed-in user. Uses the cache when the credential has not changed; otherwise
122+ * asks the backend and caches the answer. ``refresh`` forces the request (after a sign-in).
123+ * A backend rejection (401 or 403) drops the cache for that credential; a transient failure
124+ * keeps it. The answer is written and returned only if the same credential is still in use.
125+ */
126+ export async function resolve ( opts : { refresh ?: boolean } = { } ) : Promise < Identity | undefined > {
127+ try {
128+ const creds = await loadCredential ( )
129+ if ( ! creds ) {
130+ await clear ( )
104131 return undefined
105132 }
106- }
107-
108- /** The cached identity, if it belongs to the credential currently in use. No network. */
109- export async function cached ( ) : Promise < Identity | undefined > {
110- try {
111- const creds = await loadCredential ( )
112- if ( ! creds ) return undefined
133+ const fp = fingerprint ( creds )
134+ if ( ! opts . refresh ) {
113135 const hit = await readCache ( )
114- if ( ! hit || hit . fingerprint !== fingerprint ( creds ) ) return undefined
115- return { user_id : hit . user_id , tenant : hit . tenant }
116- } catch {
136+ if ( hit && hit . fingerprint === fp ) return { user_id : hit . user_id , tenant : hit . tenant }
137+ }
138+ const answer = await fetchMe ( creds )
139+ if ( answer . kind === "rejected" ) {
140+ const hit = await readCache ( )
141+ if ( hit && hit . fingerprint === fp ) await clear ( )
117142 return undefined
118143 }
119- }
120-
121- /**
122- * Resolve the signed-in user. Uses the cache when the credential has not changed; otherwise
123- * asks the backend and caches the answer. ``refresh`` forces the request (after a sign-in).
124- * A backend rejection (401 or 403) drops the cache for that credential; a transient failure
125- * keeps it. The answer is written and returned only if the same credential is still in use.
126- */
127- export async function resolve ( opts : { refresh ?: boolean } = { } ) : Promise < Identity | undefined > {
144+ if ( answer . kind !== "ok" ) return undefined
145+ const now = await loadCredential ( )
146+ if ( ! now || fingerprint ( now ) !== fp ) return undefined
147+ const identity : Identity = { user_id : answer . uuid , tenant : creds . altimateInstanceName }
128148 try {
129- const creds = await loadCredential ( )
130- if ( ! creds ) {
131- await clear ( )
132- return undefined
133- }
134- const fp = fingerprint ( creds )
135- if ( ! opts . refresh ) {
136- const hit = await readCache ( )
137- if ( hit && hit . fingerprint === fp ) return { user_id : hit . user_id , tenant : hit . tenant }
138- }
139- const answer = await fetchMe ( creds )
140- if ( answer . kind === "rejected" ) {
141- const hit = await readCache ( )
142- if ( hit && hit . fingerprint === fp ) await clear ( )
143- return undefined
144- }
145- if ( answer . kind !== "ok" ) return undefined
146- const now = await loadCredential ( )
147- if ( ! now || fingerprint ( now ) !== fp ) return undefined
148- const identity : Identity = { user_id : answer . uuid , tenant : creds . altimateInstanceName }
149- try {
150- await Filesystem . writeJson ( cachePath ( ) , { ...identity , fingerprint : fp } satisfies Cached , 0o600 )
151- } catch ( err ) {
152- log . warn ( "telemetry identity cache not written" , { err : String ( err ) } )
153- }
154- return identity
149+ await Filesystem . writeJson ( cachePath ( ) , { ...identity , fingerprint : fp } satisfies Cached , 0o600 )
155150 } catch ( err ) {
156- log . warn ( "telemetry identity unresolved" , { err : String ( err ) } )
157- return undefined
151+ log . warn ( "telemetry identity cache not written" , { err : String ( err ) } )
158152 }
153+ return identity
154+ } catch ( err ) {
155+ log . warn ( "telemetry identity unresolved" , { err : String ( err ) } )
156+ return undefined
159157 }
158+ }
160159
161- /** Forget the cached identity (sign-out). */
162- export async function clear ( ) : Promise < void > {
163- try {
164- await rm ( cachePath ( ) , { force : true } )
165- } catch {
166- // nothing to forget
167- }
160+ /** Forget the cached identity (sign-out). */
161+ export async function clear ( ) : Promise < void > {
162+ try {
163+ await rm ( cachePath ( ) , { force : true } )
164+ } catch {
165+ // nothing to forget
168166 }
167+ }
169168
170- type Answer = { kind : "ok" ; uuid : string } | { kind : "rejected" } | { kind : "error" }
169+ type Answer = { kind : "ok" ; uuid : string } | { kind : "rejected" } | { kind : "error" }
171170
172- async function fetchMe ( c : Credential ) : Promise < Answer > {
173- const controller = new AbortController ( )
174- const timeout = setTimeout ( ( ) => controller . abort ( ) , REQUEST_TIMEOUT_MS )
175- try {
176- const res = await fetch ( `${ c . altimateUrl } /users/me` , {
177- method : "GET" ,
178- headers : {
179- Authorization : `Bearer ${ c . altimateApiKey } ` ,
180- "x-tenant" : c . altimateInstanceName ,
181- ...AltimateApi . clientHeaders ( ) ,
182- } ,
183- signal : controller . signal ,
184- } )
185- if ( res . status === 401 || res . status === 403 ) return { kind : "rejected" }
186- if ( ! res . ok ) return { kind : "error" }
187- const body = ( await res . json ( ) ) as { uuid ?: unknown }
188- return typeof body ?. uuid === "string" && UUID . test ( body . uuid )
189- ? { kind : "ok" , uuid : body . uuid . toLowerCase ( ) }
190- : { kind : "error" }
191- } catch {
192- return { kind : "error" }
193- } finally {
194- clearTimeout ( timeout )
195- }
171+ async function fetchMe ( c : Credential ) : Promise < Answer > {
172+ const controller = new AbortController ( )
173+ const timeout = setTimeout ( ( ) => controller . abort ( ) , REQUEST_TIMEOUT_MS )
174+ try {
175+ const res = await fetch ( `${ c . altimateUrl } /users/me` , {
176+ method : "GET" ,
177+ headers : {
178+ Authorization : `Bearer ${ c . altimateApiKey } ` ,
179+ "x-tenant" : c . altimateInstanceName ,
180+ ...AltimateApi . clientHeaders ( ) ,
181+ } ,
182+ signal : controller . signal ,
183+ } )
184+ if ( res . status === 401 || res . status === 403 ) return { kind : "rejected" }
185+ if ( ! res . ok ) return { kind : "error" }
186+ const body = ( await res . json ( ) ) as { uuid ?: unknown }
187+ return typeof body ?. uuid === "string" && UUID . test ( body . uuid )
188+ ? { kind : "ok" , uuid : body . uuid . toLowerCase ( ) }
189+ : { kind : "error" }
190+ } catch {
191+ return { kind : "error" }
192+ } finally {
193+ clearTimeout ( timeout )
196194 }
197195}
196+
197+ export * as TelemetryIdentity from "./identity"
0 commit comments