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

Identify.ts

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