Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Identify.ts

315 lines9.6 KB

1import * as NodeOS from "node:os";
2import * as Crypto from "effect/Crypto";
3import * as Effect from "effect/Effect";
4import * as Encoding from "effect/Encoding";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as PlatformError from "effect/PlatformError";
9import * as Schema from "effect/Schema";
10​
11import * as ServerConfig from "../config.ts";
12​
13/**
14 * Codex writes `tokens` only for ChatGPT logins and omits the key for API-key,
15 * agent-identity, and personal-access-token logins, so its absence is a
16 * supported install and not a malformed file.
17 */
18const CodexAuthJsonSchema = Schema.Struct({
19 tokens: Schema.optionalKey(
20 Schema.Struct({
21 account_id: Schema.String,
22 }),
23 ),
24});
25​
26const ClaudeJsonSchema = Schema.Struct({
27 userID: Schema.String,
28});
29​
30export const TelemetryIdentitySource = Schema.Literals(["codex", "claude", "anonymous"]);
31export type TelemetryIdentitySource = typeof TelemetryIdentitySource.Type;
32​
33class TelemetryIdentityReadError extends Schema.TaggedError<TelemetryIdentityReadError>()(
34 "TelemetryIdentityReadError",
35 {
36 source: TelemetryIdentitySource,
37 filePath: Schema.String,
38 cause: Schema.Defect(),
39 },
40) {
41 override get message(): string {
42 return `Failed to read ${this.source} telemetry identity at '${this.filePath}'.`;
43 }
45​
46class TelemetryIdentityDecodeError extends Schema.TaggedError<TelemetryIdentityDecodeError>()(
47 "TelemetryIdentityDecodeError",
48 {
49 source: Schema.Literals(["codex", "claude"]),
50 filePath: Schema.String,
51 cause: Schema.Defect(),
52 },
53) {
54 override get message(): string {
55 return `Failed to decode ${this.source} telemetry identity at '${this.filePath}'.`;
56 }
58​
59export class TelemetryAnonymousIdGenerationError extends Schema.TaggedError<TelemetryAnonymousIdGenerationError>()(
60 "TelemetryAnonymousIdGenerationError",
61 {
62 source: Schema.Literal("anonymous"),
63 filePath: Schema.String,
64 cause: Schema.Defect(),
65 },
66) {
67 override get message(): string {
68 return `Failed to generate anonymous telemetry identity for '${this.filePath}'.`;
69 }
71​
72export class TelemetryAnonymousIdPersistenceError extends Schema.TaggedError<TelemetryAnonymousIdPersistenceError>()(
73 "TelemetryAnonymousIdPersistenceError",
74 {
75 source: Schema.Literal("anonymous"),
76 filePath: Schema.String,
77 cause: Schema.Defect(),
78 },
79) {
80 override get message(): string {
81 return `Failed to persist anonymous telemetry identity at '${this.filePath}'.`;
82 }
84​
85export class TelemetryIdentityHashError extends Schema.TaggedError<TelemetryIdentityHashError>()(
86 "TelemetryIdentityHashError",
87 {
88 source: TelemetryIdentitySource,
89 algorithm: Schema.Literal("SHA-256"),
90 cause: Schema.Defect(),
91 },
92) {
93 override get message(): string {
94 return `Failed to hash ${this.source} telemetry identity with ${this.algorithm}.`;
95 }
97​
98type TelemetryIdentityError =
99 | TelemetryIdentityReadError
100 | TelemetryIdentityDecodeError
101 | TelemetryAnonymousIdGenerationError
102 | TelemetryAnonymousIdPersistenceError
103 | TelemetryIdentityHashError;
104​
105const decodeCodexAuthJson = Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema));
106const decodeClaudeJson = Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema));
107​
108function isNotFoundError(error: PlatformError.PlatformError): boolean {
109 return error.reason._tag === "NotFound";
111​
112const getTelemetryIdentityCauseAnnotations = (cause: unknown) => {
113 if (cause instanceof PlatformError.PlatformError) {
114 return {
115 causeKind: "platform",
116 platformReason: cause.reason._tag,
117 };
118 }
119 if (cause instanceof Schema.SchemaError) {
120 return { causeKind: "schema" };
121 }
122 return { causeKind: "other" };
123};
124​
125const logTelemetryIdentityError = (error: TelemetryIdentityError) =>
126 Effect.logWarning(error.message).pipe(
127 Effect.annotateLogs({
128 errorTag: error._tag,
129 source: error.source,
130 ...("filePath" in error ? { filePath: error.filePath } : {}),
131 ...getTelemetryIdentityCauseAnnotations(error.cause),
132 ...(error.stack === undefined ? {} : { errorStack: error.stack }),
133 }),
134 );
135​
136const readIdentityFile = (
137 fileSystem: FileSystem.FileSystem,
138 source: TelemetryIdentitySource,
139 filePath: string,
140) =>
141 fileSystem.readFileString(filePath).pipe(
142 Effect.asSome,
143 Effect.catchTags({
144 PlatformError: (cause) =>
145 isNotFoundError(cause)
146 ? Effect.succeed(Option.none<string>())
147 : Effect.fail(
148 new TelemetryIdentityReadError({
149 source,
150 filePath,
151 cause,
152 }),
153 ),
154 }),
155 );
156​
157const hash = (source: TelemetryIdentitySource, value: string) =>
158 Crypto.Crypto.pipe(
159 Effect.flatMap((crypto) => crypto.digest("SHA-256", new TextEncoder().encode(value))),
160 Effect.map(Encoding.encodeHex),
161 Effect.mapError(
162 (cause) =>
163 new TelemetryIdentityHashError({
164 source,
165 algorithm: "SHA-256",
166 cause,
167 }),
168 ),
169 );
170​
171const getCodexAccountId = Effect.fn("TelemetryIdentity.getCodexAccountId")(function* (
172 homeDirectory: string,
173) {
174 const fileSystem = yield* FileSystem.FileSystem;
175 const path = yield* Path.Path;
176​
177 const authJsonPath = path.join(homeDirectory, ".codex", "auth.json");
178 const encoded = yield* readIdentityFile(fileSystem, "codex", authJsonPath);
179 if (Option.isNone(encoded)) {
180 return Option.none<string>();
181 }
182 const authJson = yield* decodeCodexAuthJson(encoded.value).pipe(
183 Effect.mapError(
184 (cause) =>
185 new TelemetryIdentityDecodeError({
186 source: "codex",
187 filePath: authJsonPath,
188 cause,
189 }),
190 ),
191 );
192​
193 return authJson.tokens === undefined
194 ? Option.none<string>()
195 : Option.some(authJson.tokens.account_id);
196});
197​
198const getClaudeUserId = Effect.fn("TelemetryIdentity.getClaudeUserId")(function* (
199 homeDirectory: string,
200) {
201 const fileSystem = yield* FileSystem.FileSystem;
202 const path = yield* Path.Path;
203​
204 const claudeJsonPath = path.join(homeDirectory, ".claude.json");
205 const encoded = yield* readIdentityFile(fileSystem, "claude", claudeJsonPath);
206 if (Option.isNone(encoded)) {
207 return Option.none<string>();
208 }
209 const claudeJson = yield* decodeClaudeJson(encoded.value).pipe(
210 Effect.mapError(
211 (cause) =>
212 new TelemetryIdentityDecodeError({
213 source: "claude",
214 filePath: claudeJsonPath,
215 cause,
216 }),
217 ),
218 );
219​
220 return Option.some(claudeJson.userID);
221});
222​
223const upsertAnonymousId = Effect.gen(function* () {
224 const fileSystem = yield* FileSystem.FileSystem;
225 const { anonymousIdPath } = yield* ServerConfig.ServerConfig;
226​
227 const existing = yield* readIdentityFile(fileSystem, "anonymous", anonymousIdPath);
228 if (Option.isSome(existing)) {
229 return existing.value;
230 }
231​
232 const anonymousId = yield* Crypto.Crypto.pipe(
233 Effect.flatMap((crypto) => crypto.randomUUIDv4),
234 Effect.mapError(
235 (cause) =>
236 new TelemetryAnonymousIdGenerationError({
237 source: "anonymous",
238 filePath: anonymousIdPath,
239 cause,
240 }),
241 ),
242 );
243 yield* fileSystem.writeFileString(anonymousIdPath, anonymousId).pipe(
244 Effect.mapError(
245 (cause) =>
246 new TelemetryAnonymousIdPersistenceError({
247 source: "anonymous",
248 filePath: anonymousIdPath,
249 cause,
250 }),
251 ),
252 );
253​
254 return anonymousId;
255});
256​
257/**
258 * getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
259 * 1. ~/.codex/auth.json tokens.account_id
260 * 2. ~/.claude.json userID
261 * 3. ~/.t3/telemetry/anonymous-id
262 *
263 * A missing file or an API-key-only Codex auth.json falls through quietly. Only
264 * unreadable or malformed files warn.
265 */
266export const getTelemetryIdentifierForHome = Effect.fn("getTelemetryIdentifierForHome")(
267 function* (homeDirectory: string) {
268 const codexAccountId = yield* getCodexAccountId(homeDirectory).pipe(
269 Effect.catchTags({
270 TelemetryIdentityReadError: (error) =>
271 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
272 TelemetryIdentityDecodeError: (error) =>
273 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
274 }),
275 );
276 if (Option.isSome(codexAccountId)) {
277 return yield* hash("codex", codexAccountId.value);
278 }
279​
280 const claudeUserId = yield* getClaudeUserId(homeDirectory).pipe(
281 Effect.catchTags({
282 TelemetryIdentityReadError: (error) =>
283 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
284 TelemetryIdentityDecodeError: (error) =>
285 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
286 }),
287 );
288 if (Option.isSome(claudeUserId)) {
289 return yield* hash("claude", claudeUserId.value);
290 }
291​
292 const anonymousId = yield* upsertAnonymousId.pipe(
293 Effect.asSome,
294 Effect.catchTags({
295 TelemetryIdentityReadError: (error) =>
296 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
297 TelemetryAnonymousIdGenerationError: (error) =>
298 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
299 TelemetryAnonymousIdPersistenceError: (error) =>
300 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
301 }),
302 );
303 if (Option.isSome(anonymousId)) {
304 return yield* hash("anonymous", anonymousId.value);
305 }
306​
307 return null;
308 },
309 Effect.tapError(logTelemetryIdentityError),
310 Effect.orElseSucceed(() => null),
311);
312​
313export const getTelemetryIdentifier = Effect.suspend(() =>
314 getTelemetryIdentifierForHome(NodeOS.homedir()),
315);