Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Crypto from "effect/Crypto";
4import * as Effect from "effect/Effect";
5import * as Hex from "effect/encoding/Hex";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Logger from "effect/Logger";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as References from "effect/References";
12
13import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
14import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts";
15import * as ServerConfig from "../config.ts";
16import * as Identify from "./Identify.ts";
17
18interface CapturedLog {
19 readonly message: unknown;
20 readonly annotations: Readonly<Record<string, unknown>>;
21}
22
23const sha256 = Effect.fn("test.sha256")(function* (value: string) {
24 const crypto = yield* Crypto.Crypto;
25 return Hex.encode(
26 yield* crypto.digest("SHA-256", new TextEncoder().encode(value)).pipe(Effect.orDie),
27 );
28});
29
30const makeCaptureLogger = (logs: CapturedLog[]) =>
31 Logger.make(({ fiber, message }) => {
32 logs.push({
33 message,
34 annotations: fiber.getRef(References.CurrentLogAnnotations),
35 });
36 });
37
38const findIdentityLog = (
39 logs: ReadonlyArray<CapturedLog>,
40 source: Identify.TelemetryIdentitySource,
41 errorTag: string,
42) => logs.find((log) => log.annotations.source === source && log.annotations.errorTag === errorTag);
43
44const unsignedJwt = (claims: Readonly<Record<string, unknown>>) =>
45 ["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "signature"].join(".");
46
47const layerIdentity = (prefix: string, logs?: CapturedLog[]) =>
48 Layer.provideMerge(
49 ServerSecretStore.layer,
50 ServerConfig.layerTest(process.cwd(), { prefix }),
51 ).pipe(
52 Layer.merge(
53 logs === undefined
54 ? Layer.empty
55 : Logger.layer([makeCaptureLogger(logs)], { mergeWithExisting: false }),
56 ),
57 );
58
59const writeHomeFile = Effect.fn("test.writeHomeFile")(function* (
60 homeDirectory: string,
61 relativePath: string,
62 contents: string,
63) {
64 const fileSystem = yield* FileSystem.FileSystem;
65 const path = yield* Path.Path;
66 const filePath = path.join(homeDirectory, relativePath);
67 yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });
68 yield* fileSystem.writeFileString(filePath, contents);
69 return filePath;
70});
71
72it.layer(NodeServices.layer)("telemetry identity", (it) => {
73 it.effect("keeps the old distinct_id rule and a fixed install id as logins change", () =>
74 Effect.gen(function* () {
75 const config = yield* ServerConfig.ServerConfig;
76 const fileSystem = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 const homeDirectory = path.join(config.baseDir, "home");
79 const anonymousId = "persisted-anonymous-id";
80 yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
81 const installId = yield* sha256(anonymousId);
82 const identity = () => Identify.getTelemetryIdentityForHome(homeDirectory);
83
84 assert.deepEqual(yield* identity(), { distinctId: installId, installId });
85
86 yield* writeHomeFile(homeDirectory, ".claude.json", `{"userID":"claude-machine"}`);
87 assert.deepEqual(yield* identity(), {
88 distinctId: yield* sha256("claude-machine"),
89 installId,
90 });
91
92 yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"auth_mode":"apikey"}`);
93 assert.equal((yield* identity()).distinctId, yield* sha256("claude-machine"));
94
95 yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"tokens":{"account_id":"ws-1"}}`);
96 assert.deepEqual(yield* identity(), { distinctId: yield* sha256("ws-1"), installId });
97 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-install-"))),
98 );
99
100 it.effect("leaves no torn anonymous id behind when its write fails midway", () =>
101 Effect.gen(function* () {
102 const config = yield* ServerConfig.ServerConfig;
103 const fileSystem = yield* FileSystem.FileSystem;
104 const path = yield* Path.Path;
105 const tornWrites = FileSystem.FileSystem.of({
106 ...fileSystem,
107 writeFileString: (filePath, data, options) =>
108 fileSystem
109 .writeFileString(filePath, data.slice(0, Math.floor(data.length / 2)), options)
110 .pipe(
111 Effect.andThen(
112 Effect.fail(
113 PlatformError.systemError({
114 _tag: "WriteZero",
115 module: "FileSystem",
116 method: "writeFileString",
117 pathOrDescriptor: filePath,
118 }),
119 ),
120 ),
121 ),
122 });
123
124 const identity = yield* Identify.getTelemetryIdentityForHome(
125 path.join(config.baseDir, "home"),
126 ).pipe(Effect.provideService(FileSystem.FileSystem, tornWrites));
127
128 assert.deepEqual(identity, { distinctId: null, installId: null });
129 assert.isFalse(yield* fileSystem.exists(config.anonymousIdPath));
130 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-torn-"))),
131 );
132
133 it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => {
134 const logs: CapturedLog[] = [];
135
136 return Effect.gen(function* () {
137 const config = yield* ServerConfig.ServerConfig;
138 const fileSystem = yield* FileSystem.FileSystem;
139 const path = yield* Path.Path;
140 yield* fileSystem.makeDirectory(config.anonymousIdPath);
141
142 const identity = yield* Identify.getTelemetryIdentityForHome(
143 path.join(config.baseDir, "home"),
144 );
145 assert.deepEqual(identity, { distinctId: null, installId: null });
146 assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []);
147
148 const readLog = findIdentityLog(logs, "anonymous", "TelemetryIdentityReadError");
149 assert.equal(readLog?.annotations.filePath, config.anonymousIdPath);
150 assert.notEqual(readLog?.annotations.platformReason, "NotFound");
151 assert.notProperty(readLog?.annotations ?? {}, "cause");
152 assert.isUndefined(
153 findIdentityLog(logs, "anonymous", "TelemetryAnonymousIdPersistenceError"),
154 );
155 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-read-", logs)));
156 });
157
158 it.effect("reads the Connect account and each provider account as owners", () =>
159 Effect.gen(function* () {
160 const config = yield* ServerConfig.ServerConfig;
161 const secrets = yield* ServerSecretStore.ServerSecretStore;
162 const path = yield* Path.Path;
163 const homeDirectory = path.join(config.baseDir, "home");
164 yield* secrets.set(CLOUD_LINKED_USER_ID, new TextEncoder().encode("user_connect"));
165 yield* writeHomeFile(
166 homeDirectory,
167 ".codex/auth.json",
168 JSON.stringify({
169 tokens: {
170 account_id: "team-workspace",
171 id_token: unsignedJwt({
172 sub: "google-oauth2|login-method",
173 "https://api.openai.com/auth": { user_id: "user-openai-person" },
174 }),
175 },
176 }),
177 );
178 yield* writeHomeFile(
179 homeDirectory,
180 ".claude.json",
181 JSON.stringify({
182 userID: "claude-machine",
183 oauthAccount: { accountUuid: "claude-person" },
184 }),
185 );
186
187 const owners = yield* Identify.getServerOwnersForHome(homeDirectory);
188
189 assert.deepEqual(owners, [
190 { source: "connect", ownerId: yield* sha256("user_connect") },
191 { source: "openai", ownerId: yield* sha256("user-openai-person") },
192 { source: "claude", ownerId: yield* sha256("claude-person") },
193 ]);
194 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-owners-"))),
195 );
196
197 it.effect.each([
198 {
199 login: "an API key",
200 secret: "sk-private-openai-api-key",
201 authJson: (secret: string) => `{"auth_mode":"apikey","OPENAI_API_KEY":"${secret}"}`,
202 },
203 {
204 login: "an agent identity",
205 secret: "private-agent-identity-jwt",
206 authJson: (secret: string) =>
207 `{"auth_mode":"agentIdentity","OPENAI_API_KEY":null,"agent_identity":"${secret}"}`,
208 },
209 {
210 login: "a personal access token",
211 secret: "private-personal-access-token",
212 authJson: (secret: string) => `{"OPENAI_API_KEY":null,"personal_access_token":"${secret}"}`,
213 },
214 ])(
215 "adds no owner and logs nothing when Codex authenticates with $login",
216 ({ secret, authJson }) => {
217 const logs: CapturedLog[] = [];
218
219 return Effect.gen(function* () {
220 const config = yield* ServerConfig.ServerConfig;
221 const path = yield* Path.Path;
222 const homeDirectory = path.join(config.baseDir, "home");
223 yield* writeHomeFile(homeDirectory, ".codex/auth.json", authJson(secret));
224
225 assert.deepEqual(yield* Identify.getServerOwnersForHome(homeDirectory), []);
226 assert.deepEqual(logs, []);
227 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-tokenless-", logs)));
228 },
229 );
230
231 it.effect(
232 "warns about malformed Codex auth without its tokens and keeps the other owners",
233 () => {
234 const logs: CapturedLog[] = [];
235
236 return Effect.gen(function* () {
237 const config = yield* ServerConfig.ServerConfig;
238 const path = yield* Path.Path;
239 const homeDirectory = path.join(config.baseDir, "home");
240 const privateAccessToken = "private-codex-access-token";
241 const codexAuthPath = yield* writeHomeFile(
242 homeDirectory,
243 ".codex/auth.json",
244 `{"tokens":{"access_token":"${privateAccessToken}"}}`,
245 );
246 yield* writeHomeFile(
247 homeDirectory,
248 ".claude.json",
249 `{"oauthAccount":{"accountUuid":"claude-person"}}`,
250 );
251
252 assert.deepEqual(yield* Identify.getServerOwnersForHome(homeDirectory), [
253 { source: "claude", ownerId: yield* sha256("claude-person") },
254 ]);
255 const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError");
256 assert.equal(
257 decodeLog?.message,
258 `Failed to decode codex telemetry identity at '${codexAuthPath}'.`,
259 );
260 assert.equal(decodeLog?.annotations.causeKind, "schema");
261 assert.notInclude(
262 Object.values(decodeLog?.annotations ?? {})
263 .map(String)
264 .join("\n"),
265 privateAccessToken,
266 );
267 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-decode-", logs)));
268 },
269 );
270});