|
| 1 | +import * as DateTime from "effect/DateTime"; |
| 2 | + |
| 3 | +import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls"; |
| 4 | +import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl"; |
| 5 | +import { readHostedPairingRequest } from "../../hostedPairing"; |
| 6 | +import { |
| 7 | + type ServerClientSessionRecord, |
| 8 | + type ServerPairingLinkRecord, |
| 9 | +} from "~/environments/primary"; |
1 | 10 | import { |
2 | 11 | type AdvertisedEndpoint, |
| 12 | + type AuthClientSession, |
3 | 13 | type AuthGrantScope, |
| 14 | + type AuthPairingLink, |
4 | 15 | AuthTerminalOperateScope, |
5 | 16 | AuthTerminalReadScope, |
6 | 17 | type DesktopBridge, |
7 | 18 | type DesktopServerExposureState, |
| 19 | + type DesktopSshEnvironmentTarget, |
8 | 20 | type DesktopUpdateState, |
9 | 21 | type DesktopWslState, |
10 | 22 | } from "@t3tools/contracts"; |
@@ -150,3 +162,282 @@ export async function applyWslEnableSelection(input: { |
150 | 162 | } |
151 | 163 | return await bridge.setWslBackendEnabled(true); |
152 | 164 | } |
| 165 | + |
| 166 | +const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, { |
| 167 | + dateStyle: "medium", |
| 168 | + timeStyle: "short", |
| 169 | +}); |
| 170 | + |
| 171 | +export function formatAccessTimestamp(value: string): string { |
| 172 | + const parsed = new Date(value); |
| 173 | + if (Number.isNaN(parsed.getTime())) { |
| 174 | + return value; |
| 175 | + } |
| 176 | + return accessTimestampFormatter.format(parsed); |
| 177 | +} |
| 178 | + |
| 179 | +export function parseManualDesktopSshTarget(input: { |
| 180 | + readonly host: string; |
| 181 | + readonly username: string; |
| 182 | + readonly port: string; |
| 183 | +}): DesktopSshEnvironmentTarget { |
| 184 | + const rawHost = input.host.trim(); |
| 185 | + if (rawHost.length === 0) { |
| 186 | + throw new Error("SSH host or alias is required."); |
| 187 | + } |
| 188 | + |
| 189 | + let hostname = rawHost; |
| 190 | + let username = input.username.trim() || null; |
| 191 | + let port: number | null = null; |
| 192 | + |
| 193 | + const atIndex = hostname.lastIndexOf("@"); |
| 194 | + if (atIndex > 0) { |
| 195 | + const inlineUsername = hostname.slice(0, atIndex).trim(); |
| 196 | + hostname = hostname.slice(atIndex + 1).trim(); |
| 197 | + if (!username && inlineUsername.length > 0) { |
| 198 | + username = inlineUsername; |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + const bracketedHostMatch = /^\[([^\]]+)\](?::(\d+))?$/u.exec(hostname); |
| 203 | + if (bracketedHostMatch) { |
| 204 | + hostname = bracketedHostMatch[1]!.trim(); |
| 205 | + if (bracketedHostMatch[2]) { |
| 206 | + port = Number.parseInt(bracketedHostMatch[2], 10); |
| 207 | + } |
| 208 | + } else { |
| 209 | + const colonSegments = hostname.split(":"); |
| 210 | + if (colonSegments.length === 2 && /^\d+$/u.test(colonSegments[1] ?? "")) { |
| 211 | + hostname = colonSegments[0]!.trim(); |
| 212 | + port = Number.parseInt(colonSegments[1]!, 10); |
| 213 | + } |
| 214 | + } |
| 215 | + |
| 216 | + const rawPort = input.port.trim(); |
| 217 | + if (rawPort.length > 0) { |
| 218 | + port = Number.parseInt(rawPort, 10); |
| 219 | + } |
| 220 | + |
| 221 | + if (hostname.length === 0) { |
| 222 | + throw new Error("SSH host or alias is required."); |
| 223 | + } |
| 224 | + |
| 225 | + if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) { |
| 226 | + throw new Error("SSH port must be between 1 and 65535."); |
| 227 | + } |
| 228 | + |
| 229 | + return { |
| 230 | + alias: hostname, |
| 231 | + hostname, |
| 232 | + username, |
| 233 | + port, |
| 234 | + }; |
| 235 | +} |
| 236 | + |
| 237 | +export function parsePairingUrlFields( |
| 238 | + input: string, |
| 239 | +): { readonly host: string; readonly pairingCode: string } | null { |
| 240 | + const trimmed = input.trim(); |
| 241 | + if (!trimmed) return null; |
| 242 | + |
| 243 | + try { |
| 244 | + const urlLikeInput = |
| 245 | + /^[a-zA-Z][a-zA-Z\d+.-]*:\/\//u.test(trimmed) || trimmed.startsWith("//") |
| 246 | + ? trimmed |
| 247 | + : `https://${trimmed}`; |
| 248 | + const url = new URL(urlLikeInput, window.location.origin); |
| 249 | + const hostedPairingRequest = readHostedPairingRequest(url); |
| 250 | + if (hostedPairingRequest) { |
| 251 | + return { |
| 252 | + host: hostedPairingRequest.host, |
| 253 | + pairingCode: hostedPairingRequest.token, |
| 254 | + }; |
| 255 | + } |
| 256 | + |
| 257 | + const pairingCode = getPairingTokenFromUrl(url); |
| 258 | + if (!pairingCode) return null; |
| 259 | + return { |
| 260 | + host: url.origin, |
| 261 | + pairingCode, |
| 262 | + }; |
| 263 | + } catch { |
| 264 | + return null; |
| 265 | + } |
| 266 | +} |
| 267 | + |
| 268 | +export function parseRemotePairingFields(input: { |
| 269 | + readonly host: string; |
| 270 | + readonly pairingCode: string; |
| 271 | +}): { |
| 272 | + readonly host: string; |
| 273 | + readonly pairingCode: string; |
| 274 | +} { |
| 275 | + const parsedPairingUrl = parsePairingUrlFields(input.host); |
| 276 | + if (parsedPairingUrl) return parsedPairingUrl; |
| 277 | + |
| 278 | + const host = input.host.trim(); |
| 279 | + const pairingCode = input.pairingCode.trim(); |
| 280 | + if (!host) { |
| 281 | + throw new Error("Enter a backend host."); |
| 282 | + } |
| 283 | + if (!pairingCode) { |
| 284 | + throw new Error("Enter a pairing code."); |
| 285 | + } |
| 286 | + return { host, pairingCode }; |
| 287 | +} |
| 288 | + |
| 289 | +export function formatDesktopSshConnectionError(error: unknown): string { |
| 290 | + const fallback = "Failed to connect SSH host."; |
| 291 | + const rawMessage = error instanceof Error ? error.message : fallback; |
| 292 | + const withoutIpcPrefix = rawMessage.replace( |
| 293 | + /^Error invoking remote method 'desktop:ensure-ssh-environment':\s*/u, |
| 294 | + "", |
| 295 | + ); |
| 296 | + const withoutTaggedErrorPrefix = withoutIpcPrefix.replace(/^Ssh[A-Za-z]+Error:\s*/u, ""); |
| 297 | + return withoutTaggedErrorPrefix.trim() || fallback; |
| 298 | +} |
| 299 | + |
| 300 | +export function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>) { |
| 301 | + return [...links].toSorted( |
| 302 | + (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(), |
| 303 | + ); |
| 304 | +} |
| 305 | + |
| 306 | +export function summarizeAuthorizedClients( |
| 307 | + sessions: ReadonlyArray<ServerClientSessionRecord>, |
| 308 | + links: ReadonlyArray<ServerPairingLinkRecord>, |
| 309 | +): string { |
| 310 | + const parts = [ |
| 311 | + `${sessions.length} ${sessions.length === 1 ? "client" : "clients"}`, |
| 312 | + links.length > 0 |
| 313 | + ? `${links.length} ${links.length === 1 ? "pairing link" : "pairing links"}` |
| 314 | + : null, |
| 315 | + ]; |
| 316 | + return parts.filter((part): part is string => part !== null).join(" · "); |
| 317 | +} |
| 318 | + |
| 319 | +export function sortDesktopClientSessions(sessions: ReadonlyArray<ServerClientSessionRecord>) { |
| 320 | + return [...sessions].toSorted((left, right) => { |
| 321 | + if (left.current !== right.current) { |
| 322 | + return left.current ? -1 : 1; |
| 323 | + } |
| 324 | + if (left.connected !== right.connected) { |
| 325 | + return left.connected ? -1 : 1; |
| 326 | + } |
| 327 | + return new Date(right.issuedAt).getTime() - new Date(left.issuedAt).getTime(); |
| 328 | + }); |
| 329 | +} |
| 330 | + |
| 331 | +export function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord { |
| 332 | + return { |
| 333 | + ...pairingLink, |
| 334 | + scopes: pairingLink.permissions ?? pairingLink.scopes, |
| 335 | + createdAt: DateTime.formatIso(pairingLink.createdAt), |
| 336 | + expiresAt: DateTime.formatIso(pairingLink.expiresAt), |
| 337 | + }; |
| 338 | +} |
| 339 | + |
| 340 | +export function toDesktopClientSessionRecord( |
| 341 | + clientSession: AuthClientSession, |
| 342 | +): ServerClientSessionRecord { |
| 343 | + return { |
| 344 | + ...clientSession, |
| 345 | + scopes: clientSession.permissions ?? clientSession.scopes, |
| 346 | + issuedAt: DateTime.formatIso(clientSession.issuedAt), |
| 347 | + expiresAt: DateTime.formatIso(clientSession.expiresAt), |
| 348 | + lastConnectedAt: |
| 349 | + clientSession.lastConnectedAt === null |
| 350 | + ? null |
| 351 | + : DateTime.formatIso(clientSession.lastConnectedAt), |
| 352 | + }; |
| 353 | +} |
| 354 | + |
| 355 | +export function selectPairingEndpoint( |
| 356 | + endpoints: ReadonlyArray<AdvertisedEndpoint>, |
| 357 | + defaultEndpointKey?: string | null, |
| 358 | +): AdvertisedEndpoint | null { |
| 359 | + const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable"); |
| 360 | + if (defaultEndpointKey) { |
| 361 | + const selectedEndpoint = availableEndpoints.find( |
| 362 | + (endpoint) => endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey, |
| 363 | + ); |
| 364 | + if (selectedEndpoint) { |
| 365 | + return selectedEndpoint; |
| 366 | + } |
| 367 | + } |
| 368 | + return ( |
| 369 | + availableEndpoints.find((endpoint) => endpoint.isDefault) ?? |
| 370 | + availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ?? |
| 371 | + availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ?? |
| 372 | + null |
| 373 | + ); |
| 374 | +} |
| 375 | + |
| 376 | +export function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean { |
| 377 | + return endpoint.id.startsWith("tailscale-magicdns:"); |
| 378 | +} |
| 379 | + |
| 380 | +export function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string { |
| 381 | + if (endpoint.id.startsWith("desktop-loopback:")) { |
| 382 | + return "desktop-core:loopback:http"; |
| 383 | + } |
| 384 | + if (endpoint.id.startsWith("desktop-lan:")) { |
| 385 | + return "desktop-core:lan:http"; |
| 386 | + } |
| 387 | + if (endpoint.id.startsWith("tailscale-ip:")) { |
| 388 | + return "tailscale:ip:http"; |
| 389 | + } |
| 390 | + if (isTailscaleHttpsEndpoint(endpoint)) { |
| 391 | + return "tailscale:magicdns:https"; |
| 392 | + } |
| 393 | + |
| 394 | + let scheme = "unknown"; |
| 395 | + try { |
| 396 | + scheme = new URL(endpoint.httpBaseUrl).protocol.replace(/:$/u, ""); |
| 397 | + } catch {} |
| 398 | + |
| 399 | + return `${endpoint.provider.id}:${endpoint.reachability}:${scheme}:${endpoint.label}`; |
| 400 | +} |
| 401 | + |
| 402 | +export function resolveAdvertisedEndpointPairingUrl( |
| 403 | + endpoint: AdvertisedEndpoint, |
| 404 | + credential: string, |
| 405 | +): string { |
| 406 | + if (endpoint.compatibility.hostedHttpsApp === "compatible") { |
| 407 | + return ( |
| 408 | + resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ?? |
| 409 | + resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential) |
| 410 | + ); |
| 411 | + } |
| 412 | + return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential); |
| 413 | +} |
| 414 | + |
| 415 | +export function resolveCurrentOriginPairingUrl(credential: string): string { |
| 416 | + const url = new URL("/pair", window.location.href); |
| 417 | + return setPairingTokenOnUrl(url, credential).toString(); |
| 418 | +} |
| 419 | + |
| 420 | +export function isHostedAppPairingUrl(value: string): boolean { |
| 421 | + try { |
| 422 | + const url = new URL(value); |
| 423 | + return url.pathname === "/pair" && url.searchParams.has("host"); |
| 424 | + } catch { |
| 425 | + return false; |
| 426 | + } |
| 427 | +} |
| 428 | + |
| 429 | +export function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): string { |
| 430 | + if (isHostedAppPairingUrl(url)) { |
| 431 | + return "Opens the hosted app, no install needed"; |
| 432 | + } |
| 433 | + switch (endpoint.reachability) { |
| 434 | + case "lan": |
| 435 | + return "Devices on the same network"; |
| 436 | + case "private-network": |
| 437 | + return "Devices on your private network"; |
| 438 | + case "public": |
| 439 | + return "Reachable from anywhere"; |
| 440 | + case "loopback": |
| 441 | + return "Clients on this machine"; |
| 442 | + } |
| 443 | +} |
0 commit comments