portpreview 0.1.1 → 0.2.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 CHANGED
@@ -1,8 +1,193 @@
1
+
1
2
  Apache License
2
3
  Version 2.0, January 2004
3
4
  http://www.apache.org/licenses/
4
5
 
5
- Copyright 2026 ElemOps
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
6
191
 
7
192
  Licensed under the Apache License, Version 2.0 (the "License");
8
193
  you may not use this file except in compliance with the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ PortPreview CLI
2
+ Copyright 2026 ElemOps
3
+
4
+ This product includes software developed by ElemOps (https://portpreview.com).
package/README.md CHANGED
@@ -1,33 +1,76 @@
1
- # PortPreview
1
+ # PortPreview CLI
2
2
 
3
- Expose a local port through a public HTTPS URL.
3
+ Open-source client for [PortPreview](https://portpreview.com) — expose a local port through a public URL for webhook debugging, OAuth callbacks, and dev previews.
4
+
5
+ ## Usage
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
- Connects to the PortPreview gateway and forwards public traffic to `http://127.0.0.1:3000`.
22
+ `npx` picks up the local CLI from `node_modules/.bin` before hitting the npm registry.
10
23
 
11
- ## Install
24
+ ## Publish to npm
12
25
 
13
26
  ```bash
14
- npm install -g portpreview
15
- portpreview 3000
27
+ cd cli
28
+ npm login
29
+ npm publish
30
+ ```
31
+
32
+ After the current package version is published to npm, `npx portpreview 3000` works from any directory without cloning this repo.
33
+
34
+ ## Standalone Windows x64
35
+
36
+ The standalone executable includes Node.js and the same CLI used by npm. On a
37
+ verified release, download the versioned `.exe` and its `.sha256` file, check the
38
+ hash with `Get-FileHash`, then run in PowerShell:
39
+
40
+ ```powershell
41
+ .\portpreview-0.2.0-windows-x64.exe --help
42
+ .\portpreview-0.2.0-windows-x64.exe 3000
43
+ .\portpreview-0.2.0-windows-x64.exe config set-token pp_live_...
16
44
  ```
17
45
 
18
- Pin a version:
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
- npx portpreview@0.1.0 3000
55
+ # Terminal 1 — dev gateway
56
+ npm run gateway --prefix cli
57
+
58
+ # Terminal 2 — your app
59
+ python3 -m http.server 3000
60
+
61
+ # Terminal 3 — tunnel
62
+ npx portpreview 3000 \
63
+ --gateway ws://127.0.0.1:4040/tunnel \
64
+ --domain localhost:4040
22
65
  ```
23
66
 
24
67
  ## Options
25
68
 
26
69
  | Flag | Description |
27
70
  |------|-------------|
28
- | `--host <addr>` | Local address to forward to (default `127.0.0.1`) |
29
- | `--subdomain <name>` | 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 |
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
- ## Persistent token (recommended)
85
+ See **Local development** below for `--gateway`, `--domain`, and related env vars.
43
86
 
44
- Save your CLI token once, like ngrok's `config add-authtoken`:
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
- 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:
95
+ Default config file: `~/.config/portpreview/config.json` on Linux.
81
96
 
82
- ```bash
83
- npx portpreview config set-token pp_live_...
84
- npx portpreview 3000 --subdomain my-project
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
- Or keep it in the current shell only:
101
+ ## Tests
88
102
 
89
103
  ```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):
104
+ npm test --prefix cli
109
105
 
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` |
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
- ```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
109
+ # Opt-in: real wall-clock session for 2 hours + 90 seconds
110
+ node cli/test/tunnel-soak.mjs
123
111
  ```
124
112
 
125
- ## License
126
-
127
- Apache-2.0
113
+ ## Tunnel sessions and request history
114
+
115
+ Free accounts and anonymous visitors can run one active tunnel at a time.
116
+ Tunnel sessions have no duration limit on any plan. Self-hosted gateways older
117
+ than 0.2.0 can retain their previous session limits until they are upgraded.
118
+
119
+ The 0.2.0 client negotiates protocol v3 with a 0.2.0 gateway. HTTP
120
+ request and response bodies stream without a total byte, traffic, or active
121
+ transfer duration limit. Each direction uses 64 KiB chunks and a 256 KiB credit
122
+ window; inspector captures only the first 64 KiB and marks incomplete previews.
123
+ Range, If-Range, ETag, Content-Range and original Content-Length are preserved,
124
+ including 206/416 and HEAD. Streams with no progress for 120 seconds are
125
+ cancelled; active slow streams may continue indefinitely. Tunnel transport
126
+ heartbeats detect dead connections. After transient network loss, the CLI
127
+ reconnects automatically with exponential backoff and jitter, from 500 ms up to
128
+ 30 seconds. Anonymous tunnels may receive a new URL, which the command announces;
129
+ reserved tunnels retry with the same subdomain and token. Access revocation and
130
+ permanent registration or authentication errors stop retries. Ctrl+C cancels
131
+ pending connection attempts and retry timers.
132
+
133
+ Interrupted HTTP transfers are cancelled and must be retried by the application;
134
+ reconnecting does not replay requests or resume their bytes. Applications can
135
+ resume downloads with Range and If-Range when the upstream supports them. Library
136
+ callers can observe the current URL through the returned `url` getter or an
137
+ `onReconnect` callback.
138
+
139
+ Clients older than 0.2.0 and fallback to older v2 gateways retain the legacy
140
+ 1 MiB HTTP body cap; both ends need upgrading for streaming. WebSocket messages
141
+ retain an explicit 1 MiB per-message limit; oversized messages close rather than
142
+ silently truncate. Requests made by automated agents and webhooks are included
143
+ in request history.
144
+
145
+ Protect reserved preview domains with a password or IP/CIDR allowlist in the
146
+ dashboard (all plans). A password uses HTTP Basic authentication; enter any
147
+ username and your preview password. This credential is consumed by the gateway
148
+ and is not forwarded to localhost. Application HTTP Basic authentication cannot
149
+ share the same Authorization header, so use an application session cookie or a
150
+ bearer token route without preview password protection. Policy changes and token
151
+ revocations take effect within 30 seconds on connected gateways.
@@ -1,76 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import packageJson from '../package.json' with { type: 'json' }
4
- import { parseArgs, printHelp } from '../lib/config.mjs'
5
- import { 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
- async function main() {
9
- const argv = process.argv.slice(2)
6
+ const require = createRequire(import.meta.url)
7
+ const { version } = require('../package.json')
10
8
 
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) => {
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
  })
@@ -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: npx portpreview <port>')
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
- npx portpreview <port> [options]
72
- npx portpreview config <command>
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
- 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
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
- 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
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