portpreview 0.1.1 → 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 +105 -81
- package/bin/portpreview.mjs +5 -69
- package/lib/cli-main.mjs +40 -0
- package/lib/client-info.mjs +83 -0
- package/lib/config.mjs +10 -10
- package/lib/geo.mjs +84 -0
- package/lib/http-stream.mjs +134 -0
- package/lib/index.mjs +2 -8
- package/lib/protocol.mjs +15 -2
- package/lib/tunnel-client.mjs +364 -39
- package/package.json +20 -13
package/README.md
CHANGED
|
@@ -1,33 +1,76 @@
|
|
|
1
|
-
# PortPreview
|
|
1
|
+
# PortPreview CLI
|
|
2
2
|
|
|
3
|
-
|
|
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
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx portpreview 3000
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
That connects to the PortPreview gateway and forwards public traffic to `http://127.0.0.1:3000`.
|
|
12
|
+
|
|
13
|
+
## Install in this repo
|
|
14
|
+
|
|
15
|
+
From the project root:
|
|
4
16
|
|
|
5
17
|
```bash
|
|
18
|
+
npm install
|
|
6
19
|
npx portpreview 3000
|
|
7
20
|
```
|
|
8
21
|
|
|
9
|
-
|
|
22
|
+
`npx` picks up the local CLI from `node_modules/.bin` before hitting the npm registry.
|
|
10
23
|
|
|
11
|
-
##
|
|
24
|
+
## Publish to npm
|
|
12
25
|
|
|
13
26
|
```bash
|
|
14
|
-
|
|
15
|
-
|
|
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_...
|
|
16
44
|
```
|
|
17
45
|
|
|
18
|
-
|
|
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)
|
|
19
53
|
|
|
20
54
|
```bash
|
|
21
|
-
|
|
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
|
|
29
|
-
| `--subdomain
|
|
30
|
-
| `--token
|
|
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 |
|
|
31
74
|
| `-q, --quiet` | Print only the public URL |
|
|
32
75
|
| `-h, --help` | Show help |
|
|
33
76
|
| `-v, --version` | Show version |
|
|
@@ -39,89 +82,70 @@ npx portpreview@0.1.0 3000
|
|
|
39
82
|
| `PORTPREVIEW_TOKEN` | CLI token used for reserved subdomains |
|
|
40
83
|
| `PORTPREVIEW_CONFIG` | Override local config file path |
|
|
41
84
|
|
|
42
|
-
|
|
85
|
+
See **Local development** below for `--gateway`, `--domain`, and related env vars.
|
|
43
86
|
|
|
44
|
-
|
|
87
|
+
## Persistent token (recommended)
|
|
45
88
|
|
|
46
89
|
```bash
|
|
47
90
|
npx portpreview config set-token pp_live_...
|
|
48
91
|
npx portpreview 3000
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
Default config locations:
|
|
52
|
-
|
|
53
|
-
| OS | Path |
|
|
54
|
-
|----|------|
|
|
55
|
-
| Linux | `~/.config/portpreview/config.json` |
|
|
56
|
-
| macOS | `~/Library/Application Support/portpreview/config.json` |
|
|
57
|
-
| Windows | `%LOCALAPPDATA%\\portpreview\\config.json` |
|
|
58
|
-
|
|
59
|
-
Check where your config is stored:
|
|
60
|
-
|
|
61
|
-
```bash
|
|
62
92
|
npx portpreview config check
|
|
63
93
|
```
|
|
64
94
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
```bash
|
|
68
|
-
npx portpreview config unset-token
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
## Reserved subdomains
|
|
72
|
-
|
|
73
|
-
Create a free account at [portpreview.com/register](https://portpreview.com/register), reserve a
|
|
74
|
-
subdomain in the dashboard, and save your default CLI token. Then either pass the token directly:
|
|
75
|
-
|
|
76
|
-
```bash
|
|
77
|
-
npx portpreview 3000 --subdomain my-project --token pp_live_...
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
Or save it once with config:
|
|
95
|
+
Default config file: `~/.config/portpreview/config.json` on Linux.
|
|
81
96
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
```
|
|
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`.
|
|
86
100
|
|
|
87
|
-
|
|
101
|
+
## Tests
|
|
88
102
|
|
|
89
103
|
```bash
|
|
90
|
-
|
|
91
|
-
npx portpreview 3000 --subdomain my-project
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
Commands without `--subdomain` continue to work anonymously with a random URL.
|
|
95
|
-
|
|
96
|
-
## Programmatic API
|
|
97
|
-
|
|
98
|
-
```javascript
|
|
99
|
-
import { openTunnel } from 'portpreview'
|
|
100
|
-
|
|
101
|
-
const tunnel = await openTunnel({ port: 3000, quiet: true })
|
|
102
|
-
console.log(tunnel.url)
|
|
103
|
-
await tunnel.close()
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
## Development
|
|
107
|
-
|
|
108
|
-
For local gateway development only (not needed for normal use):
|
|
104
|
+
npm test --prefix cli
|
|
109
105
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
| `--gateway <url>` | `wss://gateway.portpreview.dev/tunnel` | Point the CLI at another gateway |
|
|
113
|
-
| `--domain <domain>` | `portpreview.dev` | Base hostname used in public URLs |
|
|
114
|
-
| `PORTPREVIEW_GATEWAY_URL` | same as above | Env override for `--gateway` |
|
|
115
|
-
| `PORTPREVIEW_TUNNEL_DOMAIN` | `portpreview.dev` | Env override for `--domain` |
|
|
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
|
|
116
108
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
cd portpreview
|
|
120
|
-
npm install
|
|
121
|
-
npm test
|
|
122
|
-
node bin/portpreview.mjs 3000
|
|
109
|
+
# Opt-in: real wall-clock session for 2 hours + 90 seconds
|
|
110
|
+
node cli/test/tunnel-soak.mjs
|
|
123
111
|
```
|
|
124
112
|
|
|
125
|
-
##
|
|
126
|
-
|
|
127
|
-
|
|
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.
|
package/bin/portpreview.mjs
CHANGED
|
@@ -1,76 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import { runConfigCommand } from '../lib/config-cli.mjs'
|
|
6
|
-
import { openTunnel } from '../lib/tunnel-client.mjs'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { runCli } from '../lib/cli-main.mjs'
|
|
7
5
|
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
const require = createRequire(import.meta.url)
|
|
7
|
+
const { version } = require('../package.json')
|
|
10
8
|
|
|
11
|
-
|
|
12
|
-
runConfigCommand(argv.slice(1))
|
|
13
|
-
return
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const parsed = parseArgs(argv)
|
|
17
|
-
|
|
18
|
-
if ('help' in parsed) {
|
|
19
|
-
printHelp()
|
|
20
|
-
return
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
if ('version' in parsed) {
|
|
24
|
-
console.log(packageJson.version)
|
|
25
|
-
return
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const target = `http://${parsed.host}:${parsed.port}`
|
|
29
|
-
|
|
30
|
-
if (!parsed.quiet) {
|
|
31
|
-
console.log('Connecting to gateway…')
|
|
32
|
-
console.log(`Forwarding ${target}`)
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
let tunnel
|
|
36
|
-
try {
|
|
37
|
-
tunnel = await openTunnel(parsed)
|
|
38
|
-
} catch (err) {
|
|
39
|
-
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
|
|
40
|
-
process.exit(1)
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
if (!parsed.quiet) {
|
|
44
|
-
console.log('Connected')
|
|
45
|
-
console.log(`URL: ${tunnel.url}`)
|
|
46
|
-
console.log(`Target: ${target}`)
|
|
47
|
-
console.log('Press Ctrl+C to stop.')
|
|
48
|
-
} else {
|
|
49
|
-
console.log(tunnel.url)
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
let shuttingDown = false
|
|
53
|
-
const shutdown = () => {
|
|
54
|
-
if (shuttingDown) {
|
|
55
|
-
process.exit(1)
|
|
56
|
-
return
|
|
57
|
-
}
|
|
58
|
-
shuttingDown = true
|
|
59
|
-
|
|
60
|
-
tunnel
|
|
61
|
-
.close()
|
|
62
|
-
.then(() => process.exit(0))
|
|
63
|
-
.catch((err) => {
|
|
64
|
-
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
|
|
65
|
-
process.exit(1)
|
|
66
|
-
})
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
process.on('SIGINT', shutdown)
|
|
70
|
-
process.on('SIGTERM', shutdown)
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
main().catch((err) => {
|
|
9
|
+
runCli(process.argv.slice(2), { version }).catch((err) => {
|
|
74
10
|
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
|
|
75
11
|
process.exit(1)
|
|
76
12
|
})
|
package/lib/cli-main.mjs
ADDED
|
@@ -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
|
+
}
|
package/lib/config.mjs
CHANGED
|
@@ -52,7 +52,7 @@ export function parseArgs(argv = process.argv.slice(2)) {
|
|
|
52
52
|
port = Number(arg)
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
-
if (port === undefined) fail('Missing local port. Usage:
|
|
55
|
+
if (port === undefined) fail('Missing local port. Usage: portpreview <port>')
|
|
56
56
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
57
57
|
fail(`Invalid port: ${argv.find((a) => !a.startsWith('-'))}`)
|
|
58
58
|
}
|
|
@@ -68,8 +68,8 @@ export function printHelp() {
|
|
|
68
68
|
console.log(`PortPreview — expose localhost through a public URL
|
|
69
69
|
|
|
70
70
|
Usage:
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
portpreview <port> [options]
|
|
72
|
+
portpreview config <command>
|
|
73
73
|
|
|
74
74
|
Options:
|
|
75
75
|
--host <addr> Local bind address to forward to (default: 127.0.0.1)
|
|
@@ -82,9 +82,9 @@ Options:
|
|
|
82
82
|
-v, --version Show version
|
|
83
83
|
|
|
84
84
|
Config:
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
88
|
|
|
89
89
|
Environment:
|
|
90
90
|
PORTPREVIEW_GATEWAY_URL Override gateway WebSocket URL
|
|
@@ -93,10 +93,10 @@ Environment:
|
|
|
93
93
|
PORTPREVIEW_CONFIG Override config file path
|
|
94
94
|
|
|
95
95
|
Examples:
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
|
100
100
|
`)
|
|
101
101
|
}
|
|
102
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
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { attachedBody, encodeFrame, send, STREAM_CHUNK_BYTES, STREAM_WINDOW_BYTES } from './protocol.mjs'
|
|
2
|
+
|
|
3
|
+
/** Bounded HTTP pipe. Credits return only after the destination flushes its write.
|
|
4
|
+
* The readable is pulled in <=64KiB pieces; at most 256KiB is in flight per direction.
|
|
5
|
+
* Neither byte count nor elapsed transfer duration limits a stream.
|
|
6
|
+
*/
|
|
7
|
+
export function createHttpStream({ ws, id, outgoing, onError, onEnd, onSentEnd, onSend, onReceive, idleTimeoutMs = 120_000, destroyOnError = true }) {
|
|
8
|
+
const incoming = outgoing === 'request' ? 'response' : 'request'
|
|
9
|
+
let source, destination, credit = 0, available = STREAM_WINDOW_BYTES
|
|
10
|
+
let pumping = false, sentEnd = false, receivedEnd = false, closed = false
|
|
11
|
+
let timer
|
|
12
|
+
const activity = () => {
|
|
13
|
+
clearTimeout(timer)
|
|
14
|
+
if (idleTimeoutMs > 0 && !closed) {
|
|
15
|
+
timer = setTimeout(() => fail(new Error('HTTP stream idle timeout')), idleTimeoutMs)
|
|
16
|
+
timer.unref()
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const control = (message) => {
|
|
20
|
+
if (ws.readyState !== ws.OPEN) throw new Error('Tunnel offline')
|
|
21
|
+
send(ws, { ...message, id })
|
|
22
|
+
activity()
|
|
23
|
+
}
|
|
24
|
+
const fail = (error, notify = true) => {
|
|
25
|
+
if (closed) return
|
|
26
|
+
if (notify && ws.readyState === ws.OPEN) send(ws, { type: 'http_cancel', id, reason: error.message })
|
|
27
|
+
stop()
|
|
28
|
+
onError?.(error)
|
|
29
|
+
if (destroyOnError) { source?.destroy(); destination?.destroy() }
|
|
30
|
+
}
|
|
31
|
+
function stop() {
|
|
32
|
+
if (closed) return
|
|
33
|
+
closed = true
|
|
34
|
+
clearTimeout(timer)
|
|
35
|
+
source?.off('readable', pump)
|
|
36
|
+
source?.off('end', pump)
|
|
37
|
+
source?.off('error', fail)
|
|
38
|
+
// Aborted IncomingMessages can emit ECONNRESET after their aborted event.
|
|
39
|
+
source?.once('error', () => {})
|
|
40
|
+
destination?.off('error', fail)
|
|
41
|
+
}
|
|
42
|
+
async function pump() {
|
|
43
|
+
if (pumping || closed || sentEnd || !source) return
|
|
44
|
+
pumping = true
|
|
45
|
+
try {
|
|
46
|
+
source.read(0)
|
|
47
|
+
while (!closed && credit > 0) {
|
|
48
|
+
// IncomingMessage.read(n) may wait for n bytes. read() then split would
|
|
49
|
+
// retain an arbitrarily sized custom source chunk; cap the pull instead.
|
|
50
|
+
const size = Math.min(credit, STREAM_CHUNK_BYTES, source.readableLength)
|
|
51
|
+
if (!size) break
|
|
52
|
+
const chunk = source.read(size)
|
|
53
|
+
if (!chunk) break
|
|
54
|
+
credit -= chunk.length
|
|
55
|
+
onSend?.(chunk)
|
|
56
|
+
const frame = encodeFrame({ type: 'http_data', id, direction: outgoing }, chunk)
|
|
57
|
+
await new Promise((resolve, reject) => ws.send(frame, { binary: true }, (error) => error ? reject(error) : resolve()))
|
|
58
|
+
activity()
|
|
59
|
+
}
|
|
60
|
+
if (!closed && source.readableEnded && source.readableLength === 0) {
|
|
61
|
+
sentEnd = true
|
|
62
|
+
control({ type: 'http_end', direction: outgoing })
|
|
63
|
+
onSentEnd?.()
|
|
64
|
+
}
|
|
65
|
+
} catch (error) { fail(error) }
|
|
66
|
+
finally { pumping = false }
|
|
67
|
+
}
|
|
68
|
+
activity()
|
|
69
|
+
return {
|
|
70
|
+
setSource(readable) {
|
|
71
|
+
source = readable
|
|
72
|
+
readable.on('readable', pump)
|
|
73
|
+
readable.on('end', pump)
|
|
74
|
+
readable.on('error', fail)
|
|
75
|
+
void pump()
|
|
76
|
+
},
|
|
77
|
+
setDestination(writable) {
|
|
78
|
+
destination = writable
|
|
79
|
+
writable.on('error', fail)
|
|
80
|
+
control({ type: 'http_credit', direction: incoming, bytes: STREAM_WINDOW_BYTES })
|
|
81
|
+
},
|
|
82
|
+
handle(message) {
|
|
83
|
+
if (closed) return
|
|
84
|
+
activity()
|
|
85
|
+
if (message.type === 'http_cancel') { fail(new Error(String(message.reason ?? 'HTTP stream cancelled')), false); return }
|
|
86
|
+
if (message.type === 'http_credit') {
|
|
87
|
+
if (message.direction !== outgoing || !Number.isInteger(message.bytes) || message.bytes <= 0 || credit + message.bytes > STREAM_WINDOW_BYTES) {
|
|
88
|
+
fail(new Error('Invalid HTTP stream credit')); return
|
|
89
|
+
}
|
|
90
|
+
credit += message.bytes
|
|
91
|
+
void pump()
|
|
92
|
+
} else if (message.type === 'http_data') {
|
|
93
|
+
const chunk = attachedBody(message)
|
|
94
|
+
if (message.direction !== incoming || !destination || receivedEnd || !chunk.length || chunk.length > STREAM_CHUNK_BYTES || chunk.length > available) {
|
|
95
|
+
fail(new Error('Invalid HTTP stream data')); return
|
|
96
|
+
}
|
|
97
|
+
available -= chunk.length
|
|
98
|
+
onReceive?.(chunk)
|
|
99
|
+
destination.write(chunk, (error) => {
|
|
100
|
+
if (error) { fail(error); return }
|
|
101
|
+
if (closed || receivedEnd) return
|
|
102
|
+
available += chunk.length
|
|
103
|
+
try { control({ type: 'http_credit', direction: incoming, bytes: chunk.length }) } catch (error) { fail(error) }
|
|
104
|
+
})
|
|
105
|
+
} else if (message.type === 'http_end') {
|
|
106
|
+
if (message.direction !== incoming || !destination || receivedEnd) { fail(new Error('Invalid HTTP stream end')); return }
|
|
107
|
+
receivedEnd = true
|
|
108
|
+
destination.end(() => onEnd?.())
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
cancel: fail,
|
|
112
|
+
stop,
|
|
113
|
+
touch: activity,
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Capture only a preview; never retain the full streaming body. */
|
|
118
|
+
export function createBodyPreview(limit = 64 * 1024) {
|
|
119
|
+
const chunks = []
|
|
120
|
+
let retained = 0, bytes = 0n
|
|
121
|
+
return {
|
|
122
|
+
add(chunk) {
|
|
123
|
+
bytes += BigInt(chunk.length)
|
|
124
|
+
if (retained < limit) {
|
|
125
|
+
const part = chunk.subarray(0, limit - retained)
|
|
126
|
+
chunks.push(Buffer.from(part))
|
|
127
|
+
retained += part.length
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
get bytes() { return bytes <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(bytes) : bytes.toString() },
|
|
131
|
+
get truncated() { return bytes > BigInt(retained) },
|
|
132
|
+
body() { return Buffer.concat(chunks, retained) },
|
|
133
|
+
}
|
|
134
|
+
}
|
package/lib/index.mjs
CHANGED
|
@@ -1,10 +1,4 @@
|
|
|
1
|
-
export {
|
|
2
|
-
DEFAULT_GATEWAY_URL,
|
|
3
|
-
DEFAULT_TUNNEL_DOMAIN,
|
|
4
|
-
fail,
|
|
5
|
-
parseArgs,
|
|
6
|
-
printHelp,
|
|
7
|
-
} from './config.mjs'
|
|
1
|
+
export { parseArgs, printHelp, DEFAULT_GATEWAY_URL, DEFAULT_TUNNEL_DOMAIN, fail } from './config.mjs'
|
|
8
2
|
export { printConfigHelp, runConfigCommand } from './config-cli.mjs'
|
|
9
3
|
export {
|
|
10
4
|
assertValidToken,
|
|
@@ -15,4 +9,4 @@ export {
|
|
|
15
9
|
saveToken,
|
|
16
10
|
} from './user-config.mjs'
|
|
17
11
|
export { openTunnel, waitForLocalPort } from './tunnel-client.mjs'
|
|
18
|
-
export {
|
|
12
|
+
export { publicUrl, PROTOCOL_VERSION, MAX_BODY_BYTES } from './protocol.mjs'
|
package/lib/protocol.mjs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
/** Wire format shared by CLI client and gateway. */
|
|
2
2
|
|
|
3
|
-
export const PROTOCOL_VERSION =
|
|
3
|
+
export const PROTOCOL_VERSION = 3
|
|
4
|
+
export const LEGACY_PROTOCOL_VERSION = 2
|
|
5
|
+
export const STREAM_CHUNK_BYTES = 64 * 1024
|
|
6
|
+
export const STREAM_WINDOW_BYTES = 256 * 1024
|
|
4
7
|
|
|
5
|
-
/**
|
|
8
|
+
/** Legacy v2 attached-body cap; v3 HTTP uses bounded chunks with no total body cap. */
|
|
6
9
|
export const MAX_BODY_BYTES = 1024 * 1024
|
|
7
10
|
export const MAX_HEADER_BYTES = 256 * 1024
|
|
8
11
|
export const MAX_FRAME_BYTES = 4 + MAX_HEADER_BYTES + MAX_BODY_BYTES
|
|
@@ -83,6 +86,8 @@ function withBodyHeaders(headers, length, truncated) {
|
|
|
83
86
|
* @param {unknown} [body]
|
|
84
87
|
*/
|
|
85
88
|
export function encodeFrame(header, body) {
|
|
89
|
+
if (header.type === 'http_data' && toBuffer(body).length > STREAM_CHUNK_BYTES) throw new Error('Streaming chunk too large')
|
|
90
|
+
if (header.type === 'ws_data' && toBuffer(body).length > MAX_BODY_BYTES) throw new Error('WebSocket message too large')
|
|
86
91
|
const clipped = clipBody(body)
|
|
87
92
|
const payload = stripAttachedFields(header)
|
|
88
93
|
const truncated = Boolean(payload.truncated) || clipped.truncated
|
|
@@ -169,3 +174,11 @@ export function localGatewayHttpUrl(subdomain, tunnelDomain) {
|
|
|
169
174
|
}
|
|
170
175
|
return publicUrl(subdomain, tunnelDomain)
|
|
171
176
|
}
|
|
177
|
+
|
|
178
|
+
/** Normalize received close details before passing them to ws. */
|
|
179
|
+
export function closeWebSocket(socket, code = 1000, reason = '') {
|
|
180
|
+
const valid = [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014].includes(Number(code)) || (Number.isInteger(Number(code)) && Number(code) >= 3000 && Number(code) <= 4999)
|
|
181
|
+
let text = String(reason ?? '')
|
|
182
|
+
while (Buffer.byteLength(text) > 123) text = text.slice(0, -1)
|
|
183
|
+
socket.close(valid ? Number(code) : 1000, text)
|
|
184
|
+
}
|
package/lib/tunnel-client.mjs
CHANGED
|
@@ -3,42 +3,42 @@ import net from 'node:net'
|
|
|
3
3
|
import { WebSocket } from 'ws'
|
|
4
4
|
import {
|
|
5
5
|
attachedBody,
|
|
6
|
+
closeWebSocket,
|
|
6
7
|
localGatewayHttpUrl,
|
|
7
8
|
MAX_BODY_BYTES,
|
|
9
|
+
MAX_FRAME_BYTES,
|
|
10
|
+
LEGACY_PROTOCOL_VERSION,
|
|
8
11
|
parseMessage,
|
|
9
12
|
publicUrl,
|
|
10
13
|
PROTOCOL_VERSION,
|
|
11
14
|
send,
|
|
12
15
|
} from './protocol.mjs'
|
|
16
|
+
import { createHttpStream } from './http-stream.mjs'
|
|
13
17
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
export function waitForLocalPort({ host, port }) {
|
|
18
|
+
function abortError() { const error = new Error('Tunnel connection cancelled'); error.name = 'AbortError'; return error }
|
|
19
|
+
|
|
20
|
+
/** @param {{ host: string, port: number, signal?: AbortSignal }} options */
|
|
21
|
+
export function waitForLocalPort({ host, port, signal }) {
|
|
19
22
|
return new Promise((resolve, reject) => {
|
|
23
|
+
if (signal?.aborted) { reject(abortError()); return }
|
|
20
24
|
const socket = net.connect({ host, port })
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
})
|
|
25
|
-
socket.once('error',
|
|
26
|
-
|
|
27
|
-
})
|
|
28
|
-
socket.setTimeout(3000, () => {
|
|
29
|
-
socket.destroy()
|
|
30
|
-
reject(new Error(`Timed out waiting for http://${host}:${port}`))
|
|
31
|
-
})
|
|
25
|
+
const cleanup = () => { signal?.removeEventListener('abort', aborted); socket.setTimeout(0) }
|
|
26
|
+
const aborted = () => { cleanup(); socket.destroy(); reject(abortError()) }
|
|
27
|
+
signal?.addEventListener('abort', aborted, { once: true })
|
|
28
|
+
socket.once('connect', () => { cleanup(); socket.end(); resolve() })
|
|
29
|
+
socket.once('error', err => { cleanup(); reject(new Error(`Nothing is listening on http://${host}:${port} (${err.message})`)) })
|
|
30
|
+
socket.setTimeout(3000, () => { cleanup(); socket.destroy(); reject(new Error(`Timed out waiting for http://${host}:${port}`)) })
|
|
32
31
|
})
|
|
33
32
|
}
|
|
34
33
|
|
|
35
34
|
/**
|
|
36
35
|
* @param {import('ws').WebSocket} ws
|
|
37
|
-
* @param {string}
|
|
36
|
+
* @param {Record<string, unknown>} message
|
|
38
37
|
* @returns {Promise<Record<string, unknown>>}
|
|
39
38
|
*/
|
|
40
39
|
function waitForMessage(ws, type) {
|
|
41
40
|
return new Promise((resolve, reject) => {
|
|
41
|
+
const timer = setTimeout(() => { cleanup(); reject(new Error('Gateway registration timed out')) }, 10_000)
|
|
42
42
|
/** @param {import('ws').RawData} data */
|
|
43
43
|
const onMessage = (data) => {
|
|
44
44
|
try {
|
|
@@ -50,7 +50,9 @@ function waitForMessage(ws, type) {
|
|
|
50
50
|
}
|
|
51
51
|
if (message.type === 'error') {
|
|
52
52
|
cleanup()
|
|
53
|
-
|
|
53
|
+
const error = new Error(String(message.message ?? 'Gateway error'))
|
|
54
|
+
error.gatewayCode = message.code
|
|
55
|
+
reject(error)
|
|
54
56
|
}
|
|
55
57
|
} catch (err) {
|
|
56
58
|
cleanup()
|
|
@@ -58,9 +60,11 @@ function waitForMessage(ws, type) {
|
|
|
58
60
|
}
|
|
59
61
|
}
|
|
60
62
|
|
|
61
|
-
const onClose = () => {
|
|
63
|
+
const onClose = (code) => {
|
|
62
64
|
cleanup()
|
|
63
|
-
|
|
65
|
+
const error = new Error('Gateway connection closed before tunnel was ready')
|
|
66
|
+
error.closeCode = code
|
|
67
|
+
reject(error)
|
|
64
68
|
}
|
|
65
69
|
|
|
66
70
|
const onError = (err) => {
|
|
@@ -69,6 +73,7 @@ function waitForMessage(ws, type) {
|
|
|
69
73
|
}
|
|
70
74
|
|
|
71
75
|
const cleanup = () => {
|
|
76
|
+
clearTimeout(timer)
|
|
72
77
|
ws.off('message', onMessage)
|
|
73
78
|
ws.off('close', onClose)
|
|
74
79
|
ws.off('error', onError)
|
|
@@ -81,33 +86,145 @@ function waitForMessage(ws, type) {
|
|
|
81
86
|
}
|
|
82
87
|
|
|
83
88
|
/**
|
|
84
|
-
* @param {import('./config.mjs').TunnelOptions & { onRequest?: (info: { method: string, path: string }) => void }} options
|
|
85
|
-
* @returns {Promise<{ url: string, subdomain: string, close: () => Promise<void> }>}
|
|
89
|
+
* @param {import('./config.mjs').TunnelOptions & { signal?: AbortSignal, reconnect?: boolean, reconnectDelayMs?: number, reconnectMaxDelayMs?: number, reconnectJitter?: boolean, onRequest?: (info: { method: string, path: string }) => void, onReconnect?: (info: { url: string, previousUrl: string, subdomain: string, protocolVersion: number, streaming: boolean }) => void }} options
|
|
90
|
+
* @returns {Promise<{ url: string, subdomain: string, streaming: boolean, protocolVersion: number, closed: Promise<unknown>, close: () => Promise<void> }>}
|
|
91
|
+
*
|
|
92
|
+
* Reconnect transient transport failures. Interrupted HTTP requests fail and are
|
|
93
|
+
* never replayed; callers can observe a newly assigned anonymous URL via getters.
|
|
86
94
|
*/
|
|
87
95
|
export async function openTunnel(options) {
|
|
96
|
+
const controller = new AbortController()
|
|
97
|
+
let stopped = false, current, reconnecting, timer, releaseDelay
|
|
98
|
+
let finishClosed
|
|
99
|
+
const closed = new Promise(resolve => { finishClosed = resolve })
|
|
100
|
+
const stop = async () => {
|
|
101
|
+
if (stopped) return
|
|
102
|
+
stopped = true
|
|
103
|
+
clearTimeout(timer)
|
|
104
|
+
releaseDelay?.()
|
|
105
|
+
controller.abort()
|
|
106
|
+
await current?.close()
|
|
107
|
+
await reconnecting
|
|
108
|
+
options.signal?.removeEventListener('abort', externalAbort)
|
|
109
|
+
finishClosed()
|
|
110
|
+
}
|
|
111
|
+
const externalAbort = () => { void stop() }
|
|
112
|
+
if (options.signal?.aborted) throw abortError()
|
|
113
|
+
options.signal?.addEventListener('abort', externalAbort, { once: true })
|
|
114
|
+
try {
|
|
115
|
+
current = await openTunnelConnection({ ...options, signal: controller.signal })
|
|
116
|
+
if (stopped || controller.signal.aborted) { await current.close(); throw abortError() }
|
|
117
|
+
}
|
|
118
|
+
catch (error) { options.signal?.removeEventListener('abort', externalAbort); controller.abort(); throw error }
|
|
119
|
+
const terminal = (detail) => [4000, 4001, 4003, 1002, 1008].includes(detail.code)
|
|
120
|
+
const terminalError = error => [4000, 4001, 4003, 1002, 1008].includes(Number(error.closeCode ?? error.gatewayCode)) || /AUTH|ACCESS_REVOKED|SESSION_EXPIRED|MALFORMED_REGISTER|INVALID_REGISTER|UNSUPPORTED_PROTOCOL/.test(String(error.gatewayCode ?? '')) || /Gateway did not assign|Invalid message|authorization failed|access revoked|Invalid subdomain|Unsupported protocol version|Expected register|Reserved subdomains require|Authenticated tunnels are not configured/i.test(error.message)
|
|
121
|
+
const watch = connection => {
|
|
122
|
+
void connection.closed.then(detail => {
|
|
123
|
+
if (stopped) return
|
|
124
|
+
if (terminal(detail) || options.reconnect === false) { stopped = true; options.signal?.removeEventListener('abort', externalAbort); finishClosed(detail); return }
|
|
125
|
+
const run = reconnect(connection).finally(() => { if (reconnecting === run) reconnecting = null })
|
|
126
|
+
reconnecting = run
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
async function reconnect(previous) {
|
|
130
|
+
if (!options.quiet) console.error('Tunnel disconnected. Reconnecting…')
|
|
131
|
+
let attempt = 0
|
|
132
|
+
while (!stopped) {
|
|
133
|
+
const base = Math.max(1, options.reconnectDelayMs ?? 500)
|
|
134
|
+
const max = Math.max(base, options.reconnectMaxDelayMs ?? 30_000)
|
|
135
|
+
const delay = Math.min(max, base * 2 ** Math.min(attempt++, 10))
|
|
136
|
+
const jitter = options.reconnectJitter === false ? 1 : 0.8 + Math.random() * 0.4
|
|
137
|
+
await new Promise(resolve => { releaseDelay = resolve; timer = setTimeout(resolve, Math.ceil(Math.min(max, delay * jitter))) })
|
|
138
|
+
releaseDelay = null
|
|
139
|
+
if (stopped) break
|
|
140
|
+
try {
|
|
141
|
+
const replacement = await openTunnelConnection({ ...options, signal: controller.signal })
|
|
142
|
+
if (stopped) { await replacement.close(); break }
|
|
143
|
+
current = replacement
|
|
144
|
+
watch(replacement)
|
|
145
|
+
if (options.onReconnect) {
|
|
146
|
+
try {
|
|
147
|
+
void Promise.resolve(options.onReconnect({ url: replacement.url, previousUrl: previous.url, subdomain: replacement.subdomain, protocolVersion: replacement.protocolVersion, streaming: replacement.streaming })).catch(error => console.error(`Reconnect callback failed: ${error.message}`))
|
|
148
|
+
} catch (error) { console.error(`Reconnect callback failed: ${error.message}`) }
|
|
149
|
+
}
|
|
150
|
+
else if (options.quiet) console.log(replacement.url)
|
|
151
|
+
else console.log(`Reconnected. URL: ${replacement.url}`)
|
|
152
|
+
break
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (stopped || error.name === 'AbortError') break
|
|
155
|
+
if (terminalError(error)) {
|
|
156
|
+
stopped = true
|
|
157
|
+
console.error(`Tunnel reconnect stopped: ${error.message}`)
|
|
158
|
+
options.signal?.removeEventListener('abort', externalAbort)
|
|
159
|
+
finishClosed({ error })
|
|
160
|
+
break
|
|
161
|
+
}
|
|
162
|
+
if (!options.quiet) console.error(`Reconnect failed: ${error.message}`)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
watch(current)
|
|
167
|
+
return {
|
|
168
|
+
get url() { return current.url }, get subdomain() { return current.subdomain },
|
|
169
|
+
get expiresAt() { return current.expiresAt }, get protocolVersion() { return current.protocolVersion },
|
|
170
|
+
get streaming() { return current.streaming },
|
|
171
|
+
closed, close: stop,
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function openTunnelConnection(options) {
|
|
88
176
|
const { host, port, subdomain, apiToken, gatewayUrl, tunnelDomain, quiet, onRequest } = options
|
|
177
|
+
/** @type {Map<string, { socket: import('ws').WebSocket, queue: Array<{ data: Buffer, isBinary: boolean }> }>} */
|
|
178
|
+
const localSockets = new Map()
|
|
89
179
|
|
|
90
|
-
|
|
180
|
+
const streams = new Map()
|
|
181
|
+
const protocolVersion = options.protocolVersion ?? PROTOCOL_VERSION
|
|
182
|
+
await waitForLocalPort({ host, port, signal: options.signal })
|
|
91
183
|
|
|
92
|
-
const ws = new WebSocket(gatewayUrl)
|
|
184
|
+
const ws = new WebSocket(gatewayUrl, { maxPayload: MAX_FRAME_BYTES, handshakeTimeout: 10_000 })
|
|
185
|
+
ws.on('error', () => {})
|
|
186
|
+
const closed = new Promise(resolve => ws.once('close', (code, reason) => resolve({ code, reason: reason.toString() })))
|
|
187
|
+
const aborted = () => ws.terminate()
|
|
188
|
+
options.signal?.addEventListener('abort', aborted, { once: true })
|
|
189
|
+
ws.once('close', () => options.signal?.removeEventListener('abort', aborted))
|
|
190
|
+
if (options.signal?.aborted) ws.terminate()
|
|
93
191
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
192
|
+
try {
|
|
193
|
+
await new Promise((resolve, reject) => {
|
|
194
|
+
ws.once('open', resolve)
|
|
195
|
+
ws.once('error', reject)
|
|
196
|
+
ws.once('close', () => reject(options.signal?.aborted ? abortError() : new Error('Gateway connection closed before opening')))
|
|
197
|
+
})
|
|
198
|
+
} catch (error) {
|
|
199
|
+
ws.terminate()
|
|
200
|
+
if (options.signal?.aborted) throw abortError()
|
|
201
|
+
throw error
|
|
202
|
+
}
|
|
98
203
|
|
|
99
204
|
send(ws, {
|
|
100
205
|
type: 'register',
|
|
101
|
-
version:
|
|
206
|
+
version: protocolVersion,
|
|
102
207
|
port,
|
|
103
208
|
host,
|
|
104
209
|
subdomain,
|
|
105
210
|
apiToken,
|
|
106
211
|
})
|
|
107
212
|
|
|
108
|
-
|
|
213
|
+
let registered
|
|
214
|
+
try { registered = await waitForMessage(ws, 'registered') }
|
|
215
|
+
catch (error) {
|
|
216
|
+
ws.terminate()
|
|
217
|
+
if (options.signal?.aborted) throw abortError()
|
|
218
|
+
if (protocolVersion === PROTOCOL_VERSION && /Unsupported protocol version/.test(error.message)) {
|
|
219
|
+
if (!quiet) console.error('Gateway supports legacy v2 only: HTTP bodies remain limited to 1 MiB. Upgrade the gateway for streaming.')
|
|
220
|
+
return openTunnelConnection({ ...options, protocolVersion: LEGACY_PROTOCOL_VERSION })
|
|
221
|
+
}
|
|
222
|
+
throw error
|
|
223
|
+
}
|
|
109
224
|
const assignedSubdomain = String(registered.subdomain ?? '')
|
|
110
|
-
if (!assignedSubdomain) throw new Error('Gateway did not assign a subdomain')
|
|
225
|
+
if (!assignedSubdomain) { ws.terminate(); throw new Error('Gateway did not assign a subdomain') }
|
|
226
|
+
options.signal?.removeEventListener('abort', aborted)
|
|
227
|
+
if (options.signal?.aborted) { ws.terminate(); throw abortError() }
|
|
111
228
|
|
|
112
229
|
const url =
|
|
113
230
|
tunnelDomain.includes(':') || tunnelDomain === 'localhost'
|
|
@@ -115,24 +232,49 @@ export async function openTunnel(options) {
|
|
|
115
232
|
: publicUrl(assignedSubdomain, tunnelDomain)
|
|
116
233
|
|
|
117
234
|
ws.on('message', (data) => {
|
|
118
|
-
void handleGatewayMessage(ws, data, { host, port, quiet, onRequest })
|
|
235
|
+
void handleGatewayMessage(ws, data, { host, port, quiet, onRequest, localSockets, streams, streamIdleTimeoutMs: options.streamIdleTimeoutMs })
|
|
119
236
|
})
|
|
120
237
|
|
|
121
|
-
|
|
122
|
-
|
|
238
|
+
let alive = true
|
|
239
|
+
ws.on('pong', () => { alive = true })
|
|
240
|
+
const heartbeat = setInterval(() => {
|
|
241
|
+
if (!alive) { ws.terminate(); return }
|
|
242
|
+
alive = false
|
|
243
|
+
if (ws.readyState === ws.OPEN) ws.ping()
|
|
244
|
+
}, options.heartbeatIntervalMs ?? 30_000)
|
|
245
|
+
heartbeat.unref()
|
|
246
|
+
|
|
247
|
+
ws.on('close', (code, reason) => {
|
|
248
|
+
clearInterval(heartbeat)
|
|
249
|
+
for (const state of streams.values()) state.channel.cancel(new Error('Gateway connection closed'), false)
|
|
250
|
+
streams.clear()
|
|
251
|
+
for (const connection of localSockets.values()) {
|
|
252
|
+
connection.socket.terminate()
|
|
253
|
+
}
|
|
254
|
+
localSockets.clear()
|
|
255
|
+
if (code === 4001) console.error('\nTunnel session limit reached. Run portpreview again to start a new session.')
|
|
256
|
+
else if (code === 4003) console.error('\nTunnel access revoked. Check your account before restarting.')
|
|
257
|
+
|
|
123
258
|
})
|
|
124
259
|
|
|
125
260
|
return {
|
|
261
|
+
closed,
|
|
126
262
|
url,
|
|
127
263
|
subdomain: assignedSubdomain,
|
|
264
|
+
expiresAt: registered.expiresAt ?? null,
|
|
265
|
+
protocolVersion: registered.version ?? LEGACY_PROTOCOL_VERSION,
|
|
266
|
+
streaming: Boolean(registered.streaming),
|
|
128
267
|
close: async () => {
|
|
129
268
|
await new Promise((resolve) => {
|
|
130
269
|
if (ws.readyState === ws.CLOSED) {
|
|
131
270
|
resolve(undefined)
|
|
132
271
|
return
|
|
133
272
|
}
|
|
134
|
-
ws.
|
|
135
|
-
|
|
273
|
+
const deadline = setTimeout(() => ws.terminate(), 1000)
|
|
274
|
+
deadline.unref()
|
|
275
|
+
ws.once('close', () => { clearTimeout(deadline); resolve() })
|
|
276
|
+
if (ws.readyState === ws.CONNECTING) ws.terminate()
|
|
277
|
+
else ws.close()
|
|
136
278
|
})
|
|
137
279
|
},
|
|
138
280
|
}
|
|
@@ -141,7 +283,13 @@ export async function openTunnel(options) {
|
|
|
141
283
|
/**
|
|
142
284
|
* @param {import('ws').WebSocket} ws
|
|
143
285
|
* @param {import('ws').RawData} data
|
|
144
|
-
* @param {{
|
|
286
|
+
* @param {{
|
|
287
|
+
* host: string,
|
|
288
|
+
* port: number,
|
|
289
|
+
* quiet: boolean,
|
|
290
|
+
* onRequest?: (info: { method: string, path: string }) => void,
|
|
291
|
+
* localSockets: Map<string, { socket: import('ws').WebSocket, queue: Array<{ data: Buffer, isBinary: boolean }> }>,
|
|
292
|
+
* }} ctx
|
|
145
293
|
*/
|
|
146
294
|
async function handleGatewayMessage(ws, data, ctx) {
|
|
147
295
|
let message
|
|
@@ -151,9 +299,61 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
151
299
|
return
|
|
152
300
|
}
|
|
153
301
|
|
|
302
|
+
const id = String(message.id ?? '')
|
|
303
|
+
|
|
304
|
+
if (message.type === 'http_request') {
|
|
305
|
+
try { openLocalHttpStream(ws, message, ctx) }
|
|
306
|
+
catch (error) { sendIfOpen(ws, { type: 'http_cancel', id, reason: error.message }) }
|
|
307
|
+
return
|
|
308
|
+
}
|
|
309
|
+
if (String(message.type).startsWith('http_')) {
|
|
310
|
+
ctx.streams.get(id)?.channel.handle(message)
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (message.type === 'ws_open') {
|
|
315
|
+
openLocalWebSocket(ws, message, ctx)
|
|
316
|
+
return
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (message.type === 'ws_data') {
|
|
320
|
+
const connection = ctx.localSockets.get(id)
|
|
321
|
+
if (!connection) return
|
|
322
|
+
const frame = {
|
|
323
|
+
data: attachedBody(message),
|
|
324
|
+
isBinary: Boolean(message.isBinary),
|
|
325
|
+
}
|
|
326
|
+
if (connection.socket.readyState === connection.socket.OPEN) {
|
|
327
|
+
connection.socket.send(frame.data, { binary: frame.isBinary })
|
|
328
|
+
} else if (connection.socket.readyState === connection.socket.CONNECTING) {
|
|
329
|
+
if (connection.queue.reduce((bytes, queued) => bytes + queued.data.length, frame.data.length) > MAX_BODY_BYTES) {
|
|
330
|
+
connection.socket.terminate()
|
|
331
|
+
ctx.localSockets.delete(id)
|
|
332
|
+
sendIfOpen(ws, { type: 'ws_error', id, reason: 'WebSocket buffer limit reached' })
|
|
333
|
+
return
|
|
334
|
+
}
|
|
335
|
+
connection.queue.push(frame)
|
|
336
|
+
}
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (message.type === 'ws_close') {
|
|
341
|
+
const connection = ctx.localSockets.get(id)
|
|
342
|
+
if (!connection) return
|
|
343
|
+
ctx.localSockets.delete(id)
|
|
344
|
+
const close = () => {
|
|
345
|
+
closeWebSocket(connection.socket, message.code, message.reason)
|
|
346
|
+
}
|
|
347
|
+
if (connection.socket.readyState === connection.socket.CONNECTING) {
|
|
348
|
+
connection.socket.once('open', close)
|
|
349
|
+
} else if (connection.socket.readyState === connection.socket.OPEN) {
|
|
350
|
+
close()
|
|
351
|
+
}
|
|
352
|
+
return
|
|
353
|
+
}
|
|
354
|
+
|
|
154
355
|
if (message.type !== 'request') return
|
|
155
356
|
|
|
156
|
-
const id = String(message.id ?? '')
|
|
157
357
|
const method = String(message.method ?? 'GET').toUpperCase()
|
|
158
358
|
const path = String(message.path ?? '/')
|
|
159
359
|
const headers = /** @type {Record<string, string>} */ (message.headers ?? {})
|
|
@@ -202,6 +402,99 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
202
402
|
}
|
|
203
403
|
}
|
|
204
404
|
|
|
405
|
+
/**
|
|
406
|
+
* @param {import('ws').WebSocket} gateway
|
|
407
|
+
* @param {Record<string, unknown>} message
|
|
408
|
+
* @param {{
|
|
409
|
+
* host: string,
|
|
410
|
+
* port: number,
|
|
411
|
+
* localSockets: Map<string, { socket: import('ws').WebSocket, queue: Array<{ data: Buffer, isBinary: boolean }> }>,
|
|
412
|
+
* }} ctx
|
|
413
|
+
*/
|
|
414
|
+
function openLocalHttpStream(ws, message, ctx) {
|
|
415
|
+
const id = String(message.id ?? '')
|
|
416
|
+
if (!id || ctx.streams.has(id)) return
|
|
417
|
+
const method = String(message.method ?? 'GET').toUpperCase()
|
|
418
|
+
const path = String(message.path ?? '/')
|
|
419
|
+
if (!path.startsWith('/') || path.startsWith('//') || /[\\\r\n\0]/.test(path)) {
|
|
420
|
+
sendIfOpen(ws, { type: 'http_cancel', id, reason: 'Invalid local HTTP path' }); return
|
|
421
|
+
}
|
|
422
|
+
ctx.onRequest?.({ method, path })
|
|
423
|
+
if (!ctx.quiet) console.log(`${method} ${path}`)
|
|
424
|
+
const upstream = http.request({ host: ctx.host, port: ctx.port, method, path, headers: stripHopByHop(message.headers ?? {}) })
|
|
425
|
+
let localSocket
|
|
426
|
+
upstream.once('socket', socket => { localSocket = socket })
|
|
427
|
+
const channel = createHttpStream({
|
|
428
|
+
ws, id, outgoing: 'response', idleTimeoutMs: ctx.streamIdleTimeoutMs ?? 120_000,
|
|
429
|
+
onError: () => { upstream.destroy(); ctx.streams.delete(id) },
|
|
430
|
+
onSentEnd: () => {
|
|
431
|
+
channel.stop(); ctx.streams.delete(id)
|
|
432
|
+
if (!upstream.writableFinished) { upstream.destroy(); localSocket?.destroy() }
|
|
433
|
+
},
|
|
434
|
+
})
|
|
435
|
+
ctx.streams.set(id, { channel, upstream })
|
|
436
|
+
upstream.once('response', (response) => {
|
|
437
|
+
try {
|
|
438
|
+
send(ws, { type: 'http_response', id, status: response.statusCode ?? 502, headers: stripHopByHop(response.headers) })
|
|
439
|
+
channel.setSource(response)
|
|
440
|
+
response.once('aborted', () => channel.cancel(new Error('Local response aborted')))
|
|
441
|
+
} catch (error) { channel.cancel(error) }
|
|
442
|
+
})
|
|
443
|
+
upstream.on('error', error => channel.cancel(error))
|
|
444
|
+
channel.setDestination(upstream)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function openLocalWebSocket(gateway, message, ctx) {
|
|
448
|
+
const id = String(message.id ?? '')
|
|
449
|
+
if (!id || ctx.localSockets.has(id)) return
|
|
450
|
+
|
|
451
|
+
const path = String(message.path ?? '/')
|
|
452
|
+
const headers = /** @type {Record<string, string>} */ (message.headers ?? {})
|
|
453
|
+
const protocol = String(headers['sec-websocket-protocol'] ?? '')
|
|
454
|
+
.split(',')
|
|
455
|
+
.map((protocol) => protocol.trim())
|
|
456
|
+
.find(Boolean)
|
|
457
|
+
const options = { headers: stripWebSocketHeaders(headers), handshakeTimeout: 10_000, maxPayload: MAX_BODY_BYTES }
|
|
458
|
+
if (!path.startsWith('/') || path.startsWith('//') || /[\\\r\n\0]/.test(path)) {
|
|
459
|
+
sendIfOpen(gateway, { type: 'ws_error', id, reason: 'Invalid local WebSocket path' })
|
|
460
|
+
return
|
|
461
|
+
}
|
|
462
|
+
const url = new URL(`ws://${net.isIPv6(ctx.host) ? `[${ctx.host}]` : ctx.host}:${ctx.port}${path}`)
|
|
463
|
+
const local = protocol ? new WebSocket(url, protocol, options) : new WebSocket(url, options)
|
|
464
|
+
const connection = { socket: local, queue: [] }
|
|
465
|
+
ctx.localSockets.set(id, connection)
|
|
466
|
+
|
|
467
|
+
local.on('open', () => {
|
|
468
|
+
for (const frame of connection.queue) {
|
|
469
|
+
local.send(frame.data, { binary: frame.isBinary })
|
|
470
|
+
}
|
|
471
|
+
connection.queue.length = 0
|
|
472
|
+
})
|
|
473
|
+
|
|
474
|
+
local.on('message', (data, isBinary) => {
|
|
475
|
+
sendIfOpen(gateway, { type: 'ws_data', id, isBinary }, Buffer.from(data))
|
|
476
|
+
})
|
|
477
|
+
|
|
478
|
+
local.on('close', (code, reason) => {
|
|
479
|
+
if (ctx.localSockets.get(id)?.socket !== local) return
|
|
480
|
+
ctx.localSockets.delete(id)
|
|
481
|
+
sendIfOpen(gateway, {
|
|
482
|
+
type: 'ws_close',
|
|
483
|
+
id,
|
|
484
|
+
code,
|
|
485
|
+
reason: reason.toString(),
|
|
486
|
+
})
|
|
487
|
+
})
|
|
488
|
+
|
|
489
|
+
local.on('error', (err) => {
|
|
490
|
+
sendIfOpen(gateway, {
|
|
491
|
+
type: 'ws_error',
|
|
492
|
+
id,
|
|
493
|
+
reason: err instanceof Error ? err.message : 'Local WebSocket failed',
|
|
494
|
+
})
|
|
495
|
+
})
|
|
496
|
+
}
|
|
497
|
+
|
|
205
498
|
/**
|
|
206
499
|
* @param {{ host: string, port: number, method: string, path: string, headers: Record<string, string>, body?: Buffer }} req
|
|
207
500
|
*/
|
|
@@ -227,7 +520,7 @@ function forwardToLocal(req) {
|
|
|
227
520
|
status: res.statusCode ?? 502,
|
|
228
521
|
headers: Object.fromEntries(
|
|
229
522
|
Object.entries(res.headers).flatMap(([key, value]) =>
|
|
230
|
-
value === undefined ? [] : [[key,
|
|
523
|
+
value === undefined ? [] : [[key, value]],
|
|
231
524
|
),
|
|
232
525
|
),
|
|
233
526
|
body: Buffer.concat(chunks),
|
|
@@ -248,9 +541,11 @@ function forwardToLocal(req) {
|
|
|
248
541
|
received += chunk.length
|
|
249
542
|
})
|
|
250
543
|
res.on('end', finish)
|
|
544
|
+
res.on('error', reject)
|
|
251
545
|
},
|
|
252
546
|
)
|
|
253
547
|
|
|
548
|
+
upstream.setTimeout(30_000, () => upstream.destroy(new Error('Local request timed out')))
|
|
254
549
|
upstream.on('error', reject)
|
|
255
550
|
if (req.body?.length) upstream.write(req.body)
|
|
256
551
|
upstream.end()
|
|
@@ -265,10 +560,40 @@ function stripHopByHop(headers) {
|
|
|
265
560
|
'proxy-authenticate',
|
|
266
561
|
'proxy-authorization',
|
|
267
562
|
'te',
|
|
563
|
+
'trailer',
|
|
268
564
|
'trailers',
|
|
269
565
|
'transfer-encoding',
|
|
270
566
|
'upgrade',
|
|
271
567
|
'host',
|
|
272
568
|
])
|
|
569
|
+
for (const name of String(headers.connection ?? '').split(',')) blocked.add(name.trim().toLowerCase())
|
|
273
570
|
return Object.fromEntries(Object.entries(headers).filter(([key]) => !blocked.has(key.toLowerCase())))
|
|
274
571
|
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* @param {import('ws').WebSocket} ws
|
|
575
|
+
* @param {Record<string, unknown>} message
|
|
576
|
+
* @param {unknown} [body]
|
|
577
|
+
*/
|
|
578
|
+
function sendIfOpen(ws, message, body) {
|
|
579
|
+
if (ws.readyState === ws.OPEN) send(ws, message, body)
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** @param {Record<string, string>} headers */
|
|
583
|
+
function stripWebSocketHeaders(headers) {
|
|
584
|
+
return Object.fromEntries(
|
|
585
|
+
Object.entries(headers).filter(
|
|
586
|
+
([key]) =>
|
|
587
|
+
![
|
|
588
|
+
'connection',
|
|
589
|
+
'host',
|
|
590
|
+
'sec-websocket-accept',
|
|
591
|
+
'sec-websocket-extensions',
|
|
592
|
+
'sec-websocket-key',
|
|
593
|
+
'sec-websocket-protocol',
|
|
594
|
+
'sec-websocket-version',
|
|
595
|
+
'upgrade',
|
|
596
|
+
].includes(key.toLowerCase()),
|
|
597
|
+
),
|
|
598
|
+
)
|
|
599
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "portpreview",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Instant secure previews for localhost apps — expose a local port through a public HTTPS URL.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.mjs",
|
|
7
7
|
"exports": {
|
|
@@ -10,20 +10,28 @@
|
|
|
10
10
|
"./package.json": "./package.json"
|
|
11
11
|
},
|
|
12
12
|
"bin": {
|
|
13
|
-
"portpreview": "bin/portpreview.mjs"
|
|
13
|
+
"portpreview": "./bin/portpreview.mjs"
|
|
14
14
|
},
|
|
15
15
|
"files": [
|
|
16
16
|
"bin/portpreview.mjs",
|
|
17
|
-
"lib",
|
|
18
|
-
"
|
|
19
|
-
"
|
|
17
|
+
"lib/cli-main.mjs",
|
|
18
|
+
"lib/client-info.mjs",
|
|
19
|
+
"lib/config-cli.mjs",
|
|
20
|
+
"lib/config.mjs",
|
|
21
|
+
"lib/geo.mjs",
|
|
22
|
+
"lib/http-stream.mjs",
|
|
23
|
+
"lib/index.mjs",
|
|
24
|
+
"lib/protocol.mjs",
|
|
25
|
+
"lib/tunnel-client.mjs",
|
|
26
|
+
"lib/user-config.mjs",
|
|
27
|
+
"LICENSE",
|
|
28
|
+
"README.md"
|
|
20
29
|
],
|
|
21
|
-
"publishConfig": {
|
|
22
|
-
"access": "public",
|
|
23
|
-
"registry": "https://registry.npmjs.org/"
|
|
24
|
-
},
|
|
25
30
|
"scripts": {
|
|
26
31
|
"prepublishOnly": "npm test",
|
|
32
|
+
"start": "node bin/portpreview.mjs",
|
|
33
|
+
"gateway": "node bin/gateway.mjs",
|
|
34
|
+
"telegram-daemon": "node bin/telegram-daemon.mjs",
|
|
27
35
|
"test": "node --test test/*.test.mjs"
|
|
28
36
|
},
|
|
29
37
|
"keywords": [
|
|
@@ -32,9 +40,7 @@
|
|
|
32
40
|
"preview",
|
|
33
41
|
"webhook",
|
|
34
42
|
"devtools",
|
|
35
|
-
"cli"
|
|
36
|
-
"ngrok",
|
|
37
|
-
"localtunnel"
|
|
43
|
+
"cli"
|
|
38
44
|
],
|
|
39
45
|
"engines": {
|
|
40
46
|
"node": ">=18"
|
|
@@ -49,6 +55,7 @@
|
|
|
49
55
|
"url": "https://github.com/elemops/portpreview/issues"
|
|
50
56
|
},
|
|
51
57
|
"dependencies": {
|
|
58
|
+
"node-telegram-bot-api": "^1.2.0",
|
|
52
59
|
"ws": "^8.19.0"
|
|
53
60
|
}
|
|
54
61
|
}
|