portpreview 0.0.1 → 0.1.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/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,65 @@
1
1
  # PortPreview
2
2
 
3
- Instant secure previews for localhost apps.
4
-
5
- ## Usage
3
+ Expose a local port through a public HTTPS URL.
6
4
 
7
5
  ```bash
8
6
  npx portpreview 3000
9
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:
19
+
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>` | Request a specific subdomain |
30
+ | `--gateway <url>` | WebSocket gateway URL |
31
+ | `--domain <domain>` | Public tunnel domain |
32
+ | `-q, --quiet` | Print only the public URL |
33
+ | `-h, --help` | Show help |
34
+ | `-v, --version` | Show version |
35
+
36
+ ## Environment
37
+
38
+ | Variable | Default |
39
+ |----------|---------|
40
+ | `PORTPREVIEW_GATEWAY_URL` | `wss://gateway.portpreview.dev/tunnel` |
41
+ | `PORTPREVIEW_TUNNEL_DOMAIN` | `portpreview.dev` |
42
+
43
+ ## Programmatic API
44
+
45
+ ```javascript
46
+ import { openTunnel } from 'portpreview'
47
+
48
+ const tunnel = await openTunnel({ port: 3000, quiet: true })
49
+ console.log(tunnel.url)
50
+ await tunnel.close()
51
+ ```
52
+
53
+ ## Development
54
+
55
+ ```bash
56
+ git clone https://github.com/elemops/portpreview.git
57
+ cd portpreview
58
+ npm install
59
+ npm test
60
+ node bin/portpreview.mjs 3000
61
+ ```
62
+
63
+ ## License
64
+
65
+ Apache-2.0
@@ -0,0 +1,68 @@
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 { openTunnel } from '../lib/tunnel-client.mjs'
6
+
7
+ async function main() {
8
+ const parsed = parseArgs()
9
+
10
+ if ('help' in parsed) {
11
+ printHelp()
12
+ return
13
+ }
14
+
15
+ if ('version' in parsed) {
16
+ console.log(packageJson.version)
17
+ return
18
+ }
19
+
20
+ const target = `http://${parsed.host}:${parsed.port}`
21
+
22
+ if (!parsed.quiet) {
23
+ console.log('Connecting to gateway…')
24
+ console.log(`Forwarding ${target}`)
25
+ }
26
+
27
+ let tunnel
28
+ try {
29
+ tunnel = await openTunnel(parsed)
30
+ } catch (err) {
31
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
32
+ process.exit(1)
33
+ }
34
+
35
+ if (!parsed.quiet) {
36
+ console.log('Connected')
37
+ console.log(`URL: ${tunnel.url}`)
38
+ console.log(`Target: ${target}`)
39
+ console.log('Press Ctrl+C to stop.')
40
+ } else {
41
+ console.log(tunnel.url)
42
+ }
43
+
44
+ let shuttingDown = false
45
+ const shutdown = () => {
46
+ if (shuttingDown) {
47
+ process.exit(1)
48
+ return
49
+ }
50
+ shuttingDown = true
51
+
52
+ tunnel
53
+ .close()
54
+ .then(() => process.exit(0))
55
+ .catch((err) => {
56
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
57
+ process.exit(1)
58
+ })
59
+ }
60
+
61
+ process.on('SIGINT', shutdown)
62
+ process.on('SIGTERM', shutdown)
63
+ }
64
+
65
+ main().catch((err) => {
66
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`)
67
+ process.exit(1)
68
+ })
package/lib/config.mjs ADDED
@@ -0,0 +1,88 @@
1
+ /** @typedef {{ port: number, host: string, subdomain?: string, gatewayUrl: string, tunnelDomain: string, quiet: boolean }} TunnelOptions */
2
+
3
+ export const DEFAULT_TUNNEL_DOMAIN = 'portpreview.dev'
4
+ export const DEFAULT_GATEWAY_URL = 'wss://gateway.portpreview.dev/tunnel'
5
+
6
+ /**
7
+ * @param {string[]=} argv
8
+ * @returns {TunnelOptions | { help: true } | { version: true }}
9
+ */
10
+ export function parseArgs(argv = process.argv.slice(2)) {
11
+ let port
12
+ let host = '127.0.0.1'
13
+ /** @type {string | undefined} */
14
+ let subdomain
15
+ let gatewayUrl = process.env.PORTPREVIEW_GATEWAY_URL?.trim() || DEFAULT_GATEWAY_URL
16
+ let tunnelDomain = process.env.PORTPREVIEW_TUNNEL_DOMAIN?.trim() || DEFAULT_TUNNEL_DOMAIN
17
+ let quiet = false
18
+
19
+ for (let i = 0; i < argv.length; i++) {
20
+ const arg = argv[i]
21
+ if (arg === '--help' || arg === '-h') return { help: true }
22
+ if (arg === '--version' || arg === '-v') return { version: true }
23
+ if (arg === '--quiet' || arg === '-q') {
24
+ quiet = true
25
+ continue
26
+ }
27
+ if (arg === '--host') {
28
+ host = argv[++i] ?? fail('--host requires a value')
29
+ continue
30
+ }
31
+ if (arg === '--subdomain') {
32
+ subdomain = argv[++i] ?? fail('--subdomain requires a value')
33
+ continue
34
+ }
35
+ if (arg === '--gateway') {
36
+ gatewayUrl = argv[++i] ?? fail('--gateway requires a value')
37
+ continue
38
+ }
39
+ if (arg === '--domain') {
40
+ tunnelDomain = argv[++i] ?? fail('--domain requires a value')
41
+ continue
42
+ }
43
+ if (arg.startsWith('-')) fail(`Unknown option: ${arg}`)
44
+ if (port !== undefined) fail(`Unexpected argument: ${arg}`)
45
+ port = Number(arg)
46
+ }
47
+
48
+ if (port === undefined) fail('Missing local port. Usage: npx portpreview <port>')
49
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
50
+ fail(`Invalid port: ${argv.find((a) => !a.startsWith('-'))}`)
51
+ }
52
+
53
+ return { port, host, subdomain, gatewayUrl, tunnelDomain, quiet }
54
+ }
55
+
56
+ export function printHelp() {
57
+ console.log(`PortPreview — expose localhost through a public URL
58
+
59
+ Usage:
60
+ npx portpreview <port> [options]
61
+
62
+ Options:
63
+ --host <addr> Local bind address to forward to (default: 127.0.0.1)
64
+ --subdomain <name> Request a specific subdomain (when available)
65
+ --gateway <url> WebSocket gateway URL (default: ${DEFAULT_GATEWAY_URL})
66
+ --domain <domain> Public tunnel domain (default: ${DEFAULT_TUNNEL_DOMAIN})
67
+ -q, --quiet Minimal output
68
+ -h, --help Show this help
69
+ -v, --version Show version
70
+
71
+ Environment:
72
+ PORTPREVIEW_GATEWAY_URL Override gateway WebSocket URL
73
+ PORTPREVIEW_TUNNEL_DOMAIN Override public tunnel domain
74
+
75
+ Examples:
76
+ npx portpreview 3000
77
+ npx portpreview 8080 --subdomain myapp
78
+ npx portpreview 3000 --gateway ws://127.0.0.1:4040/tunnel --domain localhost:4040
79
+ `)
80
+ }
81
+
82
+ /**
83
+ * @param {string} message
84
+ * @returns {never}
85
+ */
86
+ export function fail(message) {
87
+ throw new Error(message)
88
+ }
package/lib/index.mjs ADDED
@@ -0,0 +1,9 @@
1
+ export {
2
+ DEFAULT_GATEWAY_URL,
3
+ DEFAULT_TUNNEL_DOMAIN,
4
+ fail,
5
+ parseArgs,
6
+ printHelp,
7
+ } from './config.mjs'
8
+ export { openTunnel, waitForLocalPort } from './tunnel-client.mjs'
9
+ export { PROTOCOL_VERSION, publicUrl } from './protocol.mjs'
@@ -0,0 +1,49 @@
1
+ /** JSON wire format between the CLI client and the gateway. */
2
+
3
+ export const PROTOCOL_VERSION = 1
4
+
5
+ /**
6
+ * @param {unknown} value
7
+ * @returns {value is Record<string, unknown>}
8
+ */
9
+ export function isObject(value) {
10
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
11
+ }
12
+
13
+ /**
14
+ * @param {import('ws').WebSocket} ws
15
+ * @param {Record<string, unknown>} message
16
+ */
17
+ export function send(ws, message) {
18
+ ws.send(JSON.stringify(message))
19
+ }
20
+
21
+ /**
22
+ * @param {string | Buffer | ArrayBuffer} data
23
+ * @returns {Record<string, unknown>}
24
+ */
25
+ export function parseMessage(data) {
26
+ const text = typeof data === 'string' ? data : Buffer.from(data).toString('utf8')
27
+ const parsed = JSON.parse(text)
28
+ if (!isObject(parsed)) throw new Error('Invalid message payload')
29
+ return parsed
30
+ }
31
+
32
+ /**
33
+ * @param {string} subdomain
34
+ * @param {string} tunnelDomain
35
+ */
36
+ export function publicUrl(subdomain, tunnelDomain) {
37
+ return `https://${subdomain}.${tunnelDomain}`
38
+ }
39
+
40
+ /**
41
+ * @param {string} subdomain
42
+ * @param {string} tunnelDomain
43
+ */
44
+ export function localGatewayHttpUrl(subdomain, tunnelDomain) {
45
+ if (tunnelDomain.includes(':')) {
46
+ return `http://${subdomain}.${tunnelDomain}`
47
+ }
48
+ return publicUrl(subdomain, tunnelDomain)
49
+ }
@@ -0,0 +1,228 @@
1
+ import http from 'node:http'
2
+ import net from 'node:net'
3
+ import { WebSocket } from 'ws'
4
+ import { localGatewayHttpUrl, parseMessage, publicUrl, PROTOCOL_VERSION, send } from './protocol.mjs'
5
+
6
+ /**
7
+ * @param {{ host: string, port: number }} options
8
+ * @returns {Promise<void>}
9
+ */
10
+ export function waitForLocalPort({ host, port }) {
11
+ return new Promise((resolve, reject) => {
12
+ const socket = net.connect({ host, port })
13
+ socket.once('connect', () => {
14
+ socket.end()
15
+ resolve()
16
+ })
17
+ socket.once('error', (err) => {
18
+ reject(new Error(`Nothing is listening on http://${host}:${port} (${err.message})`))
19
+ })
20
+ socket.setTimeout(3000, () => {
21
+ socket.destroy()
22
+ reject(new Error(`Timed out waiting for http://${host}:${port}`))
23
+ })
24
+ })
25
+ }
26
+
27
+ /**
28
+ * @param {import('ws').WebSocket} ws
29
+ * @param {string} type
30
+ * @returns {Promise<Record<string, unknown>>}
31
+ */
32
+ function waitForMessage(ws, type) {
33
+ return new Promise((resolve, reject) => {
34
+ /** @param {import('ws').RawData} data */
35
+ const onMessage = (data) => {
36
+ try {
37
+ const message = parseMessage(data)
38
+ if (message.type === type) {
39
+ cleanup()
40
+ resolve(message)
41
+ return
42
+ }
43
+ if (message.type === 'error') {
44
+ cleanup()
45
+ reject(new Error(String(message.message ?? 'Gateway error')))
46
+ }
47
+ } catch (err) {
48
+ cleanup()
49
+ reject(err)
50
+ }
51
+ }
52
+
53
+ const onClose = () => {
54
+ cleanup()
55
+ reject(new Error('Gateway connection closed before tunnel was ready'))
56
+ }
57
+
58
+ const onError = (err) => {
59
+ cleanup()
60
+ reject(err)
61
+ }
62
+
63
+ const cleanup = () => {
64
+ ws.off('message', onMessage)
65
+ ws.off('close', onClose)
66
+ ws.off('error', onError)
67
+ }
68
+
69
+ ws.on('message', onMessage)
70
+ ws.once('close', onClose)
71
+ ws.once('error', onError)
72
+ })
73
+ }
74
+
75
+ /**
76
+ * @param {import('./config.mjs').TunnelOptions & { onRequest?: (info: { method: string, path: string }) => void }} options
77
+ * @returns {Promise<{ url: string, subdomain: string, close: () => Promise<void> }>}
78
+ */
79
+ export async function openTunnel(options) {
80
+ const { host, port, subdomain, gatewayUrl, tunnelDomain, quiet, onRequest } = options
81
+
82
+ await waitForLocalPort({ host, port })
83
+
84
+ const ws = new WebSocket(gatewayUrl)
85
+
86
+ await new Promise((resolve, reject) => {
87
+ ws.once('open', resolve)
88
+ ws.once('error', reject)
89
+ })
90
+
91
+ send(ws, {
92
+ type: 'register',
93
+ version: PROTOCOL_VERSION,
94
+ port,
95
+ host,
96
+ subdomain,
97
+ })
98
+
99
+ const registered = await waitForMessage(ws, 'registered')
100
+ const assignedSubdomain = String(registered.subdomain ?? '')
101
+ if (!assignedSubdomain) throw new Error('Gateway did not assign a subdomain')
102
+
103
+ const url =
104
+ tunnelDomain.includes(':') || tunnelDomain === 'localhost'
105
+ ? localGatewayHttpUrl(assignedSubdomain, tunnelDomain)
106
+ : publicUrl(assignedSubdomain, tunnelDomain)
107
+
108
+ ws.on('message', (data) => {
109
+ void handleGatewayMessage(ws, data, { host, port, quiet, onRequest })
110
+ })
111
+
112
+ ws.on('close', () => {
113
+ if (!quiet) console.log('\nTunnel closed.')
114
+ })
115
+
116
+ return {
117
+ url,
118
+ subdomain: assignedSubdomain,
119
+ close: async () => {
120
+ await new Promise((resolve) => {
121
+ if (ws.readyState === ws.CLOSED) {
122
+ resolve(undefined)
123
+ return
124
+ }
125
+ ws.once('close', resolve)
126
+ ws.close()
127
+ })
128
+ },
129
+ }
130
+ }
131
+
132
+ /**
133
+ * @param {import('ws').WebSocket} ws
134
+ * @param {import('ws').RawData} data
135
+ * @param {{ host: string, port: number, quiet: boolean, onRequest?: (info: { method: string, path: string }) => void }} ctx
136
+ */
137
+ async function handleGatewayMessage(ws, data, ctx) {
138
+ let message
139
+ try {
140
+ message = parseMessage(data)
141
+ } catch {
142
+ return
143
+ }
144
+
145
+ if (message.type !== 'request') return
146
+
147
+ const id = String(message.id ?? '')
148
+ const method = String(message.method ?? 'GET').toUpperCase()
149
+ const path = String(message.path ?? '/')
150
+ const headers = /** @type {Record<string, string>} */ (message.headers ?? {})
151
+ const body = message.body ? Buffer.from(String(message.body), 'base64') : undefined
152
+
153
+ ctx.onRequest?.({ method, path })
154
+ if (!ctx.quiet) {
155
+ console.log(`${method} ${path}`)
156
+ }
157
+
158
+ try {
159
+ const response = await forwardToLocal({ host: ctx.host, port: ctx.port, method, path, headers, body })
160
+ send(ws, {
161
+ type: 'response',
162
+ id,
163
+ status: response.status,
164
+ headers: response.headers,
165
+ body: response.body.length ? response.body.toString('base64') : undefined,
166
+ })
167
+ } catch (err) {
168
+ send(ws, {
169
+ type: 'response',
170
+ id,
171
+ status: 502,
172
+ headers: { 'content-type': 'text/plain' },
173
+ body: Buffer.from(String(err instanceof Error ? err.message : err)).toString('base64'),
174
+ })
175
+ }
176
+ }
177
+
178
+ /**
179
+ * @param {{ host: string, port: number, method: string, path: string, headers: Record<string, string>, body?: Buffer }} req
180
+ */
181
+ function forwardToLocal(req) {
182
+ return new Promise((resolve, reject) => {
183
+ const upstream = http.request(
184
+ {
185
+ host: req.host,
186
+ port: req.port,
187
+ method: req.method,
188
+ path: req.path,
189
+ headers: stripHopByHop(req.headers),
190
+ },
191
+ (res) => {
192
+ const chunks = []
193
+ res.on('data', (chunk) => chunks.push(chunk))
194
+ res.on('end', () => {
195
+ resolve({
196
+ status: res.statusCode ?? 502,
197
+ headers: Object.fromEntries(
198
+ Object.entries(res.headers).flatMap(([key, value]) =>
199
+ value === undefined ? [] : [[key, Array.isArray(value) ? value.join(', ') : value]],
200
+ ),
201
+ ),
202
+ body: Buffer.concat(chunks),
203
+ })
204
+ })
205
+ },
206
+ )
207
+
208
+ upstream.on('error', reject)
209
+ if (req.body?.length) upstream.write(req.body)
210
+ upstream.end()
211
+ })
212
+ }
213
+
214
+ /** @param {Record<string, string>} headers */
215
+ function stripHopByHop(headers) {
216
+ const blocked = new Set([
217
+ 'connection',
218
+ 'keep-alive',
219
+ 'proxy-authenticate',
220
+ 'proxy-authorization',
221
+ 'te',
222
+ 'trailers',
223
+ 'transfer-encoding',
224
+ 'upgrade',
225
+ 'host',
226
+ ])
227
+ return Object.fromEntries(Object.entries(headers).filter(([key]) => !blocked.has(key.toLowerCase())))
228
+ }
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.0",
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
- };