portless 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +114 -1
- package/dist/chunk-SE7KL62V.js +247 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +464 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.js +14 -0
- package/package.json +76 -6
- package/index.js +0 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Vercel Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,116 @@
|
|
|
1
1
|
# portless
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Replace port numbers with stable, named .localhost URLs. For humans and agents.
|
|
4
|
+
|
|
5
|
+
```diff
|
|
6
|
+
- "dev": "next dev" # http://localhost:3000
|
|
7
|
+
+ "dev": "portless myapp next dev" # http://myapp.localhost
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Quick Start
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
# Install
|
|
14
|
+
npm install -g portless
|
|
15
|
+
|
|
16
|
+
# Start the proxy (once, requires sudo for port 80)
|
|
17
|
+
sudo portless proxy
|
|
18
|
+
|
|
19
|
+
# Run your app
|
|
20
|
+
portless myapp next dev
|
|
21
|
+
# → http://myapp.localhost
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
> When run directly in your terminal, portless can auto-start the proxy for you (prompts for sudo once). Via package scripts, start the proxy manually first.
|
|
25
|
+
|
|
26
|
+
## Why
|
|
27
|
+
|
|
28
|
+
Local dev with port numbers is fragile:
|
|
29
|
+
|
|
30
|
+
- **Port conflicts** — two projects default to the same port and you get `EADDRINUSE`
|
|
31
|
+
- **Memorizing ports** — was the API on 3001 or 8080?
|
|
32
|
+
- **Refreshing shows the wrong app** — stop one server, start another on the same port, and your open tab now shows something completely different
|
|
33
|
+
- **Monorepo multiplier** — every problem above scales with each service in the repo
|
|
34
|
+
- **Agents test the wrong port** — AI coding agents guess or hardcode the wrong port, especially in monorepos
|
|
35
|
+
- **Cookie and storage clashes** — cookies set on `localhost` bleed across apps on different ports; localStorage is lost when ports shift
|
|
36
|
+
- **Hardcoded ports in config** — CORS allowlists, OAuth redirect URIs, and `.env` files all break when ports change
|
|
37
|
+
- **Sharing URLs with teammates** — "what port is that on?" becomes a Slack question
|
|
38
|
+
- **Browser history is useless** — your history for `localhost:3000` is a jumble of unrelated projects
|
|
39
|
+
|
|
40
|
+
Portless fixes all of this by giving each dev server a stable, named `.localhost` URL that both humans and agents can rely on.
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
# Basic
|
|
46
|
+
portless myapp next dev
|
|
47
|
+
# → http://myapp.localhost
|
|
48
|
+
|
|
49
|
+
# Subdomains
|
|
50
|
+
portless api.myapp pnpm start
|
|
51
|
+
# → http://api.myapp.localhost
|
|
52
|
+
|
|
53
|
+
portless docs.myapp next dev
|
|
54
|
+
# → http://docs.myapp.localhost
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### In package.json
|
|
58
|
+
|
|
59
|
+
```json
|
|
60
|
+
{
|
|
61
|
+
"scripts": {
|
|
62
|
+
"dev": "portless myapp next dev"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Start the proxy once (`sudo portless proxy`), then just `pnpm dev`.
|
|
68
|
+
|
|
69
|
+
## How It Works
|
|
70
|
+
|
|
71
|
+
```mermaid
|
|
72
|
+
flowchart TD
|
|
73
|
+
Browser["Browser\nmyapp.localhost"]
|
|
74
|
+
Proxy["portless proxy\n(port 80)"]
|
|
75
|
+
App1[":4123\nmyapp"]
|
|
76
|
+
App2[":4567\napi"]
|
|
77
|
+
|
|
78
|
+
Browser -->|port 80| Proxy
|
|
79
|
+
Proxy --> App1
|
|
80
|
+
Proxy --> App2
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
1. **Start the proxy** -- runs on port 80 by default in the background (requires sudo once)
|
|
84
|
+
2. **Run apps** -- `portless <name> <command>` assigns a free port and registers with the proxy
|
|
85
|
+
3. **Access via URL** -- `http://<name>.localhost` routes through the proxy to your app
|
|
86
|
+
|
|
87
|
+
Apps are assigned a random port (4000-4999) via the `PORT` environment variable. Most frameworks (Next.js, Vite, etc.) respect this automatically.
|
|
88
|
+
|
|
89
|
+
## Commands
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
portless <name> <cmd> [args...] # Run app at http://<name>.localhost
|
|
93
|
+
portless list # Show active routes
|
|
94
|
+
|
|
95
|
+
# Disable portless (run command directly)
|
|
96
|
+
PORTLESS=0 pnpm dev # Bypasses proxy, uses default port
|
|
97
|
+
# Also accepts PORTLESS=skip
|
|
98
|
+
|
|
99
|
+
# Proxy control
|
|
100
|
+
sudo portless proxy # Start the proxy (port 80)
|
|
101
|
+
sudo portless proxy --port 8080 # Start the proxy on a custom port
|
|
102
|
+
sudo portless proxy stop # Stop the proxy
|
|
103
|
+
|
|
104
|
+
# Options
|
|
105
|
+
--port <number> # Port for the proxy (default: 80)
|
|
106
|
+
# Ports >= 1024 do not require sudo
|
|
107
|
+
|
|
108
|
+
# Info
|
|
109
|
+
portless --help # Show help
|
|
110
|
+
portless --version # Show version
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Requirements
|
|
114
|
+
|
|
115
|
+
- Node.js 20+
|
|
116
|
+
- macOS or Linux
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// src/utils.ts
|
|
2
|
+
function isErrnoException(err) {
|
|
3
|
+
return err instanceof Error && "code" in err;
|
|
4
|
+
}
|
|
5
|
+
function escapeHtml(str) {
|
|
6
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
7
|
+
}
|
|
8
|
+
function parseHostname(input) {
|
|
9
|
+
let hostname = input.trim().replace(/^https?:\/\//, "").split("/")[0].toLowerCase();
|
|
10
|
+
if (!hostname || hostname === ".localhost") {
|
|
11
|
+
throw new Error("Hostname cannot be empty");
|
|
12
|
+
}
|
|
13
|
+
if (!hostname.endsWith(".localhost")) {
|
|
14
|
+
hostname = `${hostname}.localhost`;
|
|
15
|
+
}
|
|
16
|
+
const name = hostname.replace(/\.localhost$/, "");
|
|
17
|
+
if (name.includes("..")) {
|
|
18
|
+
throw new Error(`Invalid hostname "${name}": consecutive dots are not allowed`);
|
|
19
|
+
}
|
|
20
|
+
if (!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/.test(name)) {
|
|
21
|
+
throw new Error(
|
|
22
|
+
`Invalid hostname "${name}": must contain only lowercase letters, digits, hyphens, and dots`
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
return hostname;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// src/proxy.ts
|
|
29
|
+
import * as http from "http";
|
|
30
|
+
import httpProxy from "http-proxy";
|
|
31
|
+
function createProxyServer(options) {
|
|
32
|
+
const { getRoutes, onError = (msg) => console.error(msg) } = options;
|
|
33
|
+
const proxy = httpProxy.createProxyServer({});
|
|
34
|
+
proxy.on("error", (err, req, res) => {
|
|
35
|
+
onError(`Proxy error for ${req.headers.host}: ${err.message}`);
|
|
36
|
+
if (res && "writeHead" in res) {
|
|
37
|
+
const serverRes = res;
|
|
38
|
+
if (!serverRes.headersSent) {
|
|
39
|
+
const errWithCode = err;
|
|
40
|
+
const message = errWithCode.code === "ECONNREFUSED" ? "Bad Gateway: the target app is not responding. It may have crashed." : "Bad Gateway: the target app may not be running.";
|
|
41
|
+
serverRes.writeHead(502, { "Content-Type": "text/plain" });
|
|
42
|
+
serverRes.end(message);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
const handleRequest = (req, res) => {
|
|
47
|
+
const routes = getRoutes();
|
|
48
|
+
const host = (req.headers.host || "").split(":")[0];
|
|
49
|
+
if (!host) {
|
|
50
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
51
|
+
res.end("Missing Host header");
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const route = routes.find((r) => r.hostname === host);
|
|
55
|
+
if (!route) {
|
|
56
|
+
const safeHost = escapeHtml(host);
|
|
57
|
+
res.writeHead(404, { "Content-Type": "text/html" });
|
|
58
|
+
res.end(`
|
|
59
|
+
<html>
|
|
60
|
+
<head><title>portless - Not Found</title></head>
|
|
61
|
+
<body style="font-family: system-ui; padding: 40px; max-width: 600px; margin: 0 auto;">
|
|
62
|
+
<h1>Not Found</h1>
|
|
63
|
+
<p>No app registered for <strong>${safeHost}</strong></p>
|
|
64
|
+
${routes.length > 0 ? `
|
|
65
|
+
<h2>Active apps:</h2>
|
|
66
|
+
<ul>
|
|
67
|
+
${routes.map((r) => `<li><a href="http://${escapeHtml(r.hostname)}">${escapeHtml(r.hostname)}</a> - localhost:${escapeHtml(String(r.port))}</li>`).join("")}
|
|
68
|
+
</ul>
|
|
69
|
+
` : "<p><em>No apps running.</em></p>"}
|
|
70
|
+
<p>Start an app with: <code>portless ${safeHost.replace(".localhost", "")} your-command</code></p>
|
|
71
|
+
</body>
|
|
72
|
+
</html>
|
|
73
|
+
`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
proxy.web(req, res, {
|
|
77
|
+
target: `http://127.0.0.1:${route.port}`,
|
|
78
|
+
xfwd: true
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
const handleUpgrade = (req, socket, head) => {
|
|
82
|
+
const routes = getRoutes();
|
|
83
|
+
const host = (req.headers.host || "").split(":")[0];
|
|
84
|
+
const route = routes.find((r) => r.hostname === host);
|
|
85
|
+
if (!route) {
|
|
86
|
+
socket.destroy();
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
proxy.ws(req, socket, head, {
|
|
90
|
+
target: `http://127.0.0.1:${route.port}`,
|
|
91
|
+
xfwd: true
|
|
92
|
+
});
|
|
93
|
+
};
|
|
94
|
+
const httpServer = http.createServer(handleRequest);
|
|
95
|
+
httpServer.on("upgrade", handleUpgrade);
|
|
96
|
+
return httpServer;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/routes.ts
|
|
100
|
+
import * as fs from "fs";
|
|
101
|
+
import * as path from "path";
|
|
102
|
+
function isValidRoute(value) {
|
|
103
|
+
return typeof value === "object" && value !== null && typeof value.hostname === "string" && typeof value.port === "number" && typeof value.pid === "number";
|
|
104
|
+
}
|
|
105
|
+
var RouteStore = class _RouteStore {
|
|
106
|
+
dir;
|
|
107
|
+
routesPath;
|
|
108
|
+
lockPath;
|
|
109
|
+
pidPath;
|
|
110
|
+
onWarning;
|
|
111
|
+
constructor(dir, options) {
|
|
112
|
+
this.dir = dir;
|
|
113
|
+
this.routesPath = path.join(dir, "routes.json");
|
|
114
|
+
this.lockPath = path.join(dir, "routes.lock");
|
|
115
|
+
this.pidPath = path.join(dir, "proxy.pid");
|
|
116
|
+
this.onWarning = options?.onWarning;
|
|
117
|
+
}
|
|
118
|
+
ensureDir() {
|
|
119
|
+
if (!fs.existsSync(this.dir)) {
|
|
120
|
+
fs.mkdirSync(this.dir, { recursive: true, mode: 493 });
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
fs.chmodSync(this.dir, 493);
|
|
124
|
+
} catch {
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
getRoutesPath() {
|
|
128
|
+
return this.routesPath;
|
|
129
|
+
}
|
|
130
|
+
// -- Locking ---------------------------------------------------------------
|
|
131
|
+
static sleepBuffer = new Int32Array(new SharedArrayBuffer(4));
|
|
132
|
+
syncSleep(ms) {
|
|
133
|
+
Atomics.wait(_RouteStore.sleepBuffer, 0, 0, ms);
|
|
134
|
+
}
|
|
135
|
+
acquireLock(maxRetries = 20, retryDelayMs = 50) {
|
|
136
|
+
for (let i = 0; i < maxRetries; i++) {
|
|
137
|
+
try {
|
|
138
|
+
fs.mkdirSync(this.lockPath);
|
|
139
|
+
return true;
|
|
140
|
+
} catch (err) {
|
|
141
|
+
if (isErrnoException(err) && err.code === "EEXIST") {
|
|
142
|
+
try {
|
|
143
|
+
const stat = fs.statSync(this.lockPath);
|
|
144
|
+
if (Date.now() - stat.mtimeMs > 1e4) {
|
|
145
|
+
fs.rmSync(this.lockPath, { recursive: true });
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
this.syncSleep(retryDelayMs);
|
|
152
|
+
} else {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
releaseLock() {
|
|
160
|
+
try {
|
|
161
|
+
fs.rmSync(this.lockPath, { recursive: true });
|
|
162
|
+
} catch {
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// -- Route I/O -------------------------------------------------------------
|
|
166
|
+
isProcessAlive(pid) {
|
|
167
|
+
try {
|
|
168
|
+
process.kill(pid, 0);
|
|
169
|
+
return true;
|
|
170
|
+
} catch {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Load routes from disk, filtering out stale entries whose owning process
|
|
176
|
+
* is no longer alive. Stale-route cleanup is only persisted when the caller
|
|
177
|
+
* already holds the lock (i.e. inside addRoute/removeRoute) to avoid
|
|
178
|
+
* unprotected concurrent writes.
|
|
179
|
+
*/
|
|
180
|
+
loadRoutes(persistCleanup = false) {
|
|
181
|
+
if (!fs.existsSync(this.routesPath)) {
|
|
182
|
+
return [];
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
const raw = fs.readFileSync(this.routesPath, "utf-8");
|
|
186
|
+
let parsed;
|
|
187
|
+
try {
|
|
188
|
+
parsed = JSON.parse(raw);
|
|
189
|
+
} catch {
|
|
190
|
+
this.onWarning?.(`Corrupted routes file (invalid JSON): ${this.routesPath}`);
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
if (!Array.isArray(parsed)) {
|
|
194
|
+
this.onWarning?.(`Corrupted routes file (expected array): ${this.routesPath}`);
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
const routes = parsed.filter(isValidRoute);
|
|
198
|
+
const alive = routes.filter((r) => this.isProcessAlive(r.pid));
|
|
199
|
+
if (persistCleanup && alive.length !== routes.length) {
|
|
200
|
+
try {
|
|
201
|
+
fs.writeFileSync(this.routesPath, JSON.stringify(alive, null, 2), { mode: 420 });
|
|
202
|
+
} catch {
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return alive;
|
|
206
|
+
} catch {
|
|
207
|
+
return [];
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
saveRoutes(routes) {
|
|
211
|
+
this.ensureDir();
|
|
212
|
+
fs.writeFileSync(this.routesPath, JSON.stringify(routes, null, 2), { mode: 420 });
|
|
213
|
+
}
|
|
214
|
+
addRoute(hostname, port, pid) {
|
|
215
|
+
this.ensureDir();
|
|
216
|
+
if (!this.acquireLock()) {
|
|
217
|
+
throw new Error("Failed to acquire route lock");
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
const routes = this.loadRoutes(true).filter((r) => r.hostname !== hostname);
|
|
221
|
+
routes.push({ hostname, port, pid });
|
|
222
|
+
this.saveRoutes(routes);
|
|
223
|
+
} finally {
|
|
224
|
+
this.releaseLock();
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
removeRoute(hostname) {
|
|
228
|
+
this.ensureDir();
|
|
229
|
+
if (!this.acquireLock()) {
|
|
230
|
+
throw new Error("Failed to acquire route lock");
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
const routes = this.loadRoutes(true).filter((r) => r.hostname !== hostname);
|
|
234
|
+
this.saveRoutes(routes);
|
|
235
|
+
} finally {
|
|
236
|
+
this.releaseLock();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
export {
|
|
242
|
+
isErrnoException,
|
|
243
|
+
escapeHtml,
|
|
244
|
+
parseHostname,
|
|
245
|
+
createProxyServer,
|
|
246
|
+
RouteStore
|
|
247
|
+
};
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
RouteStore,
|
|
4
|
+
createProxyServer,
|
|
5
|
+
isErrnoException,
|
|
6
|
+
parseHostname
|
|
7
|
+
} from "./chunk-SE7KL62V.js";
|
|
8
|
+
|
|
9
|
+
// src/cli.ts
|
|
10
|
+
import chalk from "chalk";
|
|
11
|
+
import * as fs from "fs";
|
|
12
|
+
import * as path from "path";
|
|
13
|
+
import * as readline from "readline";
|
|
14
|
+
import { spawn, spawnSync } from "child_process";
|
|
15
|
+
|
|
16
|
+
// src/cli-utils.ts
|
|
17
|
+
import * as net from "net";
|
|
18
|
+
async function findFreePort(minPort = 4e3, maxPort = 4999) {
|
|
19
|
+
const tryPort = (port) => {
|
|
20
|
+
return new Promise((resolve) => {
|
|
21
|
+
const server = net.createServer();
|
|
22
|
+
server.listen(port, () => {
|
|
23
|
+
server.close(() => resolve(true));
|
|
24
|
+
});
|
|
25
|
+
server.on("error", () => resolve(false));
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
for (let i = 0; i < 50; i++) {
|
|
29
|
+
const port = minPort + Math.floor(Math.random() * (maxPort - minPort + 1));
|
|
30
|
+
if (await tryPort(port)) {
|
|
31
|
+
return port;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
for (let port = minPort; port <= maxPort; port++) {
|
|
35
|
+
if (await tryPort(port)) {
|
|
36
|
+
return port;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
throw new Error(`No free port found in range ${minPort}-${maxPort}`);
|
|
40
|
+
}
|
|
41
|
+
function isProxyRunning(port = 80) {
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
const socket = new net.Socket();
|
|
44
|
+
socket.setTimeout(500);
|
|
45
|
+
socket.on("connect", () => {
|
|
46
|
+
socket.destroy();
|
|
47
|
+
resolve(true);
|
|
48
|
+
});
|
|
49
|
+
socket.on("error", () => resolve(false));
|
|
50
|
+
socket.on("timeout", () => {
|
|
51
|
+
socket.destroy();
|
|
52
|
+
resolve(false);
|
|
53
|
+
});
|
|
54
|
+
socket.connect(port, "127.0.0.1");
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/cli.ts
|
|
59
|
+
var SIGNAL_CODES = { SIGINT: 2, SIGTERM: 15 };
|
|
60
|
+
function prompt(question) {
|
|
61
|
+
const rl = readline.createInterface({
|
|
62
|
+
input: process.stdin,
|
|
63
|
+
output: process.stdout
|
|
64
|
+
});
|
|
65
|
+
return new Promise((resolve) => {
|
|
66
|
+
rl.on("close", () => resolve(""));
|
|
67
|
+
rl.question(question, (answer) => {
|
|
68
|
+
rl.close();
|
|
69
|
+
resolve(answer.trim().toLowerCase());
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
var PORTLESS_DIR = "/tmp/portless";
|
|
74
|
+
var PROXY_PORT_PATH = path.join(PORTLESS_DIR, "proxy.port");
|
|
75
|
+
var DEFAULT_PROXY_PORT = 80;
|
|
76
|
+
var store = new RouteStore(PORTLESS_DIR, {
|
|
77
|
+
onWarning: (msg) => console.warn(chalk.yellow(msg))
|
|
78
|
+
});
|
|
79
|
+
function readProxyPort() {
|
|
80
|
+
try {
|
|
81
|
+
const raw = fs.readFileSync(PROXY_PORT_PATH, "utf-8").trim();
|
|
82
|
+
const port = parseInt(raw, 10);
|
|
83
|
+
return isNaN(port) ? DEFAULT_PROXY_PORT : port;
|
|
84
|
+
} catch {
|
|
85
|
+
return DEFAULT_PROXY_PORT;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function waitForProxy(proxyPort, maxAttempts = 20, intervalMs = 250) {
|
|
89
|
+
const port = proxyPort ?? readProxyPort();
|
|
90
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
91
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
92
|
+
if (await isProxyRunning(port)) {
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
function spawnCommand(commandArgs, options) {
|
|
99
|
+
const child = spawn(commandArgs[0], commandArgs.slice(1), {
|
|
100
|
+
stdio: "inherit",
|
|
101
|
+
env: options?.env
|
|
102
|
+
});
|
|
103
|
+
let exiting = false;
|
|
104
|
+
const handleSignal = (signal) => {
|
|
105
|
+
if (exiting) return;
|
|
106
|
+
exiting = true;
|
|
107
|
+
child.kill(signal);
|
|
108
|
+
options?.onCleanup?.();
|
|
109
|
+
process.exit(128 + (SIGNAL_CODES[signal] || 15));
|
|
110
|
+
};
|
|
111
|
+
process.on("SIGINT", () => handleSignal("SIGINT"));
|
|
112
|
+
process.on("SIGTERM", () => handleSignal("SIGTERM"));
|
|
113
|
+
child.on("error", (err) => {
|
|
114
|
+
if (exiting) return;
|
|
115
|
+
exiting = true;
|
|
116
|
+
console.error(chalk.red(`Failed to run command: ${err.message}`));
|
|
117
|
+
options?.onCleanup?.();
|
|
118
|
+
process.exit(1);
|
|
119
|
+
});
|
|
120
|
+
child.on("exit", (code, signal) => {
|
|
121
|
+
if (exiting) return;
|
|
122
|
+
exiting = true;
|
|
123
|
+
options?.onCleanup?.();
|
|
124
|
+
if (signal) {
|
|
125
|
+
process.exit(128 + (SIGNAL_CODES[signal] || 1));
|
|
126
|
+
}
|
|
127
|
+
process.exit(code ?? 1);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
function startProxyServer(proxyPort) {
|
|
131
|
+
store.ensureDir();
|
|
132
|
+
const routesPath = store.getRoutesPath();
|
|
133
|
+
if (!fs.existsSync(routesPath)) {
|
|
134
|
+
fs.writeFileSync(routesPath, "[]", { mode: 420 });
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
fs.chmodSync(routesPath, 420);
|
|
138
|
+
} catch {
|
|
139
|
+
}
|
|
140
|
+
let cachedRoutes = store.loadRoutes();
|
|
141
|
+
let debounceTimer = null;
|
|
142
|
+
let watcher = null;
|
|
143
|
+
const reloadRoutes = () => {
|
|
144
|
+
try {
|
|
145
|
+
cachedRoutes = store.loadRoutes();
|
|
146
|
+
} catch {
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
try {
|
|
150
|
+
watcher = fs.watch(routesPath, () => {
|
|
151
|
+
if (debounceTimer) clearTimeout(debounceTimer);
|
|
152
|
+
debounceTimer = setTimeout(reloadRoutes, 100);
|
|
153
|
+
});
|
|
154
|
+
} catch {
|
|
155
|
+
console.warn(chalk.yellow("fs.watch unavailable; falling back to polling for route changes"));
|
|
156
|
+
setInterval(reloadRoutes, 3e3);
|
|
157
|
+
}
|
|
158
|
+
const server = createProxyServer({
|
|
159
|
+
getRoutes: () => cachedRoutes,
|
|
160
|
+
onError: (msg) => console.error(chalk.red(msg))
|
|
161
|
+
});
|
|
162
|
+
server.on("error", (err) => {
|
|
163
|
+
if (err.code === "EADDRINUSE") {
|
|
164
|
+
console.error(chalk.red(`Port ${proxyPort} is already in use`));
|
|
165
|
+
} else if (err.code === "EACCES") {
|
|
166
|
+
console.error(chalk.red("Permission denied. Use: sudo portless proxy"));
|
|
167
|
+
} else {
|
|
168
|
+
console.error(chalk.red(`Proxy error: ${err.message}`));
|
|
169
|
+
}
|
|
170
|
+
process.exit(1);
|
|
171
|
+
});
|
|
172
|
+
server.listen(proxyPort, () => {
|
|
173
|
+
fs.writeFileSync(store.pidPath, process.pid.toString(), { mode: 420 });
|
|
174
|
+
fs.writeFileSync(PROXY_PORT_PATH, proxyPort.toString(), { mode: 420 });
|
|
175
|
+
console.log(chalk.green(`HTTP proxy listening on port ${proxyPort}`));
|
|
176
|
+
});
|
|
177
|
+
let exiting = false;
|
|
178
|
+
const cleanup = () => {
|
|
179
|
+
if (exiting) return;
|
|
180
|
+
exiting = true;
|
|
181
|
+
if (watcher) {
|
|
182
|
+
watcher.close();
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
fs.unlinkSync(store.pidPath);
|
|
186
|
+
} catch {
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
fs.unlinkSync(PROXY_PORT_PATH);
|
|
190
|
+
} catch {
|
|
191
|
+
}
|
|
192
|
+
server.close(() => process.exit(0));
|
|
193
|
+
setTimeout(() => process.exit(0), 2e3).unref();
|
|
194
|
+
};
|
|
195
|
+
process.on("SIGINT", cleanup);
|
|
196
|
+
process.on("SIGTERM", cleanup);
|
|
197
|
+
console.log(chalk.cyan("\nProxy is running. Press Ctrl+C to stop.\n"));
|
|
198
|
+
console.log(chalk.gray(`Routes file: ${store.getRoutesPath()}`));
|
|
199
|
+
}
|
|
200
|
+
async function stopProxy() {
|
|
201
|
+
const pidPath = store.pidPath;
|
|
202
|
+
if (!fs.existsSync(pidPath)) {
|
|
203
|
+
console.log(chalk.yellow("Proxy is not running."));
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const proxyPort = readProxyPort();
|
|
207
|
+
try {
|
|
208
|
+
const pid = parseInt(fs.readFileSync(pidPath, "utf-8"), 10);
|
|
209
|
+
if (isNaN(pid)) {
|
|
210
|
+
console.error(chalk.red("Corrupted PID file. Removing it."));
|
|
211
|
+
fs.unlinkSync(pidPath);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
process.kill(pid, 0);
|
|
216
|
+
} catch {
|
|
217
|
+
console.log(chalk.yellow("Proxy process is no longer running. Cleaning up."));
|
|
218
|
+
fs.unlinkSync(pidPath);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (!await isProxyRunning(proxyPort)) {
|
|
222
|
+
console.log(
|
|
223
|
+
chalk.yellow(
|
|
224
|
+
`PID file exists but port ${proxyPort} is not listening. The PID may have been recycled.`
|
|
225
|
+
)
|
|
226
|
+
);
|
|
227
|
+
console.log(chalk.yellow("Removing stale PID file."));
|
|
228
|
+
fs.unlinkSync(pidPath);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
process.kill(pid, "SIGTERM");
|
|
232
|
+
fs.unlinkSync(pidPath);
|
|
233
|
+
try {
|
|
234
|
+
fs.unlinkSync(PROXY_PORT_PATH);
|
|
235
|
+
} catch {
|
|
236
|
+
}
|
|
237
|
+
console.log(chalk.green("Proxy stopped."));
|
|
238
|
+
} catch (err) {
|
|
239
|
+
if (isErrnoException(err) && err.code === "EPERM") {
|
|
240
|
+
console.error(chalk.red("Permission denied. The proxy runs as root."));
|
|
241
|
+
console.log(chalk.blue("Use: sudo portless proxy stop"));
|
|
242
|
+
} else {
|
|
243
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
244
|
+
console.error(chalk.red("Failed to stop proxy:"), message);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function listRoutes() {
|
|
249
|
+
const routes = store.loadRoutes();
|
|
250
|
+
if (routes.length === 0) {
|
|
251
|
+
console.log(chalk.yellow("No active routes."));
|
|
252
|
+
console.log(chalk.gray("Start an app with: portless <name> <command>"));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
console.log(chalk.blue.bold("\nActive routes:\n"));
|
|
256
|
+
for (const route of routes) {
|
|
257
|
+
console.log(
|
|
258
|
+
` ${chalk.cyan(`http://${route.hostname}`)} ${chalk.gray("->")} ${chalk.white(`localhost:${route.port}`)} ${chalk.gray(`(pid ${route.pid})`)}`
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
console.log();
|
|
262
|
+
}
|
|
263
|
+
async function runApp(name, commandArgs) {
|
|
264
|
+
const hostname = parseHostname(name);
|
|
265
|
+
const proxyPort = readProxyPort();
|
|
266
|
+
console.log(chalk.blue.bold(`
|
|
267
|
+
portless
|
|
268
|
+
`));
|
|
269
|
+
console.log(chalk.gray(`-- ${hostname} (auto-resolves to 127.0.0.1)`));
|
|
270
|
+
if (!await isProxyRunning(proxyPort)) {
|
|
271
|
+
if (process.stdin.isTTY) {
|
|
272
|
+
const answer = await prompt(chalk.yellow("Proxy not running. Start it? [Y/n/skip] "));
|
|
273
|
+
if (answer === "n" || answer === "no") {
|
|
274
|
+
console.log(chalk.gray("Cancelled."));
|
|
275
|
+
process.exit(0);
|
|
276
|
+
}
|
|
277
|
+
if (answer === "s" || answer === "skip") {
|
|
278
|
+
console.log(chalk.gray("Skipping proxy, running command directly...\n"));
|
|
279
|
+
spawnCommand(commandArgs);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
console.log(chalk.yellow("Starting proxy (requires sudo)..."));
|
|
283
|
+
const result = spawnSync("sudo", [process.execPath, process.argv[1], "proxy", "--daemon"], {
|
|
284
|
+
stdio: "inherit",
|
|
285
|
+
timeout: 3e4
|
|
286
|
+
});
|
|
287
|
+
if (result.status !== 0) {
|
|
288
|
+
console.log(chalk.red("\nFailed to start proxy"));
|
|
289
|
+
process.exit(1);
|
|
290
|
+
}
|
|
291
|
+
if (!await waitForProxy()) {
|
|
292
|
+
console.log(chalk.red("\nProxy failed to start"));
|
|
293
|
+
const logPath = path.join(PORTLESS_DIR, "proxy.log");
|
|
294
|
+
if (fs.existsSync(logPath)) {
|
|
295
|
+
console.log(chalk.gray(`Check logs: ${logPath}`));
|
|
296
|
+
}
|
|
297
|
+
process.exit(1);
|
|
298
|
+
}
|
|
299
|
+
console.log(chalk.green("Proxy started in background"));
|
|
300
|
+
} else {
|
|
301
|
+
console.log(chalk.red("\nProxy is not running!"));
|
|
302
|
+
console.log(chalk.blue("\nStart the proxy first (one time):"));
|
|
303
|
+
console.log(chalk.cyan(" sudo portless proxy\n"));
|
|
304
|
+
process.exit(1);
|
|
305
|
+
}
|
|
306
|
+
} else {
|
|
307
|
+
console.log(chalk.gray("-- Proxy is running"));
|
|
308
|
+
}
|
|
309
|
+
const port = await findFreePort();
|
|
310
|
+
console.log(chalk.green(`-- Using port ${port}`));
|
|
311
|
+
store.addRoute(hostname, port, process.pid);
|
|
312
|
+
console.log(chalk.cyan.bold(`
|
|
313
|
+
-> http://${hostname}
|
|
314
|
+
`));
|
|
315
|
+
console.log(chalk.gray(`Running: PORT=${port} ${commandArgs.join(" ")}
|
|
316
|
+
`));
|
|
317
|
+
spawnCommand(commandArgs, {
|
|
318
|
+
env: { ...process.env, PORT: port.toString() },
|
|
319
|
+
onCleanup: () => {
|
|
320
|
+
try {
|
|
321
|
+
store.removeRoute(hostname);
|
|
322
|
+
} catch {
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
async function main() {
|
|
328
|
+
const args = process.argv.slice(2);
|
|
329
|
+
const skipPortless = process.env.PORTLESS === "0" || process.env.PORTLESS === "skip";
|
|
330
|
+
if (skipPortless && args.length >= 2 && args[0] !== "proxy") {
|
|
331
|
+
spawnCommand(args.slice(1));
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
|
|
335
|
+
console.log(`
|
|
336
|
+
${chalk.bold("portless")} - Replace port numbers with stable, named .localhost URLs. For humans and agents.
|
|
337
|
+
|
|
338
|
+
Eliminates port conflicts, memorizing port numbers, and cookie/storage
|
|
339
|
+
clashes by giving each dev server a stable .localhost URL.
|
|
340
|
+
|
|
341
|
+
${chalk.bold("Usage:")}
|
|
342
|
+
${chalk.cyan("sudo portless proxy")} Start the proxy (run once, keep open)
|
|
343
|
+
${chalk.cyan("sudo portless proxy --port 8080")} Start the proxy on a custom port
|
|
344
|
+
${chalk.cyan("sudo portless proxy stop")} Stop the proxy
|
|
345
|
+
${chalk.cyan("portless <name> <cmd>")} Run your app through the proxy
|
|
346
|
+
${chalk.cyan("portless list")} Show active routes
|
|
347
|
+
|
|
348
|
+
${chalk.bold("Examples:")}
|
|
349
|
+
sudo portless proxy # Start proxy in terminal 1
|
|
350
|
+
portless myapp next dev # Terminal 2 -> http://myapp.localhost
|
|
351
|
+
portless api.myapp pnpm start # Terminal 3 -> http://api.myapp.localhost
|
|
352
|
+
|
|
353
|
+
${chalk.bold("In package.json:")}
|
|
354
|
+
{
|
|
355
|
+
"scripts": {
|
|
356
|
+
"dev": "portless myapp next dev"
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
${chalk.bold("How it works:")}
|
|
361
|
+
1. Start the proxy once with sudo (listens on port 80 by default)
|
|
362
|
+
2. Run your apps - they register automatically
|
|
363
|
+
3. Access via http://<name>.localhost
|
|
364
|
+
4. .localhost domains auto-resolve to 127.0.0.1
|
|
365
|
+
|
|
366
|
+
${chalk.bold("Options:")}
|
|
367
|
+
--port <number> Port for the proxy to listen on (default: 80)
|
|
368
|
+
Ports >= 1024 do not require sudo
|
|
369
|
+
|
|
370
|
+
${chalk.bold("Skip portless:")}
|
|
371
|
+
PORTLESS=0 pnpm dev # Runs command directly without proxy
|
|
372
|
+
PORTLESS=skip pnpm dev # Same as above
|
|
373
|
+
`);
|
|
374
|
+
process.exit(0);
|
|
375
|
+
}
|
|
376
|
+
if (args[0] === "--version" || args[0] === "-v") {
|
|
377
|
+
console.log("0.2.0");
|
|
378
|
+
process.exit(0);
|
|
379
|
+
}
|
|
380
|
+
if (args[0] === "list") {
|
|
381
|
+
listRoutes();
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
if (args[0] === "proxy") {
|
|
385
|
+
if (args[1] === "stop") {
|
|
386
|
+
await stopProxy();
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
const isDaemon = args.includes("--daemon");
|
|
390
|
+
let proxyPort = DEFAULT_PROXY_PORT;
|
|
391
|
+
const portFlagIndex = args.indexOf("--port");
|
|
392
|
+
if (portFlagIndex !== -1) {
|
|
393
|
+
const portValue = args[portFlagIndex + 1];
|
|
394
|
+
if (!portValue || portValue.startsWith("-")) {
|
|
395
|
+
console.error(chalk.red("Error: --port requires a port number"));
|
|
396
|
+
console.log(chalk.blue("Usage: portless proxy --port 8080"));
|
|
397
|
+
process.exit(1);
|
|
398
|
+
}
|
|
399
|
+
proxyPort = parseInt(portValue, 10);
|
|
400
|
+
if (isNaN(proxyPort) || proxyPort < 1 || proxyPort > 65535) {
|
|
401
|
+
console.error(chalk.red(`Error: Invalid port number: ${portValue}`));
|
|
402
|
+
console.log(chalk.blue("Port must be between 1 and 65535"));
|
|
403
|
+
process.exit(1);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (await isProxyRunning(proxyPort)) {
|
|
407
|
+
if (!isDaemon) {
|
|
408
|
+
console.log(chalk.yellow("Proxy is already running."));
|
|
409
|
+
console.log(chalk.blue("To restart: portless proxy stop && sudo portless proxy"));
|
|
410
|
+
}
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
if (proxyPort < 1024 && process.getuid() !== 0) {
|
|
414
|
+
console.error(chalk.red(`Error: Proxy requires sudo for port ${proxyPort}`));
|
|
415
|
+
console.log(chalk.blue("Usage: sudo portless proxy"));
|
|
416
|
+
process.exit(1);
|
|
417
|
+
}
|
|
418
|
+
if (isDaemon) {
|
|
419
|
+
store.ensureDir();
|
|
420
|
+
const logPath = path.join(PORTLESS_DIR, "proxy.log");
|
|
421
|
+
const logFd = fs.openSync(logPath, "a");
|
|
422
|
+
try {
|
|
423
|
+
fs.chmodSync(logPath, 420);
|
|
424
|
+
} catch {
|
|
425
|
+
}
|
|
426
|
+
const daemonArgs = [process.argv[1], "proxy"];
|
|
427
|
+
if (portFlagIndex !== -1) {
|
|
428
|
+
daemonArgs.push("--port", proxyPort.toString());
|
|
429
|
+
}
|
|
430
|
+
const child = spawn(process.execPath, daemonArgs, {
|
|
431
|
+
detached: true,
|
|
432
|
+
stdio: ["ignore", logFd, logFd],
|
|
433
|
+
env: process.env
|
|
434
|
+
});
|
|
435
|
+
child.unref();
|
|
436
|
+
fs.closeSync(logFd);
|
|
437
|
+
if (!await waitForProxy(proxyPort)) {
|
|
438
|
+
console.error(chalk.red("Proxy failed to start"));
|
|
439
|
+
if (fs.existsSync(logPath)) {
|
|
440
|
+
console.log(chalk.gray(`Check logs: ${logPath}`));
|
|
441
|
+
}
|
|
442
|
+
process.exit(1);
|
|
443
|
+
}
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
console.log(chalk.blue.bold("\nportless proxy\n"));
|
|
447
|
+
startProxyServer(proxyPort);
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
const name = args[0];
|
|
451
|
+
const commandArgs = args.slice(1);
|
|
452
|
+
if (commandArgs.length === 0) {
|
|
453
|
+
console.error(chalk.red("Error: No command provided"));
|
|
454
|
+
console.log(chalk.blue("Usage: portless <name> <command...>"));
|
|
455
|
+
console.log(chalk.blue("Example: portless myapp next dev"));
|
|
456
|
+
process.exit(1);
|
|
457
|
+
}
|
|
458
|
+
await runApp(name, commandArgs);
|
|
459
|
+
}
|
|
460
|
+
main().catch((err) => {
|
|
461
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
462
|
+
console.error(chalk.red("Error:"), message);
|
|
463
|
+
process.exit(1);
|
|
464
|
+
});
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import * as http from 'node:http';
|
|
2
|
+
|
|
3
|
+
/** Route info used by the proxy server to map hostnames to ports. */
|
|
4
|
+
interface RouteInfo {
|
|
5
|
+
hostname: string;
|
|
6
|
+
port: number;
|
|
7
|
+
}
|
|
8
|
+
interface ProxyServerOptions {
|
|
9
|
+
/** Called on each request to get the current route table. */
|
|
10
|
+
getRoutes: () => RouteInfo[];
|
|
11
|
+
/** Optional error logger; defaults to console.error. */
|
|
12
|
+
onError?: (message: string) => void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Create an HTTP proxy server that routes requests based on the Host header.
|
|
17
|
+
*
|
|
18
|
+
* The `getRoutes` callback is invoked on every request so callers can provide
|
|
19
|
+
* either a static list or a live-updating one.
|
|
20
|
+
*/
|
|
21
|
+
declare function createProxyServer(options: ProxyServerOptions): http.Server;
|
|
22
|
+
|
|
23
|
+
interface RouteMapping extends RouteInfo {
|
|
24
|
+
pid: number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Manages route mappings stored as a JSON file on disk.
|
|
28
|
+
* Supports file locking and stale-route cleanup.
|
|
29
|
+
*/
|
|
30
|
+
declare class RouteStore {
|
|
31
|
+
private readonly dir;
|
|
32
|
+
private readonly routesPath;
|
|
33
|
+
private readonly lockPath;
|
|
34
|
+
readonly pidPath: string;
|
|
35
|
+
private readonly onWarning;
|
|
36
|
+
constructor(dir: string, options?: {
|
|
37
|
+
onWarning?: (message: string) => void;
|
|
38
|
+
});
|
|
39
|
+
ensureDir(): void;
|
|
40
|
+
getRoutesPath(): string;
|
|
41
|
+
private static readonly sleepBuffer;
|
|
42
|
+
private syncSleep;
|
|
43
|
+
acquireLock(maxRetries?: number, retryDelayMs?: number): boolean;
|
|
44
|
+
releaseLock(): void;
|
|
45
|
+
private isProcessAlive;
|
|
46
|
+
/**
|
|
47
|
+
* Load routes from disk, filtering out stale entries whose owning process
|
|
48
|
+
* is no longer alive. Stale-route cleanup is only persisted when the caller
|
|
49
|
+
* already holds the lock (i.e. inside addRoute/removeRoute) to avoid
|
|
50
|
+
* unprotected concurrent writes.
|
|
51
|
+
*/
|
|
52
|
+
loadRoutes(persistCleanup?: boolean): RouteMapping[];
|
|
53
|
+
private saveRoutes;
|
|
54
|
+
addRoute(hostname: string, port: number, pid: number): void;
|
|
55
|
+
removeRoute(hostname: string): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Type guard for Node.js system errors with an error code. */
|
|
59
|
+
declare function isErrnoException(err: unknown): err is NodeJS.ErrnoException;
|
|
60
|
+
/**
|
|
61
|
+
* Escape HTML special characters to prevent XSS.
|
|
62
|
+
*/
|
|
63
|
+
declare function escapeHtml(str: string): string;
|
|
64
|
+
/**
|
|
65
|
+
* Parse and normalize a hostname input for use as a .localhost subdomain.
|
|
66
|
+
* Strips protocol prefixes, validates characters, and appends .localhost if needed.
|
|
67
|
+
*/
|
|
68
|
+
declare function parseHostname(input: string): string;
|
|
69
|
+
|
|
70
|
+
export { type ProxyServerOptions, type RouteInfo, type RouteMapping, RouteStore, createProxyServer, escapeHtml, isErrnoException, parseHostname };
|
package/dist/index.js
ADDED
package/package.json
CHANGED
|
@@ -1,12 +1,82 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "portless",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
"
|
|
7
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Replace port numbers with stable, named .localhost URLs. For humans and agents.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"portless": "./dist/cli.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=20"
|
|
22
|
+
},
|
|
23
|
+
"os": [
|
|
24
|
+
"darwin",
|
|
25
|
+
"linux"
|
|
26
|
+
],
|
|
27
|
+
"keywords": [
|
|
28
|
+
"local",
|
|
29
|
+
"development",
|
|
30
|
+
"proxy",
|
|
31
|
+
"localhost"
|
|
32
|
+
],
|
|
33
|
+
"author": "Vercel Labs",
|
|
34
|
+
"license": "Apache-2.0",
|
|
8
35
|
"repository": {
|
|
9
36
|
"type": "git",
|
|
10
|
-
"url": ""
|
|
37
|
+
"url": "https://github.com/vercel-labs/portless.git"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://github.com/vercel-labs/portless#readme",
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/vercel-labs/portless/issues"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"chalk": "^5.3.0",
|
|
45
|
+
"http-proxy": "^1.18.1"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@eslint/js": "^9.39.2",
|
|
49
|
+
"@types/http-proxy": "^1.17.14",
|
|
50
|
+
"@types/node": "^20.11.0",
|
|
51
|
+
"@vitest/coverage-v8": "^4.0.18",
|
|
52
|
+
"eslint": "^9.39.2",
|
|
53
|
+
"eslint-config-prettier": "^10.1.8",
|
|
54
|
+
"husky": "^9.1.7",
|
|
55
|
+
"lint-staged": "^16.2.7",
|
|
56
|
+
"prettier": "^3.8.1",
|
|
57
|
+
"tsup": "^8.0.1",
|
|
58
|
+
"typescript": "^5.3.3",
|
|
59
|
+
"typescript-eslint": "^8.55.0",
|
|
60
|
+
"vitest": "^4.0.18"
|
|
61
|
+
},
|
|
62
|
+
"lint-staged": {
|
|
63
|
+
"*.{ts,js}": [
|
|
64
|
+
"eslint --fix",
|
|
65
|
+
"prettier --write"
|
|
66
|
+
],
|
|
67
|
+
"*.{json,md,yml,yaml}": "prettier --write"
|
|
68
|
+
},
|
|
69
|
+
"scripts": {
|
|
70
|
+
"build": "tsup",
|
|
71
|
+
"dev": "tsup --watch",
|
|
72
|
+
"format": "prettier --write .",
|
|
73
|
+
"format:check": "prettier --check .",
|
|
74
|
+
"lint": "eslint src/",
|
|
75
|
+
"lint:fix": "eslint src/ --fix",
|
|
76
|
+
"pretest": "pnpm build",
|
|
77
|
+
"test": "vitest run",
|
|
78
|
+
"test:coverage": "vitest run --coverage",
|
|
79
|
+
"test:watch": "vitest",
|
|
80
|
+
"typecheck": "tsc --noEmit"
|
|
11
81
|
}
|
|
12
82
|
}
|
package/index.js
DELETED