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

Identify.ts

308 lines9.3 KB

1import * as Crypto from "effect/Crypto";
2import * as Effect from "effect/Effect";
3import * as Hex from "effect/encoding/Hex";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as PlatformError from "effect/PlatformError";
8import * as Schema from "effect/Schema";
9​
10import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
11import * as ServerConfig from "../config.ts";
12import * as HostProcess from "@t3tools/shared/HostProcess";
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​
258export const getTelemetryIdentifierForHome = Effect.fn("getTelemetryIdentifierForHome")(
259 function* (homeDirectory: string) {
260 const codexAccountId = yield* getCodexAccountId(homeDirectory).pipe(
261 Effect.catchTags({
262 TelemetryIdentityReadError: (error) =>
263 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
264 TelemetryIdentityDecodeError: (error) =>
265 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
266 }),
267 );
268 if (Option.isSome(codexAccountId)) {
269 return yield* hash("codex", codexAccountId.value);
270 }
271​
272 const claudeUserId = yield* getClaudeUserId(homeDirectory).pipe(
273 Effect.catchTags({
274 TelemetryIdentityReadError: (error) =>
275 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
276 TelemetryIdentityDecodeError: (error) =>
277 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
278 }),
279 );
280 if (Option.isSome(claudeUserId)) {
281 return yield* hash("claude", claudeUserId.value);
282 }
283​
284 const anonymousId = yield* upsertAnonymousId.pipe(
285 Effect.asSome,
286 Effect.catchTags({
287 TelemetryIdentityReadError: (error) =>
288 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
289 TelemetryAnonymousIdGenerationError: (error) =>
290 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
291 TelemetryAnonymousIdPersistenceError: (error) =>
292 logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
293 }),
294 );
295 if (Option.isSome(anonymousId)) {
296 return yield* hash("anonymous", anonymousId.value);
297 }
298​
299 return null;
300 },
301 Effect.tapError(logTelemetryIdentityError),
302 Effect.orElseSucceed(() => null),
303);
304​
305export const getTelemetryIdentifier = Effect.flatMap(
306 HostProcess.HomeDirectory,
307 getTelemetryIdentifierForHome,
308);