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

main
ts 93 lines 2.52 KB
Raw
1 import { readHostedPairingRequest } from "@t3tools/shared/remote";
2 import * as Schema from "effect/Schema";
3 import { msg } from "gt-react-native";
4
5 import { m } from "../../i18n/messages";
6
7 const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
8
9 function isIpLiteral(host: string): boolean {
10 try {
11 const hostname = new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, "");
12 if (hostname.includes(":")) return true;
13
14 const octets = hostname.split(".");
15 return (
16 octets.length === 4 &&
17 octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255)
18 );
19 } catch {
20 return false;
21 }
22 }
23
24 export class PairingQrPayloadEmptyError extends Schema.TaggedError<PairingQrPayloadEmptyError>()(
25 "PairingQrPayloadEmptyError",
26 {},
27 ) {
28 override get message(): string {
29 return m(msg("Scanned QR code did not contain a pairing URL."));
30 }
31 }
32
33 export function buildPairingUrl(host: string, code: string): string {
34 const h = host.trim();
35 const c = code.trim();
36 if (!h) return "";
37 if (!c) return h;
38
39 try {
40 const url = new URL(h.includes("://") ? h : `${isIpLiteral(h) ? "http" : "https"}://${h}`);
41 url.hash = new URLSearchParams([["token", c]]).toString();
42 return url.toString();
43 } catch {
44 return `${h}#token=${c}`;
45 }
46 }
47
48 export function parsePairingUrl(url: string): { host: string; code: string } {
49 const trimmed = url.trim();
50 if (!trimmed) return { host: "", code: "" };
51
52 try {
53 const parsed = new URL(trimmed);
54 const hostedPairingRequest = readHostedPairingRequest(parsed);
55 if (hostedPairingRequest) {
56 return {
57 host: hostedPairingRequest.host.replace(/\/$/, ""),
58 code: hostedPairingRequest.token,
59 };
60 }
61
62 const hashParams = new URLSearchParams(parsed.hash.slice(1));
63 const hashToken = hashParams.get("token");
64 const queryToken = parsed.searchParams.get("token");
65 const code = hashToken || queryToken || "";
66
67 parsed.hash = "";
68 parsed.search = "";
69 parsed.pathname = "/";
70 return { host: parsed.toString().replace(/\/$/, ""), code };
71 } catch {
72 return { host: trimmed, code: "" };
73 }
74 }
75
76 export function extractPairingUrlFromQrPayload(payload: string): string {
77 const trimmed = payload.trim();
78 if (!trimmed) {
79 throw new PairingQrPayloadEmptyError({});
80 }
81
82 try {
83 const url = new URL(trimmed);
84 if (url.protocol === "t3code:") {
85 const pairingUrl = url.searchParams.get(MOBILE_PAIRING_URL_PARAM)?.trim() ?? "";
86 if (pairingUrl.length > 0) {
87 return pairingUrl;
88 }
89 }
90 } catch {}
91
92 return trimmed;
93 }