Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Logger from "effect/Logger";
8import * as Path from "effect/Path";
9import * as References from "effect/References";
10
11import * as ServerConfig from "../config.ts";
12import * as Identify from "./Identify.ts";
13
14interface CapturedLog {
15 readonly message: unknown;
16 readonly annotations: Readonly<Record<string, unknown>>;
17}
18
19const sha256 = (value: string) =>
20 NodeCrypto.createHash("sha256").update(value, "utf8").digest("hex");
21
22const makeCaptureLogger = (logs: CapturedLog[]) =>
23 Logger.make(({ fiber, message }) => {
24 logs.push({
25 message,
26 annotations: fiber.getRef(References.CurrentLogAnnotations),
27 });
28 });
29
30const findIdentityLog = (
31 logs: ReadonlyArray<CapturedLog>,
32 source: Identify.TelemetryIdentitySource,
33 errorTag: string,
34) => logs.find((log) => log.annotations.source === source && log.annotations.errorTag === errorTag);
35
36it.layer(NodeServices.layer)("telemetry identity", (it) => {
37 it.effect("uses the persisted anonymous id when provider identities are absent", () =>
38 Effect.gen(function* () {
39 const config = yield* ServerConfig.ServerConfig;
40 const fileSystem = yield* FileSystem.FileSystem;
41 const path = yield* Path.Path;
42 const anonymousId = "persisted-anonymous-id";
43
44 yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
45
46 const identifier = yield* Identify.getTelemetryIdentifierForHome(
47 path.join(config.baseDir, "home"),
48 );
49
50 assert.equal(identifier, sha256(anonymousId));
51 }).pipe(
52 Effect.provide(
53 ServerConfig.layerTest(process.cwd(), {
54 prefix: "t3-telemetry-identify-anonymous-",
55 }),
56 ),
57 ),
58 );
59
60 it.effect.each([
61 {
62 login: "an API key",
63 secret: "sk-private-openai-api-key",
64 authJson: (secret: string) => `{"auth_mode":"apikey","OPENAI_API_KEY":"${secret}"}`,
65 },
66 {
67 login: "an agent identity",
68 secret: "private-agent-identity-jwt",
69 authJson: (secret: string) =>
70 `{"auth_mode":"agentIdentity","OPENAI_API_KEY":null,"agent_identity":"${secret}"}`,
71 },
72 {
73 login: "a personal access token",
74 secret: "private-personal-access-token",
75 authJson: (secret: string) => `{"OPENAI_API_KEY":null,"personal_access_token":"${secret}"}`,
76 },
77 ])("falls back quietly when Codex authenticates with $login", ({ secret, authJson }) => {
78 const logs: CapturedLog[] = [];
79 const logger = makeCaptureLogger(logs);
80
81 return Effect.gen(function* () {
82 const config = yield* ServerConfig.ServerConfig;
83 const fileSystem = yield* FileSystem.FileSystem;
84 const path = yield* Path.Path;
85 const homeDirectory = path.join(config.baseDir, "home");
86 const codexAuthPath = path.join(homeDirectory, ".codex", "auth.json");
87 const anonymousId = "tokenless-codex-anonymous-id";
88
89 yield* fileSystem.makeDirectory(path.dirname(codexAuthPath), { recursive: true });
90 yield* fileSystem.writeFileString(codexAuthPath, authJson(secret));
91 yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
92
93 const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
94
95 assert.equal(identifier, sha256(anonymousId));
96 assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError"));
97 assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityReadError"));
98 const allLogs = logs
99 .map((log) =>
100 [String(log.message), ...Object.values(log.annotations).map(String)].join("\n"),
101 )
102 .join("\n");
103 assert.notInclude(allLogs, secret);
104 }).pipe(
105 Effect.provide(
106 Layer.merge(
107 ServerConfig.layerTest(process.cwd(), {
108 prefix: "t3-telemetry-identify-tokenless-",
109 }),
110 Logger.layer([logger], { mergeWithExisting: false }),
111 ),
112 ),
113 );
114 });
115
116 it.effect("logs structured decode context and falls back from malformed Codex auth", () => {
117 const logs: CapturedLog[] = [];
118 const logger = makeCaptureLogger(logs);
119
120 return Effect.gen(function* () {
121 const config = yield* ServerConfig.ServerConfig;
122 const fileSystem = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const homeDirectory = path.join(config.baseDir, "home");
125 const codexAuthPath = path.join(homeDirectory, ".codex", "auth.json");
126 const anonymousId = "decode-fallback-anonymous-id";
127 const privateAccessToken = "private-codex-access-token";
128
129 yield* fileSystem.makeDirectory(path.dirname(codexAuthPath), { recursive: true });
130 yield* fileSystem.writeFileString(
131 codexAuthPath,
132 `{"tokens":{"access_token":"${privateAccessToken}"}}`,
133 );
134 yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
135
136 const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
137
138 assert.equal(identifier, sha256(anonymousId));
139 const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError");
140 assert.isDefined(decodeLog);
141 assert.equal(
142 decodeLog?.message,
143 `Failed to decode codex telemetry identity at '${codexAuthPath}'.`,
144 );
145
146 assert.equal(decodeLog?.annotations.filePath, codexAuthPath);
147 assert.equal(decodeLog?.annotations.causeKind, "schema");
148 assert.notProperty(decodeLog?.annotations ?? {}, "cause");
149 const errorStack = decodeLog?.annotations.errorStack;
150 assert.isString(errorStack);
151 assert.include(errorStack, "Failed to decode codex telemetry identity");
152 const annotations = Object.values(decodeLog?.annotations ?? {})
153 .map(String)
154 .join("\n");
155 assert.notInclude(annotations, privateAccessToken);
156 }).pipe(
157 Effect.provide(
158 Layer.merge(
159 ServerConfig.layerTest(process.cwd(), {
160 prefix: "t3-telemetry-identify-decode-",
161 }),
162 Logger.layer([logger], { mergeWithExisting: false }),
163 ),
164 ),
165 );
166 });
167
168 it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => {
169 const logs: CapturedLog[] = [];
170 const logger = makeCaptureLogger(logs);
171
172 return Effect.gen(function* () {
173 const config = yield* ServerConfig.ServerConfig;
174 const fileSystem = yield* FileSystem.FileSystem;
175 const path = yield* Path.Path;
176 const homeDirectory = path.join(config.baseDir, "home");
177
178 yield* fileSystem.makeDirectory(config.anonymousIdPath);
179
180 const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
181
182 assert.isNull(identifier);
183 assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []);
184
185 const readLog = findIdentityLog(logs, "anonymous", "TelemetryIdentityReadError");
186 assert.isDefined(readLog);
187 assert.equal(readLog?.annotations.filePath, config.anonymousIdPath);
188 assert.equal(readLog?.annotations.causeKind, "platform");
189 assert.notEqual(readLog?.annotations.platformReason, "NotFound");
190 assert.notProperty(readLog?.annotations ?? {}, "cause");
191 const errorStack = readLog?.annotations.errorStack;
192 assert.isString(errorStack);
193 assert.include(errorStack, "Failed to read anonymous telemetry identity");
194 assert.isUndefined(
195 findIdentityLog(logs, "anonymous", "TelemetryAnonymousIdPersistenceError"),
196 );
197 }).pipe(
198 Effect.provide(
199 Layer.merge(
200 ServerConfig.layerTest(process.cwd(), {
201 prefix: "t3-telemetry-identify-read-",
202 }),
203 Logger.layer([logger], { mergeWithExisting: false }),
204 ),
205 ),
206 );
207 });
208});