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

Identify.ts

316 lines9.7 KB

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