Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pairing.ts

93 lines2.5 KB

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 }
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 }
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 url.hash = new URLSearchParams([["token", c]]).toString();
42 return url.toString();
43 } catch {
44 return `${h}#token=${c}`;
45 }
47​
48export 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 }
75​
76export 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;