Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Identify.test.ts

158 lines6.3 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as Digest from "effect/crypto/Digest";
5import * as Effect from "effect/Effect";
6import * as Hex from "effect/encoding/Hex";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Path from "effect/Path";
11import * as PlatformError from "effect/PlatformError";
12import * as References from "effect/References";
13​
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts";
17import * as ServerConfig from "../config.ts";
18import * as Identify from "./Identify.ts";
19​
20interface CapturedLog {
21 readonly message: unknown;
22 readonly annotations: Readonly<Record<string, unknown>>;
24​
25const sha256 = Effect.fn("test.sha256")(function* (value: string) {
26 const digest = yield* Digest.Digest;
27 return Hex.encode(
28 yield* digest.digest(Digest.sha256, new TextEncoder().encode(value)).pipe(Effect.orDie),
29 );
30});
31​
32const makeCaptureLogger = (logs: CapturedLog[]) =>
33 Logger.make(({ fiber, message }) => {
34 logs.push({
35 message,
36 annotations: fiber.getRef(References.CurrentLogAnnotations),
37 });
38 });
39​
40const findIdentityLog = (logs: ReadonlyArray<CapturedLog>, errorTag: string) =>
41 logs.find((log) => log.annotations.errorTag === errorTag);
42​
43const layerIdentity = (prefix: string, logs?: CapturedLog[]) =>
44 Layer.provideMerge(
45 ServerSecretStore.layer,
46 ServerConfig.layerTest(process.cwd(), { prefix }),
47 ).pipe(
48 Layer.merge(
49 logs === undefined
50 ? Layer.empty
51 : Logger.layer([makeCaptureLogger(logs)], { mergeWithExisting: false }),
52 ),
53 );
54​
55const writeHomeFile = Effect.fn("test.writeHomeFile")(function* (
56 homeDirectory: string,
57 relativePath: string,
58 contents: string,
59) {
60 const fileSystem = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const filePath = path.join(homeDirectory, relativePath);
63 yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });
64 yield* fileSystem.writeFileString(filePath, contents);
65 return filePath;
66});
67​
68it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("telemetry identity", (it) => {
69 it.effect("uses the install id as distinct_id and ignores provider sign-in files", () =>
70 Effect.gen(function* () {
71 const config = yield* ServerConfig.ServerConfig;
72 const fileSystem = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
74 const homeDirectory = path.join(config.baseDir, "home");
75 yield* fileSystem.writeFileString(config.anonymousIdPath, "persisted-anonymous-id");
76 yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"tokens":{"account_id":"ws-1"}}`);
77 yield* writeHomeFile(homeDirectory, ".claude.json", `{"userID":"claude-machine"}`);
78 const installId = yield* sha256("persisted-anonymous-id");
79​
80 assert.deepEqual(
81 yield* Identify.getTelemetryIdentity.pipe(
82 Effect.provideService(HostProcess.HomeDirectory, homeDirectory),
83 ),
84 { distinctId: installId, installId },
85 );
86 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-install-"))),
87 );
88​
89 it.effect("leaves no torn anonymous id behind when its write fails midway", () =>
90 Effect.gen(function* () {
91 const config = yield* ServerConfig.ServerConfig;
92 const fileSystem = yield* FileSystem.FileSystem;
93 const tornWrites = FileSystem.FileSystem.of({
94 ...fileSystem,
95 open: (filePath, options) =>
96 fileSystem.open(filePath, options).pipe(
97 Effect.map((file): FileSystem.File =>
98 Object.assign(Object.create(file), {
99 writeAll: (buffer: Uint8Array) =>
100 file.writeAll(buffer.subarray(0, Math.floor(buffer.length / 2))).pipe(
101 Effect.andThen(
102 Effect.fail(
103 PlatformError.systemError({
104 _tag: "WriteZero",
105 module: "FileSystem",
106 method: "writeAll",
107 pathOrDescriptor: filePath,
108 }),
109 ),
110 ),
111 ),
112 }),
113 ),
114 ),
115 });
116​
117 const identity = yield* Identify.getTelemetryIdentity.pipe(
118 Effect.provideService(FileSystem.FileSystem, tornWrites),
119 );
120​
121 assert.deepEqual(identity, { distinctId: null, installId: null });
122 assert.isFalse(yield* fileSystem.exists(config.anonymousIdPath));
123 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-torn-"))),
124 );
125​
126 it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => {
127 const logs: CapturedLog[] = [];
128​
129 return Effect.gen(function* () {
130 const config = yield* ServerConfig.ServerConfig;
131 const fileSystem = yield* FileSystem.FileSystem;
132 yield* fileSystem.makeDirectory(config.anonymousIdPath);
133​
134 const identity = yield* Identify.getTelemetryIdentity;
135 assert.deepEqual(identity, { distinctId: null, installId: null });
136 assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []);
137​
138 const readLog = findIdentityLog(logs, "TelemetryIdentityReadError");
139 assert.equal(readLog?.annotations.filePath, config.anonymousIdPath);
140 assert.notEqual(readLog?.annotations.platformReason, "NotFound");
141 assert.notProperty(readLog?.annotations ?? {}, "cause");
142 assert.isUndefined(findIdentityLog(logs, "TelemetryAnonymousIdPersistenceError"));
143 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-read-", logs)));
144 });
145​
146 it.effect("reads only the linked Connect account as an owner", () =>
147 Effect.gen(function* () {
148 const secrets = yield* ServerSecretStore.ServerSecretStore;
149 assert.deepEqual(yield* Identify.getServerOwners, []);
150​
151 yield* secrets.set(CLOUD_LINKED_USER_ID, new TextEncoder().encode("user_connect"));
152​
153 assert.deepEqual(yield* Identify.getServerOwners, [
154 { source: "connect", ownerId: yield* sha256("user_connect") },
155 ]);
156 }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-owners-"))),
157 );
158});