@johnhenry/browsermesh-ingress 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/node.mjs ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * node.mjs -- a Node HTTP/1.1 listener for a `createMeshIngress` handler. The only entry of this package that
3
+ * imports `node:` modules.
4
+ *
5
+ * Plain HTTP only: terminate TLS in front (a reverse proxy or a platform). Binds to loopback unless `public: true`.
6
+ */
7
+ import http from 'node:http'
8
+ import { isIP } from 'node:net'
9
+ import { Readable } from 'node:stream'
10
+ import { IngressError, REASON_HEADER } from './errors.mjs'
11
+ import { applyForcedHeaders, checkHost } from './headers.mjs'
12
+
13
+ const BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
14
+
15
+ export function isLoopbackHost(host) {
16
+ const h = String(host).toLowerCase().replace(/^\[|\]$/g, '')
17
+ return h === 'localhost' || h === '::1' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)
18
+ }
19
+
20
+ /**
21
+ * The client address: the socket's, unless `trustProxy` says exactly how many trusted proxies are in front
22
+ * (`true` is one): then the entry that many places from the right of `X-Forwarded-For`, which is the one the
23
+ * outermost trusted proxy appended. Entries to its left are the client's own claim and are never used.
24
+ * An entry that is not an IP address is ignored in favour of the socket's.
25
+ */
26
+ export function clientAddressOf(socketAddress, xForwardedFor, trustProxy) {
27
+ const hops = trustProxy === true ? 1 : Number.isInteger(trustProxy) && trustProxy > 0 ? trustProxy : 0
28
+ if (!hops || typeof xForwardedFor !== 'string') return socketAddress ?? 'unknown'
29
+ const entries = xForwardedFor.split(',').map((s) => s.trim()).filter(Boolean)
30
+ const candidate = entries[entries.length - hops]
31
+ return candidate && isIP(candidate) ? candidate : (socketAddress ?? 'unknown')
32
+ }
33
+
34
+ /**
35
+ * @param {{ handle(request: Request, info?: object): Promise<Response> }} ingress
36
+ * @param {object} [opts]
37
+ * @param {number} [opts.port=0]
38
+ * @param {string} [opts.host='127.0.0.1']
39
+ * @param {boolean} [opts.public=false] - required to bind anything but loopback: the caller states it has put TLS in front
40
+ * @param {boolean|number} [opts.trustProxy=false]
41
+ * @param {number} [opts.maxConnections=256]
42
+ * @returns {Promise<{ port: number, host: string, close(): Promise<void>, server: http.Server }>}
43
+ */
44
+ export async function listenNode(ingress, { port = 0, host = '127.0.0.1', public: isPublic = false, trustProxy = false, maxConnections = 256, maxHeaderBytes = 16 * 1024, headersTimeoutMs = 10_000, requestTimeoutMs = 60_000 } = {}) {
45
+ if (!ingress || typeof ingress.handle !== 'function') throw new TypeError('listenNode: an ingress with handle() is required')
46
+ if (!isLoopbackHost(host) && isPublic !== true) throw new Error(`listenNode: ${host} is not a loopback address; pass public: true once TLS is terminated in front of this listener`)
47
+ const server = http.createServer({ maxHeaderSize: maxHeaderBytes, insecureHTTPParser: false, requestTimeout: requestTimeoutMs, headersTimeout: headersTimeoutMs, keepAliveTimeout: 5000, connectionsCheckingInterval: Math.min(5000, headersTimeoutMs) }, (req, res) => {
48
+ serve(ingress, req, res, trustProxy).catch(() => { if (!res.headersSent) fail(res, new IngressError(500, 'internal-error', 'The ingress failed.')); else res.destroy() })
49
+ })
50
+ server.maxConnections = maxConnections
51
+ server.on('clientError', (err, socket) => {
52
+ const line = err?.code === 'HPE_HEADER_OVERFLOW' ? '431 Request Header Fields Too Large' : err?.code === 'ERR_HTTP_REQUEST_TIMEOUT' ? '408 Request Timeout' : '400 Bad Request'
53
+ if (socket.writable) socket.end(`HTTP/1.1 ${line}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
54
+ else socket.destroy()
55
+ })
56
+ // An Upgrade is answered by the handler (426); a CONNECT is not served at all.
57
+ server.on('connect', (_req, socket) => socket.end('HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'))
58
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, () => { server.off('error', reject); resolve() }) })
59
+ const address = server.address()
60
+ return {
61
+ port: address.port,
62
+ host,
63
+ server,
64
+ close() {
65
+ return new Promise((resolve) => { server.close(() => resolve()); server.closeAllConnections() })
66
+ },
67
+ }
68
+ }
69
+
70
+ function fail(res, e) {
71
+ const headers = new Headers({ 'content-type': 'text/plain; charset=utf-8', [REASON_HEADER]: e.reason })
72
+ applyForcedHeaders(headers)
73
+ const body = `${e.message}\n`
74
+ res.writeHead(e.status, { ...Object.fromEntries(headers), 'content-length': Buffer.byteLength(body), connection: 'close' })
75
+ res.end(body)
76
+ }
77
+
78
+ async function serve(ingress, req, res, trustProxy) {
79
+ // The Host header is checked as sent: a URL parser would read `a@b` as host b.
80
+ const hostHeaders = []
81
+ const raw = req.rawHeaders
82
+ for (let i = 0; i < raw.length; i += 2) if (raw[i].toLowerCase() === 'host') hostHeaders.push(raw[i + 1])
83
+ if (hostHeaders.length !== 1) return fail(res, new IngressError(400, 'bad-host', 'Exactly one Host header is required.'))
84
+ let host
85
+ try { host = checkHost(hostHeaders[0]) } catch (e) { return fail(res, e) }
86
+ const target = req.url ?? ''
87
+ // Origin-form only: an absolute-form target (`GET http://elsewhere/`) names a URL the client chose, and is refused.
88
+ if (!target.startsWith('/') || target.startsWith('//')) return fail(res, new IngressError(400, 'bad-target', 'The request target must be a path.'))
89
+ let url
90
+ try { url = new URL(`http://${host}${target}`) } catch { return fail(res, new IngressError(400, 'bad-target', 'The request target is not valid.')) }
91
+ if (url.host !== host.replace(/:80$/, '')) return fail(res, new IngressError(400, 'bad-target', 'The request target is not valid.'))
92
+
93
+ const headers = new Headers()
94
+ try {
95
+ for (let i = 0; i < raw.length; i += 2) {
96
+ const name = raw[i].toLowerCase()
97
+ if (name === 'host') continue
98
+ headers.append(name, raw[i + 1])
99
+ }
100
+ } catch { return fail(res, new IngressError(400, 'bad-headers', 'A header is not valid.')) }
101
+
102
+ const ac = new AbortController()
103
+ res.on('close', () => { if (!res.writableFinished) ac.abort() })
104
+ const method = req.method ?? 'GET'
105
+ const hasBody = BODY_METHODS.has(method) && (headers.has('content-length') ? headers.get('content-length') !== '0' : headers.has('transfer-encoding'))
106
+ let request
107
+ try {
108
+ request = new Request(url, { method, headers, signal: ac.signal, ...(hasBody ? { body: Readable.toWeb(req), duplex: 'half' } : {}) })
109
+ } catch { return fail(res, new IngressError(400, 'bad-request', 'The request is not valid.')) }
110
+
111
+ const clientAddress = clientAddressOf(req.socket.remoteAddress, headers.get('x-forwarded-for') ?? undefined, trustProxy)
112
+ const response = await ingress.handle(request, { clientAddress })
113
+ const out = {}
114
+ for (const [name, value] of response.headers) if (name !== 'set-cookie') out[name] = value
115
+ const cookies = response.headers.getSetCookie?.() ?? []
116
+ if (cookies.length) out['set-cookie'] = cookies
117
+ res.writeHead(response.status, out)
118
+ if (method === 'HEAD' || !response.body) return res.end()
119
+ const reader = response.body.getReader()
120
+ res.on('close', () => { reader.cancel().catch(() => {}) })
121
+ try {
122
+ for (;;) {
123
+ const { done, value } = await reader.read()
124
+ if (done) break
125
+ if (res.destroyed) break
126
+ if (!res.write(value)) {
127
+ await new Promise((resolve) => {
128
+ const done = () => { res.off('drain', done); res.off('close', done); resolve() }
129
+ res.on('drain', done)
130
+ res.on('close', done)
131
+ })
132
+ }
133
+ }
134
+ res.end()
135
+ } catch {
136
+ // The provider failed after the head went out: the only honest signal left is to drop the connection.
137
+ res.destroy()
138
+ }
139
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * provider.mjs -- the pod that answers: `serveHttpOnMesh(service, handler, { allowFrom, limits })`.
3
+ *
4
+ * A `(Request) => Response` handler (or `{ fetch }`) is served over protocol `http` v1 to the ingress pods named in
5
+ * `allowFrom`. Two gates, both default deny: `protocol:http:open` in the provider's registry (the protocol host's own
6
+ * authorisation) and `allowFrom` (this function's). The caller is the channel's verified peer, never a field of a message.
7
+ */
8
+ import { createStreamLayer } from '@johnhenry/browsermesh-apps/protocol-stream'
9
+ import { ChannelErrorCode, MeshChannelError } from '@johnhenry/browsermesh-apps/mesh-channel'
10
+ import { IngressError } from './errors.mjs'
11
+ import { NO_BODY_STATUS, isPodId } from './headers.mjs'
12
+ import {
13
+ FETCH_METHOD, HTTP_PROTOCOL, HTTP_VERSIONS, KIND_REQUEST, KIND_RESPONSE, sha256Hex, signedBytes, validateRequestHead, validateStreamMeta,
14
+ } from './wire.mjs'
15
+
16
+ export const PROVIDER_LIMIT_DEFAULTS = Object.freeze({
17
+ maxInflight: 16,
18
+ maxRequestBodyBytes: 1024 * 1024,
19
+ maxResponseBytes: 8 * 1024 * 1024,
20
+ handlerTimeoutMs: 30_000,
21
+ bodyWaitMs: 10_000,
22
+ maxHeaderCount: 64,
23
+ maxHeaderBytes: 16 * 1024,
24
+ maxTargetLength: 2048,
25
+ })
26
+
27
+ const unref = (t) => { t?.unref?.(); return t }
28
+ const asChannelError = (e) => (e instanceof MeshChannelError ? e
29
+ : e instanceof IngressError ? new MeshChannelError(e.status === 405 ? ChannelErrorCode.UNSUPPORTED : ChannelErrorCode.INVALID, e.reason, e.message)
30
+ : new MeshChannelError(ChannelErrorCode.INTERNAL, 'handler-failed', 'the handler failed'))
31
+
32
+ function deferred() {
33
+ let resolve, reject
34
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej })
35
+ promise.catch(() => {})
36
+ return { promise, resolve, reject }
37
+ }
38
+
39
+ /**
40
+ * @param {object} service - a mesh service with the protocol channel (`attachService(node, undefined, createMeshProtocolService())`, or its `.api`)
41
+ * @param {Function|{ fetch: Function }} handler - `(request, { peer, signal, client }) => Response | Promise<Response>`
42
+ * @param {object} opts
43
+ * @param {string[]|((peer: string) => boolean)} opts.allowFrom - the ingress pods served; required, nothing is served to any other
44
+ * @param {object} [opts.limits] - see `PROVIDER_LIMIT_DEFAULTS`
45
+ * @param {(bytes: Uint8Array, info: { peer: string }) => (string|Promise<string>)} [opts.sign] - sign the response: the provider buffers it so the signature covers the body
46
+ * @param {string} [opts.protocol='http']
47
+ * @returns {{ stop(): void, stats(): object }}
48
+ */
49
+ export function serveHttpOnMesh(service, handler, { allowFrom, limits: limitOptions, sign, protocol = HTTP_PROTOCOL, onLog } = {}) {
50
+ const api = service && typeof service === 'object' ? (service.api ?? service) : null
51
+ if (typeof api?.serveProtocol !== 'function') throw new TypeError('serveHttpOnMesh: the first argument is a mesh service with serveProtocol (createMeshProtocolService)')
52
+ const fn = typeof handler === 'function' ? handler : typeof handler?.fetch === 'function' ? (req, ctx) => handler.fetch(req, ctx) : null
53
+ if (!fn) throw new TypeError('serveHttpOnMesh: handler must be a function or { fetch }')
54
+ if (sign !== undefined && typeof sign !== 'function') throw new TypeError('serveHttpOnMesh: sign must be a function')
55
+ let allowed
56
+ if (Array.isArray(allowFrom) && allowFrom.length && allowFrom.every(isPodId)) { const set = new Set(allowFrom); allowed = (p) => set.has(p) }
57
+ else if (typeof allowFrom === 'function') allowed = (p) => { try { return allowFrom(p) === true } catch { return false } }
58
+ else throw new TypeError('serveHttpOnMesh: allowFrom (a non-empty list of ingress pod ids, or a function) is required: nothing is served to a pod that is not named')
59
+ const limits = { ...PROVIDER_LIMIT_DEFAULTS, ...limitOptions }
60
+ for (const [k, v] of Object.entries(limits)) if (!Number.isSafeInteger(v) || v <= 0) throw new TypeError(`serveHttpOnMesh: limits.${k} must be a positive integer`)
61
+ const log = onLog || (() => {})
62
+
63
+ const channels = new Set()
64
+ const counters = { channels: 0, requests: 0, refused: 0, errors: 0, requestBytes: 0, responseBytes: 0, inflight: 0 }
65
+
66
+ function accept(channel, { peer }) {
67
+ if (!allowed(peer)) { counters.refused += 1; channel.close('not an ingress this pod serves'); return }
68
+ counters.channels += 1
69
+ channels.add(channel)
70
+ // One cap per layer, for both directions: the larger of the two. The request body's own cap is enforced where it is read.
71
+ const streams = createStreamLayer(channel, { maxStreams: limits.maxInflight * 2, maxStreamBytes: Math.max(limits.maxRequestBodyBytes, limits.maxResponseBytes) })
72
+ const bodies = new Map() // rid -> { reader } | { waiter }
73
+ let inflight = 0
74
+
75
+ streams.onStream((reader, { meta }) => {
76
+ if (!allowed(peer)) throw new IngressError(403, 'forbidden', 'not served')
77
+ validateStreamMeta(meta, KIND_REQUEST)
78
+ if (bodies.size >= limits.maxInflight * 2) throw new IngressError(503, 'busy', 'too many bodies waiting')
79
+ const have = bodies.get(meta.rid)
80
+ if (have?.reader) throw new IngressError(400, 'bad-stream', 'a body for that request is already open')
81
+ if (have?.waiter) { have.waiter.resolve(reader); bodies.set(meta.rid, { reader }); return }
82
+ // A body that arrives before its request is held for a bounded time, then dropped.
83
+ const entry = { reader }
84
+ entry.timer = unref(setTimeout(() => { if (bodies.get(meta.rid) === entry) { bodies.delete(meta.rid); reader.cancel('no request claimed this body').catch(() => {}) } }, limits.bodyWaitMs))
85
+ bodies.set(meta.rid, entry)
86
+ })
87
+
88
+ const claimBody = async (rid, signal) => {
89
+ const have = bodies.get(rid)
90
+ if (have?.reader) { clearTimeout(have.timer); return have.reader }
91
+ const waiter = deferred()
92
+ bodies.set(rid, { waiter })
93
+ const timer = unref(setTimeout(() => waiter.reject(new IngressError(408, 'body-timeout', 'the request body did not arrive')), limits.bodyWaitMs))
94
+ const onAbort = () => waiter.reject(signal.reason ?? new Error('aborted'))
95
+ signal.addEventListener('abort', onAbort, { once: true })
96
+ try { return await waiter.promise } finally { clearTimeout(timer); signal.removeEventListener('abort', onAbort) }
97
+ }
98
+
99
+ channel.onRequest(FETCH_METHOD, async (params, ctx) => {
100
+ if (!allowed(peer)) { counters.refused += 1; throw new MeshChannelError(ChannelErrorCode.UNAUTHORIZED, 'not-authorized', 'not served') }
101
+ if (inflight >= limits.maxInflight) throw new MeshChannelError(ChannelErrorCode.BUSY, 'busy', 'too many requests in flight')
102
+ let head
103
+ try { head = validateRequestHead(params, limits) } catch (e) { counters.errors += 1; throw asChannelError(e) }
104
+ inflight += 1
105
+ counters.requests += 1
106
+ counters.inflight += 1
107
+ const ac = new AbortController()
108
+ const onCancel = () => ac.abort(ctx.signal.reason)
109
+ ctx.signal?.addEventListener('abort', onCancel, { once: true })
110
+ const timer = unref(setTimeout(() => ac.abort(new Error('handler deadline exceeded')), limits.handlerTimeoutMs))
111
+ let handedOff = false
112
+ const finish = () => {
113
+ clearTimeout(timer)
114
+ ctx.signal?.removeEventListener('abort', onCancel)
115
+ const had = bodies.get(head.rid)
116
+ if (had) { clearTimeout(had.timer); bodies.delete(head.rid) }
117
+ inflight -= 1
118
+ counters.inflight -= 1
119
+ }
120
+ try {
121
+ const request = await buildRequest(head, ac, claimBody, limits.maxRequestBodyBytes, counters)
122
+ const response = await fn(request, { peer, signal: ac.signal, client: head.client })
123
+ if (!response || typeof response !== 'object' || !Number.isInteger(response.status) || !response.headers || typeof response.headers.entries !== 'function') {
124
+ throw new MeshChannelError(ChannelErrorCode.INTERNAL, 'bad-handler-result', 'the handler did not return a Response')
125
+ }
126
+ if (response.status < 200 || response.status > 599) throw new MeshChannelError(ChannelErrorCode.INTERNAL, 'bad-handler-status', 'the handler returned a status outside 200-599')
127
+ const headers = [...response.headers.entries()]
128
+ const hasBody = !!response.body && head.method !== 'HEAD' && !NO_BODY_STATUS.has(response.status)
129
+ if (!hasBody && response.body) response.body.cancel?.().catch?.(() => {})
130
+
131
+ if (sign) {
132
+ const bytes = hasBody ? await collect(response.body, limits.maxResponseBytes, ac.signal) : new Uint8Array(0)
133
+ counters.responseBytes += bytes.byteLength
134
+ const lengthed = headers.filter(([n]) => n !== 'content-length')
135
+ if (hasBody) lengthed.push(['content-length', String(bytes.byteLength)])
136
+ const sig = await sign(signedBytes({ rid: head.rid, nonce: head.nonce, host: head.host, method: head.method, target: head.target, status: response.status, headers: lengthed, digest: await sha256Hex(bytes) }), { peer })
137
+ let writer = null
138
+ if (hasBody) writer = await streams.open({ rid: head.rid, kind: KIND_RESPONSE })
139
+ handedOff = true
140
+ if (writer) pump(writer, new ReadableStream({ start(c) { c.enqueue(bytes); c.close() } }), { limits, counters, ac, done: finish })
141
+ else finish()
142
+ return { status: response.status, headers: lengthed, body: hasBody, sig }
143
+ }
144
+ let writer = null
145
+ if (hasBody) writer = await streams.open({ rid: head.rid, kind: KIND_RESPONSE })
146
+ handedOff = true
147
+ if (writer) pump(writer, response.body, { limits, counters, ac, done: finish })
148
+ else finish()
149
+ return { status: response.status, headers, body: hasBody }
150
+ } catch (e) {
151
+ counters.errors += 1
152
+ log('http:handler-failed', { peer, error: e?.message })
153
+ throw asChannelError(e)
154
+ } finally {
155
+ if (!handedOff) finish()
156
+ }
157
+ })
158
+
159
+ channel.onClose(() => { streams.close(); channels.delete(channel); for (const b of bodies.values()) clearTimeout(b.timer) })
160
+ }
161
+
162
+ const unserve = api.serveProtocol(protocol, accept, { versions: [...HTTP_VERSIONS] })
163
+ return {
164
+ stop() {
165
+ unserve()
166
+ for (const channel of [...channels]) { try { channel.close('stopped') } catch { /* gone */ } }
167
+ channels.clear()
168
+ },
169
+ stats: () => ({ ...counters, open: channels.size }),
170
+ }
171
+ }
172
+
173
+ async function buildRequest(head, ac, claimBody, maxBytes, counters) {
174
+ const headers = new Headers()
175
+ for (const [name, value] of head.headers) headers.append(name, value)
176
+ if (head.client) headers.set('x-forwarded-for', head.client)
177
+ let body
178
+ if (head.body) {
179
+ if (head.method === 'GET' || head.method === 'HEAD') throw new IngressError(400, 'body-on-get', 'a body on a method that has none')
180
+ const reader = await claimBody(head.rid, ac.signal)
181
+ // Read whole, bounded: a handler gets an ordinary Request body. (A ReadableStream as a Request body is not
182
+ // supported by every browser, and a page is the usual provider.) One that outgrows the cap stops the sender.
183
+ try { body = await reader.bytes({ maxBytes }) } catch (e) {
184
+ if (e?.reason === 'stream-too-large') throw new IngressError(413, 'body-too-large', 'the request body is larger than this provider takes')
185
+ throw e
186
+ }
187
+ counters.requestBytes += body.byteLength
188
+ }
189
+ return new Request(`http://${head.host}${head.target}`, { method: head.method, headers, body, signal: ac.signal, redirect: 'manual' })
190
+ }
191
+
192
+ async function collect(stream, max, signal) {
193
+ const reader = stream.getReader()
194
+ const parts = []
195
+ let n = 0
196
+ try {
197
+ for (;;) {
198
+ if (signal.aborted) throw signal.reason
199
+ const { done, value } = await reader.read()
200
+ if (done) break
201
+ n += value.byteLength
202
+ if (n > max) throw new MeshChannelError(ChannelErrorCode.TOO_LARGE, 'response-too-large', 'the response is larger than the limit')
203
+ parts.push(value)
204
+ }
205
+ } catch (e) { reader.cancel(e).catch(() => {}); throw e }
206
+ const out = new Uint8Array(n)
207
+ let at = 0
208
+ for (const p of parts) { out.set(p, at); at += p.byteLength }
209
+ return out
210
+ }
211
+
212
+ /** Copy a response body into the stream the ingress holds: credit-paced, cancelled from the other end, bounded. */
213
+ async function pump(writer, body, { limits, counters, ac, done }) {
214
+ const reader = body.getReader()
215
+ let sent = 0
216
+ const stop = () => { reader.cancel('stream cancelled').catch(() => {}) }
217
+ writer.signal.addEventListener('abort', stop, { once: true })
218
+ ac.signal.addEventListener('abort', () => { writer.abort(ac.signal.reason ?? 'deadline'); stop() }, { once: true })
219
+ try {
220
+ for (;;) {
221
+ const { done: end, value } = await reader.read()
222
+ if (end) break
223
+ if (!(value instanceof Uint8Array)) throw new TypeError('the response body must be bytes')
224
+ sent += value.byteLength
225
+ if (sent > limits.maxResponseBytes) throw new MeshChannelError(ChannelErrorCode.TOO_LARGE, 'response-too-large', 'the response is larger than the limit')
226
+ await writer.write(value)
227
+ counters.responseBytes += value.byteLength
228
+ }
229
+ await writer.end()
230
+ } catch (e) {
231
+ writer.abort(e)
232
+ stop()
233
+ } finally {
234
+ writer.signal.removeEventListener('abort', stop)
235
+ done()
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Wrap a serverless site handler (`createSiteRequestHandler(siteConfig)` from `@johnhenry/browsermesh-apps`) as a
241
+ * `(Request) => Response` handler, so a site that already exists can be served over `http`.
242
+ * @param {(req: { fromPubKey?: string, method: string, path: string, headers: object, body?: * }) => Promise<{ status: number, headers: object, body: * }>} onRequest
243
+ */
244
+ export function fromSiteHandler(onRequest) {
245
+ if (typeof onRequest !== 'function') throw new TypeError('fromSiteHandler: a site request handler is required')
246
+ return async (request, { peer } = {}) => {
247
+ const url = new URL(request.url)
248
+ const body = request.body ? new Uint8Array(await request.arrayBuffer()) : undefined
249
+ const result = await onRequest({ fromPubKey: peer, method: request.method, path: url.pathname + url.search, headers: Object.fromEntries(request.headers), body })
250
+ const { decodeWireResponse } = await import('@johnhenry/browsermesh-apps')
251
+ const wire = decodeWireResponse(result)
252
+ const bytes = wire.body instanceof Uint8Array ? wire.body : wire.body === undefined || wire.body === null ? null
253
+ : new TextEncoder().encode(typeof wire.body === 'string' ? wire.body : JSON.stringify(wire.body))
254
+ const headers = new Headers(wire.headers ?? {})
255
+ headers.delete('content-length')
256
+ if (bytes && typeof wire.body === 'object' && !(wire.body instanceof Uint8Array) && !headers.has('content-type')) headers.set('content-type', 'application/json')
257
+ const noBody = request.method === 'HEAD' || NO_BODY_STATUS.has(wire.status ?? 200)
258
+ return new Response(noBody ? null : bytes, { status: wire.status ?? 200, headers })
259
+ }
260
+ }
package/src/wire.mjs ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * wire.mjs -- protocol `http` v1: names, head validation, and the bytes a signature covers.
3
+ * No framing of its own: heads are the params and result of one channel request, bodies are protocol streams.
4
+ */
5
+ import { IngressError } from './errors.mjs'
6
+ import { checkHeaderList, checkHost, checkTarget, isToken } from './headers.mjs'
7
+
8
+ export const HTTP_PROTOCOL = 'http'
9
+ export const HTTP_VERSIONS = Object.freeze([1])
10
+ export const FETCH_METHOD = 'fetch'
11
+ export const KIND_REQUEST = 'request'
12
+ export const KIND_RESPONSE = 'response'
13
+
14
+ /** Methods the provider will build a Request for. The ingress's `methods` option narrows this further. */
15
+ export const WIRE_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
16
+
17
+ /** @param {object} head the params of `fetch` @returns {object} validated, or throws IngressError 400 */
18
+ export function validateRequestHead(head, { maxHeaderCount, maxHeaderBytes, maxTargetLength }) {
19
+ if (!head || typeof head !== 'object') throw new IngressError(400, 'bad-request-head', 'The request head is not an object.')
20
+ const { rid, method, target, host, headers, body } = head
21
+ if (!Number.isSafeInteger(rid) || rid <= 0) throw new IngressError(400, 'bad-request-head', 'The request id is not a positive integer.')
22
+ if (typeof method !== 'string' || !WIRE_METHODS.has(method)) throw new IngressError(405, 'method-not-allowed', 'The method is not served.')
23
+ checkTarget(target, maxTargetLength)
24
+ checkHost(host)
25
+ checkHeaderList(headers, { maxCount: maxHeaderCount, maxBytes: maxHeaderBytes, reason: 'bad-request-head' })
26
+ for (const [name] of headers) {
27
+ const n = name.toLowerCase()
28
+ if (['host', 'connection', 'upgrade', 'transfer-encoding', 'content-length', 'te', 'trailer', 'expect', 'forwarded', 'proxy-authorization'].includes(n)) {
29
+ throw new IngressError(400, 'bad-request-head', 'A header that frames the request was sent in the head.')
30
+ }
31
+ }
32
+ if (typeof body !== 'boolean') throw new IngressError(400, 'bad-request-head', 'The body flag is not a boolean.')
33
+ if (head.client !== undefined && (typeof head.client !== 'string' || head.client.length > 64)) throw new IngressError(400, 'bad-request-head', 'The client field is not a short string.')
34
+ if (typeof head.nonce !== 'string' || !/^[0-9a-f]{16,64}$/.test(head.nonce)) throw new IngressError(400, 'bad-request-head', 'The nonce is not 16 to 64 hex characters.')
35
+ return head
36
+ }
37
+
38
+ /** @param {object} head the result of `fetch`, from a pod this side does not control */
39
+ export function validateResponseHead(head, { maxHeaderCount, maxHeaderBytes }) {
40
+ if (!head || typeof head !== 'object') throw new IngressError(502, 'bad-response-head', 'The provider answered with something that is not a response head.')
41
+ const { status, headers, body } = head
42
+ if (!Number.isInteger(status) || status < 200 || status > 599) throw new IngressError(502, 'bad-response-status', 'The provider sent a status outside 200-599.')
43
+ checkHeaderList(headers, { maxCount: maxHeaderCount, maxBytes: maxHeaderBytes, status: 502, reason: 'bad-response-head' })
44
+ if (typeof body !== 'boolean') throw new IngressError(502, 'bad-response-head', 'The body flag is not a boolean.')
45
+ if (head.sig !== undefined && (typeof head.sig !== 'string' || head.sig.length > 2048)) throw new IngressError(502, 'bad-response-head', 'The signature is not a short string.')
46
+ return head
47
+ }
48
+
49
+ /** Stream meta both ends accept, and nothing else. */
50
+ export function validateStreamMeta(meta, kind) {
51
+ if (!meta || typeof meta !== 'object' || meta.kind !== kind || !Number.isSafeInteger(meta.rid) || meta.rid <= 0) {
52
+ throw new IngressError(400, 'bad-stream', 'The stream is not one this end expects.')
53
+ }
54
+ return meta
55
+ }
56
+
57
+ const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
58
+ export async function sha256Hex(bytes) {
59
+ return hex(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes)))
60
+ }
61
+
62
+ /**
63
+ * What a response signature covers: the request it answers (its id and a fresh nonce, so an answer cannot be replayed for another request),
64
+ * the status, the header list as the provider sent it, and the SHA-256 of the body.
65
+ * @returns {Uint8Array}
66
+ */
67
+ export function signedBytes({ rid, nonce, host, method, target, status, headers, digest }) {
68
+ for (const [name] of headers) if (!isToken(name)) throw new TypeError('bad header name')
69
+ return new TextEncoder().encode(JSON.stringify({ v: 1, rid, nonce, host, method, target, status, headers, digest }))
70
+ }