@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 361 lines 13 KB
Raw
1 import {
2 AuthAccessTokenType,
3 type AuthClientPresentationMetadata,
4 AuthEnvironmentBootstrapTokenType,
5 AuthTokenExchangeGrantType,
6 type ClientConnectionMethod,
7 type AuthEnvironmentScope,
8 type AuthWebSocketTicketResult,
9 type AuthWebSocketTicketUse,
10 } from "@t3tools/contracts";
11 import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
12 import { hashTelemetryId } from "@t3tools/shared/telemetryId";
13 import * as Effect from "effect/Effect";
14 import * as Option from "effect/Option";
15 import * as Redacted from "effect/Redacted";
16 import * as Schema from "effect/Schema";
17 import { environmentEndpointUrl } from "../environment/endpoint.ts";
18 import * as ClientCapabilities from "../platform/capabilities.ts";
19 import {
20 executeEnvironmentHttpRequest,
21 makeEnvironmentHttpApiGroupClient,
22 RemoteEnvironmentAuthUndeclaredStatusError,
23 type RemoteEnvironmentRequestError,
24 } from "../rpc/http.ts";
25
26 export { RemoteEnvironmentAuthUndeclaredStatusError } from "../rpc/http.ts";
27 export type RemoteEnvironmentAuthError = RemoteEnvironmentRequestError;
28
29 const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;
30 const isUndeclaredStatusError = Schema.is(RemoteEnvironmentAuthUndeclaredStatusError);
31
32 const clientMetadataTokenExchangeFields = (
33 clientMetadata: AuthClientPresentationMetadata | undefined,
34 ) => {
35 const displayOs = clientMetadata?.os;
36 return {
37 ...(clientMetadata?.label ? { client_label: clientMetadata.label } : {}),
38 ...(clientMetadata?.deviceType ? { client_device_type: clientMetadata.deviceType } : {}),
39 ...(displayOs && displayOs !== "unknown" && displayOs !== "other"
40 ? { client_os: displayOs }
41 : {}),
42 };
43 };
44
45 /** Hashes of who is connecting. Only hashes leave the client. */
46 export interface ClientOwnerParams {
47 readonly connect?: string;
48 readonly device?: string;
49 }
50
51 /**
52 * Tells the environment, for analytics, which T3 Connect account and device
53 * are connecting, so it can count the environment as theirs.
54 */
55 export const readClientOwnerParams = Effect.gen(function* () {
56 const session = yield* Effect.serviceOption(ClientCapabilities.CloudSession);
57 const account = Option.isSome(session) ? yield* session.value.identity : Option.none();
58 const device = yield* (yield* ClientCapabilities.AnalyticsDevice).id;
59 return {
60 ...(Option.isSome(account) ? { connect: hashTelemetryId(account.value.accountId) } : {}),
61 ...(Option.isSome(device) ? { device: hashTelemetryId(device.value) } : {}),
62 } satisfies ClientOwnerParams;
63 });
64
65 export const appendClientConnectionParams = (
66 url: URL,
67 clientMetadata: AuthClientPresentationMetadata | undefined,
68 connectionMethod?: ClientConnectionMethod,
69 owners?: ClientOwnerParams,
70 ): void => {
71 if (clientMetadata?.surface) {
72 url.searchParams.set("clientSurface", clientMetadata.surface);
73 }
74 if (clientMetadata?.appVersion) {
75 url.searchParams.set("clientAppVersion", clientMetadata.appVersion);
76 }
77 if (clientMetadata?.deviceType) {
78 const deviceType =
79 clientMetadata.deviceType === "mobile"
80 ? "phone"
81 : clientMetadata.deviceType === "desktop" || clientMetadata.deviceType === "tablet"
82 ? clientMetadata.deviceType
83 : "unknown";
84 url.searchParams.set("clientDeviceType", deviceType);
85 }
86 if (clientMetadata?.os) {
87 url.searchParams.set("clientOs", clientMetadata.os);
88 }
89 if (clientMetadata?.surface === "web") {
90 if (clientMetadata.webDeployment) {
91 url.searchParams.set("clientWebDeployment", clientMetadata.webDeployment);
92 }
93 if (clientMetadata.browser) {
94 url.searchParams.set("clientBrowser", clientMetadata.browser);
95 }
96 }
97 if (clientMetadata?.surface === "mobile") {
98 if (clientMetadata.osMajorVersion !== undefined) {
99 url.searchParams.set("clientOsMajorVersion", String(clientMetadata.osMajorVersion));
100 }
101 if (clientMetadata.deviceModel) {
102 url.searchParams.set("clientDeviceModel", clientMetadata.deviceModel);
103 }
104 }
105 if (connectionMethod) {
106 url.searchParams.set("connectionMethod", connectionMethod);
107 }
108 if (owners?.connect) {
109 url.searchParams.set("clientOwner", owners.connect);
110 }
111 if (owners?.device) {
112 url.searchParams.set("clientDevice", owners.device);
113 }
114 };
115
116 export const exchangeRemoteDpopAccessToken = Effect.fn(
117 "clientRuntime.authorization.exchangeRemoteDpopAccessToken",
118 )(function* (input: {
119 readonly httpBaseUrl: string;
120 readonly credential: string;
121 /** An access token renews its own session on hosts that advertise `accessTokenRenewal`. */
122 readonly credentialType?: typeof AuthEnvironmentBootstrapTokenType | typeof AuthAccessTokenType;
123 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
124 readonly clientMetadata?: AuthClientPresentationMetadata;
125 readonly dpopProof: string;
126 readonly timeoutMs?: number;
127 }) {
128 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
129 const response = yield* executeEnvironmentHttpRequest(
130 environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
131 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
132 client.token({
133 headers: { dpop: input.dpopProof },
134 payload: {
135 grant_type: AuthTokenExchangeGrantType,
136 subject_token: input.credential,
137 subject_token_type: input.credentialType ?? AuthEnvironmentBootstrapTokenType,
138 requested_token_type: AuthAccessTokenType,
139 ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
140 ...clientMetadataTokenExchangeFields(input.clientMetadata),
141 },
142 }),
143 );
144 return response;
145 });
146
147 export const bootstrapRemoteBearerSession = Effect.fn(
148 "clientRuntime.authorization.bootstrapRemoteBearerSession",
149 )(function* (input: {
150 readonly httpBaseUrl: string;
151 readonly credential: string;
152 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
153 readonly clientMetadata?: AuthClientPresentationMetadata;
154 readonly timeoutMs?: number;
155 }) {
156 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
157 return yield* executeEnvironmentHttpRequest(
158 environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
159 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
160 client.token({
161 headers: {},
162 payload: {
163 grant_type: AuthTokenExchangeGrantType,
164 subject_token: input.credential,
165 subject_token_type: AuthEnvironmentBootstrapTokenType,
166 requested_token_type: AuthAccessTokenType,
167 ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
168 ...clientMetadataTokenExchangeFields(input.clientMetadata),
169 },
170 }),
171 );
172 });
173
174 export const fetchRemoteSessionState = Effect.fn(
175 "clientRuntime.authorization.fetchRemoteSessionState",
176 )(function* (input: {
177 readonly httpBaseUrl: string;
178 readonly bearerToken: string;
179 readonly timeoutMs?: number;
180 }) {
181 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
182 return yield* executeEnvironmentHttpRequest(
183 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
184 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
185 client.session({
186 headers: {
187 authorization: `Bearer ${input.bearerToken}`,
188 },
189 }),
190 );
191 });
192
193 const webSocketTicketPath = (use: AuthWebSocketTicketUse | undefined) =>
194 use === undefined ? "/api/auth/websocket-ticket" : `/api/auth/websocket-ticket/${use}`;
195
196 /**
197 * A server that predates ticket audiences has no `/:use` route and answers 404.
198 * Its tickets are the unbound kind it always issued, so the bare path is the
199 * right request there, not an error.
200 */
201 const issueWebSocketTicketWithFallback = <E, R>(
202 use: AuthWebSocketTicketUse | undefined,
203 issue: (
204 use: AuthWebSocketTicketUse | undefined,
205 ) => Effect.Effect<AuthWebSocketTicketResult, E, R>,
206 canFallBack = true,
207 ) =>
208 use === undefined || !canFallBack
209 ? issue(use)
210 : issue(use).pipe(
211 Effect.catchIf(
212 (error) => isUndeclaredStatusError(error) && error.status === 404,
213 () => issue(undefined),
214 ),
215 );
216
217 export const issueRemoteWebSocketTicket = Effect.fn(
218 "clientRuntime.authorization.issueRemoteWebSocketTicket",
219 )(function* (input: {
220 readonly httpBaseUrl: string;
221 readonly bearerToken: string;
222 readonly use?: AuthWebSocketTicketUse;
223 readonly timeoutMs?: number;
224 }) {
225 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
226 const headers = { authorization: `Bearer ${input.bearerToken}` };
227 return yield* issueWebSocketTicketWithFallback(input.use, (use) =>
228 executeEnvironmentHttpRequest(
229 environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(use)),
230 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
231 use === undefined
232 ? client.webSocketTicket({ headers })
233 : client.webSocketTicketFor({ headers, params: { use } }),
234 ),
235 );
236 });
237
238 export const issueRemoteDpopWebSocketTicket = Effect.fn(
239 "clientRuntime.authorization.issueRemoteDpopWebSocketTicket",
240 )(function* <E = never>(input: {
241 readonly httpBaseUrl: string;
242 readonly accessToken: string;
243 readonly dpopProof: string;
244 readonly use?: AuthWebSocketTicketUse;
245 /** Proof for the bare path, used only when the server lacks the `/:use` route. */
246 readonly fallbackProof?: Effect.Effect<string, E>;
247 readonly timeoutMs?: number;
248 }) {
249 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
250 const fallbackProof = input.fallbackProof;
251 return yield* issueWebSocketTicketWithFallback(
252 input.use,
253 (use) =>
254 Effect.gen(function* () {
255 // The proof names the path it signs, so the fallback request needs its own.
256 const dpopProof =
257 use === input.use || fallbackProof === undefined ? input.dpopProof : yield* fallbackProof;
258 const headers = { authorization: `DPoP ${input.accessToken}`, dpop: dpopProof };
259 return yield* executeEnvironmentHttpRequest(
260 environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(use)),
261 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
262 use === undefined
263 ? client.webSocketTicket({ headers })
264 : client.webSocketTicketFor({ headers, params: { use } }),
265 );
266 }),
267 fallbackProof !== undefined,
268 );
269 });
270
271 function rpcSocketUrl(wsBaseUrl: string): URL {
272 const url = new URL(wsBaseUrl);
273 if (url.pathname === "" || url.pathname === "/") {
274 url.pathname = "/ws";
275 }
276 return url;
277 }
278
279 export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
280 "clientRuntime.authorization.resolveRemoteWebSocketConnectionUrl",
281 )(function* (input: {
282 readonly wsBaseUrl: string;
283 readonly httpBaseUrl: string;
284 readonly bearerToken: string;
285 readonly clientMetadata?: AuthClientPresentationMetadata;
286 readonly connectionMethod?: ClientConnectionMethod;
287 readonly timeoutMs?: number;
288 }) {
289 const issued = yield* issueRemoteWebSocketTicket({
290 httpBaseUrl: input.httpBaseUrl,
291 bearerToken: input.bearerToken,
292 use: "rpc",
293 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
294 });
295
296 const url = rpcSocketUrl(input.wsBaseUrl);
297 url.searchParams.set("wsTicket", Redacted.value(issued.ticket));
298 appendClientConnectionParams(
299 url,
300 input.clientMetadata,
301 input.connectionMethod,
302 yield* readClientOwnerParams,
303 );
304 return url.toString();
305 });
306
307 /**
308 * A DPoP client's RPC ticket is bound to its key, so the upgrade carries a
309 * proof too. A WebSocket cannot set headers, so it rides in the `dpop` query
310 * parameter and names the socket URL as the HTTP request the server sees.
311 */
312 export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
313 "clientRuntime.authorization.resolveRemoteDpopWebSocketConnectionUrl",
314 )(function* <E>(input: {
315 readonly wsBaseUrl: string;
316 readonly httpBaseUrl: string;
317 readonly accessToken: string;
318 readonly createProof: (input: {
319 readonly method: "GET" | "POST";
320 readonly url: string;
321 readonly accessToken: string;
322 }) => Effect.Effect<string, E>;
323 readonly clientMetadata?: AuthClientPresentationMetadata;
324 readonly connectionMethod?: ClientConnectionMethod;
325 readonly timeoutMs?: number;
326 }) {
327 const ticketProof = yield* input.createProof({
328 method: "POST",
329 url: environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath("rpc")),
330 accessToken: input.accessToken,
331 });
332 const issued = yield* issueRemoteDpopWebSocketTicket({
333 httpBaseUrl: input.httpBaseUrl,
334 accessToken: input.accessToken,
335 dpopProof: ticketProof,
336 use: "rpc",
337 fallbackProof: Effect.suspend(() =>
338 input.createProof({
339 method: "POST",
340 url: environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(undefined)),
341 accessToken: input.accessToken,
342 }),
343 ),
344 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
345 });
346 const url = rpcSocketUrl(input.wsBaseUrl);
347 const upgradeProof = yield* input.createProof({
348 method: "GET",
349 url: `${url.protocol === "wss:" ? "https:" : "http:"}//${url.host}${url.pathname}`,
350 accessToken: Redacted.value(issued.ticket),
351 });
352 url.searchParams.set("wsTicket", Redacted.value(issued.ticket));
353 url.searchParams.set("dpop", upgradeProof);
354 appendClientConnectionParams(
355 url,
356 input.clientMetadata,
357 input.connectionMethod,
358 yield* readClientOwnerParams,
359 );
360 return url.toString();
361 });