portpreview 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,65 +1,151 @@
1
- # PortPreview
1
+ # PortPreview CLI
2
2
 
3
- Expose a local port through a public HTTPS URL.
3
+ Open-source client for [PortPreview](https://portpreview.com) — expose a local port through a public URL for webhook debugging, OAuth callbacks, and dev previews.
4
+
5
+ ## Usage
4
6
 
5
7
  ```bash
6
8
  npx portpreview 3000
7
9
  ```
8
10
 
9
- Connects to the PortPreview gateway and forwards public traffic to `http://127.0.0.1:3000`.
11
+ That connects to the PortPreview gateway and forwards public traffic to `http://127.0.0.1:3000`.
12
+
13
+ ## Install in this repo
10
14
 
11
- ## Install
15
+ From the project root:
12
16
 
13
17
  ```bash
14
- npm install -g portpreview
15
- portpreview 3000
18
+ npm install
19
+ npx portpreview 3000
16
20
  ```
17
21
 
18
- Pin a version:
22
+ `npx` picks up the local CLI from `node_modules/.bin` before hitting the npm registry.
23
+
24
+ ## Publish to npm
19
25
 
20
26
  ```bash
21
- npx portpreview@0.1.0 3000
27
+ cd cli
28
+ npm login
29
+ npm publish
30
+ ```
31
+
32
+ After the current package version is published to npm, `npx portpreview 3000` works from any directory without cloning this repo.
33
+
34
+ ## Standalone Windows x64
35
+
36
+ The standalone executable includes Node.js and the same CLI used by npm. On a
37
+ verified release, download the versioned `.exe` and its `.sha256` file, check the
38
+ hash with `Get-FileHash`, then run in PowerShell:
39
+
40
+ ```powershell
41
+ .\portpreview-0.2.0-windows-x64.exe --help
42
+ .\portpreview-0.2.0-windows-x64.exe 3000
43
+ .\portpreview-0.2.0-windows-x64.exe config set-token pp_live_...
44
+ ```
45
+
46
+ No Node.js or npm installation is needed to run the executable. Windows tokens
47
+ are stored in `%LOCALAPPDATA%\portpreview\config.json` by default. Current builds
48
+ are unsigned. Download availability depends on successful Windows verification;
49
+ a cross-built artifact alone is not a verified release. See
50
+ [Windows packaging and release checks](packaging/README.md).
51
+
52
+ ## Local development (no production gateway)
53
+
54
+ ```bash
55
+ # Terminal 1 — dev gateway
56
+ npm run gateway --prefix cli
57
+
58
+ # Terminal 2 — your app
59
+ python3 -m http.server 3000
60
+
61
+ # Terminal 3 — tunnel
62
+ npx portpreview 3000 \
63
+ --gateway ws://127.0.0.1:4040/tunnel \
64
+ --domain localhost:4040
22
65
  ```
23
66
 
24
67
  ## Options
25
68
 
26
69
  | Flag | Description |
27
70
  |------|-------------|
28
- | `--host <addr>` | Local address to forward to (default `127.0.0.1`) |
29
- | `--subdomain <name>` | Request a specific subdomain |
30
- | `--gateway <url>` | WebSocket gateway URL |
31
- | `--domain <domain>` | Public tunnel domain |
71
+ | `--host` | Local address to forward to (default `127.0.0.1`) |
72
+ | `--subdomain` | Use a name reserved in your dashboard |
73
+ | `--token` | Authenticate with a dashboard CLI token |
32
74
  | `-q, --quiet` | Print only the public URL |
33
75
  | `-h, --help` | Show help |
34
76
  | `-v, --version` | Show version |
35
77
 
36
78
  ## Environment
37
79
 
38
- | Variable | Default |
39
- |----------|---------|
40
- | `PORTPREVIEW_GATEWAY_URL` | `wss://gateway.portpreview.dev/tunnel` |
41
- | `PORTPREVIEW_TUNNEL_DOMAIN` | `portpreview.dev` |
80
+ | Variable | Description |
81
+ |----------|-------------|
82
+ | `PORTPREVIEW_TOKEN` | CLI token used for reserved subdomains |
83
+ | `PORTPREVIEW_CONFIG` | Override local config file path |
42
84
 
43
- ## Programmatic API
85
+ See **Local development** below for `--gateway`, `--domain`, and related env vars.
44
86
 
45
- ```javascript
46
- import { openTunnel } from 'portpreview'
87
+ ## Persistent token (recommended)
47
88
 
48
- const tunnel = await openTunnel({ port: 3000, quiet: true })
49
- console.log(tunnel.url)
50
- await tunnel.close()
89
+ ```bash
90
+ npx portpreview config set-token pp_live_...
91
+ npx portpreview 3000
92
+ npx portpreview config check
51
93
  ```
52
94
 
53
- ## Development
95
+ Default config file: `~/.config/portpreview/config.json` on Linux.
96
+
97
+ Gateway deployments also require `GATEWAY_API_SECRET` (shared with the website) and may set
98
+ `PORTPREVIEW_ACCOUNT_API_URL`, `PORTPREVIEW_MAX_TUNNELS`, and
99
+ `PORTPREVIEW_MAX_REQUEST_BODY_BYTES`.
100
+
101
+ ## Tests
54
102
 
55
103
  ```bash
56
- git clone https://github.com/elemops/portpreview.git
57
- cd portpreview
58
- npm install
59
- npm test
60
- node bin/portpreview.mjs 3000
61
- ```
104
+ npm test --prefix cli
105
+
106
+ # Opt-in: generated >5 GiB upload and download, checksums, bounded memory; no disk body
107
+ RUN_LARGE_STREAM_TEST=1 node --test --test-concurrency=1 cli/test/streaming.test.mjs
62
108
 
63
- ## License
109
+ # Opt-in: real wall-clock session for 2 hours + 90 seconds
110
+ node cli/test/tunnel-soak.mjs
111
+ ```
64
112
 
65
- Apache-2.0
113
+ ## Tunnel sessions and request history
114
+
115
+ Free accounts and anonymous visitors can run one active tunnel at a time.
116
+ Tunnel sessions have no duration limit on any plan. Self-hosted gateways older
117
+ than 0.2.0 can retain their previous session limits until they are upgraded.
118
+
119
+ The 0.2.0 client negotiates protocol v3 with a 0.2.0 gateway. HTTP
120
+ request and response bodies stream without a total byte, traffic, or active
121
+ transfer duration limit. Each direction uses 64 KiB chunks and a 256 KiB credit
122
+ window; inspector captures only the first 64 KiB and marks incomplete previews.
123
+ Range, If-Range, ETag, Content-Range and original Content-Length are preserved,
124
+ including 206/416 and HEAD. Streams with no progress for 120 seconds are
125
+ cancelled; active slow streams may continue indefinitely. Tunnel transport
126
+ heartbeats detect dead connections. After transient network loss, the CLI
127
+ reconnects automatically with exponential backoff and jitter, from 500 ms up to
128
+ 30 seconds. Anonymous tunnels may receive a new URL, which the command announces;
129
+ reserved tunnels retry with the same subdomain and token. Access revocation and
130
+ permanent registration or authentication errors stop retries. Ctrl+C cancels
131
+ pending connection attempts and retry timers.
132
+
133
+ Interrupted HTTP transfers are cancelled and must be retried by the application;
134
+ reconnecting does not replay requests or resume their bytes. Applications can
135
+ resume downloads with Range and If-Range when the upstream supports them. Library
136
+ callers can observe the current URL through the returned `url` getter or an
137
+ `onReconnect` callback.
138
+
139
+ Clients older than 0.2.0 and fallback to older v2 gateways retain the legacy
140
+ 1 MiB HTTP body cap; both ends need upgrading for streaming. WebSocket messages
141
+ retain an explicit 1 MiB per-message limit; oversized messages close rather than
142
+ silently truncate. Requests made by automated agents and webhooks are included
143
+ in request history.
144
+
145
+ Protect reserved preview domains with a password or IP/CIDR allowlist in the
146
+ dashboard (all plans). A password uses HTTP Basic authentication; enter any
147
+ username and your preview password. This credential is consumed by the gateway
148
+ and is not forwarded to localhost. Application HTTP Basic authentication cannot
149
+ share the same Authorization header, so use an application session cookie or a
150
+ bearer token route without preview password protection. Policy changes and token
151
+ revocations take effect within 30 seconds on connected gateways.
@@ -1,68 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import packageJson from '../package.json' with { type: 'json' }
4
- import { parseArgs, printHelp } from '../lib/config.mjs'
5
- import { openTunnel } from '../lib/tunnel-client.mjs'
3
+ import { createRequire } from 'node:module'
4
+ import { runCli } from '../lib/cli-main.mjs'
6
5
 
7
- async function main() {
8
- const parsed = parseArgs()
6
+ const require = createRequire(import.meta.url)
7
+ const { version } = require('../package.json')
9
8
 
10
- if ('help' in parsed) {
11
- printHelp()
12
- return
13
- }
14
-
15
- if ('version' in parsed) {
16
- console.log(packageJson.version)
17
- return
18
- }
19
-
20
- const target = `http://${parsed.host}:${parsed.port}`
21
-
22
- if (!parsed.quiet) {
23
- console.log('Connecting to gateway…')
24
- console.log(`Forwarding ${target}`)
25
- }
26
-
27
- let tunnel
28
- try {
29
- tunnel = await openTunnel(parsed)
30
- } catch (err) {
31
- console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
32
- process.exit(1)
33
- }
34
-
35
- if (!parsed.quiet) {
36
- console.log('Connected')
37
- console.log(`URL: ${tunnel.url}`)
38
- console.log(`Target: ${target}`)
39
- console.log('Press Ctrl+C to stop.')
40
- } else {
41
- console.log(tunnel.url)
42
- }
43
-
44
- let shuttingDown = false
45
- const shutdown = () => {
46
- if (shuttingDown) {
47
- process.exit(1)
48
- return
49
- }
50
- shuttingDown = true
51
-
52
- tunnel
53
- .close()
54
- .then(() => process.exit(0))
55
- .catch((err) => {
56
- console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
57
- process.exit(1)
58
- })
59
- }
60
-
61
- process.on('SIGINT', shutdown)
62
- process.on('SIGTERM', shutdown)
63
- }
64
-
65
- main().catch((err) => {
9
+ runCli(process.argv.slice(2), { version }).catch((err) => {
66
10
  console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
67
11
  process.exit(1)
68
12
  })
@@ -0,0 +1,40 @@
1
+ import { parseArgs, printHelp } from './config.mjs'
2
+ import { runConfigCommand } from './config-cli.mjs'
3
+ import { openTunnel } from './tunnel-client.mjs'
4
+
5
+ /** Shared entry point for the npm command and the standalone executable. */
6
+ export async function runCli(argv, { version }) {
7
+ if (argv[0] === 'config') {
8
+ runConfigCommand(argv.slice(1))
9
+ return
10
+ }
11
+ const parsed = parseArgs(argv)
12
+ if ('help' in parsed) { printHelp(); return }
13
+ if ('version' in parsed) { console.log(version); return }
14
+
15
+ const target = `http://${parsed.host}:${parsed.port}`
16
+ if (!parsed.quiet) {
17
+ console.log('Connecting to gateway…')
18
+ console.log(`Forwarding ${target}`)
19
+ }
20
+ const controller = new AbortController()
21
+ let tunnel
22
+ const shutdown = () => { controller.abort(); void tunnel?.close() }
23
+ process.on('SIGINT', shutdown)
24
+ process.on('SIGTERM', shutdown)
25
+ try { tunnel = await openTunnel({ ...parsed, signal: controller.signal }) }
26
+ catch (error) {
27
+ process.off('SIGINT', shutdown); process.off('SIGTERM', shutdown)
28
+ if (controller.signal.aborted) return
29
+ throw error
30
+ }
31
+ if (!parsed.quiet) {
32
+ console.log('Connected')
33
+ console.log(`URL: ${tunnel.url}`)
34
+ console.log(`Target: ${target}`)
35
+ console.log('Press Ctrl+C to stop.')
36
+ } else {
37
+ console.log(tunnel.url)
38
+ }
39
+ void tunnel.closed.then(() => { process.off('SIGINT', shutdown); process.off('SIGTERM', shutdown) })
40
+ }
@@ -0,0 +1,83 @@
1
+ import { normalizeCountryName, resolveCountryFromIp } from './geo.mjs'
2
+
3
+ /**
4
+ * @typedef {Object} TunnelSession
5
+ * @property {string} subdomain
6
+ * @property {string} url
7
+ * @property {string} localHost
8
+ * @property {number} localPort
9
+ * @property {Date} openedAt
10
+ * @property {Date} [closedAt]
11
+ * @property {string} clientIp
12
+ * @property {string | null} country
13
+ * @property {Record<string, number>} [messageIds]
14
+ */
15
+
16
+ /** @typedef {{ ip: string, country: string | null }} ClientInfo */
17
+
18
+ /**
19
+ * @typedef {Object} SiteVisit
20
+ * @property {string} path
21
+ * @property {string | null} locale
22
+ * @property {string | null} referer
23
+ * @property {string} ip
24
+ * @property {string | null} country
25
+ * @property {string | null} userAgent
26
+ * @property {Date} visitedAt
27
+ */
28
+
29
+ /**
30
+ * @param {import('node:http').IncomingMessage | import('node:http').IncomingMessage & { headers: Record<string, string | string[] | undefined> }} req
31
+ * @param {{ path: string, locale?: string | null }} context
32
+ * @returns {SiteVisit}
33
+ */
34
+ export function extractSiteVisit(req, context) {
35
+ const clientInfo = extractClientInfo(req)
36
+ const referer = req.headers.referer ?? req.headers.referrer ?? null
37
+ const userAgent = req.headers['user-agent'] ?? null
38
+
39
+ return {
40
+ path: context.path,
41
+ locale: context.locale ?? null,
42
+ referer: referer ? String(referer) : null,
43
+ ip: clientInfo.ip,
44
+ country: clientInfo.country,
45
+ userAgent: userAgent ? String(userAgent) : null,
46
+ visitedAt: new Date(),
47
+ }
48
+ }
49
+
50
+ /**
51
+ * @param {import('node:http').IncomingMessage} req
52
+ */
53
+ export function extractClientInfo(req) {
54
+ const forwarded =
55
+ req.headers['cf-connecting-ip'] ??
56
+ String(req.headers['x-forwarded-for'] ?? '')
57
+ .split(',')[0]
58
+ ?.trim() ??
59
+ req.headers['x-real-ip'] ??
60
+ req.socket?.remoteAddress
61
+
62
+ const ip = forwarded ? String(forwarded).replace(/^::ffff:/, '') : 'unknown'
63
+ const rawCountry = req.headers['cf-ipcountry']
64
+ const country =
65
+ rawCountry && String(rawCountry).toUpperCase() !== 'XX' ? String(rawCountry).toUpperCase() : null
66
+
67
+ return { ip, country }
68
+ }
69
+
70
+ /**
71
+ * Uses Cloudflare country when present; otherwise resolves from the client IP.
72
+ * @param {ClientInfo} clientInfo
73
+ * @returns {Promise<ClientInfo>}
74
+ */
75
+ export async function enrichClientInfo(clientInfo) {
76
+ let country = normalizeCountryName(clientInfo.country)
77
+
78
+ if (!country && clientInfo.ip && clientInfo.ip !== 'unknown') {
79
+ country = await resolveCountryFromIp(clientInfo.ip)
80
+ }
81
+
82
+ return country ? { ...clientInfo, country } : { ...clientInfo, country: null }
83
+ }
@@ -0,0 +1,65 @@
1
+ import {
2
+ clearStoredToken,
3
+ defaultConfigPath,
4
+ readUserConfig,
5
+ saveToken,
6
+ } from './user-config.mjs'
7
+ import { fail } from './config.mjs'
8
+
9
+ export function printConfigHelp() {
10
+ console.log(`PortPreview config — save your CLI token locally
11
+
12
+ Usage:
13
+ portpreview config set-token <token> Save token to the local config file
14
+ portpreview config check Show config file location and token status
15
+ portpreview config unset-token Remove the saved token
16
+ portpreview config --help Show this help
17
+
18
+ After set-token, run tunnels without --token or export:
19
+ portpreview 3000
20
+ portpreview 3000 --subdomain my-app
21
+
22
+ Environment:
23
+ PORTPREVIEW_CONFIG Override config file path
24
+ `)
25
+ }
26
+
27
+ /**
28
+ * @param {string[]} args
29
+ */
30
+ export function runConfigCommand(args) {
31
+ const subcommand = args[0]
32
+
33
+ if (!subcommand || subcommand === '--help' || subcommand === '-h') {
34
+ printConfigHelp()
35
+ return
36
+ }
37
+
38
+ if (subcommand === 'set-token') {
39
+ const token = args[1]
40
+ if (!token) fail('Usage: portpreview config set-token <token>')
41
+ saveToken(token)
42
+ console.log(`Token saved to ${defaultConfigPath()}`)
43
+ return
44
+ }
45
+
46
+ if (subcommand === 'check') {
47
+ const configPath = defaultConfigPath()
48
+ const config = readUserConfig()
49
+ console.log(`Config file: ${configPath}`)
50
+ console.log(`Token: ${config.token ? 'saved' : 'not set'}`)
51
+ return
52
+ }
53
+
54
+ if (subcommand === 'unset-token') {
55
+ const removed = clearStoredToken()
56
+ console.log(
57
+ removed
58
+ ? `Token removed from ${defaultConfigPath()}`
59
+ : `No config file at ${defaultConfigPath()}`,
60
+ )
61
+ return
62
+ }
63
+
64
+ fail(`Unknown config command: ${subcommand}`)
65
+ }
package/lib/config.mjs CHANGED
@@ -1,4 +1,6 @@
1
- /** @typedef {{ port: number, host: string, subdomain?: string, gatewayUrl: string, tunnelDomain: string, quiet: boolean }} TunnelOptions */
1
+ /** @typedef {{ port: number, host: string, subdomain?: string, apiToken?: string, gatewayUrl: string, tunnelDomain: string, quiet: boolean }} TunnelOptions */
2
+
3
+ import { readStoredToken } from './user-config.mjs'
2
4
 
3
5
  export const DEFAULT_TUNNEL_DOMAIN = 'portpreview.dev'
4
6
  export const DEFAULT_GATEWAY_URL = 'wss://gateway.portpreview.dev/tunnel'
@@ -12,6 +14,7 @@ export function parseArgs(argv = process.argv.slice(2)) {
12
14
  let host = '127.0.0.1'
13
15
  /** @type {string | undefined} */
14
16
  let subdomain
17
+ let apiToken = process.env.PORTPREVIEW_TOKEN?.trim() || readStoredToken() || undefined
15
18
  let gatewayUrl = process.env.PORTPREVIEW_GATEWAY_URL?.trim() || DEFAULT_GATEWAY_URL
16
19
  let tunnelDomain = process.env.PORTPREVIEW_TUNNEL_DOMAIN?.trim() || DEFAULT_TUNNEL_DOMAIN
17
20
  let quiet = false
@@ -32,6 +35,10 @@ export function parseArgs(argv = process.argv.slice(2)) {
32
35
  subdomain = argv[++i] ?? fail('--subdomain requires a value')
33
36
  continue
34
37
  }
38
+ if (arg === '--token') {
39
+ apiToken = argv[++i] ?? fail('--token requires a value')
40
+ continue
41
+ }
35
42
  if (arg === '--gateway') {
36
43
  gatewayUrl = argv[++i] ?? fail('--gateway requires a value')
37
44
  continue
@@ -45,37 +52,51 @@ export function parseArgs(argv = process.argv.slice(2)) {
45
52
  port = Number(arg)
46
53
  }
47
54
 
48
- if (port === undefined) fail('Missing local port. Usage: npx portpreview <port>')
55
+ if (port === undefined) fail('Missing local port. Usage: portpreview <port>')
49
56
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
50
57
  fail(`Invalid port: ${argv.find((a) => !a.startsWith('-'))}`)
51
58
  }
52
59
 
53
- return { port, host, subdomain, gatewayUrl, tunnelDomain, quiet }
60
+ if (subdomain && !apiToken) {
61
+ fail('Reserved subdomains require --token, PORTPREVIEW_TOKEN, or portpreview config set-token')
62
+ }
63
+
64
+ return { port, host, subdomain, apiToken, gatewayUrl, tunnelDomain, quiet }
54
65
  }
55
66
 
56
67
  export function printHelp() {
57
68
  console.log(`PortPreview — expose localhost through a public URL
58
69
 
59
70
  Usage:
60
- npx portpreview <port> [options]
71
+ portpreview <port> [options]
72
+ portpreview config <command>
61
73
 
62
74
  Options:
63
75
  --host <addr> Local bind address to forward to (default: 127.0.0.1)
64
- --subdomain <name> Request a specific subdomain (when available)
76
+ --subdomain <name> Use a subdomain reserved by your account
77
+ --token <token> Authenticate with a CLI token
65
78
  --gateway <url> WebSocket gateway URL (default: ${DEFAULT_GATEWAY_URL})
66
79
  --domain <domain> Public tunnel domain (default: ${DEFAULT_TUNNEL_DOMAIN})
67
80
  -q, --quiet Minimal output
68
81
  -h, --help Show this help
69
82
  -v, --version Show version
70
83
 
84
+ Config:
85
+ portpreview config set-token <token> Save token locally (recommended)
86
+ portpreview config check Show config file location
87
+ portpreview config unset-token Remove saved token
88
+
71
89
  Environment:
72
90
  PORTPREVIEW_GATEWAY_URL Override gateway WebSocket URL
73
91
  PORTPREVIEW_TUNNEL_DOMAIN Override public tunnel domain
92
+ PORTPREVIEW_TOKEN Authenticate with a CLI token
93
+ PORTPREVIEW_CONFIG Override config file path
74
94
 
75
95
  Examples:
76
- npx portpreview 3000
77
- npx portpreview 8080 --subdomain myapp
78
- npx portpreview 3000 --gateway ws://127.0.0.1:4040/tunnel --domain localhost:4040
96
+ portpreview config set-token pp_live_...
97
+ portpreview 3000
98
+ portpreview 8080 --subdomain myapp
99
+ portpreview 3000 --gateway ws://127.0.0.1:4040/tunnel --domain localhost:4040
79
100
  `)
80
101
  }
81
102
 
package/lib/geo.mjs ADDED
@@ -0,0 +1,84 @@
1
+ /** @type {Map<string, string | null>} */
2
+ const countryCache = new Map()
3
+
4
+ const regionNames = new Intl.DisplayNames(['en'], { type: 'region' })
5
+
6
+ /**
7
+ * @param {string} code
8
+ * @returns {string | null}
9
+ */
10
+ export function countryNameFromCode(code) {
11
+ if (!code) return null
12
+ const normalized = String(code).trim().toUpperCase()
13
+ if (normalized.length !== 2 || normalized === 'XX') return null
14
+ try {
15
+ return regionNames.of(normalized) ?? null
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+
21
+ /**
22
+ * @param {string | null | undefined} value
23
+ * @returns {string | null}
24
+ */
25
+ export function normalizeCountryName(value) {
26
+ if (!value) return null
27
+ const trimmed = String(value).trim()
28
+ if (!trimmed) return null
29
+ if (trimmed.length === 2) return countryNameFromCode(trimmed)
30
+ return trimmed
31
+ }
32
+
33
+ /**
34
+ * @param {string} ip
35
+ */
36
+ export function isPublicIp(ip) {
37
+ if (!ip || ip === 'unknown') return false
38
+ if (ip.includes(':')) {
39
+ if (ip === '::1') return false
40
+ if (ip.startsWith('fe80:') || ip.startsWith('fc') || ip.startsWith('fd')) return false
41
+ return true
42
+ }
43
+
44
+ const parts = ip.split('.').map(Number)
45
+ if (parts.length !== 4 || parts.some((part) => Number.isNaN(part) || part < 0 || part > 255)) return false
46
+ const [a, b] = parts
47
+ if (a === 10) return false
48
+ if (a === 127) return false
49
+ if (a === 0) return false
50
+ if (a === 169 && b === 254) return false
51
+ if (a === 172 && b >= 16 && b <= 31) return false
52
+ if (a === 192 && b === 168) return false
53
+ return true
54
+ }
55
+
56
+ /**
57
+ * @param {string} ip
58
+ * @returns {Promise<string | null>}
59
+ */
60
+ export async function resolveCountryFromIp(ip) {
61
+ if (!isPublicIp(ip)) return null
62
+ if (countryCache.has(ip)) return countryCache.get(ip) ?? null
63
+
64
+ /** @type {string | null} */
65
+ let country = null
66
+
67
+ try {
68
+ const response = await fetch(
69
+ `http://ip-api.com/json/${encodeURIComponent(ip)}?fields=status,country,countryCode`,
70
+ { signal: AbortSignal.timeout(3000) },
71
+ )
72
+ if (response.ok) {
73
+ const data = await response.json()
74
+ if (data?.status === 'success') {
75
+ country = normalizeCountryName(data.country) ?? normalizeCountryName(data.countryCode)
76
+ }
77
+ }
78
+ } catch {
79
+ // Best-effort lookup — tunnel notifications still work without country.
80
+ }
81
+
82
+ countryCache.set(ip, country)
83
+ return country
84
+ }