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