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

Identify.ts

77 lines2.3 KB

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 { anonymousIdPath } = yield* ServerConfig;
43​
44 const anonymousId = yield* fileSystem.readFileString(anonymousIdPath).pipe(
45 Effect.catch(() =>
46 Effect.gen(function* () {
47 const randomId = yield* Random.nextUUIDv4;
48 yield* fileSystem.writeFileString(anonymousIdPath, randomId);
49 return randomId;
50 }),
51 ),
52 );
53​
54 return anonymousId;
55});
56​
57/**
58 * getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
59 * 1. ~/.codex/auth.json tokens.account_id
60 * 2. ~/.t3/telemetry/anonymous-id
61 */
62export const getTelemetryIdentifier = Effect.gen(function* () {
63 const codexAccountId = yield* Effect.result(getCodexAccountId);
64 if (codexAccountId._tag === "Success") {
65 return yield* hash(codexAccountId.success);
66 }
67​
68 const anonymousId = yield* Effect.result(upsertAnonymousId);
69 if (anonymousId._tag === "Success") {
70 return yield* hash(anonymousId.success);
71 }
72​
73 return null;
74}).pipe(
75 Effect.tapError((error) => Effect.logWarning("Failed to get identifier", { cause: error })),
76 Effect.orElseSucceed(() => null),
77);