Skip to content
TypeScript

fix(connect): refresh HTTP credentials without reconnecting (#9594)

Julius Marminge363cde4114c2
diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts
index d6b50e50a6a..f7fa30c8f23 100644
--- a/apps/mobile/src/connection/platform.ts
+++ b/apps/mobile/src/connection/platform.ts
@@ -118,6 +118,9 @@ const capabilitiesLayer = Layer.effectContext(
return Context.make(
CloudSession,
CloudSession.of({
+ identity: Effect.sync(() =>
+ Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
+ ),
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
diff --git a/apps/mobile/src/connection/runtime.ts b/apps/mobile/src/connection/runtime.ts
index 662a4dcdf70..deee27ef040 100644
--- a/apps/mobile/src/connection/runtime.ts
+++ b/apps/mobile/src/connection/runtime.ts
@@ -30,10 +30,8 @@ type ConnectionLayerSource =
| typeof mobileBackgroundActivityObserverLayer
| typeof mobileBackgroundActivityReporterLayer;
-const providedClientConnectionLayer = Layer.merge(
- Connection.layerWithOptions({ usageLimitSources: true }),
- snapshotLoaderLayer,
-).pipe(
+const providedClientConnectionLayer = snapshotLoaderLayer.pipe(
+ Layer.provideMerge(Connection.layerWithOptions({ usageLimitSources: true })),
Layer.provideMerge(
Layer.mergeAll(
runtimeContextLayer,
diff --git a/apps/mobile/src/connection/storage.ts b/apps/mobile/src/connection/storage.ts
index e844181673d..ab361b8331a 100644
--- a/apps/mobile/src/connection/storage.ts
+++ b/apps/mobile/src/connection/storage.ts
@@ -2,6 +2,7 @@ import {
ConnectionPersistenceError,
ConnectionRegistrationStore,
ConnectionTargetStore,
+ putRemoteDpopTokenInCatalog,
registerConnectionInCatalog,
removeConnectionFromCatalog,
removeCatalogValue,
@@ -109,15 +110,7 @@ export const connectionStorageLayer = Layer.effectContext(
),
),
),
- put: (token) =>
- catalog.update((document) => ({
- ...document,
- remoteDpopTokens: replaceCatalogValue(
- document.remoteDpopTokens,
- (value) => value.environmentId,
- token,
- ),
- })),
+ put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
remove: (environmentId) =>
catalog.update((document) => ({
...document,
diff --git a/apps/server/src/auth/SessionStore.test.ts b/apps/server/src/auth/SessionStore.test.ts
index fa87c5ce4e8..1e2d5c60e9c 100644
--- a/apps/server/src/auth/SessionStore.test.ts
+++ b/apps/server/src/auth/SessionStore.test.ts
@@ -5,6 +5,8 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Queue from "effect/Queue";
+import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -44,6 +46,14 @@ const makeSessionStoreLayer = (
Layer.provide(makeServerConfigLayer(overrides)),
);
+const relaySessionInput = {
+ subject: "managed-relay-bootstrap",
+ method: "dpop-access-token",
+ proofKeyThumbprint: "relay-proof-key",
+ ttl: Duration.hours(1),
+ client: { label: "Relay desktop", deviceType: "desktop" },
+} as const;
+
const repositoryFailure = new PersistenceSqlError({
operation: "AuthSessionRepository.getById:query",
detail: "sqlite is unavailable",
@@ -420,6 +430,124 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
);
+
+ it.effect("keeps connected relay sessions visible through expiry and HTTP renewal", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionStore.SessionStore;
+ const original = yield* sessions.issue(relaySessionInput);
+ const websocket = yield* sessions.issueWebSocketToken(original.sessionId, {
+ ttl: Duration.hours(2),
+ });
+ yield* sessions.verifyWebSocketToken(websocket.token);
+ yield* sessions.markConnected(original.sessionId);
+ const beforeExpiry = yield* sessions.listActive();
+ expect(beforeExpiry).toHaveLength(1);
+ expect(beforeExpiry[0]?.connected).toBe(true);
+
+ yield* TestClock.adjust(Duration.minutes(61));
+
+ expect(yield* sessions.listActive()).toEqual(beforeExpiry);
+ expect(yield* Effect.flip(sessions.verify(original.token))).toMatchObject({
+ _tag: "SessionTokenExpiredError",
+ });
+ expect(yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token))).toMatchObject({
+ _tag: "WebSocketSessionExpiredError",
+ });
+
+ const renewed = yield* sessions.issue(relaySessionInput);
+ const afterRenewal = yield* sessions.listActive();
+ expect(renewed.sessionId).not.toBe(original.sessionId);
+ expect(afterRenewal).toHaveLength(2);
+ expect(afterRenewal).toEqual(
+ expect.arrayContaining([
+ beforeExpiry[0],
+ expect.objectContaining({
+ sessionId: renewed.sessionId,
+ connected: false,
+ lastConnectedAt: null,
+ }),
+ ]),
+ );
+ }).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
+ );
+
+ it.effect.each([1, 2])(
+ "removes an expired session from listings and updates after its last of %s sockets closes",
+ (socketCount) =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionStore.SessionStore;
+ const issued = yield* sessions.issue(relaySessionInput);
+ const changes = yield* Queue.unbounded<SessionStore.SessionCredentialChange>();
+ yield* sessions.streamChanges.pipe(
+ Stream.runForEach((change) => Queue.offer(changes, change)),
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ for (let index = 0; index < socketCount; index += 1) {
+ yield* sessions.markConnected(issued.sessionId);
+ expect(yield* Queue.take(changes)).toMatchObject({
+ type: "clientUpserted",
+ clientSession: { sessionId: issued.sessionId, connected: true },
+ });
+ }
+
+ yield* TestClock.adjust(Duration.minutes(61));
+
+ for (let remaining = socketCount - 1; remaining >= 0; remaining -= 1) {
+ yield* sessions.markDisconnected(issued.sessionId);
+ const change = yield* Queue.take(changes);
+ const listed = yield* sessions.listActive();
+ if (remaining > 0) {
+ expect(change).toMatchObject({
+ type: "clientUpserted",
+ clientSession: { sessionId: issued.sessionId, connected: true },
+ });
+ expect(listed).toHaveLength(1);
+ expect(listed[0]?.connected).toBe(true);
+ } else {
+ expect(change).toEqual({ type: "clientRemoved", sessionId: issued.sessionId });
+ expect(listed).toEqual([]);
+ }
+ }
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer())),
+ ),
+ );
+
+ it.effect.each(["revoke", "revokeAllExcept"] as const)(
+ "removes expired connected sessions with %s",
+ (operation) =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionStore.SessionStore;
+ const administrative = yield* sessions.issue({ subject: "desktop-bootstrap" });
+ const client = yield* sessions.issue(relaySessionInput);
+ yield* sessions.markConnected(client.sessionId);
+ yield* TestClock.adjust(Duration.minutes(61));
+ const changes = yield* Queue.unbounded<SessionStore.SessionCredentialChange>();
+ yield* sessions.streamChanges.pipe(
+ Stream.runForEach((change) => Queue.offer(changes, change)),
+ Effect.forkScoped({ startImmediately: true }),
+ );
+
+ if (operation === "revoke") {
+ expect(yield* sessions.revoke(client.sessionId)).toBe(true);
+ } else {
+ expect(yield* sessions.revokeAllExcept(administrative.sessionId)).toBe(1);
+ }
+
+ expect(yield* Queue.take(changes)).toEqual({
+ type: "clientRemoved",
+ sessionId: client.sessionId,
+ });
+ const listed = yield* sessions.listActive();
+ expect(listed).toHaveLength(1);
+ expect(listed[0]?.sessionId).toBe(administrative.sessionId);
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer())),
+ ),
+ );
+
it.effect("records client connection metadata without clearing prior values", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts
index b315bdf87c7..f4e5e3c487a 100644
--- a/apps/server/src/auth/SessionStore.ts
+++ b/apps/server/src/auth/SessionStore.ts
@@ -482,7 +482,7 @@ export const make = Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const authSessions = yield* AuthSessions.AuthSessionRepository;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
- const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
+ const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>());
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieInput = {
mode: serverConfig.mode,
@@ -515,6 +515,11 @@ export const make = Effect.gen(function* () {
}
const connectedSessions = yield* Ref.get(connectedSessionsRef);
+ const connected = connectedSessions.has(row.value.sessionId);
+ const now = yield* DateTime.now;
+ if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
+ return Option.none<AuthClientSession>();
+ }
return Option.some(
toAuthClientSession({
sessionId: row.value.sessionId,
@@ -525,7 +530,7 @@ export const make = Effect.gen(function* () {
issuedAt: row.value.issuedAt,
expiresAt: row.value.expiresAt,
lastConnectedAt: row.value.lastConnectedAt,
- connected: connectedSessions.has(row.value.sessionId),
+ connected,
}),
);
});
@@ -599,7 +604,7 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.flatMap(() => loadActiveSession(sessionId)),
Effect.flatMap((session) =>
- Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
+ Option.isSome(session) ? emitUpsert(session.value) : emitRemoved(sessionId),
),
Effect.catchCause((cause) =>
Effect.logError("Failed to publish disconnected-session auth update.").pipe(
@@ -882,7 +887,10 @@ export const make = Effect.gen(function* () {
function* () {
const now = yield* DateTime.now;
const connectedSessions = yield* Ref.get(connectedSessionsRef);
- const rows = yield* authSessions.listActive({ now });
+ const rows = yield* authSessions.listActive({
+ now,
+ connectedSessionIds: Array.from(connectedSessions.keys()),
+ });
return rows.map((row) =>
toAuthClientSession({
diff --git a/apps/server/src/persistence/AuthSessions.ts b/apps/server/src/persistence/AuthSessions.ts
index b47f148f076..aebbb839e5c 100644
--- a/apps/server/src/persistence/AuthSessions.ts
+++ b/apps/server/src/persistence/AuthSessions.ts
@@ -69,6 +69,7 @@ export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
export const ListActiveAuthSessionsInput = Schema.Struct({
now: Schema.DateTimeUtcFromString,
+ connectedSessionIds: Schema.optionalKey(Schema.Array(AuthSessionId)),
});
export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
@@ -282,7 +283,7 @@ export const make = Effect.gen(function* () {
const listActiveSessionRows = SqlSchema.findAll({
Request: ListActiveAuthSessionsInput,
Result: AuthSessionRawDbRow,
- execute: ({ now }) =>
+ execute: ({ now, connectedSessionIds = [] }) =>
sql`
SELECT
session_id AS "sessionId",
@@ -301,7 +302,7 @@ export const make = Effect.gen(function* () {
revoked_at AS "revokedAt"
FROM auth_sessions
WHERE revoked_at IS NULL
- AND expires_at > ${now}
+ AND (expires_at > ${now} OR ${sql.in("session_id", connectedSessionIds)})
ORDER BY issued_at DESC, session_id DESC
`,
});
diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts
index ac9f77c53c2..7e88c4aae3c 100644
--- a/apps/web/src/connection/platform.ts
+++ b/apps/web/src/connection/platform.ts
@@ -182,6 +182,9 @@ const capabilitiesLayer = Layer.effectContext(
scopes: AuthStandardClientScopes,
});
const cloudSession = CloudSession.of({
+ identity: Effect.sync(() =>
+ Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
+ ),
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.ts
index eacce33a816..ac2316560d9 100644
--- a/apps/web/src/connection/runtime.ts
+++ b/apps/web/src/connection/runtime.ts
@@ -30,10 +30,10 @@ type ConnectionLayerSource =
| typeof backgroundActivityObserverLayer
| typeof backgroundActivityReporterLayer;
-const providedClientConnectionLayer = Layer.merge(
- Connection.layerWithOptions({ environmentThemes: true, usageLimitSources: true }),
- snapshotLoaderLayer,
-).pipe(
+const providedClientConnectionLayer = snapshotLoaderLayer.pipe(
+ Layer.provideMerge(
+ Connection.layerWithOptions({ environmentThemes: true, usageLimitSources: true }),
+ ),
Layer.provideMerge(
Layer.mergeAll(
runtimeContextLayer,
diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.ts
index 4ae476c1d11..0a1183d48ab 100644
--- a/apps/web/src/connection/storage.ts
+++ b/apps/web/src/connection/storage.ts
@@ -6,6 +6,7 @@ import {
ConnectionTargetStore,
EMPTY_CONNECTION_CATALOG_DOCUMENT,
EnvironmentCacheStore,
+ putRemoteDpopTokenInCatalog,
registerConnectionInCatalog,
removeCatalogValue,
removeConnectionFromCatalog,
@@ -446,15 +447,7 @@ export const connectionStorageLayer = Layer.effectContext(
),
),
),
- put: (token) =>
- catalog.update((document) => ({
- ...document,
- remoteDpopTokens: replaceCatalogValue(
- document.remoteDpopTokens,
- (value) => value.environmentId,
- token,
- ),
- })),
+ put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
remove: (environmentId) =>
catalog.update((document) => ({
...document,
diff --git a/docs/internals/connection-runtime.md b/docs/internals/connection-runtime.md
index 21baaa4def0..797ff8fe31f 100644
--- a/docs/internals/connection-runtime.md
+++ b/docs/internals/connection-runtime.md
@@ -6,10 +6,10 @@ signals, and application lifecycle events. React views consume the runtime.
Keeping retries and session lifetime here prevents competing reconnect loops when
several views need the same environment.
-## One retry owner
+## One transport retry owner
The [supervisor](../../packages/client-runtime/src/connection/supervisor.ts) owns
-retry policy; resolving an endpoint and opening an RPC session are single
+transport retry policy; resolving an endpoint and opening an RPC session are single
attempts. Transient failures retry with capped backoff. Offline states and
authentication failures wait for a wakeup instead of spending attempts on
unchanged conditions.
@@ -27,6 +27,20 @@ and cached data. Explicit removal closes the scope and clears credentials,
projections, and platform-owned state such as drafts. Cloud-account changes apply
to relay registrations; they must not discard directly paired environments.
+## HTTP authorization
+
+RPC sessions authenticate at socket upgrade, while HTTP requests need current
+credentials from the
+[authorization service](../../packages/client-runtime/src/authorization/service.ts).
+Replacing a healthy socket for HTTP renewal would interrupt conversations and
+change the transport generation without a transport failure. Credential expiry
+does not close the socket, and refresh failure belongs to the HTTP operation.
+
+Session listings must retain unrevoked connected sessions after credential expiry
+so an open connection does not disappear from connection management. This does
+not extend the credential's lifetime. New HTTP requests and socket upgrades still
+require valid credentials.
+
## Transport health and data freshness are separate
A socket opening is insufficient evidence that the environment is usable. The
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index fa1b2a73df5..ec2724b4b04 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -24,6 +24,11 @@ On your other device, sign in to the same T3 Connect account and choose the
environment. Over SSH, the CLI prints a browser link and accepts the returned
authorization code, so you do not need to forward an OAuth callback port.
+T3 Connect renews access credentials when needed without disconnecting a healthy
+connection. Pull request diffs and provider settings keep working after the
+previous credential expires. A failed renewal affects that request; it does not
+disconnect an otherwise healthy conversation.
+
## Pair over a LAN or private network
Use direct pairing when the other device can reach the host's network address.
@@ -127,6 +132,9 @@ pairing links and revoke client sessions. Revoking an unused link prevents new
pairings; revoke a device's session to remove its existing access. Command-line
management is available through `npx t3 auth --help`.
+A session with an open connection stays listed after its access credential
+expires.
+
To remove an environment from T3 Connect, open your account menu's **T3 Connect**
page, or **Settings → T3 Connect** on mobile, and choose **Deregister**. This
revokes its cloud access and frees its host space even when the environment is
diff --git a/packages/client-runtime/src/authorization/index.ts b/packages/client-runtime/src/authorization/index.ts
index 6236b5922d8..d232aea0d30 100644
--- a/packages/client-runtime/src/authorization/index.ts
+++ b/packages/client-runtime/src/authorization/index.ts
@@ -1,7 +1,7 @@
export * from "./remote.ts";
export {
type AuthorizedRemoteEnvironment,
- type RelayEnvironmentAuthorization,
+ type AuthorizedRemoteHttpEnvironment,
RemoteEnvironmentAuthorization,
} from "./service.ts";
export * as TokenStore from "./tokenStore.ts";
diff --git a/packages/client-runtime/src/authorization/layer.test.ts b/packages/client-runtime/src/authorization/layer.test.ts
index 890a73d1696..5cd2d89d1ac 100644
--- a/packages/client-runtime/src/authorization/layer.test.ts
+++ b/packages/client-runtime/src/authorization/layer.test.ts
@@ -1,8 +1,16 @@
import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
+import {
+ RelayEnvironmentConnectScope,
+ type RelayEnvironmentConnectResponse,
+} from "@t3tools/contracts/relay";
import { describe, expect, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
@@ -31,10 +39,11 @@ const DESCRIPTOR = {
repositoryIdentity: true,
},
};
-const BOOTSTRAP: RemoteEnvironmentAuthorization.RelayEnvironmentAuthorization = {
+const BOOTSTRAP: RelayEnvironmentConnectResponse = {
environmentId: ENVIRONMENT_ID,
endpoint: ENDPOINT,
credential: "relay-bootstrap",
+ expiresAt: "2026-06-06T01:00:00.000Z",
};
function recordedFetch(responses: ReadonlyArray<Response>) {
@@ -76,9 +85,31 @@ const authInvalid = () =>
{ status: 401 },
);
+const persistedToken = (
+ input: {
+ readonly environmentId?: EnvironmentId;
+ readonly accessToken?: string;
+ readonly expiresAtEpochMs?: number;
+ readonly dpopThumbprint?: string;
+ } = {},
+) =>
+ new TokenStore.RemoteDpopAccessToken({
+ environmentId: input.environmentId ?? ENVIRONMENT_ID,
+ accountId: "account-1",
+ label: DESCRIPTOR.label,
+ endpoint: ENDPOINT,
+ accessToken: input.accessToken ?? "cached-access-token",
+ expiresAtEpochMs: input.expiresAtEpochMs ?? Number.MAX_SAFE_INTEGER,
+ dpopThumbprint: input.dpopThumbprint ?? "thumbprint-1",
+ });
+
const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (input: {
readonly initialToken?: TokenStore.RemoteDpopAccessToken;
readonly responses: ReadonlyArray<Response>;
+ readonly bootstrap?: RelayEnvironmentConnectResponse;
+ readonly beforeBootstrap?: Effect.Effect<void, ManagedRelay.ManagedRelayClientError>;
+ readonly beforePut?: Effect.Effect<void>;
+ readonly clerkToken?: ClientCapabilities.CloudSession["Service"]["clerkToken"];
}) {
const tokens = yield* Ref.make(
new Map(
@@ -88,6 +119,14 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
),
);
const bootstrapCalls = yield* Ref.make(0);
+ const relayInputs = yield* Ref.make<
+ ReadonlyArray<Parameters<ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"]>[0]>
+ >([]);
+ const session = yield* Ref.make<Option.Option<ClientCapabilities.CloudSessionIdentity>>(
+ Option.some({ accountId: "account-1" }),
+ );
+ const thumbprint = yield* Ref.make("thumbprint-1");
+ const tokenReads = yield* Queue.unbounded<EnvironmentId>();
const proofInputs = yield* Ref.make<
ReadonlyArray<{
readonly method: string;
@@ -101,13 +140,18 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
get: (environmentId) =>
Ref.get(tokens).pipe(
Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))),
+ Effect.tap(() => Queue.offer(tokenReads, environmentId)),
),
put: (token) =>
- Ref.update(tokens, (current) => {
- const next = new Map(current);
- next.set(token.environmentId, token);
- return next;
- }),
+ (input.beforePut ?? Effect.void).pipe(
+ Effect.andThen(
+ Ref.update(tokens, (current) => {
+ const next = new Map(current);
+ next.set(token.environmentId, token);
+ return next;
+ }),
+ ),
+ ),
remove: (environmentId) =>
Ref.update(tokens, (current) => {
const next = new Map(current);
@@ -116,17 +160,47 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
}),
});
const signer = ManagedRelay.ManagedRelayDpopSigner.of({
- thumbprint: Effect.succeed("thumbprint-1"),
+ thumbprint: Ref.get(thumbprint),
createProof: (proofInput) =>
Ref.update(proofInputs, (current) => [...current, proofInput]).pipe(
Effect.as(`proof:${proofInput.url}`),
),
});
+ const unexpected = () => Effect.die("Unexpected relay request");
+ const relay = ManagedRelay.ManagedRelayClient.of({
+ relayUrl: "https://relay.example.test",
+ listEnvironments: unexpected,
+ listDevices: unexpected,
+ createEnvironmentLinkChallenge: unexpected,
+ linkEnvironment: unexpected,
+ unlinkEnvironment: unexpected,
+ getEnvironmentStatus: unexpected,
+ connectEnvironment: (request) =>
+ Effect.gen(function* () {
+ yield* Ref.update(bootstrapCalls, (count) => count + 1);
+ yield* Ref.update(relayInputs, (current) => [...current, request]);
+ yield* input.beforeBootstrap ?? Effect.void;
+ return input.bootstrap ?? BOOTSTRAP;
+ }),
+ registerDevice: unexpected,
+ unregisterDevice: unexpected,
+ registerLiveActivity: unexpected,
+ getAgentActivitySnapshot: unexpected,
+ resetTokenCache: Effect.void,
+ });
const layer = RemoteEnvironmentAuthorization.layer.pipe(
Layer.provide(
Layer.mergeAll(
remoteHttpClientLayer(fetch.fetchFn),
Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, signer),
+ Layer.succeed(ManagedRelay.ManagedRelayClient, relay),
+ Layer.succeed(ClientCapabilities.CloudSession, {
+ identity: Ref.get(session),
+ clerkToken: input.clerkToken ?? Effect.succeed("clerk-session"),
+ }),
+ Layer.succeed(ClientCapabilities.RelayDeviceIdentity, {
+ deviceId: Effect.succeed(Option.some("device-1")),
+ }),
Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),
Layer.succeed(
ClientCapabilities.ClientPresentation,
@@ -142,17 +216,16 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
),
),
);
- const obtainBootstrap = Ref.update(bootstrapCalls, (count) => count + 1).pipe(
- Effect.as(BOOTSTRAP),
- );
-
return {
layer,
tokens,
bootstrapCalls,
proofInputs,
fetch,
- obtainBootstrap,
+ relayInputs,
+ session,
+ thumbprint,
+ tokenReads,
};
});
@@ -234,10 +307,11 @@ describe("RemoteEnvironmentAuthorization", () => {
}),
);
- it.effect("reuses a valid persisted environment token without contacting the relay", () =>
+ it.effect("reuses a same-account persisted environment token without contacting the relay", () =>
Effect.gen(function* () {
const cached = new TokenStore.RemoteDpopAccessToken({
environmentId: ENVIRONMENT_ID,
+ accountId: "account-1",
label: DESCRIPTOR.label,
endpoint: ENDPOINT,
accessToken: "cached-access-token",
@@ -253,7 +327,6 @@ describe("RemoteEnvironmentAuthorization", () => {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return yield* remote.authorizeDpop({
expectedEnvironmentId: ENVIRONMENT_ID,
- obtainBootstrap: harness.obtainBootstrap,
});
}).pipe(Effect.provide(harness.layer));
@@ -271,6 +344,7 @@ describe("RemoteEnvironmentAuthorization", () => {
Effect.gen(function* () {
const expired = new TokenStore.RemoteDpopAccessToken({
environmentId: ENVIRONMENT_ID,
+ accountId: "account-1",
label: DESCRIPTOR.label,
endpoint: ENDPOINT,
accessToken: "expired-access-token",
@@ -290,7 +364,6 @@ describe("RemoteEnvironmentAuthorization", () => {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return yield* remote.authorizeDpop({
expectedEnvironmentId: ENVIRONMENT_ID,
- obtainBootstrap: harness.obtainBootstrap,
});
}).pipe(Effect.provide(harness.layer));
@@ -310,6 +383,7 @@ describe("RemoteEnvironmentAuthorization", () => {
Effect.gen(function* () {
const cached = new TokenStore.RemoteDpopAccessToken({
environmentId: ENVIRONMENT_ID,
+ accountId: "account-1",
label: DESCRIPTOR.label,
endpoint: ENDPOINT,
accessToken: "invalid-access-token",
@@ -330,7 +404,6 @@ describe("RemoteEnvironmentAuthorization", () => {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return yield* remote.authorizeDpop({
expectedEnvironmentId: ENVIRONMENT_ID,
- obtainBootstrap: harness.obtainBootstrap,
});
}).pipe(Effect.provide(harness.layer));
@@ -355,7 +428,6 @@ describe("RemoteEnvironmentAuthorization", () => {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return yield* remote.authorizeDpop({
expectedEnvironmentId: ENVIRONMENT_ID,
- obtainBootstrap: harness.obtainBootstrap,
});
}).pipe(Effect.provide(harness.layer), Effect.flip);
@@ -372,6 +444,7 @@ describe("RemoteEnvironmentAuthorization", () => {
Effect.gen(function* () {
const cached = new TokenStore.RemoteDpopAccessToken({
environmentId: ENVIRONMENT_ID,
+ accountId: "account-1",
label: DESCRIPTOR.label,
endpoint: ENDPOINT,
accessToken: "cached-access-token",
@@ -392,7 +465,6 @@ describe("RemoteEnvironmentAuthorization", () => {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return yield* remote.authorizeDpop({
expectedEnvironmentId: ENVIRONMENT_ID,
- obtainBootstrap: harness.obtainBootstrap,
});
}).pipe(Effect.provide(harness.layer));
@@ -407,7 +479,7 @@ describe("RemoteEnvironmentAuthorization", () => {
}),
);
- it.effect("does not persist a refreshed token until its websocket ticket succeeds", () =>
+ it.effect("removes a newly refreshed token when websocket ticket authorization fails", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
responses: [
@@ -421,7 +493,6 @@ describe("RemoteEnvironmentAuthorization", () => {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return yield* remote.authorizeDpop({
expectedEnvironmentId: ENVIRONMENT_ID,
- obtainBootstrap: harness.obtainBootstrap,
});
}).pipe(Effect.provide(harness.layer), Effect.flip);
@@ -430,4 +501,437 @@ describe("RemoteEnvironmentAuthorization", () => {
expect(harness.fetch.calls).toHaveLength(3);
}),
);
+
+ it.effect("uses the current cached HTTP token without a relay request or websocket ticket", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({ initialToken: persistedToken(), responses: [] });
+ const authorized = yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ return yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ }).pipe(Effect.provide(harness.layer));
+
+ expect(authorized).toEqual({
+ environmentId: ENVIRONMENT_ID,
+ label: DESCRIPTOR.label,
+ httpBaseUrl: ENDPOINT.httpBaseUrl,
+ httpAuthorization: {
+ _tag: "Dpop",
+ accessToken: "cached-access-token",
+ expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
+ },
+ });
+ expect(harness.fetch.calls).toHaveLength(0);
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
+ expect(yield* Ref.get(harness.proofInputs)).toEqual([]);
+ }),
+ );
+
+ it.effect(
+ "renews HTTP credentials near expiry through the current cloud account and device",
+ () =>
+ Effect.gen(function* () {
+ const now = yield* Clock.currentTimeMillis;
+ const harness = yield* makeHarness({
+ initialToken: persistedToken({ expiresAtEpochMs: now + 61_000 }),
+ responses: [Response.json(DESCRIPTOR), accessToken("fresh-access-token")],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const before = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ expect(before.httpAuthorization.accessToken).toBe("cached-access-token");
+ yield* TestClock.adjust("1 second");
+ const after = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ expect(after.httpAuthorization.accessToken).toBe("fresh-access-token");
+ expect(after.httpAuthorization.expiresAtEpochMs).toBe(now + 3_601_000);
+ }).pipe(Effect.provide(harness.layer));
+
+ expect(yield* Ref.get(harness.relayInputs)).toEqual([
+ {
+ environmentId: ENVIRONMENT_ID,
+ clerkToken: "clerk-session",
+ scopes: [RelayEnvironmentConnectScope],
+ deviceId: "device-1",
+ },
+ ]);
+ expect(harness.fetch.calls.map(([url]) => String(url))).toEqual([
+ `${ENDPOINT.httpBaseUrl}/.well-known/t3/environment`,
+ `${ENDPOINT.httpBaseUrl}/oauth/token`,
+ ]);
+ expect(yield* Ref.get(harness.proofInputs)).toEqual([
+ {
+ method: "POST",
+ url: `${ENDPOINT.httpBaseUrl}/oauth/token`,
+ },
+ ]);
+ }),
+ );
+
+ it.effect("does not evict a replacement token when a late request rejects the old one", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({
+ initialToken: persistedToken(),
+ responses: [Response.json(DESCRIPTOR), accessToken("replacement-token")],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const initial = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ const retry = {
+ expectedEnvironmentId: ENVIRONMENT_ID,
+ rejectedAccessToken: initial.httpAuthorization.accessToken,
+ };
+ const first = yield* remote.authorizeDpopHttp(retry);
+ const late = yield* remote.authorizeDpopHttp(retry);
+ expect(first.httpAuthorization.accessToken).toBe("replacement-token");
+ expect(late).toEqual(first);
+ }).pipe(Effect.provide(harness.layer));
+
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ expect(harness.fetch.calls).toHaveLength(2);
+ expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.accessToken).toBe(
+ "replacement-token",
+ );
+ }),
+ );
+
+ it.effect("shares one in-flight renewal between concurrent HTTP requests", () =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const harness = yield* makeHarness({
+ initialToken: persistedToken({ expiresAtEpochMs: 0 }),
+ beforeBootstrap: Deferred.succeed(started, undefined).pipe(
+ Effect.andThen(Deferred.await(release)),
+ ),
+ responses: [Response.json(DESCRIPTOR), accessToken("shared-token")],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const requests = yield* Effect.all(
+ Array.from({ length: 6 }, () =>
+ remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }),
+ ),
+ { concurrency: "unbounded" },
+ ).pipe(Effect.forkChild);
+ yield* Queue.takeN(harness.tokenReads, 6);
+ yield* Deferred.await(started);
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ yield* Deferred.succeed(release, undefined);
+ const results = yield* Fiber.join(requests);
+ expect(results.map((result) => result.httpAuthorization.accessToken)).toEqual(
+ Array(6).fill("shared-token"),
+ );
+ }).pipe(Effect.provide(harness.layer));
+
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ expect(harness.fetch.calls).toHaveLength(2);
+ }),
+ );
+
+ it.effect(
+ "shares a failed renewal and allows a later attempt instead of caching its failure",
+ () =>
+ Effect.gen(function* () {
+ const release = yield* Deferred.make<void, ManagedRelay.ManagedRelayClientError>();
+ const failure = new ManagedRelay.ManagedRelayRequestTimeoutError({
+ activity: "Relay environment connection",
+ timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,
+ traceId: null,
+ });
+ const harness = yield* makeHarness({
+ responses: [],
+ beforeBootstrap: Deferred.await(release),
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const requests = yield* Effect.all(
+ Array.from({ length: 6 }, () =>
+ remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }).pipe(Effect.flip),
+ ),
+ { concurrency: "unbounded" },
+ ).pipe(Effect.forkChild);
+ yield* Queue.takeN(harness.tokenReads, 6);
+ yield* Deferred.fail(release, failure);
+ const failures = yield* Fiber.join(requests);
+ expect(failures).toEqual(
+ Array(6).fill(
+ expect.objectContaining({
+ _tag: "ConnectionTransientError",
+ reason: "timeout",
+ }),
+ ),
+ );
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ yield* remote
+ .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID })
+ .pipe(Effect.flip);
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(2);
+ }).pipe(Effect.provide(harness.layer));
+ expect(harness.fetch.calls).toHaveLength(0);
+ }),
+ );
+
+ it.effect("does not block another environment behind a pending renewal", () =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const otherEnvironmentId = EnvironmentId.make("environment-2");
+ const harness = yield* makeHarness({
+ initialToken: persistedToken({
+ environmentId: otherEnvironmentId,
+ accessToken: "other-token",
+ }),
+ beforeBootstrap: Deferred.succeed(started, undefined).pipe(
+ Effect.andThen(Deferred.await(release)),
+ ),
+ responses: [Response.json(DESCRIPTOR), accessToken("fresh-token")],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const pending = yield* remote
+ .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID })
+ .pipe(Effect.forkChild);
+ yield* Deferred.await(started);
+ const other = yield* remote.authorizeDpopHttp({
+ expectedEnvironmentId: otherEnvironmentId,
+ });
+ expect(other.httpAuthorization.accessToken).toBe("other-token");
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(pending);
+ }).pipe(Effect.provide(harness.layer));
+ }),
+ );
+
+ it.effect("does not return or persist credentials after logout during renewal", () =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const harness = yield* makeHarness({
+ beforeBootstrap: Deferred.succeed(started, undefined).pipe(
+ Effect.andThen(Deferred.await(release)),
+ ),
+ responses: [],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const pending = yield* remote
+ .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID })
+ .pipe(Effect.flip, Effect.forkChild);
+ yield* Deferred.await(started);
+ yield* Ref.set(harness.session, Option.none());
+ yield* Deferred.succeed(release, undefined);
+ expect(yield* Fiber.join(pending)).toMatchObject({
+ _tag: "ConnectionBlockedError",
+ reason: "authentication",
+ });
+ }).pipe(Effect.provide(harness.layer));
+ expect((yield* Ref.get(harness.tokens)).size).toBe(0);
+ expect(harness.fetch.calls).toHaveLength(0);
+ }),
+ );
+
+ it.effect("removes an obsolete credential if logout overlaps the persistent write", () =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const harness = yield* makeHarness({
+ beforePut: Deferred.succeed(started, undefined).pipe(
+ Effect.andThen(Deferred.await(release)),
+ ),
+ responses: [Response.json(DESCRIPTOR), accessToken("obsolete-token")],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const pending = yield* remote
+ .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID })
+ .pipe(Effect.flip, Effect.forkChild);
+ yield* Deferred.await(started);
+ yield* Ref.set(harness.session, Option.none());
+ yield* Deferred.succeed(release, undefined);
+ expect(yield* Fiber.join(pending)).toMatchObject({
+ _tag: "ConnectionBlockedError",
+ reason: "authentication",
+ });
+ }).pipe(Effect.provide(harness.layer));
+ expect((yield* Ref.get(harness.tokens)).size).toBe(0);
+ }),
+ );
+
+ it.effect(
+ "renews another account's persisted token after the authorization service restarts",
+ () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({
+ initialToken: persistedToken(),
+ responses: [Response.json(DESCRIPTOR), accessToken("account-2-token")],
+ });
+ const authorize = Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ return yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ }).pipe(Effect.provide(harness.layer));
+
+ expect((yield* authorize).httpAuthorization.accessToken).toBe("cached-access-token");
+ yield* Ref.set(harness.session, Option.some({ accountId: "account-2" }));
+ expect((yield* authorize).httpAuthorization.accessToken).toBe("account-2-token");
+ expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.accountId).toBe("account-2");
+
+ yield* Ref.set(harness.session, Option.some({ accountId: "account-2" }));
+ expect((yield* authorize).httpAuthorization.accessToken).toBe("account-2-token");
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ expect(harness.fetch.calls).toHaveLength(2);
+ }),
+ );
+
+ it.effect("renews a legacy unowned token once and reuses its account-bound replacement", () =>
+ Effect.gen(function* () {
+ const legacy = new TokenStore.RemoteDpopAccessToken({
+ environmentId: ENVIRONMENT_ID,
+ label: DESCRIPTOR.label,
+ endpoint: ENDPOINT,
+ accessToken: "legacy-access-token",
+ expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
+ dpopThumbprint: "thumbprint-1",
+ });
+ const harness = yield* makeHarness({
+ initialToken: legacy,
+ responses: [Response.json(DESCRIPTOR), accessToken("account-bound-token")],
+ });
+ const authorize = Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ return yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ }).pipe(Effect.provide(harness.layer));
+
+ expect((yield* authorize).httpAuthorization.accessToken).toBe("account-bound-token");
+ expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.accountId).toBe("account-1");
+ expect((yield* authorize).httpAuthorization.accessToken).toBe("account-bound-token");
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ expect(harness.fetch.calls).toHaveLength(2);
+ }),
+ );
+
+ it.effect("requires fresh credentials after signing back into the same account", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({
+ initialToken: persistedToken(),
+ responses: [Response.json(DESCRIPTOR), accessToken("new-session-token")],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ yield* Ref.set(harness.session, Option.none());
+ const signedOut = yield* remote
+ .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID })
+ .pipe(Effect.flip);
+ expect(signedOut).toMatchObject({
+ _tag: "ConnectionBlockedError",
+ reason: "authentication",
+ });
+ yield* Ref.set(harness.session, Option.some({ accountId: "account-1" }));
+ const signedIn = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ expect(signedIn.httpAuthorization.accessToken).toBe("new-session-token");
+ }).pipe(Effect.provide(harness.layer));
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ }),
+ );
+
+ it.effect("renews a cached credential bound to a different signing key", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({
+ initialToken: persistedToken(),
+ responses: [Response.json(DESCRIPTOR), accessToken("new-key-token")],
+ });
+ yield* Ref.set(harness.thumbprint, "thumbprint-2");
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const authorized = yield* remote.authorizeDpopHttp({
+ expectedEnvironmentId: ENVIRONMENT_ID,
+ });
+ expect(authorized.httpAuthorization.accessToken).toBe("new-key-token");
+ }).pipe(Effect.provide(harness.layer));
+ expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.dpopThumbprint).toBe(
+ "thumbprint-2",
+ );
+ }),
+ );
+
+ it.effect("rejects a relay bootstrap for a different environment before contacting it", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({
+ responses: [],
+ bootstrap: { ...BOOTSTRAP, environmentId: EnvironmentId.make("wrong-environment") },
+ });
+ const failure = yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ return yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ }).pipe(Effect.provide(harness.layer), Effect.flip);
+ expect(failure).toMatchObject({ _tag: "ConnectionBlockedError", reason: "configuration" });
+ expect(harness.fetch.calls).toHaveLength(0);
+ }),
+ );
+
+ it.effect("keeps a shared renewal alive when one waiting request is interrupted", () =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const harness = yield* makeHarness({
+ beforeBootstrap: Deferred.succeed(started, undefined).pipe(
+ Effect.andThen(Deferred.await(release)),
+ ),
+ responses: [Response.json(DESCRIPTOR), accessToken("fresh-token")],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const pending = yield* remote
+ .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID })
+ .pipe(Effect.forkChild);
+ yield* Deferred.await(started);
+ const other = yield* remote
+ .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID })
+ .pipe(Effect.forkChild);
+ yield* Queue.takeN(harness.tokenReads, 2);
+ yield* Fiber.interrupt(pending);
+ yield* Deferred.succeed(release, undefined);
+ const authorized = yield* Fiber.join(other);
+ expect(authorized.httpAuthorization.accessToken).toBe("fresh-token");
+ const cached = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID });
+ expect(cached).toEqual(authorized);
+ }).pipe(Effect.provide(harness.layer));
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ }),
+ );
+
+ it.effect("times out a stalled cloud token read so later requests can renew again", () =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const reads = yield* Ref.make(0);
+ const harness = yield* makeHarness({
+ clerkToken: Effect.gen(function* () {
+ const read = yield* Ref.updateAndGet(reads, (value) => value + 1);
+ if (read === 1) {
+ yield* Deferred.succeed(started, undefined);
+ return yield* Effect.never;
+ }
+ return "clerk-session";
+ }),
+ responses: [Response.json(DESCRIPTOR), accessToken("fresh-token")],
+ });
+ yield* Effect.gen(function* () {
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ const pending = yield* remote
+ .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID })
+ .pipe(Effect.flip, Effect.forkChild);
+ yield* Deferred.await(started);
+ yield* TestClock.adjust("30 seconds");
+ expect(yield* Fiber.join(pending)).toMatchObject({
+ _tag: "ConnectionTransientError",
+ reason: "timeout",
+ });
+ const authorized = yield* remote.authorizeDpopHttp({
+ expectedEnvironmentId: ENVIRONMENT_ID,
+ });
+ expect(authorized.httpAuthorization.accessToken).toBe("fresh-token");
+ }).pipe(Effect.provide(harness.layer));
+ expect(yield* Ref.get(reads)).toBe(2);
+ expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
+ }),
+ );
});
diff --git a/packages/client-runtime/src/authorization/service.ts b/packages/client-runtime/src/authorization/service.ts
index d7adc9a99db..85929f73dd3 100644
--- a/packages/client-runtime/src/authorization/service.ts
+++ b/packages/client-runtime/src/authorization/service.ts
@@ -3,7 +3,8 @@ import {
EnvironmentId,
type ExecutionEnvironmentDescriptor,
} from "@t3tools/contracts";
-import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
+import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import {
exchangeRemoteDpopAccessToken,
type RemoteEnvironmentAuthError,
@@ -12,10 +13,15 @@ import {
} from "./remote.ts";
import {
environmentMismatchError,
+ mapManagedRelayError,
mapRemoteDpopEnvironmentError,
mapRemoteEnvironmentError,
} from "../connection/errors.ts";
-import { ConnectionBlockedError, type ConnectionAttemptError } from "../connection/model.ts";
+import {
+ ConnectionBlockedError,
+ ConnectionTransientError,
+ type ConnectionAttemptError,
+} from "../connection/model.ts";
import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import * as ClientCapabilities from "../platform/capabilities.ts";
@@ -24,10 +30,13 @@ import * as TokenStore from "./tokenStore.ts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
+import * as Scope from "effect/Scope";
+import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/unstable/http/HttpClient";
import {
@@ -35,12 +44,6 @@ import {
type PreparedHttpAuthorization,
} from "../connection/model.ts";
-export interface RelayEnvironmentAuthorization {
- readonly environmentId: EnvironmentId;
- readonly endpoint: RelayManagedEndpoint;
- readonly credential: string;
-}
-
export interface AuthorizedRemoteEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
@@ -49,6 +52,13 @@ export interface AuthorizedRemoteEnvironment {
readonly httpAuthorization: PreparedHttpAuthorization;
}
+export interface AuthorizedRemoteHttpEnvironment {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly httpBaseUrl: string;
+ readonly httpAuthorization: Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>;
+}
+
export class RemoteEnvironmentAuthorization extends Context.Service<
RemoteEnvironmentAuthorization,
{
@@ -61,16 +71,17 @@ export class RemoteEnvironmentAuthorization extends Context.Service<
}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
readonly authorizeDpop: (input: {
readonly expectedEnvironmentId: EnvironmentId;
- readonly obtainBootstrap: Effect.Effect<
- RelayEnvironmentAuthorization,
- ConnectionAttemptError
- >;
}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
+ readonly authorizeDpopHttp: (input: {
+ readonly expectedEnvironmentId: EnvironmentId;
+ readonly rejectedAccessToken?: string;
+ }) => Effect.Effect<AuthorizedRemoteHttpEnvironment, ConnectionAttemptError>;
}
>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
const BEARER_DESCRIPTOR_CACHE_TTL_MS = 10_000;
+const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000;
function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
@@ -88,10 +99,28 @@ const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescript
});
export const make = Effect.gen(function* () {
+ const serviceScope = yield* Scope.Scope;
const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
+ const relay = yield* ManagedRelay.ManagedRelayClient;
+ const cloudSession = yield* ClientCapabilities.CloudSession;
+ const deviceIdentity = yield* ClientCapabilities.RelayDeviceIdentity;
const presentation = yield* ClientCapabilities.ClientPresentation;
const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
const httpClient = yield* HttpClient.HttpClient;
+ const tokenLock = yield* Semaphore.make(1);
+ const tokenOwners = new Map<
+ EnvironmentId,
+ { readonly accessToken: string; readonly identity: ClientCapabilities.CloudSessionIdentity }
+ >();
+ const pendingTokens = new Map<
+ EnvironmentId,
+ {
+ readonly id: object;
+ readonly identity: ClientCapabilities.CloudSessionIdentity;
+ readonly thumbprint: string;
+ readonly token: Effect.Effect<TokenStore.RemoteDpopAccessToken, ConnectionAttemptError>;
+ }
+ >();
const bearerDescriptors = yield* Ref.make<
ReadonlyMap<
EnvironmentId,
@@ -192,74 +221,77 @@ export const make = Effect.gen(function* () {
},
);
- const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(
- function* (input: {
- readonly expectedEnvironmentId: Parameters<
- RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]
- >[0]["expectedEnvironmentId"];
- readonly obtainBootstrap: Parameters<
- RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]
- >[0]["obtainBootstrap"];
- }) {
- const thumbprint = yield* signer.thumbprint.pipe(
- Effect.mapError(
- () =>
- new ConnectionBlockedError({
- reason: "configuration",
- detail: "Could not load the environment authorization key.",
- }),
- ),
- Effect.withSpan("environment.authorization.dpopKey.resolve"),
- );
- const now = yield* Clock.currentTimeMillis;
- const cached = yield* tokenStore
- .get(input.expectedEnvironmentId)
- .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
- if (
- Option.isSome(cached) &&
- cached.value.environmentId === input.expectedEnvironmentId &&
- cached.value.dpopThumbprint === thumbprint &&
- cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS
- ) {
- yield* Effect.annotateCurrentSpan({
- "connection.remote_token_cache": "hit",
- });
- const cachedSocket = yield* createDpopSocketUrl(
- cached.value,
- CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
- ).pipe(Effect.result);
- if (Result.isSuccess(cachedSocket)) {
- return {
- environmentId: cached.value.environmentId,
- label: cached.value.label,
- httpBaseUrl: cached.value.endpoint.httpBaseUrl,
- socketUrl: cachedSocket.success,
- httpAuthorization: {
- _tag: "Dpop" as const,
- accessToken: cached.value.accessToken,
- expiresAtEpochMs: cached.value.expiresAtEpochMs,
- },
- };
- }
- if (cachedSocket.failure._tag === "ConnectionBlockedError") {
- return yield* mapDpopSocketError(cachedSocket.failure);
- }
- yield* tokenStore
- .remove(input.expectedEnvironmentId)
- .pipe(Effect.withSpan("environment.authorization.accessToken.remove"));
- }
+ const sessionChanged = () =>
+ new ConnectionBlockedError({
+ reason: "authentication",
+ detail: "Your cloud sign-in changed. Sign in again to authorize the environment.",
+ });
+
+ const assertSession = Effect.fnUntraced(function* (
+ identity: ClientCapabilities.CloudSessionIdentity,
+ ) {
+ const current = yield* cloudSession.identity;
+ if (Option.isNone(current) || current.value !== identity) {
+ return yield* sessionChanged();
+ }
+ });
- yield* Effect.annotateCurrentSpan({
- "connection.remote_token_cache": "miss",
+ // Called under tokenLock so a late rejection cannot remove a newer credential.
+ const removeRejectedToken = Effect.fnUntraced(function* (
+ environmentId: EnvironmentId,
+ accessToken: string,
+ ) {
+ const cached = yield* tokenStore.get(environmentId);
+ if (Option.isSome(cached) && cached.value.accessToken === accessToken) {
+ yield* tokenStore.remove(environmentId);
+ tokenOwners.delete(environmentId);
+ }
+ });
+
+ const obtainBootstrap = Effect.fn("relay.connection.bootstrap.obtain")(function* (
+ environmentId: EnvironmentId,
+ identity: ClientCapabilities.CloudSessionIdentity,
+ ) {
+ yield* assertSession(identity);
+ const clerkToken = yield* cloudSession.clerkToken.pipe(
+ Effect.withSpan("relay.connection.cloudSessionToken.resolve"),
+ );
+ const deviceId = yield* deviceIdentity.deviceId.pipe(
+ Effect.withSpan("relay.connection.deviceIdentity.resolve"),
+ );
+ yield* assertSession(identity);
+ const connected = yield* relay
+ .connectEnvironment({
+ clerkToken,
+ scopes: [RelayEnvironmentConnectScope],
+ environmentId,
+ ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
+ })
+ .pipe(Effect.mapError(mapManagedRelayError));
+ if (connected.environmentId !== environmentId) {
+ return yield* environmentMismatchError({
+ expected: environmentId,
+ actual: connected.environmentId,
});
- const bootstrap = yield* input.obtainBootstrap;
+ }
+ yield* assertSession(identity);
+ return connected;
+ });
+
+ const exchangeDpopToken = Effect.fn("clientRuntime.connection.remote.exchangeDpopToken")(
+ function* (
+ environmentId: EnvironmentId,
+ thumbprint: string,
+ identity: ClientCapabilities.CloudSessionIdentity,
+ ) {
+ const bootstrap = yield* obtainBootstrap(environmentId, identity);
const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl, "relay").pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.withSpan("environment.authorization.descriptor"),
);
- if (descriptor.environmentId !== input.expectedEnvironmentId) {
+ if (descriptor.environmentId !== environmentId) {
return yield* environmentMismatchError({
- expected: input.expectedEnvironmentId,
+ expected: environmentId,
actual: descriptor.environmentId,
});
}
@@ -277,6 +309,7 @@ export const make = Effect.gen(function* () {
}),
),
);
+ yield* assertSession(identity);
const access = yield* exchangeRemoteDpopAccessToken({
httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
credential: bootstrap.credential,
@@ -289,36 +322,186 @@ export const make = Effect.gen(function* () {
Effect.withSpan("environment.authorization.accessToken.exchange"),
);
const issuedAt = yield* Clock.currentTimeMillis;
- const token = new TokenStore.RemoteDpopAccessToken({
+ return new TokenStore.RemoteDpopAccessToken({
environmentId: descriptor.environmentId,
+ accountId: identity.accountId,
label: descriptor.label,
endpoint: bootstrap.endpoint,
accessToken: access.access_token,
expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
dpopThumbprint: thumbprint,
});
- const socketUrl = yield* createDpopSocketUrl(token).pipe(Effect.mapError(mapDpopSocketError));
- yield* tokenStore
- .put(token)
- .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
- return {
- environmentId: descriptor.environmentId,
- label: descriptor.label,
- httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
- socketUrl,
- httpAuthorization: {
- _tag: "Dpop" as const,
- accessToken: token.accessToken,
- expiresAtEpochMs: token.expiresAtEpochMs,
- },
- };
},
);
+ const getDpopToken = Effect.fn("clientRuntime.connection.remote.getDpopToken")(function* (
+ input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0],
+ ) {
+ const session = yield* cloudSession.identity;
+ if (Option.isNone(session)) {
+ return yield* sessionChanged();
+ }
+ const identity = session.value;
+ const thumbprint = yield* signer.thumbprint.pipe(
+ Effect.mapError(
+ () =>
+ new ConnectionBlockedError({
+ reason: "configuration",
+ detail: "Could not load the environment authorization key.",
+ }),
+ ),
+ Effect.withSpan("environment.authorization.dpopKey.resolve"),
+ );
+ const selected = yield* tokenLock.withPermits(1)(
+ Effect.gen(function* () {
+ yield* assertSession(identity);
+ const now = yield* Clock.currentTimeMillis;
+ const cached = yield* tokenStore
+ .get(input.expectedEnvironmentId)
+ .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
+ const owner = tokenOwners.get(input.expectedEnvironmentId);
+ if (
+ Option.isSome(cached) &&
+ cached.value.environmentId === input.expectedEnvironmentId &&
+ cached.value.accountId === identity.accountId &&
+ cached.value.dpopThumbprint === thumbprint &&
+ cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS &&
+ cached.value.accessToken !== input.rejectedAccessToken &&
+ (owner?.accessToken !== cached.value.accessToken || owner.identity === identity)
+ ) {
+ tokenOwners.set(input.expectedEnvironmentId, {
+ accessToken: cached.value.accessToken,
+ identity,
+ });
+ return { token: Effect.succeed(cached.value), fromCache: true };
+ }
+ if (input.rejectedAccessToken !== undefined) {
+ yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken);
+ }
+ const pending = pendingTokens.get(input.expectedEnvironmentId);
+ if (pending?.identity === identity && pending.thumbprint === thumbprint) {
+ return { token: pending.token, fromCache: false };
+ }
+
+ const id = {};
+ const fiber = yield* exchangeDpopToken(
+ input.expectedEnvironmentId,
+ thumbprint,
+ identity,
+ ).pipe(
+ Effect.flatMap((token) =>
+ tokenLock.withPermits(1)(
+ Effect.gen(function* () {
+ yield* assertSession(identity);
+ yield* tokenStore
+ .put(token)
+ .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
+ const current = yield* cloudSession.identity;
+ if (Option.isNone(current) || current.value !== identity) {
+ yield* removeRejectedToken(input.expectedEnvironmentId, token.accessToken);
+ return yield* sessionChanged();
+ }
+ tokenOwners.set(input.expectedEnvironmentId, {
+ accessToken: token.accessToken,
+ identity,
+ });
+ if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
+ pendingTokens.delete(input.expectedEnvironmentId);
+ }
+ return token;
+ }),
+ ),
+ ),
+ Effect.timeoutOrElse({
+ duration: DPOP_AUTHORIZATION_TIMEOUT_MS,
+ orElse: () =>
+ Effect.fail(
+ new ConnectionTransientError({
+ reason: "timeout",
+ detail: "Timed out renewing the environment credential.",
+ }),
+ ),
+ }),
+ Effect.ensuring(
+ tokenLock.withPermits(1)(
+ Effect.sync(() => {
+ if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
+ pendingTokens.delete(input.expectedEnvironmentId);
+ }
+ }),
+ ),
+ ),
+ // One caller's timeout must not cancel renewal for other HTTP requests.
+ Effect.forkIn(serviceScope),
+ );
+ const token = Fiber.join(fiber);
+ pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, token });
+ return { token, fromCache: false };
+ }),
+ );
+ yield* Effect.annotateCurrentSpan({
+ "connection.remote_token_cache": selected.fromCache ? "hit" : "miss",
+ });
+ const token = yield* selected.token;
+ yield* assertSession(identity);
+ return { token, fromCache: selected.fromCache, identity };
+ });
+
+ const httpAuthorization = (
+ token: TokenStore.RemoteDpopAccessToken,
+ ): AuthorizedRemoteHttpEnvironment => ({
+ environmentId: token.environmentId,
+ label: token.label,
+ httpBaseUrl: token.endpoint.httpBaseUrl,
+ httpAuthorization: {
+ _tag: "Dpop",
+ accessToken: token.accessToken,
+ expiresAtEpochMs: token.expiresAtEpochMs,
+ },
+ });
+
+ const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(function* (
+ input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
+ ) {
+ let selected = yield* getDpopToken(input);
+ if (selected.fromCache) {
+ const cachedSocket = yield* createDpopSocketUrl(
+ selected.token,
+ CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
+ ).pipe(Effect.result);
+ if (Result.isSuccess(cachedSocket)) {
+ yield* assertSession(selected.identity);
+ return { ...httpAuthorization(selected.token), socketUrl: cachedSocket.success };
+ }
+ if (cachedSocket.failure._tag === "ConnectionBlockedError") {
+ return yield* mapDpopSocketError(cachedSocket.failure);
+ }
+ selected = yield* getDpopToken({
+ ...input,
+ rejectedAccessToken: selected.token.accessToken,
+ });
+ }
+ const socket = yield* createDpopSocketUrl(selected.token).pipe(Effect.result);
+ if (Result.isFailure(socket)) {
+ yield* tokenLock.withPermits(1)(
+ removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken),
+ );
+ return yield* mapDpopSocketError(socket.failure);
+ }
+ yield* assertSession(selected.identity);
+ return { ...httpAuthorization(selected.token), socketUrl: socket.success };
+ });
+
return RemoteEnvironmentAuthorization.of({
authorizeBearer,
authorizeDpop: (input) =>
authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),
+ authorizeDpopHttp: (input) =>
+ getDpopToken(input).pipe(
+ Effect.map(({ token }) => httpAuthorization(token)),
+ Effect.withSpan("environment.authorization.http"),
+ withRelayClientTracing,
+ ),
});
});
diff --git a/packages/client-runtime/src/authorization/tokenStore.ts b/packages/client-runtime/src/authorization/tokenStore.ts
index c490a22da13..78be32653de 100644
--- a/packages/client-runtime/src/authorization/tokenStore.ts
+++ b/packages/client-runtime/src/authorization/tokenStore.ts
@@ -12,6 +12,7 @@ export class RemoteDpopAccessToken extends Schema.Class<RemoteDpopAccessToken>(
"@t3tools/client-runtime/authorization/RemoteDpopAccessToken",
)({
environmentId: EnvironmentId,
+ accountId: Schema.optionalKey(Schema.String),
label: Schema.String,
endpoint: RelayManagedEndpoint,
accessToken: Schema.String,
diff --git a/packages/client-runtime/src/connection/layer.ts b/packages/client-runtime/src/connection/layer.ts
index 7927151e5d4..43153838df3 100644
--- a/packages/client-runtime/src/connection/layer.ts
+++ b/packages/client-runtime/src/connection/layer.ts
@@ -11,13 +11,9 @@ import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import * as RpcSession from "../rpc/session.ts";
-const resolverLayer = ConnectionResolver.layer.pipe(
- Layer.provide(RemoteEnvironmentAuthorization.layer),
-);
-
export function layerWithOptions(options: RpcSession.RpcSessionOptions) {
const driverLayer = ConnectionDriver.layer.pipe(
- Layer.provide(Layer.mergeAll(resolverLayer, RpcSession.layerWithOptions(options))),
+ Layer.provide(Layer.mergeAll(ConnectionResolver.layer, RpcSession.layerWithOptions(options))),
);
const registryLayer = EnvironmentRegistry.layer.pipe(Layer.provide(driverLayer));
const onboardingLayer = ConnectionOnboarding.layer.pipe(Layer.provide(registryLayer));
@@ -37,7 +33,10 @@ export function layerWithOptions(options: RpcSession.RpcSessionOptions) {
);
}).pipe(Effect.withSpan("clientRuntime.connection.application.start")),
);
- return connectionStartupLayer.pipe(Layer.provideMerge(connectionServicesLayer));
+ return connectionStartupLayer.pipe(
+ Layer.provideMerge(connectionServicesLayer),
+ Layer.provideMerge(RemoteEnvironmentAuthorization.layer),
+ );
}
export const layer = layerWithOptions({});
diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.ts
index 5bfac4faada..d1fc270f21f 100644
--- a/packages/client-runtime/src/connection/resolver.test.ts
+++ b/packages/client-runtime/src/connection/resolver.test.ts
@@ -1,5 +1,4 @@
import { EnvironmentId, type DesktopSshEnvironmentTarget } from "@t3tools/contracts";
-import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -8,7 +7,6 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Tracer from "effect/Tracer";
-import * as ManagedRelay from "../relay/managedRelay.ts";
import * as ConnectionResolver from "./resolver.ts";
import * as ClientCapabilities from "../platform/capabilities.ts";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
@@ -35,7 +33,6 @@ const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
const ENDPOINT = {
httpBaseUrl: "https://environment.example.test",
wsBaseUrl: "wss://environment.example.test",
- providerKind: "cloudflare_tunnel" as const,
};
const SSH_TARGET: DesktopSshEnvironmentTarget = {
alias: "development",
@@ -51,10 +48,6 @@ function catalogEntry(
return { target, profile };
}
-function unsupported<A>(name: string): Effect.Effect<A> {
- return Effect.die(new Error(`Unexpected relay call: ${name}`));
-}
-
function collectingTracer(spans: Array<string>): Tracer.Tracer {
return Tracer.make({
span: (options) => {
@@ -69,30 +62,9 @@ function collectingTracer(spans: Array<string>): Tracer.Tracer {
});
}
-function relayClient(
- connectEnvironment: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"],
-) {
- return ManagedRelay.ManagedRelayClient.of({
- relayUrl: "https://relay.example.test",
- listEnvironments: () => unsupported("listEnvironments"),
- listDevices: () => unsupported("listDevices"),
- createEnvironmentLinkChallenge: () => unsupported("createEnvironmentLinkChallenge"),
- linkEnvironment: () => unsupported("linkEnvironment"),
- unlinkEnvironment: () => unsupported("unlinkEnvironment"),
- getEnvironmentStatus: () => unsupported("getEnvironmentStatus"),
- connectEnvironment,
- registerDevice: () => unsupported("registerDevice"),
- unregisterDevice: () => unsupported("unregisterDevice"),
- registerLiveActivity: () => unsupported("registerLiveActivity"),
- getAgentActivitySnapshot: () => unsupported("getAgentActivitySnapshot"),
- resetTokenCache: Effect.void,
- });
-}
-
const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((options?: {
readonly profiles?: ReadonlyArray<ConnectionProfile>;
readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
- readonly connectEnvironment?: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"];
readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
readonly primaryBearerToken?: string;
@@ -131,19 +103,18 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
authorizeDpop:
options?.authorizeDpop ??
((input) =>
- input.obtainBootstrap.pipe(
- Effect.as({
- environmentId: input.expectedEnvironmentId,
- label: "Authorized relay environment",
- httpBaseUrl: ENDPOINT.httpBaseUrl,
- socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
- httpAuthorization: {
- _tag: "Dpop" as const,
- accessToken: "dpop-access-token",
- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
- },
- }),
- )),
+ Effect.succeed({
+ environmentId: input.expectedEnvironmentId,
+ label: "Authorized relay environment",
+ httpBaseUrl: ENDPOINT.httpBaseUrl,
+ socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
+ httpAuthorization: {
+ _tag: "Dpop" as const,
+ accessToken: "dpop-access-token",
+ expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
+ },
+ })),
+ authorizeDpopHttp: () => Effect.die("unused"),
});
const ssh = ClientCapabilities.SshEnvironmentGateway.of({
provision: () => Effect.die("unused"),
@@ -165,10 +136,6 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
const dependencies = Layer.mergeAll(
Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
- Layer.succeed(
- ClientCapabilities.CloudSession,
- ClientCapabilities.CloudSession.of({ clerkToken: Effect.succeed("clerk-session") }),
- ),
Layer.succeed(
ClientCapabilities.PrimaryEnvironmentAuth,
ClientCapabilities.PrimaryEnvironmentAuth.of({
@@ -182,27 +149,8 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
scopes: [],
}),
),
- Layer.succeed(
- ClientCapabilities.RelayDeviceIdentity,
- ClientCapabilities.RelayDeviceIdentity.of({
- deviceId: Effect.succeed(Option.some("device-1")),
- }),
- ),
Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
- Layer.succeed(
- ManagedRelay.ManagedRelayClient,
- relayClient(
- options?.connectEnvironment ??
- ((input) =>
- Effect.succeed({
- environmentId: input.environmentId,
- endpoint: ENDPOINT,
- credential: "relay-bootstrap",
- expiresAt: "2026-06-06T00:00:00.000Z",
- })),
- ),
- ),
);
return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(dependencies)));
@@ -314,66 +262,27 @@ describe("ConnectionResolver", () => {
}),
);
- it.effect("brokers relay credentials with the current cloud session and device identity", () =>
+ it.effect("prepares relay connections with the authorized endpoint and credentials", () =>
Effect.gen(function* () {
- const relayInputs = yield* Ref.make<
- ReadonlyArray<{
- readonly clerkToken: string;
- readonly scopes: ReadonlyArray<string>;
- readonly deviceId?: string;
- }>
- >([]);
- const bootstrapCredentials = yield* Ref.make<ReadonlyArray<string>>([]);
const target = new RelayConnectionTarget({
environmentId: ENVIRONMENT_ID,
label: "Cloud",
});
- const brokerLayer = yield* makeDependencies({
- connectEnvironment: (input) =>
- Ref.update(relayInputs, (values) => [
- ...values,
- {
- clerkToken: input.clerkToken,
- scopes: input.scopes,
- ...(input.deviceId ? { deviceId: input.deviceId } : {}),
- },
- ]).pipe(
- Effect.as({
- environmentId: input.environmentId,
- endpoint: ENDPOINT,
- credential: "relay-bootstrap",
- expiresAt: "2026-06-06T00:00:00.000Z",
- }),
- ),
- authorizeDpop: (input) =>
- input.obtainBootstrap.pipe(
- Effect.tap((bootstrap) =>
- Ref.update(bootstrapCredentials, (values) => [...values, bootstrap.credential]),
- ),
- Effect.as({
- environmentId: input.expectedEnvironmentId,
- label: "Cloud",
- httpBaseUrl: ENDPOINT.httpBaseUrl,
- socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
- httpAuthorization: {
- _tag: "Dpop" as const,
- accessToken: "dpop-access-token",
- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
- },
- }),
- ),
- });
+ const brokerLayer = yield* makeDependencies();
const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
- expect((yield* broker.prepare(catalogEntry(target))).socketUrl).toContain("wsTicket=dpop");
- expect(yield* Ref.get(relayInputs)).toEqual([
- {
- clerkToken: "clerk-session",
- scopes: [RelayEnvironmentConnectScope],
- deviceId: "device-1",
+ expect(yield* broker.prepare(catalogEntry(target))).toEqual({
+ environmentId: ENVIRONMENT_ID,
+ label: "Authorized relay environment",
+ httpBaseUrl: ENDPOINT.httpBaseUrl,
+ socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
+ httpAuthorization: {
+ _tag: "Dpop",
+ accessToken: "dpop-access-token",
+ expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
},
- ]);
- expect(yield* Ref.get(bootstrapCredentials)).toEqual(["relay-bootstrap"]);
+ target,
+ });
}),
);
@@ -387,20 +296,17 @@ describe("ConnectionResolver", () => {
});
const brokerLayer = yield* makeDependencies({
authorizeDpop: (input) =>
- input.obtainBootstrap.pipe(
- Effect.as({
- environmentId: input.expectedEnvironmentId,
- label: "Cloud",
- httpBaseUrl: ENDPOINT.httpBaseUrl,
- socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
- httpAuthorization: {
- _tag: "Dpop" as const,
- accessToken: "dpop-access-token",
- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
- },
- }),
- Effect.withSpan("test.remote.authorizeDpop"),
- ),
+ Effect.succeed({
+ environmentId: input.expectedEnvironmentId,
+ label: "Cloud",
+ httpBaseUrl: ENDPOINT.httpBaseUrl,
+ socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
+ httpAuthorization: {
+ _tag: "Dpop" as const,
+ accessToken: "dpop-access-token",
+ expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
+ },
+ }).pipe(Effect.withSpan("test.remote.authorizeDpop")),
});
const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
@@ -470,27 +376,24 @@ describe("ConnectionResolver", () => {
}),
);
- it.effect("classifies relay request timeouts as retryable connection failures", () =>
+ it.effect("preserves relay authorization failure classification and trace details", () =>
Effect.gen(function* () {
const target = new RelayConnectionTarget({
environmentId: ENVIRONMENT_ID,
label: "Cloud",
});
+ const authorizationError = new ConnectionTransientError({
+ reason: "timeout",
+ detail: "Relay environment connection timed out.",
+ traceId: "relay-trace",
+ });
const brokerLayer = yield* makeDependencies({
- connectEnvironment: () =>
- Effect.fail(
- new ManagedRelay.ManagedRelayRequestTimeoutError({
- activity: "Relay environment connection",
- timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,
- traceId: null,
- }),
- ),
+ authorizeDpop: () => Effect.fail(authorizationError),
});
const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
- expect(error).toBeInstanceOf(ConnectionTransientError);
- expect(error).toMatchObject({ reason: "timeout" });
+ expect(error).toBe(authorizationError);
}),
);
});
diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.ts
index a786ed9f9d8..cbffca7b29e 100644
--- a/packages/client-runtime/src/connection/resolver.ts
+++ b/packages/client-runtime/src/connection/resolver.ts
@@ -1,5 +1,4 @@
import type { AuthClientPresentationMetadata } from "@t3tools/contracts";
-import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -9,7 +8,6 @@ import * as Schema from "effect/Schema";
import { appendClientConnectionParams } from "../authorization/remote.ts";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
-import * as ManagedRelay from "../relay/managedRelay.ts";
import * as ClientCapabilities from "../platform/capabilities.ts";
import {
BearerConnectionCredential,
@@ -18,12 +16,7 @@ import {
SshConnectionProfile,
} from "./catalog.ts";
import * as ConnectionCredentialStore from "./credentialStore.ts";
-import {
- credentialMissingError,
- environmentMismatchError,
- mapManagedRelayError,
- profileMissingError,
-} from "./errors.ts";
+import { credentialMissingError, environmentMismatchError, profileMissingError } from "./errors.ts";
import type {
BearerConnectionTarget,
ConnectionTarget,
@@ -148,38 +141,12 @@ const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")
});
const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(function* () {
- const relay = yield* ManagedRelay.ManagedRelayClient;
- const session = yield* ClientCapabilities.CloudSession;
- const identity = yield* ClientCapabilities.RelayDeviceIdentity;
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return Effect.fnUntraced(
function* (target: RelayConnectionTarget) {
const authorized = yield* remote.authorizeDpop({
expectedEnvironmentId: target.environmentId,
- obtainBootstrap: Effect.gen(function* () {
- const clerkToken = yield* session.clerkToken.pipe(
- Effect.withSpan("relay.connection.cloudSessionToken.resolve"),
- );
- const deviceId = yield* identity.deviceId.pipe(
- Effect.withSpan("relay.connection.deviceIdentity.resolve"),
- );
- const connected = yield* relay
- .connectEnvironment({
- clerkToken,
- scopes: [RelayEnvironmentConnectScope],
- environmentId: target.environmentId,
- ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
- })
- .pipe(Effect.mapError(mapManagedRelayError));
- if (connected.environmentId !== target.environmentId) {
- return yield* environmentMismatchError({
- expected: target.environmentId,
- actual: connected.environmentId,
- });
- }
- return connected;
- }).pipe(Effect.withSpan("relay.connection.bootstrap.obtain")),
});
return {
environmentId: authorized.environmentId,
diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts
index f532e504605..2da7a68bd3c 100644
--- a/packages/client-runtime/src/connection/supervisor.test.ts
+++ b/packages/client-runtime/src/connection/supervisor.test.ts
@@ -1,4 +1,4 @@
-import { EnvironmentId } from "@t3tools/contracts";
+import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
@@ -11,12 +11,21 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
import * as TestClock from "effect/testing/TestClock";
import * as Tracer from "effect/Tracer";
+import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
+import * as TokenStore from "../authorization/tokenStore.ts";
+import * as ClientCapabilities from "../platform/capabilities.ts";
+import {
+ ManagedRelayClient,
+ ManagedRelayDpopSigner,
+ ManagedRelayRequestTimeoutError,
+} from "../relay/managedRelay.ts";
+import { remoteHttpClientLayer } from "../rpc/http.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
+import { fetchEnvironmentSessionState } from "../state/session.ts";
import type { ConnectionCatalogEntry } from "./catalog.ts";
import * as Connectivity from "./connectivity.ts";
import * as ConnectionDriver from "./driver.ts";
import {
- DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,
ConnectionBlockedError,
ConnectionTransientError,
PrimaryConnectionTarget,
@@ -1127,183 +1136,220 @@ describe("EnvironmentSupervisor", () => {
}),
);
- it.effect("hands off relay authorization after the replacement session is ready", () =>
+ it.effect("keeps a healthy relay session when its HTTP access token expires", () =>
Effect.gen(function* () {
- const tokenLifetimeMs = DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS * 2;
- const replacementStarted = yield* Deferred.make<void>();
- const releaseReplacement = yield* Deferred.make<void>();
const harness = yield* makeHarness({
prepare: (attempt) =>
- attempt === 2
- ? Effect.fail(transient("Authorization refresh failed."))
- : Effect.succeed({
- ...PREPARED_CONNECTION,
- target: RELAY_TARGET,
- httpAuthorization: {
- _tag: "Dpop",
- accessToken: `access-token-${attempt}`,
- expiresAtEpochMs: tokenLifetimeMs * attempt,
- },
- }),
- ready: (attempt) =>
- attempt === 2
- ? Deferred.succeed(replacementStarted, undefined).pipe(
- Effect.andThen(Deferred.await(releaseReplacement)),
- )
- : Effect.void,
+ Effect.succeed({
+ ...PREPARED_CONNECTION,
+ target: RELAY_TARGET,
+ httpAuthorization: {
+ _tag: "Dpop",
+ accessToken: `access-token-${attempt}`,
+ expiresAtEpochMs: 3_600_000 * attempt,
+ },
+ }),
});
const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
- const firstSession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
- const firstPrepared = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared));
- yield* TestClock.adjust(DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - 1);
- expect(yield* Ref.get(harness.sessionCount)).toBe(1);
+ const session = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
- yield* TestClock.adjust(1);
- expect(yield* Ref.get(harness.prepareCount)).toBe(2);
- expect(yield* Ref.get(harness.sessionCount)).toBe(1);
- expect(yield* Ref.get(harness.releaseCount)).toBe(0);
- yield* Effect.yieldNow;
+ yield* TestClock.adjust("2 hours");
- yield* TestClock.adjust("2999 millis");
- expect(yield* Ref.get(harness.prepareCount)).toBe(2);
- yield* TestClock.adjust("1 milli");
- yield* Deferred.await(replacementStarted);
-
- expect(yield* Ref.get(harness.prepareCount)).toBe(3);
- expect(yield* Ref.get(harness.sessionCount)).toBe(2);
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
expect(yield* Ref.get(harness.releaseCount)).toBe(0);
+ expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(session);
expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
phase: "connected",
generation: 1,
});
- expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(firstSession);
- expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared))).toBe(
- firstPrepared,
- );
-
- yield* Deferred.succeed(releaseReplacement, undefined);
- yield* awaitState(
- supervisor.state,
- (state) => state.phase === "connected" && state.generation === 2,
- );
-
- expect(yield* Ref.get(harness.releaseCount)).toBe(1);
- expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).not.toBe(
- firstSession,
- );
- expect(
- Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).httpAuthorization,
- ).toMatchObject({ accessToken: "access-token-3" });
}).pipe(Effect.provide(TestClock.layer())),
);
- it.effect("cleans up timed-out replacements and an interrupted retry", () =>
+ it.effect("refreshes HTTP authorization without replacing the active relay session", () =>
Effect.gen(function* () {
- const tokenLifetimeMs = DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS * 2;
- const replacementStarted = yield* Deferred.make<void>();
- const retryStarted = yield* Deferred.make<void>();
- const harness = yield* makeHarness({
- prepare: (attempt) =>
- Effect.succeed({
- ...PREPARED_CONNECTION,
- target: RELAY_TARGET,
- httpAuthorization: {
- _tag: "Dpop",
- accessToken: `access-token-${attempt}`,
- expiresAtEpochMs: tokenLifetimeMs * attempt,
- },
+ const endpoint = {
+ httpBaseUrl: TARGET.httpBaseUrl,
+ wsBaseUrl: TARGET.wsBaseUrl,
+ providerKind: "cloudflare_tunnel" as const,
+ };
+ const token = yield* Ref.make(
+ Option.some(
+ new TokenStore.RemoteDpopAccessToken({
+ environmentId: TARGET.environmentId,
+ accountId: "test-account",
+ label: TARGET.label,
+ endpoint,
+ accessToken: "access-token-1",
+ expiresAtEpochMs: 3_600_000,
+ dpopThumbprint: "test-thumbprint",
}),
- ready: (attempt) => {
- if (attempt === 2) {
- return Deferred.succeed(replacementStarted, undefined).pipe(
- Effect.andThen(Effect.never),
+ ),
+ );
+ const bootstrapFails = yield* Ref.make(false);
+ const bootstrapCalls = yield* Ref.make(0);
+ const httpPaths: Array<string> = [];
+ const sessionAuthorizations: Array<string | null> = [];
+ const fetchFn = ((input, init) => {
+ const request = new Request(input, init);
+ const pathname = new URL(request.url).pathname;
+ httpPaths.push(pathname);
+ switch (pathname) {
+ case "/.well-known/t3/environment":
+ return Promise.resolve(
+ Response.json({
+ environmentId: TARGET.environmentId,
+ label: TARGET.label,
+ platform: { os: "linux", arch: "x64" },
+ serverVersion: "0.0.0-test",
+ capabilities: { repositoryIdentity: true },
+ }),
+ );
+ case "/oauth/token":
+ return Promise.resolve(
+ Response.json({
+ access_token: "access-token-2",
+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
+ token_type: "DPoP",
+ expires_in: 3_600,
+ scope: AuthStandardClientScopes.join(" "),
+ }),
+ );
+ case "/api/auth/websocket-ticket":
+ return Promise.resolve(
+ Response.json({
+ ticket: "ws-ticket",
+ expiresAt: "2026-09-04T01:00:00.000Z",
+ }),
+ );
+ case "/api/auth/session": {
+ const authorization = request.headers.get("authorization");
+ sessionAuthorizations.push(authorization);
+ return Promise.resolve(
+ Response.json({
+ authenticated: authorization === "DPoP access-token-2",
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["dpop-access-token"],
+ sessionCookieName: "t3_session_test",
+ },
+ scopes: AuthStandardClientScopes,
+ }),
);
}
- if (attempt === 3) {
- return Deferred.succeed(retryStarted, undefined).pipe(Effect.andThen(Effect.never));
+ default:
+ return Promise.reject(new Error(`Unexpected HTTP request to ${request.url}`));
+ }
+ }) satisfies typeof fetch;
+ const signer = ManagedRelayDpopSigner.of({
+ thumbprint: Effect.succeed("test-thumbprint"),
+ createProof: () => Effect.succeed("test-proof"),
+ });
+ const unused = () => Effect.die("Unexpected relay operation.");
+ const relay = ManagedRelayClient.of({
+ relayUrl: "https://relay.example.test",
+ listEnvironments: unused,
+ listDevices: unused,
+ createEnvironmentLinkChallenge: unused,
+ linkEnvironment: unused,
+ unlinkEnvironment: unused,
+ getEnvironmentStatus: unused,
+ connectEnvironment: Effect.fn("TestConnectionHttp.connectEnvironment")(function* () {
+ yield* Ref.update(bootstrapCalls, (count) => count + 1);
+ if (yield* Ref.get(bootstrapFails)) {
+ return yield* new ManagedRelayRequestTimeoutError({
+ activity: "Relay environment connection",
+ timeoutMs: 6_000,
+ traceId: null,
+ });
}
- return Effect.void;
- },
+ return {
+ environmentId: TARGET.environmentId,
+ endpoint,
+ credential: "relay-bootstrap",
+ expiresAt: "2026-09-04T01:00:00.000Z",
+ };
+ }),
+ registerDevice: unused,
+ unregisterDevice: unused,
+ registerLiveActivity: unused,
+ getAgentActivitySnapshot: unused,
+ resetTokenCache: Effect.void,
+ });
+ const httpLayer = remoteHttpClientLayer(fetchFn);
+ const remoteAuthorization = yield* RemoteEnvironmentAuthorization.make.pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ httpLayer,
+ Layer.succeed(ManagedRelayDpopSigner, signer),
+ Layer.succeed(ManagedRelayClient, relay),
+ Layer.succeed(ClientCapabilities.CloudSession, {
+ identity: Effect.succeed(Option.some({ accountId: "test-account" })),
+ clerkToken: Effect.succeed("clerk-token"),
+ }),
+ Layer.succeed(ClientCapabilities.RelayDeviceIdentity, {
+ deviceId: Effect.succeed(Option.none()),
+ }),
+ TokenStore.layer({
+ get: () => Ref.get(token),
+ put: (value) => Ref.set(token, Option.some(value)),
+ remove: () => Ref.set(token, Option.none()),
+ }),
+ Layer.succeed(ClientCapabilities.ClientPresentation, {
+ metadata: { label: "Test client", deviceType: "desktop" },
+ scopes: AuthStandardClientScopes,
+ }),
+ ),
+ ),
+ );
+ const harness = yield* makeHarness({
+ prepare: () =>
+ remoteAuthorization
+ .authorizeDpop({ expectedEnvironmentId: TARGET.environmentId })
+ .pipe(Effect.map((prepared) => ({ ...prepared, target: RELAY_TARGET }))),
});
const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));
-
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
- const firstSession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
- yield* TestClock.adjust(DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS);
- yield* Deferred.await(replacementStarted);
-
- expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(firstSession);
+ const session = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
+ const prepared = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared));
+ const readSession = fetchEnvironmentSessionState({
+ prepared,
+ signer: Option.some(signer),
+ remoteAuthorization: Option.some(remoteAuthorization),
+ }).pipe(Effect.provide(httpLayer));
+
+ yield* TestClock.adjust("2 hours");
+ expect((yield* readSession).authenticated).toBe(true);
+ expect(sessionAuthorizations).toEqual(["DPoP access-token-2"]);
+ expect(yield* Ref.get(bootstrapCalls)).toBe(1);
+ expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(session);
expect(yield* Ref.get(harness.releaseCount)).toBe(0);
-
- yield* TestClock.adjust("15 seconds");
- yield* Effect.yieldNow;
- expect(yield* Ref.get(harness.releaseCount)).toBe(1);
- expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(firstSession);
expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
phase: "connected",
generation: 1,
});
- yield* TestClock.adjust("3 seconds");
- yield* Deferred.await(retryStarted);
- expect(yield* Ref.get(harness.sessionCount)).toBe(3);
- expect(yield* Ref.get(harness.releaseCount)).toBe(1);
- expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(firstSession);
-
- yield* supervisor.disconnect;
- yield* awaitState(supervisor.state, (state) => state.phase === "available");
-
- expect(yield* Ref.get(harness.releaseCount)).toBe(3);
- expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
- expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
- }).pipe(Effect.provide(TestClock.layer())),
- );
-
- it.effect("does not keep a relay session past its authorization expiry", () =>
- Effect.gen(function* () {
- const tokenLifetimeMs = DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS * 2;
- const harness = yield* makeHarness({
- prepare: (attempt) =>
- attempt === 1
- ? Effect.succeed({
- ...PREPARED_CONNECTION,
- target: RELAY_TARGET,
- httpAuthorization: {
- _tag: "Dpop",
- accessToken: "access-token-1",
- expiresAtEpochMs: tokenLifetimeMs,
- },
- })
- : Effect.fail(transient("Authorization refresh failed.")),
- });
- const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
- initiallyDesired: true,
- }).pipe(Effect.provide(harness.dependencies));
-
- yield* awaitState(supervisor.state, (state) => state.phase === "connected");
- yield* TestClock.adjust(DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS);
- yield* Effect.yieldNow;
- for (const delay of [3_000, 4_000, 8_000, 16_000, 16_000, 13_000]) {
- yield* TestClock.adjust(delay);
- yield* Effect.yieldNow;
- }
-
- yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
-
+ yield* TestClock.adjust("2 hours");
+ yield* Ref.set(bootstrapFails, true);
+ const failure = yield* readSession.pipe(Effect.flip);
+ expect(failure._tag).toBe("RemoteEnvironmentAuthFetchError");
+ expect(yield* Ref.get(bootstrapCalls)).toBe(2);
+ expect(sessionAuthorizations).toEqual(["DPoP access-token-2"]);
+ expect(httpPaths.filter((path) => path === "/api/auth/websocket-ticket")).toHaveLength(1);
+ expect(httpPaths.filter((path) => path === "/oauth/token")).toHaveLength(1);
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
- expect(yield* Ref.get(harness.releaseCount)).toBe(1);
+ expect(yield* Ref.get(harness.releaseCount)).toBe(0);
+ expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(session);
expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
- phase: "backoff",
+ phase: "connected",
generation: 1,
});
- expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
- expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
}).pipe(Effect.provide(TestClock.layer())),
);
diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts
index 0ff7b247a16..0246a21397f 100644
--- a/packages/client-runtime/src/connection/supervisor.ts
+++ b/packages/client-runtime/src/connection/supervisor.ts
@@ -18,7 +18,6 @@ import type { ConnectionCatalogEntry } from "./catalog.ts";
import * as Connectivity from "./connectivity.ts";
import * as ConnectionDriver from "./driver.ts";
import {
- DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,
type ConnectionAttemptError,
type ConnectionTarget,
ConnectionTransientError,
@@ -61,24 +60,16 @@ interface TracedAttemptFailure {
readonly attemptSpan: Option.Option<Tracer.Span>;
}
-interface ScopedConnection {
- readonly attemptSpan: Option.Option<Tracer.Span>;
- readonly lease: ConnectionDriver.EnvironmentConnectionLease;
- readonly scope: Scope.Closeable;
-}
-
type AttemptOutcome =
| {
readonly _tag: "Interrupted";
readonly established: boolean;
- readonly generation: number;
readonly stable: boolean;
readonly resetRetry: boolean;
}
| {
readonly _tag: "Failure";
readonly established: boolean;
- readonly generation: number;
readonly stable: boolean;
readonly failure: TracedAttemptFailure;
};
@@ -86,26 +77,17 @@ type AttemptOutcome =
type EstablishmentEvent =
| {
readonly _tag: "Completed";
- readonly exit: Exit.Exit<ScopedConnection, TracedAttemptFailure>;
+ readonly exit: Exit.Exit<
+ {
+ readonly attemptSpan: Option.Option<Tracer.Span>;
+ readonly lease: ConnectionDriver.EnvironmentConnectionLease;
+ },
+ TracedAttemptFailure
+ >;
}
| { readonly _tag: "Interrupted"; readonly resetRetry: boolean }
| { readonly _tag: "TimedOut" };
-type ReplacementPreparationEvent =
- | { readonly _tag: "Completed"; readonly exit: Exit.Exit<ScopedConnection, TracedAttemptFailure> }
- | { readonly _tag: "TimedOut" }
- | { readonly _tag: "AuthorizationExpired" };
-
-type ConnectedLeaseEvent =
- | {
- readonly _tag: "ActiveCompleted";
- readonly exit: Exit.Exit<boolean, TracedAttemptFailure>;
- }
- | {
- readonly _tag: "ReplacementCompleted";
- readonly exit: Exit.Exit<Option.Option<ScopedConnection>, TracedAttemptFailure>;
- };
-
function exitUnlessInterrupted<A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<Exit.Exit<A, E>, never, R> {
@@ -186,18 +168,16 @@ function failureFromExit<A>(
target: ConnectionTarget,
exit: Exit.Exit<A, TracedAttemptFailure>,
established: boolean,
- generation: number,
stable: boolean,
): AttemptOutcome {
if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
- return { _tag: "Interrupted", established, generation, stable, resetRetry: false };
+ return { _tag: "Interrupted", established, stable, resetRetry: false };
}
const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
if (typedFailure) {
return {
_tag: "Failure",
established,
- generation,
stable,
failure: typedFailure.error,
};
@@ -205,7 +185,6 @@ function failureFromExit<A>(
return {
_tag: "Failure",
established,
- generation,
stable,
failure: {
error: new ConnectionTransientError({
@@ -313,10 +292,9 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
attempt: number,
generation: number,
lastFailure: ConnectionAttemptError | null,
- publishProgress: boolean,
) {
return yield* driver.connect(entry, (progress) =>
- publishProgress ? reportProgress(attempt, generation, lastFailure, progress) : Effect.void,
+ reportProgress(attempt, generation, lastFailure, progress),
);
});
@@ -367,17 +345,16 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
generation: number,
lastFailure: ConnectionAttemptError | null,
pendingRetry: Option.Option<PendingRetryTrace>,
- publishProgress: boolean,
) {
if (target._tag === "RelayConnectionTarget") {
return yield* traceRelayEstablishment(
- establishConnection(attempt, generation, lastFailure, publishProgress),
+ establishConnection(attempt, generation, lastFailure),
attempt,
generation,
pendingRetry,
);
}
- return yield* establishConnection(attempt, generation, lastFailure, publishProgress).pipe(
+ return yield* establishConnection(attempt, generation, lastFailure).pipe(
Effect.map((lease) => ({
attemptSpan: Option.none<Tracer.Span>(),
lease,
@@ -389,37 +366,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
);
});
- const forkScopedTracedConnection = Effect.fnUntraced(function* (
- attempt: number,
- generation: number,
- lastFailure: ConnectionAttemptError | null,
- pendingRetry: Option.Option<PendingRetryTrace>,
- publishProgress: boolean,
- ) {
- const parentScope = yield* Scope.Scope;
- return yield* Effect.uninterruptibleMask((restore) =>
- Effect.gen(function* () {
- const connectionScope = yield* Scope.fork(parentScope, "sequential");
- const fiber = yield* restore(
- establishTracedConnection(
- attempt,
- generation,
- lastFailure,
- pendingRetry,
- publishProgress,
- ).pipe(
- Scope.provide(connectionScope),
- Effect.map(
- (established) =>
- ({ ...established, scope: connectionScope }) satisfies ScopedConnection,
- ),
- ),
- ).pipe(Effect.forkChild);
- return { fiber, scope: connectionScope };
- }),
- );
- });
-
const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
for (;;) {
const next = yield* Queue.take(signals);
@@ -541,136 +487,17 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
}
});
- const waitForAuthorizationDeadline = Effect.fnUntraced(function* (
- preparedConnection: PreparedConnection,
- skewMs: number,
- ) {
- const authorization = preparedConnection.httpAuthorization;
- if (authorization?._tag !== "Dpop") {
- return yield* Effect.never;
- }
- const now = yield* Clock.currentTimeMillis;
- yield* Effect.sleep(Math.max(0, authorization.expiresAtEpochMs - now - skewMs));
- });
-
- const waitForActiveCompletion = Effect.fnUntraced(function* (active: ScopedConnection) {
- const exit = yield* exitUnlessInterrupted(
- Effect.raceAllFirst([
- active.lease.session.closed.pipe(
- Effect.mapError((error): TracedAttemptFailure => ({
- error,
- attemptSpan: active.attemptSpan,
- })),
- ),
- monitorConnectedLease(active.lease).pipe(
- Effect.mapError((error): TracedAttemptFailure => ({
- error,
- attemptSpan: active.attemptSpan,
- })),
- ),
- ]),
- );
- return { _tag: "ActiveCompleted", exit } satisfies ConnectedLeaseEvent;
- });
-
- const prepareReplacement = Effect.fnUntraced(function* (
- active: ScopedConnection,
- generation: number,
- ) {
- yield* waitForAuthorizationDeadline(active.lease.prepared, DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS);
- yield* Effect.logDebug(
- "Preparing a replacement environment connection before its DPoP token expires.",
- );
-
- let failureCount = 0;
- for (;;) {
- const candidate = yield* forkScopedTracedConnection(
- failureCount + 1,
- generation,
- null,
- Option.none(),
- false,
- );
- const replacement = yield* Effect.raceAllFirst([
- Fiber.await(candidate.fiber).pipe(
- Effect.map((exit): ReplacementPreparationEvent => ({ _tag: "Completed", exit })),
- ),
- waitForAuthorizationDeadline(active.lease.prepared, 0).pipe(
- Effect.as<ReplacementPreparationEvent>({ _tag: "AuthorizationExpired" }),
- ),
- Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
- Effect.as<ReplacementPreparationEvent>({ _tag: "TimedOut" }),
- ),
- ]);
-
- if (replacement._tag !== "Completed") {
- yield* Fiber.interrupt(candidate.fiber);
- yield* Fiber.await(candidate.fiber);
- yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
- } else if (Exit.isFailure(replacement.exit)) {
- yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
- }
- if (replacement._tag === "AuthorizationExpired") {
- return Option.none<ScopedConnection>();
- }
- if (replacement._tag === "Completed" && Exit.isSuccess(replacement.exit)) {
- return Option.some(replacement.exit.value);
- }
-
- let replacementError: ConnectionTransientError;
- if (replacement._tag === "Completed") {
- if (Exit.isSuccess(replacement.exit)) {
- return yield* Effect.die("A successful replacement was not installed.");
- }
- const failure = Cause.findErrorOption(replacement.exit.cause);
- if (Option.isNone(failure) || failure.value.error._tag === "ConnectionBlockedError") {
- return yield* Effect.failCause(replacement.exit.cause);
- }
- replacementError = failure.value.error;
- } else {
- replacementError = new ConnectionTransientError({
- reason: "timeout",
- detail: setupTimeoutDetail,
- });
- }
-
- const retryDelay = retryDelayMs(failureCount);
- failureCount += 1;
- yield* Effect.logWarning(
- "Could not prepare a replacement environment connection; keeping the active connection.",
- ).pipe(
- Effect.annotateLogs({
- "authorization.refresh.retry_delay_ms": retryDelay,
- ...safeErrorLogAttributes(replacementError),
- }),
- );
- const retryBeforeExpiry = yield* Effect.raceFirst(
- Effect.sleep(retryDelay).pipe(Effect.as(true)),
- waitForAuthorizationDeadline(active.lease.prepared, 0).pipe(Effect.as(false)),
- );
- if (!retryBeforeExpiry) {
- return Option.none<ScopedConnection>();
- }
- }
- });
-
const runAttempt = Effect.fnUntraced(function* (
attempt: number,
- previousGeneration: number,
+ generation: number,
lastFailure: ConnectionAttemptError | null,
pendingRetry: Option.Option<PendingRetryTrace>,
) {
- const initialGeneration = previousGeneration + 1;
yield* SubscriptionRef.set(prepared, Option.none());
- const initial = yield* forkScopedTracedConnection(
- attempt,
- initialGeneration,
- lastFailure,
- pendingRetry,
- true,
- );
const establishment = yield* Effect.raceAllFirst([
- Fiber.await(initial.fiber).pipe(
+ exitUnlessInterrupted(
+ establishTracedConnection(attempt, generation, lastFailure, pendingRetry),
+ ).pipe(
Effect.map((exit): EstablishmentEvent => ({
_tag: "Completed",
exit,
@@ -687,18 +514,10 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
),
]);
- if (establishment._tag !== "Completed") {
- yield* Fiber.interrupt(initial.fiber);
- yield* Fiber.await(initial.fiber);
- yield* Scope.close(initial.scope, Exit.void).pipe(Effect.ignore);
- } else if (Exit.isFailure(establishment.exit)) {
- yield* Scope.close(initial.scope, Exit.void).pipe(Effect.ignore);
- }
if (establishment._tag === "Interrupted") {
return {
_tag: "Interrupted",
established: false,
- generation: previousGeneration,
stable: false,
resetRetry: establishment.resetRetry,
} satisfies AttemptOutcome;
@@ -707,7 +526,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
return {
_tag: "Failure",
established: false,
- generation: previousGeneration,
stable: false,
failure: {
error: new ConnectionTransientError({
@@ -722,7 +540,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
const isUnexpectedDefect =
!Cause.hasInterruptsOnly(establishment.exit.cause) &&
!establishment.exit.cause.reasons.some(Cause.isFailReason);
- const outcome = failureFromExit(target, establishment.exit, false, previousGeneration, false);
+ const outcome = failureFromExit(target, establishment.exit, false, false);
if (isUnexpectedDefect) {
const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
@@ -737,20 +555,18 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
return outcome;
}
+ const active = establishment.exit.value;
const currentIntent = yield* Ref.get(intent);
if (!currentIntent.desired || currentIntent.network === "offline") {
return {
_tag: "Interrupted",
established: false,
- generation: previousGeneration,
stable: false,
resetRetry: false,
} satisfies AttemptOutcome;
}
const connectedAt = yield* Clock.currentTimeMillis;
- let active = establishment.exit.value;
- let activeGeneration = initialGeneration;
yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
yield* SubscriptionRef.set(session, Option.some(active.lease.session));
yield* setState({
@@ -759,78 +575,35 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
phase: "connected",
stage: null,
attempt,
- generation: activeGeneration,
+ generation,
lastFailure: null,
retryAt: null,
});
- for (;;) {
- const connectedEvent = yield* Effect.raceAllFirst([
- waitForActiveCompletion(active),
- exitUnlessInterrupted(prepareReplacement(active, activeGeneration + 1)).pipe(
- Effect.map((exit): ConnectedLeaseEvent => ({ _tag: "ReplacementCompleted", exit })),
- ),
- ]);
- const stable = (yield* Clock.currentTimeMillis) - connectedAt >= BACKOFF_RESET_AFTER_MS;
- if (connectedEvent._tag === "ActiveCompleted") {
- if (Exit.isSuccess(connectedEvent.exit)) {
- return {
- _tag: "Interrupted",
- established: true,
- generation: activeGeneration,
- stable,
- resetRetry: connectedEvent.exit.value,
- } satisfies AttemptOutcome;
- }
- return failureFromExit(target, connectedEvent.exit, true, activeGeneration, stable);
- }
- if (Exit.isFailure(connectedEvent.exit)) {
- return failureFromExit(target, connectedEvent.exit, true, activeGeneration, stable);
- }
- if (Option.isNone(connectedEvent.exit.value)) {
- return {
- _tag: "Interrupted",
- established: true,
- generation: activeGeneration,
- stable,
- resetRetry: true,
- } satisfies AttemptOutcome;
- }
-
- const candidate = connectedEvent.exit.value.value;
- const replacementIntent = yield* Ref.get(intent);
- if (!replacementIntent.desired || replacementIntent.network === "offline") {
- yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
- return {
- _tag: "Interrupted",
- established: true,
- generation: activeGeneration,
- stable,
- resetRetry: false,
- } satisfies AttemptOutcome;
- }
-
- const previous = active;
- yield* Effect.uninterruptible(
- Effect.gen(function* () {
- active = candidate;
- activeGeneration += 1;
- yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
- yield* SubscriptionRef.set(session, Option.some(active.lease.session));
- yield* setState({
- desired: true,
- network: replacementIntent.network,
- phase: "connected",
- stage: null,
- attempt: 1,
- generation: activeGeneration,
- lastFailure: null,
- retryAt: null,
- });
- yield* Scope.close(previous.scope, Exit.void).pipe(Effect.ignore);
- }),
- );
+ const connectedExit = yield* Effect.raceFirst(
+ active.lease.session.closed.pipe(
+ Effect.mapError((error): TracedAttemptFailure => ({
+ error,
+ attemptSpan: active.attemptSpan,
+ })),
+ ),
+ monitorConnectedLease(active.lease).pipe(
+ Effect.mapError((error): TracedAttemptFailure => ({
+ error,
+ attemptSpan: active.attemptSpan,
+ })),
+ ),
+ ).pipe(exitUnlessInterrupted);
+ const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
+ if (Exit.isSuccess(connectedExit)) {
+ return {
+ _tag: "Interrupted",
+ established: true,
+ stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
+ resetRetry: connectedExit.value,
+ } satisfies AttemptOutcome;
}
+ return failureFromExit(target, connectedExit, true, connectedForMs >= BACKOFF_RESET_AFTER_MS);
}, Effect.ensuring(clearLease));
const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
@@ -895,14 +668,15 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
}
const attempt = failureCount + 1;
+ const nextGeneration = generation + 1;
const outcome: AttemptOutcome = yield* Effect.scoped(
- runAttempt(attempt, generation, latestFailure, pendingRetry),
+ runAttempt(attempt, nextGeneration, latestFailure, pendingRetry),
);
// Consumed on every iteration so a stale marker can never leak into a
// later, unrelated failure.
const failedWakeProbe = yield* Ref.getAndSet(wakeProbeFailed, false);
- generation = outcome.generation;
if (outcome.established) {
+ generation = nextGeneration;
if (outcome.stable) {
resetRetryLadder();
latestFailure = null;
diff --git a/packages/client-runtime/src/platform/capabilities.ts b/packages/client-runtime/src/platform/capabilities.ts
index a20b7d404b2..bc793b00565 100644
--- a/packages/client-runtime/src/platform/capabilities.ts
+++ b/packages/client-runtime/src/platform/capabilities.ts
@@ -21,9 +21,15 @@ export interface ProvisionedSshEnvironment extends PreparedSshEnvironment {
readonly label: string;
}
+/** Stable for one signed-in session, including same-account token refreshes. */
+export interface CloudSessionIdentity {
+ readonly accountId: string;
+}
+
export class CloudSession extends Context.Service<
CloudSession,
{
+ readonly identity: Effect.Effect<Option.Option<CloudSessionIdentity>>;
readonly clerkToken: Effect.Effect<string, ConnectionAttemptError>;
}
>()("@t3tools/client-runtime/platform/capabilities/CloudSession") {}
diff --git a/packages/client-runtime/src/platform/storageDocument.test.ts b/packages/client-runtime/src/platform/storageDocument.test.ts
index 8ad6b81e12b..c9ab41e3bf5 100644
--- a/packages/client-runtime/src/platform/storageDocument.test.ts
+++ b/packages/client-runtime/src/platform/storageDocument.test.ts
@@ -1,5 +1,6 @@
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
+import * as Schema from "effect/Schema";
import * as TokenStore from "../authorization/tokenStore.ts";
import {
@@ -16,13 +17,19 @@ import {
SshConnectionTarget,
} from "../connection/model.ts";
import {
+ ConnectionCatalogDocument,
EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ putRemoteDpopTokenInCatalog,
registerConnectionInCatalog,
removeConnectionFromCatalog,
} from "./storageDocument.ts";
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
+const RELAY_TARGET = new RelayConnectionTarget({
+ environmentId: ENVIRONMENT_ID,
+ label: "Remote",
+});
const BEARER_TARGET = new BearerConnectionTarget({
environmentId: ENVIRONMENT_ID,
label: "Remote",
@@ -52,6 +59,26 @@ const REMOTE_TOKEN = new TokenStore.RemoteDpopAccessToken({
});
describe("ConnectionCatalogDocument", () => {
+ it.each([
+ { name: "legacy", accountId: undefined },
+ { name: "account-bound", accountId: "account-1" },
+ ])("round-trips a catalog containing a $name DPoP token", ({ accountId }) => {
+ const token = new TokenStore.RemoteDpopAccessToken({
+ ...REMOTE_TOKEN,
+ ...(accountId === undefined ? {} : { accountId }),
+ });
+ const document = {
+ ...EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ targets: [RELAY_TARGET],
+ remoteDpopTokens: [token],
+ };
+ const schema = Schema.fromJsonString(ConnectionCatalogDocument);
+ const restored = Schema.decodeUnknownSync(schema)(Schema.encodeSync(schema)(document));
+
+ expect(restored).toEqual(document);
+ expect(restored.remoteDpopTokens[0]?.accountId).toBe(accountId);
+ });
+
it("registers a bearer connection as one catalog mutation", () => {
const document = registerConnectionInCatalog(
EMPTY_CONNECTION_CATALOG_DOCUMENT,
@@ -117,6 +144,65 @@ describe("ConnectionCatalogDocument", () => {
);
});
+ it("stores a DPoP token for a registered relay environment", () => {
+ const registered = registerConnectionInCatalog(
+ EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ new RelayConnectionRegistration({ target: RELAY_TARGET }),
+ );
+
+ expect(putRemoteDpopTokenInCatalog(registered, REMOTE_TOKEN)).toEqual({
+ ...registered,
+ remoteDpopTokens: [REMOTE_TOKEN],
+ });
+ });
+
+ it("ignores a late DPoP token after the environment is removed", () => {
+ const registered = registerConnectionInCatalog(
+ EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ new RelayConnectionRegistration({ target: RELAY_TARGET }),
+ );
+ const removed = removeConnectionFromCatalog(registered, RELAY_TARGET);
+
+ expect(putRemoteDpopTokenInCatalog(removed, REMOTE_TOKEN)).toEqual(
+ EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ );
+ });
+
+ it("removes a DPoP token stored before the environment is removed", () => {
+ const registered = registerConnectionInCatalog(
+ EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ new RelayConnectionRegistration({ target: RELAY_TARGET }),
+ );
+ const refreshed = putRemoteDpopTokenInCatalog(registered, REMOTE_TOKEN);
+
+ expect(removeConnectionFromCatalog(refreshed, RELAY_TARGET)).toEqual(
+ EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ );
+ });
+
+ it("does not store DPoP tokens for a different environment or connection kind", () => {
+ const bearer = registerConnectionInCatalog(
+ EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ new BearerConnectionRegistration({
+ target: BEARER_TARGET,
+ profile: BEARER_PROFILE,
+ credential: BEARER_CREDENTIAL,
+ }),
+ );
+ const otherRelay = registerConnectionInCatalog(
+ EMPTY_CONNECTION_CATALOG_DOCUMENT,
+ new RelayConnectionRegistration({
+ target: new RelayConnectionTarget({
+ environmentId: EnvironmentId.make("environment-2"),
+ label: "Other relay",
+ }),
+ }),
+ );
+
+ expect(putRemoteDpopTokenInCatalog(bearer, REMOTE_TOKEN)).toBe(bearer);
+ expect(putRemoteDpopTokenInCatalog(otherRelay, REMOTE_TOKEN)).toBe(otherRelay);
+ });
+
it("persists the normalized SSH profile beside its target", () => {
const target = new SshConnectionTarget({
environmentId: ENVIRONMENT_ID,
diff --git a/packages/client-runtime/src/platform/storageDocument.ts b/packages/client-runtime/src/platform/storageDocument.ts
index 0ba55dfa2fb..40a008b6c9a 100644
--- a/packages/client-runtime/src/platform/storageDocument.ts
+++ b/packages/client-runtime/src/platform/storageDocument.ts
@@ -139,3 +139,24 @@ export function removeConnectionFromCatalog(
): ConnectionCatalogDocument {
return removeConnectionMetadata(document, target, true);
}
+
+export function putRemoteDpopTokenInCatalog(
+ document: ConnectionCatalogDocument,
+ token: TokenStore.RemoteDpopAccessToken,
+): ConnectionCatalogDocument {
+ const registered = document.targets.some(
+ (target) =>
+ target._tag === "RelayConnectionTarget" && target.environmentId === token.environmentId,
+ );
+ if (!registered) {
+ return document;
+ }
+ return {
+ ...document,
+ remoteDpopTokens: replaceCatalogValue(
+ document.remoteDpopTokens,
+ (value) => value.environmentId,
+ token,
+ ),
+ };
+}
diff --git a/packages/client-runtime/src/relay/discovery.test.ts b/packages/client-runtime/src/relay/discovery.test.ts
index 36dacf82648..fdbcceb7df8 100644
--- a/packages/client-runtime/src/relay/discovery.test.ts
+++ b/packages/client-runtime/src/relay/discovery.test.ts
@@ -62,6 +62,7 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
const listFailure = yield* Ref.make<ManagedRelay.ManagedRelayClientError | null>(null);
const secondListCall = yield* Deferred.make<void>();
const clerkToken = yield* Ref.make<string | null>("clerk-token");
+ const sessionIdentity = { accountId: "account-1" };
const wakeups = yield* SubscriptionRef.make<{
readonly sequence: number;
readonly reason: "application-active" | "credentials-changed";
@@ -127,6 +128,11 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
Layer.succeed(
ClientCapabilities.CloudSession,
ClientCapabilities.CloudSession.of({
+ identity: Ref.get(clerkToken).pipe(
+ Effect.map((token) =>
+ token === null ? Option.none() : Option.some(sessionIdentity),
+ ),
+ ),
clerkToken: Ref.get(clerkToken).pipe(
Effect.flatMap((token) =>
token === null
@@ -283,6 +289,7 @@ describe("RelayEnvironmentDiscovery", () => {
Layer.mergeAll(
Layer.succeed(ManagedRelay.ManagedRelayClient, client),
Layer.succeed(ClientCapabilities.CloudSession, {
+ identity: Effect.succeed(Option.some({ accountId: "account-1" })),
clerkToken: Effect.succeed("clerk-token"),
}),
Layer.succeed(Connectivity.Connectivity, {
diff --git a/packages/client-runtime/src/state/environmentHttpAuth.test.ts b/packages/client-runtime/src/state/environmentHttpAuth.test.ts
new file mode 100644
index 00000000000..114b2c67e54
--- /dev/null
+++ b/packages/client-runtime/src/state/environmentHttpAuth.test.ts
@@ -0,0 +1,531 @@
+import { describe, expect, it } from "@effect/vitest";
+import {
+ EnvironmentId,
+ ProjectId,
+ ProviderInstanceId,
+ ThreadId,
+ type AuthSessionState,
+ type OrchestrationShellSnapshot,
+ type OrchestrationThreadDetailSnapshot,
+} from "@t3tools/contracts";
+import * as Deferred from "effect/Deferred";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import { TestClock } from "effect/testing";
+import type { HttpClient } from "effect/unstable/http";
+
+import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
+import {
+ ConnectionTransientError,
+ RelayConnectionTarget,
+ type PreparedConnection,
+ type PreparedHttpAuthorization,
+} from "../connection/model.ts";
+import { ManagedRelayDpopSigner, type ManagedRelayDpopProofInput } from "../relay/managedRelay.ts";
+import { remoteHttpClientLayer, type RemoteEnvironmentRequestError } from "../rpc/http.ts";
+import {
+ fetchEnvironmentPullRequestDiff,
+ type PullRequestDiffCredentialRejectedError,
+ PullRequestDiffLoader,
+ pullRequestDiffLoaderLayer,
+} from "./pullRequestDiffHttp.ts";
+import { fetchEnvironmentSessionState } from "./session.ts";
+import { fetchEnvironmentShellSnapshot } from "./shellSnapshotHttp.ts";
+import { fetchEnvironmentThreadSnapshot } from "./threadSnapshotHttp.ts";
+
+const TARGET = new RelayConnectionTarget({
+ environmentId: EnvironmentId.make("environment-1"),
+ label: "Remote environment",
+});
+const PREPARED: PreparedConnection = {
+ environmentId: TARGET.environmentId,
+ label: TARGET.label,
+ httpBaseUrl: "https://previous.example.test",
+ socketUrl: "wss://previous.example.test/ws",
+ httpAuthorization: { _tag: "Dpop", accessToken: "expired-token", expiresAtEpochMs: 0 },
+ target: TARGET,
+};
+const CURRENT_ORIGIN = "https://current.example.test";
+const RENEWED_ORIGIN = "https://renewed.example.test";
+const DIFF = {
+ projectId: ProjectId.make("project-1"),
+ repository: "owner/repository",
+ number: 42,
+};
+const DIFF_RESULT = { patch: "diff --git a/file.ts b/file.ts", truncated: false, nextCursor: null };
+const AUTH = {
+ policy: "remote-reachable",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["dpop-access-token"],
+ sessionCookieName: "t3_session",
+} satisfies AuthSessionState["auth"];
+const SESSION = {
+ authenticated: true,
+ auth: AUTH,
+ scopes: ["orchestration:read", "orchestration:operate"],
+ sessionMethod: "dpop-access-token",
+} satisfies AuthSessionState;
+const UNAUTHENTICATED_SESSION = { authenticated: false, auth: AUTH } satisfies AuthSessionState;
+const SHELL = {
+ snapshotSequence: 1,
+ projects: [],
+ threads: [],
+ updatedAt: "2026-09-04T00:00:00.000Z",
+} satisfies OrchestrationShellSnapshot;
+const THREAD = {
+ snapshotSequence: 2,
+ thread: {
+ id: ThreadId.make("thread-1"),
+ projectId: ProjectId.make("project-1"),
+ title: "Thread",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-09-04T00:00:00.000Z",
+ updatedAt: "2026-09-04T00:00:00.000Z",
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ deletedAt: null,
+ messages: [],
+ proposedPlans: [],
+ activities: [],
+ checkpoints: [],
+ session: null,
+ },
+ page: { beforeCursor: null, hasMore: false, snapshotSequence: 2 },
+} satisfies OrchestrationThreadDetailSnapshot;
+
+function credentialRejectedResponse(reason = "invalid_credential") {
+ return Response.json(
+ {
+ _tag: "EnvironmentAuthInvalidError",
+ code: "auth_invalid",
+ reason,
+ traceId: "trace-rejected",
+ },
+ { status: 401 },
+ );
+}
+
+function makeHarness(reply: (requestNumber: number) => Response | Promise<Response>) {
+ const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
+ const authorizations: Array<
+ Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0]
+ > = [];
+ const proofs: Array<ManagedRelayDpopProofInput> = [];
+ const remoteAuthorization = RemoteEnvironmentAuthorization.of({
+ authorizeBearer: () => Effect.die("Unexpected bearer connection preparation."),
+ authorizeDpop: () => Effect.die("HTTP requests must not prepare a WebSocket connection."),
+ authorizeDpopHttp: (input) =>
+ Effect.sync(() => {
+ authorizations.push(input);
+ const rejected = input.rejectedAccessToken !== undefined;
+ return {
+ environmentId: TARGET.environmentId,
+ label: TARGET.label,
+ httpBaseUrl: rejected ? RENEWED_ORIGIN : CURRENT_ORIGIN,
+ httpAuthorization: {
+ _tag: "Dpop" as const,
+ accessToken: rejected ? "renewed-token" : "current-token",
+ expiresAtEpochMs: 3_600_000,
+ },
+ };
+ }),
+ });
+ const signer = ManagedRelayDpopSigner.of({
+ thumbprint: Effect.succeed("test-thumbprint"),
+ createProof: (input) =>
+ Effect.sync(() => {
+ proofs.push(input);
+ return `proof-${proofs.length}`;
+ }),
+ });
+ const fetchFn: typeof fetch = async (request, init) => {
+ calls.push({ url: String(request), init: init ?? {} });
+ return reply(calls.length);
+ };
+ return {
+ calls,
+ authorizations,
+ proofs,
+ remoteAuthorization,
+ input: {
+ prepared: PREPARED,
+ signer: Option.some(signer),
+ remoteAuthorization: Option.some(remoteAuthorization),
+ },
+ httpLayer: remoteHttpClientLayer(fetchFn),
+ };
+}
+
+type HttpInput = ReturnType<typeof makeHarness>["input"];
+const LOADERS: ReadonlyArray<{
+ readonly name: string;
+ readonly method: string;
+ readonly path: string;
+ readonly response: unknown;
+ readonly load: (
+ input: HttpInput,
+ ) => Effect.Effect<
+ unknown,
+ RemoteEnvironmentRequestError | PullRequestDiffCredentialRejectedError,
+ HttpClient.HttpClient
+ >;
+}> = [
+ {
+ name: "PR diff",
+ method: "POST",
+ path: "/api/pull-requests/diff",
+ response: DIFF_RESULT,
+ load: (input: HttpInput) => fetchEnvironmentPullRequestDiff({ ...input, diff: DIFF }),
+ },
+ {
+ name: "session permissions",
+ method: "GET",
+ path: "/api/auth/session",
+ response: SESSION,
+ load: fetchEnvironmentSessionState,
+ },
+ {
+ name: "shell snapshot",
+ method: "GET",
+ path: "/api/orchestration/shell",
+ response: SHELL,
+ load: fetchEnvironmentShellSnapshot,
+ },
+ {
+ name: "older thread history",
+ method: "GET",
+ path: "/api/orchestration/threads/thread-1",
+ response: THREAD,
+ load: (input: HttpInput) =>
+ fetchEnvironmentThreadSnapshot({
+ ...input,
+ threadId: THREAD.thread.id,
+ window: { turnLimit: 20, beforeCursor: "older-page" },
+ }),
+ },
+];
+
+describe("authenticated environment HTTP requests", () => {
+ it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => Response.json(loader.response));
+ const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
+
+ expect(result).toEqual(loader.response);
+ expect(harness.calls).toHaveLength(1);
+ const call = harness.calls[0]!;
+ const url = new URL(call.url);
+ expect(url.origin).toBe(CURRENT_ORIGIN);
+ expect(url.pathname).toBe(loader.path);
+ expect(call.init.method).toBe(loader.method);
+ expect(new Headers(call.init.headers).get("authorization")).toBe("DPoP current-token");
+ expect(new Headers(call.init.headers).get("dpop")).toBe("proof-1");
+ expect(call.init.credentials).toBeUndefined();
+ expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
+ expect(harness.proofs).toEqual([
+ {
+ method: loader.method,
+ url: `${CURRENT_ORIGIN}${loader.path}`,
+ accessToken: "current-token",
+ },
+ ]);
+ if (loader.name === "older thread history") {
+ expect(url.searchParams.get("turnLimit")).toBe("20");
+ expect(url.searchParams.get("beforeCursor")).toBe("older-page");
+ }
+ expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
+ }),
+ );
+
+ it.effect("retries a rejected diff once with a new token, endpoint, and proof", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness((requestNumber) =>
+ requestNumber === 1 ? credentialRejectedResponse() : Response.json(DIFF_RESULT),
+ );
+ const result = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
+ Effect.provide(harness.httpLayer),
+ );
+
+ expect(result).toEqual(DIFF_RESULT);
+ expect(harness.authorizations).toEqual([
+ { expectedEnvironmentId: TARGET.environmentId },
+ { expectedEnvironmentId: TARGET.environmentId, rejectedAccessToken: "current-token" },
+ ]);
+ expect(harness.calls.map((call) => call.url)).toEqual([
+ `${CURRENT_ORIGIN}/api/pull-requests/diff`,
+ `${RENEWED_ORIGIN}/api/pull-requests/diff`,
+ ]);
+ expect(
+ harness.calls.map((call) => new Headers(call.init.headers).get("authorization")),
+ ).toEqual(["DPoP current-token", "DPoP renewed-token"]);
+ expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual([
+ "proof-1",
+ "proof-2",
+ ]);
+ expect(harness.proofs[1]).toEqual({
+ method: "POST",
+ url: `${RENEWED_ORIGIN}/api/pull-requests/diff`,
+ accessToken: "renewed-token",
+ });
+ expect(harness.calls[1]!.init.body).toEqual(harness.calls[0]!.init.body);
+ }),
+ );
+
+ it.effect("uses the authorization service captured by the diff loader layer", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => Response.json(DIFF_RESULT));
+ const loaderLayer = pullRequestDiffLoaderLayer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ harness.httpLayer,
+ Layer.succeed(ManagedRelayDpopSigner, Option.getOrThrow(harness.input.signer)),
+ Layer.succeed(RemoteEnvironmentAuthorization, harness.remoteAuthorization),
+ ),
+ ),
+ );
+ const loader = yield* PullRequestDiffLoader.pipe(Effect.provide(loaderLayer));
+ const result = yield* loader.load(PREPARED, DIFF);
+
+ expect(result).toEqual(DIFF_RESULT);
+ expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
+ "DPoP current-token",
+ );
+ }),
+ );
+
+ it.effect("preserves the credential rejection after the one recovery attempt fails", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => credentialRejectedResponse());
+ const error = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
+ Effect.provide(harness.httpLayer),
+ Effect.flip,
+ );
+
+ expect(error).toMatchObject({
+ _tag: "PullRequestDiffCredentialRejectedError",
+ traceId: "trace-rejected",
+ });
+ expect(harness.calls).toHaveLength(2);
+ expect(harness.authorizations).toHaveLength(2);
+ }),
+ );
+
+ it.effect.each([
+ {
+ name: "insufficient scope",
+ reply: () =>
+ Response.json(
+ {
+ _tag: "EnvironmentScopeRequiredError",
+ code: "insufficient_scope",
+ requiredScope: "orchestration:read",
+ traceId: "trace-scope",
+ },
+ { status: 403 },
+ ),
+ errorTag: "EnvironmentScopeRequiredError",
+ },
+ {
+ name: "missing credential",
+ reply: () => credentialRejectedResponse("missing_credential"),
+ errorTag: "EnvironmentAuthInvalidError",
+ },
+ {
+ name: "Cloudflare 530",
+ reply: () => new Response("error code: 1033", { status: 530 }),
+ errorTag: "RemoteEnvironmentAuthUndeclaredStatusError",
+ },
+ {
+ name: "network failure",
+ reply: () => Promise.reject(new Error("Network unreachable")),
+ errorTag: "RemoteEnvironmentAuthFetchError",
+ },
+ ])("does not renew or retry on $name", ({ reply, errorTag }) =>
+ Effect.gen(function* () {
+ const harness = makeHarness(reply);
+ const error = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
+ Effect.provide(harness.httpLayer),
+ Effect.flip,
+ );
+
+ expect(error._tag).toBe(errorTag);
+ expect(harness.calls).toHaveLength(1);
+ expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
+ }),
+ );
+
+ it.effect("recovers a session's unauthenticated 200 response before checking permissions", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness((requestNumber) =>
+ Response.json(requestNumber === 1 ? UNAUTHENTICATED_SESSION : SESSION),
+ );
+ const result = yield* fetchEnvironmentSessionState(harness.input).pipe(
+ Effect.provide(harness.httpLayer),
+ );
+
+ expect(result).toEqual(SESSION);
+ expect(harness.authorizations[1]).toEqual({
+ expectedEnvironmentId: TARGET.environmentId,
+ rejectedAccessToken: "current-token",
+ });
+ expect(harness.calls).toHaveLength(2);
+ }),
+ );
+
+ it.effect("reports persistent session rejection instead of showing missing permissions", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
+ const error = yield* fetchEnvironmentSessionState(harness.input).pipe(
+ Effect.provide(harness.httpLayer),
+ Effect.flip,
+ );
+
+ expect(error).toMatchObject({
+ _tag: "RemoteEnvironmentAuthFetchError",
+ message: "The environment rejected the renewed session authorization.",
+ });
+ expect(harness.calls).toHaveLength(2);
+ }),
+ );
+
+ it.effect.each([
+ { name: "cookie", authorization: null },
+ { name: "bearer", authorization: { _tag: "Bearer", token: "bearer-token" } },
+ ] satisfies ReadonlyArray<{ name: string; authorization: PreparedHttpAuthorization | null }>)(
+ "leaves $name sessions unchanged without relay services",
+ ({ authorization }) =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
+ const result = yield* fetchEnvironmentSessionState({
+ prepared: { ...PREPARED, httpAuthorization: authorization },
+ signer: Option.none(),
+ }).pipe(Effect.provide(harness.httpLayer));
+
+ expect(result).toEqual(UNAUTHENTICATED_SESSION);
+ expect(harness.calls).toHaveLength(1);
+ expect(harness.authorizations).toEqual([]);
+ expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
+ authorization === null ? null : "Bearer bearer-token",
+ );
+ expect(harness.calls[0]!.init.credentials).toBe(
+ authorization === null ? "include" : undefined,
+ );
+ }),
+ );
+
+ it.effect("keeps the caller's timeout while waiting for renewal", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => Response.json(SESSION));
+ const authorizing = yield* Deferred.make<void>();
+ const remoteAuthorization = RemoteEnvironmentAuthorization.of({
+ ...harness.remoteAuthorization,
+ authorizeDpopHttp: () =>
+ Deferred.succeed(authorizing, undefined).pipe(Effect.andThen(Effect.never)),
+ });
+ const pending = yield* fetchEnvironmentSessionState({
+ ...harness.input,
+ remoteAuthorization: Option.some(remoteAuthorization),
+ timeoutMs: 100,
+ }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
+ yield* Deferred.await(authorizing);
+ yield* TestClock.adjust(100);
+
+ expect(yield* Fiber.join(pending)).toMatchObject({
+ _tag: "RemoteEnvironmentAuthTimeoutError",
+ requestUrl: `${PREPARED.httpBaseUrl}/api/auth/session`,
+ timeoutMs: 100,
+ });
+ expect(harness.calls).toEqual([]);
+ }),
+ );
+
+ it.effect("reports the current endpoint when the total timeout expires during HTTP", () =>
+ Effect.gen(function* () {
+ const requested = Promise.withResolvers<void>();
+ const response = Promise.withResolvers<Response>();
+ const harness = makeHarness(() => {
+ requested.resolve();
+ return response.promise;
+ });
+ const authorizing = yield* Deferred.make<void>();
+ const authorize = yield* Deferred.make<void>();
+ const remoteAuthorization = RemoteEnvironmentAuthorization.of({
+ ...harness.remoteAuthorization,
+ authorizeDpopHttp: (input) =>
+ Deferred.succeed(authorizing, undefined).pipe(
+ Effect.andThen(Deferred.await(authorize)),
+ Effect.andThen(harness.remoteAuthorization.authorizeDpopHttp(input)),
+ ),
+ });
+ const pending = yield* fetchEnvironmentSessionState({
+ ...harness.input,
+ remoteAuthorization: Option.some(remoteAuthorization),
+ timeoutMs: 100,
+ }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
+ yield* Deferred.await(authorizing);
+ yield* TestClock.adjust(25);
+ yield* Deferred.succeed(authorize, undefined);
+ yield* Effect.promise(() => requested.promise);
+ yield* TestClock.adjust(75);
+
+ expect(yield* Fiber.join(pending)).toMatchObject({
+ _tag: "RemoteEnvironmentAuthTimeoutError",
+ requestUrl: `${CURRENT_ORIGIN}/api/auth/session`,
+ timeoutMs: 100,
+ });
+ expect(harness.calls.map((call) => call.url)).toEqual([`${CURRENT_ORIGIN}/api/auth/session`]);
+ expect(harness.authorizations).toHaveLength(1);
+ response.resolve(Response.json(SESSION));
+ }),
+ );
+
+ it.effect("reports renewal failure without sending the expired prepared token", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => Response.json(SESSION));
+ const failure = new ConnectionTransientError({
+ reason: "transport",
+ detail: "Relay unavailable",
+ });
+ const remoteAuthorization = RemoteEnvironmentAuthorization.of({
+ ...harness.remoteAuthorization,
+ authorizeDpopHttp: () => Effect.fail(failure),
+ });
+ const error = yield* fetchEnvironmentSessionState({
+ ...harness.input,
+ remoteAuthorization: Option.some(remoteAuthorization),
+ }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
+
+ expect(error).toMatchObject({
+ _tag: "RemoteEnvironmentAuthFetchError",
+ message: "Could not authorize the environment request.",
+ cause: failure,
+ });
+ expect(harness.calls).toEqual([]);
+ expect(harness.proofs).toEqual([]);
+ }),
+ );
+
+ it.effect("does not fall back to a captured DPoP token when authorization is unavailable", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => Response.json(SESSION));
+ const error = yield* fetchEnvironmentSessionState({
+ prepared: PREPARED,
+ signer: harness.input.signer,
+ }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
+
+ expect(error).toMatchObject({
+ _tag: "RemoteEnvironmentAuthFetchError",
+ message: "No relay authorization service is available for the environment request.",
+ });
+ expect(harness.calls).toEqual([]);
+ }),
+ );
+});
diff --git a/packages/client-runtime/src/state/environmentHttpAuth.ts b/packages/client-runtime/src/state/environmentHttpAuth.ts
index 09770806620..cfc42f56071 100644
--- a/packages/client-runtime/src/state/environmentHttpAuth.ts
+++ b/packages/client-runtime/src/state/environmentHttpAuth.ts
@@ -1,10 +1,18 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
-import { FetchHttpClient, type HttpMethod } from "effect/unstable/http";
+import * as Result from "effect/Result";
+import { FetchHttpClient, type HttpClient, type HttpMethod } from "effect/unstable/http";
-import type { PreparedHttpAuthorization } from "../connection/model.ts";
+import type { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
+import type { PreparedConnection, PreparedHttpAuthorization } from "../connection/model.ts";
import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
-import { RemoteEnvironmentAuthFetchError } from "../rpc/http.ts";
+import {
+ executeEnvironmentHttpRequest,
+ makeEnvironmentHttpApiClient,
+ RemoteEnvironmentAuthFetchError,
+ RemoteEnvironmentAuthTimeoutError,
+ type RemoteEnvironmentRequestError,
+} from "../rpc/http.ts";
export interface EnvironmentHttpAuthHeaders {
readonly authorization?: string;
@@ -28,8 +36,7 @@ export const withEnvironmentCredentials = <A, E, R>(
: request;
/**
- * Build the authorization headers for an authenticated environment HTTP
- * request, matching the credential the connection was prepared with:
+ * Build request-bound headers from the current environment credential:
* - primary/local connections carry no credential,
* - bearer connections send a static `Bearer` token,
* - relay connections send a `DPoP` access token with a freshly signed proof
@@ -71,3 +78,106 @@ export const buildEnvironmentAuthHeaders = (
);
return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof };
});
+
+/**
+ * Resolve relay credentials at request time without replacing the live socket.
+ * A rejected credential gets one refresh and retry, with a new request-bound
+ * proof. Cookie and bearer requests keep their existing authentication behavior.
+ */
+export const executeAuthenticatedEnvironmentHttpRequest = Effect.fn(
+ "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest",
+)(function* <A, E, R>(input: {
+ readonly prepared: PreparedConnection;
+ readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
+ readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
+ readonly method: HttpMethod.HttpMethod;
+ readonly url: (httpBaseUrl: string) => string;
+ readonly timeoutMs: number;
+ readonly request: (input: {
+ readonly client: Effect.Success<ReturnType<typeof makeEnvironmentHttpApiClient>>;
+ readonly headers: EnvironmentHttpAuthHeaders;
+ }) => Effect.Effect<A, E, R>;
+ /** Some endpoints report rejected credentials in a successful response. */
+ readonly isUnauthorizedResponse?: (response: NoInfer<A>) => boolean;
+}): Effect.fn.Return<A, RemoteEnvironmentRequestError, HttpClient.HttpClient | R> {
+ let httpBaseUrl = input.prepared.httpBaseUrl;
+ return yield* Effect.gen(function* () {
+ let rejectedAccessToken: string | undefined;
+ for (;;) {
+ let authorization = input.prepared.httpAuthorization;
+ if (authorization?._tag === "Dpop") {
+ const remote = input.remoteAuthorization;
+ if (remote === undefined || Option.isNone(remote)) {
+ return yield* new RemoteEnvironmentAuthFetchError({
+ message: "No relay authorization service is available for the environment request.",
+ cause: input.prepared.target._tag,
+ });
+ }
+ const current = yield* remote.value
+ .authorizeDpopHttp({
+ expectedEnvironmentId: input.prepared.environmentId,
+ ...(rejectedAccessToken === undefined ? {} : { rejectedAccessToken }),
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new RemoteEnvironmentAuthFetchError({
+ message: "Could not authorize the environment request.",
+ cause,
+ }),
+ ),
+ );
+ httpBaseUrl = current.httpBaseUrl;
+ authorization = current.httpAuthorization;
+ }
+
+ const requestUrl = input.url(httpBaseUrl);
+ const client = yield* makeEnvironmentHttpApiClient(httpBaseUrl);
+ const headers = yield* buildEnvironmentAuthHeaders(
+ authorization,
+ input.method,
+ requestUrl,
+ input.signer,
+ );
+ const result = yield* executeEnvironmentHttpRequest(
+ requestUrl,
+ input.timeoutMs,
+ withEnvironmentCredentials(authorization, input.request({ client, headers })),
+ ).pipe(Effect.result);
+
+ if (Result.isFailure(result)) {
+ if (
+ authorization?._tag === "Dpop" &&
+ rejectedAccessToken === undefined &&
+ result.failure._tag === "EnvironmentAuthInvalidError" &&
+ result.failure.reason === "invalid_credential"
+ ) {
+ rejectedAccessToken = authorization.accessToken;
+ continue;
+ }
+ return yield* result.failure;
+ }
+
+ if (
+ authorization?._tag === "Dpop" &&
+ input.isUnauthorizedResponse?.(result.success) === true
+ ) {
+ if (rejectedAccessToken === undefined) {
+ rejectedAccessToken = authorization.accessToken;
+ continue;
+ }
+ return yield* new RemoteEnvironmentAuthFetchError({
+ message: "The environment rejected the renewed session authorization.",
+ cause: result.success,
+ });
+ }
+ return result.success;
+ }
+ }).pipe(
+ Effect.timeoutOrElse({
+ duration: input.timeoutMs,
+ orElse: () =>
+ Effect.fail(new RemoteEnvironmentAuthTimeoutError(input.url(httpBaseUrl), input.timeoutMs)),
+ }),
+ );
+});
diff --git a/packages/client-runtime/src/state/pullRequestDiffHttp.ts b/packages/client-runtime/src/state/pullRequestDiffHttp.ts
index b6b925917b9..fdb4fcde7de 100644
--- a/packages/client-runtime/src/state/pullRequestDiffHttp.ts
+++ b/packages/client-runtime/src/state/pullRequestDiffHttp.ts
@@ -10,15 +10,14 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
+import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
import type { PreparedConnection } from "../connection/model.ts";
import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
import {
- executeEnvironmentHttpRequest,
- makeEnvironmentHttpApiClient,
makeEnvironmentHttpApiUrlBuilder,
type RemoteEnvironmentRequestError,
} from "../rpc/http.ts";
-import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
+import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
const DEFAULT_PULL_REQUEST_DIFF_TIMEOUT_MS = 60_000;
@@ -46,26 +45,16 @@ export const fetchEnvironmentPullRequestDiff = Effect.fn(
readonly prepared: PreparedConnection;
readonly diff: PullRequestDiffInput;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
+ readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
readonly timeoutMs?: number;
}) {
- const requestUrl = makeEnvironmentHttpApiUrlBuilder(
- input.prepared.httpBaseUrl,
- ).pullRequests.diff();
- const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
- const headers = yield* buildEnvironmentAuthHeaders(
- input.prepared.httpAuthorization,
- "POST",
- requestUrl,
- input.signer,
- );
- return yield* executeEnvironmentHttpRequest(
- requestUrl,
- input.timeoutMs ?? DEFAULT_PULL_REQUEST_DIFF_TIMEOUT_MS,
- withEnvironmentCredentials(
- input.prepared.httpAuthorization,
- client.pullRequests.diff({ payload: input.diff, headers }),
- ),
- ).pipe(
+ return yield* executeAuthenticatedEnvironmentHttpRequest({
+ ...input,
+ method: "POST",
+ url: (httpBaseUrl) => makeEnvironmentHttpApiUrlBuilder(httpBaseUrl).pullRequests.diff(),
+ timeoutMs: input.timeoutMs ?? DEFAULT_PULL_REQUEST_DIFF_TIMEOUT_MS,
+ request: ({ client, headers }) => client.pullRequests.diff({ payload: input.diff, headers }),
+ }).pipe(
Effect.mapError((error) =>
error._tag === "EnvironmentAuthInvalidError" && error.reason === "invalid_credential"
? new PullRequestDiffCredentialRejectedError({
@@ -98,11 +87,15 @@ export const pullRequestDiffLoaderLayer: Layer.Layer<
Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
+ const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
return PullRequestDiffLoader.of({
load: (prepared, input) =>
- fetchEnvironmentPullRequestDiff({ prepared, diff: input, signer }).pipe(
- Effect.provideService(HttpClient.HttpClient, httpClient),
- ),
+ fetchEnvironmentPullRequestDiff({
+ prepared,
+ diff: input,
+ signer,
+ remoteAuthorization,
+ }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
});
}),
);
diff --git a/packages/client-runtime/src/state/session.ts b/packages/client-runtime/src/state/session.ts
index 43adb980f3a..5ed60afc8a5 100644
--- a/packages/client-runtime/src/state/session.ts
+++ b/packages/client-runtime/src/state/session.ts
@@ -6,14 +6,14 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
import type { HttpClient } from "effect/unstable/http";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
+import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
import { EnvironmentRegistry } from "../connection/registry.ts";
import type { PreparedConnection } from "../connection/model.ts";
import { EnvironmentSupervisor } from "../connection/supervisor.ts";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
-import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts";
-import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
+import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
import { followStreamInEnvironment } from "./runtime.ts";
function initialConfigOption<E>(
@@ -36,29 +36,26 @@ const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;
/**
* Read the granted scopes of this client's session on one environment via its
- * `/api/auth/session` endpoint, authenticated with whatever credential the
- * connection was prepared with (cookie, bearer, or DPoP).
+ * `/api/auth/session` endpoint, using the connection's authentication method
+ * and refreshing relay credentials when needed.
*/
export const fetchEnvironmentSessionState = Effect.fn(
"clientRuntime.state.fetchEnvironmentSessionState",
)(function* (input: {
readonly prepared: PreparedConnection;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
+ readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
readonly timeoutMs?: number;
}) {
- const requestUrl = environmentEndpointUrl(input.prepared.httpBaseUrl, "/api/auth/session");
- const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
- const headers = yield* buildEnvironmentAuthHeaders(
- input.prepared.httpAuthorization,
- "GET",
- requestUrl,
- input.signer,
- );
- return yield* executeEnvironmentHttpRequest(
- requestUrl,
- input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS,
- withEnvironmentCredentials(input.prepared.httpAuthorization, client.auth.session({ headers })),
- );
+ return yield* executeAuthenticatedEnvironmentHttpRequest({
+ ...input,
+ method: "GET",
+ url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/auth/session"),
+ timeoutMs: input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS,
+ request: ({ client, headers }) => client.auth.session({ headers }),
+ // This endpoint returns 200 with authenticated:false for expired credentials.
+ isUnauthorizedResponse: (response) => !response.authenticated,
+ });
});
export function createEnvironmentSessionAtoms<R, E>(
@@ -134,7 +131,8 @@ export function createEnvironmentSessionAtoms<R, E>(
}
return Effect.gen(function* () {
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
- return yield* fetchEnvironmentSessionState({ prepared, signer });
+ const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
+ return yield* fetchEnvironmentSessionState({ prepared, signer, remoteAuthorization });
});
})
.pipe(
diff --git a/packages/client-runtime/src/state/shellSnapshotHttp.ts b/packages/client-runtime/src/state/shellSnapshotHttp.ts
index b0a492a1305..aa1ad9081e0 100644
--- a/packages/client-runtime/src/state/shellSnapshotHttp.ts
+++ b/packages/client-runtime/src/state/shellSnapshotHttp.ts
@@ -6,11 +6,11 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { HttpClient } from "effect/unstable/http";
+import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
import type { PreparedConnection } from "../connection/model.ts";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
-import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts";
-import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
+import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
// fallback for long. The cached shell renders while this runs.
@@ -27,24 +27,16 @@ export const fetchEnvironmentShellSnapshot = Effect.fn(
)(function* (input: {
readonly prepared: PreparedConnection;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
+ readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
readonly timeoutMs?: number;
}) {
- const requestUrl = environmentEndpointUrl(input.prepared.httpBaseUrl, "/api/orchestration/shell");
- const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
- const headers = yield* buildEnvironmentAuthHeaders(
- input.prepared.httpAuthorization,
- "GET",
- requestUrl,
- input.signer,
- );
- return yield* executeEnvironmentHttpRequest(
- requestUrl,
- input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
- withEnvironmentCredentials(
- input.prepared.httpAuthorization,
- client.orchestration.shellSnapshot({ headers }),
- ),
- );
+ return yield* executeAuthenticatedEnvironmentHttpRequest({
+ ...input,
+ method: "GET",
+ url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/orchestration/shell"),
+ timeoutMs: input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
+ request: ({ client, headers }) => client.orchestration.shellSnapshot({ headers }),
+ });
});
/**
@@ -73,9 +65,10 @@ export const shellSnapshotLoaderLayer: Layer.Layer<
// Resolve the DPoP signer optionally: it is only needed for relay/DPoP
// connections, so the loader must not hard-require it.
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
+ const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
return ShellSnapshotLoader.of({
load: (prepared: PreparedConnection) =>
- fetchEnvironmentShellSnapshot({ prepared, signer }).pipe(
+ fetchEnvironmentShellSnapshot({ prepared, signer, remoteAuthorization }).pipe(
Effect.map(Option.some<OrchestrationShellSnapshot>),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.catchCause((cause) =>
diff --git a/packages/client-runtime/src/state/threadSnapshotHttp.ts b/packages/client-runtime/src/state/threadSnapshotHttp.ts
index 6acc3b5d8a4..a82d4c1555c 100644
--- a/packages/client-runtime/src/state/threadSnapshotHttp.ts
+++ b/packages/client-runtime/src/state/threadSnapshotHttp.ts
@@ -6,15 +6,12 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { HttpClient } from "effect/unstable/http";
+import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
import type { PreparedConnection } from "../connection/model.ts";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
-import {
- executeEnvironmentHttpRequest,
- makeEnvironmentHttpApiClient,
- type RemoteEnvironmentRequestError,
-} from "../rpc/http.ts";
-import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
+import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
+import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
// fallback for long. The cached thread renders while this runs, so the wait only
@@ -42,25 +39,17 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(
readonly prepared: PreparedConnection;
readonly threadId: ThreadId;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
+ readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
readonly timeoutMs?: number;
readonly window?: ThreadSnapshotWindow;
}) {
- const requestUrl = environmentEndpointUrl(
- input.prepared.httpBaseUrl,
- `/api/orchestration/threads/${input.threadId}`,
- );
- const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
- const headers = yield* buildEnvironmentAuthHeaders(
- input.prepared.httpAuthorization,
- "GET",
- requestUrl,
- input.signer,
- );
- return yield* executeEnvironmentHttpRequest(
- requestUrl,
- input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
- withEnvironmentCredentials(
- input.prepared.httpAuthorization,
+ return yield* executeAuthenticatedEnvironmentHttpRequest({
+ ...input,
+ method: "GET",
+ url: (httpBaseUrl) =>
+ environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
+ timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
+ request: ({ client, headers }) =>
client.orchestration.threadSnapshot({
params: { threadId: input.threadId },
payload: {
@@ -71,8 +60,7 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(
},
headers,
}),
- ),
- );
+ });
});
export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
@@ -106,12 +94,14 @@ export const threadSnapshotLoaderLayer: Layer.Layer<
// connections, so the loader must not hard-require it (bearer/primary
// connections work without one).
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
+ const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
return ThreadSnapshotLoader.of({
load: (prepared: PreparedConnection, threadId: ThreadId, window?: ThreadSnapshotWindow) =>
fetchEnvironmentThreadSnapshot({
prepared,
threadId,
signer,
+ remoteAuthorization,
...(window !== undefined ? { window } : {}),
}).pipe(
Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),