Open History to see the last commit
1import * as Schema from "effect/Schema";
2
3const PAIRING_TOKEN_PARAM = "token";
4const HOSTED_PAIRING_HOST_PARAM = "host";
5const HOSTED_PAIRING_LABEL_PARAM = "label";
6const SUPPORTED_REMOTE_BACKEND_PROTOCOLS = new Set(["http:", "https:", "ws:", "wss:"]);
7
8export const readHashParams = (url: URL): URLSearchParams =>
9 new URLSearchParams(url.hash.startsWith("#") ? url.hash.slice(1) : url.hash);
10
11export class RemoteBackendUrlMissingError extends Schema.TaggedError<RemoteBackendUrlMissingError>()(
12 "RemoteBackendUrlMissingError",
13 {},
14) {
15 override get message(): string {
16 return "Enter a backend URL.";
17 }
18}
19
20export class RemotePairingUrlInvalidError extends Schema.TaggedError<RemotePairingUrlInvalidError>()(
21 "RemotePairingUrlInvalidError",
22 {
23 cause: Schema.optional(Schema.Defect()),
24 protocol: Schema.optional(Schema.String),
25 },
26) {
27 override get message(): string {
28 return "Pairing URL is invalid.";
29 }
30}
31
32export class RemoteBackendUrlInvalidError extends Schema.TaggedError<RemoteBackendUrlInvalidError>()(
33 "RemoteBackendUrlInvalidError",
34 {
35 source: Schema.Literals(["direct-host", "hosted-pairing-host"]),
36 cause: Schema.optional(Schema.Defect()),
37 protocol: Schema.optional(Schema.String),
38 },
39) {
40 override get message(): string {
41 return "Backend URL is invalid.";
42 }
43}
44
45export class RemotePairingTokenMissingError extends Schema.TaggedError<RemotePairingTokenMissingError>()(
46 "RemotePairingTokenMissingError",
47 { host: Schema.String },
48) {
49 override get message(): string {
50 return "Pairing URL is missing its token.";
51 }
52}
53
54export class RemotePairingCodeMissingError extends Schema.TaggedError<RemotePairingCodeMissingError>()(
55 "RemotePairingCodeMissingError",
56 { host: Schema.String },
57) {
58 override get message(): string {
59 return "Enter a pairing code.";
60 }
61}
62
63export const RemotePairingTargetError = Schema.Union([
64 RemoteBackendUrlMissingError,
65 RemotePairingUrlInvalidError,
66 RemoteBackendUrlInvalidError,
67 RemotePairingTokenMissingError,
68 RemotePairingCodeMissingError,
69]);
70export type RemotePairingTargetError = typeof RemotePairingTargetError.Type;
71
72const hasSupportedRemoteBackendProtocol = (url: URL): boolean =>
73 SUPPORTED_REMOTE_BACKEND_PROTOCOLS.has(url.protocol);
74
75const normalizeRemoteBaseUrl = (
76 rawValue: string,
77 source: RemoteBackendUrlInvalidError["source"],
78): URL => {
79 const trimmed = rawValue.trim();
80 if (!trimmed) {
81 throw new RemoteBackendUrlMissingError();
82 }
83
84 const withoutLeadingSlashes = trimmed.replace(/^\/+/, "");
85 const normalizedInput = /^[a-zA-Z][a-zA-Z\d+-]*:\/\//.test(withoutLeadingSlashes)
86 ? withoutLeadingSlashes
87 : `https://${withoutLeadingSlashes}`;
88 let url: URL;
89 try {
90 url = new URL(normalizedInput);
91 } catch (cause) {
92 throw new RemoteBackendUrlInvalidError({ source, cause });
93 }
94 if (!hasSupportedRemoteBackendProtocol(url)) {
95 throw new RemoteBackendUrlInvalidError({
96 source,
97 protocol: url.protocol,
98 });
99 }
100 url.pathname = "/";
101 url.search = "";
102 url.hash = "";
103 return url;
104};
105
106const toHttpBaseUrl = (url: URL): string => {
107 const next = new URL(url.toString());
108 if (next.protocol === "ws:") {
109 next.protocol = "http:";
110 } else if (next.protocol === "wss:") {
111 next.protocol = "https:";
112 }
113 next.pathname = "/";
114 next.search = "";
115 next.hash = "";
116 return next.toString();
117};
118
119const toWsBaseUrl = (url: URL): string => {
120 const next = new URL(url.toString());
121 if (next.protocol === "http:") {
122 next.protocol = "ws:";
123 } else if (next.protocol === "https:") {
124 next.protocol = "wss:";
125 }
126 next.pathname = "/";
127 next.search = "";
128 next.hash = "";
129 return next.toString();
130};
131
132export interface ResolvedRemotePairingTarget {
133 readonly credential: string;
134 readonly httpBaseUrl: string;
135 readonly wsBaseUrl: string;
136}
137
138export interface HostedPairingRequest {
139 readonly host: string;
140 readonly token: string;
141 readonly label: string;
142}
143
144export const getPairingTokenFromUrl = (url: URL): string | null => {
145 const hashToken = readHashParams(url).get(PAIRING_TOKEN_PARAM)?.trim() ?? "";
146 if (hashToken.length > 0) {
147 return hashToken;
148 }
149
150 const searchToken = url.searchParams.get(PAIRING_TOKEN_PARAM)?.trim() ?? "";
151 return searchToken.length > 0 ? searchToken : null;
152};
153
154export const stripPairingTokenFromUrl = (url: URL): URL => {
155 const next = new URL(url.toString());
156 const hashParams = readHashParams(next);
157 if (hashParams.has(PAIRING_TOKEN_PARAM)) {
158 hashParams.delete(PAIRING_TOKEN_PARAM);
159 next.hash = hashParams.toString();
160 }
161 next.searchParams.delete(PAIRING_TOKEN_PARAM);
162 return next;
163};
164
165export const setPairingTokenOnUrl = (url: URL, credential: string): URL => {
166 const next = new URL(url.toString());
167 next.searchParams.delete(PAIRING_TOKEN_PARAM);
168 next.hash = new URLSearchParams([[PAIRING_TOKEN_PARAM, credential]]).toString();
169 return next;
170};
171
172export const readHostedPairingRequest = (url: URL): HostedPairingRequest | null => {
173 const host = url.searchParams.get(HOSTED_PAIRING_HOST_PARAM)?.trim() ?? "";
174 const token = getPairingTokenFromUrl(url)?.trim() ?? "";
175 const label = url.searchParams.get(HOSTED_PAIRING_LABEL_PARAM)?.trim() ?? "";
176
177 if (!host || !token) {
178 return null;
179 }
180
181 return {
182 host,
183 token,
184 label,
185 };
186};
187
188export const resolveRemotePairingTarget = (input: {
189 readonly pairingUrl?: string;
190 readonly host?: string;
191 readonly pairingCode?: string;
192}): ResolvedRemotePairingTarget => {
193 const pairingUrl = input.pairingUrl?.trim() ?? "";
194 if (pairingUrl.length > 0) {
195 let url: URL;
196 try {
197 url = new URL(pairingUrl);
198 } catch (cause) {
199 throw new RemotePairingUrlInvalidError({ cause });
200 }
201 if (!hasSupportedRemoteBackendProtocol(url)) {
202 throw new RemotePairingUrlInvalidError({
203 protocol: url.protocol,
204 });
205 }
206 const hostedPairingRequest = readHostedPairingRequest(url);
207 if (hostedPairingRequest) {
208 const hostedBackendUrl = normalizeRemoteBaseUrl(
209 hostedPairingRequest.host,
210 "hosted-pairing-host",
211 );
212 return {
213 credential: hostedPairingRequest.token,
214 httpBaseUrl: toHttpBaseUrl(hostedBackendUrl),
215 wsBaseUrl: toWsBaseUrl(hostedBackendUrl),
216 };
217 }
218
219 const credential = getPairingTokenFromUrl(url) ?? "";
220 if (!credential) {
221 throw new RemotePairingTokenMissingError({ host: url.host });
222 }
223 return {
224 credential,
225 httpBaseUrl: toHttpBaseUrl(url),
226 wsBaseUrl: toWsBaseUrl(url),
227 };
228 }
229
230 const host = input.host?.trim() ?? "";
231 const pairingCode = input.pairingCode?.trim() ?? "";
232 if (!host) {
233 throw new RemoteBackendUrlMissingError();
234 }
235 const normalizedHost = normalizeRemoteBaseUrl(host, "direct-host");
236 if (!pairingCode) {
237 throw new RemotePairingCodeMissingError({ host: normalizedHost.host });
238 }
239
240 return {
241 credential: pairingCode,
242 httpBaseUrl: toHttpBaseUrl(normalizedHost),
243 wsBaseUrl: toWsBaseUrl(normalizedHost),
244 };
245};