Open History to see the last commit
1import { Effect, FileSystem, Path, Random, Schema } from "effect";
2import * as Crypto from "node:crypto";
3import { homedir } from "node:os";
4import { ServerConfig } from "../config";
5
6const CodexAuthJsonSchema = Schema.Struct({
7 tokens: Schema.Struct({
8 account_id: Schema.String,
9 }),
10});
11
12class IdentifyUserError extends Schema.TaggedErrorClass<IdentifyUserError>()("IdentifyUserError", {
13 message: Schema.String,
14 cause: Schema.optional(Schema.Defect),
15}) {}
16
17const hash = (value: string) =>
18 Effect.try({
19 try: () => Crypto.createHash("sha256").update(value).digest("hex"),
20 catch: (error) =>
21 new IdentifyUserError({
22 message: "Failed to hash identifier",
23 cause: error,
24 }),
25 });
26
27const getCodexAccountId = Effect.gen(function* () {
28 const fileSystem = yield* FileSystem.FileSystem;
29 const path = yield* Path.Path;
30
31 const authJsonPath = path.join(homedir(), ".codex", "auth.json");
32 const authJson = yield* Effect.flatMap(
33 fileSystem.readFileString(authJsonPath),
34 Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema)),
35 );
36
37 return authJson.tokens.account_id;
38});
39
40const upsertAnonymousId = Effect.gen(function* () {
41 const fileSystem = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43 const serverConfig = yield* ServerConfig;
44
45 const anonymousIdPath = path.join(serverConfig.stateDir, "anonymous-id");
46 const anonymousId = yield* fileSystem.readFileString(anonymousIdPath).pipe(
47 Effect.catch(() =>
48 Effect.gen(function* () {
49 const randomId = yield* Random.nextUUIDv4;
50 yield* fileSystem.writeFileString(anonymousIdPath, randomId);
51 return randomId;
52 }),
53 ),
54 );
55
56 return anonymousId;
57});
58
59/**
60 * getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
61 * 1. ~/.codex/auth.json tokens.account_id
62 * 2. ~/.t3/telemetry/anonymous-id
63 */
64export const getTelemetryIdentifier = Effect.gen(function* () {
65 const codexAccountId = yield* Effect.result(getCodexAccountId);
66 if (codexAccountId._tag === "Success") {
67 return yield* hash(codexAccountId.success);
68 }
69
70 const anonymousId = yield* Effect.result(upsertAnonymousId);
71 if (anonymousId._tag === "Success") {
72 return yield* hash(anonymousId.success);
73 }
74
75 return null;
76}).pipe(
77 Effect.tapError((error) => Effect.logWarning("Failed to get identifier", { cause: error })),
78 Effect.orElseSucceed(() => null),
79);