add managed relay tunnels and standards-based auth
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
348a9140e9
commit
556e893df0
212 files changed
+34451
-610
No files matched your search
@@ -26,3 +26,4 @@ export * from "./composerPathSearchState.ts";
|
||||
export * from "./archivedThreadsState.ts";
|
||||
export * from "./checkpointDiffState.ts";
|
||||
export * from "./remote.ts";
|
||||
export * from "./managedRelay.ts";
|
||||
@@ -0,0 +1,114 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { RelayEnvironmentStatusScope } from "@t3tools/contracts/relay";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import {
|
||||
MANAGED_RELAY_REQUEST_TIMEOUT_MS,
|
||||
ManagedRelayClient,
|
||||
ManagedRelayDpopSigner,
|
||||
managedRelayClientLayer,
|
||||
type ManagedRelayDpopProofInput,
|
||||
} from "./managedRelay.ts";
|
||||
import { remoteHttpClientLayer } from "./remote.ts";
|
||||
|
||||
function managedRelayTestLayer(fetchFn: typeof globalThis.fetch) {
|
||||
const httpClientLayer = remoteHttpClientLayer(fetchFn);
|
||||
const signerLayer = Layer.succeed(
|
||||
ManagedRelayDpopSigner,
|
||||
ManagedRelayDpopSigner.of({
|
||||
thumbprint: Effect.succeed("client-thumbprint"),
|
||||
createProof: (input: ManagedRelayDpopProofInput) => Effect.succeed(`proof:${input.url}`),
|
||||
}),
|
||||
);
|
||||
return managedRelayClientLayer({
|
||||
relayUrl: "https://relay.example.test",
|
||||
clientId: "t3-mobile",
|
||||
}).pipe(Layer.provide(signerLayer), Layer.provide(httpClientLayer));
|
||||
}
|
||||
|
||||
describe("ManagedRelayClient", () => {
|
||||
it.effect("reuses usable DPoP tokens and refreshes cleared or expiring cache entries", () => {
|
||||
let tokenExchangeCount = 0;
|
||||
const fetchFn = ((input) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/v1/client/dpop-token")) {
|
||||
tokenExchangeCount += 1;
|
||||
return Promise.resolve(
|
||||
Response.json({
|
||||
access_token: `relay-token-${tokenExchangeCount}`,
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "DPoP",
|
||||
expires_in: 10,
|
||||
scope: RelayEnvironmentStatusScope,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(
|
||||
Response.json({
|
||||
environmentId: "env-1",
|
||||
endpoint: {
|
||||
httpBaseUrl: "https://desktop.example.test/",
|
||||
wsBaseUrl: "wss://desktop.example.test/ws",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
},
|
||||
status: "online",
|
||||
checkedAt: "2026-05-25T00:01:00.000Z",
|
||||
descriptor: {
|
||||
environmentId: "env-1",
|
||||
label: "Desktop",
|
||||
platform: { os: "darwin", arch: "arm64" },
|
||||
serverVersion: "0.0.0-test",
|
||||
capabilities: { repositoryIdentity: true },
|
||||
},
|
||||
}),
|
||||
);
|
||||
}) satisfies typeof globalThis.fetch;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const relayClient = yield* ManagedRelayClient;
|
||||
const statusInput = {
|
||||
clerkToken: "clerk-token",
|
||||
scopes: [RelayEnvironmentStatusScope],
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
} as const;
|
||||
|
||||
yield* relayClient.getEnvironmentStatus(statusInput);
|
||||
yield* relayClient.getEnvironmentStatus(statusInput);
|
||||
expect(tokenExchangeCount).toBe(1);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(6));
|
||||
yield* relayClient.getEnvironmentStatus(statusInput);
|
||||
expect(tokenExchangeCount).toBe(2);
|
||||
|
||||
yield* relayClient.resetTokenCache;
|
||||
yield* relayClient.getEnvironmentStatus(statusInput);
|
||||
expect(tokenExchangeCount).toBe(3);
|
||||
}).pipe(Effect.provide(managedRelayTestLayer(fetchFn)));
|
||||
});
|
||||
|
||||
it.effect("times out stalled relay environment listing requests", () => {
|
||||
const fetchFn = (() =>
|
||||
new Promise<Response>(() => undefined)) satisfies typeof globalThis.fetch;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const relayClient = yield* ManagedRelayClient;
|
||||
const errorFiber = yield* relayClient
|
||||
.listEnvironments({ clerkToken: "clerk-token" })
|
||||
.pipe(Effect.flip, Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(MANAGED_RELAY_REQUEST_TIMEOUT_MS));
|
||||
const error = yield* Fiber.join(errorFiber);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ManagedRelayClientError",
|
||||
message: "Relay environment listing timed out.",
|
||||
});
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managedRelayTestLayer(fetchFn))));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,470 @@
|
||||
import {
|
||||
RelayAccessTokenType,
|
||||
RelayApi,
|
||||
type RelayClientEnvironmentRecord,
|
||||
RelayConnectEnvironmentEndpoint,
|
||||
type RelayDeviceRegistrationRequest,
|
||||
type RelayDpopAccessTokenScope,
|
||||
RelayDpopTokenExchangeGrantType,
|
||||
type RelayEnvironmentConnectRequest,
|
||||
type RelayEnvironmentConnectResponse,
|
||||
type RelayEnvironmentLinkChallengeRequest,
|
||||
type RelayEnvironmentLinkChallengeResponse,
|
||||
type RelayEnvironmentLinkRequest,
|
||||
type RelayEnvironmentLinkResponse,
|
||||
type RelayEnvironmentStatusResponse,
|
||||
RelayExchangeDpopAccessTokenEndpoint,
|
||||
RelayGetEnvironmentStatusEndpoint,
|
||||
RelayJwtSubjectTokenType,
|
||||
type RelayLiveActivityRegistrationRequest,
|
||||
RelayMobileRegistrationScope,
|
||||
type RelayOkResponse,
|
||||
type RelayPublicClientId,
|
||||
RelayRegisterDeviceEndpoint,
|
||||
RelayRegisterLiveActivityEndpoint,
|
||||
RelayUnregisterDeviceEndpoint,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { encodeOAuthScope, oauthScopeSetEquals } from "@t3tools/shared/oauthScope";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
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 SynchronizedRef from "effect/SynchronizedRef";
|
||||
import type { HttpMethod } from "effect/unstable/http/HttpMethod";
|
||||
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
|
||||
|
||||
export interface ManagedRelayDpopProofInput {
|
||||
readonly method: HttpMethod;
|
||||
readonly url: string;
|
||||
readonly accessToken?: string;
|
||||
}
|
||||
|
||||
export class ManagedRelayDpopSignerError extends Data.TaggedError("ManagedRelayDpopSignerError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ManagedRelayDpopSignerShape {
|
||||
readonly thumbprint: Effect.Effect<string, ManagedRelayDpopSignerError>;
|
||||
readonly createProof: (
|
||||
input: ManagedRelayDpopProofInput,
|
||||
) => Effect.Effect<string, ManagedRelayDpopSignerError>;
|
||||
}
|
||||
|
||||
export class ManagedRelayDpopSigner extends Context.Service<
|
||||
ManagedRelayDpopSigner,
|
||||
ManagedRelayDpopSignerShape
|
||||
>()("@t3tools/client-runtime/managedRelay/ManagedRelayDpopSigner") {}
|
||||
|
||||
export class ManagedRelayClientError extends Data.TaggedError("ManagedRelayClientError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export const MANAGED_RELAY_REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
interface CachedRelayAccessToken {
|
||||
readonly clerkToken: string;
|
||||
readonly thumbprint: string;
|
||||
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
readonly accessToken: string;
|
||||
readonly expiresAtMillis: number;
|
||||
}
|
||||
|
||||
export interface ManagedRelayAuthorization {
|
||||
readonly accessToken: string;
|
||||
readonly proof: string;
|
||||
readonly thumbprint: string;
|
||||
}
|
||||
|
||||
export interface ManagedRelayClientLayerOptions {
|
||||
readonly relayUrl: string;
|
||||
readonly clientId: RelayPublicClientId;
|
||||
}
|
||||
|
||||
export interface ManagedRelayClientShape {
|
||||
readonly relayUrl: string;
|
||||
readonly listEnvironments: (input: {
|
||||
readonly clerkToken: string;
|
||||
}) => Effect.Effect<ReadonlyArray<RelayClientEnvironmentRecord>, ManagedRelayClientError>;
|
||||
readonly createEnvironmentLinkChallenge: (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly payload: RelayEnvironmentLinkChallengeRequest;
|
||||
}) => Effect.Effect<RelayEnvironmentLinkChallengeResponse, ManagedRelayClientError>;
|
||||
readonly linkEnvironment: (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly payload: RelayEnvironmentLinkRequest;
|
||||
}) => Effect.Effect<RelayEnvironmentLinkResponse, ManagedRelayClientError>;
|
||||
readonly unlinkEnvironment: (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
|
||||
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
|
||||
readonly getEnvironmentStatus: (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
|
||||
}) => Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelayClientError>;
|
||||
readonly connectEnvironment: (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
|
||||
readonly deviceId?: string;
|
||||
}) => Effect.Effect<RelayEnvironmentConnectResponse, ManagedRelayClientError>;
|
||||
readonly registerDevice: (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly payload: RelayDeviceRegistrationRequest;
|
||||
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
|
||||
readonly unregisterDevice: (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly deviceId: string;
|
||||
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
|
||||
readonly registerLiveActivity: (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly payload: RelayLiveActivityRegistrationRequest;
|
||||
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
|
||||
readonly resetTokenCache: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class ManagedRelayClient extends Context.Service<
|
||||
ManagedRelayClient,
|
||||
ManagedRelayClientShape
|
||||
>()("@t3tools/client-runtime/managedRelay/ManagedRelayClient") {}
|
||||
|
||||
function relayClientError(message: string, cause?: unknown): ManagedRelayClientError {
|
||||
return new ManagedRelayClientError({ message, ...(cause === undefined ? {} : { cause }) });
|
||||
}
|
||||
|
||||
function timeoutRelayRequest(message: string) {
|
||||
return <A, E, R>(
|
||||
request: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<A, E | ManagedRelayClientError, R> =>
|
||||
request.pipe(
|
||||
Effect.timeoutOption(Duration.millis(MANAGED_RELAY_REQUEST_TIMEOUT_MS)),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.fail(relayClientError(message)),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function tokenMatches(
|
||||
token: CachedRelayAccessToken,
|
||||
input: {
|
||||
readonly clerkToken: string;
|
||||
readonly thumbprint: string;
|
||||
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
readonly nowMillis: number;
|
||||
},
|
||||
): boolean {
|
||||
return (
|
||||
token.clerkToken === input.clerkToken &&
|
||||
token.thumbprint === input.thumbprint &&
|
||||
token.expiresAtMillis > input.nowMillis + 5_000 &&
|
||||
input.scopes.every((scope) => token.scopes.includes(scope))
|
||||
);
|
||||
}
|
||||
|
||||
function bearerHeaders(clerkToken: string) {
|
||||
return { authorization: `Bearer ${clerkToken}` };
|
||||
}
|
||||
|
||||
function dpopHeaders(authorization: ManagedRelayAuthorization) {
|
||||
return {
|
||||
authorization: `DPoP ${authorization.accessToken}`,
|
||||
dpop: authorization.proof,
|
||||
};
|
||||
}
|
||||
|
||||
export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions) {
|
||||
return Layer.effect(
|
||||
ManagedRelayClient,
|
||||
Effect.gen(function* () {
|
||||
const signer = yield* ManagedRelayDpopSigner;
|
||||
const client = yield* HttpApiClient.make(RelayApi, { baseUrl: options.relayUrl });
|
||||
const cachedTokens = yield* SynchronizedRef.make<ReadonlyArray<CachedRelayAccessToken>>([]);
|
||||
const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: options.relayUrl });
|
||||
|
||||
type DpopProofTarget = Pick<ManagedRelayDpopProofInput, "method" | "url">;
|
||||
const dpopProofTargets = {
|
||||
exchangeAccessToken: (): DpopProofTarget => ({
|
||||
method: RelayExchangeDpopAccessTokenEndpoint.method,
|
||||
url: urlBuilder.token.exchangeDpopAccessToken(),
|
||||
}),
|
||||
getEnvironmentStatus: (
|
||||
environmentId: RelayClientEnvironmentRecord["environmentId"],
|
||||
): DpopProofTarget => ({
|
||||
method: RelayGetEnvironmentStatusEndpoint.method,
|
||||
url: urlBuilder.dpopClient.getEnvironmentStatus({ params: { environmentId } }),
|
||||
}),
|
||||
connectEnvironment: (
|
||||
environmentId: RelayClientEnvironmentRecord["environmentId"],
|
||||
): DpopProofTarget => ({
|
||||
method: RelayConnectEnvironmentEndpoint.method,
|
||||
url: urlBuilder.dpopClient.connectEnvironment({ params: { environmentId } }),
|
||||
}),
|
||||
registerDevice: (): DpopProofTarget => ({
|
||||
method: RelayRegisterDeviceEndpoint.method,
|
||||
url: urlBuilder.mobile.registerDevice(),
|
||||
}),
|
||||
unregisterDevice: (deviceId: string): DpopProofTarget => ({
|
||||
method: RelayUnregisterDeviceEndpoint.method,
|
||||
url: urlBuilder.mobile.unregisterDevice({ params: { deviceId } }),
|
||||
}),
|
||||
registerLiveActivity: (): DpopProofTarget => ({
|
||||
method: RelayRegisterLiveActivityEndpoint.method,
|
||||
url: urlBuilder.mobile.registerLiveActivity(),
|
||||
}),
|
||||
};
|
||||
|
||||
const obtainAccessToken = Effect.fn("clientRuntime.managedRelay.obtainAccessToken")(
|
||||
function* (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
readonly thumbprint: string;
|
||||
}) {
|
||||
const nowMillis = yield* Clock.currentTimeMillis;
|
||||
return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) => {
|
||||
const activeTokens = tokens.filter(
|
||||
(token) => token.expiresAtMillis > nowMillis + 5_000,
|
||||
);
|
||||
const cached = activeTokens.find((token) =>
|
||||
tokenMatches(token, { ...input, nowMillis }),
|
||||
);
|
||||
if (cached) {
|
||||
return Effect.succeed([cached, activeTokens] as const);
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
const proof = yield* signer
|
||||
.createProof(dpopProofTargets.exchangeAccessToken())
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not create relay token DPoP proof.", cause),
|
||||
),
|
||||
);
|
||||
const response = yield* client.token
|
||||
.exchangeDpopAccessToken({
|
||||
headers: { dpop: proof },
|
||||
payload: {
|
||||
grant_type: RelayDpopTokenExchangeGrantType,
|
||||
subject_token: input.clerkToken,
|
||||
subject_token_type: RelayJwtSubjectTokenType,
|
||||
requested_token_type: RelayAccessTokenType,
|
||||
resource: options.relayUrl,
|
||||
scope: encodeOAuthScope(input.scopes),
|
||||
client_id: options.clientId,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not exchange relay DPoP access token.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay DPoP access token exchange timed out."),
|
||||
);
|
||||
if (!oauthScopeSetEquals(response.scope, input.scopes)) {
|
||||
return yield* relayClientError(
|
||||
"Relay granted unexpected DPoP access token scopes.",
|
||||
);
|
||||
}
|
||||
const next: CachedRelayAccessToken = {
|
||||
clerkToken: input.clerkToken,
|
||||
thumbprint: input.thumbprint,
|
||||
scopes: input.scopes,
|
||||
accessToken: response.access_token,
|
||||
expiresAtMillis: nowMillis + response.expires_in * 1_000,
|
||||
};
|
||||
return [next, [...activeTokens, next]] as const;
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const authorize = (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
readonly target: DpopProofTarget;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const thumbprint = yield* signer.thumbprint.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not load relay DPoP proof key.", cause),
|
||||
),
|
||||
);
|
||||
const token = yield* obtainAccessToken({
|
||||
clerkToken: input.clerkToken,
|
||||
scopes: input.scopes,
|
||||
thumbprint,
|
||||
});
|
||||
const proof = yield* signer
|
||||
.createProof({
|
||||
...input.target,
|
||||
accessToken: token.accessToken,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not create relay request DPoP proof.", cause),
|
||||
),
|
||||
);
|
||||
return { accessToken: token.accessToken, proof, thumbprint };
|
||||
});
|
||||
|
||||
const authorizeMobileRegistration = (input: {
|
||||
readonly clerkToken: string;
|
||||
readonly target: DpopProofTarget;
|
||||
}) =>
|
||||
authorize({
|
||||
...input,
|
||||
scopes: [RelayMobileRegistrationScope],
|
||||
});
|
||||
|
||||
return ManagedRelayClient.of({
|
||||
relayUrl: options.relayUrl,
|
||||
listEnvironments: (input) =>
|
||||
client.client.listEnvironments({ headers: bearerHeaders(input.clerkToken) }).pipe(
|
||||
Effect.map((response) => response.environments),
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not list relay-managed environments.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay environment listing timed out."),
|
||||
),
|
||||
createEnvironmentLinkChallenge: (input) =>
|
||||
client.client
|
||||
.createEnvironmentLinkChallenge({
|
||||
headers: bearerHeaders(input.clerkToken),
|
||||
payload: input.payload,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not create relay environment link challenge.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay environment link challenge timed out."),
|
||||
),
|
||||
linkEnvironment: (input) =>
|
||||
client.client
|
||||
.linkEnvironment({
|
||||
headers: bearerHeaders(input.clerkToken),
|
||||
payload: input.payload,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not link relay environment.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay environment linking timed out."),
|
||||
),
|
||||
unlinkEnvironment: (input) =>
|
||||
client.client
|
||||
.unlinkEnvironment({
|
||||
headers: bearerHeaders(input.clerkToken),
|
||||
params: { environmentId: input.environmentId },
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not unlink relay environment.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay environment unlinking timed out."),
|
||||
),
|
||||
getEnvironmentStatus: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const authorization = yield* authorize({
|
||||
clerkToken: input.clerkToken,
|
||||
scopes: input.scopes,
|
||||
target: dpopProofTargets.getEnvironmentStatus(input.environmentId),
|
||||
});
|
||||
return yield* client.dpopClient
|
||||
.getEnvironmentStatus({
|
||||
headers: dpopHeaders(authorization),
|
||||
params: { environmentId: input.environmentId },
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not get relay environment status.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay environment status request timed out."),
|
||||
);
|
||||
}),
|
||||
connectEnvironment: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const authorization = yield* authorize({
|
||||
clerkToken: input.clerkToken,
|
||||
scopes: input.scopes,
|
||||
target: dpopProofTargets.connectEnvironment(input.environmentId),
|
||||
});
|
||||
const payload: RelayEnvironmentConnectRequest = {
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
clientKeyThumbprint: authorization.thumbprint,
|
||||
};
|
||||
return yield* client.dpopClient
|
||||
.connectEnvironment({
|
||||
headers: dpopHeaders(authorization),
|
||||
params: { environmentId: input.environmentId },
|
||||
payload,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not connect relay environment.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay environment connection timed out."),
|
||||
);
|
||||
}),
|
||||
registerDevice: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const authorization = yield* authorizeMobileRegistration({
|
||||
clerkToken: input.clerkToken,
|
||||
target: dpopProofTargets.registerDevice(),
|
||||
});
|
||||
return yield* client.mobile
|
||||
.registerDevice({
|
||||
headers: dpopHeaders(authorization),
|
||||
payload: input.payload,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not register relay mobile device.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay mobile device registration timed out."),
|
||||
);
|
||||
}),
|
||||
unregisterDevice: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const authorization = yield* authorizeMobileRegistration({
|
||||
clerkToken: input.clerkToken,
|
||||
target: dpopProofTargets.unregisterDevice(input.deviceId),
|
||||
});
|
||||
return yield* client.mobile
|
||||
.unregisterDevice({
|
||||
headers: dpopHeaders(authorization),
|
||||
params: { deviceId: input.deviceId },
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not unregister relay mobile device.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay mobile device unregistration timed out."),
|
||||
);
|
||||
}),
|
||||
registerLiveActivity: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const authorization = yield* authorizeMobileRegistration({
|
||||
clerkToken: input.clerkToken,
|
||||
target: dpopProofTargets.registerLiveActivity(),
|
||||
});
|
||||
return yield* client.mobile
|
||||
.registerLiveActivity({
|
||||
headers: dpopHeaders(authorization),
|
||||
payload: input.payload,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
relayClientError("Could not register relay live activity.", cause),
|
||||
),
|
||||
timeoutRelayRequest("Relay Live Activity registration timed out."),
|
||||
);
|
||||
}),
|
||||
resetTokenCache: SynchronizedRef.set(cachedTokens, []),
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -8,8 +8,11 @@ import * as TestClock from "effect/testing/TestClock";
|
||||
import { EnvironmentAuthInvalidError } from "@t3tools/contracts";
|
||||
import {
|
||||
bootstrapRemoteBearerSession,
|
||||
exchangeRemoteDpopAccessToken,
|
||||
fetchRemoteDpopSessionState,
|
||||
fetchRemoteEnvironmentDescriptor,
|
||||
fetchRemoteSessionState,
|
||||
issueRemoteDpopWebSocketTicket,
|
||||
issueRemoteWebSocketTicket,
|
||||
remoteHttpClientLayer,
|
||||
RemoteEnvironmentAuthInvalidJsonError,
|
||||
@@ -123,6 +126,55 @@ describe("remote", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("exchanges managed credentials and admits websocket requests with DPoP", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetch = recordedFetch(
|
||||
Response.json({
|
||||
access_token: "dpop-access-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "DPoP",
|
||||
expires_in: 3600,
|
||||
scope: "orchestration:read orchestration:operate terminal:operate review:write",
|
||||
}),
|
||||
Response.json({
|
||||
ticket: "ws-ticket",
|
||||
expiresAt: "2026-05-01T12:05:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const token = yield* exchangeRemoteDpopAccessToken({
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
credential: "one-time-credential",
|
||||
dpopProof: "token-proof",
|
||||
clientMetadata: {
|
||||
label: "T3 Code Mobile",
|
||||
deviceType: "mobile",
|
||||
os: "iOS",
|
||||
},
|
||||
}).pipe(provideRemoteHttp(fetch.fetchFn));
|
||||
yield* issueRemoteDpopWebSocketTicket({
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
accessToken: token.access_token,
|
||||
dpopProof: "resource-proof",
|
||||
}).pipe(provideRemoteHttp(fetch.fetchFn));
|
||||
|
||||
expectFetchCall(fetch.calls, 1, {
|
||||
url: "https://remote.example.com/oauth/token",
|
||||
method: "POST",
|
||||
headers: { dpop: "token-proof", "content-type": "application/x-www-form-urlencoded" },
|
||||
body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=one-time-credential&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&client_label=T3+Code+Mobile&client_device_type=mobile&client_os=iOS",
|
||||
});
|
||||
expectFetchCall(fetch.calls, 2, {
|
||||
url: "https://remote.example.com/api/auth/websocket-ticket",
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: "DPoP dpop-access-token",
|
||||
dpop: "resource-proof",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("submits optional client display metadata during bearer token exchange", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetch = recordedFetch(
|
||||
@@ -186,7 +238,7 @@ describe("remote", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("loads remote session state and websocket tokens over bearer auth", () =>
|
||||
it.effect("loads remote session state and websocket tickets over bearer auth", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetch = recordedFetch(
|
||||
Response.json(
|
||||
@@ -257,11 +309,11 @@ describe("remote", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const token = yield* issueRemoteWebSocketTicket({
|
||||
const ticket = yield* issueRemoteWebSocketTicket({
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
bearerToken: "bearer-token",
|
||||
}).pipe(provideRemoteHttp(fetch.fetchFn));
|
||||
expect(token).toMatchObject({
|
||||
expect(ticket).toMatchObject({
|
||||
ticket: "ws-ticket",
|
||||
});
|
||||
|
||||
@@ -286,6 +338,45 @@ describe("remote", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("loads remote session state with a DPoP-bound access token", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetch = recordedFetch(
|
||||
Response.json({
|
||||
authenticated: true,
|
||||
auth: {
|
||||
policy: "remote-reachable",
|
||||
bootstrapMethods: ["one-time-token"],
|
||||
sessionMethods: ["dpop-access-token"],
|
||||
sessionCookieName: "t3_session",
|
||||
},
|
||||
sessionMethod: "dpop-access-token",
|
||||
scopes: [
|
||||
"orchestration:read",
|
||||
"orchestration:operate",
|
||||
"terminal:operate",
|
||||
"review:write",
|
||||
],
|
||||
expiresAt: "2026-05-01T12:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
yield* fetchRemoteDpopSessionState({
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
accessToken: "dpop-access-token",
|
||||
dpopProof: "dpop-proof",
|
||||
}).pipe(provideRemoteHttp(fetch.fetchFn));
|
||||
|
||||
expectFetchCall(fetch.calls, 1, {
|
||||
url: "https://remote.example.com/api/auth/session",
|
||||
method: "GET",
|
||||
headers: {
|
||||
authorization: "DPoP dpop-access-token",
|
||||
dpop: "dpop-proof",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails hung fetch requests on the configured timeout", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetch = hangingFetch();
|
||||
@@ -360,27 +451,25 @@ describe("remote", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"mints a websocket url that targets the rpc route with a short-lived websocket ticket",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fetch = recordedFetch(
|
||||
Response.json(
|
||||
{
|
||||
ticket: "ws-ticket",
|
||||
expiresAt: "2026-05-01T12:05:00.000Z",
|
||||
},
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
it.effect("mints a websocket url that targets the rpc route with a short-lived ticket", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetch = recordedFetch(
|
||||
Response.json(
|
||||
{
|
||||
ticket: "ws-ticket",
|
||||
expiresAt: "2026-05-01T12:05:00.000Z",
|
||||
},
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
const url = yield* resolveRemoteWebSocketConnectionUrl({
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
bearerToken: "bearer-token",
|
||||
}).pipe(provideRemoteHttp(fetch.fetchFn));
|
||||
const url = yield* resolveRemoteWebSocketConnectionUrl({
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
bearerToken: "bearer-token",
|
||||
}).pipe(provideRemoteHttp(fetch.fetchFn));
|
||||
|
||||
expect(url).toBe("wss://remote.example.com/ws?wsTicket=ws-ticket");
|
||||
}),
|
||||
expect(url).toBe("wss://remote.example.com/ws?wsTicket=ws-ticket");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
EnvironmentHttpApi,
|
||||
EnvironmentHttpCommonError,
|
||||
} from "@t3tools/contracts";
|
||||
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import type {
|
||||
EnvironmentAuthInvalidError,
|
||||
EnvironmentInternalError,
|
||||
@@ -15,6 +14,7 @@ import type {
|
||||
EnvironmentRequestInvalidError,
|
||||
EnvironmentScopeRequiredError,
|
||||
} from "@t3tools/contracts";
|
||||
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -27,7 +27,7 @@ import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
|
||||
const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
|
||||
const remoteEndpointUrl = (httpBaseUrl: string, pathname: string): string => {
|
||||
export const remoteEndpointUrl = (httpBaseUrl: string, pathname: string): string => {
|
||||
const url = new URL(httpBaseUrl);
|
||||
url.pathname = pathname;
|
||||
url.search = "";
|
||||
@@ -43,6 +43,14 @@ const remoteApiBaseUrl = (httpBaseUrl: string): string => {
|
||||
return url.toString();
|
||||
};
|
||||
|
||||
const clientMetadataTokenExchangeFields = (
|
||||
clientMetadata: AuthClientPresentationMetadata | undefined,
|
||||
) => ({
|
||||
...(clientMetadata?.label ? { client_label: clientMetadata.label } : {}),
|
||||
...(clientMetadata?.deviceType ? { client_device_type: clientMetadata.deviceType } : {}),
|
||||
...(clientMetadata?.os ? { client_os: clientMetadata.os } : {}),
|
||||
});
|
||||
|
||||
export class RemoteEnvironmentAuthFetchError extends Data.TaggedError(
|
||||
"RemoteEnvironmentAuthFetchError",
|
||||
)<{
|
||||
@@ -170,6 +178,35 @@ export const makeEnvironmentHttpApiClient = (httpBaseUrl: string) =>
|
||||
});
|
||||
});
|
||||
|
||||
export const exchangeRemoteDpopAccessToken = Effect.fn(
|
||||
"clientRuntime.remote.exchangeRemoteDpopAccessToken",
|
||||
)(function* (input: {
|
||||
readonly httpBaseUrl: string;
|
||||
readonly credential: string;
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly clientMetadata?: AuthClientPresentationMetadata;
|
||||
readonly dpopProof: string;
|
||||
readonly timeoutMs?: number;
|
||||
}) {
|
||||
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
|
||||
const response = yield* executeRemoteRequest(
|
||||
remoteEndpointUrl(input.httpBaseUrl, "/oauth/token"),
|
||||
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
|
||||
client.auth.token({
|
||||
headers: { dpop: input.dpopProof },
|
||||
payload: {
|
||||
grant_type: AuthTokenExchangeGrantType,
|
||||
subject_token: input.credential,
|
||||
subject_token_type: AuthEnvironmentBootstrapTokenType,
|
||||
requested_token_type: AuthAccessTokenType,
|
||||
...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
|
||||
...clientMetadataTokenExchangeFields(input.clientMetadata),
|
||||
},
|
||||
}),
|
||||
);
|
||||
return response;
|
||||
});
|
||||
|
||||
export const bootstrapRemoteBearerSession = Effect.fn(
|
||||
"clientRuntime.remote.bootstrapRemoteBearerSession",
|
||||
)(function* (input: {
|
||||
@@ -184,17 +221,14 @@ export const bootstrapRemoteBearerSession = Effect.fn(
|
||||
remoteEndpointUrl(input.httpBaseUrl, "/oauth/token"),
|
||||
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
|
||||
client.auth.token({
|
||||
headers: {},
|
||||
payload: {
|
||||
grant_type: AuthTokenExchangeGrantType,
|
||||
subject_token: input.credential,
|
||||
subject_token_type: AuthEnvironmentBootstrapTokenType,
|
||||
requested_token_type: AuthAccessTokenType,
|
||||
...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
|
||||
...(input.clientMetadata?.label ? { client_label: input.clientMetadata.label } : {}),
|
||||
...(input.clientMetadata?.deviceType
|
||||
? { client_device_type: input.clientMetadata.deviceType }
|
||||
: {}),
|
||||
...(input.clientMetadata?.os ? { client_os: input.clientMetadata.os } : {}),
|
||||
...clientMetadataTokenExchangeFields(input.clientMetadata),
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -219,6 +253,27 @@ export const fetchRemoteSessionState = Effect.fn("clientRuntime.remote.fetchRemo
|
||||
},
|
||||
);
|
||||
|
||||
export const fetchRemoteDpopSessionState = Effect.fn(
|
||||
"clientRuntime.remote.fetchRemoteDpopSessionState",
|
||||
)(function* (input: {
|
||||
readonly httpBaseUrl: string;
|
||||
readonly accessToken: string;
|
||||
readonly dpopProof: string;
|
||||
readonly timeoutMs?: number;
|
||||
}) {
|
||||
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
|
||||
return yield* executeRemoteRequest(
|
||||
remoteEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
|
||||
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
|
||||
client.auth.session({
|
||||
headers: {
|
||||
authorization: `DPoP ${input.accessToken}`,
|
||||
dpop: input.dpopProof,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const fetchRemoteEnvironmentDescriptor = Effect.fn(
|
||||
"clientRuntime.remote.fetchRemoteEnvironmentDescriptor",
|
||||
)(function* (input: { readonly httpBaseUrl: string; readonly timeoutMs?: number }) {
|
||||
@@ -249,6 +304,27 @@ export const issueRemoteWebSocketTicket = Effect.fn(
|
||||
);
|
||||
});
|
||||
|
||||
export const issueRemoteDpopWebSocketTicket = Effect.fn(
|
||||
"clientRuntime.remote.issueRemoteDpopWebSocketTicket",
|
||||
)(function* (input: {
|
||||
readonly httpBaseUrl: string;
|
||||
readonly accessToken: string;
|
||||
readonly dpopProof: string;
|
||||
readonly timeoutMs?: number;
|
||||
}) {
|
||||
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
|
||||
return yield* executeRemoteRequest(
|
||||
remoteEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
|
||||
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
|
||||
client.auth.webSocketTicket({
|
||||
headers: {
|
||||
authorization: `DPoP ${input.accessToken}`,
|
||||
dpop: input.dpopProof,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
|
||||
"clientRuntime.remote.resolveRemoteWebSocketConnectionUrl",
|
||||
)(function* (input: {
|
||||
@@ -270,3 +346,26 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
|
||||
url.searchParams.set("wsTicket", issued.ticket);
|
||||
return url.toString();
|
||||
});
|
||||
|
||||
export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
|
||||
"clientRuntime.remote.resolveRemoteDpopWebSocketConnectionUrl",
|
||||
)(function* (input: {
|
||||
readonly wsBaseUrl: string;
|
||||
readonly httpBaseUrl: string;
|
||||
readonly accessToken: string;
|
||||
readonly dpopProof: string;
|
||||
readonly timeoutMs?: number;
|
||||
}) {
|
||||
const issued = yield* issueRemoteDpopWebSocketTicket({
|
||||
httpBaseUrl: input.httpBaseUrl,
|
||||
accessToken: input.accessToken,
|
||||
dpopProof: input.dpopProof,
|
||||
...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
|
||||
});
|
||||
const url = new URL(input.wsBaseUrl);
|
||||
if (url.pathname === "" || url.pathname === "/") {
|
||||
url.pathname = "/ws";
|
||||
}
|
||||
url.searchParams.set("wsTicket", issued.ticket);
|
||||
return url.toString();
|
||||
});
|
||||
Reference in new issue
Block a user