Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

connection.ts

96 lines2.8 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import {
3 bootstrapRemoteBearerSession,
4 fetchRemoteEnvironmentDescriptor,
5} from "@t3tools/client-runtime";
6import { resolveRemotePairingTarget, stripPairingTokenFromUrl } from "@t3tools/shared/remote";
7import * as Effect from "effect/Effect";
8import { mobileAuthClientMetadata } from "./authClientMetadata";
9import { mobileRuntime } from "./runtime";
10​
11export { mobileAuthClientMetadata } from "./authClientMetadata";
12​
13export interface RemoteConnectionInput {
14 readonly pairingUrl: string;
16​
17export interface SavedRemoteConnection {
18 readonly environmentId: EnvironmentId;
19 readonly environmentLabel: string;
20 readonly pairingUrl: string;
21 readonly displayUrl: string;
22 readonly httpBaseUrl: string;
23 readonly wsBaseUrl: string;
24 readonly bearerToken: string | null;
25 readonly authenticationMethod?: "bearer" | "dpop";
26 readonly dpopAccessToken?: string;
27 readonly relayManaged?: true;
29​
30export type RemoteClientConnectionState =
31 | "idle"
32 | "connecting"
33 | "ready"
34 | "reconnecting"
35 | "disconnected";
36​
37export function redactPairingCredential(pairingUrl: string): string {
38 const trimmed = pairingUrl.trim();
39 try {
40 return stripPairingTokenFromUrl(new URL(trimmed)).toString();
41 } catch {
42 return trimmed;
43 }
45​
46export function isRelayManagedConnection(
47 connection: Pick<SavedRemoteConnection, "authenticationMethod" | "relayManaged">,
48): boolean {
49 return connection.relayManaged === true || connection.authenticationMethod === "dpop";
51​
52export function toStableSavedRemoteConnection(
53 connection: SavedRemoteConnection,
54): SavedRemoteConnection {
55 if (!isRelayManagedConnection(connection) || !connection.dpopAccessToken) {
56 return connection;
57 }
58​
59 const { dpopAccessToken: _, ...stableConnection } = connection;
60 return stableConnection;
62​
63export async function bootstrapRemoteConnection(
64 input: RemoteConnectionInput,
65): Promise<SavedRemoteConnection> {
66 const target = resolveRemotePairingTarget({
67 pairingUrl: input.pairingUrl,
68 });
69​
70 const { descriptor, bootstrap } = await mobileRuntime.runPromise(
71 Effect.all(
72 {
73 descriptor: fetchRemoteEnvironmentDescriptor({
74 httpBaseUrl: target.httpBaseUrl,
75 }),
76 bootstrap: bootstrapRemoteBearerSession({
77 httpBaseUrl: target.httpBaseUrl,
78 credential: target.credential,
79 clientMetadata: mobileAuthClientMetadata(),
80 }),
81 },
82 { concurrency: "unbounded" },
83 ),
84 );
85​
86 return {
87 environmentId: descriptor.environmentId,
88 environmentLabel: descriptor.label,
89 pairingUrl: redactPairingCredential(input.pairingUrl),
90 displayUrl: target.httpBaseUrl,
91 httpBaseUrl: target.httpBaseUrl,
92 wsBaseUrl: target.wsBaseUrl,
93 bearerToken: bootstrap.access_token,
94 authenticationMethod: "bearer",
95 };