Open History to see the last commit
1import { readHostedPairingRequest } from "@t3tools/shared/remote";
2import * as Schema from "effect/Schema";
3import { msg } from "gt-react-native";
4
5import { m } from "../../i18n/messages";
6
7const MOBILE_PAIRING_URL_PARAM = "pairingUrl";
8
9function 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
24export 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
33export 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 // The code goes to the address shown, so a query cannot name another destination.
42 url.search = "";
43 url.hash = new URLSearchParams([["token", c]]).toString();
44 return url.toString();
45 } catch {
46 return `${h}#token=${c}`;
47 }
48}
49
50export function parsePairingUrl(url: string): { host: string; code: string } {
51 const trimmed = url.trim();
52 if (!trimmed) return { host: "", code: "" };
53
54 try {
55 const parsed = new URL(trimmed);
56 const hostedPairingRequest = readHostedPairingRequest(parsed);
57 if (hostedPairingRequest) {
58 return {
59 host: hostedPairingRequest.host.replace(/\/$/, ""),
60 code: hostedPairingRequest.token,
61 };
62 }
63
64 const hashParams = new URLSearchParams(parsed.hash.slice(1));
65 const hashToken = hashParams.get("token");
66 const queryToken = parsed.searchParams.get("token");
67 const code = hashToken || queryToken || "";
68
69 parsed.hash = "";
70 parsed.search = "";
71 parsed.pathname = "/";
72 return { host: parsed.toString().replace(/\/$/, ""), code };
73 } catch {
74 return { host: trimmed, code: "" };
75 }
76}
77
78export function extractPairingUrlFromQrPayload(payload: string): string {
79 const trimmed = payload.trim();
80 if (!trimmed) {
81 throw new PairingQrPayloadEmptyError({});
82 }
83
84 try {
85 const url = new URL(trimmed);
86 if (url.protocol === "t3code:") {
87 const pairingUrl = url.searchParams.get(MOBILE_PAIRING_URL_PARAM)?.trim() ?? "";
88 if (pairingUrl.length > 0) {
89 return pairingUrl;
90 }
91 }
92 } catch {}
93
94 return trimmed;
95}