@johnhenry/browsermesh-ingress 0.0.0-stage → 0.0.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 +21 -0
- package/README.md +162 -2
- package/bin/browsermesh-ingress.mjs +7 -0
- package/package.json +47 -4
- package/src/cli/args.mjs +198 -0
- package/src/cli/mesh-node.mjs +125 -0
- package/src/cli/run.mjs +108 -0
- package/src/errors.mjs +21 -0
- package/src/headers.mjs +201 -0
- package/src/index.mjs +15 -0
- package/src/ingress.mjs +483 -0
- package/src/limits.mjs +110 -0
- package/src/node.mjs +139 -0
- package/src/provider.mjs +260 -0
- package/src/wire.mjs +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Clawser Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,163 @@
|
|
|
1
|
-
#
|
|
1
|
+
# browsermesh-ingress
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@johnhenry/browsermesh-ingress)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
Real HTTP in, a mesh pod answers. A request arrives at a listener you run; a mapping you wrote names ONE pod; that pod
|
|
7
|
+
(a browser tab, or a pod in Node or anywhere else that runs `serveHttpOnMesh`) answers it with a
|
|
8
|
+
`(Request) => Response` handler; the response goes back to the HTTP client.
|
|
9
|
+
|
|
10
|
+
It is a library (a web-standard `(Request) => Promise<Response>`, plus a Node listener on its own entry) and a CLI
|
|
11
|
+
(`browsermesh-ingress`).
|
|
12
|
+
|
|
13
|
+
Peer dependency: `@johnhenry/browsermesh-apps` `>=0.21.0` (the protocol channel and its streams). The CLI also needs
|
|
14
|
+
`@johnhenry/browsermesh-core`, `-pod`, `-primitives`, `-transport` and `-discovery` (optional dependencies, installed by
|
|
15
|
+
default) and `node-datachannel` (an optional dependency) to reach pods over WebRTC from Node.
|
|
16
|
+
|
|
17
|
+
## What it is, and what it is not
|
|
18
|
+
|
|
19
|
+
- **It is** a bounded request forwarder: one mapping, one pod, protocol `http` v1 on the existing protocol channel
|
|
20
|
+
(`openProtocol(peer, 'http', { versions: [1] })`), request and response bodies as protocol streams with
|
|
21
|
+
cancellation and backpressure.
|
|
22
|
+
- **It is not a CDN**: nothing is cached (`Cache-Control: no-store`), nothing is replicated.
|
|
23
|
+
- **It is not a file server**: it holds no content and serves none; the pod does.
|
|
24
|
+
- **It is not an egress proxy**: it never fetches a URL, and a peer never supplies one. (`ServerSharing` in
|
|
25
|
+
`browsermesh-apps` goes the other way, a peer asking this pod to fetch from a local server; it is separate.)
|
|
26
|
+
|
|
27
|
+
## The security model, plainly
|
|
28
|
+
|
|
29
|
+
**An ingress operator serves content they do not control.** The pod behind a mapping answers with whatever it likes; the
|
|
30
|
+
HTTP client is anyone. The ingress sits between them and does only translating and limiting:
|
|
31
|
+
|
|
32
|
+
- the answer is accepted only from the pod the mapping names (a channel bound to another pod is refused, 502
|
|
33
|
+
`provider-pin-mismatch`; a pod with no direct link is refused, 502 `provider-unreachable`);
|
|
34
|
+
- the provider decides whom it serves (`protocol:http:open` in its registry, default deny, and `allowFrom`);
|
|
35
|
+
- every dimension is bounded (see Defaults) and everything a provider sends is filtered: no cookies, no redirects off
|
|
36
|
+
the origin, no headers outside an allow-list, an inert `Content-Security-Policy`.
|
|
37
|
+
|
|
38
|
+
**One origin per provider is your responsibility.** Two providers behind one hostname share cookies, storage and script
|
|
39
|
+
reach in a browser; the response policy reduces that and must not be relied on. Give each pod its own hostname. The CLI
|
|
40
|
+
refuses two different pods under one hostname, and warns when mappings share an origin by path.
|
|
41
|
+
|
|
42
|
+
The listener speaks plain HTTP: put TLS in front of it. Nothing public is on by default.
|
|
43
|
+
|
|
44
|
+
## Library
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
import { attachService, createMeshProtocolService } from '@johnhenry/browsermesh-apps'
|
|
48
|
+
import { createMeshIngress } from '@johnhenry/browsermesh-ingress'
|
|
49
|
+
import { listenNode } from '@johnhenry/browsermesh-ingress/node'
|
|
50
|
+
|
|
51
|
+
const service = attachService(node, undefined, createMeshProtocolService())
|
|
52
|
+
const ingress = createMeshIngress({
|
|
53
|
+
service, // or `node`, to have one attached
|
|
54
|
+
resolve: (request) => new URL(request.url).host === 'app.example.test' ? { peer: appPodId } : null,
|
|
55
|
+
methods: ['GET', 'HEAD', 'POST'], // GET and HEAD by default
|
|
56
|
+
onAudit: (record) => console.log(record), // { peer, host, method, status, reason?, requestBytes, responseBytes, durationMs }
|
|
57
|
+
})
|
|
58
|
+
const { port, close } = await listenNode(ingress, { port: 8080, host: '127.0.0.1', trustProxy: false })
|
|
59
|
+
|
|
60
|
+
// anywhere else: a Workers or Deno handler is just
|
|
61
|
+
// export default { fetch: (request) => ingress.handle(request, { clientAddress }) }
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`createMeshIngress({ node | service, resolve, authorize?, deny?, limits?, methods?, forwardHeaders?, exposeHeaders?,
|
|
65
|
+
forwardClientAddress?, verifyResponse?, rpc?, onAudit?, clock? })` returns `{ handle(request, { clientAddress }),
|
|
66
|
+
stats(), close() }`.
|
|
67
|
+
|
|
68
|
+
- `resolve(request) -> Promise<{ peer, path?, headers?, response? } | null>`: `peer` is the pod id the answer is pinned
|
|
69
|
+
to; `path` replaces the request's path (the query is kept); `headers` are added to what the provider is sent;
|
|
70
|
+
`response` is `{ contentSecurityPolicy, cacheControl, allowSetCookie }` to opt this mapping out of the response policy
|
|
71
|
+
(`nosniff` is not optional). `null` is a 404.
|
|
72
|
+
- `authorize(request, target) -> boolean`: anything but `true` is a 403. `deny(request) -> Response | true | null`: a
|
|
73
|
+
Response is sent as it is, `true` is a 451.
|
|
74
|
+
- `limits`: see Defaults. `verifyResponse({ peer, bytes, sig, request })`: signed responses (below).
|
|
75
|
+
- `rpc`: a `createMeshRpcService` api on the site service's envelope type; with it the ingress asks a provider that does
|
|
76
|
+
not serve `http` (it said so, or never answered the open) through one buffered mesh-rpc request, for a minute at a
|
|
77
|
+
time. Off by default: the older service has no default deny of its own. A provider that refused the open is never
|
|
78
|
+
asked this way.
|
|
79
|
+
- A hook never has to read the body: `resolve`, `authorize` and `deny` get the `Request` before it is read.
|
|
80
|
+
|
|
81
|
+
### The provider
|
|
82
|
+
|
|
83
|
+
```js
|
|
84
|
+
import { serveHttpOnMesh, fromSiteHandler } from '@johnhenry/browsermesh-ingress'
|
|
85
|
+
|
|
86
|
+
const served = serveHttpOnMesh(service, async (request, { peer, signal, client }) => new Response('hello'), {
|
|
87
|
+
allowFrom: [ingressPodId], // required: nothing is served to a pod that is not named
|
|
88
|
+
limits: { maxInflight: 16, maxRequestBodyBytes: 1024 * 1024, maxResponseBytes: 8 * 1024 * 1024, handlerTimeoutMs: 30_000 },
|
|
89
|
+
})
|
|
90
|
+
node.registry.grantCapabilities(ingressPodId, ['protocol:http:open']) // the registry grant is required too
|
|
91
|
+
// served.stop(); served.stats()
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`handler` is a function or `{ fetch }`. `peer` is the ingress pod, the channel's verified peer (never a header);
|
|
95
|
+
`signal` aborts when the client goes away or the deadline passes. `request.url` is `http://<the client's host><path>`.
|
|
96
|
+
A request body is read whole (bounded) before the handler runs, so it works in every browser; response bodies stream.
|
|
97
|
+
|
|
98
|
+
`fromSiteHandler(createSiteRequestHandler(siteConfig))` serves a serverless site (`browsermesh-apps`) over `http`
|
|
99
|
+
without rewriting it (wrap, not replace: the legacy service keeps working over mesh-rpc).
|
|
100
|
+
|
|
101
|
+
### Signed responses (optional)
|
|
102
|
+
|
|
103
|
+
`serveHttpOnMesh(..., { sign: async (bytes, { peer }) => signature })` and
|
|
104
|
+
`createMeshIngress({ verifyResponse: async ({ peer, bytes, sig }) => boolean })`. The signed bytes (`signedBytes()` in
|
|
105
|
+
the source) are the request's id and a fresh nonce, host, method and target, the status, the headers as the provider sent
|
|
106
|
+
them and the SHA-256 of the body; the provider buffers a signed response. A response with no signature, or one the hook
|
|
107
|
+
does not accept, is a 502 (`response-unsigned`, `response-signature-invalid`). The package chooses no cryptography.
|
|
108
|
+
|
|
109
|
+
## Defaults (each has a test)
|
|
110
|
+
|
|
111
|
+
| Rule | Default |
|
|
112
|
+
| --- | --- |
|
|
113
|
+
| Listener bind | `127.0.0.1` (`public: true` for anything else) |
|
|
114
|
+
| Methods | `GET`, `HEAD`; `methods` can add `POST PUT PATCH DELETE OPTIONS`; `CONNECT` and `TRACE` never |
|
|
115
|
+
| Request body | 64 KiB (`maxRequestBodyBytes`); over it is a 413; read in full before the provider is asked |
|
|
116
|
+
| Response | 8 MiB (`maxResponseBytes`); a declared length over it is refused before anything is sent |
|
|
117
|
+
| Whole request | 30 s (`timeoutMs`), 504 `provider-timeout` |
|
|
118
|
+
| Slow body / idle response | 10 s (`bodyIdleMs`, 408) / 15 s (`responseIdleMs`) between chunks |
|
|
119
|
+
| Headers / target | 64 headers, 16 KiB, 2048 characters |
|
|
120
|
+
| In flight | 64 total, 8 per client, 16 per provider (429 / 503, `Retry-After`) |
|
|
121
|
+
| Rate | 120 per client and 600 per provider, per minute |
|
|
122
|
+
| Request headers to the provider | `accept`, `accept-language`, `content-type`, conditional and `range` headers; `forwardHeaders` adds names. Never: hop-by-hop, `Host`, `Forwarded`, `X-Forwarded-*`, `Upgrade`, `Proxy-*`, `Expect`, `Content-Length` |
|
|
123
|
+
| Client address | the socket's; `trustProxy` (off) takes the entry the trusted proxy appended |
|
|
124
|
+
| Framing | `Transfer-Encoding` with `Content-Length`, a bad or repeated `Content-Length`, a body on GET/HEAD: 400 |
|
|
125
|
+
| Upgrade | 426: WebSocket is not bridged |
|
|
126
|
+
| Response headers | allow-list; `Set-Cookie`, `Content-Encoding`, HSTS, `Refresh`, CORS and unknown headers dropped |
|
|
127
|
+
| Forced | `Content-Security-Policy: default-src 'none'; sandbox`, `X-Content-Type-Options: nosniff`, `Cache-Control: no-store`, `Vary` |
|
|
128
|
+
| Redirects | never followed; a `Location` that is not a path on this origin is a 502 |
|
|
129
|
+
| Audit | pod, host, method, status, reason, bytes, duration; never query strings, paths or bodies |
|
|
130
|
+
|
|
131
|
+
## CLI
|
|
132
|
+
|
|
133
|
+
```
|
|
134
|
+
browsermesh-ingress --listen 127.0.0.1:8080 --signaling wss://signal.example \
|
|
135
|
+
--map app.example.test=<podId> [--map ...] [--allow-methods GET,HEAD,POST] [--max-body 64k] [--timeout 30s] \
|
|
136
|
+
[--auth bearer:<file>] [--identity <file>] [--config file.json]
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
It joins the mesh as a pod (its identity is kept in `--identity`, created at mode 0600 on first run; the printed pod id
|
|
140
|
+
is what a provider names in `allowFrom` and grants `protocol:http:open`), prints what it serves and where it listens, and
|
|
141
|
+
exits non-zero with one sentence on bad input (2) or when the node cannot start (1). `--listen` must be loopback unless
|
|
142
|
+
`--public` is given together with `--tls-terminated-in-front` (a statement that TLS is terminated in front of it).
|
|
143
|
+
`--map HOST[/PREFIX]=PODID` (a prefix is stripped; two different pods under one hostname are refused). `--auth
|
|
144
|
+
bearer:FILE` requires `Authorization: Bearer <token in FILE>` on every request. `--config` takes the same options in JSON.
|
|
145
|
+
Without `node-datachannel` the CLI cannot reach any pod and says so; the library works over any transport you attach a
|
|
146
|
+
protocol service to.
|
|
147
|
+
|
|
148
|
+
## What is not built
|
|
149
|
+
|
|
150
|
+
- WebSocket upgrades (426). A later bridge would map each upgrade onto `mesh-websocket` frames over a second protocol,
|
|
151
|
+
with the same pin, per-connection byte and idle limits and an explicit `Origin` policy.
|
|
152
|
+
- Routed (multi-hop) delivery: only direct links. Carrying `http` over routed messages would need `requireSealed` end to
|
|
153
|
+
end and the verified originator of each sealed message compared with the mapped pod.
|
|
154
|
+
- Streaming the client's request body to the provider while the client is still sending (it is read first, bounded).
|
|
155
|
+
- TLS, caching, compression, per-root authorisation on the provider (`http:<root>:<action>`).
|
|
156
|
+
|
|
157
|
+
## Wire
|
|
158
|
+
|
|
159
|
+
Protocol `http` v1 on a protocol channel: one channel request `fetch { rid, nonce, method, target, host, headers, body,
|
|
160
|
+
client? } -> { status, headers, body, sig? }`; bodies are protocol streams (`{ rid, kind: 'request' }` ingress to
|
|
161
|
+
provider, `{ rid, kind: 'response' }` opened by the provider before it answers). No new framing; a peer without the
|
|
162
|
+
protocol answers the open with `unknown-protocol` and is sent nothing else. Design: [`docs/design/http-ingress.md`](../../docs/design/http-ingress.md);
|
|
163
|
+
threat model: [`docs/security.md`](../../docs/security.md#http-ingress).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { main } from '../src/cli/run.mjs'
|
|
3
|
+
|
|
4
|
+
// `main` resolves with an exit code when it ends (bad input, `--help`) and with `null` once the listener is up:
|
|
5
|
+
// the open server then keeps the process alive until a signal ends it.
|
|
6
|
+
const code = await main(process.argv.slice(2), { env: process.env, stdout: process.stdout, stderr: process.stderr })
|
|
7
|
+
if (code !== null) process.exit(code)
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-ingress",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Real HTTP in, a mesh peer answers: a bounded request forwarder from an HTTP listener to the one BrowserMesh pod a mapping names, over a protocol channel",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.mjs",
|
|
9
|
+
"./node": "./src/node.mjs"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"browsermesh-ingress": "./bin/browsermesh-ingress.mjs"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src",
|
|
16
|
+
"bin",
|
|
17
|
+
"LICENSE",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"keywords": [
|
|
21
|
+
"http",
|
|
22
|
+
"ingress",
|
|
23
|
+
"gateway",
|
|
24
|
+
"mesh",
|
|
25
|
+
"webrtc",
|
|
26
|
+
"browser"
|
|
27
|
+
],
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "https://github.com/johnhenry/browsermesh",
|
|
32
|
+
"directory": "packages/browsermesh-ingress"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://opensource.johnhenry.me/browsermesh/",
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=26.0.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@johnhenry/browsermesh-apps": ">=0.21.0 <1.0.0"
|
|
40
|
+
},
|
|
41
|
+
"optionalDependencies": {
|
|
42
|
+
"@johnhenry/browsermesh-core": "^0.13.0",
|
|
43
|
+
"@johnhenry/browsermesh-discovery": "^0.4.0",
|
|
44
|
+
"@johnhenry/browsermesh-pod": "^0.5.0",
|
|
45
|
+
"@johnhenry/browsermesh-primitives": "^0.6.1",
|
|
46
|
+
"@johnhenry/browsermesh-transport": "^0.10.0",
|
|
47
|
+
"node-datachannel": "^0.33.4"
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/cli/args.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* args.mjs -- the CLI's input: flags and an optional JSON config, merged and checked. Pure: no I/O, no process.
|
|
3
|
+
*
|
|
4
|
+
* Every refusal is a `UsageError` whose message is one sentence the person who typed the command can act on.
|
|
5
|
+
*/
|
|
6
|
+
import { checkHost, isPodId } from '../headers.mjs'
|
|
7
|
+
import { isLoopbackHost } from '../node.mjs'
|
|
8
|
+
import { parseBytes, parseDuration } from '../limits.mjs'
|
|
9
|
+
|
|
10
|
+
export class UsageError extends Error {
|
|
11
|
+
constructor(message) { super(message); this.name = 'UsageError' }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const USAGE = `browsermesh-ingress: serve a mesh pod over HTTP
|
|
15
|
+
|
|
16
|
+
Usage:
|
|
17
|
+
browsermesh-ingress --signaling wss://signal.example --map app.example.test=<podId> [options]
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
--listen HOST:PORT where to listen (default 127.0.0.1:8080)
|
|
21
|
+
--signaling URL the signaling server the mesh node joins (wss://, or ws:// to loopback)
|
|
22
|
+
--map HOST[/PREFIX]=PODID serve this pod for this Host (repeatable); one pod per hostname
|
|
23
|
+
--allow-methods LIST methods served, comma separated (default GET,HEAD)
|
|
24
|
+
--max-body SIZE request body cap, e.g. 64k (default 64k)
|
|
25
|
+
--timeout DURATION whole-request deadline, e.g. 30s (default 30s)
|
|
26
|
+
--auth bearer:FILE require "Authorization: Bearer <the token in FILE>" on every request
|
|
27
|
+
--identity FILE the ingress's identity file (created on first run)
|
|
28
|
+
--config FILE a JSON file with the same options (flags win)
|
|
29
|
+
--public allow a listen address that is not loopback ...
|
|
30
|
+
--tls-terminated-in-front ... and state that TLS is terminated in front of this listener
|
|
31
|
+
--allow-shared-origin allow different pods under path mappings of one hostname (not recommended)
|
|
32
|
+
--help this text
|
|
33
|
+
|
|
34
|
+
The listener speaks plain HTTP. It binds to loopback unless you pass --public together with
|
|
35
|
+
--tls-terminated-in-front: there is no plaintext public default.
|
|
36
|
+
|
|
37
|
+
One origin per provider is your responsibility: two pods behind one hostname share cookies, storage and script
|
|
38
|
+
reach in a browser. Give each pod its own hostname.
|
|
39
|
+
|
|
40
|
+
Exit status: 0 after --help, 2 on bad input, 1 if the node cannot start.
|
|
41
|
+
`
|
|
42
|
+
|
|
43
|
+
const FLAGS = new Map([
|
|
44
|
+
['listen', 'value'], ['signaling', 'value'], ['map', 'list'], ['allow-methods', 'value'], ['max-body', 'value'], ['timeout', 'value'],
|
|
45
|
+
['auth', 'value'], ['identity', 'value'], ['config', 'value'], ['public', 'bool'], ['tls-terminated-in-front', 'bool'],
|
|
46
|
+
['allow-shared-origin', 'bool'], ['help', 'bool'],
|
|
47
|
+
])
|
|
48
|
+
|
|
49
|
+
/** @param {string[]} argv @returns {object} raw flags: `{ listen, map: [...], public: true, ... }` */
|
|
50
|
+
export function parseArgv(argv) {
|
|
51
|
+
const out = { map: [] }
|
|
52
|
+
for (let i = 0; i < argv.length; i++) {
|
|
53
|
+
const arg = argv[i]
|
|
54
|
+
if (arg === '-h') { out.help = true; continue }
|
|
55
|
+
if (!arg.startsWith('--')) throw new UsageError(`Unexpected argument "${arg}". Run with --help.`)
|
|
56
|
+
const eq = arg.indexOf('=')
|
|
57
|
+
const name = arg.slice(2, eq === -1 ? undefined : eq)
|
|
58
|
+
const kind = FLAGS.get(name)
|
|
59
|
+
if (!kind) throw new UsageError(`Unknown option --${name}. Run with --help.`)
|
|
60
|
+
if (kind === 'bool') {
|
|
61
|
+
if (eq !== -1) throw new UsageError(`--${name} takes no value.`)
|
|
62
|
+
out[name] = true
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
const value = eq !== -1 ? arg.slice(eq + 1) : argv[++i]
|
|
66
|
+
if (value === undefined || (eq === -1 && value.startsWith('--'))) throw new UsageError(`--${name} needs a value.`)
|
|
67
|
+
if (kind === 'list') out[name].push(value)
|
|
68
|
+
else {
|
|
69
|
+
if (name in out) throw new UsageError(`--${name} was given twice.`)
|
|
70
|
+
out[name] = value
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return out
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A config file's contents -> the same shape `parseArgv` makes. Unknown keys are refused: a typo must not be silently ignored. */
|
|
77
|
+
export function fromConfig(json) {
|
|
78
|
+
if (!json || typeof json !== 'object' || Array.isArray(json)) throw new UsageError('The config file must contain one JSON object.')
|
|
79
|
+
const out = { map: [] }
|
|
80
|
+
const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase())
|
|
81
|
+
const byCamel = new Map([...FLAGS.keys()].map((n) => [camel(n), n]))
|
|
82
|
+
for (const [key, value] of Object.entries(json)) {
|
|
83
|
+
const name = FLAGS.has(key) ? key : byCamel.get(key)
|
|
84
|
+
if (!name || name === 'config' || name === 'help') throw new UsageError(`The config file has an unknown key "${key}".`)
|
|
85
|
+
const kind = FLAGS.get(name)
|
|
86
|
+
if (name === 'map') {
|
|
87
|
+
if (Array.isArray(value)) out.map.push(...value.map(String))
|
|
88
|
+
else if (value && typeof value === 'object') for (const [host, pod] of Object.entries(value)) out.map.push(`${host}=${pod}`)
|
|
89
|
+
else throw new UsageError('"map" in the config file must be an object of host: podId, or a list of host=podId.')
|
|
90
|
+
} else if (kind === 'bool') out[name] = value === true
|
|
91
|
+
else out[name] = Array.isArray(value) ? value.join(',') : String(value)
|
|
92
|
+
}
|
|
93
|
+
return out
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Flags win over the config file; `map` entries of both are kept. */
|
|
97
|
+
export function merge(config, flags) {
|
|
98
|
+
const out = { ...config, ...flags, map: [...(config.map ?? []), ...(flags.map ?? [])] }
|
|
99
|
+
return out
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @returns {{ host: string, prefix: string, peer: string }} */
|
|
103
|
+
export function parseMapping(text) {
|
|
104
|
+
const eq = text.lastIndexOf('=')
|
|
105
|
+
if (eq <= 0 || eq === text.length - 1) throw new UsageError(`--map "${text}" is not HOST=PODID (or HOST/PREFIX=PODID).`)
|
|
106
|
+
const left = text.slice(0, eq)
|
|
107
|
+
const peer = text.slice(eq + 1)
|
|
108
|
+
if (!isPodId(peer)) throw new UsageError(`--map "${text}": "${peer}" is not a pod id.`)
|
|
109
|
+
const slash = left.indexOf('/')
|
|
110
|
+
const hostPart = slash === -1 ? left : left.slice(0, slash)
|
|
111
|
+
let prefix = slash === -1 ? '' : left.slice(slash)
|
|
112
|
+
let host
|
|
113
|
+
try { host = checkHost(hostPart) } catch { throw new UsageError(`--map "${text}": "${hostPart}" is not a hostname (with an optional port).`) }
|
|
114
|
+
if (prefix) {
|
|
115
|
+
prefix = prefix.replace(/\/+$/, '')
|
|
116
|
+
if (!/^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$/.test(prefix) || prefix.includes('//') || prefix.split('/').some((s) => s === '.' || s === '..')) {
|
|
117
|
+
throw new UsageError(`--map "${text}": "${left.slice(slash)}" is not a plain path prefix.`)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return { host, prefix, peer }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The checked configuration. `warnings` are sentences for stderr; nothing is read from disk here.
|
|
125
|
+
* @returns {{ host: string, port: number, signaling: string, mappings: object[], methods: string[], maxBody: number|undefined,
|
|
126
|
+
* timeoutMs: number|undefined, auth: { file: string }|null, identity: string|undefined, public: boolean, warnings: string[] }}
|
|
127
|
+
*/
|
|
128
|
+
export function resolveOptions(raw) {
|
|
129
|
+
const warnings = []
|
|
130
|
+
const listen = raw.listen ?? '127.0.0.1:8080'
|
|
131
|
+
const m = /^(?:\[([0-9a-fA-F:.]+)\]|([^:\s]+)):(\d{1,5})$/.exec(listen)
|
|
132
|
+
if (!m) throw new UsageError(`--listen "${listen}" is not HOST:PORT (for IPv6, [::1]:PORT).`)
|
|
133
|
+
const host = m[1] ?? m[2]
|
|
134
|
+
const port = Number(m[3])
|
|
135
|
+
if (port > 65535) throw new UsageError(`--listen "${listen}": the port is out of range.`)
|
|
136
|
+
const isPublic = !isLoopbackHost(host)
|
|
137
|
+
if (isPublic && !raw.public) throw new UsageError(`--listen ${host} is not a loopback address. Serving on a public address needs --public together with --tls-terminated-in-front: this listener speaks plain HTTP, so TLS must be terminated in front of it.`)
|
|
138
|
+
if (isPublic && !raw['tls-terminated-in-front']) throw new UsageError('--public needs --tls-terminated-in-front: state that TLS is terminated in front of this listener. There is no plaintext public default.')
|
|
139
|
+
if (!isPublic && raw.public) warnings.push('--public has no effect on a loopback listen address.')
|
|
140
|
+
|
|
141
|
+
if (!raw.signaling) throw new UsageError('--signaling URL is required: the mesh node needs a signaling server to find pods.')
|
|
142
|
+
let sig
|
|
143
|
+
try { sig = new URL(raw.signaling) } catch { throw new UsageError(`--signaling "${raw.signaling}" is not a URL.`) }
|
|
144
|
+
if (sig.protocol !== 'wss:' && !(sig.protocol === 'ws:' && isLoopbackHost(sig.hostname))) throw new UsageError('--signaling must be wss:// (ws:// is accepted only for a loopback server).')
|
|
145
|
+
|
|
146
|
+
if (!raw.map.length) throw new UsageError('At least one --map HOST=PODID is required: nothing is served without a mapping.')
|
|
147
|
+
const mappings = raw.map.map(parseMapping)
|
|
148
|
+
const seen = new Map() // host -> mappings
|
|
149
|
+
for (const mp of mappings) {
|
|
150
|
+
const list = seen.get(mp.host) ?? []
|
|
151
|
+
if (list.some((o) => o.prefix === mp.prefix)) throw new UsageError(`${mp.host}${mp.prefix} is mapped twice.`)
|
|
152
|
+
list.push(mp)
|
|
153
|
+
seen.set(mp.host, list)
|
|
154
|
+
}
|
|
155
|
+
for (const [hostName, list] of seen) {
|
|
156
|
+
const pods = new Set(list.map((o) => o.peer))
|
|
157
|
+
if (pods.size > 1 && !raw['allow-shared-origin']) {
|
|
158
|
+
throw new UsageError(`${hostName} is mapped to ${pods.size} different pods. One origin per provider: give each pod its own hostname (or pass --allow-shared-origin and accept that those pods can read each other's cookies and storage).`)
|
|
159
|
+
}
|
|
160
|
+
if (list.some((o) => o.prefix)) warnings.push(`warning: ${hostName} is served from more than one path mapping, so those mappings share one origin. One origin per provider is your responsibility.`)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const methods = (raw['allow-methods'] ?? 'GET,HEAD').split(',').map((s) => s.trim().toUpperCase()).filter(Boolean)
|
|
164
|
+
const known = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
|
|
165
|
+
if (!methods.length || methods.some((x) => !known.includes(x))) throw new UsageError(`--allow-methods must be a list of ${known.join(', ')}.`)
|
|
166
|
+
|
|
167
|
+
let maxBody, timeoutMs
|
|
168
|
+
try { if (raw['max-body'] !== undefined) maxBody = parseBytes(raw['max-body']) } catch { throw new UsageError(`--max-body "${raw['max-body']}" is not a size (for example 64k).`) }
|
|
169
|
+
try { if (raw.timeout !== undefined) timeoutMs = parseDuration(raw.timeout) } catch { throw new UsageError(`--timeout "${raw.timeout}" is not a duration (for example 30s).`) }
|
|
170
|
+
|
|
171
|
+
let auth = null
|
|
172
|
+
if (raw.auth !== undefined) {
|
|
173
|
+
const am = /^bearer:(.+)$/.exec(raw.auth)
|
|
174
|
+
if (!am) throw new UsageError('--auth must be bearer:FILE, where FILE holds the token.')
|
|
175
|
+
auth = { file: am[1] }
|
|
176
|
+
}
|
|
177
|
+
return { host, port, signaling: raw.signaling, mappings, methods, maxBody, timeoutMs, auth, identity: raw.identity, public: isPublic, warnings }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Hostname (+ prefix) -> pod, longest prefix first. A request whose Host is not mapped gets no mapping (404).
|
|
182
|
+
* With a prefix the provider is asked for the rest of the path.
|
|
183
|
+
*/
|
|
184
|
+
export function createResolver(mappings) {
|
|
185
|
+
const byHost = new Map()
|
|
186
|
+
for (const mp of mappings) { const l = byHost.get(mp.host) ?? []; l.push(mp); byHost.set(mp.host, l) }
|
|
187
|
+
for (const l of byHost.values()) l.sort((a, b) => b.prefix.length - a.prefix.length)
|
|
188
|
+
return (request) => {
|
|
189
|
+
const url = new URL(request.url)
|
|
190
|
+
const list = byHost.get(url.host)
|
|
191
|
+
if (!list) return null
|
|
192
|
+
for (const mp of list) {
|
|
193
|
+
if (!mp.prefix) return { peer: mp.peer }
|
|
194
|
+
if (url.pathname === mp.prefix || url.pathname.startsWith(`${mp.prefix}/`)) return { peer: mp.peer, path: url.pathname.slice(mp.prefix.length) || '/' }
|
|
195
|
+
}
|
|
196
|
+
return null
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mesh-node.mjs -- the CLI's own mesh node: a persisted identity, a signaling connection, WebRTC through
|
|
3
|
+
* `node-datachannel` (an optional dependency) and the protocol channel service the ingress opens `http` on.
|
|
4
|
+
*
|
|
5
|
+
* Without `node-datachannel` there is no WebRTC in Node, so there is nothing for this node to connect with and
|
|
6
|
+
* `startMeshNode` says so (the library still works over any other transport you attach a service to).
|
|
7
|
+
*/
|
|
8
|
+
import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
9
|
+
import { dirname } from 'node:path'
|
|
10
|
+
|
|
11
|
+
export class MeshStartError extends Error {
|
|
12
|
+
constructor(message) { super(message); this.name = 'MeshStartError' }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function readStored(path) {
|
|
16
|
+
let text
|
|
17
|
+
try { text = await readFile(path, 'utf8') } catch (e) { if (e.code === 'ENOENT') return null; throw e }
|
|
18
|
+
let json
|
|
19
|
+
try { json = JSON.parse(text) } catch { throw new MeshStartError(`The identity file ${path} is not valid JSON; refusing to overwrite it.`) }
|
|
20
|
+
if (!json?.privateKeyJwk) throw new MeshStartError(`The identity file ${path} has no key in it; refusing to overwrite it.`)
|
|
21
|
+
return json
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {object} opts
|
|
26
|
+
* @param {string} opts.signaling - signaling server URL
|
|
27
|
+
* @param {string} [opts.identityPath] - persisted identity (created, mode 0600, when missing); without it the identity is new each run
|
|
28
|
+
* @param {Function} [opts.onLog]
|
|
29
|
+
* @returns {Promise<{ podId: string, created: boolean, service: object, close(): Promise<void> }>}
|
|
30
|
+
*/
|
|
31
|
+
export async function startMeshNode({ signaling, identityPath, iceServers = [], connectTimeoutMs = 30_000, onLog = () => {} }) {
|
|
32
|
+
let ndc
|
|
33
|
+
try { ndc = await import('node-datachannel/polyfill') } catch {
|
|
34
|
+
throw new MeshStartError('WebRTC is not available: the optional dependency node-datachannel is not installed, so this node cannot connect to any pod. Install it (npm install node-datachannel) and run again.')
|
|
35
|
+
}
|
|
36
|
+
Object.assign(globalThis, { RTCPeerConnection: ndc.RTCPeerConnection, RTCIceCandidate: ndc.RTCIceCandidate, RTCSessionDescription: ndc.RTCSessionDescription })
|
|
37
|
+
let apps, core, pod
|
|
38
|
+
try {
|
|
39
|
+
;[apps, core, pod] = await Promise.all([import('@johnhenry/browsermesh-apps'), import('@johnhenry/browsermesh-core'), import('@johnhenry/browsermesh-pod')])
|
|
40
|
+
} catch (e) {
|
|
41
|
+
throw new MeshStartError(`A BrowserMesh package the CLI needs could not be loaded (${e.message}). Install @johnhenry/browsermesh-apps, -core, -pod, -primitives, -transport and -discovery next to this package.`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// An identity that is created once and reused: `createMeshNode` creates one through `identityManager.create`, so the
|
|
45
|
+
// manager hands back the persisted one when it has it.
|
|
46
|
+
class StableIdentityManager extends core.MeshIdentityManager {
|
|
47
|
+
#pending = null
|
|
48
|
+
adopt(summary) { this.#pending = summary }
|
|
49
|
+
async create(label, opts) {
|
|
50
|
+
if (this.#pending) { const s = this.#pending; this.#pending = null; return s }
|
|
51
|
+
return super.create(label, opts)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const identityManager = new StableIdentityManager({})
|
|
55
|
+
let summary
|
|
56
|
+
let created = false
|
|
57
|
+
const stored = identityPath ? await readStored(identityPath) : null
|
|
58
|
+
if (stored) summary = await identityManager.import(stored.privateKeyJwk, stored.label || 'ingress')
|
|
59
|
+
else {
|
|
60
|
+
summary = await identityManager.create('ingress')
|
|
61
|
+
created = true
|
|
62
|
+
if (identityPath) {
|
|
63
|
+
await mkdir(dirname(identityPath), { recursive: true })
|
|
64
|
+
await writeFile(identityPath, `${JSON.stringify({ podId: summary.podId, label: 'ingress', privateKeyJwk: await identityManager.export(summary.podId) }, null, 2)}\n`, { mode: 0o600 })
|
|
65
|
+
await chmod(identityPath, 0o600)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
identityManager.adopt(summary)
|
|
69
|
+
const podId = summary.podId
|
|
70
|
+
|
|
71
|
+
const signalingTransport = new pod.WebSocketTransport({
|
|
72
|
+
url: signaling,
|
|
73
|
+
podId,
|
|
74
|
+
protocol: 'signaling',
|
|
75
|
+
identity: { podId, rawPublicKey: () => identityManager.getPublicKeyBytes(podId), sign: (data) => identityManager.sign(podId, data) },
|
|
76
|
+
authentication: 'auto',
|
|
77
|
+
onLog,
|
|
78
|
+
})
|
|
79
|
+
await signalingTransport.open?.()
|
|
80
|
+
const node = await apps.createMeshNode({
|
|
81
|
+
label: 'ingress',
|
|
82
|
+
identityManager,
|
|
83
|
+
signalingTransport,
|
|
84
|
+
discoveryStrategies: [],
|
|
85
|
+
skipDiscovery: true,
|
|
86
|
+
iceServers,
|
|
87
|
+
onLog,
|
|
88
|
+
})
|
|
89
|
+
if (node.podId !== podId) throw new MeshStartError('The mesh node did not take the stored identity; refusing to run under another pod id.')
|
|
90
|
+
const protocols = apps.attachService(node, undefined, apps.createMeshProtocolService())
|
|
91
|
+
|
|
92
|
+
// The mesh channel needs a session with the peer: connect to a pod the first time it is wanted (and only the
|
|
93
|
+
// pods a mapping names ever get here), once at a time per pod.
|
|
94
|
+
const connecting = new Map()
|
|
95
|
+
const ensureConnected = (peer) => {
|
|
96
|
+
if (node.hasActiveSession(peer)) return Promise.resolve()
|
|
97
|
+
let p = connecting.get(peer)
|
|
98
|
+
if (!p) {
|
|
99
|
+
p = node.connectToPeer(peer, { webrtc: peer }, { answerTimeoutMs: connectTimeoutMs, openTimeoutMs: connectTimeoutMs }).finally(() => connecting.delete(peer))
|
|
100
|
+
connecting.set(peer, p)
|
|
101
|
+
}
|
|
102
|
+
return p
|
|
103
|
+
}
|
|
104
|
+
const service = {
|
|
105
|
+
api: {
|
|
106
|
+
...protocols.api,
|
|
107
|
+
async openProtocol(peer, name, opts) {
|
|
108
|
+
await ensureConnected(peer)
|
|
109
|
+
return protocols.api.openProtocol(peer, name, opts)
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
podId,
|
|
115
|
+
created,
|
|
116
|
+
service,
|
|
117
|
+
node,
|
|
118
|
+
async close() {
|
|
119
|
+
try { await protocols.teardown?.() } catch { /* gone */ }
|
|
120
|
+
try { await node.shutdown() } catch { /* gone */ }
|
|
121
|
+
try { await signalingTransport.close?.() } catch { /* gone */ }
|
|
122
|
+
try { ndc && (await import('node-datachannel')).cleanup?.() } catch { /* nothing to clean up */ }
|
|
123
|
+
},
|
|
124
|
+
}
|
|
125
|
+
}
|