forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIdentify.ts
More file actions
315 lines (284 loc) · 9.57 KB
/
Copy pathIdentify.ts
File metadata and controls
315 lines (284 loc) · 9.57 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
import * as NodeOS from "node:os";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
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 Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
/**
* Codex omits `tokens` entirely when the install authenticates with an API key
* rather than a ChatGPT account, so an absent `tokens` is a supported install
* and not a malformed file.
*/
const CodexAuthJsonSchema = Schema.Struct({
tokens: Schema.optional(
Schema.Struct({
account_id: Schema.String,
}),
),
});
const ClaudeJsonSchema = Schema.Struct({
userID: Schema.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}'.`;
}
}
export class TelemetryIdentityHashError extends Schema.TaggedError<TelemetryIdentityHashError>()(
"TelemetryIdentityHashError",
{
source: TelemetryIdentitySource,
algorithm: Schema.Literal("SHA-256"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to hash ${this.source} telemetry identity with ${this.algorithm}.`;
}
}
type TelemetryIdentityError =
| TelemetryIdentityReadError
| TelemetryIdentityDecodeError
| TelemetryAnonymousIdGenerationError
| TelemetryAnonymousIdPersistenceError
| TelemetryIdentityHashError;
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.map(Option.some),
Effect.catchTags({
PlatformError: (cause) =>
isNotFoundError(cause)
? Effect.succeed(Option.none<string>())
: Effect.fail(
new TelemetryIdentityReadError({
source,
filePath,
cause,
}),
),
}),
);
const hash = (source: TelemetryIdentitySource, value: string) =>
Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.digest("SHA-256", new TextEncoder().encode(value))),
Effect.map(Encoding.encodeHex),
Effect.mapError(
(cause) =>
new TelemetryIdentityHashError({
source,
algorithm: "SHA-256",
cause,
}),
),
);
const getCodexAccountId = Effect.fn("TelemetryIdentity.getCodexAccountId")(function* (
homeDirectory: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const authJsonPath = path.join(homeDirectory, ".codex", "auth.json");
const encoded = yield* readIdentityFile(fileSystem, "codex", authJsonPath);
if (Option.isNone(encoded)) {
return Option.none<string>();
}
const authJson = yield* decodeCodexAuthJson(encoded.value).pipe(
Effect.mapError(
(cause) =>
new TelemetryIdentityDecodeError({
source: "codex",
filePath: authJsonPath,
cause,
}),
),
);
return authJson.tokens === undefined
? Option.none<string>()
: Option.some(authJson.tokens.account_id);
});
const getClaudeUserId = Effect.fn("TelemetryIdentity.getClaudeUserId")(function* (
homeDirectory: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const claudeJsonPath = path.join(homeDirectory, ".claude.json");
const encoded = yield* readIdentityFile(fileSystem, "claude", claudeJsonPath);
if (Option.isNone(encoded)) {
return Option.none<string>();
}
const claudeJson = yield* decodeClaudeJson(encoded.value).pipe(
Effect.mapError(
(cause) =>
new TelemetryIdentityDecodeError({
source: "claude",
filePath: claudeJsonPath,
cause,
}),
),
);
return Option.some(claudeJson.userID);
});
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* Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
(cause) =>
new TelemetryAnonymousIdGenerationError({
source: "anonymous",
filePath: anonymousIdPath,
cause,
}),
),
);
yield* fileSystem.writeFileString(anonymousIdPath, anonymousId).pipe(
Effect.mapError(
(cause) =>
new TelemetryAnonymousIdPersistenceError({
source: "anonymous",
filePath: anonymousIdPath,
cause,
}),
),
);
return anonymousId;
});
/**
* getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
* 1. ~/.codex/auth.json tokens.account_id
* 2. ~/.claude.json userID
* 3. ~/.t3/telemetry/anonymous-id
*
* A missing file or an API-key-only Codex auth.json falls through quietly. Only
* unreadable or malformed files warn.
*/
export const getTelemetryIdentifierForHome = Effect.fn("getTelemetryIdentifierForHome")(
function* (homeDirectory: string) {
const codexAccountId = yield* getCodexAccountId(homeDirectory).pipe(
Effect.catchTags({
TelemetryIdentityReadError: (error) =>
logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
TelemetryIdentityDecodeError: (error) =>
logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
}),
);
if (Option.isSome(codexAccountId)) {
return yield* hash("codex", codexAccountId.value);
}
const claudeUserId = yield* getClaudeUserId(homeDirectory).pipe(
Effect.catchTags({
TelemetryIdentityReadError: (error) =>
logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
TelemetryIdentityDecodeError: (error) =>
logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
}),
);
if (Option.isSome(claudeUserId)) {
return yield* hash("claude", claudeUserId.value);
}
const anonymousId = yield* upsertAnonymousId.pipe(
Effect.map(Option.some),
Effect.catchTags({
TelemetryIdentityReadError: (error) =>
logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
TelemetryAnonymousIdGenerationError: (error) =>
logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
TelemetryAnonymousIdPersistenceError: (error) =>
logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
}),
);
if (Option.isSome(anonymousId)) {
return yield* hash("anonymous", anonymousId.value);
}
return null;
},
Effect.tapError(logTelemetryIdentityError),
Effect.orElseSucceed(() => null),
);
export const getTelemetryIdentifier = Effect.suspend(() =>
getTelemetryIdentifierForHome(NodeOS.homedir()),
);