@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 416 lines 12.7 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import type {
3 AuthBrowserSessionResult,
4 AuthClientMetadata,
5 AuthConnectDeviceRequest,
6 AuthEnvironmentScope,
7 ServerAuthSessionMethod,
8 AuthSessionId,
9 AuthSessionState,
10 } from "@t3tools/contracts";
11 import { EnvironmentHttpCommonError, PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
12 import type { EnvironmentHttpCommonError as EnvironmentHttpCommonErrorType } from "@t3tools/contracts";
13 import * as Effect from "effect/Effect";
14 import * as Schema from "effect/Schema";
15 import { HttpClientError } from "effect/http";
16
17 import {
18 getPairingTokenFromUrl,
19 stripPairingTokenFromUrl as stripPairingTokenUrl,
20 } from "@t3tools/shared/remote";
21
22 import { PrimaryEnvironmentHttpClient } from "./httpClient";
23 import { runPrimaryHttp } from "../../lib/runtime";
24 import { msg } from "gt-react";
25 import { m } from "../../i18n/messages";
26
27 const PrimaryEnvironmentRequestOperation = Schema.Literals([
28 "fetch-session-state",
29 "exchange-bootstrap-credential",
30 "fetch-environment-descriptor",
31 "create-pairing-credential",
32 "list-pairing-links",
33 "revoke-pairing-link",
34 "list-client-sessions",
35 "revoke-client-session",
36 "revoke-other-client-sessions",
37 ]);
38 type PrimaryEnvironmentRequestOperation = typeof PrimaryEnvironmentRequestOperation.Type;
39
40 export class PrimaryEnvironmentRequestError extends Schema.TaggedError<PrimaryEnvironmentRequestError>()(
41 "PrimaryEnvironmentRequestError",
42 {
43 operation: PrimaryEnvironmentRequestOperation,
44 status: Schema.Number,
45 pairingLinkId: Schema.optional(Schema.String),
46 sessionId: Schema.optional(Schema.String),
47 cause: Schema.Defect(),
48 },
49 ) {
50 static fromCause(input: {
51 readonly operation: PrimaryEnvironmentRequestOperation;
52 readonly cause: unknown;
53 readonly pairingLinkId?: string;
54 readonly sessionId?: string;
55 }): PrimaryEnvironmentRequestError {
56 const status = readHttpApiStatus(input.cause) ?? 500;
57 return new PrimaryEnvironmentRequestError({
58 operation: input.operation,
59 status,
60 ...(input.pairingLinkId !== undefined ? { pairingLinkId: input.pairingLinkId } : {}),
61 ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
62 cause: input.cause,
63 });
64 }
65
66 override get message(): string {
67 return m(
68 msg("Primary environment request failed during {operation} (HTTP {status}).", {
69 operation: this.operation,
70 status: this.status,
71 }),
72 );
73 }
74 }
75
76 const isPrimaryEnvironmentRequestError = Schema.is(PrimaryEnvironmentRequestError);
77
78 export class PrimaryEnvironmentPairingCredentialRejectedError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRejectedError>()(
79 "PrimaryEnvironmentPairingCredentialRejectedError",
80 {
81 providedLength: Schema.Number,
82 cause: Schema.Defect(),
83 },
84 ) {
85 override get message(): string {
86 return m(msg("Invalid pairing token. Check the token and try again."));
87 }
88 }
89
90 export class PrimaryEnvironmentAuthSessionTimeoutError extends Schema.TaggedError<PrimaryEnvironmentAuthSessionTimeoutError>()(
91 "PrimaryEnvironmentAuthSessionTimeoutError",
92 {
93 timeoutMs: Schema.Number,
94 elapsedMs: Schema.Number,
95 },
96 ) {
97 override get message(): string {
98 return m(msg("Timed out waiting for authenticated session after bootstrap."));
99 }
100 }
101
102 export class PrimaryEnvironmentPairingCredentialRequiredError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRequiredError>()(
103 "PrimaryEnvironmentPairingCredentialRequiredError",
104 {
105 providedLength: Schema.Number,
106 },
107 ) {
108 override get message(): string {
109 return m(msg("Enter a pairing token to continue."));
110 }
111 }
112
113 const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
114
115 export interface ServerPairingLinkRecord {
116 readonly id: string;
117 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
118 readonly subject: string;
119 readonly label?: string;
120 readonly createdAt: string;
121 readonly expiresAt: string;
122 readonly connectDeviceRequest?: AuthConnectDeviceRequest;
123 }
124
125 export interface ServerClientSessionRecord {
126 readonly sessionId: AuthSessionId;
127 readonly subject: string;
128 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
129 readonly method: ServerAuthSessionMethod;
130 readonly client: AuthClientMetadata;
131 readonly issuedAt: string;
132 readonly expiresAt: string;
133 readonly lastConnectedAt: string | null;
134 readonly connected: boolean;
135 readonly current: boolean;
136 }
137
138 type ServerAuthGateState =
139 | { status: "authenticated" }
140 | {
141 status: "requires-auth";
142 auth: AuthSessionState["auth"];
143 errorMessage?: string;
144 };
145
146 let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
147 let resolvedAuthenticatedGateState: ServerAuthGateState | null = null;
148 let explicitPairingRequested = false;
149 const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
150 const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
151
152 export function peekPairingTokenFromUrl(): string | null {
153 return getPairingTokenFromUrl(new URL(window.location.href));
154 }
155
156 export function stripPairingTokenFromUrl() {
157 const url = new URL(window.location.href);
158 const next = stripPairingTokenUrl(url);
159 if (next.toString() === url.toString()) {
160 return;
161 }
162 window.history.replaceState(window.history.state, document.title, next.toString());
163 }
164
165 export function takePairingTokenFromUrl(): string | null {
166 const token = peekPairingTokenFromUrl();
167 if (!token) {
168 return null;
169 }
170 stripPairingTokenFromUrl();
171 return token;
172 }
173
174 function getDesktopBootstrapCredential(): string | null {
175 // DesktopBackendConfiguration gives primary and WSL the same bootstrap token.
176 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
177 const primary = bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
178 return typeof primary?.bootstrapToken === "string" && primary.bootstrapToken.length > 0
179 ? primary.bootstrapToken
180 : null;
181 }
182
183 export async function fetchSessionState(): Promise<AuthSessionState> {
184 return retryTransientBootstrap(async () => {
185 try {
186 return await runPrimaryHttp(
187 PrimaryEnvironmentHttpClient.pipe(
188 Effect.flatMap((client) => client.auth.session({ headers: {} })),
189 ),
190 );
191 } catch (error) {
192 throw PrimaryEnvironmentRequestError.fromCause({
193 operation: "fetch-session-state",
194 cause: error,
195 });
196 }
197 });
198 }
199
200 function readHttpApiStatus(error: unknown): number | null {
201 if (isEnvironmentHttpCommonError(error)) {
202 return readEnvironmentHttpErrorStatus(error);
203 }
204 return HttpClientError.isHttpClientError(error) && error.response !== undefined
205 ? error.response.status
206 : null;
207 }
208
209 function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
210 switch (error._tag) {
211 case "EnvironmentRequestInvalidError":
212 return 400;
213 case "EnvironmentAuthInvalidError":
214 return 401;
215 case "EnvironmentScopeRequiredError":
216 case "EnvironmentOperationForbiddenError":
217 case "EnvironmentConnectApprovalPendingError":
218 return 403;
219 case "EnvironmentResourceNotFoundError":
220 return 404;
221 case "EnvironmentInternalError":
222 return 500;
223 }
224 }
225
226 async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
227 return retryTransientBootstrap(async () => {
228 try {
229 return await runPrimaryHttp(
230 PrimaryEnvironmentHttpClient.pipe(
231 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
232 ),
233 );
234 } catch (error) {
235 if (
236 isEnvironmentHttpCommonError(error) &&
237 error._tag === "EnvironmentAuthInvalidError" &&
238 error.reason === "invalid_credential"
239 ) {
240 throw new PrimaryEnvironmentPairingCredentialRejectedError({
241 providedLength: credential.length,
242 cause: error,
243 });
244 }
245 throw PrimaryEnvironmentRequestError.fromCause({
246 operation: "exchange-bootstrap-credential",
247 cause: error,
248 });
249 }
250 });
251 }
252
253 async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
254 const startedAt = Date.now();
255
256 while (true) {
257 const session = await fetchSessionState();
258 if (session.authenticated) {
259 return session;
260 }
261
262 const elapsedMs = Date.now() - startedAt;
263 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
264 throw new PrimaryEnvironmentAuthSessionTimeoutError({
265 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
266 elapsedMs,
267 });
268 }
269
270 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
271 }
272 }
273
274 const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
275 const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
276 const BOOTSTRAP_RETRY_STEP_MS = 500;
277
278 async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
279 const startedAt = Date.now();
280 while (true) {
281 try {
282 return await operation();
283 } catch (error) {
284 if (!isTransientBootstrapError(error)) {
285 throw error;
286 }
287
288 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
289 throw error;
290 }
291
292 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
293 }
294 }
295 }
296
297 function waitForBootstrapRetry(delayMs: number): Promise<void> {
298 return new Promise((resolve) => {
299 setTimeout(resolve, delayMs);
300 });
301 }
302
303 function isTransientBootstrapError(error: unknown): boolean {
304 if (isPrimaryEnvironmentRequestError(error)) {
305 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status) || isTransportError(error.cause);
306 }
307
308 if (error instanceof TypeError) {
309 return true;
310 }
311
312 return error instanceof DOMException && error.name === "AbortError";
313 }
314
315 function isTransportError(error: unknown): boolean {
316 return HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError";
317 }
318
319 async function bootstrapServerAuth(urlCredential: string | null): Promise<ServerAuthGateState> {
320 const currentSession = await fetchSessionState();
321 if (currentSession.authenticated && !urlCredential) {
322 return { status: "authenticated" };
323 }
324
325 const bootstrapCredential = urlCredential ?? getDesktopBootstrapCredential();
326 if (!bootstrapCredential) {
327 return {
328 status: "requires-auth",
329 auth: currentSession.auth,
330 };
331 }
332
333 try {
334 await exchangeBootstrapCredential(bootstrapCredential);
335 await waitForAuthenticatedSessionAfterBootstrap();
336 return { status: "authenticated" };
337 } catch (error) {
338 return {
339 status: "requires-auth",
340 auth: currentSession.auth,
341 errorMessage: thrownErrorMessage(error, m) ?? m(msg("Authentication failed.")),
342 };
343 }
344 }
345
346 export async function submitServerAuthCredential(credential: string): Promise<void> {
347 const trimmedCredential = credential.trim();
348 if (!trimmedCredential) {
349 throw new PrimaryEnvironmentPairingCredentialRequiredError({
350 providedLength: credential.length,
351 });
352 }
353
354 resolvedAuthenticatedGateState = null;
355 await exchangeBootstrapCredential(trimmedCredential);
356 await waitForAuthenticatedSessionAfterBootstrap();
357 resolvedAuthenticatedGateState = { status: "authenticated" };
358 bootstrapPromise = null;
359 explicitPairingRequested = false;
360 stripPairingTokenFromUrl();
361 }
362
363 export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
364 // Preserve explicit grant replacement across the auth-gate reload triggered by token removal.
365 if (window.location.pathname.replace(/\/+$/, "") !== "/pair") {
366 explicitPairingRequested = false;
367 } else if (peekPairingTokenFromUrl()) {
368 explicitPairingRequested = true;
369 }
370 if (explicitPairingRequested) {
371 const currentSession = await fetchSessionState();
372 return { status: "requires-auth", auth: currentSession.auth };
373 }
374
375 const urlCredential = takePairingTokenFromUrl();
376 const previousPromise = bootstrapPromise;
377 if (urlCredential) {
378 resolvedAuthenticatedGateState = null;
379 } else {
380 if (previousPromise) {
381 return previousPromise;
382 }
383
384 if (resolvedAuthenticatedGateState?.status === "authenticated") {
385 return resolvedAuthenticatedGateState;
386 }
387 }
388
389 const nextPromise = previousPromise
390 ? previousPromise
391 .catch(() => undefined)
392 .then(() => {
393 resolvedAuthenticatedGateState = null;
394 return bootstrapServerAuth(urlCredential);
395 })
396 : bootstrapServerAuth(urlCredential);
397 bootstrapPromise = nextPromise;
398 return nextPromise
399 .then((result) => {
400 if (bootstrapPromise === nextPromise && result.status === "authenticated") {
401 resolvedAuthenticatedGateState = result;
402 }
403 return result;
404 })
405 .finally(() => {
406 if (bootstrapPromise === nextPromise) {
407 bootstrapPromise = null;
408 }
409 });
410 }
411
412 export function __resetServerAuthBootstrapForTests() {
413 bootstrapPromise = null;
414 resolvedAuthenticatedGateState = null;
415 explicitPairingRequested = false;
416 }