Open History to see the last commit
1import type {
2 RelayClientEnvironmentRecord,
3 RelayEnvironmentLinkProofPayload,
4 RelayEnvironmentLinkRequest,
5 RelayManagedEndpoint,
6} from "@t3tools/contracts/relay";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Schema from "effect/Schema";
12import { and, eq, isNull, or, sql } from "drizzle-orm";
13
14import * as RelayDb from "../db.ts";
15import { relayEnvironmentLinks } from "../persistence/schema.ts";
16
17export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord {
18 readonly environmentPublicKey: string;
19}
20
21export interface AgentAwarenessDeliveryUserRecord {
22 readonly userId: string;
23 readonly notificationsEnabled: boolean;
24 readonly liveActivitiesEnabled: boolean;
25}
26
27export 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
41export 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
53export 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
65export 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
78export 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
90export 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
103export 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 revokeForUser: (input: {
149 readonly userId: string;
150 readonly environmentId: string;
151 }) => Effect.Effect<boolean, EnvironmentLinkRevokePersistenceError>;
152 }
153>()("t3code-relay/environments/EnvironmentLinks") {}
154
155function agentAwarenessDeliveryUserKeyCondition(input: {
156 readonly environmentId: string;
157 readonly environmentPublicKey: string;
158}) {
159 return and(
160 eq(relayEnvironmentLinks.environmentId, input.environmentId),
161 isNull(relayEnvironmentLinks.revokedAt),
162 or(
163 eq(relayEnvironmentLinks.notificationsEnabled, true),
164 eq(relayEnvironmentLinks.liveActivitiesEnabled, true),
165 ),
166 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
167 );
168}
169
170const make = Effect.gen(function* () {
171 const db = yield* RelayDb.RelayDb;
172
173 return EnvironmentLinks.of({
174 upsert: Effect.fn("relay.environment_links.upsert")(function* (input) {
175 yield* Effect.annotateCurrentSpan({
176 "relay.environment_id": input.proof.environmentId,
177 });
178 const now = DateTime.formatIso(yield* DateTime.now);
179 const { request, proof } = input;
180 const environmentId = proof.environmentId;
181 // Inherit opt-in only from links proven by the same key; anyone can claim the public environment id.
182 const inheritedHoldWebhooks = sql<boolean>`EXISTS (
183 SELECT 1 FROM ${relayEnvironmentLinks} AS other
184 WHERE other.environment_id = ${environmentId}
185 AND other.environment_public_key = ${proof.environmentPublicKey}
186 AND other.revoked_at IS NULL
187 AND other.hold_webhooks_while_offline
188 )`;
189 const { endpoint } = input;
190 yield* db
191 .insert(relayEnvironmentLinks)
192 .values({
193 userId: input.userId,
194 environmentId,
195 holdWebhooksWhileOffline: inheritedHoldWebhooks,
196 environmentLabel: proof.descriptor.label,
197 environmentPublicKey: proof.environmentPublicKey,
198 endpointHttpBaseUrl: endpoint.httpBaseUrl,
199 endpointWsBaseUrl: endpoint.wsBaseUrl,
200 endpointProviderKind: endpoint.providerKind,
201 notificationsEnabled: request.notificationsEnabled,
202 liveActivitiesEnabled: request.liveActivitiesEnabled,
203 managedTunnelsEnabled: request.managedTunnelsEnabled,
204 createdByDeviceId: request.deviceId ?? null,
205 revokedAt: null,
206 createdAt: now,
207 updatedAt: now,
208 })
209 .onConflictDoUpdate({
210 target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
211 set: {
212 environmentPublicKey: proof.environmentPublicKey,
213 environmentLabel: proof.descriptor.label,
214 endpointHttpBaseUrl: endpoint.httpBaseUrl,
215 endpointWsBaseUrl: endpoint.wsBaseUrl,
216 endpointProviderKind: endpoint.providerKind,
217 notificationsEnabled: request.notificationsEnabled,
218 liveActivitiesEnabled: request.liveActivitiesEnabled,
219 managedTunnelsEnabled: request.managedTunnelsEnabled,
220 createdByDeviceId: request.deviceId ?? null,
221 revokedAt: null,
222 updatedAt: now,
223 holdWebhooksWhileOffline: inheritedHoldWebhooks,
224 },
225 })
226 .pipe(
227 Effect.mapError(
228 (cause) =>
229 new EnvironmentLinkUpsertPersistenceError({
230 userId: input.userId,
231 environmentId,
232 ...(request.deviceId === undefined ? {} : { deviceId: request.deviceId }),
233 cause,
234 }),
235 ),
236 );
237 }),
238
239 listDeliveryUsersForEnvironment: Effect.fn(
240 "relay.environment_links.list_delivery_users_for_environment",
241 )(function* (input) {
242 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
243 return yield* db
244 .select({
245 userId: relayEnvironmentLinks.userId,
246 notificationsEnabled: relayEnvironmentLinks.notificationsEnabled,
247 liveActivitiesEnabled: relayEnvironmentLinks.liveActivitiesEnabled,
248 })
249 .from(relayEnvironmentLinks)
250 .where(agentAwarenessDeliveryUserKeyCondition(input))
251 .pipe(
252 Effect.map((rows) =>
253 rows.map((row) => ({
254 userId: row.userId,
255 notificationsEnabled: row.notificationsEnabled,
256 liveActivitiesEnabled: row.liveActivitiesEnabled,
257 })),
258 ),
259 Effect.mapError(
260 (cause) =>
261 new EnvironmentLinkUserListPersistenceError({
262 environmentId: input.environmentId,
263 cause,
264 }),
265 ),
266 );
267 }),
268
269 listForUser: Effect.fn("relay.environment_links.list_for_user")(function* (input) {
270 return yield* db
271 .select({
272 environmentId: relayEnvironmentLinks.environmentId,
273 environmentLabel: relayEnvironmentLinks.environmentLabel,
274 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
275 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
276 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
277 createdAt: relayEnvironmentLinks.createdAt,
278 })
279 .from(relayEnvironmentLinks)
280 .where(
281 and(
282 eq(relayEnvironmentLinks.userId, input.userId),
283 isNull(relayEnvironmentLinks.revokedAt),
284 ),
285 )
286 .pipe(
287 Effect.map((rows) =>
288 rows.map((row) => ({
289 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
290 label:
291 row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,
292 endpoint: {
293 httpBaseUrl: row.endpointHttpBaseUrl,
294 wsBaseUrl: row.endpointWsBaseUrl,
295 providerKind:
296 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
297 },
298 linkedAt: row.createdAt,
299 })),
300 ),
301 Effect.mapError(
302 (cause) =>
303 new EnvironmentLinkListPersistenceError({
304 userId: input.userId,
305 cause,
306 }),
307 ),
308 );
309 }),
310
311 getForUser: Effect.fn("relay.environment_links.get_for_user")(function* (input) {
312 yield* Effect.annotateCurrentSpan({
313 "relay.environment_id": input.environmentId,
314 });
315 return yield* db
316 .select({
317 environmentId: relayEnvironmentLinks.environmentId,
318 environmentLabel: relayEnvironmentLinks.environmentLabel,
319 environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
320 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
321 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
322 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
323 createdAt: relayEnvironmentLinks.createdAt,
324 })
325 .from(relayEnvironmentLinks)
326 .where(
327 and(
328 eq(relayEnvironmentLinks.userId, input.userId),
329 eq(relayEnvironmentLinks.environmentId, input.environmentId),
330 isNull(relayEnvironmentLinks.revokedAt),
331 ),
332 )
333 .limit(1)
334 .pipe(
335 Effect.map((rows) => {
336 const row = rows[0];
337 return row
338 ? {
339 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
340 label:
341 row.environmentLabel.trim().length > 0
342 ? row.environmentLabel
343 : row.environmentId,
344 endpoint: {
345 httpBaseUrl: row.endpointHttpBaseUrl,
346 wsBaseUrl: row.endpointWsBaseUrl,
347 providerKind:
348 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
349 },
350 environmentPublicKey: row.environmentPublicKey,
351 linkedAt: row.createdAt,
352 }
353 : null;
354 }),
355 Effect.mapError(
356 (cause) =>
357 new EnvironmentLinkLookupPersistenceError({
358 userId: input.userId,
359 environmentId: input.environmentId,
360 cause,
361 }),
362 ),
363 );
364 }),
365
366 findActiveManagedForEnvironment: Effect.fn(
367 "relay.environment_links.find_active_managed_for_environment",
368 )(function* (input) {
369 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
370 return yield* db
371 .select({
372 userId: relayEnvironmentLinks.userId,
373 environmentId: relayEnvironmentLinks.environmentId,
374 environmentLabel: relayEnvironmentLinks.environmentLabel,
375 environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
376 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
377 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
378 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
379 createdAt: relayEnvironmentLinks.createdAt,
380 holdWebhooksWhileOffline: relayEnvironmentLinks.holdWebhooksWhileOffline,
381 })
382 .from(relayEnvironmentLinks)
383 .where(
384 and(
385 eq(relayEnvironmentLinks.environmentId, input.environmentId),
386 isNull(relayEnvironmentLinks.revokedAt),
387 eq(relayEnvironmentLinks.endpointProviderKind, "cloudflare_tunnel"),
388 eq(relayEnvironmentLinks.managedTunnelsEnabled, true),
389 input.userId === undefined ? undefined : eq(relayEnvironmentLinks.userId, input.userId),
390 input.environmentPublicKey === undefined
391 ? undefined
392 : eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
393 ),
394 )
395 .pipe(
396 Effect.map((rows) =>
397 rows.map((row) => ({
398 userId: row.userId,
399 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
400 label:
401 row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,
402 endpoint: {
403 httpBaseUrl: row.endpointHttpBaseUrl,
404 wsBaseUrl: row.endpointWsBaseUrl,
405 providerKind:
406 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
407 },
408 environmentPublicKey: row.environmentPublicKey,
409 linkedAt: row.createdAt,
410 holdWebhooksWhileOffline: row.holdWebhooksWhileOffline,
411 })),
412 ),
413 Effect.mapError(
414 (cause) =>
415 new EnvironmentLinkEnvironmentLookupPersistenceError({
416 environmentId: input.environmentId,
417 cause,
418 }),
419 ),
420 );
421 }),
422
423 setHoldWebhooksWhileOffline: Effect.fn(
424 "relay.environment_links.set_hold_webhooks_while_offline",
425 )(function* (input) {
426 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
427 yield* db
428 .update(relayEnvironmentLinks)
429 .set({ holdWebhooksWhileOffline: input.holdWebhooksWhileOffline })
430 .where(
431 and(
432 eq(relayEnvironmentLinks.environmentId, input.environmentId),
433 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
434 isNull(relayEnvironmentLinks.revokedAt),
435 ),
436 )
437 .pipe(
438 Effect.mapError(
439 (cause) =>
440 new EnvironmentLinkEnvironmentLookupPersistenceError({
441 environmentId: input.environmentId,
442 cause,
443 }),
444 ),
445 );
446 }),
447
448 revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {
449 yield* Effect.annotateCurrentSpan({
450 "relay.environment_id": input.environmentId,
451 });
452 const revokedAt = DateTime.formatIso(yield* DateTime.now);
453 const rows = yield* db
454 .update(relayEnvironmentLinks)
455 .set({
456 revokedAt,
457 updatedAt: revokedAt,
458 })
459 .where(
460 and(
461 eq(relayEnvironmentLinks.userId, input.userId),
462 eq(relayEnvironmentLinks.environmentId, input.environmentId),
463 isNull(relayEnvironmentLinks.revokedAt),
464 ),
465 )
466 .returning({ environmentId: relayEnvironmentLinks.environmentId })
467 .pipe(
468 Effect.mapError(
469 (cause) =>
470 new EnvironmentLinkRevokePersistenceError({
471 userId: input.userId,
472 environmentId: input.environmentId,
473 cause,
474 }),
475 ),
476 );
477 return rows.length > 0;
478 }),
479 });
480});
481
482export const layer = Layer.effect(EnvironmentLinks, make);