Repository navigation
Expand file tree
/
Copy pathIdentify.ts
More file actions
341 lines (311 loc) · 11.4 KB
/
Copy pathIdentify.ts
File metadata and controls
341 lines (311 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as Base64Url from "effect/encoding/Base64Url";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { hashTelemetryId } from "@t3tools/shared/telemetryId";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts";
import * as ServerConfig from "../config.ts";
/**
* Codex writes `tokens` only for ChatGPT logins and omits the key for API-key,
* agent-identity, and personal-access-token logins, so its absence is a
* supported install and not a malformed file. `account_id` is the ChatGPT
* workspace, which a whole Team shares; the `id_token` names the person.
*/
const CodexAuthJsonSchema = Schema.Struct({
tokens: Schema.optionalKey(
Schema.Struct({
account_id: Schema.String,
id_token: Schema.optionalKey(Schema.String),
}),
),
});
/** `userID` is random per machine. `oauthAccount` is present only while Claude Code is logged in. */
const ClaudeJsonSchema = Schema.Struct({
userID: Schema.optionalKey(Schema.String),
oauthAccount: Schema.optionalKey(
Schema.Struct({
accountUuid: Schema.optionalKey(Schema.String),
}),
),
});
// `sub` names the login method (`google-oauth2|…`), so one person can have several.
// `user_id` (`user-…`) is the OpenAI account and is the same for every login.
const IdTokenClaims = Schema.Struct({
"https://api.openai.com/auth": Schema.Struct({ user_id: Schema.NonEmptyString }),
});
const decodeIdTokenClaims = Schema.decodeUnknownOption(Schema.fromJsonString(IdTokenClaims));
/**
* Who an install belongs to, from strongest to weakest. `connect` is the T3
* Connect account. `openai` and `claude` are provider accounts. `device` is a
* client device that connected.
*/
export const TelemetryOwnerSource = Schema.Literals(["connect", "openai", "claude", "device"]);
export type TelemetryOwnerSource = typeof TelemetryOwnerSource.Type;
export interface TelemetryOwner {
readonly source: TelemetryOwnerSource;
/** `hashTelemetryId` of the source's raw id. */
readonly ownerId: string;
}
export const TelemetryIdentitySource = Schema.Literals(["codex", "claude", "anonymous"]);
export type TelemetryIdentitySource = typeof TelemetryIdentitySource.Type;
class TelemetryIdentityReadError extends Schema.TaggedError<TelemetryIdentityReadError>()(
"TelemetryIdentityReadError",
{
source: TelemetryIdentitySource,
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.source} telemetry identity at '${this.filePath}'.`;
}
}
class TelemetryIdentityDecodeError extends Schema.TaggedError<TelemetryIdentityDecodeError>()(
"TelemetryIdentityDecodeError",
{
source: Schema.Literals(["codex", "claude"]),
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode ${this.source} telemetry identity at '${this.filePath}'.`;
}
}
export class TelemetryAnonymousIdGenerationError extends Schema.TaggedError<TelemetryAnonymousIdGenerationError>()(
"TelemetryAnonymousIdGenerationError",
{
source: Schema.Literal("anonymous"),
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to generate anonymous telemetry identity for '${this.filePath}'.`;
}
}
export class TelemetryAnonymousIdPersistenceError extends Schema.TaggedError<TelemetryAnonymousIdPersistenceError>()(
"TelemetryAnonymousIdPersistenceError",
{
source: Schema.Literal("anonymous"),
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to persist anonymous telemetry identity at '${this.filePath}'.`;
}
}
type TelemetryIdentityError =
| TelemetryIdentityReadError
| TelemetryIdentityDecodeError
| TelemetryAnonymousIdGenerationError
| TelemetryAnonymousIdPersistenceError;
const decodeCodexAuthJson = Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema));
const decodeClaudeJson = Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema));
function isNotFoundError(error: PlatformError.PlatformError): boolean {
return error.reason._tag === "NotFound";
}
const getTelemetryIdentityCauseAnnotations = (cause: unknown) => {
if (cause instanceof PlatformError.PlatformError) {
return {
causeKind: "platform",
platformReason: cause.reason._tag,
};
}
if (cause instanceof Schema.SchemaError) {
return { causeKind: "schema" };
}
return { causeKind: "other" };
};
const logTelemetryIdentityError = (error: TelemetryIdentityError) =>
Effect.logWarning(error.message).pipe(
Effect.annotateLogs({
errorTag: error._tag,
source: error.source,
...("filePath" in error ? { filePath: error.filePath } : {}),
...getTelemetryIdentityCauseAnnotations(error.cause),
...(error.stack === undefined ? {} : { errorStack: error.stack }),
}),
);
const readIdentityFile = (
fileSystem: FileSystem.FileSystem,
source: TelemetryIdentitySource,
filePath: string,
) =>
fileSystem.readFileString(filePath).pipe(
Effect.asSome,
Effect.catchTags({
PlatformError: (cause) =>
isNotFoundError(cause)
? Effect.succeed(Option.none<string>())
: Effect.fail(
new TelemetryIdentityReadError({
source,
filePath,
cause,
}),
),
}),
);
/**
* The OpenAI account id in a ChatGPT id_token, read without verifying it:
* analytics needs only a stable id. Codex CLI and T3's own sign-in both use it.
*/
export const openAiUserId = (idToken: string) => {
const payload = Base64Url.decodeString(idToken.split(".")[1] ?? "");
return Result.isSuccess(payload)
? Option.map(
decodeIdTokenClaims(payload.success),
(claims) => claims["https://api.openai.com/auth"].user_id,
)
: Option.none<string>();
};
const readJsonIdentityFile = Effect.fn("TelemetryIdentity.readJsonIdentityFile")(function* <A>(
source: "codex" | "claude",
filePath: string,
decode: (encoded: string) => Effect.Effect<A, Schema.SchemaError>,
) {
const fileSystem = yield* FileSystem.FileSystem;
const encoded = yield* readIdentityFile(fileSystem, source, filePath);
if (Option.isNone(encoded)) {
return Option.none<A>();
}
return yield* decode(encoded.value).pipe(
Effect.asSome,
Effect.mapError((cause) => new TelemetryIdentityDecodeError({ source, filePath, cause })),
);
});
// A missing or unreadable file only removes that owner; it never blocks the others.
const skipOnError = <A, R>(
effect: Effect.Effect<
Option.Option<A>,
TelemetryIdentityReadError | TelemetryIdentityDecodeError,
R
>,
) =>
effect.pipe(
Effect.catch((error) => logTelemetryIdentityError(error).pipe(Effect.as(Option.none<A>()))),
);
const upsertAnonymousId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const { anonymousIdPath } = yield* ServerConfig.ServerConfig;
const existing = yield* readIdentityFile(fileSystem, "anonymous", anonymousIdPath);
if (Option.isSome(existing)) {
return existing.value;
}
const anonymousId = yield* SecureRandom.SecureRandom.pipe(
Effect.flatMap((crypto) => crypto.uuidV4()),
Effect.mapError(
(cause) =>
new TelemetryAnonymousIdGenerationError({
source: "anonymous",
filePath: anonymousIdPath,
cause,
}),
),
);
yield* writeFileStringAtomically({ filePath: anonymousIdPath, contents: anonymousId }).pipe(
Effect.mapError(
(cause) =>
new TelemetryAnonymousIdPersistenceError({
source: "anonymous",
filePath: anonymousIdPath,
cause,
}),
),
);
return anonymousId;
});
const readProviderLogins = Effect.fn("TelemetryIdentity.readProviderLogins")(function* (
homeDirectory: string,
) {
const path = yield* Path.Path;
const codexTokens = yield* readJsonIdentityFile(
"codex",
path.join(homeDirectory, ".codex", "auth.json"),
decodeCodexAuthJson,
).pipe(
skipOnError,
Effect.map(Option.flatMap((authJson) => Option.fromUndefinedOr(authJson.tokens))),
);
const claudeJson = yield* readJsonIdentityFile(
"claude",
path.join(homeDirectory, ".claude.json"),
decodeClaudeJson,
).pipe(skipOnError);
return { codexTokens, claudeJson };
});
/**
* `distinctId` preserves legacy priority: hashed Codex account_id, Claude userID, then anonymous id.
* It can change on login or be shared by a Codex Team; hashed `installId` stays stable per install.
* A null `distinctId` disables telemetry. Missing files and API-key-only Codex auth fall through;
* only unreadable or malformed files warn.
*/
export const getTelemetryIdentityForHome = Effect.fn("getTelemetryIdentityForHome")(function* (
homeDirectory: string,
) {
const { codexTokens, claudeJson } = yield* readProviderLogins(homeDirectory);
const installId = yield* upsertAnonymousId.pipe(
Effect.map(hashTelemetryId),
Effect.catch((error) => logTelemetryIdentityError(error).pipe(Effect.as(null))),
);
const providerId = Option.orElse(
Option.map(codexTokens, (tokens) => tokens.account_id),
() => Option.flatMap(claudeJson, (json) => Option.fromUndefinedOr(json.userID)),
);
return {
distinctId: Option.isSome(providerId) ? hashTelemetryId(providerId.value) : installId,
installId,
};
});
export const getTelemetryIdentity = Effect.flatMap(
HostProcess.HomeDirectory,
getTelemetryIdentityForHome,
);
/**
* Owners the server can read without a client: the linked T3 Connect account
* and the provider logins under `homeDirectory`. Clients add `connect` and
* `device` owners when they connect.
*/
export const getServerOwnersForHome = Effect.fn("getServerOwnersForHome")(function* (
homeDirectory: string,
) {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const connectUser = yield* secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes))),
Effect.catch((cause) =>
Effect.logWarning("Failed to read the linked T3 Connect account for telemetry", {
errorTag: cause._tag,
}).pipe(Effect.as(Option.none<string>())),
),
);
const { codexTokens, claudeJson } = yield* readProviderLogins(homeDirectory);
const raw: ReadonlyArray<readonly [TelemetryOwnerSource, Option.Option<string>]> = [
["connect", connectUser],
[
"openai",
Option.flatMap(codexTokens, (tokens) =>
Option.flatMap(Option.fromUndefinedOr(tokens.id_token), openAiUserId),
),
],
[
"claude",
Option.flatMap(claudeJson, (json) => Option.fromUndefinedOr(json.oauthAccount?.accountUuid)),
],
];
return raw.flatMap(([source, value]): ReadonlyArray<TelemetryOwner> =>
Option.isSome(value) && value.value.trim() !== ""
? [{ source, ownerId: hashTelemetryId(value.value) }]
: [],
);
});
export const getServerOwners = Effect.flatMap(HostProcess.HomeDirectory, getServerOwnersForHome);