@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 205 lines 7.97 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { PGlite } from "@electric-sql/pglite";
3 import { drizzle } from "drizzle-orm/pglite";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Path from "effect/Path";
6 import { describe, expect, it } from "@effect/vitest";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
9 import type { SQL } from "drizzle-orm";
10 import { PgDialect } from "drizzle-orm/pg-core";
11
12 import * as RelayDb from "../db.ts";
13 import { relayEnvironmentLinks } from "../persistence/schema.ts";
14 import * as EnvironmentLinks from "./EnvironmentLinks.ts";
15
16 describe("EnvironmentLinks", () => {
17 it.effect("carries the webhook-hold opt-in over only from links with the same key", () => {
18 const inserted: Array<Record<string, unknown>> = [];
19 const revoked: Array<{ values: Record<string, unknown>; condition: unknown }> = [];
20 const fakeDb = {
21 $client: {
22 withTransaction: (effect: Effect.Effect<unknown>) => effect,
23 },
24 execute: () => Effect.void,
25 update: () => ({
26 set: (values: Record<string, unknown>) => ({
27 where: (condition: unknown) =>
28 Effect.sync(() => {
29 revoked.push({ values, condition });
30 }),
31 }),
32 }),
33 insert: () => ({
34 values: (values: Record<string, unknown>) => {
35 inserted.push(values);
36 return { onConflictDoUpdate: () => Effect.void };
37 },
38 }),
39 } as unknown as RelayDb.RelayDb["Service"];
40
41 return Effect.gen(function* () {
42 const links = yield* EnvironmentLinks.EnvironmentLinks;
43 yield* links.upsert({
44 userId: "user-1",
45 request: {
46 notificationsEnabled: false,
47 liveActivitiesEnabled: false,
48 managedTunnelsEnabled: true,
49 } as never,
50 proof: {
51 environmentId: "env-1",
52 environmentPublicKey: "public-key-1",
53 descriptor: { label: "Laptop" },
54 } as never,
55 endpoint: { httpBaseUrl: "https://a.example", wsBaseUrl: "wss://a.example" } as never,
56 });
57 const query = new PgDialect().sqlToQuery(inserted[0]?.holdWebhooksWhileOffline as never);
58 expect(query.sql).toContain("environment_public_key");
59 expect(query.params).toEqual(["env-1", "public-key-1"]);
60 expect(revoked).toHaveLength(1);
61 expect(revoked[0]?.values.revokedAt).toEqual(inserted[0]?.updatedAt);
62 const priorLinks = new PgDialect().sqlToQuery(revoked[0]?.condition as never);
63 expect(priorLinks.sql).toContain('"user_id" <>');
64 expect(priorLinks.sql).toContain('"revoked_at" is null');
65 expect(priorLinks.params).toEqual(["env-1", "public-key-1", "user-1"]);
66 }).pipe(
67 Effect.provide(
68 EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
69 ),
70 );
71 });
72
73 it.effect("updates Live Activities only on the matching active link", () =>
74 Effect.gen(function* () {
75 const pg = yield* Effect.acquireRelease(
76 Effect.promise(() => PGlite.create()),
77 (client) => Effect.promise(() => client.close()),
78 );
79 const fs = yield* FileSystem.FileSystem;
80 const path = yield* Path.Path;
81 const migrationsDir = yield* path.fromFileUrl(
82 new URL("../../migrations/postgres/", import.meta.url),
83 );
84 for (const name of (yield* fs.readDirectory(migrationsDir)).toSorted()) {
85 const migration = yield* fs.readFileString(`${migrationsDir}${name}/migration.sql`);
86 yield* Effect.promise(() => pg.exec(migration));
87 }
88
89 const db = drizzle({ client: pg });
90 const matching = { userId: "user-1", environmentId: "env-1", environmentPublicKey: "key-1" };
91 const revoked = { ...matching, environmentId: "revoked-env" };
92 const timestamp = "2026-01-01T00:00:00.000Z";
93 const rows = [
94 matching,
95 { ...matching, userId: "user-2" },
96 { ...matching, environmentId: "env-2" },
97 { ...matching, userId: "user-3", environmentPublicKey: "key-2" },
98 { ...revoked, revokedAt: timestamp },
99 ];
100 yield* Effect.promise(() =>
101 db.insert(relayEnvironmentLinks).values(
102 rows.map((row) => ({
103 ...row,
104 endpointHttpBaseUrl: "https://environment.test",
105 endpointWsBaseUrl: "wss://environment.test",
106 endpointProviderKind: "cloudflare_tunnel",
107 createdAt: timestamp,
108 updatedAt: timestamp,
109 })),
110 ),
111 );
112 // PGlite returns promises where the production Drizzle driver returns Effects.
113 const effectDb = {
114 update: (table: typeof relayEnvironmentLinks) => ({
115 set: (values: Partial<typeof relayEnvironmentLinks.$inferInsert>) => ({
116 where: (condition: SQL | undefined) => ({
117 returning: (fields: { environmentId: typeof relayEnvironmentLinks.environmentId }) =>
118 Effect.promise(() =>
119 db.update(table).set(values).where(condition).returning(fields),
120 ),
121 }),
122 }),
123 }),
124 } as unknown as RelayDb.RelayDb["Service"];
125 const links = yield* Effect.service(EnvironmentLinks.EnvironmentLinks).pipe(
126 Effect.provide(
127 EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, effectDb))),
128 ),
129 );
130 expect(
131 yield* links.updateLiveActivityPreference({ ...matching, liveActivitiesEnabled: false }),
132 ).toBe(true);
133 expect(
134 yield* links.updateLiveActivityPreference({
135 ...matching,
136 environmentPublicKey: "key-2",
137 liveActivitiesEnabled: false,
138 }),
139 ).toBe(false);
140 expect(
141 yield* links.updateLiveActivityPreference({ ...revoked, liveActivitiesEnabled: false }),
142 ).toBe(false);
143
144 const updated = yield* Effect.promise(() => db.select().from(relayEnvironmentLinks));
145 expect(
146 updated
147 .filter((row) => !row.liveActivitiesEnabled)
148 .map(({ userId, environmentId }) => ({
149 userId,
150 environmentId,
151 })),
152 ).toEqual([{ userId: matching.userId, environmentId: matching.environmentId }]);
153 }).pipe(Effect.provide(NodeServices.layer)),
154 );
155
156 it.effect("revokes only the active link owned by the requesting user", () => {
157 const updateValues: Array<Record<string, unknown>> = [];
158 const whereConditions: Array<unknown> = [];
159 const fakeDb = {
160 update: (table: unknown) => {
161 expect(table).toBe(relayEnvironmentLinks);
162 return {
163 set: (values: Record<string, unknown>) => {
164 updateValues.push(values);
165 return {
166 where: (condition: unknown) => {
167 whereConditions.push(condition);
168 return {
169 returning: () => {
170 return Effect.succeed([{ environmentId: "env-1" }]);
171 },
172 };
173 },
174 };
175 },
176 };
177 },
178 } as unknown as RelayDb.RelayDb["Service"];
179
180 return Effect.gen(function* () {
181 const links = yield* EnvironmentLinks.EnvironmentLinks;
182 const revoked = yield* links.revokeForUser({
183 userId: "user-1",
184 environmentId: "env-1",
185 });
186
187 expect(revoked).toBe(true);
188 expect(updateValues).toHaveLength(1);
189 expect(updateValues[0]?.revokedAt).toEqual(updateValues[0]?.updatedAt);
190 expect(typeof updateValues[0]?.revokedAt).toBe("string");
191 expect(whereConditions).toHaveLength(1);
192
193 const dialect = new PgDialect();
194 const query = dialect.sqlToQuery(whereConditions[0] as never);
195 expect(query.sql).toContain('"relay_environment_links"."user_id" = $1');
196 expect(query.sql).toContain('"relay_environment_links"."environment_id" = $2');
197 expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
198 expect(query.params).toEqual(["user-1", "env-1"]);
199 }).pipe(
200 Effect.provide(
201 EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
202 ),
203 );
204 });
205 });