@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.
@@ -0,0 +1,108 @@
1
+ /**
2
+ * run.mjs -- `browsermesh-ingress`: parse, check, start the mesh node, start the listener, say what it serves.
3
+ *
4
+ * `main` returns an exit code when the process should end (`--help`, bad input, a node that cannot start) and
5
+ * `null` once the listener is up, so the open server keeps the process alive.
6
+ */
7
+ import { createHash, timingSafeEqual } from 'node:crypto'
8
+ import { readFile } from 'node:fs/promises'
9
+ import { createMeshIngress } from '../ingress.mjs'
10
+ import { applyForcedHeaders } from '../headers.mjs'
11
+ import { listenNode } from '../node.mjs'
12
+ import { UsageError, USAGE, createResolver, fromConfig, merge, parseArgv, resolveOptions } from './args.mjs'
13
+ import { MeshStartError, startMeshNode } from './mesh-node.mjs'
14
+
15
+ const digest = (s) => createHash('sha256').update(s).digest()
16
+
17
+ export function bearerDeny(token) {
18
+ const wanted = digest(`Bearer ${token}`)
19
+ return (request) => {
20
+ const given = request.headers.get('authorization')
21
+ if (given !== null && timingSafeEqual(digest(given), wanted)) return null
22
+ const headers = new Headers({ 'content-type': 'text/plain; charset=utf-8', 'www-authenticate': 'Bearer' })
23
+ applyForcedHeaders(headers)
24
+ return new Response('A bearer token is required.\n', { status: 401, headers })
25
+ }
26
+ }
27
+
28
+ /**
29
+ * @param {string[]} argv
30
+ * @param {{ env?: object, stdout: { write(s: string): any }, stderr: { write(s: string): any }, startNode?: Function, process?: object }} io
31
+ * @returns {Promise<number|null>}
32
+ */
33
+ export async function main(argv, { stdout, stderr, startNode = startMeshNode, process: proc = process } = {}) {
34
+ const say = (s) => stdout.write(`${s}\n`)
35
+ const warn = (s) => stderr.write(`${s}\n`)
36
+ let options
37
+ let token = null
38
+ try {
39
+ const flags = parseArgv(argv)
40
+ if (flags.help) { stdout.write(USAGE); return 0 }
41
+ let config = { map: [] }
42
+ if (flags.config) {
43
+ let text
44
+ try { text = await readFile(flags.config, 'utf8') } catch (e) { throw new UsageError(`Cannot read the config file ${flags.config}: ${e.code ?? e.message}.`) }
45
+ let json
46
+ try { json = JSON.parse(text) } catch { throw new UsageError(`The config file ${flags.config} is not valid JSON.`) }
47
+ config = fromConfig(json)
48
+ }
49
+ options = resolveOptions(merge(config, flags))
50
+ if (options.auth) {
51
+ let text
52
+ try { text = await readFile(options.auth.file, 'utf8') } catch (e) { throw new UsageError(`Cannot read the token file ${options.auth.file}: ${e.code ?? e.message}.`) }
53
+ token = text.trim()
54
+ if (token.length < 16 || /\s/.test(token)) throw new UsageError(`The token in ${options.auth.file} must be one word of at least 16 characters.`)
55
+ }
56
+ } catch (e) {
57
+ if (e instanceof UsageError) { warn(`browsermesh-ingress: ${e.message}`); return 2 }
58
+ throw e
59
+ }
60
+ for (const w of options.warnings) warn(`browsermesh-ingress: ${w}`)
61
+
62
+ let mesh
63
+ try {
64
+ mesh = await startNode({ signaling: options.signaling, identityPath: options.identity })
65
+ } catch (e) {
66
+ warn(`browsermesh-ingress: cannot start the mesh node: ${e instanceof MeshStartError ? e.message : (e?.message ?? e)}`)
67
+ return 1
68
+ }
69
+
70
+ const limits = {}
71
+ if (options.maxBody) limits.maxRequestBodyBytes = options.maxBody
72
+ if (options.timeoutMs) limits.timeoutMs = options.timeoutMs
73
+ const ingress = createMeshIngress({
74
+ service: mesh.service,
75
+ resolve: createResolver(options.mappings),
76
+ methods: options.methods,
77
+ limits,
78
+ deny: token ? bearerDeny(token) : undefined,
79
+ onAudit: (r) => say(`${r.method} ${r.host} -> ${r.peer ?? '-'} ${r.status}${r.reason ? ` (${r.reason})` : ''} in ${r.requestBytes}B out ${r.responseBytes}B ${r.durationMs}ms`),
80
+ })
81
+ let listener
82
+ try {
83
+ listener = await listenNode(ingress, { host: options.host, port: options.port, public: options.public, trustProxy: false })
84
+ } catch (e) {
85
+ await ingress.close()
86
+ await mesh.close()
87
+ warn(`browsermesh-ingress: cannot listen on ${options.host}:${options.port}: ${e?.code ?? e?.message}`)
88
+ return 1
89
+ }
90
+
91
+ say(`browsermesh-ingress pod id: ${mesh.podId}${mesh.created ? ' (new identity)' : ''}`)
92
+ for (const mp of options.mappings) say(`serving ${mp.host}${mp.prefix} -> ${mp.peer}`)
93
+ say(`methods: ${options.methods.join(', ')}; body cap ${limits.maxRequestBodyBytes ?? 65536} bytes; auth: ${token ? 'bearer token required' : 'none'}`)
94
+ say(`listening on http://${options.host.includes(':') ? `[${options.host}]` : options.host}:${listener.port}`)
95
+
96
+ let stopping = false
97
+ const stop = async () => {
98
+ if (stopping) return
99
+ stopping = true
100
+ await listener.close()
101
+ await ingress.close()
102
+ await mesh.close()
103
+ proc.exit?.(0)
104
+ }
105
+ proc.once?.('SIGINT', stop)
106
+ proc.once?.('SIGTERM', stop)
107
+ return null
108
+ }
package/src/errors.mjs ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * A refusal with a status and a named reason. The reason is a short machine-readable word (it is sent to the HTTP
3
+ * client in a header and in the audit record); the message is one plain sentence.
4
+ */
5
+ export class IngressError extends Error {
6
+ /**
7
+ * @param {number} status - the HTTP status this becomes
8
+ * @param {string} reason - `provider-pin-mismatch`, `response-too-large`, ...
9
+ * @param {string} [message]
10
+ * @param {object} [extra] - `{ headers }` to add to the HTTP response
11
+ */
12
+ constructor(status, reason, message, extra = {}) {
13
+ super(message || reason)
14
+ this.name = 'IngressError'
15
+ this.status = status
16
+ this.reason = reason
17
+ this.headers = extra.headers
18
+ }
19
+ }
20
+
21
+ export const REASON_HEADER = 'x-browsermesh-ingress-reason'
@@ -0,0 +1,201 @@
1
+ /**
2
+ * headers.mjs -- every header rule of the ingress, in one place, as pure functions.
3
+ *
4
+ * Nothing here touches the network. Lists are plain arrays of `[name, value]` pairs (the wire form) or web
5
+ * `Headers` objects (the HTTP side).
6
+ */
7
+ import { IngressError } from './errors.mjs'
8
+
9
+ const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
10
+ // eslint-disable-next-line no-control-regex
11
+ const BAD_VALUE = /[\u0000-\u0008\u000a-\u001f\u007f]/
12
+ const HOST_RE = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::\d{1,5})?$/
13
+ const IPV6_HOST_RE = /^\[[0-9a-f:.]{2,45}\](?::\d{1,5})?$/
14
+
15
+ /** Request headers a client may pass to the provider unless the operator widens the list. */
16
+ export const DEFAULT_FORWARD_REQUEST_HEADERS = Object.freeze([
17
+ 'accept', 'accept-language', 'content-type', 'if-match', 'if-modified-since', 'if-none-match', 'if-unmodified-since', 'range',
18
+ ])
19
+
20
+ /** Request headers that are never taken from a client and never sent to a provider, whatever the operator allows. */
21
+ export const NEVER_FORWARD_REQUEST = new Set([
22
+ 'host', 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer',
23
+ 'transfer-encoding', 'upgrade', 'content-length', 'expect', 'forwarded', 'x-real-ip', 'via', 'x-forwarded-for',
24
+ 'x-forwarded-host', 'x-forwarded-proto', 'x-forwarded-port', 'x-forwarded-server', 'x-original-url', 'x-rewrite-url',
25
+ ])
26
+ const isNeverForward = (name) => NEVER_FORWARD_REQUEST.has(name) || name.startsWith('proxy-') || name.startsWith('x-forwarded-')
27
+
28
+ /** Response headers a provider may set. Everything else is dropped. */
29
+ export const DEFAULT_PASS_RESPONSE_HEADERS = Object.freeze([
30
+ 'content-type', 'content-length', 'content-language', 'content-disposition', 'content-range', 'accept-ranges',
31
+ 'etag', 'last-modified', 'location', 'vary', 'retry-after', 'allow',
32
+ ])
33
+
34
+ export const DEFAULT_CSP = "default-src 'none'; sandbox"
35
+
36
+ /** Statuses that carry no body. */
37
+ export const NO_BODY_STATUS = new Set([204, 205, 304])
38
+
39
+ export const isToken = (s) => typeof s === 'string' && s.length > 0 && s.length <= 128 && TOKEN.test(s)
40
+ export const isValue = (s) => typeof s === 'string' && s.length <= 8192 && !BAD_VALUE.test(s)
41
+
42
+ const utf8 = new TextEncoder()
43
+ export const byteLength = (s) => utf8.encode(s).byteLength
44
+
45
+ /** Does this look like a pod id a mapping may name? (no scope syntax, no whitespace, bounded). */
46
+ export const isPodId = (s) => typeof s === 'string' && /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/.test(s)
47
+
48
+ /**
49
+ * The Host a client used, validated: a lower-case hostname (or bracketed IPv6) with an optional port; no userinfo,
50
+ * path or whitespace.
51
+ * @returns {string} normalised, or throws IngressError 400 `bad-host`
52
+ */
53
+ export function checkHost(host) {
54
+ const h = typeof host === 'string' ? host.trim().toLowerCase() : ''
55
+ if (!h || h.length > 261 || !(HOST_RE.test(h) || IPV6_HOST_RE.test(h))) throw new IngressError(400, 'bad-host', 'The Host is not a plain hostname with an optional port.')
56
+ return h
57
+ }
58
+
59
+ /** Only the hostname of a validated host (no port). */
60
+ export function hostName(host) {
61
+ if (host.startsWith('[')) return host.slice(0, host.indexOf(']') + 1)
62
+ const i = host.lastIndexOf(':')
63
+ return i === -1 ? host : host.slice(0, i)
64
+ }
65
+
66
+ /**
67
+ * The target of a request (path and query) in origin form: starts with one `/`, no backslash, no control or
68
+ * whitespace character, bounded. A peer or a client never supplies more than this.
69
+ * @returns {string}
70
+ */
71
+ export function checkTarget(target, maxLength = 2048) {
72
+ if (typeof target !== 'string' || !target.startsWith('/') || target.startsWith('//')) throw new IngressError(400, 'bad-target', 'The request target must be a path.')
73
+ if (target.length > maxLength) throw new IngressError(414, 'target-too-long', `The request target is longer than ${maxLength} characters.`)
74
+ // eslint-disable-next-line no-control-regex
75
+ if (/[\u0000- \u007f-\u009f\\]/.test(target)) throw new IngressError(400, 'bad-target', 'The request target contains a character that is not allowed.')
76
+ return target
77
+ }
78
+
79
+ /** Path of a mapping (`resolve`'s `path`): origin form, no query, no dot segments. */
80
+ export function checkMappedPath(path) {
81
+ try { checkTarget(path) } catch { throw new IngressError(500, 'bad-mapping', 'A mapping named an invalid path.') }
82
+ if (path.includes('?') || path.includes('#') || path.split('/').some((s) => s === '.' || s === '..')) throw new IngressError(500, 'bad-mapping', 'A mapping named an invalid path.')
83
+ return path
84
+ }
85
+
86
+ /**
87
+ * Shape rules for a header list in either direction: counted, bounded, tokens for names, no control characters.
88
+ * @param {Array<[string, string]>} list
89
+ */
90
+ export function checkHeaderList(list, { maxCount, maxBytes, status = 400, reason = 'bad-headers' }) {
91
+ if (!Array.isArray(list) || list.length > maxCount) throw new IngressError(status, reason, 'Too many headers.')
92
+ let bytes = 0
93
+ for (const pair of list) {
94
+ if (!Array.isArray(pair) || pair.length !== 2 || !isToken(pair[0]) || !isValue(pair[1])) throw new IngressError(status, reason, 'A header is malformed.')
95
+ bytes += byteLength(pair[0]) + byteLength(pair[1]) + 4
96
+ if (bytes > maxBytes) throw new IngressError(status, reason, 'The headers are too large.')
97
+ }
98
+ return list
99
+ }
100
+
101
+ /** @param {Headers} headers @returns {Array<[string,string]>} */
102
+ export function listOf(headers) {
103
+ const out = []
104
+ for (const [name, value] of headers) out.push([name, value])
105
+ return out
106
+ }
107
+
108
+ /**
109
+ * Client headers -> what the provider is sent. Only allow-listed names; never a name on the never-list; the
110
+ * operator's own headers (`extra`, from `resolve`) are added last and may not be on the never-list either.
111
+ * @param {Headers} headers
112
+ * @param {{ forward?: string[], extra?: Record<string,string> }} opts
113
+ * @returns {Array<[string,string]>}
114
+ */
115
+ export function requestHeadersForProvider(headers, { forward = [], extra } = {}) {
116
+ const allowed = new Set([...DEFAULT_FORWARD_REQUEST_HEADERS, ...forward.map((n) => String(n).toLowerCase())].filter((n) => !isNeverForward(n)))
117
+ const out = []
118
+ for (const [name, value] of headers) if (allowed.has(name) && isValue(value)) out.push([name, value])
119
+ for (const [rawName, value] of Object.entries(extra ?? {})) {
120
+ const name = String(rawName).toLowerCase()
121
+ if (!isToken(name) || isNeverForward(name) || !isValue(String(value))) throw new IngressError(500, 'bad-mapping', 'A mapping named a header that may not be sent.')
122
+ for (let i = out.length - 1; i >= 0; i--) if (out[i][0] === name) out.splice(i, 1)
123
+ out.push([name, String(value)])
124
+ }
125
+ return out
126
+ }
127
+
128
+ /** Names the ingress will list in `Vary`: the request headers it forwards (they change what the provider answers). */
129
+ export function varyNames(forward = []) {
130
+ return [...new Set([...DEFAULT_FORWARD_REQUEST_HEADERS, ...forward.map((n) => String(n).toLowerCase())].filter((n) => !isNeverForward(n) && !['content-type'].includes(n)))]
131
+ }
132
+
133
+ /**
134
+ * A client's request, checked for the shapes request smuggling and header abuse use. Throws `IngressError`.
135
+ * @param {Headers} headers
136
+ * @param {string} method
137
+ */
138
+ export function checkClientRequestShape(headers, method, { maxCount, maxBytes }) {
139
+ let count = 0
140
+ let bytes = 0
141
+ for (const [name, value] of headers) {
142
+ count += 1
143
+ bytes += byteLength(name) + byteLength(value) + 4
144
+ if (count > maxCount || bytes > maxBytes) throw new IngressError(431, 'headers-too-large', 'The request headers are too large.')
145
+ if (!isValue(value)) throw new IngressError(400, 'bad-header-value', 'A request header has a character that is not allowed.')
146
+ }
147
+ const te = headers.get('transfer-encoding')
148
+ const cl = headers.get('content-length')
149
+ if (te !== null && cl !== null) throw new IngressError(400, 'bad-framing', 'Transfer-Encoding and Content-Length together are refused.')
150
+ if (te !== null && !/^\s*chunked\s*$/i.test(te)) throw new IngressError(400, 'bad-framing', 'Only the chunked transfer coding is accepted.')
151
+ if (cl !== null && (!/^\d{1,15}$/.test(cl.trim()))) throw new IngressError(400, 'bad-framing', 'Content-Length must be one number.')
152
+ if ((method === 'GET' || method === 'HEAD') && ((cl !== null && Number(cl) > 0) || te !== null)) throw new IngressError(400, 'body-on-get', 'A GET or HEAD request may not carry a body.')
153
+ return { contentLength: cl === null ? null : Number(cl.trim()), chunked: te !== null }
154
+ }
155
+
156
+ /** Is this a Location the ingress may pass on? Only an absolute path on the same origin; never another origin or scheme. */
157
+ export function safeLocation(value) {
158
+ return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') && !/[\\\u0000-\u001f\u007f]/.test(value)
159
+ }
160
+
161
+ /**
162
+ * A provider's response head -> the headers the HTTP client gets.
163
+ * @param {Array<[string,string]>} list - already shape-checked
164
+ * @param {{ response?: object, forward?: string[], expose?: string[] }} opts
165
+ * @returns {Headers}
166
+ */
167
+ export function responseHeadersForClient(list, { response = {}, forward = [], expose = [] } = {}) {
168
+ const pass = new Set([...DEFAULT_PASS_RESPONSE_HEADERS, ...expose.map((n) => String(n).toLowerCase())])
169
+ if (response.allowSetCookie === true) pass.add('set-cookie')
170
+ const out = new Headers()
171
+ const vary = new Set(varyNames(forward))
172
+ for (const [name, value] of list) {
173
+ const lower = name.toLowerCase()
174
+ if (lower === 'content-encoding') {
175
+ if (value.trim().toLowerCase() !== 'identity') throw new IngressError(502, 'bad-content-encoding', 'The provider sent a content coding the ingress did not negotiate.')
176
+ continue
177
+ }
178
+ if (lower === 'location' && !safeLocation(value)) throw new IngressError(502, 'provider-redirect-refused', 'The provider redirected somewhere other than a path on this origin; redirects are never followed.')
179
+ if (lower === 'vary') { for (const v of value.split(',')) if (v.trim()) vary.add(v.trim().toLowerCase()); continue }
180
+ if (!pass.has(lower)) continue
181
+ if (lower === 'set-cookie') out.append(name, value)
182
+ else if (out.has(lower) && lower !== 'allow') continue // one value for a singleton
183
+ else out.set(lower, value)
184
+ }
185
+ if (vary.has('*')) out.set('vary', '*')
186
+ else if (vary.size) out.set('vary', [...vary].join(', '))
187
+ applyForcedHeaders(out, response)
188
+ return out
189
+ }
190
+
191
+ /** Headers every response the ingress sends carries, unless a mapping opted out. */
192
+ export function applyForcedHeaders(headers, response = {}) {
193
+ const csp = response.contentSecurityPolicy
194
+ if (csp === false) headers.delete('content-security-policy')
195
+ else headers.set('content-security-policy', typeof csp === 'string' && csp ? csp : DEFAULT_CSP)
196
+ headers.set('x-content-type-options', 'nosniff')
197
+ const cache = response.cacheControl
198
+ if (cache === false) headers.delete('cache-control')
199
+ else headers.set('cache-control', typeof cache === 'string' && cache ? cache : 'no-store')
200
+ return headers
201
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @johnhenry/browsermesh-ingress -- real HTTP in, a mesh peer answers.
3
+ *
4
+ * ingress: createMeshIngress({ service | node, resolve, ... }) -> { handle(Request): Promise<Response>, stats(), close() }
5
+ * provider: serveHttpOnMesh(service, handler | { fetch }, { allowFrom, limits })
6
+ * Node: import { listenNode } from '@johnhenry/browsermesh-ingress/node'
7
+ *
8
+ * This entry imports no `node:` module (a test asserts it).
9
+ */
10
+ export { createMeshIngress } from './ingress.mjs'
11
+ export { serveHttpOnMesh, fromSiteHandler, PROVIDER_LIMIT_DEFAULTS } from './provider.mjs'
12
+ export { INGRESS_LIMIT_DEFAULTS, parseBytes, parseDuration } from './limits.mjs'
13
+ export { IngressError, REASON_HEADER } from './errors.mjs'
14
+ export { DEFAULT_CSP, DEFAULT_FORWARD_REQUEST_HEADERS, DEFAULT_PASS_RESPONSE_HEADERS } from './headers.mjs'
15
+ export { HTTP_PROTOCOL, HTTP_VERSIONS, signedBytes } from './wire.mjs'