Skip to content
TypeScript

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

Theo Browne8e76f945d2e1
diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.yml
index ff68c19caab..5db7a86eb98 100644
--- a/.github/workflows/deploy-relay.yml
+++ b/.github/workflows/deploy-relay.yml
@@ -80,6 +80,7 @@ jobs:
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
FCM_SERVICE_ACCOUNT: ${{ secrets.FCM_SERVICE_ACCOUNT }}
+ T3CHAT_LINK_SECRET: ${{ secrets.T3CHAT_LINK_SECRET }}
- name: Publish relay deploy commit status
uses: actions/github-script@v8
diff --git a/.github/workflows/relay-preview.yml b/.github/workflows/relay-preview.yml
index 53a71110cef..fdce22c68a5 100644
--- a/.github/workflows/relay-preview.yml
+++ b/.github/workflows/relay-preview.yml
@@ -79,3 +79,5 @@ jobs:
PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
+ # Unset by default, so previews keep the T3 Chat link off.
+ T3CHAT_LINK_SECRET: ${{ secrets.T3CHAT_LINK_SECRET }}
diff --git a/apps/web/src/cloud/managedRelayState.ts b/apps/web/src/cloud/managedRelayState.ts
index 16fec79749b..f562373463e 100644
--- a/apps/web/src/cloud/managedRelayState.ts
+++ b/apps/web/src/cloud/managedRelayState.ts
@@ -1,10 +1,12 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
+ createManagedRelayT3ChatLinkRequest,
deregisterManagedRelayEnvironment,
ManagedRelay,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
+ unlinkManagedRelayT3Chat,
} from "@t3tools/client-runtime/relay";
import {
createAtomCommandScheduler,
@@ -13,6 +15,7 @@ import {
import type {
RelayClientDeviceRecord,
RelayClientEnvironmentRecord,
+ RelayT3ChatLinkResponse,
} from "@t3tools/contracts/relay";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -50,6 +53,50 @@ export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand(
},
);
+const accountSerial = {
+ mode: "serial",
+ key: (input: { readonly accountId: string }) => input.accountId,
+} as const;
+
+export const createManagedRelayT3ChatLinkRequestCommand = createRuntimeCommand(
+ managedRelayAtomRuntime,
+ {
+ label: "web:managed-relay:create-t3chat-link-request",
+ scheduler: managedRelayMutationScheduler,
+ concurrency: accountSerial,
+ execute: (input: { readonly accountId: string }, registry) =>
+ createManagedRelayT3ChatLinkRequest(registry, input),
+ },
+);
+
+export const unlinkManagedRelayT3ChatCommand = createRuntimeCommand(managedRelayAtomRuntime, {
+ label: "web:managed-relay:unlink-t3chat",
+ scheduler: managedRelayMutationScheduler,
+ concurrency: accountSerial,
+ execute: (input: { readonly accountId: string }, registry) =>
+ unlinkManagedRelayT3Chat(registry, input),
+});
+
+const EMPTY_T3CHAT_LINK_ATOM = Atom.make(
+ AsyncResult.success<RelayT3ChatLinkResponse>({ available: false, link: null }),
+).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:t3chat-link:null"));
+
+export function useManagedRelayT3ChatLink() {
+ const session = useAtomValue(managedRelaySessionAtom);
+ const accountId = session?.accountId ?? null;
+ const atom = accountId
+ ? managedRelayQueryManager.t3ChatLinkAtom(accountId)
+ : EMPTY_T3CHAT_LINK_ATOM;
+ const snapshot = readManagedRelaySnapshotState(useAtomValue(atom));
+ const refresh = () => {
+ if (accountId) {
+ managedRelayQueryManager.refreshT3ChatLink(appAtomRegistry, accountId);
+ }
+ };
+
+ return { ...snapshot, accountId, refresh };
+}
+
const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:environments:null"));
diff --git a/apps/web/src/components/clerk/T3ChatUserProfilePage.tsx b/apps/web/src/components/clerk/T3ChatUserProfilePage.tsx
new file mode 100644
index 00000000000..689e0466112
--- /dev/null
+++ b/apps/web/src/components/clerk/T3ChatUserProfilePage.tsx
@@ -0,0 +1,167 @@
+import { findErrorTraceId } from "@t3tools/client-runtime/errors";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+import { T3CHAT_PLAN_TUNNEL_LIMITS, type RelayT3ChatLink } from "@t3tools/contracts/relay";
+import { MessageSquareIcon } from "lucide-react";
+import { useState } from "react";
+
+import {
+ createManagedRelayT3ChatLinkRequestCommand,
+ unlinkManagedRelayT3ChatCommand,
+ useManagedRelayT3ChatLink,
+} from "../../cloud/managedRelayState";
+import { readLocalApi } from "../../localApi";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { Button } from "../ui/button";
+import { toastManager } from "../ui/toast";
+import {
+ ClerkUserProfilePage,
+ ClerkUserProfileRefreshButton,
+ ClerkUserProfileRow,
+} from "./ClerkUserProfilePage";
+
+function planLabel(link: RelayT3ChatLink): string {
+ switch (link.plan) {
+ case "premier":
+ return `Premier · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} tunnels`;
+ case "pro":
+ return `Pro · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.pro} tunnels, or ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} with Premier`;
+ case "free":
+ return "Upgrade on T3 Chat for more tunnels";
+ }
+}
+
+function reportFailure(title: string, cause: unknown) {
+ const traceId = findErrorTraceId(cause);
+ toastManager.add({
+ type: "error",
+ title,
+ description: cause instanceof Error ? cause.message : "Try again.",
+ data: traceId
+ ? {
+ secondaryActionProps: {
+ children: "Copy trace ID",
+ onClick: () => void navigator.clipboard?.writeText(traceId),
+ },
+ }
+ : undefined,
+ });
+}
+
+/** Links a T3 Chat account so paid subscribers get more tunnels. */
+export function T3ChatUserProfilePage() {
+ const linkState = useManagedRelayT3ChatLink();
+ const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, {
+ reportFailure: false,
+ });
+ const unlink = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false });
+ const [pending, setPending] = useState<"link" | "unlink" | null>(null);
+ // Kept so a blocked popup still leaves the user a link to open.
+ const [linkUrl, setLinkUrl] = useState<string | null>(null);
+
+ const handleLink = async () => {
+ const accountId = linkState.accountId;
+ if (!accountId || pending) return;
+ setPending("link");
+ const result = await createLinkRequest({ accountId });
+ if (result._tag === "Success") {
+ setLinkUrl(result.value);
+ await readLocalApi()
+ ?.shell.openExternal(result.value)
+ .catch(() => undefined);
+ } else if (!isAtomCommandInterrupted(result)) {
+ reportFailure("Could not start linking", squashAtomCommandFailure(result));
+ }
+ setPending(null);
+ };
+
+ const handleUnlink = async () => {
+ const accountId = linkState.accountId;
+ if (!accountId || pending) return;
+ setPending("unlink");
+ const result = await unlink({ accountId });
+ if (result._tag === "Success") {
+ setLinkUrl(null);
+ linkState.refresh();
+ } else if (!isAtomCommandInterrupted(result)) {
+ reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result));
+ }
+ setPending(null);
+ };
+
+ const data = linkState.data;
+ const link = data?.link ?? null;
+
+ return (
+ <ClerkUserProfilePage
+ title="T3 Chat"
+ 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.`}
+ action={
+ <ClerkUserProfileRefreshButton
+ disabled={pending !== null}
+ isPending={linkState.isPending}
+ onClick={linkState.refresh}
+ />
+ }
+ >
+ {linkState.error ? (
+ <div className="border-t py-3 text-xs" role="alert">
+ <p className="font-medium text-destructive-foreground">Could not load T3 Chat link</p>
+ <p className="mt-0.5 text-muted-foreground">{linkState.error}</p>
+ </div>
+ ) : data === null ? null : !data.available ? (
+ <p className="border-t py-4 text-xs text-muted-foreground">
+ This T3 Connect server does not support T3 Chat linking.
+ </p>
+ ) : (
+ <ul className="border-t">
+ <ClerkUserProfileRow icon={<MessageSquareIcon className="size-4" />}>
+ <div className="flex items-start gap-4">
+ <div className="min-w-0 flex-1">
+ <h3 className="truncate text-sm leading-4.5 font-medium text-foreground">
+ {link ? link.email : "Not linked"}
+ </h3>
+ <p className="mt-1 text-xs leading-4.5 text-muted-foreground">
+ {link ? (
+ planLabel(link)
+ ) : linkUrl ? (
+ <>
+ Confirm on{" "}
+ <a
+ className="underline"
+ href={linkUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ t3.chat
+ </a>
+ , then select Refresh.
+ </>
+ ) : (
+ "You confirm the link on t3.chat."
+ )}
+ </p>
+ </div>
+ {link ? (
+ <Button
+ size="sm"
+ variant="destructive-outline"
+ disabled={pending !== null}
+ onClick={() => void handleUnlink()}
+ >
+ {pending === "unlink" ? "Unlinking…" : "Unlink"}
+ </Button>
+ ) : (
+ <Button size="sm" disabled={pending !== null} onClick={() => void handleLink()}>
+ {pending === "link" ? "Opening…" : "Link T3 Chat"}
+ </Button>
+ )}
+ </div>
+ </ClerkUserProfileRow>
+ </ul>
+ )}
+ </ClerkUserProfilePage>
+ );
+}
diff --git a/apps/web/src/components/clerk/T3ConnectAccountPages.tsx b/apps/web/src/components/clerk/T3ConnectAccountPages.tsx
index 267bf4cd21c..85dcc7dd255 100644
--- a/apps/web/src/components/clerk/T3ConnectAccountPages.tsx
+++ b/apps/web/src/components/clerk/T3ConnectAccountPages.tsx
@@ -1,9 +1,10 @@
import { useAuth, useClerk } from "@clerk/react";
-import { ServerIcon, SmartphoneIcon } from "lucide-react";
+import { MessageSquareIcon, ServerIcon, SmartphoneIcon } from "lucide-react";
import { type ReactNode, useState } from "react";
import { createPortal } from "react-dom";
import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";
+import { T3ChatUserProfilePage } from "./T3ChatUserProfilePage";
import { T3ConnectUserProfilePage } from "./T3ConnectUserProfilePage";
export const T3_CONNECT_ACCOUNT_PAGES = [
@@ -19,6 +20,12 @@ export const T3_CONNECT_ACCOUNT_PAGES = [
icon: <ServerIcon className="size-4" />,
content: <T3ConnectUserProfilePage />,
},
+ {
+ label: "T3 Chat",
+ url: "t3-chat",
+ icon: <MessageSquareIcon className="size-4" />,
+ content: <T3ChatUserProfilePage />,
+ },
] as const;
type PortalTargets = Readonly<Record<string, HTMLDivElement | undefined>>;
diff --git a/docs/internals/t3-connect.md b/docs/internals/t3-connect.md
index 6bf3ba74935..4c9bbcb780b 100644
--- a/docs/internals/t3-connect.md
+++ b/docs/internals/t3-connect.md
@@ -131,6 +131,21 @@ and clients keep their bindings. Every mutation on an allocation bumps its
`generation`, and deletion locks the row at the generation it claimed, so a
host that reconnects mid-sweep wins.
+## A paid T3 Chat plan raises the tunnel cap
+
+T3 Chat uses WorkOS, not Clerk, so the two accounts are linked by consent
+rather than by a shared identity. The relay and T3 Chat share one secret
+(`T3CHAT_LINK_SECRET` here, `T3CODE_LINK_SECRET` there). The relay signs a
+short-lived token naming the Clerk user and email; the user confirms it while
+signed in to T3 Chat, and T3 Chat stores the link. T3 Chat owns the link and the
+plan, so the relay keeps no copy. It asks T3 Chat only when an account reaches
+its normal cap for a new environment, and any failure keeps the normal cap.
+An environment that already holds a counted slot restarts without asking, so a
+downgrade or a T3 Chat outage only blocks new environments. A manual override
+row replaces the default for new environments, and a T3 Chat plan does not
+raise it
+([limits](../../infra/relay/src/environments/ManagedTunnelLimits.ts)).
+
## The relay client follows the server's pin
The host runs `cloudflared` pinned by `CLOUDFLARED_VERSION` in
diff --git a/docs/operations/release.md b/docs/operations/release.md
index 7e632bdc9bf..39f4f63ddd9 100644
--- a/docs/operations/release.md
+++ b/docs/operations/release.md
@@ -148,6 +148,11 @@ Required `production` environment secrets:
- `CLERK_SECRET_KEY`
- `APNS_PRIVATE_KEY`
+Optional `production` environment secrets:
+
+- `T3CHAT_LINK_SECRET` for the T3 Chat account link. It must match
+ `T3CODE_LINK_SECRET` on T3 Chat.
+
After changing a variable or secret, run the **Deploy T3 Connect relay** workflow manually from
`main` with **force** unchecked. Alchemy compares the values the Worker reads and redeploys it when
one changed. Check **force** only to redeploy resources with no detected change.
diff --git a/infra/relay/README.md b/infra/relay/README.md
index 5fe620a835e..4b5ac35e438 100644
--- a/infra/relay/README.md
+++ b/infra/relay/README.md
@@ -160,6 +160,9 @@ The `production` GitHub environment must define these Actions secrets:
- `CLERK_SECRET_KEY`
- `APNS_PRIVATE_KEY`
- `FCM_SERVICE_ACCOUNT` when Android push is enabled
+- `T3CHAT_LINK_SECRET`, optional, shared with T3 Chat's `T3CODE_LINK_SECRET`. Without it the
+ T3 Chat account link is off. Local and preview stages can set `T3CHAT_URL` to point
+ at another T3 Chat deployment; production uses `https://t3.chat`.
The account-scoped repository credentials are consumed by Alchemy while provisioning relay stages; they
are not bound into the relay Worker. The production deployment uses an Axiom personal access token,
diff --git a/infra/relay/src/Config.ts b/infra/relay/src/Config.ts
index a8673547ba2..ecc71a5a96a 100644
--- a/infra/relay/src/Config.ts
+++ b/infra/relay/src/Config.ts
@@ -48,6 +48,12 @@ export interface ApnsCredentials {
readonly environment: ApnsEnvironment;
}
+export interface T3ChatSettings {
+ readonly baseUrl: string;
+ // Shared with T3 Chat: signs link tokens and authenticates relay calls.
+ readonly linkSecret: Redacted.Redacted<string>;
+}
+
export class RelayConfiguration extends Context.Service<
RelayConfiguration,
{
@@ -65,6 +71,7 @@ export class RelayConfiguration extends Context.Service<
readonly managedEndpointCleanupMode?: ManagedEndpointCleanupMode;
readonly legacyManagedEndpointCleanupMode?: ManagedEndpointCleanupMode;
readonly legacyTunnelGraceMinutes?: number;
+ readonly t3Chat?: T3ChatSettings;
}
>()("t3code-relay/Config/RelayConfiguration") {}
diff --git a/infra/relay/src/environments/ManagedTunnelLimits.test.ts b/infra/relay/src/environments/ManagedTunnelLimits.test.ts
index 9879e38f18a..d45dfc0fde8 100644
--- a/infra/relay/src/environments/ManagedTunnelLimits.test.ts
+++ b/infra/relay/src/environments/ManagedTunnelLimits.test.ts
@@ -4,18 +4,28 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Semaphore from "effect/Semaphore";
import { PgDialect } from "drizzle-orm/pg-core";
+import type { RelayT3ChatPlan } from "@t3tools/contracts/relay";
import * as RelayDb from "../db.ts";
import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
+import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
class FakeTransaction extends Context.Service<FakeTransaction, { holdsLock: boolean }>()(
"t3code-relay/environments/ManagedTunnelLimits.test/FakeTransaction",
) {}
+interface FakeDbInput {
+ readonly otherSlots: () => number;
+ readonly ownSlot?: boolean;
+ readonly override?: number;
+ readonly countConditions?: Array<unknown>;
+}
+
// Models Postgres just enough: the advisory lock only works inside a transaction and is held until it ends.
-function makeFakeDb(reserved: ReadonlyArray<unknown>, countConditions: Array<unknown> = []) {
+function makeFakeDb(input: FakeDbInput) {
const userLock = Semaphore.makeUnsafe(1);
+ const dialect = new PgDialect();
return {
$client: {
withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) => {
@@ -42,16 +52,70 @@ function makeFakeDb(reserved: ReadonlyArray<unknown>, countConditions: Array<unk
from: (table: unknown) => ({
where: (condition: unknown) => {
if (table !== relayManagedEndpointAllocations) {
- return { limit: () => Effect.succeed([]) };
+ return {
+ limit: () =>
+ Effect.succeed(
+ input.override === undefined ? [] : [{ maxTunnels: input.override }],
+ ),
+ };
}
- countConditions.push(condition);
- return Effect.yieldNow.pipe(Effect.as([{ activeTunnels: reserved.length }]));
+ input.countConditions?.push(condition);
+ const countsOthers = dialect
+ .sqlToQuery(condition as never)
+ .sql.includes('"relay_managed_endpoint_allocations"."environment_id" <>');
+ return Effect.yieldNow.pipe(
+ Effect.andThen(
+ Effect.sync(() => [
+ { slots: countsOthers ? input.otherSlots() : input.ownSlot ? 1 : 0 },
+ ]),
+ ),
+ );
},
}),
}),
} as unknown as RelayDb.RelayDb["Service"];
}
+const t3ChatLayer = (plan: RelayT3ChatPlan | "lookup-fails", lookups?: Array<string>) =>
+ Layer.mock(T3ChatAccounts.T3ChatAccounts, {
+ available: true,
+ getLink: ({ userId }) => {
+ lookups?.push(userId);
+ return plan === "lookup-fails"
+ ? Effect.fail(
+ new T3ChatAccounts.T3ChatRequestFailed({
+ operation: "get-link",
+ cause: new Error("down"),
+ }),
+ )
+ : Effect.succeed({ email: "[email protected]", plan });
+ },
+ });
+
+const reserve = (
+ input: Omit<FakeDbInput, "otherSlots"> & {
+ readonly activeTunnels: number;
+ readonly plan: RelayT3ChatPlan | "lookup-fails";
+ readonly lookups?: Array<string>;
+ },
+) =>
+ Effect.gen(function* () {
+ const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
+ return yield* limits.withCapacity({ userId: "user-1", environmentId: "env-new" }, Effect.void);
+ }).pipe(
+ Effect.provide(
+ ManagedTunnelLimits.layer.pipe(
+ Layer.provide(
+ Layer.succeed(
+ RelayDb.RelayDb,
+ makeFakeDb({ ...input, otherSlots: () => input.activeTunnels }),
+ ),
+ ),
+ Layer.provide(t3ChatLayer(input.plan, input.lookups)),
+ ),
+ ),
+ );
+
describe("ManagedTunnelLimits", () => {
it.effect("rejects concurrent reservations past the limit", () => {
const reserved: Array<string> = [];
@@ -81,7 +145,10 @@ describe("ManagedTunnelLimits", () => {
}).pipe(
Effect.provide(
ManagedTunnelLimits.layer.pipe(
- Layer.provide(Layer.succeed(RelayDb.RelayDb, makeFakeDb(reserved))),
+ Layer.provide(
+ Layer.succeed(RelayDb.RelayDb, makeFakeDb({ otherSlots: () => reserved.length })),
+ ),
+ Layer.provide(t3ChatLayer("free")),
),
),
);
@@ -91,8 +158,7 @@ describe("ManagedTunnelLimits", () => {
const countConditions: Array<unknown> = [];
return Effect.gen(function* () {
- const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
- yield* limits.withCapacity({ userId: "user-1", environmentId: "environment-1" }, Effect.void);
+ yield* reserve({ activeTunnels: 0, plan: "free", countConditions });
expect(countConditions).toHaveLength(1);
const query = new PgDialect().sqlToQuery(countConditions[0] as never);
@@ -104,12 +170,57 @@ describe("ManagedTunnelLimits", () => {
expect(query.sql).toContain(
'"relay_environment_links"."updated_at" >= "relay_managed_endpoint_allocations"."updated_at"',
);
- }).pipe(
- Effect.provide(
- ManagedTunnelLimits.layer.pipe(
- Layer.provide(Layer.succeed(RelayDb.RelayDb, makeFakeDb([], countConditions))),
- ),
- ),
- );
+ });
});
+
+ it.effect("does not ask T3 Chat while the account is under its cap", () =>
+ Effect.gen(function* () {
+ const lookups: Array<string> = [];
+ yield* reserve({ activeTunnels: 2, plan: "free", lookups });
+ expect(lookups).toEqual([]);
+ }),
+ );
+
+ it.effect("raises the cap to the linked T3 Chat plan's limit", () =>
+ Effect.gen(function* () {
+ for (const [plan, limit] of [
+ ["pro", 10],
+ ["premier", 100],
+ ] as const) {
+ yield* reserve({ activeTunnels: limit - 1, plan });
+ const error = yield* Effect.flip(reserve({ activeTunnels: limit, plan }));
+ expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: limit });
+ }
+ }),
+ );
+
+ it.effect("keeps the default cap for free plans and failed lookups", () =>
+ Effect.gen(function* () {
+ for (const plan of ["free", "lookup-fails"] as const) {
+ const error = yield* Effect.flip(reserve({ activeTunnels: 3, plan }));
+ expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: 3 });
+ }
+ }),
+ );
+
+ it.effect("treats a manual override as the exact cap", () =>
+ Effect.gen(function* () {
+ const lookups: Array<string> = [];
+ for (const override of [1, 200]) {
+ const error = yield* Effect.flip(
+ reserve({ override, activeTunnels: override, plan: "premier", lookups }),
+ );
+ expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: override });
+ }
+ expect(lookups).toEqual([]);
+ }),
+ );
+
+ it.effect("lets an environment holding a slot relink without asking T3 Chat", () =>
+ Effect.gen(function* () {
+ const lookups: Array<string> = [];
+ yield* reserve({ activeTunnels: 10, plan: "lookup-fails", ownSlot: true, lookups });
+ expect(lookups).toEqual([]);
+ }),
+ );
});
diff --git a/infra/relay/src/environments/ManagedTunnelLimits.ts b/infra/relay/src/environments/ManagedTunnelLimits.ts
index 15c50ae7efb..e06bd883a23 100644
--- a/infra/relay/src/environments/ManagedTunnelLimits.ts
+++ b/infra/relay/src/environments/ManagedTunnelLimits.ts
@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlError from "effect/sql/SqlError";
+import { T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay";
import * as RelayDb from "../db.ts";
import {
@@ -13,6 +14,7 @@ import {
relayManagedEndpointAllocations,
relayManagedTunnelLimits,
} from "../persistence/schema.ts";
+import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
export const DEFAULT_MANAGED_TUNNEL_LIMIT = 3;
// 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<
const make = Effect.gen(function* () {
const db = yield* RelayDb.RelayDb;
+ const t3Chat = yield* T3ChatAccounts.T3ChatAccounts;
+
+ // Asked only at the cap, so most links never call T3 Chat. Any failure keeps the lower cap.
+ const t3ChatTunnelLimit = (userId: string) =>
+ t3Chat.getLink({ userId }).pipe(
+ Effect.map((link) =>
+ link && link.plan !== "free" ? T3CHAT_PLAN_TUNNEL_LIMITS[link.plan] : 0,
+ ),
+ Effect.catch((error) =>
+ Effect.logWarning("T3 Chat plan check failed", { userId, error: error.message }).pipe(
+ Effect.as(0),
+ ),
+ ),
+ );
return ManagedTunnelLimits.of({
withCapacity: Effect.fn("relay.managed_tunnel_limits.with_capacity")(function* <A, E, R>(
@@ -96,7 +112,7 @@ const make = Effect.gen(function* () {
}),
),
);
- const maxTunnels = overrides[0]?.maxTunnels ?? DEFAULT_MANAGED_TUNNEL_LIMIT;
+ const baseMaxTunnels = overrides[0]?.maxTunnels ?? DEFAULT_MANAGED_TUNNEL_LIMIT;
const pendingCutoff = DateTime.formatIso(
DateTime.subtract(yield* DateTime.now, {
@@ -123,44 +139,57 @@ const make = Effect.gen(function* () {
),
),
);
- const counted = yield* db
- .select({ activeTunnels: count() })
- .from(allocation)
- .where(
- and(
- eq(allocation.userId, input.userId),
- ne(allocation.environmentId, input.environmentId),
- or(
- // Reserved but not yet holding a tunnel. Release writes updatedAt = tunnelReleasedAt and
- // a relink reserves before rewriting its link, so only a newer reservation counts here.
- and(
- gt(allocation.updatedAt, pendingCutoff),
- or(
+ const countSlots = (environment: typeof eq) =>
+ db
+ .select({ slots: count() })
+ .from(allocation)
+ .where(
+ and(
+ eq(allocation.userId, input.userId),
+ environment(allocation.environmentId, input.environmentId),
+ or(
+ // Reserved but not yet holding a tunnel. Release writes updatedAt = tunnelReleasedAt and
+ // a relink reserves before rewriting its link, so only a newer reservation counts here.
+ and(
+ gt(allocation.updatedAt, pendingCutoff),
+ or(
+ isNull(allocation.tunnelReleasedAt),
+ gt(allocation.updatedAt, allocation.tunnelReleasedAt),
+ ),
+ not(withdrawnLink(allocation.updatedAt)),
+ ),
+ and(
+ isNotNull(allocation.tunnelId),
isNull(allocation.tunnelReleasedAt),
- gt(allocation.updatedAt, allocation.tunnelReleasedAt),
+ not(withdrawnLink()),
),
- not(withdrawnLink(allocation.updatedAt)),
- ),
- and(
- isNotNull(allocation.tunnelId),
- isNull(allocation.tunnelReleasedAt),
- not(withdrawnLink()),
),
),
- ),
- )
- .pipe(
- Effect.mapError(
- (cause) =>
- new ManagedTunnelLimitPersistenceError({
- operation: "count-tunnels",
- userId: input.userId,
- cause,
- }),
- ),
- );
- const activeTunnels = counted[0]?.activeTunnels ?? 0;
+ )
+ .pipe(
+ Effect.map((rows) => rows[0]?.slots ?? 0),
+ Effect.mapError(
+ (cause) =>
+ new ManagedTunnelLimitPersistenceError({
+ operation: "count-tunnels",
+ userId: input.userId,
+ cause,
+ }),
+ ),
+ );
+ const activeTunnels = yield* countSlots(ne);
+ if (activeTunnels < baseMaxTunnels) return yield* reserve;
+
+ // An environment that already holds a counted slot relinks without asking T3 Chat,
+ // so a downgrade or a T3 Chat outage only blocks new environments.
+ if ((yield* countSlots(eq)) > 0) return yield* reserve;
+ // A manual override is the exact cap; a T3 Chat plan raises only the default.
+ // Runs under the user lock, bounded by the T3 Chat request timeout.
+ const maxTunnels =
+ t3Chat.available && overrides.length === 0
+ ? Math.max(baseMaxTunnels, yield* t3ChatTunnelLimit(input.userId))
+ : baseMaxTunnels;
if (activeTunnels >= maxTunnels) {
return yield* new ManagedTunnelLimitExceeded({
userId: input.userId,
diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts
index 39cdd619feb..a20989cd3c0 100644
--- a/infra/relay/src/http/Api.test.ts
+++ b/infra/relay/src/http/Api.test.ts
@@ -66,6 +66,7 @@ import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllo
import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";
import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts";
import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
+import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
vi.mock("@clerk/backend", () => ({
createClerkClient: vi.fn(),
@@ -128,6 +129,7 @@ describe("managed endpoint provisioning errors", () => {
Layer.mock(EnvironmentLinks.EnvironmentLinks, {}),
Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}),
Layer.mock(Devices.Devices, {}),
+ Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
),
),
Layer.provideMerge(
@@ -238,6 +240,7 @@ describe("device listing compatibility", () => {
return Effect.succeed([iphone, android]);
},
}),
+ Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
),
),
Layer.provideMerge(
@@ -318,6 +321,7 @@ describe("Cloudflare rate-limit retry hint", () => {
Layer.mock(EnvironmentLinks.EnvironmentLinks, {}),
Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}),
Layer.mock(Devices.Devices, {}),
+ Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
),
),
Layer.provideMerge(
diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts
index 53551d6d344..5a4d77c28d3 100644
--- a/infra/relay/src/http/Api.ts
+++ b/infra/relay/src/http/Api.ts
@@ -77,6 +77,7 @@ import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvide
import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";
import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts";
+import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
import { withSpanAttributes } from "../observability.ts";
import { isRelayHookPath, redactRelayHookUrl } from "../hooks/HookForwarder.ts";
import * as RelayDb from "../db.ts";
@@ -823,6 +824,7 @@ export const layerClientApi = HttpApiBuilder.group(
const links = yield* EnvironmentLinks.EnvironmentLinks;
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const devices = yield* Devices.Devices;
+ const t3Chat = yield* T3ChatAccounts.T3ChatAccounts;
return handlers
.handle(
"listEnvironments",
@@ -989,6 +991,41 @@ export const layerClientApi = HttpApiBuilder.group(
.pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
return { ok: released };
}, mapRelayCommonApiErrors("not_authorized")),
+ )
+ .handle(
+ "getT3ChatLink",
+ Effect.fn("relay.api.client.getT3ChatLink")(function* () {
+ yield* appendRelayCredentialResponseHeaders;
+ if (!t3Chat.available) return { available: false, link: null };
+ const { userId } = yield* RelayClientPrincipal;
+ const link = yield* t3Chat
+ .getLink({ userId })
+ .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
+ return { available: true, link };
+ }, mapRelayCommonApiErrors("not_authorized")),
+ )
+ .handle(
+ "createT3ChatLinkRequest",
+ Effect.fn("relay.api.client.createT3ChatLinkRequest")(function* () {
+ const { userId } = yield* RelayClientPrincipal;
+ const url = yield* t3Chat.createLinkUrl({ userId }).pipe(
+ Effect.catchTags({
+ T3ChatNotConfigured: () => relayInternalErrorResponse("internal_error"),
+ ClerkUserLookupFailed: () => relayInternalErrorResponse("upstream_unavailable"),
+ }),
+ );
+ return { url };
+ }, mapRelayCommonApiErrors("not_authorized")),
+ )
+ .handle(
+ "unlinkT3Chat",
+ Effect.fn("relay.api.client.unlinkT3Chat")(function* () {
+ const { userId } = yield* RelayClientPrincipal;
+ yield* t3Chat
+ .unlink({ userId })
+ .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
+ return { ok: true };
+ }, mapRelayCommonApiErrors("not_authorized")),
);
}),
);
diff --git a/infra/relay/src/t3chat/T3ChatAccounts.test.ts b/infra/relay/src/t3chat/T3ChatAccounts.test.ts
new file mode 100644
index 00000000000..2fc9cc9e3e5
--- /dev/null
+++ b/infra/relay/src/t3chat/T3ChatAccounts.test.ts
@@ -0,0 +1,176 @@
+import { describe, expect, it } from "@effect/vitest";
+import { vi } from "vite-plus/test";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as TestClock from "effect/testing/TestClock";
+import * as Layer from "effect/Layer";
+import * as Redacted from "effect/Redacted";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
+
+import * as RelayConfiguration from "../Config.ts";
+import * as T3ChatAccounts from "./T3ChatAccounts.ts";
+
+const clerk = vi.hoisted(() => ({
+ getUser: async (): Promise<unknown> => ({ primaryEmailAddress: { emailAddress: "[email protected]" } }),
+}));
+vi.mock("@clerk/backend", () => ({
+ createClerkClient: () => ({ users: { getUser: () => clerk.getUser() } }),
+}));
+
+const SECRET = "shared-link-secret";
+
+const relaySettings = (
+ t3Chat: RelayConfiguration.T3ChatSettings | null,
+): RelayConfiguration.RelayConfiguration["Service"] => ({
+ relayIssuer: "https://relay.example.test",
+ apns: null,
+ clerkSecretKey: Redacted.make("clerk-secret-key"),
+ clerkPublishableKey: "pk_test_test",
+ clerkJwtAudience: "t3-code-relay",
+ apnsDeliveryJobSigningSecret: Redacted.make("apns-delivery-secret"),
+ cloudMintPrivateKey: Redacted.make("cloud-mint-private-key"),
+ cloudMintPublicKey: "cloud-mint-public-key",
+ managedEndpointBaseDomain: undefined,
+ managedEndpointNamespace: undefined,
+ ...(t3Chat ? { t3Chat } : {}),
+});
+
+const fakeT3Chat = (body: unknown, status = 200) => {
+ const requests: Array<{ url: string; authorization: string | undefined; body: unknown }> = [];
+ const client = HttpClient.make((request) =>
+ Effect.gen(function* () {
+ requests.push({
+ url: request.url,
+ authorization: request.headers["authorization"],
+ body:
+ request.body._tag === "Uint8Array"
+ ? JSON.parse(new TextDecoder().decode(request.body.body))
+ : null,
+ });
+ return HttpClientResponse.fromWeb(
+ request,
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ }),
+ );
+ return { client, requests };
+};
+
+const provide = (
+ client: HttpClient.HttpClient,
+ t3Chat: RelayConfiguration.T3ChatSettings | null = {
+ baseUrl: "https://chat.example.test",
+ linkSecret: Redacted.make(SECRET),
+ },
+) =>
+ Effect.provide(
+ T3ChatAccounts.layer.pipe(
+ Layer.provide(RelayConfiguration.layer(relaySettings(t3Chat))),
+ Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
+ ),
+ );
+
+describe("T3ChatAccounts", () => {
+ it.effect("signs link tokens in the format T3 Chat verifies", () =>
+ Effect.gen(function* () {
+ const accounts = yield* T3ChatAccounts.T3ChatAccounts;
+ const url = new URL(yield* accounts.createLinkUrl({ userId: "user_1" }));
+ expect(`${url.origin}${url.pathname}`).toBe("https://chat.example.test/link/t3code");
+
+ const [payload = "", signature = ""] = (url.searchParams.get("token") ?? "").split(".");
+ // Verify with Web Crypto, as T3 Chat does, rather than the signing library.
+ const verified = yield* Effect.promise(async () => {
+ const encoder = new TextEncoder();
+ const key = await crypto.subtle.importKey(
+ "raw",
+ encoder.encode(SECRET),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["verify"],
+ );
+ return crypto.subtle.verify(
+ "HMAC",
+ key,
+ Buffer.from(signature, "base64url"),
+ encoder.encode(payload),
+ );
+ });
+ expect(verified).toBe(true);
+ expect(JSON.parse(Buffer.from(payload, "base64url").toString("utf8"))).toEqual({
+ v: 1,
+ sub: "user_1",
+ email: "[email protected]",
+ exp: 600,
+ });
+ }).pipe(provide(fakeT3Chat({}).client)),
+ );
+
+ it.effect("asks T3 Chat for the link with the shared secret", () => {
+ const t3Chat = fakeT3Chat({ link: { email: "[email protected]", plan: "premier", linkedAt: 1 } });
+ return Effect.gen(function* () {
+ const accounts = yield* T3ChatAccounts.T3ChatAccounts;
+ const link = yield* accounts.getLink({ userId: "user_1" });
+ expect(link).toEqual({ email: "[email protected]", plan: "premier" });
+ expect(t3Chat.requests).toEqual([
+ {
+ url: "https://chat.example.test/api/t3code/link",
+ authorization: `Bearer ${SECRET}`,
+ body: { clerkUserId: "user_1" },
+ },
+ ]);
+ }).pipe(provide(t3Chat.client));
+ });
+
+ it.effect("fails instead of guessing when T3 Chat errors", () =>
+ Effect.gen(function* () {
+ const accounts = yield* T3ChatAccounts.T3ChatAccounts;
+ const error = yield* Effect.flip(accounts.getLink({ userId: "user_1" }));
+ expect(error._tag).toBe("T3ChatRequestFailed");
+ }).pipe(provide(fakeT3Chat({ error: "nope" }, 401).client)),
+ );
+
+ it.effect("times out when T3 Chat stalls while sending the body", () => {
+ const client = HttpClient.make((request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ new Response(new ReadableStream({ start: () => {} }), { status: 200 }),
+ ),
+ ),
+ );
+ return Effect.gen(function* () {
+ const accounts = yield* T3ChatAccounts.T3ChatAccounts;
+ const fiber = yield* Effect.forkChild(Effect.flip(accounts.getLink({ userId: "user_1" })));
+ yield* TestClock.adjust("5 seconds");
+ const error = yield* Fiber.join(fiber);
+ expect(error._tag).toBe("T3ChatRequestFailed");
+ }).pipe(provide(client));
+ });
+
+ it.effect("times out when Clerk stalls on the email lookup", () =>
+ Effect.gen(function* () {
+ const getUser = clerk.getUser;
+ clerk.getUser = () => new Promise(() => {});
+ const accounts = yield* T3ChatAccounts.T3ChatAccounts;
+ const fiber = yield* Effect.forkChild(Effect.flip(accounts.createLinkUrl({ userId: "u" })));
+ yield* TestClock.adjust("5 seconds");
+ const error = yield* Fiber.join(fiber).pipe(
+ Effect.ensuring(Effect.sync(() => (clerk.getUser = getUser))),
+ );
+ expect(error._tag).toBe("ClerkUserLookupFailed");
+ }).pipe(provide(fakeT3Chat({}).client)),
+ );
+
+ it.effect("reports itself unavailable without a shared secret", () =>
+ Effect.gen(function* () {
+ const accounts = yield* T3ChatAccounts.T3ChatAccounts;
+ expect(accounts.available).toBe(false);
+ const error = yield* Effect.flip(accounts.getLink({ userId: "user_1" }));
+ expect(error._tag).toBe("T3ChatNotConfigured");
+ }).pipe(provide(fakeT3Chat({}).client, null)),
+ );
+});
diff --git a/infra/relay/src/t3chat/T3ChatAccounts.ts b/infra/relay/src/t3chat/T3ChatAccounts.ts
new file mode 100644
index 00000000000..d81bc049fd8
--- /dev/null
+++ b/infra/relay/src/t3chat/T3ChatAccounts.ts
@@ -0,0 +1,166 @@
+import { createClerkClient } from "@clerk/backend";
+import { hmac } from "@noble/hashes/hmac";
+import { sha256 } from "@noble/hashes/sha2";
+import * as Context from "effect/Context";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Redacted from "effect/Redacted";
+import * as Schema from "effect/Schema";
+import * as Base64Url from "effect/encoding/Base64Url";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
+import { RelayT3ChatLink } from "@t3tools/contracts/relay";
+
+import * as RelayConfiguration from "../Config.ts";
+
+const LINK_TOKEN_TTL_SECONDS = 10 * 60;
+const T3CHAT_REQUEST_TIMEOUT = "5 seconds";
+
+const decodeLinkResponse = Schema.decodeUnknownEffect(
+ Schema.Struct({ link: Schema.NullOr(RelayT3ChatLink) }),
+);
+
+export class T3ChatNotConfigured extends Schema.TaggedError<T3ChatNotConfigured>()(
+ "T3ChatNotConfigured",
+ {},
+) {
+ override get message(): string {
+ return "T3 Chat linking is not configured on this relay";
+ }
+}
+
+export class ClerkUserLookupFailed extends Schema.TaggedError<ClerkUserLookupFailed>()(
+ "ClerkUserLookupFailed",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not read the Clerk user's primary email";
+ }
+}
+
+export class T3ChatRequestFailed extends Schema.TaggedError<T3ChatRequestFailed>()(
+ "T3ChatRequestFailed",
+ {
+ operation: Schema.Literals(["get-link", "unlink"]),
+ cause: Schema.Defect(),
+ },
+) {
+ override get message(): string {
+ return `T3 Chat '${this.operation}' request failed`;
+ }
+}
+
+/**
+ * Bridge to T3 Chat. T3 Chat owns the account link; the relay
+ * signs link requests and asks T3 Chat for the linked account's plan.
+ */
+export class T3ChatAccounts extends Context.Service<
+ T3ChatAccounts,
+ {
+ readonly available: boolean;
+ readonly createLinkUrl: (input: {
+ readonly userId: string;
+ }) => Effect.Effect<string, T3ChatNotConfigured | ClerkUserLookupFailed>;
+ readonly getLink: (input: {
+ readonly userId: string;
+ }) => Effect.Effect<RelayT3ChatLink | null, T3ChatNotConfigured | T3ChatRequestFailed>;
+ readonly unlink: (input: {
+ readonly userId: string;
+ }) => Effect.Effect<void, T3ChatNotConfigured | T3ChatRequestFailed>;
+ }
+>()("t3code-relay/t3chat/T3ChatAccounts") {}
+
+/** Token format shared with T3 Chat: `<base64url JSON payload>.<base64url HMAC-SHA256>`. */
+export const signLinkToken = (
+ secret: string,
+ payload: { readonly sub: string; readonly email: string; readonly exp: number },
+) => {
+ const encoded = Base64Url.encode(JSON.stringify({ v: 1, ...payload }));
+ const signature = hmac(
+ sha256,
+ new TextEncoder().encode(secret),
+ new TextEncoder().encode(encoded),
+ );
+ return `${encoded}.${Base64Url.encode(signature)}`;
+};
+
+export const make = Effect.gen(function* () {
+ const config = yield* RelayConfiguration.RelayConfiguration;
+ const client = yield* HttpClient.HttpClient;
+ const settings = config.t3Chat;
+
+ const requireSettings = settings
+ ? Effect.succeed(settings)
+ : Effect.fail(new T3ChatNotConfigured());
+
+ // The timeout covers the body read so a stalled response still fails fast.
+ const post = Effect.fn("relay.t3chat.post")(function* (
+ operation: T3ChatRequestFailed["operation"],
+ path: string,
+ userId: string,
+ ) {
+ const { baseUrl, linkSecret } = yield* requireSettings;
+ return yield* HttpClientRequest.post(new URL(path, baseUrl).toString()).pipe(
+ HttpClientRequest.bearerToken(Redacted.value(linkSecret)),
+ HttpClientRequest.bodyJsonUnsafe({ clerkUserId: userId }),
+ client.execute,
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
+ Effect.flatMap((response) => response.json),
+ Effect.timeout(T3CHAT_REQUEST_TIMEOUT),
+ Effect.mapError((cause) => new T3ChatRequestFailed({ operation, cause })),
+ );
+ });
+
+ const lookupClerkPrimaryEmail = Effect.fn("relay.t3chat.lookup_clerk_primary_email")(function* (
+ userId: string,
+ ) {
+ return yield* Effect.tryPromise({
+ try: async () => {
+ const user = await createClerkClient({
+ secretKey: Redacted.value(config.clerkSecretKey),
+ publishableKey: config.clerkPublishableKey,
+ }).users.getUser(userId);
+ const email = user.primaryEmailAddress?.emailAddress;
+ if (!email) throw new Error("Clerk user has no primary email address.");
+ return email;
+ },
+ catch: (cause) => new ClerkUserLookupFailed({ cause }),
+ }).pipe(
+ Effect.timeoutOrElse({
+ duration: T3CHAT_REQUEST_TIMEOUT,
+ orElse: () => Effect.fail(new ClerkUserLookupFailed({ cause: "timed out" })),
+ }),
+ );
+ });
+
+ return T3ChatAccounts.of({
+ available: settings !== undefined,
+ createLinkUrl: Effect.fn("relay.t3chat.create_link_url")(function* (input) {
+ const { baseUrl, linkSecret } = yield* requireSettings;
+ const email = yield* lookupClerkPrimaryEmail(input.userId);
+ const now = yield* DateTime.now;
+ const token = signLinkToken(Redacted.value(linkSecret), {
+ sub: input.userId,
+ email,
+ exp: Math.floor(now.epochMilliseconds / 1_000) + LINK_TOKEN_TTL_SECONDS,
+ });
+ const url = new URL("/link/t3code", baseUrl);
+ url.searchParams.set("token", token);
+ return url.toString();
+ }),
+ getLink: Effect.fn("relay.t3chat.get_link")(function* (input) {
+ const body = yield* post("get-link", "/api/t3code/link", input.userId);
+ const decoded = yield* decodeLinkResponse(body).pipe(
+ Effect.mapError((cause) => new T3ChatRequestFailed({ operation: "get-link", cause })),
+ );
+ return decoded.link;
+ }),
+ unlink: Effect.fn("relay.t3chat.unlink")(function* (input) {
+ yield* post("unlink", "/api/t3code/unlink", input.userId);
+ }),
+ });
+});
+
+export const layer = Layer.effect(T3ChatAccounts, make);
diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts
index 45414b2c68f..d59fc2f6c91 100644
--- a/infra/relay/src/worker.ts
+++ b/infra/relay/src/worker.ts
@@ -64,6 +64,7 @@ import * as EnvironmentPublishSignatures from "./environments/EnvironmentPublish
import * as ManagedEndpointProvider from "./environments/ManagedEndpointProvider.ts";
import * as ManagedEndpointReaper from "./environments/ManagedEndpointReaper.ts";
import * as ManagedTunnelLimits from "./environments/ManagedTunnelLimits.ts";
+import * as T3ChatAccounts from "./t3chat/T3ChatAccounts.ts";
import * as MobileRegistrations from "./agentActivity/MobileRegistrations.ts";
import * as HookForwarder from "./hooks/HookForwarder.ts";
import * as HeldHooks from "./hooks/HeldHooks.ts";
@@ -166,6 +167,15 @@ export const layer = Api.make(
const clerkSecretKey = yield* Config.Redacted("CLERK_SECRET_KEY");
const clerkPublishableKey = yield* Config.String("CLERK_PUBLISHABLE_KEY");
const clerkJwtAudience = yield* Config.String("CLERK_JWT_AUDIENCE");
+ const t3ChatLinkSecret = Option.getOrUndefined(
+ Option.filter(
+ yield* Config.option(Config.Redacted("T3CHAT_LINK_SECRET")),
+ (value) => Redacted.value(value).trim().length > 0,
+ ),
+ );
+ const t3ChatBaseUrl = yield* Config.String("T3CHAT_URL").pipe(
+ Config.withDefault("https://t3.chat"),
+ );
const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey;
const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey;
@@ -236,6 +246,9 @@ export const layer = Api.make(
managedEndpointCleanupMode,
legacyManagedEndpointCleanupMode,
...(legacyTunnelGraceMinutes === undefined ? {} : { legacyTunnelGraceMinutes }),
+ ...(t3ChatLinkSecret
+ ? { t3Chat: { baseUrl: t3ChatBaseUrl, linkSecret: t3ChatLinkSecret } }
+ : {}),
});
});
@@ -329,7 +342,7 @@ export const layer = Api.make(
ManagedTunnelLimits.layer,
),
),
- Layer.provideMerge(LiveActivities.layer),
+ Layer.provideMerge(Layer.mergeAll(LiveActivities.layer, T3ChatAccounts.layer)),
Layer.provideMerge(DeliveryAttempts.layer),
Layer.provideMerge(RelayTokens.layer),
Layer.provideMerge(
diff --git a/packages/client-runtime/src/authorization/layer.test.ts b/packages/client-runtime/src/authorization/layer.test.ts
index f7d8665549e..b98d019e1af 100644
--- a/packages/client-runtime/src/authorization/layer.test.ts
+++ b/packages/client-runtime/src/authorization/layer.test.ts
@@ -180,6 +180,9 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
createEnvironmentLinkChallenge: unexpected,
linkEnvironment: unexpected,
unlinkEnvironment: unexpected,
+ getT3ChatLink: unexpected,
+ createT3ChatLinkRequest: unexpected,
+ unlinkT3Chat: unexpected,
getEnvironmentStatus: unexpected,
connectEnvironment: (request) =>
Effect.gen(function* () {
diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts
index d920a8f0856..347bde9cc44 100644
--- a/packages/client-runtime/src/connection/supervisor.test.ts
+++ b/packages/client-runtime/src/connection/supervisor.test.ts
@@ -1181,6 +1181,9 @@ describe("EnvironmentSupervisor", () => {
createEnvironmentLinkChallenge: unused,
linkEnvironment: unused,
unlinkEnvironment: unused,
+ getT3ChatLink: unused,
+ createT3ChatLinkRequest: unused,
+ unlinkT3Chat: unused,
getEnvironmentStatus: unused,
connectEnvironment: Effect.fn("TestConnectionHttp.connectEnvironment")(function* () {
yield* Ref.update(bootstrapCalls, (count) => count + 1);
diff --git a/packages/client-runtime/src/relay/discovery.test.ts b/packages/client-runtime/src/relay/discovery.test.ts
index 53ded8855bd..2e15b5448c2 100644
--- a/packages/client-runtime/src/relay/discovery.test.ts
+++ b/packages/client-runtime/src/relay/discovery.test.ts
@@ -110,6 +110,9 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
createEnvironmentLinkChallenge: () => Effect.die("unused"),
linkEnvironment: () => Effect.die("unused"),
unlinkEnvironment: () => Effect.die("unused"),
+ getT3ChatLink: () => Effect.die("unused"),
+ createT3ChatLinkRequest: () => Effect.die("unused"),
+ unlinkT3Chat: () => Effect.die("unused"),
connectEnvironment: () => Effect.die("unused"),
registerDevice: () => Effect.die("unused"),
unregisterDevice: () => Effect.die("unused"),
@@ -275,6 +278,9 @@ describe("RelayEnvironmentDiscovery", () => {
createEnvironmentLinkChallenge: () => Effect.die("unused"),
linkEnvironment: () => Effect.die("unused"),
unlinkEnvironment: () => Effect.die("unused"),
+ getT3ChatLink: () => Effect.die("unused"),
+ createT3ChatLinkRequest: () => Effect.die("unused"),
+ unlinkT3Chat: () => Effect.die("unused"),
connectEnvironment: () => Effect.die("unused"),
registerDevice: () => Effect.die("unused"),
unregisterDevice: () => Effect.die("unused"),
diff --git a/packages/client-runtime/src/relay/errorPresentation.ts b/packages/client-runtime/src/relay/errorPresentation.ts
index e3dd743bd14..a446cb24893 100644
--- a/packages/client-runtime/src/relay/errorPresentation.ts
+++ b/packages/client-runtime/src/relay/errorPresentation.ts
@@ -1,5 +1,9 @@
import type { DpopFailureReason } from "@t3tools/contracts";
-import type { RelayEnvironmentStatusResponse, RelayProtectedError } from "@t3tools/contracts/relay";
+import {
+ T3CHAT_PLAN_TUNNEL_LIMITS,
+ type RelayEnvironmentStatusResponse,
+ type RelayProtectedError,
+} from "@t3tools/contracts/relay";
export const DPOP_CLOCK_HINT =
"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 {
error.provisioningStage ? ` Failed stage: ${error.provisioningStage}.` : ""
}`;
case "RelayEnvironmentLinkLimitExceededError":
- return `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`;
+ return error.maxTunnels < T3CHAT_PLAN_TUNNEL_LIMITS.premier
+ ? `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}.`
+ : `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`;
case "RelayAgentActivityPublishProofExpiredError":
return "Relay rejected an expired agent activity publish proof.";
case "RelayAgentActivityPublishProofInvalidError":
diff --git a/packages/client-runtime/src/relay/managedRelay.ts b/packages/client-runtime/src/relay/managedRelay.ts
index 35135466759..7c30ff640fb 100644
--- a/packages/client-runtime/src/relay/managedRelay.ts
+++ b/packages/client-runtime/src/relay/managedRelay.ts
@@ -22,6 +22,8 @@ import {
RelayMobileRegistrationScope,
type RelayOkResponse,
type RelayPublicClientId,
+ type RelayT3ChatLinkRequestResponse,
+ type RelayT3ChatLinkResponse,
RelayRegisterDeviceEndpoint,
RelayAgentActivitySnapshotEndpoint,
RelayRegisterLiveActivityEndpoint,
@@ -96,6 +98,9 @@ export const ManagedRelayRequestAction = Schema.Literals([
"unregister relay mobile device",
"register relay live activity",
"read relay agent activity snapshot",
+ "read linked T3 Chat account",
+ "start T3 Chat linking",
+ "unlink T3 Chat account",
]);
export type ManagedRelayRequestAction = typeof ManagedRelayRequestAction.Type;
@@ -112,6 +117,9 @@ export const ManagedRelayRequestActivity = Schema.Literals([
"Relay mobile device unregistration",
"Relay Live Activity registration",
"Relay agent activity snapshot",
+ "Relay T3 Chat link lookup",
+ "Relay T3 Chat link request",
+ "Relay T3 Chat unlinking",
]);
export type ManagedRelayRequestActivity = typeof ManagedRelayRequestActivity.Type;
@@ -272,6 +280,15 @@ export class ManagedRelayClient extends Context.Service<
readonly clerkToken: string;
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
+ readonly getT3ChatLink: (input: {
+ readonly clerkToken: string;
+ }) => Effect.Effect<RelayT3ChatLinkResponse, ManagedRelayClientError>;
+ readonly createT3ChatLinkRequest: (input: {
+ readonly clerkToken: string;
+ }) => Effect.Effect<RelayT3ChatLinkRequestResponse, ManagedRelayClientError>;
+ readonly unlinkT3Chat: (input: {
+ readonly clerkToken: string;
+ }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
readonly getEnvironmentStatus: (input: {
readonly clerkToken: string;
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
@@ -426,6 +443,9 @@ function disabledManagedRelayClient(relayUrl: string): ManagedRelayClient["Servi
),
linkEnvironment: unavailable("clientRuntime.managedRelay.linkEnvironment"),
unlinkEnvironment: unavailable("clientRuntime.managedRelay.unlinkEnvironment"),
+ getT3ChatLink: unavailable("clientRuntime.managedRelay.getT3ChatLink"),
+ createT3ChatLinkRequest: unavailable("clientRuntime.managedRelay.createT3ChatLinkRequest"),
+ unlinkT3Chat: unavailable("clientRuntime.managedRelay.unlinkT3Chat"),
getEnvironmentStatus: unavailable("clientRuntime.managedRelay.getEnvironmentStatus"),
connectEnvironment: unavailable("clientRuntime.managedRelay.connectEnvironment"),
registerDevice: unavailable("clientRuntime.managedRelay.registerDevice"),
@@ -791,6 +811,42 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* (
Effect.withSpan("clientRuntime.managedRelay.unlinkEnvironment"),
withRelayClientTracing,
),
+ getT3ChatLink: Effect.fnUntraced(
+ function* (input) {
+ return yield* client.client
+ .getT3ChatLink({ headers: bearerHeaders(input.clerkToken) })
+ .pipe(
+ Effect.mapError(relayRequestError("read linked T3 Chat account")),
+ timeoutRelayRequest("Relay T3 Chat link lookup"),
+ );
+ },
+ Effect.withSpan("clientRuntime.managedRelay.getT3ChatLink"),
+ withRelayClientTracing,
+ ),
+ createT3ChatLinkRequest: Effect.fnUntraced(
+ function* (input) {
+ return yield* client.client
+ .createT3ChatLinkRequest({ headers: bearerHeaders(input.clerkToken) })
+ .pipe(
+ Effect.mapError(relayRequestError("start T3 Chat linking")),
+ timeoutRelayRequest("Relay T3 Chat link request"),
+ );
+ },
+ Effect.withSpan("clientRuntime.managedRelay.createT3ChatLinkRequest"),
+ withRelayClientTracing,
+ ),
+ unlinkT3Chat: Effect.fnUntraced(
+ function* (input) {
+ return yield* client.client
+ .unlinkT3Chat({ headers: bearerHeaders(input.clerkToken) })
+ .pipe(
+ Effect.mapError(relayRequestError("unlink T3 Chat account")),
+ timeoutRelayRequest("Relay T3 Chat unlinking"),
+ );
+ },
+ Effect.withSpan("clientRuntime.managedRelay.unlinkT3Chat"),
+ withRelayClientTracing,
+ ),
getEnvironmentStatus: Effect.fnUntraced(
function* (input) {
yield* Effect.annotateCurrentSpan({
diff --git a/packages/client-runtime/src/relay/managedRelayState.test.ts b/packages/client-runtime/src/relay/managedRelayState.test.ts
index eb7772b9746..113de2e40bf 100644
--- a/packages/client-runtime/src/relay/managedRelayState.test.ts
+++ b/packages/client-runtime/src/relay/managedRelayState.test.ts
@@ -66,6 +66,9 @@ function createClient(overrides?: Partial<ManagedRelay.ManagedRelayClient["Servi
createEnvironmentLinkChallenge: () => Effect.die("unused"),
linkEnvironment: () => Effect.die("unused"),
unlinkEnvironment: () => Effect.die("unused"),
+ getT3ChatLink: () => Effect.die("unused"),
+ createT3ChatLinkRequest: () => Effect.die("unused"),
+ unlinkT3Chat: () => Effect.die("unused"),
getEnvironmentStatus: () =>
Effect.succeed({
environmentId: environment.environmentId,
diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.ts
index 7153f203cff..94e8fe33689 100644
--- a/packages/client-runtime/src/relay/managedRelayState.ts
+++ b/packages/client-runtime/src/relay/managedRelayState.ts
@@ -42,7 +42,7 @@ export interface ManagedRelaySnapshotState<A> {
}
export interface ManagedRelayQueryEvent {
- readonly operation: "environments" | "devices";
+ readonly operation: "environments" | "devices" | "t3chat-link";
readonly stage: "clerk-token" | "relay-request";
readonly phase: "start" | "success" | "failure";
readonly accountId: string;
@@ -178,23 +178,56 @@ function readSessionClerkToken(
);
}
+function requireSessionClerkToken(
+ registry: AtomRegistry.AtomRegistry,
+ accountId: string,
+ action: string,
+): Effect.Effect<string, ManagedRelaySessionError> {
+ const session = registry.get(managedRelaySessionAtom);
+ if (!session || session.accountId !== accountId) {
+ return Effect.fail(
+ new ManagedRelaySessionError({ message: `Sign in to T3 Connect before ${action}.` }),
+ );
+ }
+ return readSessionClerkToken(session);
+}
+
export const deregisterManagedRelayEnvironment = Effect.fn(
"clientRuntime.managedRelaySession.deregisterEnvironment",
)(function* (
registry: AtomRegistry.AtomRegistry,
input: { readonly accountId: string; readonly environmentId: EnvironmentId },
) {
- const session = registry.get(managedRelaySessionAtom);
- if (!session || session.accountId !== input.accountId) {
- return yield* new ManagedRelaySessionError({
- message: "Sign in to T3 Connect before deregistering an environment.",
- });
- }
- const clerkToken = yield* readSessionClerkToken(session);
+ const clerkToken = yield* requireSessionClerkToken(
+ registry,
+ input.accountId,
+ "deregistering an environment",
+ );
const relay = yield* ManagedRelay.ManagedRelayClient;
yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId });
});
+/** Returns the T3 Chat page URL where the signed-in user confirms the link. */
+export const createManagedRelayT3ChatLinkRequest = Effect.fn(
+ "clientRuntime.managedRelaySession.createT3ChatLinkRequest",
+)(function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) {
+ const clerkToken = yield* requireSessionClerkToken(registry, input.accountId, "linking T3 Chat");
+ const relay = yield* ManagedRelay.ManagedRelayClient;
+ return (yield* relay.createT3ChatLinkRequest({ clerkToken })).url;
+});
+
+export const unlinkManagedRelayT3Chat = Effect.fn("clientRuntime.managedRelaySession.unlinkT3Chat")(
+ function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) {
+ const clerkToken = yield* requireSessionClerkToken(
+ registry,
+ input.accountId,
+ "unlinking T3 Chat",
+ );
+ const relay = yield* ManagedRelay.ManagedRelayClient;
+ yield* relay.unlinkT3Chat({ clerkToken });
+ },
+);
+
function requireClerkToken(
get: Atom.AtomContext,
accountId: string,
@@ -333,14 +366,41 @@ export function createManagedRelayQueryManager(
),
);
+ const t3ChatLinkAtom = Atom.family((accountId: string) =>
+ runtime
+ .atom((get) =>
+ Effect.gen(function* () {
+ const base = { operation: "t3chat-link" as const, accountId };
+ const clerkToken = yield* observe(
+ { ...base, stage: "clerk-token" },
+ requireClerkToken(get, accountId),
+ );
+ const relay = yield* ManagedRelay.ManagedRelayClient;
+ return yield* observe(
+ { ...base, stage: "relay-request" },
+ relay.getT3ChatLink({ clerkToken }),
+ );
+ }),
+ )
+ .pipe(
+ Atom.swr({ staleTime, revalidateOnMount: true }),
+ Atom.setIdleTTL(idleTtl),
+ Atom.withLabel(`managed-relay:t3chat-link:${accountId}`),
+ ),
+ );
+
return {
environmentsAtom,
devicesAtom,
+ t3ChatLinkAtom,
refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
registry.refresh(environmentsAtom(accountId));
},
refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {
registry.refresh(devicesAtom(accountId));
},
+ refreshT3ChatLink(registry: AtomRegistry.AtomRegistry, accountId: string): void {
+ registry.refresh(t3ChatLinkAtom(accountId));
+ },
};
}
diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts
index b11b7cca5ef..983f74de418 100644
--- a/packages/contracts/src/relay.ts
+++ b/packages/contracts/src/relay.ts
@@ -963,6 +963,30 @@ export const RelayOkResponse = Schema.Struct({
});
export type RelayOkResponse = typeof RelayOkResponse.Type;
+export const RelayT3ChatPlan = Schema.Literals(["free", "pro", "premier"]);
+export type RelayT3ChatPlan = typeof RelayT3ChatPlan.Type;
+
+// A linked paid T3 Chat plan raises the default managed tunnel cap.
+export const T3CHAT_PLAN_TUNNEL_LIMITS = { pro: 10, premier: 100 } as const;
+
+export const RelayT3ChatLink = Schema.Struct({
+ email: Schema.String,
+ plan: RelayT3ChatPlan,
+});
+export type RelayT3ChatLink = typeof RelayT3ChatLink.Type;
+
+export const RelayT3ChatLinkResponse = Schema.Struct({
+ // False when this relay has no T3 Chat secret, so clients hide the feature.
+ available: Schema.Boolean,
+ link: Schema.NullOr(RelayT3ChatLink),
+});
+export type RelayT3ChatLinkResponse = typeof RelayT3ChatLinkResponse.Type;
+
+export const RelayT3ChatLinkRequestResponse = Schema.Struct({
+ url: TrimmedNonEmptyString,
+});
+export type RelayT3ChatLinkRequestResponse = typeof RelayT3ChatLinkRequestResponse.Type;
+
export const RelayPublishResponse = Schema.Struct({
ok: Schema.Boolean,
deliveries: Schema.Array(RelayDeliveryResult),
@@ -1107,6 +1131,21 @@ const RelayClientGroup = HttpApiGroup.make("client")
OpenApi.Description,
"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.",
),
+ HttpApiEndpoint.get("getT3ChatLink", "/v1/client/t3chat-link", {
+ headers: RelayBearerRequestHeaders,
+ success: RelayT3ChatLinkResponse,
+ error: RelayAuthAndInternalErrors,
+ }).annotate(OpenApi.Summary, "Get the linked T3 Chat account"),
+ HttpApiEndpoint.post("createT3ChatLinkRequest", "/v1/client/t3chat-link-requests", {
+ headers: RelayBearerRequestHeaders,
+ success: RelayT3ChatLinkRequestResponse,
+ error: RelayAuthAndInternalErrors,
+ }).annotate(OpenApi.Summary, "Start linking a T3 Chat account"),
+ HttpApiEndpoint.delete("unlinkT3Chat", "/v1/client/t3chat-link", {
+ headers: RelayBearerRequestHeaders,
+ success: RelayOkResponse,
+ error: RelayAuthAndInternalErrors,
+ }).annotate(OpenApi.Summary, "Unlink the T3 Chat account"),
)
.annotate(OpenApi.Description, "Cloud-user environment links and registered devices.")
.middleware(RelayClientAuth);