Skip to content
TypeScript

feat(desktop): add a remote server by clicking its t3code://pair link (#24111)

Theo Brownedde3fdb5a6cd
diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts
index a244ff4b3fa..34b7286c335 100644
--- a/apps/desktop/src/app/DesktopClerk.test.ts
+++ b/apps/desktop/src/app/DesktopClerk.test.ts
@@ -156,6 +156,7 @@ describe("DesktopClerk", () => {
`setPath:userData:${userData}`,
"requestSingleInstanceLock",
"on:second-instance",
+ "on:open-url",
"createClerkBridge",
]);
},
@@ -200,7 +201,7 @@ describe("DesktopClerk", () => {
},
);
- it.effect("delivers queued startup links and later links once in arrival order", () => {
+ it.effect("delivers each queued startup link once, before later links", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
const listeners = new Map<string, (...args: unknown[]) => void>();
@@ -208,6 +209,7 @@ describe("DesktopClerk", () => {
const first = "t3code://new?prompt=first";
const second = "t3code://threads/env-1/thread-1";
const later = "t3code://new?prompt=later";
+ const launchPair = "t3code://pair?pairingUrl=https%3A%2F%2Fvps.example.com%2F%23token%3Dabc";
const delivered = Promise.withResolvers<void>();
const electronApp = {
on: (name: string, listener: (...args: unknown[]) => void) =>
@@ -220,13 +222,14 @@ describe("DesktopClerk", () => {
const clerk = yield* DesktopClerk.DesktopClerk;
listeners.get("second-instance")?.({}, ["t3", first]);
listeners.get("second-instance")?.({}, ["t3", second]);
+ listeners.get("open-url")?.({ preventDefault: () => undefined }, launchPair);
assert.deepEqual(received, []);
yield* clerk.configure;
listeners.get("second-instance")!({}, ["t3", later]);
yield* Effect.promise(() => delivered.promise);
- assert.deepEqual(received, [first, second, later]);
+ assert.deepEqual(received, [launchPair, first, second, later]);
}).pipe(
Effect.scoped,
Effect.provide(layerDesktopClerk(true, [], "darwin", undefined, undefined, listeners)),
@@ -425,6 +428,7 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const received: Array<string> = [];
+ const pairLink = "t3code://pair?pairingUrl=https%3A%2F%2Fvps.example.com%2F%23token%3Dabc";
yield* Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
yield* clerk.configure;
@@ -437,6 +441,8 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
assert.strictEqual(open("http://localhost:3000/"), 1);
assert.strictEqual(open("t3code://new?prompt=hi"), 1);
assert.strictEqual(open("t3code://threads/env-1/thread-1"), 1);
+ assert.strictEqual(open(pairLink), 1);
+ assert.strictEqual(open("t3code://pair"), 0);
assert.strictEqual(open("mailto:[email protected]"), 0);
assert.strictEqual(open("t3code://somewhere-else"), 0);
yield* Effect.yieldNow;
@@ -445,6 +451,7 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
"http://localhost:3000/",
"t3code://new?prompt=hi",
"t3code://threads/env-1/thread-1",
+ pairLink,
]);
}).pipe(
Effect.provide(layerDesktopClerk(true, [], "darwin", undefined, undefined, listeners)),
diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts
index 3e0d753d1bf..992e1fe0569 100644
--- a/apps/desktop/src/app/DesktopClerk.ts
+++ b/apps/desktop/src/app/DesktopClerk.ts
@@ -13,6 +13,7 @@ import { receiveCodexAuthCallback, CodexAuthCallbackError } from "./CodexAuthCal
import * as ElectronShell from "../electron/ElectronShell.ts";
import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl";
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
+import { readPairingAppLink } from "@t3tools/shared/remote";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
import * as ElectronApp from "../electron/ElectronApp.ts";
@@ -118,6 +119,15 @@ export const make = Effect.gen(function* () {
yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
handleSecondInstance(argv);
});
+ // macOS hands a launch link to open-url, which can fire before configure runs.
+ const pendingOpenUrls: Array<string> = [];
+ let handleOpenUrl = (url: string) => {
+ pendingOpenUrls.push(url);
+ return true;
+ };
+ yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
+ if (handleOpenUrl(url)) event.preventDefault();
+ });
yield* Effect.acquireRelease(
Effect.try({
@@ -194,7 +204,8 @@ export const make = Effect.gen(function* () {
return true;
};
const openAppLink = (value: string | undefined) => {
- if (!value || promptLinkAppPath(value) === null) return false;
+ if (!value || (promptLinkAppPath(value) === null && readPairingAppLink(value) === null))
+ return false;
void runPromise(webLinks.receive(value));
return true;
};
@@ -205,15 +216,12 @@ export const make = Effect.gen(function* () {
void runPromise(webLinks.receive(url));
return true;
};
- yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
- if (
- startProviderAuthHandoff(url) ||
- resumeProviderAuth(url) ||
- openWebLink(url) ||
- openAppLink(url)
- )
- event.preventDefault();
- });
+ handleOpenUrl = (url) =>
+ startProviderAuthHandoff(url) ||
+ resumeProviderAuth(url) ||
+ openWebLink(url) ||
+ openAppLink(url);
+ for (const url of pendingOpenUrls.splice(0)) handleOpenUrl(url);
yield* electronApp.on("open-file", (event: { preventDefault: () => void }, path: string) => {
if (!DesktopWebLinks.isWebPageFile(path)) return;
event.preventDefault();
diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts
index 1f326207a4a..5ad9bde0acc 100644
--- a/apps/server/src/cli/pair.test.ts
+++ b/apps/server/src/cli/pair.test.ts
@@ -35,6 +35,7 @@ import {
import { DevServerNotProxiableError, resolveTailscaleLocalTarget } from "./pair.ts";
import packageJson from "../../package.json" with { type: "json" };
+import { buildPairingAppLink } from "@t3tools/shared/remote";
const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -213,6 +214,7 @@ describe("t3 pair", () => {
const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
assert.isString(token);
+ assert.include(output, `App link: ${buildPairingAppLink(`${origin}/pair#token=${token}`)}`);
const listed = yield* captureStdout(
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts
index 846c1814a78..abec0f6c5e9 100644
--- a/apps/server/src/cli/pair.ts
+++ b/apps/server/src/cli/pair.ts
@@ -8,6 +8,7 @@ import {
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
+import { buildPairingAppLink } from "@t3tools/shared/remote";
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
import {
buildTailscaleHttpsBaseUrl,
@@ -193,6 +194,7 @@ const formatPairOutput = (input: {
renderTerminalQrCode(input.pairingUrl),
"",
`Pairing URL: ${input.pairingUrl}`,
+ `App link: ${buildPairingAppLink(input.pairingUrl)}`,
`Token: ${input.token}`,
`Expires: ${DateTime.formatIso(input.expiresAt)}`,
...input.notes.flatMap((note) => ["", `Note: ${note}`]),
diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts
index cd2815931e3..910584d110b 100644
--- a/apps/server/src/startupAccess.ts
+++ b/apps/server/src/startupAccess.ts
@@ -3,6 +3,7 @@ import * as NodeOS from "node:os";
import { isPrivateNetworkHost, isSharedAddressSpaceHost } from "@t3tools/shared/hostClassification";
import { QrCode } from "@t3tools/shared/qrCode";
+import { buildPairingAppLink } from "@t3tools/shared/remote";
import * as Effect from "effect/Effect";
import { HttpServer } from "effect/http";
import * as NetAddress from "effect/net/NetAddress";
@@ -186,6 +187,7 @@ export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo):
`Connection string: ${accessInfo.connectionString}`,
`Token: ${accessInfo.token}`,
`Pairing URL: ${accessInfo.pairingUrl}`,
+ `App link: ${buildPairingAppLink(accessInfo.pairingUrl)}`,
"",
renderTerminalQrCode(accessInfo.pairingUrl),
"",
diff --git a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx
index ee4ece96af2..a2a0f874d6e 100644
--- a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx
+++ b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx
@@ -8,6 +8,9 @@ const state = vi.hoisted(() => ({
projects: [] as never[],
navigate: vi.fn(async (): Promise<void> => undefined),
openScratchProject: vi.fn(async () => null),
+ confirm: vi.fn(async (_message: string) => true),
+ connectPairing: vi.fn(async (_input: { pairingUrl: string }) => ({ _tag: "Success" })),
+ localEnvironmentDisabled: false,
}));
// One connected primary environment that can read pull requests. Its project list and
@@ -20,11 +23,17 @@ vi.mock(import("@tanstack/react-router"), async (original) => ({
vi.mock(import("../../state/environments"), async (original) => ({
...(await original()),
usePrimaryEnvironmentId: () => "local" as EnvironmentId,
- usePrimaryEnvironment: (() => ({
- environmentId: "local",
- connection: { phase: "connected" },
- serverConfig: {},
- })) as never,
+ usePrimaryEnvironment: (() =>
+ state.localEnvironmentDisabled
+ ? null
+ : {
+ environmentId: "local",
+ connection: { phase: "connected" },
+ serverConfig: {},
+ }) as never,
+}));
+vi.mock(import("../../localEnvironment"), () => ({
+ isLocalEnvironmentDisabled: () => state.localEnvironmentDisabled,
}));
vi.mock(import("../../state/server"), async (original) => {
const { Atom } = await import("effect/reactivity");
@@ -52,6 +61,25 @@ vi.mock(import("../../hooks/useScratchProject"), async (original) => ({
})) as never,
}));
+vi.mock(import("../../confirmDialog"), async (original) => ({
+ ...(await original()),
+ requestConfirmDialog: state.confirm,
+}));
+vi.mock(import("../../connection/onboarding"), async (original) => ({
+ ...(await original()),
+ connectPairing: "connectPairing" as never,
+}));
+vi.mock(import("../../state/use-atom-command"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ useAtomCommand: ((command: unknown, options: never) =>
+ command === "connectPairing"
+ ? state.connectPairing
+ : actual.useAtomCommand(command as never, options)) as never,
+ };
+});
+
import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
import { allReachableShellsLiveAtom } from "../../state/shell";
import { DesktopWebLinkCoordinator } from "./DesktopWebLinkCoordinator";
@@ -87,8 +115,13 @@ const pullRequestView = {
},
};
+const pairingUrl = "https://vps.example.com/pair#token=ABC123";
+const pairLink = `t3code://pair?pairingUrl=${encodeURIComponent(pairingUrl)}`;
+
function setup() {
vi.clearAllMocks();
+ state.confirm.mockResolvedValue(true);
+ state.localEnvironmentDisabled = false;
state.projects = [];
appAtomRegistry.set(discoverySettled, false);
}
@@ -138,3 +171,62 @@ it("holds a launch PR link until project discovery settles, then opens the PR vi
expect(state.navigate).toHaveBeenCalledExactlyOnceWith(pullRequestView);
expect(state.openScratchProject).not.toHaveBeenCalled();
});
+
+it("adds the backend from a pairing link after the user confirms its host", async () => {
+ setup();
+ await using _coordinator = await mount(pairLink);
+ await vi.waitFor(() =>
+ expect(state.connectPairing).toHaveBeenCalledExactlyOnceWith({ pairingUrl }),
+ );
+ expect(state.confirm).toHaveBeenCalledExactlyOnceWith(
+ "Add the backend at https://vps.example.com?",
+ );
+ expect(state.navigate).not.toHaveBeenCalled();
+});
+
+it("does not spend the pairing token when the user declines", async () => {
+ setup();
+ const otherPairingUrl = "https://other.example.com/pair#token=XYZ789";
+ state.confirm.mockResolvedValueOnce(false);
+ await using _coordinator = await mount(
+ pairLink,
+ `t3code://pair?pairingUrl=${encodeURIComponent(otherPairingUrl)}`,
+ );
+ await vi.waitFor(() => expect(state.connectPairing).toHaveBeenCalled());
+ expect(state.confirm).toHaveBeenCalledTimes(2);
+ expect(state.connectPairing).toHaveBeenCalledExactlyOnceWith({ pairingUrl: otherPairingUrl });
+});
+
+it("skips a repeat of a pairing link that already paired", async () => {
+ setup();
+ const otherPairingUrl = "https://other.example.com/pair#token=XYZ789";
+ await using _coordinator = await mount(
+ pairLink,
+ pairLink,
+ `t3code://pair?pairingUrl=${encodeURIComponent(otherPairingUrl)}`,
+ );
+ await vi.waitFor(() =>
+ expect(state.connectPairing).toHaveBeenLastCalledWith({ pairingUrl: otherPairingUrl }),
+ );
+ expect(state.confirm).toHaveBeenCalledTimes(2);
+ expect(state.connectPairing.mock.calls).toEqual([
+ [{ pairingUrl }],
+ [{ pairingUrl: otherPairingUrl }],
+ ]);
+});
+
+it("pairs with Local environment disabled, where there is no primary environment to wait for", async () => {
+ setup();
+ state.localEnvironmentDisabled = true;
+ await using _coordinator = await mount(pairLink);
+ await vi.waitFor(() =>
+ expect(state.connectPairing).toHaveBeenCalledExactlyOnceWith({ pairingUrl }),
+ );
+});
+
+it("does not hold a PR link for project discovery that never settles with Local environment disabled", async () => {
+ setup();
+ state.localEnvironmentDisabled = true;
+ await using _coordinator = await mount(pullRequestUrl);
+ await vi.waitFor(() => expect(state.openScratchProject).toHaveBeenCalledOnce());
+});
diff --git a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
index 768101cd5ad..4ae0b6cdb25 100644
--- a/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
+++ b/apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
@@ -1,16 +1,23 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
+import { readPairingAppLink, resolveRemotePairingTarget } from "@t3tools/shared/remote";
import { useRouter } from "@tanstack/react-router";
import * as Effect from "effect/Effect";
import { AtomRegistry } from "effect/reactivity";
import * as Stream from "effect/Stream";
-import { useEffect, useEffectEvent, useRef } from "react";
+import { useEffect, useEffectEvent, useRef, useState } from "react";
import { openFileInPreview, openUrlInPreview } from "../../browser/openFileInPreview";
import { isPreviewAvailableFor } from "../../browser/previewRuntime";
+import { requestConfirmDialog } from "../../confirmDialog";
+import { connectPairing } from "../../connection/onboarding";
+import { isLocalEnvironmentDisabled } from "../../localEnvironment";
import { useComposerDraftStore } from "../../composerDraftStore";
import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
import { useScratchProject } from "../../hooks/useScratchProject";
@@ -82,19 +89,62 @@ export function DesktopWebLinkCoordinator() {
reportFailure: false,
refresh: true,
});
+ const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false });
const httpBaseUrl = useEnvironmentHttpBaseUrl(primaryEnvironment?.environmentId ?? null);
const queueRef = useRef(Promise.resolve());
+ const pairedUrlsRef = useRef(new Set<string>());
const webLinks = window.desktopBridge?.webLinks;
+ // A sync IPC read; the setting only changes across a relaunch.
+ const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled);
+ // With Local environment disabled there is no primary to wait for, so links run against the
+ // saved remote environments instead of waiting forever.
const ready =
webLinks !== undefined &&
- primaryEnvironment?.connection.phase === "connected" &&
- primaryEnvironment.serverConfig !== null;
+ (localEnvironmentDisabled ||
+ (primaryEnvironment?.connection.phase === "connected" &&
+ primaryEnvironment.serverConfig !== null));
const reportFailure = (url: string, description = url) =>
toastManager.add(
stackedThreadToast({ type: "error", title: "Could not open the link", description }),
);
+ const reportPairingFailure = (error: unknown) =>
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Could not add backend",
+ description: error instanceof Error ? error.message : "Failed to add backend.",
+ }),
+ );
+
+ // Any page can open a pairing link, so the user confirms the host before its one-time token is spent.
+ const pairFromLink = async (pairingUrl: string) => {
+ // A repeated click would only ask again and then fail on the spent one-time token.
+ if (pairedUrlsRef.current.has(pairingUrl)) return;
+ // The origin keeps the scheme visible, so a plain HTTP backend is not mistaken for HTTPS.
+ let origin: string;
+ try {
+ origin = new URL(resolveRemotePairingTarget({ pairingUrl }).httpBaseUrl).origin;
+ } catch (error) {
+ reportPairingFailure(error);
+ return;
+ }
+ const confirmed = (await requestConfirmDialog(`Add the backend at ${origin}?`)) ?? false;
+ if (!confirmed) return;
+ const result = await connectPairingEnvironment({ pairingUrl });
+ if (result._tag === "Failure") {
+ if (!isAtomCommandInterrupted(result)) reportPairingFailure(squashAtomCommandFailure(result));
+ return;
+ }
+ pairedUrlsRef.current.add(pairingUrl);
+ toastManager.add({
+ type: "success",
+ title: "Backend added",
+ description: "The environment is saved and will reconnect on app startup.",
+ });
+ };
+
const startThread = async (url: string): Promise<ScopedThreadRef | null> => {
const environmentId = scratchEnvironmentId(primaryEnvironment?.environmentId ?? null);
if (environmentId === null) {
@@ -114,6 +164,11 @@ export function DesktopWebLinkCoordinator() {
};
const openLink = useEffectEvent(async (url: string) => {
+ const pairingUrl = readPairingAppLink(url);
+ if (pairingUrl !== null) {
+ await pairFromLink(pairingUrl);
+ return;
+ }
const appPath = promptLinkAppPath(url);
if (appPath !== null) {
await router.navigate({ href: appPath });
@@ -121,6 +176,11 @@ export function DesktopWebLinkCoordinator() {
}
if (openChangeRequest(externalClick, url)) return;
const isFile = url.startsWith("file:");
+ // Only this machine's environment serves files, so fail before starting a thread.
+ if (isFile && httpBaseUrl === null) {
+ reportFailure(url);
+ return;
+ }
const routeParams = router.state.matches.at(-1)?.params ?? {};
const threadRef =
threadShowingBrowser(
@@ -154,8 +214,11 @@ export function DesktopWebLinkCoordinator() {
// A connected server publishes its config before its project snapshot, so a PR link
// delivered at launch would miss its project and fall through to the browser. Hold PR
// links, and only those, until discovery settles; an ordinary link never waits for it.
+ // Discovery never settles without the local environment, so those links do not wait.
const hold =
- openPullRequestsInApp && sourceControlClients.parseChangeRequestUrl(url) !== null
+ openPullRequestsInApp &&
+ !localEnvironmentDisabled &&
+ sourceControlClients.parseChangeRequestUrl(url) !== null
? projectsSettled()
: Promise.resolve();
void hold.then(() => {
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index d05c664cb6d..c6ae748f1e3 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -143,6 +143,8 @@ function RootRouteBranch() {
const pathname = useLocation({ select: (location) => location.pathname });
const { authGateState } = Route.useRouteContext();
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
+ // A sync IPC read; the setting only changes across a relaunch.
+ const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled);
// Once true, stays true: a visit to /welcome means the bootstrap already chose a route.
const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome");
if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true);
@@ -195,7 +197,9 @@ function RootRouteBranch() {
hostedStatic={authGateState.status === "hosted-static"}
>
{primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
- {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
+ {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? (
+ <DesktopWebLinkCoordinator />
+ ) : null}
{isElectron ? <RunningThreadKeepAlive /> : null}
<RelayClientInstallDialog />
<ConnectOnboardingDialog />
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 30e560ca444..2f7a8018766 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -58,6 +58,10 @@ in the receiving app. Connection settings are under **Settings → Environments*
on web and desktop and **Settings → Environments** on mobile. A loopback address
such as `127.0.0.1` reaches only the device opening the link.
+On a computer with the desktop app, you can open the printed `t3code://pair`
+app link instead. The desktop app asks you to confirm the server address, then
+adds it.
+
Pairing authorizes that device for future connections. Use a fresh one-time link
for each new device; you do not need the original token to reconnect. Links
created in Settings can only be copied from the client that created them while
diff --git a/packages/shared/src/remote.test.ts b/packages/shared/src/remote.test.ts
index c355f0f699d..30f30a2ad96 100644
--- a/packages/shared/src/remote.test.ts
+++ b/packages/shared/src/remote.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vite-plus/test";
import {
+ buildPairingAppLink,
+ readPairingAppLink,
RemoteBackendUrlMissingError,
RemotePairingTokenMissingError,
RemotePairingUrlInvalidError,
@@ -141,4 +143,20 @@ describe("remote", () => {
}),
);
});
+
+ it("round-trips pairing urls through app links on every channel scheme", () => {
+ const pairingUrl = "https://vps.example.com/pair#token=ABC123";
+ const appLink = buildPairingAppLink(pairingUrl);
+ expect(appLink.startsWith("t3code://pair?")).toBe(true);
+ expect(readPairingAppLink(appLink)).toBe(pairingUrl);
+ expect(readPairingAppLink(appLink.replace("t3code:", "t3code-dev:"))).toBe(pairingUrl);
+ expect(readPairingAppLink("t3code://pair")).toBeNull();
+ expect(readPairingAppLink(appLink.replace("//pair?", "//pair/other?"))).toBeNull();
+ expect(
+ readPairingAppLink(`t3code://threads?pairingUrl=${encodeURIComponent(pairingUrl)}`),
+ ).toBeNull();
+ expect(
+ readPairingAppLink(`https://pair?pairingUrl=${encodeURIComponent(pairingUrl)}`),
+ ).toBeNull();
+ });
});
diff --git a/packages/shared/src/remote.ts b/packages/shared/src/remote.ts
index 55698568fb9..2f1740b1e65 100644
--- a/packages/shared/src/remote.ts
+++ b/packages/shared/src/remote.ts
@@ -3,6 +3,8 @@ import * as Schema from "effect/Schema";
const PAIRING_TOKEN_PARAM = "token";
const HOSTED_PAIRING_HOST_PARAM = "host";
const HOSTED_PAIRING_LABEL_PARAM = "label";
+const PAIRING_APP_LINK_PARAM = "pairingUrl";
+const APP_LINK_PROTOCOL = /^t3code(?:-[a-z]+)?:$/;
const SUPPORTED_REMOTE_BACKEND_PROTOCOLS = new Set(["http:", "https:", "ws:", "wss:"]);
export const readHashParams = (url: URL): URLSearchParams =>
@@ -185,6 +187,19 @@ export const readHostedPairingRequest = (url: URL): HostedPairingRequest | null
};
};
+/** Wraps a pairing URL in the `t3code://pair` link that desktop opens and mobile scans. */
+export const buildPairingAppLink = (pairingUrl: string): string =>
+ `t3code://pair?${new URLSearchParams([[PAIRING_APP_LINK_PARAM, pairingUrl]])}`;
+
+/** Reads the pairing URL from a `t3code://pair` link on any app channel scheme. */
+export const readPairingAppLink = (value: string): string | null => {
+ if (!URL.canParse(value)) return null;
+ const url = new URL(value);
+ if (!APP_LINK_PROTOCOL.test(url.protocol) || url.host !== "pair") return null;
+ if (url.pathname !== "" && url.pathname !== "/") return null;
+ return url.searchParams.get(PAIRING_APP_LINK_PARAM)?.trim() || null;
+};
+
export const resolveRemotePairingTarget = (input: {
readonly pairingUrl?: string;
readonly host?: string;