portpreview 0.1.0 → 0.1.1
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 +69 -7
- package/bin/portpreview.mjs +9 -1
- package/lib/config-cli.mjs +65 -0
- package/lib/config.mjs +24 -3
- package/lib/index.mjs +10 -1
- package/lib/protocol.mjs +132 -10
- package/lib/tunnel-client.mjs +65 -19
- package/lib/user-config.mjs +81 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -26,19 +26,72 @@ npx portpreview@0.1.0 3000
|
|
|
26
26
|
| Flag | Description |
|
|
27
27
|
|------|-------------|
|
|
28
28
|
| `--host <addr>` | Local address to forward to (default `127.0.0.1`) |
|
|
29
|
-
| `--subdomain <name>` |
|
|
30
|
-
| `--
|
|
31
|
-
| `--domain <domain>` | Public tunnel domain |
|
|
29
|
+
| `--subdomain <name>` | Use a name you reserved in your dashboard (e.g. `my-project` → `my-project.portpreview.dev`) |
|
|
30
|
+
| `--token <token>` | Authenticate with a CLI token from the dashboard |
|
|
32
31
|
| `-q, --quiet` | Print only the public URL |
|
|
33
32
|
| `-h, --help` | Show help |
|
|
34
33
|
| `-v, --version` | Show version |
|
|
35
34
|
|
|
36
35
|
## Environment
|
|
37
36
|
|
|
38
|
-
| Variable |
|
|
39
|
-
|
|
40
|
-
| `
|
|
41
|
-
| `
|
|
37
|
+
| Variable | Description |
|
|
38
|
+
|----------|-------------|
|
|
39
|
+
| `PORTPREVIEW_TOKEN` | CLI token used for reserved subdomains |
|
|
40
|
+
| `PORTPREVIEW_CONFIG` | Override local config file path |
|
|
41
|
+
|
|
42
|
+
## Persistent token (recommended)
|
|
43
|
+
|
|
44
|
+
Save your CLI token once, like ngrok's `config add-authtoken`:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npx portpreview config set-token pp_live_...
|
|
48
|
+
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
|
+
npx portpreview config check
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Remove the saved token:
|
|
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:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
npx portpreview config set-token pp_live_...
|
|
84
|
+
npx portpreview 3000 --subdomain my-project
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Or keep it in the current shell only:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
export PORTPREVIEW_TOKEN=pp_live_...
|
|
91
|
+
npx portpreview 3000 --subdomain my-project
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Commands without `--subdomain` continue to work anonymously with a random URL.
|
|
42
95
|
|
|
43
96
|
## Programmatic API
|
|
44
97
|
|
|
@@ -52,6 +105,15 @@ await tunnel.close()
|
|
|
52
105
|
|
|
53
106
|
## Development
|
|
54
107
|
|
|
108
|
+
For local gateway development only (not needed for normal use):
|
|
109
|
+
|
|
110
|
+
| Flag / variable | Default | Purpose |
|
|
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` |
|
|
116
|
+
|
|
55
117
|
```bash
|
|
56
118
|
git clone https://github.com/elemops/portpreview.git
|
|
57
119
|
cd portpreview
|
package/bin/portpreview.mjs
CHANGED
|
@@ -2,10 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
import packageJson from '../package.json' with { type: 'json' }
|
|
4
4
|
import { parseArgs, printHelp } from '../lib/config.mjs'
|
|
5
|
+
import { runConfigCommand } from '../lib/config-cli.mjs'
|
|
5
6
|
import { openTunnel } from '../lib/tunnel-client.mjs'
|
|
6
7
|
|
|
7
8
|
async function main() {
|
|
8
|
-
const
|
|
9
|
+
const argv = process.argv.slice(2)
|
|
10
|
+
|
|
11
|
+
if (argv[0] === 'config') {
|
|
12
|
+
runConfigCommand(argv.slice(1))
|
|
13
|
+
return
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const parsed = parseArgs(argv)
|
|
9
17
|
|
|
10
18
|
if ('help' in parsed) {
|
|
11
19
|
printHelp()
|
|
@@ -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
|
|
@@ -50,7 +57,11 @@ export function parseArgs(argv = process.argv.slice(2)) {
|
|
|
50
57
|
fail(`Invalid port: ${argv.find((a) => !a.startsWith('-'))}`)
|
|
51
58
|
}
|
|
52
59
|
|
|
53
|
-
|
|
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() {
|
|
@@ -58,21 +69,31 @@ export function printHelp() {
|
|
|
58
69
|
|
|
59
70
|
Usage:
|
|
60
71
|
npx portpreview <port> [options]
|
|
72
|
+
npx 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>
|
|
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
|
+
npx portpreview config set-token <token> Save token locally (recommended)
|
|
86
|
+
npx portpreview config check Show config file location
|
|
87
|
+
npx 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:
|
|
96
|
+
npx portpreview config set-token pp_live_...
|
|
76
97
|
npx portpreview 3000
|
|
77
98
|
npx portpreview 8080 --subdomain myapp
|
|
78
99
|
npx portpreview 3000 --gateway ws://127.0.0.1:4040/tunnel --domain localhost:4040
|
package/lib/index.mjs
CHANGED
|
@@ -5,5 +5,14 @@ export {
|
|
|
5
5
|
parseArgs,
|
|
6
6
|
printHelp,
|
|
7
7
|
} from './config.mjs'
|
|
8
|
+
export { printConfigHelp, runConfigCommand } from './config-cli.mjs'
|
|
9
|
+
export {
|
|
10
|
+
assertValidToken,
|
|
11
|
+
clearStoredToken,
|
|
12
|
+
defaultConfigPath,
|
|
13
|
+
readStoredToken,
|
|
14
|
+
readUserConfig,
|
|
15
|
+
saveToken,
|
|
16
|
+
} from './user-config.mjs'
|
|
8
17
|
export { openTunnel, waitForLocalPort } from './tunnel-client.mjs'
|
|
9
|
-
export { PROTOCOL_VERSION, publicUrl } from './protocol.mjs'
|
|
18
|
+
export { PROTOCOL_VERSION, publicUrl, MAX_BODY_BYTES } from './protocol.mjs'
|
package/lib/protocol.mjs
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Wire format shared by CLI client and gateway. */
|
|
2
2
|
|
|
3
|
-
export const PROTOCOL_VERSION =
|
|
3
|
+
export const PROTOCOL_VERSION = 2
|
|
4
|
+
|
|
5
|
+
/** Hard cap for attached HTTP / WebSocket payloads. Oversized bodies are truncated. */
|
|
6
|
+
export const MAX_BODY_BYTES = 1024 * 1024
|
|
7
|
+
export const MAX_HEADER_BYTES = 256 * 1024
|
|
8
|
+
export const MAX_FRAME_BYTES = 4 + MAX_HEADER_BYTES + MAX_BODY_BYTES
|
|
4
9
|
|
|
5
10
|
/**
|
|
6
11
|
* @param {unknown} value
|
|
@@ -11,22 +16,139 @@ export function isObject(value) {
|
|
|
11
16
|
}
|
|
12
17
|
|
|
13
18
|
/**
|
|
14
|
-
* @param {
|
|
15
|
-
* @
|
|
19
|
+
* @param {unknown} data
|
|
20
|
+
* @returns {Buffer}
|
|
21
|
+
*/
|
|
22
|
+
export function toBuffer(data) {
|
|
23
|
+
if (data == null) return Buffer.alloc(0)
|
|
24
|
+
if (Buffer.isBuffer(data)) return data
|
|
25
|
+
if (typeof data === 'string') return Buffer.from(data)
|
|
26
|
+
if (data instanceof ArrayBuffer) return Buffer.from(data)
|
|
27
|
+
if (ArrayBuffer.isView(data)) {
|
|
28
|
+
return Buffer.from(data.buffer, data.byteOffset, data.byteLength)
|
|
29
|
+
}
|
|
30
|
+
if (Array.isArray(data)) return Buffer.concat(data.map((part) => toBuffer(part)))
|
|
31
|
+
return Buffer.from(data)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {unknown} value
|
|
36
|
+
* @param {number} [maxBytes]
|
|
16
37
|
*/
|
|
17
|
-
export function
|
|
18
|
-
|
|
38
|
+
export function clipBody(value, maxBytes = MAX_BODY_BYTES) {
|
|
39
|
+
const body = toBuffer(value)
|
|
40
|
+
if (body.length <= maxBytes) {
|
|
41
|
+
return { body, truncated: false, originalLength: body.length }
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
body: body.subarray(0, maxBytes),
|
|
45
|
+
truncated: true,
|
|
46
|
+
originalLength: body.length,
|
|
47
|
+
}
|
|
19
48
|
}
|
|
20
49
|
|
|
21
50
|
/**
|
|
22
|
-
* @param {string
|
|
51
|
+
* @param {Record<string, unknown>} header
|
|
23
52
|
* @returns {Record<string, unknown>}
|
|
24
53
|
*/
|
|
54
|
+
function stripAttachedFields(header) {
|
|
55
|
+
const { body: _body, data: _data, ...rest } = header
|
|
56
|
+
return rest
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {Record<string, unknown>} headers
|
|
61
|
+
* @param {number} length
|
|
62
|
+
* @param {boolean} truncated
|
|
63
|
+
* @returns {Record<string, unknown>}
|
|
64
|
+
*/
|
|
65
|
+
function withBodyHeaders(headers, length, truncated) {
|
|
66
|
+
/** @type {Record<string, unknown>} */
|
|
67
|
+
const next = {}
|
|
68
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
69
|
+
const name = key.toLowerCase()
|
|
70
|
+
if (name === 'content-length' || name === 'transfer-encoding') continue
|
|
71
|
+
next[key] = value
|
|
72
|
+
}
|
|
73
|
+
next['content-length'] = String(length)
|
|
74
|
+
if (truncated) next['x-portpreview-truncated'] = '1'
|
|
75
|
+
return next
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Length-prefixed binary frame: [uint32be jsonLen][utf8 json][raw body].
|
|
80
|
+
* JSON holds control fields only; the body is never base64.
|
|
81
|
+
*
|
|
82
|
+
* @param {Record<string, unknown>} header
|
|
83
|
+
* @param {unknown} [body]
|
|
84
|
+
*/
|
|
85
|
+
export function encodeFrame(header, body) {
|
|
86
|
+
const clipped = clipBody(body)
|
|
87
|
+
const payload = stripAttachedFields(header)
|
|
88
|
+
const truncated = Boolean(payload.truncated) || clipped.truncated
|
|
89
|
+
if (truncated) {
|
|
90
|
+
payload.truncated = true
|
|
91
|
+
payload.originalLength = Number(payload.originalLength ?? clipped.originalLength)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (
|
|
95
|
+
(payload.type === 'request' || payload.type === 'response') &&
|
|
96
|
+
isObject(payload.headers)
|
|
97
|
+
) {
|
|
98
|
+
payload.headers = withBodyHeaders(
|
|
99
|
+
/** @type {Record<string, unknown>} */ (payload.headers),
|
|
100
|
+
clipped.body.length,
|
|
101
|
+
truncated,
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const headerBuf = Buffer.from(JSON.stringify(payload), 'utf8')
|
|
106
|
+
if (headerBuf.length > MAX_HEADER_BYTES) {
|
|
107
|
+
throw new Error('Control header too large')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const frame = Buffer.allocUnsafe(4 + headerBuf.length + clipped.body.length)
|
|
111
|
+
frame.writeUInt32BE(headerBuf.length, 0)
|
|
112
|
+
headerBuf.copy(frame, 4)
|
|
113
|
+
clipped.body.copy(frame, 4 + headerBuf.length)
|
|
114
|
+
return frame
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* @param {import('ws').WebSocket} ws
|
|
119
|
+
* @param {Record<string, unknown>} header
|
|
120
|
+
* @param {unknown} [body]
|
|
121
|
+
*/
|
|
122
|
+
export function send(ws, header, body) {
|
|
123
|
+
ws.send(encodeFrame(header, body), { binary: true })
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @param {unknown} data
|
|
128
|
+
* @returns {Record<string, unknown> & { body: Buffer }}
|
|
129
|
+
*/
|
|
25
130
|
export function parseMessage(data) {
|
|
26
|
-
const
|
|
27
|
-
|
|
131
|
+
const buf = toBuffer(data)
|
|
132
|
+
if (buf.length < 4 || buf[0] === 0x7b) {
|
|
133
|
+
throw new Error('Invalid message payload')
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const headerLen = buf.readUInt32BE(0)
|
|
137
|
+
if (headerLen < 2 || headerLen > MAX_HEADER_BYTES || 4 + headerLen > buf.length) {
|
|
138
|
+
throw new Error('Invalid message header')
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const parsed = JSON.parse(buf.subarray(4, 4 + headerLen).toString('utf8'))
|
|
28
142
|
if (!isObject(parsed)) throw new Error('Invalid message payload')
|
|
29
|
-
|
|
143
|
+
parsed.body = buf.subarray(4 + headerLen)
|
|
144
|
+
return /** @type {Record<string, unknown> & { body: Buffer }} */ (parsed)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* @param {Record<string, unknown>} message
|
|
149
|
+
*/
|
|
150
|
+
export function attachedBody(message) {
|
|
151
|
+
return Buffer.isBuffer(message.body) ? message.body : Buffer.alloc(0)
|
|
30
152
|
}
|
|
31
153
|
|
|
32
154
|
/**
|
package/lib/tunnel-client.mjs
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
import http from 'node:http'
|
|
2
2
|
import net from 'node:net'
|
|
3
3
|
import { WebSocket } from 'ws'
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
attachedBody,
|
|
6
|
+
localGatewayHttpUrl,
|
|
7
|
+
MAX_BODY_BYTES,
|
|
8
|
+
parseMessage,
|
|
9
|
+
publicUrl,
|
|
10
|
+
PROTOCOL_VERSION,
|
|
11
|
+
send,
|
|
12
|
+
} from './protocol.mjs'
|
|
5
13
|
|
|
6
14
|
/**
|
|
7
15
|
* @param {{ host: string, port: number }} options
|
|
@@ -77,7 +85,7 @@ function waitForMessage(ws, type) {
|
|
|
77
85
|
* @returns {Promise<{ url: string, subdomain: string, close: () => Promise<void> }>}
|
|
78
86
|
*/
|
|
79
87
|
export async function openTunnel(options) {
|
|
80
|
-
const { host, port, subdomain, gatewayUrl, tunnelDomain, quiet, onRequest } = options
|
|
88
|
+
const { host, port, subdomain, apiToken, gatewayUrl, tunnelDomain, quiet, onRequest } = options
|
|
81
89
|
|
|
82
90
|
await waitForLocalPort({ host, port })
|
|
83
91
|
|
|
@@ -94,6 +102,7 @@ export async function openTunnel(options) {
|
|
|
94
102
|
port,
|
|
95
103
|
host,
|
|
96
104
|
subdomain,
|
|
105
|
+
apiToken,
|
|
97
106
|
})
|
|
98
107
|
|
|
99
108
|
const registered = await waitForMessage(ws, 'registered')
|
|
@@ -148,7 +157,8 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
148
157
|
const method = String(message.method ?? 'GET').toUpperCase()
|
|
149
158
|
const path = String(message.path ?? '/')
|
|
150
159
|
const headers = /** @type {Record<string, string>} */ (message.headers ?? {})
|
|
151
|
-
const body =
|
|
160
|
+
const body = attachedBody(message)
|
|
161
|
+
const requestBody = body.length ? body : undefined
|
|
152
162
|
|
|
153
163
|
ctx.onRequest?.({ method, path })
|
|
154
164
|
if (!ctx.quiet) {
|
|
@@ -156,22 +166,39 @@ async function handleGatewayMessage(ws, data, ctx) {
|
|
|
156
166
|
}
|
|
157
167
|
|
|
158
168
|
try {
|
|
159
|
-
const response = await forwardToLocal({
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
headers
|
|
165
|
-
body:
|
|
169
|
+
const response = await forwardToLocal({
|
|
170
|
+
host: ctx.host,
|
|
171
|
+
port: ctx.port,
|
|
172
|
+
method,
|
|
173
|
+
path,
|
|
174
|
+
headers,
|
|
175
|
+
body: requestBody,
|
|
166
176
|
})
|
|
177
|
+
if (!ctx.quiet && response.truncated) {
|
|
178
|
+
console.log(`${method} ${path} (truncated to 1MB)`)
|
|
179
|
+
}
|
|
180
|
+
send(
|
|
181
|
+
ws,
|
|
182
|
+
{
|
|
183
|
+
type: 'response',
|
|
184
|
+
id,
|
|
185
|
+
status: response.status,
|
|
186
|
+
headers: response.headers,
|
|
187
|
+
truncated: response.truncated || undefined,
|
|
188
|
+
},
|
|
189
|
+
response.body,
|
|
190
|
+
)
|
|
167
191
|
} catch (err) {
|
|
168
|
-
send(
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
192
|
+
send(
|
|
193
|
+
ws,
|
|
194
|
+
{
|
|
195
|
+
type: 'response',
|
|
196
|
+
id,
|
|
197
|
+
status: 502,
|
|
198
|
+
headers: { 'content-type': 'text/plain' },
|
|
199
|
+
},
|
|
200
|
+
Buffer.from(String(err instanceof Error ? err.message : err)),
|
|
201
|
+
)
|
|
175
202
|
}
|
|
176
203
|
}
|
|
177
204
|
|
|
@@ -190,8 +217,12 @@ function forwardToLocal(req) {
|
|
|
190
217
|
},
|
|
191
218
|
(res) => {
|
|
192
219
|
const chunks = []
|
|
193
|
-
|
|
194
|
-
|
|
220
|
+
let received = 0
|
|
221
|
+
let truncated = false
|
|
222
|
+
let settled = false
|
|
223
|
+
const finish = () => {
|
|
224
|
+
if (settled) return
|
|
225
|
+
settled = true
|
|
195
226
|
resolve({
|
|
196
227
|
status: res.statusCode ?? 502,
|
|
197
228
|
headers: Object.fromEntries(
|
|
@@ -200,8 +231,23 @@ function forwardToLocal(req) {
|
|
|
200
231
|
),
|
|
201
232
|
),
|
|
202
233
|
body: Buffer.concat(chunks),
|
|
234
|
+
truncated,
|
|
203
235
|
})
|
|
236
|
+
}
|
|
237
|
+
res.on('data', (chunk) => {
|
|
238
|
+
if (settled) return
|
|
239
|
+
if (received + chunk.length > MAX_BODY_BYTES) {
|
|
240
|
+
chunks.push(chunk.subarray(0, MAX_BODY_BYTES - received))
|
|
241
|
+
received = MAX_BODY_BYTES
|
|
242
|
+
truncated = true
|
|
243
|
+
finish()
|
|
244
|
+
res.destroy()
|
|
245
|
+
return
|
|
246
|
+
}
|
|
247
|
+
chunks.push(chunk)
|
|
248
|
+
received += chunk.length
|
|
204
249
|
})
|
|
250
|
+
res.on('end', finish)
|
|
205
251
|
},
|
|
206
252
|
)
|
|
207
253
|
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync, chmodSync, unlinkSync, existsSync } from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
const TOKEN_PREFIX = 'pp_live_'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @returns {string}
|
|
9
|
+
*/
|
|
10
|
+
export function defaultConfigPath() {
|
|
11
|
+
if (process.env.PORTPREVIEW_CONFIG?.trim()) {
|
|
12
|
+
return process.env.PORTPREVIEW_CONFIG.trim()
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const home = os.homedir()
|
|
16
|
+
|
|
17
|
+
if (process.platform === 'win32') {
|
|
18
|
+
const localAppData = process.env.LOCALAPPDATA ?? path.join(home, 'AppData', 'Local')
|
|
19
|
+
return path.join(localAppData, 'portpreview', 'config.json')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (process.platform === 'darwin') {
|
|
23
|
+
return path.join(home, 'Library', 'Application Support', 'portpreview', 'config.json')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return path.join(home, '.config', 'portpreview', 'config.json')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {string} token
|
|
31
|
+
*/
|
|
32
|
+
export function assertValidToken(token) {
|
|
33
|
+
const value = token.trim()
|
|
34
|
+
if (!value.startsWith(TOKEN_PREFIX) || value.length < 40 || value.length > 100) {
|
|
35
|
+
throw new Error('Invalid token. Copy the CLI token from your PortPreview dashboard.')
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @returns {{ token?: string }}
|
|
41
|
+
*/
|
|
42
|
+
export function readUserConfig() {
|
|
43
|
+
const configPath = defaultConfigPath()
|
|
44
|
+
if (!existsSync(configPath)) return {}
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
const parsed = JSON.parse(readFileSync(configPath, 'utf8'))
|
|
48
|
+
if (typeof parsed?.token !== 'string') return {}
|
|
49
|
+
const token = parsed.token.trim()
|
|
50
|
+
return token ? { token } : {}
|
|
51
|
+
} catch {
|
|
52
|
+
return {}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @returns {string | undefined}
|
|
58
|
+
*/
|
|
59
|
+
export function readStoredToken() {
|
|
60
|
+
return readUserConfig().token
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @param {string} token
|
|
65
|
+
*/
|
|
66
|
+
export function saveToken(token) {
|
|
67
|
+
assertValidToken(token)
|
|
68
|
+
const configPath = defaultConfigPath()
|
|
69
|
+
mkdirSync(path.dirname(configPath), { recursive: true, mode: 0o700 })
|
|
70
|
+
|
|
71
|
+
const payload = `${JSON.stringify({ token: token.trim() }, null, 2)}\n`
|
|
72
|
+
writeFileSync(configPath, payload, { encoding: 'utf8', mode: 0o600 })
|
|
73
|
+
chmodSync(configPath, 0o600)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function clearStoredToken() {
|
|
77
|
+
const configPath = defaultConfigPath()
|
|
78
|
+
if (!existsSync(configPath)) return false
|
|
79
|
+
unlinkSync(configPath)
|
|
80
|
+
return true
|
|
81
|
+
}
|
package/package.json
CHANGED