portpreview 0.0.1 → 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/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2026 ElemOps
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
package/README.md CHANGED
@@ -1,9 +1,127 @@
1
1
  # PortPreview
2
2
 
3
- Instant secure previews for localhost apps.
3
+ Expose a local port through a public HTTPS URL.
4
4
 
5
- ## Usage
5
+ ```bash
6
+ npx portpreview 3000
7
+ ```
8
+
9
+ Connects to the PortPreview gateway and forwards public traffic to `http://127.0.0.1:3000`.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install -g portpreview
15
+ portpreview 3000
16
+ ```
17
+
18
+ Pin a version:
6
19
 
7
20
  ```bash
21
+ npx portpreview@0.1.0 3000
22
+ ```
23
+
24
+ ## Options
25
+
26
+ | Flag | Description |
27
+ |------|-------------|
28
+ | `--host <addr>` | Local address to forward to (default `127.0.0.1`) |
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 |
31
+ | `-q, --quiet` | Print only the public URL |
32
+ | `-h, --help` | Show help |
33
+ | `-v, --version` | Show version |
34
+
35
+ ## Environment
36
+
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_...
8
48
  npx portpreview 3000
9
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.
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):
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
+
117
+ ```bash
118
+ git clone https://github.com/elemops/portpreview.git
119
+ cd portpreview
120
+ npm install
121
+ npm test
122
+ node bin/portpreview.mjs 3000
123
+ ```
124
+
125
+ ## License
126
+
127
+ Apache-2.0
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env node
2
+
3
+ import packageJson from '../package.json' with { type: 'json' }
4
+ import { parseArgs, printHelp } from '../lib/config.mjs'
5
+ import { runConfigCommand } from '../lib/config-cli.mjs'
6
+ import { openTunnel } from '../lib/tunnel-client.mjs'
7
+
8
+ async function main() {
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)
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) => {
74
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
75
+ process.exit(1)
76
+ })
@@ -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 ADDED
@@ -0,0 +1,109 @@
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'
4
+
5
+ export const DEFAULT_TUNNEL_DOMAIN = 'portpreview.dev'
6
+ export const DEFAULT_GATEWAY_URL = 'wss://gateway.portpreview.dev/tunnel'
7
+
8
+ /**
9
+ * @param {string[]=} argv
10
+ * @returns {TunnelOptions | { help: true } | { version: true }}
11
+ */
12
+ export function parseArgs(argv = process.argv.slice(2)) {
13
+ let port
14
+ let host = '127.0.0.1'
15
+ /** @type {string | undefined} */
16
+ let subdomain
17
+ let apiToken = process.env.PORTPREVIEW_TOKEN?.trim() || readStoredToken() || undefined
18
+ let gatewayUrl = process.env.PORTPREVIEW_GATEWAY_URL?.trim() || DEFAULT_GATEWAY_URL
19
+ let tunnelDomain = process.env.PORTPREVIEW_TUNNEL_DOMAIN?.trim() || DEFAULT_TUNNEL_DOMAIN
20
+ let quiet = false
21
+
22
+ for (let i = 0; i < argv.length; i++) {
23
+ const arg = argv[i]
24
+ if (arg === '--help' || arg === '-h') return { help: true }
25
+ if (arg === '--version' || arg === '-v') return { version: true }
26
+ if (arg === '--quiet' || arg === '-q') {
27
+ quiet = true
28
+ continue
29
+ }
30
+ if (arg === '--host') {
31
+ host = argv[++i] ?? fail('--host requires a value')
32
+ continue
33
+ }
34
+ if (arg === '--subdomain') {
35
+ subdomain = argv[++i] ?? fail('--subdomain requires a value')
36
+ continue
37
+ }
38
+ if (arg === '--token') {
39
+ apiToken = argv[++i] ?? fail('--token requires a value')
40
+ continue
41
+ }
42
+ if (arg === '--gateway') {
43
+ gatewayUrl = argv[++i] ?? fail('--gateway requires a value')
44
+ continue
45
+ }
46
+ if (arg === '--domain') {
47
+ tunnelDomain = argv[++i] ?? fail('--domain requires a value')
48
+ continue
49
+ }
50
+ if (arg.startsWith('-')) fail(`Unknown option: ${arg}`)
51
+ if (port !== undefined) fail(`Unexpected argument: ${arg}`)
52
+ port = Number(arg)
53
+ }
54
+
55
+ if (port === undefined) fail('Missing local port. Usage: npx portpreview <port>')
56
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
57
+ fail(`Invalid port: ${argv.find((a) => !a.startsWith('-'))}`)
58
+ }
59
+
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 }
65
+ }
66
+
67
+ export function printHelp() {
68
+ console.log(`PortPreview — expose localhost through a public URL
69
+
70
+ Usage:
71
+ npx portpreview <port> [options]
72
+ npx portpreview config <command>
73
+
74
+ Options:
75
+ --host <addr> Local bind address to forward to (default: 127.0.0.1)
76
+ --subdomain <name> Use a subdomain reserved by your account
77
+ --token <token> Authenticate with a CLI token
78
+ --gateway <url> WebSocket gateway URL (default: ${DEFAULT_GATEWAY_URL})
79
+ --domain <domain> Public tunnel domain (default: ${DEFAULT_TUNNEL_DOMAIN})
80
+ -q, --quiet Minimal output
81
+ -h, --help Show this help
82
+ -v, --version Show version
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
+
89
+ Environment:
90
+ PORTPREVIEW_GATEWAY_URL Override gateway WebSocket URL
91
+ PORTPREVIEW_TUNNEL_DOMAIN Override public tunnel domain
92
+ PORTPREVIEW_TOKEN Authenticate with a CLI token
93
+ PORTPREVIEW_CONFIG Override config file path
94
+
95
+ Examples:
96
+ npx portpreview config set-token pp_live_...
97
+ npx portpreview 3000
98
+ npx portpreview 8080 --subdomain myapp
99
+ npx portpreview 3000 --gateway ws://127.0.0.1:4040/tunnel --domain localhost:4040
100
+ `)
101
+ }
102
+
103
+ /**
104
+ * @param {string} message
105
+ * @returns {never}
106
+ */
107
+ export function fail(message) {
108
+ throw new Error(message)
109
+ }
package/lib/index.mjs ADDED
@@ -0,0 +1,18 @@
1
+ export {
2
+ DEFAULT_GATEWAY_URL,
3
+ DEFAULT_TUNNEL_DOMAIN,
4
+ fail,
5
+ parseArgs,
6
+ printHelp,
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'
17
+ export { openTunnel, waitForLocalPort } from './tunnel-client.mjs'
18
+ export { PROTOCOL_VERSION, publicUrl, MAX_BODY_BYTES } from './protocol.mjs'
@@ -0,0 +1,171 @@
1
+ /** Wire format shared by CLI client and gateway. */
2
+
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
9
+
10
+ /**
11
+ * @param {unknown} value
12
+ * @returns {value is Record<string, unknown>}
13
+ */
14
+ export function isObject(value) {
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
16
+ }
17
+
18
+ /**
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]
37
+ */
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
+ }
48
+ }
49
+
50
+ /**
51
+ * @param {Record<string, unknown>} header
52
+ * @returns {Record<string, unknown>}
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
+ */
130
+ export function parseMessage(data) {
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'))
142
+ if (!isObject(parsed)) throw new Error('Invalid message payload')
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)
152
+ }
153
+
154
+ /**
155
+ * @param {string} subdomain
156
+ * @param {string} tunnelDomain
157
+ */
158
+ export function publicUrl(subdomain, tunnelDomain) {
159
+ return `https://${subdomain}.${tunnelDomain}`
160
+ }
161
+
162
+ /**
163
+ * @param {string} subdomain
164
+ * @param {string} tunnelDomain
165
+ */
166
+ export function localGatewayHttpUrl(subdomain, tunnelDomain) {
167
+ if (tunnelDomain.includes(':')) {
168
+ return `http://${subdomain}.${tunnelDomain}`
169
+ }
170
+ return publicUrl(subdomain, tunnelDomain)
171
+ }
@@ -0,0 +1,274 @@
1
+ import http from 'node:http'
2
+ import net from 'node:net'
3
+ import { WebSocket } from 'ws'
4
+ import {
5
+ attachedBody,
6
+ localGatewayHttpUrl,
7
+ MAX_BODY_BYTES,
8
+ parseMessage,
9
+ publicUrl,
10
+ PROTOCOL_VERSION,
11
+ send,
12
+ } from './protocol.mjs'
13
+
14
+ /**
15
+ * @param {{ host: string, port: number }} options
16
+ * @returns {Promise<void>}
17
+ */
18
+ export function waitForLocalPort({ host, port }) {
19
+ return new Promise((resolve, reject) => {
20
+ const socket = net.connect({ host, port })
21
+ socket.once('connect', () => {
22
+ socket.end()
23
+ resolve()
24
+ })
25
+ socket.once('error', (err) => {
26
+ reject(new Error(`Nothing is listening on http://${host}:${port} (${err.message})`))
27
+ })
28
+ socket.setTimeout(3000, () => {
29
+ socket.destroy()
30
+ reject(new Error(`Timed out waiting for http://${host}:${port}`))
31
+ })
32
+ })
33
+ }
34
+
35
+ /**
36
+ * @param {import('ws').WebSocket} ws
37
+ * @param {string} type
38
+ * @returns {Promise<Record<string, unknown>>}
39
+ */
40
+ function waitForMessage(ws, type) {
41
+ return new Promise((resolve, reject) => {
42
+ /** @param {import('ws').RawData} data */
43
+ const onMessage = (data) => {
44
+ try {
45
+ const message = parseMessage(data)
46
+ if (message.type === type) {
47
+ cleanup()
48
+ resolve(message)
49
+ return
50
+ }
51
+ if (message.type === 'error') {
52
+ cleanup()
53
+ reject(new Error(String(message.message ?? 'Gateway error')))
54
+ }
55
+ } catch (err) {
56
+ cleanup()
57
+ reject(err)
58
+ }
59
+ }
60
+
61
+ const onClose = () => {
62
+ cleanup()
63
+ reject(new Error('Gateway connection closed before tunnel was ready'))
64
+ }
65
+
66
+ const onError = (err) => {
67
+ cleanup()
68
+ reject(err)
69
+ }
70
+
71
+ const cleanup = () => {
72
+ ws.off('message', onMessage)
73
+ ws.off('close', onClose)
74
+ ws.off('error', onError)
75
+ }
76
+
77
+ ws.on('message', onMessage)
78
+ ws.once('close', onClose)
79
+ ws.once('error', onError)
80
+ })
81
+ }
82
+
83
+ /**
84
+ * @param {import('./config.mjs').TunnelOptions & { onRequest?: (info: { method: string, path: string }) => void }} options
85
+ * @returns {Promise<{ url: string, subdomain: string, close: () => Promise<void> }>}
86
+ */
87
+ export async function openTunnel(options) {
88
+ const { host, port, subdomain, apiToken, gatewayUrl, tunnelDomain, quiet, onRequest } = options
89
+
90
+ await waitForLocalPort({ host, port })
91
+
92
+ const ws = new WebSocket(gatewayUrl)
93
+
94
+ await new Promise((resolve, reject) => {
95
+ ws.once('open', resolve)
96
+ ws.once('error', reject)
97
+ })
98
+
99
+ send(ws, {
100
+ type: 'register',
101
+ version: PROTOCOL_VERSION,
102
+ port,
103
+ host,
104
+ subdomain,
105
+ apiToken,
106
+ })
107
+
108
+ const registered = await waitForMessage(ws, 'registered')
109
+ const assignedSubdomain = String(registered.subdomain ?? '')
110
+ if (!assignedSubdomain) throw new Error('Gateway did not assign a subdomain')
111
+
112
+ const url =
113
+ tunnelDomain.includes(':') || tunnelDomain === 'localhost'
114
+ ? localGatewayHttpUrl(assignedSubdomain, tunnelDomain)
115
+ : publicUrl(assignedSubdomain, tunnelDomain)
116
+
117
+ ws.on('message', (data) => {
118
+ void handleGatewayMessage(ws, data, { host, port, quiet, onRequest })
119
+ })
120
+
121
+ ws.on('close', () => {
122
+ if (!quiet) console.log('\nTunnel closed.')
123
+ })
124
+
125
+ return {
126
+ url,
127
+ subdomain: assignedSubdomain,
128
+ close: async () => {
129
+ await new Promise((resolve) => {
130
+ if (ws.readyState === ws.CLOSED) {
131
+ resolve(undefined)
132
+ return
133
+ }
134
+ ws.once('close', resolve)
135
+ ws.close()
136
+ })
137
+ },
138
+ }
139
+ }
140
+
141
+ /**
142
+ * @param {import('ws').WebSocket} ws
143
+ * @param {import('ws').RawData} data
144
+ * @param {{ host: string, port: number, quiet: boolean, onRequest?: (info: { method: string, path: string }) => void }} ctx
145
+ */
146
+ async function handleGatewayMessage(ws, data, ctx) {
147
+ let message
148
+ try {
149
+ message = parseMessage(data)
150
+ } catch {
151
+ return
152
+ }
153
+
154
+ if (message.type !== 'request') return
155
+
156
+ const id = String(message.id ?? '')
157
+ const method = String(message.method ?? 'GET').toUpperCase()
158
+ const path = String(message.path ?? '/')
159
+ const headers = /** @type {Record<string, string>} */ (message.headers ?? {})
160
+ const body = attachedBody(message)
161
+ const requestBody = body.length ? body : undefined
162
+
163
+ ctx.onRequest?.({ method, path })
164
+ if (!ctx.quiet) {
165
+ console.log(`${method} ${path}`)
166
+ }
167
+
168
+ try {
169
+ const response = await forwardToLocal({
170
+ host: ctx.host,
171
+ port: ctx.port,
172
+ method,
173
+ path,
174
+ headers,
175
+ body: requestBody,
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
+ )
191
+ } catch (err) {
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
+ )
202
+ }
203
+ }
204
+
205
+ /**
206
+ * @param {{ host: string, port: number, method: string, path: string, headers: Record<string, string>, body?: Buffer }} req
207
+ */
208
+ function forwardToLocal(req) {
209
+ return new Promise((resolve, reject) => {
210
+ const upstream = http.request(
211
+ {
212
+ host: req.host,
213
+ port: req.port,
214
+ method: req.method,
215
+ path: req.path,
216
+ headers: stripHopByHop(req.headers),
217
+ },
218
+ (res) => {
219
+ const chunks = []
220
+ let received = 0
221
+ let truncated = false
222
+ let settled = false
223
+ const finish = () => {
224
+ if (settled) return
225
+ settled = true
226
+ resolve({
227
+ status: res.statusCode ?? 502,
228
+ headers: Object.fromEntries(
229
+ Object.entries(res.headers).flatMap(([key, value]) =>
230
+ value === undefined ? [] : [[key, Array.isArray(value) ? value.join(', ') : value]],
231
+ ),
232
+ ),
233
+ body: Buffer.concat(chunks),
234
+ truncated,
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
249
+ })
250
+ res.on('end', finish)
251
+ },
252
+ )
253
+
254
+ upstream.on('error', reject)
255
+ if (req.body?.length) upstream.write(req.body)
256
+ upstream.end()
257
+ })
258
+ }
259
+
260
+ /** @param {Record<string, string>} headers */
261
+ function stripHopByHop(headers) {
262
+ const blocked = new Set([
263
+ 'connection',
264
+ 'keep-alive',
265
+ 'proxy-authenticate',
266
+ 'proxy-authorization',
267
+ 'te',
268
+ 'trailers',
269
+ 'transfer-encoding',
270
+ 'upgrade',
271
+ 'host',
272
+ ])
273
+ return Object.fromEntries(Object.entries(headers).filter(([key]) => !blocked.has(key.toLowerCase())))
274
+ }
@@ -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
@@ -1,28 +1,54 @@
1
1
  {
2
2
  "name": "portpreview",
3
- "version": "0.0.1",
4
- "description": "Instant secure previews for localhost apps.",
5
- "main": "index.js",
6
- "type": "commonjs",
3
+ "version": "0.1.1",
4
+ "description": "Expose a local port through a public HTTPS URL — webhook debugging, OAuth callbacks, and dev previews.",
5
+ "type": "module",
6
+ "main": "./lib/index.mjs",
7
+ "exports": {
8
+ ".": "./lib/index.mjs",
9
+ "./protocol": "./lib/protocol.mjs",
10
+ "./package.json": "./package.json"
11
+ },
7
12
  "bin": {
8
- "portpreview": "./bin/portpreview.js"
13
+ "portpreview": "bin/portpreview.mjs"
9
14
  },
10
15
  "files": [
11
- "bin",
16
+ "bin/portpreview.mjs",
17
+ "lib",
12
18
  "README.md",
13
- "index.js",
14
- "package.json"
19
+ "LICENSE"
15
20
  ],
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org/"
24
+ },
25
+ "scripts": {
26
+ "prepublishOnly": "npm test",
27
+ "test": "node --test test/*.test.mjs"
28
+ },
16
29
  "keywords": [
17
30
  "tunnel",
18
31
  "localhost",
19
32
  "preview",
20
33
  "webhook",
21
34
  "devtools",
22
- "cli"
35
+ "cli",
36
+ "ngrok",
37
+ "localtunnel"
23
38
  ],
24
39
  "engines": {
25
40
  "node": ">=18"
26
41
  },
27
- "license": "Apache-2.0"
42
+ "license": "Apache-2.0",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/elemops/portpreview.git"
46
+ },
47
+ "homepage": "https://portpreview.com",
48
+ "bugs": {
49
+ "url": "https://github.com/elemops/portpreview/issues"
50
+ },
51
+ "dependencies": {
52
+ "ws": "^8.19.0"
53
+ }
28
54
  }
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const port = process.argv[2];
4
-
5
- console.log("PortPreview CLI is coming soon.");
6
- console.log("Usage: npx portpreview <port>");
7
- console.log("Example: npx portpreview 3000");
8
- console.log("Website: https://portpreview.com");
9
-
10
- if (port) {
11
- console.log(`Requested local port: ${port}`);
12
- }
package/index.js DELETED
@@ -1,5 +0,0 @@
1
- module.exports = {
2
- name: "portpreview",
3
- description: "Instant secure previews for localhost apps.",
4
- website: "https://portpreview.com"
5
- };