@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 538 lines 20.1 KB
Raw
1 import type {
2 RelayClientEnvironmentRecord,
3 RelayEnvironmentLinkProofPayload,
4 RelayEnvironmentLinkRequest,
5 RelayManagedEndpoint,
6 } from "@t3tools/contracts/relay";
7 import * as Context from "effect/Context";
8 import * as DateTime from "effect/DateTime";
9 import * as Effect from "effect/Effect";
10 import * as Layer from "effect/Layer";
11 import * as Schema from "effect/Schema";
12 import { and, eq, isNull, ne, or, sql } from "drizzle-orm";
13
14 import * as RelayDb from "../db.ts";
15 import { relayEnvironmentLinks } from "../persistence/schema.ts";
16
17 export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord {
18 readonly environmentPublicKey: string;
19 }
20
21 export interface AgentAwarenessDeliveryUserRecord {
22 readonly userId: string;
23 readonly notificationsEnabled: boolean;
24 readonly liveActivitiesEnabled: boolean;
25 }
26
27 export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedError<EnvironmentLinkUpsertPersistenceError>()(
28 "EnvironmentLinkUpsertPersistenceError",
29 {
30 userId: Schema.String,
31 environmentId: Schema.String,
32 deviceId: Schema.optionalKey(Schema.String),
33 cause: Schema.Defect(),
34 },
35 ) {
36 override get message(): string {
37 return `Failed to persist environment link for user '${this.userId}', environment '${this.environmentId}'`;
38 }
39 }
40
41 export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedError<EnvironmentLinkUserListPersistenceError>()(
42 "EnvironmentLinkUserListPersistenceError",
43 {
44 environmentId: Schema.String,
45 cause: Schema.Defect(),
46 },
47 ) {
48 override get message(): string {
49 return `Environment link user query 'list-delivery-users' failed for environment '${this.environmentId}'`;
50 }
51 }
52
53 export class EnvironmentLinkListPersistenceError extends Schema.TaggedError<EnvironmentLinkListPersistenceError>()(
54 "EnvironmentLinkListPersistenceError",
55 {
56 userId: Schema.String,
57 cause: Schema.Defect(),
58 },
59 ) {
60 override get message(): string {
61 return `Failed to list environment links for user '${this.userId}'`;
62 }
63 }
64
65 export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedError<EnvironmentLinkLookupPersistenceError>()(
66 "EnvironmentLinkLookupPersistenceError",
67 {
68 userId: Schema.String,
69 environmentId: Schema.String,
70 cause: Schema.Defect(),
71 },
72 ) {
73 override get message(): string {
74 return `Failed to look up environment link for user '${this.userId}', environment '${this.environmentId}'`;
75 }
76 }
77
78 export class EnvironmentLinkEnvironmentLookupPersistenceError extends Schema.TaggedError<EnvironmentLinkEnvironmentLookupPersistenceError>()(
79 "EnvironmentLinkEnvironmentLookupPersistenceError",
80 {
81 environmentId: Schema.String,
82 cause: Schema.Defect(),
83 },
84 ) {
85 override get message(): string {
86 return `Failed to look up active managed links for environment '${this.environmentId}'`;
87 }
88 }
89
90 export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedError<EnvironmentLinkRevokePersistenceError>()(
91 "EnvironmentLinkRevokePersistenceError",
92 {
93 userId: Schema.String,
94 environmentId: Schema.String,
95 cause: Schema.Defect(),
96 },
97 ) {
98 override get message(): string {
99 return `Failed to revoke environment link for user '${this.userId}', environment '${this.environmentId}'`;
100 }
101 }
102
103 export class EnvironmentLinks extends Context.Service<
104 EnvironmentLinks,
105 {
106 readonly upsert: (input: {
107 readonly userId: string;
108 readonly request: RelayEnvironmentLinkRequest;
109 readonly proof: RelayEnvironmentLinkProofPayload;
110 readonly endpoint: RelayManagedEndpoint;
111 }) => Effect.Effect<void, EnvironmentLinkUpsertPersistenceError>;
112 readonly listDeliveryUsersForEnvironment: (input: {
113 readonly environmentId: string;
114 readonly environmentPublicKey: string;
115 }) => Effect.Effect<
116 ReadonlyArray<AgentAwarenessDeliveryUserRecord>,
117 EnvironmentLinkUserListPersistenceError
118 >;
119 readonly listForUser: (input: {
120 readonly userId: string;
121 }) => Effect.Effect<
122 ReadonlyArray<RelayClientEnvironmentRecord>,
123 EnvironmentLinkListPersistenceError
124 >;
125 readonly getForUser: (input: {
126 readonly userId: string;
127 readonly environmentId: string;
128 }) => Effect.Effect<RelayLinkedEnvironmentRecord | null, EnvironmentLinkLookupPersistenceError>;
129 /** Narrow by user or proven key: a public environment id alone does not authorize access to its links. */
130 readonly findActiveManagedForEnvironment: (input: {
131 readonly environmentId: string;
132 readonly userId?: string;
133 readonly environmentPublicKey?: string;
134 }) => Effect.Effect<
135 ReadonlyArray<
136 RelayLinkedEnvironmentRecord & {
137 readonly userId: string;
138 readonly holdWebhooksWhileOffline: boolean;
139 }
140 >,
141 EnvironmentLinkEnvironmentLookupPersistenceError
142 >;
143 readonly setHoldWebhooksWhileOffline: (input: {
144 readonly environmentId: string;
145 readonly environmentPublicKey: string;
146 readonly holdWebhooksWhileOffline: boolean;
147 }) => Effect.Effect<void, EnvironmentLinkEnvironmentLookupPersistenceError>;
148 readonly updateLiveActivityPreference: (input: {
149 readonly userId: string;
150 readonly environmentId: string;
151 readonly environmentPublicKey: string;
152 readonly liveActivitiesEnabled: boolean;
153 }) => Effect.Effect<boolean, EnvironmentLinkEnvironmentLookupPersistenceError>;
154 readonly revokeForUser: (input: {
155 readonly userId: string;
156 readonly environmentId: string;
157 }) => Effect.Effect<boolean, EnvironmentLinkRevokePersistenceError>;
158 }
159 >()("t3code-relay/environments/EnvironmentLinks") {}
160
161 function agentAwarenessDeliveryUserKeyCondition(input: {
162 readonly environmentId: string;
163 readonly environmentPublicKey: string;
164 }) {
165 return and(
166 eq(relayEnvironmentLinks.environmentId, input.environmentId),
167 isNull(relayEnvironmentLinks.revokedAt),
168 or(
169 eq(relayEnvironmentLinks.notificationsEnabled, true),
170 eq(relayEnvironmentLinks.liveActivitiesEnabled, true),
171 ),
172 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
173 );
174 }
175
176 const make = Effect.gen(function* () {
177 const db = yield* RelayDb.RelayDb;
178
179 return EnvironmentLinks.of({
180 upsert: Effect.fn("relay.environment_links.upsert")(function* (input) {
181 yield* Effect.annotateCurrentSpan({
182 "relay.environment_id": input.proof.environmentId,
183 });
184 const now = DateTime.formatIso(yield* DateTime.now);
185 const { request, proof } = input;
186 const environmentId = proof.environmentId;
187 // Inherit opt-in only from links proven by the same key; anyone can claim the public environment id.
188 const inheritedHoldWebhooks = sql<boolean>`EXISTS (
189 SELECT 1 FROM ${relayEnvironmentLinks} AS other
190 WHERE other.environment_id = ${environmentId}
191 AND other.environment_public_key = ${proof.environmentPublicKey}
192 AND other.revoked_at IS NULL
193 AND other.hold_webhooks_while_offline
194 )`;
195 const { endpoint } = input;
196 yield* db.$client
197 .withTransaction(
198 Effect.gen(function* () {
199 // Serialize account switches for the same proven environment identity.
200 yield* db.execute(
201 sql`select pg_advisory_xact_lock(hashtext(${environmentId}), hashtext(${proof.environmentPublicKey}))`,
202 );
203 yield* db
204 .insert(relayEnvironmentLinks)
205 .values({
206 userId: input.userId,
207 environmentId,
208 holdWebhooksWhileOffline: inheritedHoldWebhooks,
209 environmentLabel: proof.descriptor.label,
210 environmentPublicKey: proof.environmentPublicKey,
211 endpointHttpBaseUrl: endpoint.httpBaseUrl,
212 endpointWsBaseUrl: endpoint.wsBaseUrl,
213 endpointProviderKind: endpoint.providerKind,
214 notificationsEnabled: request.notificationsEnabled,
215 liveActivitiesEnabled: request.liveActivitiesEnabled,
216 managedTunnelsEnabled: request.managedTunnelsEnabled,
217 createdByDeviceId: request.deviceId ?? null,
218 revokedAt: null,
219 createdAt: now,
220 updatedAt: now,
221 })
222 .onConflictDoUpdate({
223 target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
224 set: {
225 environmentPublicKey: proof.environmentPublicKey,
226 environmentLabel: proof.descriptor.label,
227 endpointHttpBaseUrl: endpoint.httpBaseUrl,
228 endpointWsBaseUrl: endpoint.wsBaseUrl,
229 endpointProviderKind: endpoint.providerKind,
230 notificationsEnabled: request.notificationsEnabled,
231 liveActivitiesEnabled: request.liveActivitiesEnabled,
232 managedTunnelsEnabled: request.managedTunnelsEnabled,
233 createdByDeviceId: request.deviceId ?? null,
234 revokedAt: null,
235 updatedAt: now,
236 holdWebhooksWhileOffline: inheritedHoldWebhooks,
237 },
238 });
239 yield* db
240 .update(relayEnvironmentLinks)
241 .set({ revokedAt: now, updatedAt: now })
242 .where(
243 and(
244 eq(relayEnvironmentLinks.environmentId, environmentId),
245 eq(relayEnvironmentLinks.environmentPublicKey, proof.environmentPublicKey),
246 ne(relayEnvironmentLinks.userId, input.userId),
247 isNull(relayEnvironmentLinks.revokedAt),
248 ),
249 );
250 }),
251 )
252 .pipe(
253 Effect.mapError(
254 (cause) =>
255 new EnvironmentLinkUpsertPersistenceError({
256 userId: input.userId,
257 environmentId,
258 ...(request.deviceId === undefined ? {} : { deviceId: request.deviceId }),
259 cause,
260 }),
261 ),
262 );
263 }),
264
265 listDeliveryUsersForEnvironment: Effect.fn(
266 "relay.environment_links.list_delivery_users_for_environment",
267 )(function* (input) {
268 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
269 return yield* db
270 .select({
271 userId: relayEnvironmentLinks.userId,
272 notificationsEnabled: relayEnvironmentLinks.notificationsEnabled,
273 liveActivitiesEnabled: relayEnvironmentLinks.liveActivitiesEnabled,
274 })
275 .from(relayEnvironmentLinks)
276 .where(agentAwarenessDeliveryUserKeyCondition(input))
277 .pipe(
278 Effect.map((rows) =>
279 rows.map((row) => ({
280 userId: row.userId,
281 notificationsEnabled: row.notificationsEnabled,
282 liveActivitiesEnabled: row.liveActivitiesEnabled,
283 })),
284 ),
285 Effect.mapError(
286 (cause) =>
287 new EnvironmentLinkUserListPersistenceError({
288 environmentId: input.environmentId,
289 cause,
290 }),
291 ),
292 );
293 }),
294
295 listForUser: Effect.fn("relay.environment_links.list_for_user")(function* (input) {
296 return yield* db
297 .select({
298 environmentId: relayEnvironmentLinks.environmentId,
299 environmentLabel: relayEnvironmentLinks.environmentLabel,
300 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
301 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
302 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
303 createdAt: relayEnvironmentLinks.createdAt,
304 })
305 .from(relayEnvironmentLinks)
306 .where(
307 and(
308 eq(relayEnvironmentLinks.userId, input.userId),
309 isNull(relayEnvironmentLinks.revokedAt),
310 ),
311 )
312 .pipe(
313 Effect.map((rows) =>
314 rows.map((row) => ({
315 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
316 label:
317 row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,
318 endpoint: {
319 httpBaseUrl: row.endpointHttpBaseUrl,
320 wsBaseUrl: row.endpointWsBaseUrl,
321 providerKind:
322 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
323 },
324 linkedAt: row.createdAt,
325 })),
326 ),
327 Effect.mapError(
328 (cause) =>
329 new EnvironmentLinkListPersistenceError({
330 userId: input.userId,
331 cause,
332 }),
333 ),
334 );
335 }),
336
337 getForUser: Effect.fn("relay.environment_links.get_for_user")(function* (input) {
338 yield* Effect.annotateCurrentSpan({
339 "relay.environment_id": input.environmentId,
340 });
341 return yield* db
342 .select({
343 environmentId: relayEnvironmentLinks.environmentId,
344 environmentLabel: relayEnvironmentLinks.environmentLabel,
345 environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
346 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
347 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
348 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
349 createdAt: relayEnvironmentLinks.createdAt,
350 })
351 .from(relayEnvironmentLinks)
352 .where(
353 and(
354 eq(relayEnvironmentLinks.userId, input.userId),
355 eq(relayEnvironmentLinks.environmentId, input.environmentId),
356 isNull(relayEnvironmentLinks.revokedAt),
357 ),
358 )
359 .limit(1)
360 .pipe(
361 Effect.map((rows) => {
362 const row = rows[0];
363 return row
364 ? {
365 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
366 label:
367 row.environmentLabel.trim().length > 0
368 ? row.environmentLabel
369 : row.environmentId,
370 endpoint: {
371 httpBaseUrl: row.endpointHttpBaseUrl,
372 wsBaseUrl: row.endpointWsBaseUrl,
373 providerKind:
374 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
375 },
376 environmentPublicKey: row.environmentPublicKey,
377 linkedAt: row.createdAt,
378 }
379 : null;
380 }),
381 Effect.mapError(
382 (cause) =>
383 new EnvironmentLinkLookupPersistenceError({
384 userId: input.userId,
385 environmentId: input.environmentId,
386 cause,
387 }),
388 ),
389 );
390 }),
391
392 findActiveManagedForEnvironment: Effect.fn(
393 "relay.environment_links.find_active_managed_for_environment",
394 )(function* (input) {
395 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
396 return yield* db
397 .select({
398 userId: relayEnvironmentLinks.userId,
399 environmentId: relayEnvironmentLinks.environmentId,
400 environmentLabel: relayEnvironmentLinks.environmentLabel,
401 environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
402 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
403 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
404 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
405 createdAt: relayEnvironmentLinks.createdAt,
406 holdWebhooksWhileOffline: relayEnvironmentLinks.holdWebhooksWhileOffline,
407 })
408 .from(relayEnvironmentLinks)
409 .where(
410 and(
411 eq(relayEnvironmentLinks.environmentId, input.environmentId),
412 isNull(relayEnvironmentLinks.revokedAt),
413 eq(relayEnvironmentLinks.endpointProviderKind, "cloudflare_tunnel"),
414 eq(relayEnvironmentLinks.managedTunnelsEnabled, true),
415 input.userId === undefined ? undefined : eq(relayEnvironmentLinks.userId, input.userId),
416 input.environmentPublicKey === undefined
417 ? undefined
418 : eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
419 ),
420 )
421 .pipe(
422 Effect.map((rows) =>
423 rows.map((row) => ({
424 userId: row.userId,
425 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
426 label:
427 row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,
428 endpoint: {
429 httpBaseUrl: row.endpointHttpBaseUrl,
430 wsBaseUrl: row.endpointWsBaseUrl,
431 providerKind:
432 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
433 },
434 environmentPublicKey: row.environmentPublicKey,
435 linkedAt: row.createdAt,
436 holdWebhooksWhileOffline: row.holdWebhooksWhileOffline,
437 })),
438 ),
439 Effect.mapError(
440 (cause) =>
441 new EnvironmentLinkEnvironmentLookupPersistenceError({
442 environmentId: input.environmentId,
443 cause,
444 }),
445 ),
446 );
447 }),
448
449 setHoldWebhooksWhileOffline: Effect.fn(
450 "relay.environment_links.set_hold_webhooks_while_offline",
451 )(function* (input) {
452 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
453 yield* db
454 .update(relayEnvironmentLinks)
455 .set({ holdWebhooksWhileOffline: input.holdWebhooksWhileOffline })
456 .where(
457 and(
458 eq(relayEnvironmentLinks.environmentId, input.environmentId),
459 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
460 isNull(relayEnvironmentLinks.revokedAt),
461 ),
462 )
463 .pipe(
464 Effect.mapError(
465 (cause) =>
466 new EnvironmentLinkEnvironmentLookupPersistenceError({
467 environmentId: input.environmentId,
468 cause,
469 }),
470 ),
471 );
472 }),
473
474 updateLiveActivityPreference: Effect.fn(
475 "relay.environment_links.update_live_activity_preference",
476 )(function* (input) {
477 const rows = yield* db
478 .update(relayEnvironmentLinks)
479 .set({
480 liveActivitiesEnabled: input.liveActivitiesEnabled,
481 updatedAt: DateTime.formatIso(yield* DateTime.now),
482 })
483 .where(
484 and(
485 eq(relayEnvironmentLinks.userId, input.userId),
486 eq(relayEnvironmentLinks.environmentId, input.environmentId),
487 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
488 isNull(relayEnvironmentLinks.revokedAt),
489 ),
490 )
491 .returning({ environmentId: relayEnvironmentLinks.environmentId })
492 .pipe(
493 Effect.mapError(
494 (cause) =>
495 new EnvironmentLinkEnvironmentLookupPersistenceError({
496 environmentId: input.environmentId,
497 cause,
498 }),
499 ),
500 );
501 return rows.length > 0;
502 }),
503
504 revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {
505 yield* Effect.annotateCurrentSpan({
506 "relay.environment_id": input.environmentId,
507 });
508 const revokedAt = DateTime.formatIso(yield* DateTime.now);
509 const rows = yield* db
510 .update(relayEnvironmentLinks)
511 .set({
512 revokedAt,
513 updatedAt: revokedAt,
514 })
515 .where(
516 and(
517 eq(relayEnvironmentLinks.userId, input.userId),
518 eq(relayEnvironmentLinks.environmentId, input.environmentId),
519 isNull(relayEnvironmentLinks.revokedAt),
520 ),
521 )
522 .returning({ environmentId: relayEnvironmentLinks.environmentId })
523 .pipe(
524 Effect.mapError(
525 (cause) =>
526 new EnvironmentLinkRevokePersistenceError({
527 userId: input.userId,
528 environmentId: input.environmentId,
529 cause,
530 }),
531 ),
532 );
533 return rows.length > 0;
534 }),
535 });
536 });
537
538 export const layer = Layer.effect(EnvironmentLinks, make);