@devries-cameron20 / t3code-1 / commits / 8e76f945d2
Fork 0

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

feat(relay): T3 Chat Pro and Premier accounts get more tunnels (#25931)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 27, 2026 at 23:29 UTC 8e76f945d2e1aacfad5da52b92ae7b547ae0ee6f
24 files changed +1026 -60
.github/workflows/deploy-relay.yml
+1
@@ -80,6 +80,7 @@ jobs:
80 CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
81 APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
82 FCM_SERVICE_ACCOUNT: ${{ secrets.FCM_SERVICE_ACCOUNT }}
83 + T3CHAT_LINK_SECRET: ${{ secrets.T3CHAT_LINK_SECRET }}
84
85 - name: Publish relay deploy commit status
86 uses: actions/github-script@v8
.github/workflows/relay-preview.yml
+2
@@ -79,3 +79,5 @@ jobs:
79 PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
80 AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
81 CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
82 + # Unset by default, so previews keep the T3 Chat link off.
83 + T3CHAT_LINK_SECRET: ${{ secrets.T3CHAT_LINK_SECRET }}
apps/web/src/cloud/managedRelayState.ts
+47
@@ -1,10 +1,12 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import {
3 createManagedRelayQueryManager,
4 + createManagedRelayT3ChatLinkRequest,
5 deregisterManagedRelayEnvironment,
6 ManagedRelay,
7 managedRelaySessionAtom,
8 readManagedRelaySnapshotState,
9 + unlinkManagedRelayT3Chat,
10 } from "@t3tools/client-runtime/relay";
11 import {
12 createAtomCommandScheduler,
@@ -13,6 +15,7 @@ import {
15 import type {
16 RelayClientDeviceRecord,
17 RelayClientEnvironmentRecord,
18 + RelayT3ChatLinkResponse,
19 } from "@t3tools/contracts/relay";
20 import type { EnvironmentId } from "@t3tools/contracts";
21 import * as Context from "effect/Context";
@@ -50,6 +53,50 @@ export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand(
53 },
54 );
55
56 +const accountSerial = {
57 + mode: "serial",
58 + key: (input: { readonly accountId: string }) => input.accountId,
59 +} as const;
60 +
61 +export const createManagedRelayT3ChatLinkRequestCommand = createRuntimeCommand(
62 + managedRelayAtomRuntime,
63 + {
64 + label: "web:managed-relay:create-t3chat-link-request",
65 + scheduler: managedRelayMutationScheduler,
66 + concurrency: accountSerial,
67 + execute: (input: { readonly accountId: string }, registry) =>
68 + createManagedRelayT3ChatLinkRequest(registry, input),
69 + },
70 +);
71 +
72 +export const unlinkManagedRelayT3ChatCommand = createRuntimeCommand(managedRelayAtomRuntime, {
73 + label: "web:managed-relay:unlink-t3chat",
74 + scheduler: managedRelayMutationScheduler,
75 + concurrency: accountSerial,
76 + execute: (input: { readonly accountId: string }, registry) =>
77 + unlinkManagedRelayT3Chat(registry, input),
78 +});
79 +
80 +const EMPTY_T3CHAT_LINK_ATOM = Atom.make(
81 + AsyncResult.success<RelayT3ChatLinkResponse>({ available: false, link: null }),
82 +).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:t3chat-link:null"));
83 +
84 +export function useManagedRelayT3ChatLink() {
85 + const session = useAtomValue(managedRelaySessionAtom);
86 + const accountId = session?.accountId ?? null;
87 + const atom = accountId
88 + ? managedRelayQueryManager.t3ChatLinkAtom(accountId)
89 + : EMPTY_T3CHAT_LINK_ATOM;
90 + const snapshot = readManagedRelaySnapshotState(useAtomValue(atom));
91 + const refresh = () => {
92 + if (accountId) {
93 + managedRelayQueryManager.refreshT3ChatLink(appAtomRegistry, accountId);
94 + }
95 + };
96 +
97 + return { ...snapshot, accountId, refresh };
98 +}
99 +
100 const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
101 AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
102 ).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:environments:null"));
apps/web/src/components/clerk/T3ChatUserProfilePage.tsx new
+167
@@ -0,0 +1,167 @@
1 +import { findErrorTraceId } from "@t3tools/client-runtime/errors";
2 +import {
3 + isAtomCommandInterrupted,
4 + squashAtomCommandFailure,
5 +} from "@t3tools/client-runtime/state/runtime";
6 +import { T3CHAT_PLAN_TUNNEL_LIMITS, type RelayT3ChatLink } from "@t3tools/contracts/relay";
7 +import { MessageSquareIcon } from "lucide-react";
8 +import { useState } from "react";
9 +
10 +import {
11 + createManagedRelayT3ChatLinkRequestCommand,
12 + unlinkManagedRelayT3ChatCommand,
13 + useManagedRelayT3ChatLink,
14 +} from "../../cloud/managedRelayState";
15 +import { readLocalApi } from "../../localApi";
16 +import { useAtomCommand } from "../../state/use-atom-command";
17 +import { Button } from "../ui/button";
18 +import { toastManager } from "../ui/toast";
19 +import {
20 + ClerkUserProfilePage,
21 + ClerkUserProfileRefreshButton,
22 + ClerkUserProfileRow,
23 +} from "./ClerkUserProfilePage";
24 +
25 +function planLabel(link: RelayT3ChatLink): string {
26 + switch (link.plan) {
27 + case "premier":
28 + return `Premier · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} tunnels`;
29 + case "pro":
30 + return `Pro · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.pro} tunnels, or ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} with Premier`;
31 + case "free":
32 + return "Upgrade on T3 Chat for more tunnels";
33 + }
34 +}
35 +
36 +function reportFailure(title: string, cause: unknown) {
37 + const traceId = findErrorTraceId(cause);
38 + toastManager.add({
39 + type: "error",
40 + title,
41 + description: cause instanceof Error ? cause.message : "Try again.",
42 + data: traceId
43 + ? {
44 + secondaryActionProps: {
45 + children: "Copy trace ID",
46 + onClick: () => void navigator.clipboard?.writeText(traceId),
47 + },
48 + }
49 + : undefined,
50 + });
51 +}
52 +
53 +/** Links a T3 Chat account so paid subscribers get more tunnels. */
54 +export function T3ChatUserProfilePage() {
55 + const linkState = useManagedRelayT3ChatLink();
56 + const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, {
57 + reportFailure: false,
58 + });
59 + const unlink = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false });
60 + const [pending, setPending] = useState<"link" | "unlink" | null>(null);
61 + // Kept so a blocked popup still leaves the user a link to open.
62 + const [linkUrl, setLinkUrl] = useState<string | null>(null);
63 +
64 + const handleLink = async () => {
65 + const accountId = linkState.accountId;
66 + if (!accountId || pending) return;
67 + setPending("link");
68 + const result = await createLinkRequest({ accountId });
69 + if (result._tag === "Success") {
70 + setLinkUrl(result.value);
71 + await readLocalApi()
72 + ?.shell.openExternal(result.value)
73 + .catch(() => undefined);
74 + } else if (!isAtomCommandInterrupted(result)) {
75 + reportFailure("Could not start linking", squashAtomCommandFailure(result));
76 + }
77 + setPending(null);
78 + };
79 +
80 + const handleUnlink = async () => {
81 + const accountId = linkState.accountId;
82 + if (!accountId || pending) return;
83 + setPending("unlink");
84 + const result = await unlink({ accountId });
85 + if (result._tag === "Success") {
86 + setLinkUrl(null);
87 + linkState.refresh();
88 + } else if (!isAtomCommandInterrupted(result)) {
89 + reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result));
90 + }
91 + setPending(null);
92 + };
93 +
94 + const data = linkState.data;
95 + const link = data?.link ?? null;
96 +
97 + return (
98 + <ClerkUserProfilePage
99 + title="T3 Chat"
100 + description={`Link a paid T3 Chat account for more T3 Connect tunnels: up to ${T3CHAT_PLAN_TUNNEL_LIMITS.pro} with Pro, ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} with Premier.`}
101 + action={
102 + <ClerkUserProfileRefreshButton
103 + disabled={pending !== null}
104 + isPending={linkState.isPending}
105 + onClick={linkState.refresh}
106 + />
107 + }
108 + >
109 + {linkState.error ? (
110 + <div className="border-t py-3 text-xs" role="alert">
111 + <p className="font-medium text-destructive-foreground">Could not load T3 Chat link</p>
112 + <p className="mt-0.5 text-muted-foreground">{linkState.error}</p>
113 + </div>
114 + ) : data === null ? null : !data.available ? (
115 + <p className="border-t py-4 text-xs text-muted-foreground">
116 + This T3 Connect server does not support T3 Chat linking.
117 + </p>
118 + ) : (
119 + <ul className="border-t">
120 + <ClerkUserProfileRow icon={<MessageSquareIcon className="size-4" />}>
121 + <div className="flex items-start gap-4">
122 + <div className="min-w-0 flex-1">
123 + <h3 className="truncate text-sm leading-4.5 font-medium text-foreground">
124 + {link ? link.email : "Not linked"}
125 + </h3>
126 + <p className="mt-1 text-xs leading-4.5 text-muted-foreground">
127 + {link ? (
128 + planLabel(link)
129 + ) : linkUrl ? (
130 + <>
131 + Confirm on{" "}
132 + <a
133 + className="underline"
134 + href={linkUrl}
135 + target="_blank"
136 + rel="noopener noreferrer"
137 + >
138 + t3.chat
139 + </a>
140 + , then select Refresh.
141 + </>
142 + ) : (
143 + "You confirm the link on t3.chat."
144 + )}
145 + </p>
146 + </div>
147 + {link ? (
148 + <Button
149 + size="sm"
150 + variant="destructive-outline"
151 + disabled={pending !== null}
152 + onClick={() => void handleUnlink()}
153 + >
154 + {pending === "unlink" ? "Unlinking…" : "Unlink"}
155 + </Button>
156 + ) : (
157 + <Button size="sm" disabled={pending !== null} onClick={() => void handleLink()}>
158 + {pending === "link" ? "Opening…" : "Link T3 Chat"}
159 + </Button>
160 + )}
161 + </div>
162 + </ClerkUserProfileRow>
163 + </ul>
164 + )}
165 + </ClerkUserProfilePage>
166 + );
167 +}
apps/web/src/components/clerk/T3ConnectAccountPages.tsx
+8 -1
@@ -1,9 +1,10 @@
1 import { useAuth, useClerk } from "@clerk/react";
2 -import { ServerIcon, SmartphoneIcon } from "lucide-react";
2 +import { MessageSquareIcon, ServerIcon, SmartphoneIcon } from "lucide-react";
3 import { type ReactNode, useState } from "react";
4 import { createPortal } from "react-dom";
5
6 import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";
7 +import { T3ChatUserProfilePage } from "./T3ChatUserProfilePage";
8 import { T3ConnectUserProfilePage } from "./T3ConnectUserProfilePage";
9
10 export const T3_CONNECT_ACCOUNT_PAGES = [
@@ -19,6 +20,12 @@ export const T3_CONNECT_ACCOUNT_PAGES = [
20 icon: <ServerIcon className="size-4" />,
21 content: <T3ConnectUserProfilePage />,
22 },
23 + {
24 + label: "T3 Chat",
25 + url: "t3-chat",
26 + icon: <MessageSquareIcon className="size-4" />,
27 + content: <T3ChatUserProfilePage />,
28 + },
29 ] as const;
30
31 type PortalTargets = Readonly<Record<string, HTMLDivElement | undefined>>;
docs/internals/t3-connect.md
+15
@@ -131,6 +131,21 @@ and clients keep their bindings. Every mutation on an allocation bumps its
131 `generation`, and deletion locks the row at the generation it claimed, so a
132 host that reconnects mid-sweep wins.
133
134 +## A paid T3 Chat plan raises the tunnel cap
135 +
136 +T3 Chat uses WorkOS, not Clerk, so the two accounts are linked by consent
137 +rather than by a shared identity. The relay and T3 Chat share one secret
138 +(`T3CHAT_LINK_SECRET` here, `T3CODE_LINK_SECRET` there). The relay signs a
139 +short-lived token naming the Clerk user and email; the user confirms it while
140 +signed in to T3 Chat, and T3 Chat stores the link. T3 Chat owns the link and the
141 +plan, so the relay keeps no copy. It asks T3 Chat only when an account reaches
142 +its normal cap for a new environment, and any failure keeps the normal cap.
143 +An environment that already holds a counted slot restarts without asking, so a
144 +downgrade or a T3 Chat outage only blocks new environments. A manual override
145 +row replaces the default for new environments, and a T3 Chat plan does not
146 +raise it
147 +([limits](../../infra/relay/src/environments/ManagedTunnelLimits.ts)).
148 +
149 ## The relay client follows the server's pin
150
151 The host runs `cloudflared` pinned by `CLOUDFLARED_VERSION` in
docs/operations/release.md
+5
@@ -148,6 +148,11 @@ Required `production` environment secrets:
148 - `CLERK_SECRET_KEY`
149 - `APNS_PRIVATE_KEY`
150
151 +Optional `production` environment secrets:
152 +
153 +- `T3CHAT_LINK_SECRET` for the T3 Chat account link. It must match
154 + `T3CODE_LINK_SECRET` on T3 Chat.
155 +
156 After changing a variable or secret, run the **Deploy T3 Connect relay** workflow manually from
157 `main` with **force** unchecked. Alchemy compares the values the Worker reads and redeploys it when
158 one changed. Check **force** only to redeploy resources with no detected change.
infra/relay/README.md
+3
@@ -160,6 +160,9 @@ The `production` GitHub environment must define these Actions secrets:
160 - `CLERK_SECRET_KEY`
161 - `APNS_PRIVATE_KEY`
162 - `FCM_SERVICE_ACCOUNT` when Android push is enabled
163 +- `T3CHAT_LINK_SECRET`, optional, shared with T3 Chat's `T3CODE_LINK_SECRET`. Without it the
164 + T3 Chat account link is off. Local and preview stages can set `T3CHAT_URL` to point
165 + at another T3 Chat deployment; production uses `https://t3.chat`.
166
167 The account-scoped repository credentials are consumed by Alchemy while provisioning relay stages; they
168 are not bound into the relay Worker. The production deployment uses an Axiom personal access token,
infra/relay/src/Config.ts
+7
@@ -48,6 +48,12 @@ export interface ApnsCredentials {
48 readonly environment: ApnsEnvironment;
49 }
50
51 +export interface T3ChatSettings {
52 + readonly baseUrl: string;
53 + // Shared with T3 Chat: signs link tokens and authenticates relay calls.
54 + readonly linkSecret: Redacted.Redacted<string>;
55 +}
56 +
57 export class RelayConfiguration extends Context.Service<
58 RelayConfiguration,
59 {
@@ -65,6 +71,7 @@ export class RelayConfiguration extends Context.Service<
71 readonly managedEndpointCleanupMode?: ManagedEndpointCleanupMode;
72 readonly legacyManagedEndpointCleanupMode?: ManagedEndpointCleanupMode;
73 readonly legacyTunnelGraceMinutes?: number;
74 + readonly t3Chat?: T3ChatSettings;
75 }
76 >()("t3code-relay/Config/RelayConfiguration") {}
77
infra/relay/src/environments/ManagedTunnelLimits.test.ts
+125 -14
@@ -4,18 +4,28 @@ import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Semaphore from "effect/Semaphore";
6 import { PgDialect } from "drizzle-orm/pg-core";
7 +import type { RelayT3ChatPlan } from "@t3tools/contracts/relay";
8
9 import * as RelayDb from "../db.ts";
10 import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
11 +import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
12 import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
13
14 class FakeTransaction extends Context.Service<FakeTransaction, { holdsLock: boolean }>()(
15 "t3code-relay/environments/ManagedTunnelLimits.test/FakeTransaction",
16 ) {}
17
18 +interface FakeDbInput {
19 + readonly otherSlots: () => number;
20 + readonly ownSlot?: boolean;
21 + readonly override?: number;
22 + readonly countConditions?: Array<unknown>;
23 +}
24 +
25 // Models Postgres just enough: the advisory lock only works inside a transaction and is held until it ends.
17 -function makeFakeDb(reserved: ReadonlyArray<unknown>, countConditions: Array<unknown> = []) {
26 +function makeFakeDb(input: FakeDbInput) {
27 const userLock = Semaphore.makeUnsafe(1);
28 + const dialect = new PgDialect();
29 return {
30 $client: {
31 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) => {
@@ -42,16 +52,70 @@ function makeFakeDb(reserved: ReadonlyArray<unknown>, countConditions: Array<unk
52 from: (table: unknown) => ({
53 where: (condition: unknown) => {
54 if (table !== relayManagedEndpointAllocations) {
45 - return { limit: () => Effect.succeed([]) };
55 + return {
56 + limit: () =>
57 + Effect.succeed(
58 + input.override === undefined ? [] : [{ maxTunnels: input.override }],
59 + ),
60 + };
61 }
47 - countConditions.push(condition);
48 - return Effect.yieldNow.pipe(Effect.as([{ activeTunnels: reserved.length }]));
62 + input.countConditions?.push(condition);
63 + const countsOthers = dialect
64 + .sqlToQuery(condition as never)
65 + .sql.includes('"relay_managed_endpoint_allocations"."environment_id" <>');
66 + return Effect.yieldNow.pipe(
67 + Effect.andThen(
68 + Effect.sync(() => [
69 + { slots: countsOthers ? input.otherSlots() : input.ownSlot ? 1 : 0 },
70 + ]),
71 + ),
72 + );
73 },
74 }),
75 }),
76 } as unknown as RelayDb.RelayDb["Service"];
77 }
78
79 +const t3ChatLayer = (plan: RelayT3ChatPlan | "lookup-fails", lookups?: Array<string>) =>
80 + Layer.mock(T3ChatAccounts.T3ChatAccounts, {
81 + available: true,
82 + getLink: ({ userId }) => {
83 + lookups?.push(userId);
84 + return plan === "lookup-fails"
85 + ? Effect.fail(
86 + new T3ChatAccounts.T3ChatRequestFailed({
87 + operation: "get-link",
88 + cause: new Error("down"),
89 + }),
90 + )
91 + : Effect.succeed({ email: "theo@example.com", plan });
92 + },
93 + });
94 +
95 +const reserve = (
96 + input: Omit<FakeDbInput, "otherSlots"> & {
97 + readonly activeTunnels: number;
98 + readonly plan: RelayT3ChatPlan | "lookup-fails";
99 + readonly lookups?: Array<string>;
100 + },
101 +) =>
102 + Effect.gen(function* () {
103 + const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
104 + return yield* limits.withCapacity({ userId: "user-1", environmentId: "env-new" }, Effect.void);
105 + }).pipe(
106 + Effect.provide(
107 + ManagedTunnelLimits.layer.pipe(
108 + Layer.provide(
109 + Layer.succeed(
110 + RelayDb.RelayDb,
111 + makeFakeDb({ ...input, otherSlots: () => input.activeTunnels }),
112 + ),
113 + ),
114 + Layer.provide(t3ChatLayer(input.plan, input.lookups)),
115 + ),
116 + ),
117 + );
118 +
119 describe("ManagedTunnelLimits", () => {
120 it.effect("rejects concurrent reservations past the limit", () => {
121 const reserved: Array<string> = [];
@@ -81,7 +145,10 @@ describe("ManagedTunnelLimits", () => {
145 }).pipe(
146 Effect.provide(
147 ManagedTunnelLimits.layer.pipe(
84 - Layer.provide(Layer.succeed(RelayDb.RelayDb, makeFakeDb(reserved))),
148 + Layer.provide(
149 + Layer.succeed(RelayDb.RelayDb, makeFakeDb({ otherSlots: () => reserved.length })),
150 + ),
151 + Layer.provide(t3ChatLayer("free")),
152 ),
153 ),
154 );
@@ -91,8 +158,7 @@ describe("ManagedTunnelLimits", () => {
158 const countConditions: Array<unknown> = [];
159
160 return Effect.gen(function* () {
94 - const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
95 - yield* limits.withCapacity({ userId: "user-1", environmentId: "environment-1" }, Effect.void);
161 + yield* reserve({ activeTunnels: 0, plan: "free", countConditions });
162
163 expect(countConditions).toHaveLength(1);
164 const query = new PgDialect().sqlToQuery(countConditions[0] as never);
@@ -104,12 +170,57 @@ describe("ManagedTunnelLimits", () => {
170 expect(query.sql).toContain(
171 '"relay_environment_links"."updated_at" >= "relay_managed_endpoint_allocations"."updated_at"',
172 );
107 - }).pipe(
108 - Effect.provide(
109 - ManagedTunnelLimits.layer.pipe(
110 - Layer.provide(Layer.succeed(RelayDb.RelayDb, makeFakeDb([], countConditions))),
111 - ),
112 - ),
113 - );
173 + });
174 });
175 +
176 + it.effect("does not ask T3 Chat while the account is under its cap", () =>
177 + Effect.gen(function* () {
178 + const lookups: Array<string> = [];
179 + yield* reserve({ activeTunnels: 2, plan: "free", lookups });
180 + expect(lookups).toEqual([]);
181 + }),
182 + );
183 +
184 + it.effect("raises the cap to the linked T3 Chat plan's limit", () =>
185 + Effect.gen(function* () {
186 + for (const [plan, limit] of [
187 + ["pro", 10],
188 + ["premier", 100],
189 + ] as const) {
190 + yield* reserve({ activeTunnels: limit - 1, plan });
191 + const error = yield* Effect.flip(reserve({ activeTunnels: limit, plan }));
192 + expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: limit });
193 + }
194 + }),
195 + );
196 +
197 + it.effect("keeps the default cap for free plans and failed lookups", () =>
198 + Effect.gen(function* () {
199 + for (const plan of ["free", "lookup-fails"] as const) {
200 + const error = yield* Effect.flip(reserve({ activeTunnels: 3, plan }));
201 + expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: 3 });
202 + }
203 + }),
204 + );
205 +
206 + it.effect("treats a manual override as the exact cap", () =>
207 + Effect.gen(function* () {
208 + const lookups: Array<string> = [];
209 + for (const override of [1, 200]) {
210 + const error = yield* Effect.flip(
211 + reserve({ override, activeTunnels: override, plan: "premier", lookups }),
212 + );
213 + expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: override });
214 + }
215 + expect(lookups).toEqual([]);
216 + }),
217 + );
218 +
219 + it.effect("lets an environment holding a slot relink without asking T3 Chat", () =>
220 + Effect.gen(function* () {
221 + const lookups: Array<string> = [];
222 + yield* reserve({ activeTunnels: 10, plan: "lookup-fails", ownSlot: true, lookups });
223 + expect(lookups).toEqual([]);
224 + }),
225 + );
226 });
infra/relay/src/environments/ManagedTunnelLimits.ts
+63 -34
@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import * as Schema from "effect/Schema";
8 import * as SqlError from "effect/sql/SqlError";
9 +import { T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay";
10
11 import * as RelayDb from "../db.ts";
12 import {
@@ -13,6 +14,7 @@ import {
14 relayManagedEndpointAllocations,
15 relayManagedTunnelLimits,
16 } from "../persistence/schema.ts";
17 +import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
18
19 export const DEFAULT_MANAGED_TUNNEL_LIMIT = 3;
20 // Reserve-to-tunnel takes two Cloudflare calls capped at 8 seconds each; a reservation older than this was abandoned.
@@ -58,6 +60,20 @@ export class ManagedTunnelLimits extends Context.Service<
60
61 const make = Effect.gen(function* () {
62 const db = yield* RelayDb.RelayDb;
63 + const t3Chat = yield* T3ChatAccounts.T3ChatAccounts;
64 +
65 + // Asked only at the cap, so most links never call T3 Chat. Any failure keeps the lower cap.
66 + const t3ChatTunnelLimit = (userId: string) =>
67 + t3Chat.getLink({ userId }).pipe(
68 + Effect.map((link) =>
69 + link && link.plan !== "free" ? T3CHAT_PLAN_TUNNEL_LIMITS[link.plan] : 0,
70 + ),
71 + Effect.catch((error) =>
72 + Effect.logWarning("T3 Chat plan check failed", { userId, error: error.message }).pipe(
73 + Effect.as(0),
74 + ),
75 + ),
76 + );
77
78 return ManagedTunnelLimits.of({
79 withCapacity: Effect.fn("relay.managed_tunnel_limits.with_capacity")(function* <A, E, R>(
@@ -96,7 +112,7 @@ const make = Effect.gen(function* () {
112 }),
113 ),
114 );
99 - const maxTunnels = overrides[0]?.maxTunnels ?? DEFAULT_MANAGED_TUNNEL_LIMIT;
115 + const baseMaxTunnels = overrides[0]?.maxTunnels ?? DEFAULT_MANAGED_TUNNEL_LIMIT;
116
117 const pendingCutoff = DateTime.formatIso(
118 DateTime.subtract(yield* DateTime.now, {
@@ -123,44 +139,57 @@ const make = Effect.gen(function* () {
139 ),
140 ),
141 );
126 - const counted = yield* db
127 - .select({ activeTunnels: count() })
128 - .from(allocation)
129 - .where(
130 - and(
131 - eq(allocation.userId, input.userId),
132 - ne(allocation.environmentId, input.environmentId),
133 - or(
134 - // Reserved but not yet holding a tunnel. Release writes updatedAt = tunnelReleasedAt and
135 - // a relink reserves before rewriting its link, so only a newer reservation counts here.
136 - and(
137 - gt(allocation.updatedAt, pendingCutoff),
138 - or(
142 + const countSlots = (environment: typeof eq) =>
143 + db
144 + .select({ slots: count() })
145 + .from(allocation)
146 + .where(
147 + and(
148 + eq(allocation.userId, input.userId),
149 + environment(allocation.environmentId, input.environmentId),
150 + or(
151 + // Reserved but not yet holding a tunnel. Release writes updatedAt = tunnelReleasedAt and
152 + // a relink reserves before rewriting its link, so only a newer reservation counts here.
153 + and(
154 + gt(allocation.updatedAt, pendingCutoff),
155 + or(
156 + isNull(allocation.tunnelReleasedAt),
157 + gt(allocation.updatedAt, allocation.tunnelReleasedAt),
158 + ),
159 + not(withdrawnLink(allocation.updatedAt)),
160 + ),
161 + and(
162 + isNotNull(allocation.tunnelId),
163 isNull(allocation.tunnelReleasedAt),
140 - gt(allocation.updatedAt, allocation.tunnelReleasedAt),
164 + not(withdrawnLink()),
165 ),
142 - not(withdrawnLink(allocation.updatedAt)),
143 - ),
144 - and(
145 - isNotNull(allocation.tunnelId),
146 - isNull(allocation.tunnelReleasedAt),
147 - not(withdrawnLink()),
166 ),
167 ),
150 - ),
151 - )
152 - .pipe(
153 - Effect.mapError(
154 - (cause) =>
155 - new ManagedTunnelLimitPersistenceError({
156 - operation: "count-tunnels",
157 - userId: input.userId,
158 - cause,
159 - }),
160 - ),
161 - );
162 - const activeTunnels = counted[0]?.activeTunnels ?? 0;
168 + )
169 + .pipe(
170 + Effect.map((rows) => rows[0]?.slots ?? 0),
171 + Effect.mapError(
172 + (cause) =>
173 + new ManagedTunnelLimitPersistenceError({
174 + operation: "count-tunnels",
175 + userId: input.userId,
176 + cause,
177 + }),
178 + ),
179 + );
180 + const activeTunnels = yield* countSlots(ne);
181 + if (activeTunnels < baseMaxTunnels) return yield* reserve;
182 +
183 + // An environment that already holds a counted slot relinks without asking T3 Chat,
184 + // so a downgrade or a T3 Chat outage only blocks new environments.
185 + if ((yield* countSlots(eq)) > 0) return yield* reserve;
186
187 + // A manual override is the exact cap; a T3 Chat plan raises only the default.
188 + // Runs under the user lock, bounded by the T3 Chat request timeout.
189 + const maxTunnels =
190 + t3Chat.available && overrides.length === 0
191 + ? Math.max(baseMaxTunnels, yield* t3ChatTunnelLimit(input.userId))
192 + : baseMaxTunnels;
193 if (activeTunnels >= maxTunnels) {
194 return yield* new ManagedTunnelLimitExceeded({
195 userId: input.userId,
infra/relay/src/http/Api.test.ts
+4
@@ -66,6 +66,7 @@ import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllo
66 import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";
67 import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts";
68 import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
69 +import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
70
71 vi.mock("@clerk/backend", () => ({
72 createClerkClient: vi.fn(),
@@ -128,6 +129,7 @@ describe("managed endpoint provisioning errors", () => {
129 Layer.mock(EnvironmentLinks.EnvironmentLinks, {}),
130 Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}),
131 Layer.mock(Devices.Devices, {}),
132 + Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
133 ),
134 ),
135 Layer.provideMerge(
@@ -238,6 +240,7 @@ describe("device listing compatibility", () => {
240 return Effect.succeed([iphone, android]);
241 },
242 }),
243 + Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
244 ),
245 ),
246 Layer.provideMerge(
@@ -318,6 +321,7 @@ describe("Cloudflare rate-limit retry hint", () => {
321 Layer.mock(EnvironmentLinks.EnvironmentLinks, {}),
322 Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}),
323 Layer.mock(Devices.Devices, {}),
324 + Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
325 ),
326 ),
327 Layer.provideMerge(
infra/relay/src/http/Api.ts
+37
@@ -77,6 +77,7 @@ import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvide
77 import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";
78 import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
79 import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts";
80 +import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
81 import { withSpanAttributes } from "../observability.ts";
82 import { isRelayHookPath, redactRelayHookUrl } from "../hooks/HookForwarder.ts";
83 import * as RelayDb from "../db.ts";
@@ -823,6 +824,7 @@ export const layerClientApi = HttpApiBuilder.group(
824 const links = yield* EnvironmentLinks.EnvironmentLinks;
825 const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
826 const devices = yield* Devices.Devices;
827 + const t3Chat = yield* T3ChatAccounts.T3ChatAccounts;
828 return handlers
829 .handle(
830 "listEnvironments",
@@ -989,6 +991,41 @@ export const layerClientApi = HttpApiBuilder.group(
991 .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
992 return { ok: released };
993 }, mapRelayCommonApiErrors("not_authorized")),
994 + )
995 + .handle(
996 + "getT3ChatLink",
997 + Effect.fn("relay.api.client.getT3ChatLink")(function* () {
998 + yield* appendRelayCredentialResponseHeaders;
999 + if (!t3Chat.available) return { available: false, link: null };
1000 + const { userId } = yield* RelayClientPrincipal;
1001 + const link = yield* t3Chat
1002 + .getLink({ userId })
1003 + .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
1004 + return { available: true, link };
1005 + }, mapRelayCommonApiErrors("not_authorized")),
1006 + )
1007 + .handle(
1008 + "createT3ChatLinkRequest",
1009 + Effect.fn("relay.api.client.createT3ChatLinkRequest")(function* () {
1010 + const { userId } = yield* RelayClientPrincipal;
1011 + const url = yield* t3Chat.createLinkUrl({ userId }).pipe(
1012 + Effect.catchTags({
1013 + T3ChatNotConfigured: () => relayInternalErrorResponse("internal_error"),
1014 + ClerkUserLookupFailed: () => relayInternalErrorResponse("upstream_unavailable"),
1015 + }),
1016 + );
1017 + return { url };
1018 + }, mapRelayCommonApiErrors("not_authorized")),
1019 + )
1020 + .handle(
1021 + "unlinkT3Chat",
1022 + Effect.fn("relay.api.client.unlinkT3Chat")(function* () {
1023 + const { userId } = yield* RelayClientPrincipal;
1024 + yield* t3Chat
1025 + .unlink({ userId })
1026 + .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
1027 + return { ok: true };
1028 + }, mapRelayCommonApiErrors("not_authorized")),
1029 );
1030 }),
1031 );
infra/relay/src/t3chat/T3ChatAccounts.test.ts new
+176
@@ -0,0 +1,176 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import { vi } from "vite-plus/test";
3 +import * as Effect from "effect/Effect";
4 +import * as Fiber from "effect/Fiber";
5 +import * as TestClock from "effect/testing/TestClock";
6 +import * as Layer from "effect/Layer";
7 +import * as Redacted from "effect/Redacted";
8 +import * as HttpClient from "effect/http/HttpClient";
9 +import * as HttpClientResponse from "effect/http/HttpClientResponse";
10 +
11 +import * as RelayConfiguration from "../Config.ts";
12 +import * as T3ChatAccounts from "./T3ChatAccounts.ts";
13 +
14 +const clerk = vi.hoisted(() => ({
15 + getUser: async (): Promise<unknown> => ({ primaryEmailAddress: { emailAddress: "a@b.co" } }),
16 +}));
17 +vi.mock("@clerk/backend", () => ({
18 + createClerkClient: () => ({ users: { getUser: () => clerk.getUser() } }),
19 +}));
20 +
21 +const SECRET = "shared-link-secret";
22 +
23 +const relaySettings = (
24 + t3Chat: RelayConfiguration.T3ChatSettings | null,
25 +): RelayConfiguration.RelayConfiguration["Service"] => ({
26 + relayIssuer: "https://relay.example.test",
27 + apns: null,
28 + clerkSecretKey: Redacted.make("clerk-secret-key"),
29 + clerkPublishableKey: "pk_test_test",
30 + clerkJwtAudience: "t3-code-relay",
31 + apnsDeliveryJobSigningSecret: Redacted.make("apns-delivery-secret"),
32 + cloudMintPrivateKey: Redacted.make("cloud-mint-private-key"),
33 + cloudMintPublicKey: "cloud-mint-public-key",
34 + managedEndpointBaseDomain: undefined,
35 + managedEndpointNamespace: undefined,
36 + ...(t3Chat ? { t3Chat } : {}),
37 +});
38 +
39 +const fakeT3Chat = (body: unknown, status = 200) => {
40 + const requests: Array<{ url: string; authorization: string | undefined; body: unknown }> = [];
41 + const client = HttpClient.make((request) =>
42 + Effect.gen(function* () {
43 + requests.push({
44 + url: request.url,
45 + authorization: request.headers["authorization"],
46 + body:
47 + request.body._tag === "Uint8Array"
48 + ? JSON.parse(new TextDecoder().decode(request.body.body))
49 + : null,
50 + });
51 + return HttpClientResponse.fromWeb(
52 + request,
53 + new Response(JSON.stringify(body), {
54 + status,
55 + headers: { "content-type": "application/json" },
56 + }),
57 + );
58 + }),
59 + );
60 + return { client, requests };
61 +};
62 +
63 +const provide = (
64 + client: HttpClient.HttpClient,
65 + t3Chat: RelayConfiguration.T3ChatSettings | null = {
66 + baseUrl: "https://chat.example.test",
67 + linkSecret: Redacted.make(SECRET),
68 + },
69 +) =>
70 + Effect.provide(
71 + T3ChatAccounts.layer.pipe(
72 + Layer.provide(RelayConfiguration.layer(relaySettings(t3Chat))),
73 + Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
74 + ),
75 + );
76 +
77 +describe("T3ChatAccounts", () => {
78 + it.effect("signs link tokens in the format T3 Chat verifies", () =>
79 + Effect.gen(function* () {
80 + const accounts = yield* T3ChatAccounts.T3ChatAccounts;
81 + const url = new URL(yield* accounts.createLinkUrl({ userId: "user_1" }));
82 + expect(`${url.origin}${url.pathname}`).toBe("https://chat.example.test/link/t3code");
83 +
84 + const [payload = "", signature = ""] = (url.searchParams.get("token") ?? "").split(".");
85 + // Verify with Web Crypto, as T3 Chat does, rather than the signing library.
86 + const verified = yield* Effect.promise(async () => {
87 + const encoder = new TextEncoder();
88 + const key = await crypto.subtle.importKey(
89 + "raw",
90 + encoder.encode(SECRET),
91 + { name: "HMAC", hash: "SHA-256" },
92 + false,
93 + ["verify"],
94 + );
95 + return crypto.subtle.verify(
96 + "HMAC",
97 + key,
98 + Buffer.from(signature, "base64url"),
99 + encoder.encode(payload),
100 + );
101 + });
102 + expect(verified).toBe(true);
103 + expect(JSON.parse(Buffer.from(payload, "base64url").toString("utf8"))).toEqual({
104 + v: 1,
105 + sub: "user_1",
106 + email: "a@b.co",
107 + exp: 600,
108 + });
109 + }).pipe(provide(fakeT3Chat({}).client)),
110 + );
111 +
112 + it.effect("asks T3 Chat for the link with the shared secret", () => {
113 + const t3Chat = fakeT3Chat({ link: { email: "theo@t3.chat", plan: "premier", linkedAt: 1 } });
114 + return Effect.gen(function* () {
115 + const accounts = yield* T3ChatAccounts.T3ChatAccounts;
116 + const link = yield* accounts.getLink({ userId: "user_1" });
117 + expect(link).toEqual({ email: "theo@t3.chat", plan: "premier" });
118 + expect(t3Chat.requests).toEqual([
119 + {
120 + url: "https://chat.example.test/api/t3code/link",
121 + authorization: `Bearer ${SECRET}`,
122 + body: { clerkUserId: "user_1" },
123 + },
124 + ]);
125 + }).pipe(provide(t3Chat.client));
126 + });
127 +
128 + it.effect("fails instead of guessing when T3 Chat errors", () =>
129 + Effect.gen(function* () {
130 + const accounts = yield* T3ChatAccounts.T3ChatAccounts;
131 + const error = yield* Effect.flip(accounts.getLink({ userId: "user_1" }));
132 + expect(error._tag).toBe("T3ChatRequestFailed");
133 + }).pipe(provide(fakeT3Chat({ error: "nope" }, 401).client)),
134 + );
135 +
136 + it.effect("times out when T3 Chat stalls while sending the body", () => {
137 + const client = HttpClient.make((request) =>
138 + Effect.succeed(
139 + HttpClientResponse.fromWeb(
140 + request,
141 + new Response(new ReadableStream({ start: () => {} }), { status: 200 }),
142 + ),
143 + ),
144 + );
145 + return Effect.gen(function* () {
146 + const accounts = yield* T3ChatAccounts.T3ChatAccounts;
147 + const fiber = yield* Effect.forkChild(Effect.flip(accounts.getLink({ userId: "user_1" })));
148 + yield* TestClock.adjust("5 seconds");
149 + const error = yield* Fiber.join(fiber);
150 + expect(error._tag).toBe("T3ChatRequestFailed");
151 + }).pipe(provide(client));
152 + });
153 +
154 + it.effect("times out when Clerk stalls on the email lookup", () =>
155 + Effect.gen(function* () {
156 + const getUser = clerk.getUser;
157 + clerk.getUser = () => new Promise(() => {});
158 + const accounts = yield* T3ChatAccounts.T3ChatAccounts;
159 + const fiber = yield* Effect.forkChild(Effect.flip(accounts.createLinkUrl({ userId: "u" })));
160 + yield* TestClock.adjust("5 seconds");
161 + const error = yield* Fiber.join(fiber).pipe(
162 + Effect.ensuring(Effect.sync(() => (clerk.getUser = getUser))),
163 + );
164 + expect(error._tag).toBe("ClerkUserLookupFailed");
165 + }).pipe(provide(fakeT3Chat({}).client)),
166 + );
167 +
168 + it.effect("reports itself unavailable without a shared secret", () =>
169 + Effect.gen(function* () {
170 + const accounts = yield* T3ChatAccounts.T3ChatAccounts;
171 + expect(accounts.available).toBe(false);
172 + const error = yield* Effect.flip(accounts.getLink({ userId: "user_1" }));
173 + expect(error._tag).toBe("T3ChatNotConfigured");
174 + }).pipe(provide(fakeT3Chat({}).client, null)),
175 + );
176 +});
infra/relay/src/t3chat/T3ChatAccounts.ts new
+166
@@ -0,0 +1,166 @@
1 +import { createClerkClient } from "@clerk/backend";
2 +import { hmac } from "@noble/hashes/hmac";
3 +import { sha256 } from "@noble/hashes/sha2";
4 +import * as Context from "effect/Context";
5 +import * as DateTime from "effect/DateTime";
6 +import * as Effect from "effect/Effect";
7 +import * as Layer from "effect/Layer";
8 +import * as Redacted from "effect/Redacted";
9 +import * as Schema from "effect/Schema";
10 +import * as Base64Url from "effect/encoding/Base64Url";
11 +import * as HttpClient from "effect/http/HttpClient";
12 +import * as HttpClientRequest from "effect/http/HttpClientRequest";
13 +import * as HttpClientResponse from "effect/http/HttpClientResponse";
14 +import { RelayT3ChatLink } from "@t3tools/contracts/relay";
15 +
16 +import * as RelayConfiguration from "../Config.ts";
17 +
18 +const LINK_TOKEN_TTL_SECONDS = 10 * 60;
19 +const T3CHAT_REQUEST_TIMEOUT = "5 seconds";
20 +
21 +const decodeLinkResponse = Schema.decodeUnknownEffect(
22 + Schema.Struct({ link: Schema.NullOr(RelayT3ChatLink) }),
23 +);
24 +
25 +export class T3ChatNotConfigured extends Schema.TaggedError<T3ChatNotConfigured>()(
26 + "T3ChatNotConfigured",
27 + {},
28 +) {
29 + override get message(): string {
30 + return "T3 Chat linking is not configured on this relay";
31 + }
32 +}
33 +
34 +export class ClerkUserLookupFailed extends Schema.TaggedError<ClerkUserLookupFailed>()(
35 + "ClerkUserLookupFailed",
36 + { cause: Schema.Defect() },
37 +) {
38 + override get message(): string {
39 + return "Could not read the Clerk user's primary email";
40 + }
41 +}
42 +
43 +export class T3ChatRequestFailed extends Schema.TaggedError<T3ChatRequestFailed>()(
44 + "T3ChatRequestFailed",
45 + {
46 + operation: Schema.Literals(["get-link", "unlink"]),
47 + cause: Schema.Defect(),
48 + },
49 +) {
50 + override get message(): string {
51 + return `T3 Chat '${this.operation}' request failed`;
52 + }
53 +}
54 +
55 +/**
56 + * Bridge to T3 Chat. T3 Chat owns the account link; the relay
57 + * signs link requests and asks T3 Chat for the linked account's plan.
58 + */
59 +export class T3ChatAccounts extends Context.Service<
60 + T3ChatAccounts,
61 + {
62 + readonly available: boolean;
63 + readonly createLinkUrl: (input: {
64 + readonly userId: string;
65 + }) => Effect.Effect<string, T3ChatNotConfigured | ClerkUserLookupFailed>;
66 + readonly getLink: (input: {
67 + readonly userId: string;
68 + }) => Effect.Effect<RelayT3ChatLink | null, T3ChatNotConfigured | T3ChatRequestFailed>;
69 + readonly unlink: (input: {
70 + readonly userId: string;
71 + }) => Effect.Effect<void, T3ChatNotConfigured | T3ChatRequestFailed>;
72 + }
73 +>()("t3code-relay/t3chat/T3ChatAccounts") {}
74 +
75 +/** Token format shared with T3 Chat: `<base64url JSON payload>.<base64url HMAC-SHA256>`. */
76 +export const signLinkToken = (
77 + secret: string,
78 + payload: { readonly sub: string; readonly email: string; readonly exp: number },
79 +) => {
80 + const encoded = Base64Url.encode(JSON.stringify({ v: 1, ...payload }));
81 + const signature = hmac(
82 + sha256,
83 + new TextEncoder().encode(secret),
84 + new TextEncoder().encode(encoded),
85 + );
86 + return `${encoded}.${Base64Url.encode(signature)}`;
87 +};
88 +
89 +export const make = Effect.gen(function* () {
90 + const config = yield* RelayConfiguration.RelayConfiguration;
91 + const client = yield* HttpClient.HttpClient;
92 + const settings = config.t3Chat;
93 +
94 + const requireSettings = settings
95 + ? Effect.succeed(settings)
96 + : Effect.fail(new T3ChatNotConfigured());
97 +
98 + // The timeout covers the body read so a stalled response still fails fast.
99 + const post = Effect.fn("relay.t3chat.post")(function* (
100 + operation: T3ChatRequestFailed["operation"],
101 + path: string,
102 + userId: string,
103 + ) {
104 + const { baseUrl, linkSecret } = yield* requireSettings;
105 + return yield* HttpClientRequest.post(new URL(path, baseUrl).toString()).pipe(
106 + HttpClientRequest.bearerToken(Redacted.value(linkSecret)),
107 + HttpClientRequest.bodyJsonUnsafe({ clerkUserId: userId }),
108 + client.execute,
109 + Effect.flatMap(HttpClientResponse.filterStatusOk),
110 + Effect.flatMap((response) => response.json),
111 + Effect.timeout(T3CHAT_REQUEST_TIMEOUT),
112 + Effect.mapError((cause) => new T3ChatRequestFailed({ operation, cause })),
113 + );
114 + });
115 +
116 + const lookupClerkPrimaryEmail = Effect.fn("relay.t3chat.lookup_clerk_primary_email")(function* (
117 + userId: string,
118 + ) {
119 + return yield* Effect.tryPromise({
120 + try: async () => {
121 + const user = await createClerkClient({
122 + secretKey: Redacted.value(config.clerkSecretKey),
123 + publishableKey: config.clerkPublishableKey,
124 + }).users.getUser(userId);
125 + const email = user.primaryEmailAddress?.emailAddress;
126 + if (!email) throw new Error("Clerk user has no primary email address.");
127 + return email;
128 + },
129 + catch: (cause) => new ClerkUserLookupFailed({ cause }),
130 + }).pipe(
131 + Effect.timeoutOrElse({
132 + duration: T3CHAT_REQUEST_TIMEOUT,
133 + orElse: () => Effect.fail(new ClerkUserLookupFailed({ cause: "timed out" })),
134 + }),
135 + );
136 + });
137 +
138 + return T3ChatAccounts.of({
139 + available: settings !== undefined,
140 + createLinkUrl: Effect.fn("relay.t3chat.create_link_url")(function* (input) {
141 + const { baseUrl, linkSecret } = yield* requireSettings;
142 + const email = yield* lookupClerkPrimaryEmail(input.userId);
143 + const now = yield* DateTime.now;
144 + const token = signLinkToken(Redacted.value(linkSecret), {
145 + sub: input.userId,
146 + email,
147 + exp: Math.floor(now.epochMilliseconds / 1_000) + LINK_TOKEN_TTL_SECONDS,
148 + });
149 + const url = new URL("/link/t3code", baseUrl);
150 + url.searchParams.set("token", token);
151 + return url.toString();
152 + }),
153 + getLink: Effect.fn("relay.t3chat.get_link")(function* (input) {
154 + const body = yield* post("get-link", "/api/t3code/link", input.userId);
155 + const decoded = yield* decodeLinkResponse(body).pipe(
156 + Effect.mapError((cause) => new T3ChatRequestFailed({ operation: "get-link", cause })),
157 + );
158 + return decoded.link;
159 + }),
160 + unlink: Effect.fn("relay.t3chat.unlink")(function* (input) {
161 + yield* post("unlink", "/api/t3code/unlink", input.userId);
162 + }),
163 + });
164 +});
165 +
166 +export const layer = Layer.effect(T3ChatAccounts, make);
infra/relay/src/worker.ts
+14 -1
@@ -64,6 +64,7 @@ import * as EnvironmentPublishSignatures from "./environments/EnvironmentPublish
64 import * as ManagedEndpointProvider from "./environments/ManagedEndpointProvider.ts";
65 import * as ManagedEndpointReaper from "./environments/ManagedEndpointReaper.ts";
66 import * as ManagedTunnelLimits from "./environments/ManagedTunnelLimits.ts";
67 +import * as T3ChatAccounts from "./t3chat/T3ChatAccounts.ts";
68 import * as MobileRegistrations from "./agentActivity/MobileRegistrations.ts";
69 import * as HookForwarder from "./hooks/HookForwarder.ts";
70 import * as HeldHooks from "./hooks/HeldHooks.ts";
@@ -166,6 +167,15 @@ export const layer = Api.make(
167 const clerkSecretKey = yield* Config.Redacted("CLERK_SECRET_KEY");
168 const clerkPublishableKey = yield* Config.String("CLERK_PUBLISHABLE_KEY");
169 const clerkJwtAudience = yield* Config.String("CLERK_JWT_AUDIENCE");
170 + const t3ChatLinkSecret = Option.getOrUndefined(
171 + Option.filter(
172 + yield* Config.option(Config.Redacted("T3CHAT_LINK_SECRET")),
173 + (value) => Redacted.value(value).trim().length > 0,
174 + ),
175 + );
176 + const t3ChatBaseUrl = yield* Config.String("T3CHAT_URL").pipe(
177 + Config.withDefault("https://t3.chat"),
178 + );
179
180 const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey;
181 const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey;
@@ -236,6 +246,9 @@ export const layer = Api.make(
246 managedEndpointCleanupMode,
247 legacyManagedEndpointCleanupMode,
248 ...(legacyTunnelGraceMinutes === undefined ? {} : { legacyTunnelGraceMinutes }),
249 + ...(t3ChatLinkSecret
250 + ? { t3Chat: { baseUrl: t3ChatBaseUrl, linkSecret: t3ChatLinkSecret } }
251 + : {}),
252 });
253 });
254
@@ -329,7 +342,7 @@ export const layer = Api.make(
342 ManagedTunnelLimits.layer,
343 ),
344 ),
332 - Layer.provideMerge(LiveActivities.layer),
345 + Layer.provideMerge(Layer.mergeAll(LiveActivities.layer, T3ChatAccounts.layer)),
346 Layer.provideMerge(DeliveryAttempts.layer),
347 Layer.provideMerge(RelayTokens.layer),
348 Layer.provideMerge(
packages/client-runtime/src/authorization/layer.test.ts
+3
@@ -180,6 +180,9 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
180 createEnvironmentLinkChallenge: unexpected,
181 linkEnvironment: unexpected,
182 unlinkEnvironment: unexpected,
183 + getT3ChatLink: unexpected,
184 + createT3ChatLinkRequest: unexpected,
185 + unlinkT3Chat: unexpected,
186 getEnvironmentStatus: unexpected,
187 connectEnvironment: (request) =>
188 Effect.gen(function* () {
packages/client-runtime/src/connection/supervisor.test.ts
+3
@@ -1181,6 +1181,9 @@ describe("EnvironmentSupervisor", () => {
1181 createEnvironmentLinkChallenge: unused,
1182 linkEnvironment: unused,
1183 unlinkEnvironment: unused,
1184 + getT3ChatLink: unused,
1185 + createT3ChatLinkRequest: unused,
1186 + unlinkT3Chat: unused,
1187 getEnvironmentStatus: unused,
1188 connectEnvironment: Effect.fn("TestConnectionHttp.connectEnvironment")(function* () {
1189 yield* Ref.update(bootstrapCalls, (count) => count + 1);
packages/client-runtime/src/relay/discovery.test.ts
+6
@@ -110,6 +110,9 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
110 createEnvironmentLinkChallenge: () => Effect.die("unused"),
111 linkEnvironment: () => Effect.die("unused"),
112 unlinkEnvironment: () => Effect.die("unused"),
113 + getT3ChatLink: () => Effect.die("unused"),
114 + createT3ChatLinkRequest: () => Effect.die("unused"),
115 + unlinkT3Chat: () => Effect.die("unused"),
116 connectEnvironment: () => Effect.die("unused"),
117 registerDevice: () => Effect.die("unused"),
118 unregisterDevice: () => Effect.die("unused"),
@@ -275,6 +278,9 @@ describe("RelayEnvironmentDiscovery", () => {
278 createEnvironmentLinkChallenge: () => Effect.die("unused"),
279 linkEnvironment: () => Effect.die("unused"),
280 unlinkEnvironment: () => Effect.die("unused"),
281 + getT3ChatLink: () => Effect.die("unused"),
282 + createT3ChatLinkRequest: () => Effect.die("unused"),
283 + unlinkT3Chat: () => Effect.die("unused"),
284 connectEnvironment: () => Effect.die("unused"),
285 registerDevice: () => Effect.die("unused"),
286 unregisterDevice: () => Effect.die("unused"),
packages/client-runtime/src/relay/errorPresentation.ts
+8 -2
@@ -1,5 +1,9 @@
1 import type { DpopFailureReason } from "@t3tools/contracts";
2 -import type { RelayEnvironmentStatusResponse, RelayProtectedError } from "@t3tools/contracts/relay";
2 +import {
3 + T3CHAT_PLAN_TUNNEL_LIMITS,
4 + type RelayEnvironmentStatusResponse,
5 + type RelayProtectedError,
6 +} from "@t3tools/contracts/relay";
7
8 export const DPOP_CLOCK_HINT =
9 "Hint: Check that automatic date and time is enabled on both devices, then try again.";
@@ -63,7 +67,9 @@ export function relayProtectedErrorMessage(error: RelayProtectedError): string {
67 error.provisioningStage ? ` Failed stage: ${error.provisioningStage}.` : ""
68 }`;
69 case "RelayEnvironmentLinkLimitExceededError":
66 - return `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`;
70 + return error.maxTunnels < T3CHAT_PLAN_TUNNEL_LIMITS.premier
71 + ? `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment, or link a paid T3 Chat account in your T3 Connect account settings on web or desktop. Pro raises the default limit to ${T3CHAT_PLAN_TUNNEL_LIMITS.pro} and Premier to ${T3CHAT_PLAN_TUNNEL_LIMITS.premier}.`
72 + : `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`;
73 case "RelayAgentActivityPublishProofExpiredError":
74 return "Relay rejected an expired agent activity publish proof.";
75 case "RelayAgentActivityPublishProofInvalidError":
packages/client-runtime/src/relay/managedRelay.ts
+56
@@ -22,6 +22,8 @@ import {
22 RelayMobileRegistrationScope,
23 type RelayOkResponse,
24 type RelayPublicClientId,
25 + type RelayT3ChatLinkRequestResponse,
26 + type RelayT3ChatLinkResponse,
27 RelayRegisterDeviceEndpoint,
28 RelayAgentActivitySnapshotEndpoint,
29 RelayRegisterLiveActivityEndpoint,
@@ -96,6 +98,9 @@ export const ManagedRelayRequestAction = Schema.Literals([
98 "unregister relay mobile device",
99 "register relay live activity",
100 "read relay agent activity snapshot",
101 + "read linked T3 Chat account",
102 + "start T3 Chat linking",
103 + "unlink T3 Chat account",
104 ]);
105 export type ManagedRelayRequestAction = typeof ManagedRelayRequestAction.Type;
106
@@ -112,6 +117,9 @@ export const ManagedRelayRequestActivity = Schema.Literals([
117 "Relay mobile device unregistration",
118 "Relay Live Activity registration",
119 "Relay agent activity snapshot",
120 + "Relay T3 Chat link lookup",
121 + "Relay T3 Chat link request",
122 + "Relay T3 Chat unlinking",
123 ]);
124 export type ManagedRelayRequestActivity = typeof ManagedRelayRequestActivity.Type;
125
@@ -272,6 +280,15 @@ export class ManagedRelayClient extends Context.Service<
280 readonly clerkToken: string;
281 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
282 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
283 + readonly getT3ChatLink: (input: {
284 + readonly clerkToken: string;
285 + }) => Effect.Effect<RelayT3ChatLinkResponse, ManagedRelayClientError>;
286 + readonly createT3ChatLinkRequest: (input: {
287 + readonly clerkToken: string;
288 + }) => Effect.Effect<RelayT3ChatLinkRequestResponse, ManagedRelayClientError>;
289 + readonly unlinkT3Chat: (input: {
290 + readonly clerkToken: string;
291 + }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
292 readonly getEnvironmentStatus: (input: {
293 readonly clerkToken: string;
294 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
@@ -426,6 +443,9 @@ function disabledManagedRelayClient(relayUrl: string): ManagedRelayClient["Servi
443 ),
444 linkEnvironment: unavailable("clientRuntime.managedRelay.linkEnvironment"),
445 unlinkEnvironment: unavailable("clientRuntime.managedRelay.unlinkEnvironment"),
446 + getT3ChatLink: unavailable("clientRuntime.managedRelay.getT3ChatLink"),
447 + createT3ChatLinkRequest: unavailable("clientRuntime.managedRelay.createT3ChatLinkRequest"),
448 + unlinkT3Chat: unavailable("clientRuntime.managedRelay.unlinkT3Chat"),
449 getEnvironmentStatus: unavailable("clientRuntime.managedRelay.getEnvironmentStatus"),
450 connectEnvironment: unavailable("clientRuntime.managedRelay.connectEnvironment"),
451 registerDevice: unavailable("clientRuntime.managedRelay.registerDevice"),
@@ -791,6 +811,42 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* (
811 Effect.withSpan("clientRuntime.managedRelay.unlinkEnvironment"),
812 withRelayClientTracing,
813 ),
814 + getT3ChatLink: Effect.fnUntraced(
815 + function* (input) {
816 + return yield* client.client
817 + .getT3ChatLink({ headers: bearerHeaders(input.clerkToken) })
818 + .pipe(
819 + Effect.mapError(relayRequestError("read linked T3 Chat account")),
820 + timeoutRelayRequest("Relay T3 Chat link lookup"),
821 + );
822 + },
823 + Effect.withSpan("clientRuntime.managedRelay.getT3ChatLink"),
824 + withRelayClientTracing,
825 + ),
826 + createT3ChatLinkRequest: Effect.fnUntraced(
827 + function* (input) {
828 + return yield* client.client
829 + .createT3ChatLinkRequest({ headers: bearerHeaders(input.clerkToken) })
830 + .pipe(
831 + Effect.mapError(relayRequestError("start T3 Chat linking")),
832 + timeoutRelayRequest("Relay T3 Chat link request"),
833 + );
834 + },
835 + Effect.withSpan("clientRuntime.managedRelay.createT3ChatLinkRequest"),
836 + withRelayClientTracing,
837 + ),
838 + unlinkT3Chat: Effect.fnUntraced(
839 + function* (input) {
840 + return yield* client.client
841 + .unlinkT3Chat({ headers: bearerHeaders(input.clerkToken) })
842 + .pipe(
843 + Effect.mapError(relayRequestError("unlink T3 Chat account")),
844 + timeoutRelayRequest("Relay T3 Chat unlinking"),
845 + );
846 + },
847 + Effect.withSpan("clientRuntime.managedRelay.unlinkT3Chat"),
848 + withRelayClientTracing,
849 + ),
850 getEnvironmentStatus: Effect.fnUntraced(
851 function* (input) {
852 yield* Effect.annotateCurrentSpan({
packages/client-runtime/src/relay/managedRelayState.test.ts
+3
@@ -66,6 +66,9 @@ function createClient(overrides?: Partial<ManagedRelay.ManagedRelayClient["Servi
66 createEnvironmentLinkChallenge: () => Effect.die("unused"),
67 linkEnvironment: () => Effect.die("unused"),
68 unlinkEnvironment: () => Effect.die("unused"),
69 + getT3ChatLink: () => Effect.die("unused"),
70 + createT3ChatLinkRequest: () => Effect.die("unused"),
71 + unlinkT3Chat: () => Effect.die("unused"),
72 getEnvironmentStatus: () =>
73 Effect.succeed({
74 environmentId: environment.environmentId,
packages/client-runtime/src/relay/managedRelayState.ts
+68 -8
@@ -42,7 +42,7 @@ export interface ManagedRelaySnapshotState<A> {
42 }
43
44 export interface ManagedRelayQueryEvent {
45 - readonly operation: "environments" | "devices";
45 + readonly operation: "environments" | "devices" | "t3chat-link";
46 readonly stage: "clerk-token" | "relay-request";
47 readonly phase: "start" | "success" | "failure";
48 readonly accountId: string;
@@ -178,23 +178,56 @@ function readSessionClerkToken(
178 );
179 }
180
181 +function requireSessionClerkToken(
182 + registry: AtomRegistry.AtomRegistry,
183 + accountId: string,
184 + action: string,
185 +): Effect.Effect<string, ManagedRelaySessionError> {
186 + const session = registry.get(managedRelaySessionAtom);
187 + if (!session || session.accountId !== accountId) {
188 + return Effect.fail(
189 + new ManagedRelaySessionError({ message: `Sign in to T3 Connect before ${action}.` }),
190 + );
191 + }
192 + return readSessionClerkToken(session);
193 +}
194 +
195 export const deregisterManagedRelayEnvironment = Effect.fn(
196 "clientRuntime.managedRelaySession.deregisterEnvironment",
197 )(function* (
198 registry: AtomRegistry.AtomRegistry,
199 input: { readonly accountId: string; readonly environmentId: EnvironmentId },
200 ) {
187 - const session = registry.get(managedRelaySessionAtom);
188 - if (!session || session.accountId !== input.accountId) {
189 - return yield* new ManagedRelaySessionError({
190 - message: "Sign in to T3 Connect before deregistering an environment.",
191 - });
192 - }
193 - const clerkToken = yield* readSessionClerkToken(session);
201 + const clerkToken = yield* requireSessionClerkToken(
202 + registry,
203 + input.accountId,
204 + "deregistering an environment",
205 + );
206 const relay = yield* ManagedRelay.ManagedRelayClient;
207 yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId });
208 });
209
210 +/** Returns the T3 Chat page URL where the signed-in user confirms the link. */
211 +export const createManagedRelayT3ChatLinkRequest = Effect.fn(
212 + "clientRuntime.managedRelaySession.createT3ChatLinkRequest",
213 +)(function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) {
214 + const clerkToken = yield* requireSessionClerkToken(registry, input.accountId, "linking T3 Chat");
215 + const relay = yield* ManagedRelay.ManagedRelayClient;
216 + return (yield* relay.createT3ChatLinkRequest({ clerkToken })).url;
217 +});
218 +
219 +export const unlinkManagedRelayT3Chat = Effect.fn("clientRuntime.managedRelaySession.unlinkT3Chat")(
220 + function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) {
221 + const clerkToken = yield* requireSessionClerkToken(
222 + registry,
223 + input.accountId,
224 + "unlinking T3 Chat",
225 + );
226 + const relay = yield* ManagedRelay.ManagedRelayClient;
227 + yield* relay.unlinkT3Chat({ clerkToken });
228 + },
229 +);
230 +
231 function requireClerkToken(
232 get: Atom.AtomContext,
233 accountId: string,
@@ -333,14 +366,41 @@ export function createManagedRelayQueryManager(
366 ),
367 );
368
369 + const t3ChatLinkAtom = Atom.family((accountId: string) =>
370 + runtime
371 + .atom((get) =>
372 + Effect.gen(function* () {
373 + const base = { operation: "t3chat-link" as const, accountId };
374 + const clerkToken = yield* observe(
375 + { ...base, stage: "clerk-token" },
376 + requireClerkToken(get, accountId),
377 + );
378 + const relay = yield* ManagedRelay.ManagedRelayClient;
379 + return yield* observe(
380 + { ...base, stage: "relay-request" },
381 + relay.getT3ChatLink({ clerkToken }),
382 + );
383 + }),
384 + )
385 + .pipe(
386 + Atom.swr({ staleTime, revalidateOnMount: true }),
387 + Atom.setIdleTTL(idleTtl),
388 + Atom.withLabel(`managed-relay:t3chat-link:${accountId}`),
389 + ),
390 + );
391 +
392 return {
393 environmentsAtom,
394 devicesAtom,
395 + t3ChatLinkAtom,
396 refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
397 registry.refresh(environmentsAtom(accountId));
398 },
399 refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {
400 registry.refresh(devicesAtom(accountId));
401 },
402 + refreshT3ChatLink(registry: AtomRegistry.AtomRegistry, accountId: string): void {
403 + registry.refresh(t3ChatLinkAtom(accountId));
404 + },
405 };
406 }
packages/contracts/src/relay.ts
+39
@@ -963,6 +963,30 @@ export const RelayOkResponse = Schema.Struct({
963 });
964 export type RelayOkResponse = typeof RelayOkResponse.Type;
965
966 +export const RelayT3ChatPlan = Schema.Literals(["free", "pro", "premier"]);
967 +export type RelayT3ChatPlan = typeof RelayT3ChatPlan.Type;
968 +
969 +// A linked paid T3 Chat plan raises the default managed tunnel cap.
970 +export const T3CHAT_PLAN_TUNNEL_LIMITS = { pro: 10, premier: 100 } as const;
971 +
972 +export const RelayT3ChatLink = Schema.Struct({
973 + email: Schema.String,
974 + plan: RelayT3ChatPlan,
975 +});
976 +export type RelayT3ChatLink = typeof RelayT3ChatLink.Type;
977 +
978 +export const RelayT3ChatLinkResponse = Schema.Struct({
979 + // False when this relay has no T3 Chat secret, so clients hide the feature.
980 + available: Schema.Boolean,
981 + link: Schema.NullOr(RelayT3ChatLink),
982 +});
983 +export type RelayT3ChatLinkResponse = typeof RelayT3ChatLinkResponse.Type;
984 +
985 +export const RelayT3ChatLinkRequestResponse = Schema.Struct({
986 + url: TrimmedNonEmptyString,
987 +});
988 +export type RelayT3ChatLinkRequestResponse = typeof RelayT3ChatLinkRequestResponse.Type;
989 +
990 export const RelayPublishResponse = Schema.Struct({
991 ok: Schema.Boolean,
992 deliveries: Schema.Array(RelayDeliveryResult),
@@ -1107,6 +1131,21 @@ const RelayClientGroup = HttpApiGroup.make("client")
1131 OpenApi.Description,
1132 "Deletes the provisioned Cloudflare tunnel while keeping the environment link and its hostname reservation, so a later link re-provisions the tunnel under the same URL. Environments call this when they shut down; Cloudflare bills per provisioned tunnel, so idle tunnels should not outlive their environment.",
1133 ),
1134 + HttpApiEndpoint.get("getT3ChatLink", "/v1/client/t3chat-link", {
1135 + headers: RelayBearerRequestHeaders,
1136 + success: RelayT3ChatLinkResponse,
1137 + error: RelayAuthAndInternalErrors,
1138 + }).annotate(OpenApi.Summary, "Get the linked T3 Chat account"),
1139 + HttpApiEndpoint.post("createT3ChatLinkRequest", "/v1/client/t3chat-link-requests", {
1140 + headers: RelayBearerRequestHeaders,
1141 + success: RelayT3ChatLinkRequestResponse,
1142 + error: RelayAuthAndInternalErrors,
1143 + }).annotate(OpenApi.Summary, "Start linking a T3 Chat account"),
1144 + HttpApiEndpoint.delete("unlinkT3Chat", "/v1/client/t3chat-link", {
1145 + headers: RelayBearerRequestHeaders,
1146 + success: RelayOkResponse,
1147 + error: RelayAuthAndInternalErrors,
1148 + }).annotate(OpenApi.Summary, "Unlink the T3 Chat account"),
1149 )
1150 .annotate(OpenApi.Description, "Cloud-user environment links and registered devices.")
1151 .middleware(RelayClientAuth);