Open History to see the last commit
1import type {
2 AuthBearerBootstrapResult,
3 AuthSessionState,
4 AuthWebSocketTokenResult,
5 ExecutionEnvironmentDescriptor,
6} from "@t3tools/contracts";
7
8class RemoteEnvironmentAuthHttpError extends Error {
9 readonly status: number;
10
11 constructor(message: string, status: number) {
12 super(message);
13 this.name = "RemoteEnvironmentAuthHttpError";
14 this.status = status;
15 }
16}
17
18function remoteEndpointUrl(httpBaseUrl: string, pathname: string): string {
19 const url = new URL(httpBaseUrl);
20 url.pathname = pathname;
21 url.search = "";
22 url.hash = "";
23 return url.toString();
24}
25
26async function readRemoteAuthErrorMessage(
27 response: Response,
28 fallbackMessage: string,
29): Promise<string> {
30 const text = await response.text();
31 if (!text) {
32 return fallbackMessage;
33 }
34
35 try {
36 const parsed = JSON.parse(text) as { readonly error?: string };
37 if (typeof parsed.error === "string" && parsed.error.length > 0) {
38 return parsed.error;
39 }
40 } catch {
41 // Fall back to raw text below.
42 }
43
44 return text;
45}
46
47async function fetchRemoteJson<T>(input: {
48 readonly httpBaseUrl: string;
49 readonly pathname: string;
50 readonly method?: "GET" | "POST";
51 readonly bearerToken?: string;
52 readonly body?: unknown;
53}): Promise<T> {
54 const requestUrl = remoteEndpointUrl(input.httpBaseUrl, input.pathname);
55 let response: Response;
56 try {
57 response = await fetch(requestUrl, {
58 method: input.method ?? "GET",
59 headers: {
60 ...(input.body !== undefined ? { "content-type": "application/json" } : {}),
61 ...(input.bearerToken ? { authorization: `Bearer ${input.bearerToken}` } : {}),
62 },
63 ...(input.body !== undefined ? { body: JSON.stringify(input.body) } : {}),
64 });
65 } catch (error) {
66 throw new Error(
67 `Failed to fetch remote auth endpoint ${requestUrl} (${(error as Error).message}).`,
68 { cause: error },
69 );
70 }
71
72 if (!response.ok) {
73 throw new RemoteEnvironmentAuthHttpError(
74 await readRemoteAuthErrorMessage(
75 response,
76 `Remote auth request failed (${response.status}).`,
77 ),
78 response.status,
79 );
80 }
81
82 return (await response.json()) as T;
83}
84
85export async function bootstrapRemoteBearerSession(input: {
86 readonly httpBaseUrl: string;
87 readonly credential: string;
88}): Promise<AuthBearerBootstrapResult> {
89 return fetchRemoteJson<AuthBearerBootstrapResult>({
90 httpBaseUrl: input.httpBaseUrl,
91 pathname: "/api/auth/bootstrap/bearer",
92 method: "POST",
93 body: {
94 credential: input.credential,
95 },
96 });
97}
98
99export async function fetchRemoteSessionState(input: {
100 readonly httpBaseUrl: string;
101 readonly bearerToken: string;
102}): Promise<AuthSessionState> {
103 return fetchRemoteJson<AuthSessionState>({
104 httpBaseUrl: input.httpBaseUrl,
105 pathname: "/api/auth/session",
106 bearerToken: input.bearerToken,
107 });
108}
109
110export async function fetchRemoteEnvironmentDescriptor(input: {
111 readonly httpBaseUrl: string;
112}): Promise<ExecutionEnvironmentDescriptor> {
113 return fetchRemoteJson<ExecutionEnvironmentDescriptor>({
114 httpBaseUrl: input.httpBaseUrl,
115 pathname: "/.well-known/t3/environment",
116 });
117}
118
119export async function issueRemoteWebSocketToken(input: {
120 readonly httpBaseUrl: string;
121 readonly bearerToken: string;
122}): Promise<AuthWebSocketTokenResult> {
123 return fetchRemoteJson<AuthWebSocketTokenResult>({
124 httpBaseUrl: input.httpBaseUrl,
125 pathname: "/api/auth/ws-token",
126 method: "POST",
127 bearerToken: input.bearerToken,
128 });
129}
130
131export async function resolveRemoteWebSocketConnectionUrl(input: {
132 readonly wsBaseUrl: string;
133 readonly httpBaseUrl: string;
134 readonly bearerToken: string;
135}): Promise<string> {
136 const issued = await issueRemoteWebSocketToken({
137 httpBaseUrl: input.httpBaseUrl,
138 bearerToken: input.bearerToken,
139 });
140 const url = new URL(input.wsBaseUrl, window.location.origin);
141 url.searchParams.set("wsToken", issued.token);
142 return url.toString();
143}