fix(mobile): refresh cloud environment credentials on reconnect

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-04 14:03:00 -07:00
1 parent fb2d7cca77
commit 6e87a42247
10 files changed
+411 -39

No files matched your search

@@ -19,6 +19,7 @@ import {
listCloudEnvironments,
listCloudEnvironmentsWithStatus,
normalizeRelayBaseUrl,
refreshCloudEnvironmentConnection,
} from "./linkEnvironment";
vi.mock("expo-constants", () => ({
@@ -843,6 +844,81 @@ describe("mobile cloud link environment client", () => {
}),
);
it.effect("refreshes a saved environment against a rotated managed endpoint", () =>
Effect.gen(function* () {
vi.stubGlobal(
"fetch",
vi.fn((url: string | URL) => {
if (String(url).endsWith("/v1/client/dpop-token")) {
return Promise.resolve(
Response.json(validDpopAccessTokenResponse("environment:connect")),
);
}
if (String(url).endsWith("/.well-known/t3/environment")) {
return Promise.resolve(
Response.json({
environmentId: "env-1",
label: "Rotated Desktop",
platform: { os: "darwin", arch: "arm64" },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
}),
);
}
if (String(url).endsWith("/oauth/token")) {
return Promise.resolve(
Response.json({
access_token: "fresh-environment-dpop-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 3600,
scope: "orchestration:read orchestration:operate terminal:operate review:write",
}),
);
}
return Promise.resolve(
Response.json({
environmentId: "env-1",
endpoint: {
httpBaseUrl: "https://rotated-desktop.example.test/",
wsBaseUrl: "wss://rotated-desktop.example.test/ws",
providerKind: "cloudflare_tunnel",
},
credential: "rotated-one-time-cloud-credential",
expiresAt: "2026-05-25T00:05:00.000Z",
}),
);
}),
);
const connection = yield* withCloudServices(
refreshCloudEnvironmentConnection({
clerkToken: "clerk-token",
connection: {
environmentId: EnvironmentId.make("env-1"),
environmentLabel: "Desktop",
pairingUrl: "https://desktop.example.test/",
displayUrl: "https://desktop.example.test/",
httpBaseUrl: "https://desktop.example.test/",
wsBaseUrl: "wss://desktop.example.test/ws",
bearerToken: null,
authenticationMethod: "dpop",
relayManaged: true,
},
}),
);
expect(connection).toMatchObject({
environmentId: "env-1",
environmentLabel: "Rotated Desktop",
displayUrl: "https://rotated-desktop.example.test/",
httpBaseUrl: "https://rotated-desktop.example.test/",
wsBaseUrl: "wss://rotated-desktop.example.test/ws",
dpopAccessToken: "fresh-environment-dpop-token",
});
}),
);
it.effect("rejects relay connect responses for a different environment", () =>
Effect.gen(function* () {
vi.stubGlobal(
@@ -465,9 +465,10 @@ export function listCloudEnvironmentsWithStatus(input: {
});
}
export function connectCloudEnvironment(input: {
function connectRelayManagedEnvironment(input: {
readonly clerkToken: string;
readonly environment: RelayClientEnvironmentRecord;
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
readonly expectedEnvironment?: RelayClientEnvironmentRecord;
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
@@ -485,25 +486,27 @@ export function connectCloudEnvironment(input: {
.connectEnvironment({
clerkToken: input.clerkToken,
scopes: [RelayEnvironmentConnectScope],
environmentId: input.environment.environmentId,
environmentId: input.environmentId,
deviceId,
})
.pipe(
Effect.mapError(
decodedRelayClientError(
`${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/connect failed`,
`${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
),
),
);
if (connect.environmentId !== input.environment.environmentId) {
if (connect.environmentId !== input.environmentId) {
return yield* new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different environment.",
});
}
yield* ensureConnectEndpointMatchesEnvironment({
environment: input.environment,
connect,
});
if (input.expectedEnvironment) {
yield* ensureConnectEndpointMatchesEnvironment({
environment: input.expectedEnvironment,
connect,
});
}
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: connect.endpoint.httpBaseUrl,
@@ -551,3 +554,32 @@ export function connectCloudEnvironment(input: {
};
});
}
export function connectCloudEnvironment(input: {
readonly clerkToken: string;
readonly environment: RelayClientEnvironmentRecord;
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
environmentId: input.environment.environmentId,
expectedEnvironment: input.environment,
});
}
export function refreshCloudEnvironmentConnection(input: {
readonly clerkToken: string;
readonly connection: SavedRemoteConnection;
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
environmentId: input.connection.environmentId,
});
}
+19
View File
@@ -1,9 +1,11 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { EnvironmentId } from "@t3tools/contracts";
import {
isRelayManagedConnection,
mobileAuthClientMetadata,
redactPairingCredential,
toStableSavedRemoteConnection,
} from "./connection";
vi.mock("./runtime", () => ({
@@ -52,4 +54,21 @@ describe("mobile remote connection records", () => {
expect(isRelayManagedConnection({ authenticationMethod: "dpop" })).toBe(true);
expect(isRelayManagedConnection({ authenticationMethod: "bearer" })).toBe(false);
});
it("drops short-lived managed environment credentials from stable records", () => {
const connection = {
environmentId: EnvironmentId.make("environment-1"),
environmentLabel: "Desktop",
pairingUrl: "https://desktop.example/",
displayUrl: "https://desktop.example/",
httpBaseUrl: "https://desktop.example/",
wsBaseUrl: "wss://desktop.example/",
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: "short-lived-token",
relayManaged: true,
} as const;
expect(toStableSavedRemoteConnection(connection)).not.toHaveProperty("dpopAccessToken");
});
});
+11
View File
@@ -49,6 +49,17 @@ export function isRelayManagedConnection(
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
}
export function toStableSavedRemoteConnection(
connection: SavedRemoteConnection,
): SavedRemoteConnection {
if (!isRelayManagedConnection(connection) || !connection.dpopAccessToken) {
return connection;
}
const { dpopAccessToken: _, ...stableConnection } = connection;
return stableConnection;
}
export async function bootstrapRemoteConnection(
input: RemoteConnectionInput,
): Promise<SavedRemoteConnection> {
+72
View File
@@ -0,0 +1,72 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => {
const values = new Map<string, string>();
return {
clear: () => values.clear(),
getItemAsync: vi.fn((key: string) => Promise.resolve(values.get(key) ?? null)),
setItemAsync: vi.fn((key: string, value: string) => {
values.set(key, value);
return Promise.resolve();
}),
};
});
vi.mock("expo-secure-store", () => ({
getItemAsync: mocks.getItemAsync,
setItemAsync: mocks.setItemAsync,
}));
vi.mock("react-native", () => ({
Platform: {
OS: "ios",
},
}));
vi.mock("./runtime", () => ({
mobileRuntime: {
runPromise: vi.fn(),
},
}));
import { loadSavedConnections, saveConnection } from "./storage";
import { toStableSavedRemoteConnection } from "./connection";
const managedConnection = {
environmentId: EnvironmentId.make("environment-1"),
environmentLabel: "Desktop",
pairingUrl: "https://desktop.example/",
displayUrl: "https://desktop.example/",
httpBaseUrl: "https://desktop.example/",
wsBaseUrl: "wss://desktop.example/",
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: "short-lived-token",
relayManaged: true,
} as const;
describe("mobile connection storage", () => {
beforeEach(() => {
mocks.clear();
vi.clearAllMocks();
});
it("persists relay-managed connections without their ephemeral access token", async () => {
await saveConnection(managedConnection);
const savedValue = mocks.setItemAsync.mock.calls[0]?.[1];
expect(savedValue).toBeDefined();
expect(JSON.parse(savedValue ?? "")).toEqual({
connections: [toStableSavedRemoteConnection(managedConnection)],
});
});
it("loads relay-managed connection metadata without a cached access token", async () => {
await saveConnection(managedConnection);
await expect(loadSavedConnections()).resolves.toEqual([
toStableSavedRemoteConnection(managedConnection),
]);
});
});
+11 -7
View File
@@ -5,7 +5,11 @@ import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "./connection";
import {
isRelayManagedConnection,
type SavedRemoteConnection,
toStableSavedRemoteConnection,
} from "./connection";
const CONNECTIONS_KEY = "t3code.connections";
const PREFERENCES_KEY = "t3code.preferences";
@@ -136,22 +140,22 @@ export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteC
return pipe(
parsed.connections ?? [],
Arr.filter(
(c) =>
!!c.environmentId &&
(!!c.bearerToken?.trim() ||
(c.authenticationMethod === "dpop" && !!c.dpopAccessToken?.trim())),
(c) => !!c.environmentId && (!!c.bearerToken?.trim() || isRelayManagedConnection(c)),
),
);
}
export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
const current = await loadSavedConnections();
const stableConnection = toStableSavedRemoteConnection(connection);
const next = current.some((entry) => entry.environmentId === connection.environmentId)
? pipe(
current,
Arr.map((entry) => (entry.environmentId === connection.environmentId ? connection : entry)),
Arr.map((entry) =>
entry.environmentId === connection.environmentId ? stableConnection : entry,
),
)
: pipe(current, Arr.append(connection));
: pipe(current, Arr.append(stableConnection));
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
}
@@ -1,6 +1,10 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import { ManagedRelayDpopSigner } from "@t3tools/client-runtime";
import {
createManagedRelaySession,
ManagedRelayDpopSigner,
setManagedRelaySession,
} from "@t3tools/client-runtime";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
@@ -23,10 +27,11 @@ const mocks = vi.hoisted(() => {
resolveRemoteDpopWebSocketConnectionUrl: vi.fn(),
remoteEndpointUrl: vi.fn((baseUrl: string, path: string) => new URL(path, baseUrl).toString()),
createDpopProof: vi.fn(),
refreshCloudEnvironmentConnection: vi.fn(),
bootstrapRemoteConnection: vi.fn(),
clearCachedShellSnapshot: vi.fn(() => Promise.resolve()),
clearSavedConnection: vi.fn(() => Promise.resolve()),
saveConnection: vi.fn(() => Promise.resolve()),
saveConnection: vi.fn((_connection?: unknown) => Promise.resolve()),
saveCachedShellSnapshot: vi.fn(() => Promise.resolve()),
mobileRunPromise: vi.fn((_effect?: unknown) =>
Promise.resolve("wss://desktop.example/ws?wsTicket=token"),
@@ -71,10 +76,15 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
};
});
vi.mock("../lib/connection", () => ({
vi.mock("../lib/connection", async (importOriginal) => ({
...(await importOriginal<typeof import("../lib/connection")>()),
bootstrapRemoteConnection: mocks.bootstrapRemoteConnection,
}));
vi.mock("../features/cloud/linkEnvironment", () => ({
refreshCloudEnvironmentConnection: mocks.refreshCloudEnvironmentConnection,
}));
vi.mock("../lib/storage", () => ({
clearCachedShellSnapshot: mocks.clearCachedShellSnapshot,
clearSavedConnection: mocks.clearSavedConnection,
@@ -142,6 +152,7 @@ vi.mock("./use-terminal-session", () => ({
}));
import { connectSavedEnvironment, disconnectEnvironment } from "./use-remote-environment-registry";
import { appAtomRegistry } from "./atom-registry";
const environmentId = EnvironmentId.make("env-mobile-test");
@@ -165,9 +176,11 @@ describe("mobile remote environment registry effects", () => {
mocks.removeEnvironmentSession.mockReturnValue(null);
mocks.mobileRunPromise.mockResolvedValue("wss://desktop.example/ws?wsTicket=token");
mocks.createDpopProof.mockReturnValue(Effect.succeed("dpop-proof"));
mocks.refreshCloudEnvironmentConnection.mockReturnValue(Effect.die("unexpected refresh"));
mocks.resolveRemoteDpopWebSocketConnectionUrl.mockReturnValue(
Effect.succeed("wss://desktop.example/ws?wsTicket=dpop-token"),
);
setManagedRelaySession(appAtomRegistry, null);
});
it.effect("connects a saved managed endpoint environment through Effect-wrapped APIs", () =>
@@ -235,6 +248,76 @@ describe("mobile remote environment registry effects", () => {
}),
);
it.effect("refreshes a persisted managed connection before reconnecting", () =>
Effect.gen(function* () {
const savedDpopConnection = {
...connection,
bearerToken: null,
authenticationMethod: "dpop",
relayManaged: true,
} as const;
const refreshedConnection = {
...savedDpopConnection,
displayUrl: "https://rotated-desktop.example/",
httpBaseUrl: "https://rotated-desktop.example/",
wsBaseUrl: "wss://rotated-desktop.example/",
dpopAccessToken: "fresh-environment-dpop-token",
} as const;
setManagedRelaySession(
appAtomRegistry,
createManagedRelaySession({
accountId: "account-1",
readClerkToken: () => Promise.resolve("fresh-clerk-token"),
}),
);
mocks.refreshCloudEnvironmentConnection.mockReturnValue(Effect.succeed(refreshedConnection));
mocks.mobileRunPromise.mockImplementationOnce((effect?: unknown) =>
Effect.runPromise(
(effect as Effect.Effect<string, unknown, ManagedRelayDpopSigner>).pipe(
Effect.provideService(
ManagedRelayDpopSigner,
ManagedRelayDpopSigner.of({
thumbprint: Effect.succeed("mobile-key-thumbprint"),
createProof: mocks.createDpopProof,
}),
),
),
),
);
yield* connectSavedEnvironment(savedDpopConnection, { persist: false });
const openSocket = mocks.wsTransportConstructor.mock.calls[0]?.[0] as
| (() => Promise<string>)
| undefined;
expect(openSocket).toBeDefined();
yield* Effect.promise(() => openSocket!());
expect(mocks.refreshCloudEnvironmentConnection).toHaveBeenCalledWith({
clerkToken: "fresh-clerk-token",
connection: savedDpopConnection,
});
const persistedConnection = mocks.saveConnection.mock.calls[0]?.[0];
expect(persistedConnection).toMatchObject({
...savedDpopConnection,
displayUrl: refreshedConnection.displayUrl,
httpBaseUrl: refreshedConnection.httpBaseUrl,
wsBaseUrl: refreshedConnection.wsBaseUrl,
});
expect(persistedConnection).not.toHaveProperty("dpopAccessToken");
expect(mocks.createDpopProof).toHaveBeenCalledWith({
method: "POST",
url: "https://rotated-desktop.example/api/auth/websocket-ticket",
accessToken: "fresh-environment-dpop-token",
});
expect(mocks.resolveRemoteDpopWebSocketConnectionUrl).toHaveBeenCalledWith({
wsBaseUrl: refreshedConnection.wsBaseUrl,
httpBaseUrl: refreshedConnection.httpBaseUrl,
accessToken: "fresh-environment-dpop-token",
dpopProof: "dpop-proof",
});
}),
);
it.effect("fails interactive connects when the managed endpoint bootstrap fails", () =>
Effect.gen(function* () {
mocks.environmentConnection.ensureBootstrapped.mockRejectedValueOnce(
@@ -14,6 +14,7 @@ import {
remoteEndpointUrl,
resolveRemoteDpopWebSocketConnectionUrl,
resolveRemoteWebSocketConnectionUrl,
waitForManagedRelayClerkToken,
} from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
@@ -27,7 +28,9 @@ import {
type SavedRemoteConnection,
bootstrapRemoteConnection,
isRelayManagedConnection,
toStableSavedRemoteConnection,
} from "../lib/connection";
import { refreshCloudEnvironmentConnection } from "../features/cloud/linkEnvironment";
import { terminalDebugLog } from "../features/terminal/terminalDebugLog";
import {
clearCachedShellSnapshot,
@@ -223,6 +226,9 @@ export function connectSavedEnvironment(
return Effect.gen(function* () {
const connectionAttempt = environmentConnectionAttempts.begin(connection.environmentId);
const isCurrentAttempt = connectionAttempt.isCurrent;
let activeConnection = connection;
let initialDpopAccessToken =
options?.persist === false ? undefined : connection.dpopAccessToken;
yield* disconnectEnvironment(connection.environmentId, {
preserveShellSnapshot: true,
@@ -233,32 +239,54 @@ export function connectSavedEnvironment(
}
if (options?.persist !== false) {
yield* fromPromise(() => saveConnection(connection));
yield* fromPromise(() => saveConnection(toStableSavedRemoteConnection(connection)));
if (!isCurrentAttempt()) {
return;
}
}
upsertSavedConnection(connection);
upsertSavedConnection(toStableSavedRemoteConnection(connection));
setEnvironmentConnectionStatus(connection.environmentId, "connecting", null);
shellSnapshotManager.markPending({ environmentId: connection.environmentId });
const dpopAccessToken =
connection.authenticationMethod === "dpop" ? connection.dpopAccessToken : undefined;
const transport = new WsTransport(
() =>
mobileRuntime.runPromise(
dpopAccessToken
isRelayManagedConnection(connection)
? Effect.gen(function* () {
let dpopAccessToken = initialDpopAccessToken;
initialDpopAccessToken = undefined;
if (!dpopAccessToken) {
const clerkToken = yield* waitForManagedRelayClerkToken(appAtomRegistry);
const refreshedConnection = yield* refreshCloudEnvironmentConnection({
clerkToken,
connection: activeConnection,
});
const stableConnection = toStableSavedRemoteConnection(refreshedConnection);
activeConnection = refreshedConnection;
if (isCurrentAttempt()) {
yield* fromPromise(() => saveConnection(stableConnection));
upsertSavedConnection(stableConnection);
}
dpopAccessToken = refreshedConnection.dpopAccessToken;
}
if (!dpopAccessToken) {
return yield* Effect.fail(
new Error("Managed environment connection did not return a DPoP access token."),
);
}
const signer = yield* ManagedRelayDpopSigner;
const dpop = yield* signer.createProof({
method: "POST",
url: remoteEndpointUrl(connection.httpBaseUrl, "/api/auth/websocket-ticket"),
url: remoteEndpointUrl(
activeConnection.httpBaseUrl,
"/api/auth/websocket-ticket",
),
accessToken: dpopAccessToken,
});
return yield* resolveRemoteDpopWebSocketConnectionUrl({
wsBaseUrl: connection.wsBaseUrl,
httpBaseUrl: connection.httpBaseUrl,
wsBaseUrl: activeConnection.wsBaseUrl,
httpBaseUrl: activeConnection.httpBaseUrl,
accessToken: dpopAccessToken,
dpopProof: dpop,
});
@@ -423,7 +451,7 @@ export function connectSavedEnvironment(
terminalDebugLog("registry:terminal-metadata-subscribed", {
environmentId: connection.environmentId,
});
startAgentAwarenessForEnvironment(connection);
startAgentAwarenessForEnvironment(toStableSavedRemoteConnection(activeConnection));
notifyEnvironmentConnectionListeners();
});
}
@@ -13,8 +13,10 @@ import { ManagedRelayClient, type ManagedRelayClientShape } from "./managedRelay
import {
createManagedRelayQueryManager,
createManagedRelaySession,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
setManagedRelaySession,
waitForManagedRelayClerkToken,
} from "./managedRelayState.ts";
let registry = AtomRegistry.make();
@@ -93,6 +95,15 @@ function setSession() {
describe("createManagedRelayQueryManager", () => {
afterEach(resetRegistry);
it("waits for the current cloud session before reading its token", async () => {
const token = Effect.runPromise(waitForManagedRelayClerkToken(registry));
setSession();
await expect(token).resolves.toBe("clerk-token");
expect(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size).toBe(0);
});
it("keeps environment snapshots cached and refreshes them explicitly", async () => {
const listEnvironments = vi.fn(() => Effect.succeed([environment]));
const manager = createManager({ listEnvironments });
@@ -67,6 +67,52 @@ export function setManagedRelaySession(
registry.set(managedRelaySessionAtom, session);
}
function readSessionClerkToken(
session: ManagedRelaySession,
): Effect.Effect<string, ManagedRelaySessionError> {
return session.readClerkToken().pipe(
Effect.flatMap((token) =>
token
? Effect.succeed(token)
: Effect.fail(
new ManagedRelaySessionError({
message: "The T3 Cloud session token is unavailable.",
}),
),
),
);
}
export function waitForManagedRelayClerkToken(
registry: AtomRegistry.AtomRegistry,
): Effect.Effect<string, ManagedRelaySessionError> {
return Effect.callback<string, ManagedRelaySessionError>((resume) => {
let unsubscribe: (() => void) | undefined;
let completed = false;
const readCurrentSession = () => {
if (completed) {
return true;
}
const session = registry.get(managedRelaySessionAtom);
if (!session) {
return false;
}
completed = true;
unsubscribe?.();
resume(readSessionClerkToken(session));
return true;
};
if (readCurrentSession()) {
return;
}
unsubscribe = registry.subscribe(managedRelaySessionAtom, readCurrentSession);
readCurrentSession();
return Effect.sync(() => unsubscribe?.());
});
}
function requireClerkToken(
get: Atom.AtomContext,
accountId: string,
@@ -79,17 +125,7 @@ function requireClerkToken(
}),
);
}
return session.readClerkToken().pipe(
Effect.flatMap((token) =>
token
? Effect.succeed(token)
: Effect.fail(
new ManagedRelaySessionError({
message: "The T3 Cloud session token is unavailable.",
}),
),
),
);
return readSessionClerkToken(session);
}
function statusKey(input: {