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

main
ts 240 lines 6.66 KB
Raw
1 import type {
2 AuthClientMetadata,
3 AuthClientSession,
4 AuthConnectDevice,
5 AuthConnectDeviceRequest,
6 AuthPairingLink,
7 } from "@t3tools/contracts";
8 import * as DateTime from "effect/DateTime";
9
10 import type { IssuedBearerSession, IssuedPairingLink } from "./auth/EnvironmentAuth.ts";
11
12 const newline = "\n";
13
14 function serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {
15 return values.filter((value): value is string => typeof value === "string" && value.length > 0);
16 }
17
18 function formatClientMetadata(metadata: AuthClientMetadata): string {
19 const details = serializeOptionalFields([
20 metadata.label,
21 metadata.deviceType !== "unknown" ? metadata.deviceType : undefined,
22 metadata.os,
23 metadata.browser,
24 metadata.ipAddress,
25 ]);
26 return details.length > 0 ? details.join(" | ") : "unlabeled client";
27 }
28
29 function toIsoString(value: DateTime.DateTime | DateTime.Utc): string {
30 return DateTime.formatIso(DateTime.toUtc(value));
31 }
32
33 export function formatIssuedPairingCredential(
34 credential: IssuedPairingLink,
35 options?: {
36 readonly json?: boolean;
37 readonly baseUrl?: string;
38 },
39 ): string {
40 const pairUrl =
41 options?.baseUrl != null && options.baseUrl.length > 0
42 ? (() => {
43 const url = new URL("/pair", options.baseUrl);
44 url.searchParams.delete("token");
45 url.hash = new URLSearchParams([["token", credential.credential]]).toString();
46 return url.toString();
47 })()
48 : undefined;
49
50 if (options?.json) {
51 return `${JSON.stringify(
52 {
53 id: credential.id,
54 credential: credential.credential,
55 ...(credential.label ? { label: credential.label } : {}),
56 scopes: credential.scopes,
57 expiresAt: toIsoString(credential.expiresAt),
58 ...(pairUrl ? { pairUrl } : {}),
59 },
60 null,
61 2,
62 )}${newline}`;
63 }
64
65 return (
66 [
67 `Issued client pairing token ${credential.id}.`,
68 `Token: ${credential.credential}`,
69 ...(pairUrl ? [`Pair URL: ${pairUrl}`] : []),
70 `Expires at: ${toIsoString(credential.expiresAt)}`,
71 ].join(newline) + newline
72 );
73 }
74
75 export function formatPairingCredentialList(
76 credentials: ReadonlyArray<AuthPairingLink>,
77 options?: {
78 readonly json?: boolean;
79 },
80 ): string {
81 if (options?.json) {
82 return `${JSON.stringify(
83 credentials.map((credential) => ({
84 id: credential.id,
85 ...(credential.label ? { label: credential.label } : {}),
86 scopes: credential.permissions ?? credential.scopes,
87 createdAt: toIsoString(credential.createdAt),
88 expiresAt: toIsoString(credential.expiresAt),
89 })),
90 null,
91 2,
92 )}${newline}`;
93 }
94
95 if (credentials.length === 0) {
96 return `No active pairing credentials.${newline}`;
97 }
98
99 return (
100 credentials
101 .map((credential) =>
102 [
103 `${credential.id}${credential.label ? ` (${credential.label})` : ""}`,
104 ` scopes: ${(credential.permissions ?? credential.scopes).join(" ")}`,
105 ` created: ${toIsoString(credential.createdAt)}`,
106 ` expires: ${toIsoString(credential.expiresAt)}`,
107 ].join(newline),
108 )
109 .join(`${newline}${newline}`) + newline
110 );
111 }
112
113 export function formatIssuedSession(
114 session: IssuedBearerSession,
115 options?: {
116 readonly json?: boolean;
117 readonly tokenOnly?: boolean;
118 },
119 ): string {
120 if (options?.tokenOnly) {
121 return `${session.token}${newline}`;
122 }
123
124 if (options?.json) {
125 return `${JSON.stringify(
126 {
127 sessionId: session.sessionId,
128 token: session.token,
129 method: session.method,
130 scopes: session.scopes,
131 subject: session.subject,
132 client: session.client,
133 expiresAt: toIsoString(session.expiresAt),
134 },
135 null,
136 2,
137 )}${newline}`;
138 }
139
140 return (
141 [
142 `Issued bearer access token ${session.sessionId}.`,
143 `Scopes: ${session.scopes.join(" ")}`,
144 `Token: ${session.token}`,
145 `Subject: ${session.subject}`,
146 `Client: ${formatClientMetadata(session.client)}`,
147 `Expires at: ${toIsoString(session.expiresAt)}`,
148 ].join(newline) + newline
149 );
150 }
151
152 export function formatSessionList(
153 sessions: ReadonlyArray<AuthClientSession>,
154 options?: {
155 readonly json?: boolean;
156 },
157 ): string {
158 if (options?.json) {
159 return `${JSON.stringify(
160 sessions.map((session) => ({
161 sessionId: session.sessionId,
162 method: session.method,
163 scopes: session.scopes,
164 subject: session.subject,
165 client: session.client,
166 connected: session.connected,
167 issuedAt: toIsoString(session.issuedAt),
168 expiresAt: toIsoString(session.expiresAt),
169 lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null,
170 })),
171 null,
172 2,
173 )}${newline}`;
174 }
175
176 if (sessions.length === 0) {
177 return `No active sessions.${newline}`;
178 }
179
180 return (
181 sessions
182 .map((session) =>
183 [
184 `${session.sessionId}${session.connected ? " connected" : ""}`,
185 ` scopes: ${session.scopes.join(" ")}`,
186 ` method: ${session.method}`,
187 ` subject: ${session.subject}`,
188 ` client: ${formatClientMetadata(session.client)}`,
189 ` issued: ${toIsoString(session.issuedAt)}`,
190 ` last connected: ${
191 session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : "never"
192 }`,
193 ` expires: ${toIsoString(session.expiresAt)}`,
194 ].join(newline),
195 )
196 .join(`${newline}${newline}`) + newline
197 );
198 }
199
200 export function formatConnectDeviceList(
201 devices: {
202 readonly waiting: ReadonlyArray<AuthConnectDeviceRequest>;
203 readonly trusted: ReadonlyArray<AuthConnectDevice>;
204 },
205 options?: {
206 readonly json?: boolean;
207 },
208 ): string {
209 if (options?.json) {
210 return `${JSON.stringify(
211 {
212 waiting: devices.waiting,
213 trusted: devices.trusted.map((device) => ({
214 ...device,
215 approvedAt: toIsoString(device.approvedAt),
216 })),
217 },
218 null,
219 2,
220 )}${newline}`;
221 }
222 const describe = (client: AuthClientMetadata | undefined) =>
223 client ? formatClientMetadata(client) : "unlabeled client";
224 return (
225 [
226 devices.waiting.length === 0
227 ? "No devices are waiting for approval."
228 : "Waiting for approval:",
229 ...devices.waiting.map(
230 (request) => ` ${request.verificationCode} ${describe(request.client)}`,
231 ),
232 "",
233 devices.trusted.length === 0 ? "No trusted T3 Connect devices." : "Trusted:",
234 ...devices.trusted.map(
235 (device) =>
236 ` ${device.verificationCode} ${describe(device.client)} since ${toIsoString(device.approvedAt)}`,
237 ),
238 ].join(newline) + newline
239 );
240 }