@gitsang/dsh-gateway 0.0.0-stage → 0.5.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/proxy.js ADDED
@@ -0,0 +1,599 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { request as httpRequest } from 'node:http'
3
+ import { renderUnauthorizedPage } from './pages.js'
4
+ import { injectHostModeTag, injectPwaTags } from './pwa.js'
5
+
6
+ /** Headers that must not be forwarded as-is by a proxy. */
7
+ const HOP_BY_HOP = new Set([
8
+ 'connection',
9
+ 'keep-alive',
10
+ 'proxy-authenticate',
11
+ 'proxy-authorization',
12
+ 'te',
13
+ 'trailer',
14
+ 'transfer-encoding',
15
+ 'upgrade'
16
+ ])
17
+
18
+ /**
19
+ * Drop hop-by-hop headers named by the request's own `Connection` header, as
20
+ * required by RFC 9110, in addition to the fixed list above. Without this a
21
+ * proxy could forward a header relevant only to the browser-to-proxy hop.
22
+ */
23
+ function filterHopByHop(headers) {
24
+ const connectionTokens = typeof headers.connection === 'string'
25
+ ? headers.connection.split(',').map((token) => token.trim().toLowerCase())
26
+ : []
27
+ const out = {}
28
+ for (const [name, value] of Object.entries(headers)) {
29
+ const lower = name.toLowerCase()
30
+ if (value === undefined || HOP_BY_HOP.has(lower) || connectionTokens.includes(lower)) continue
31
+ out[name] = value
32
+ }
33
+ return out
34
+ }
35
+
36
+ /**
37
+ * Canonical `host:port` of the upstream dsh server, in the same form dsh uses
38
+ * for its authority-bound browser-session cookie. IPv6 literals are bracketed.
39
+ *
40
+ * @param target - the upstream `{ host, port }` tuple.
41
+ * @returns the upstream authority.
42
+ */
43
+ export function targetAuthority(target) {
44
+ const host = String(target.host)
45
+ return `${host.includes(':') ? `[${host}]` : host}:${String(target.port)}`
46
+ }
47
+
48
+ /**
49
+ * Rewrite the request identity headers so the upstream sees a loopback
50
+ * request, regardless of the public hostname the browser used to reach this
51
+ * proxy.
52
+ *
53
+ * dsh and many dsh plugins treat a request as local when its `Host` (and the
54
+ * matching `Origin`) names loopback. A request that reached this proxy has
55
+ * already been routed deliberately by the operator, so forwarding the
56
+ * browser's public `Host`/`Origin` only makes those plugins reject an
57
+ * otherwise valid request. This is the behavior the Traefik `dsh-loopback`
58
+ * middleware used to implement; doing it here keeps every deployment path
59
+ * consistent, including WebSocket upgrades.
60
+ *
61
+ * `Referer` is normalized for the same reason: it is a browser-origin hint,
62
+ * not user identity. `Sec-Fetch-Site` is deliberately left untouched, so dsh's
63
+ * CSRF fence still rejects genuinely cross-site traffic even after Host and
64
+ * Origin have been translated to loopback.
65
+ *
66
+ * Forwarding headers are rewritten too: a plugin that consults
67
+ * `X-Forwarded-For`/`X-Forwarded-Host` instead of the socket or `Host` must see
68
+ * the same loopback peer, not the public client address added by Traefik or
69
+ * nginx.
70
+ *
71
+ * @param headers - incoming request headers (already hop-by-hop filtered).
72
+ * @param target - the upstream `{ host, port }` tuple.
73
+ * @returns a new header object addressed to the loopback upstream.
74
+ */
75
+ export function loopbackHeaders(headers, target) {
76
+ const authority = targetAuthority(target)
77
+ const origin = `http://${authority}`
78
+ const out = { ...headers, host: authority, origin }
79
+ if (typeof out.referer === 'string' && out.referer !== '') {
80
+ try {
81
+ const referer = new URL(out.referer)
82
+ referer.protocol = 'http:'
83
+ referer.host = authority
84
+ out.referer = referer.href
85
+ } catch {
86
+ // A malformed Referer is not worth preserving; make it local as well.
87
+ out.referer = `${origin}/`
88
+ }
89
+ }
90
+ if (out['x-forwarded-for'] !== undefined) out['x-forwarded-for'] = '127.0.0.1'
91
+ if (out['x-real-ip'] !== undefined) out['x-real-ip'] = '127.0.0.1'
92
+ if (out['x-forwarded-host'] !== undefined) out['x-forwarded-host'] = authority
93
+ if (out['x-forwarded-port'] !== undefined) out['x-forwarded-port'] = String(target.port)
94
+ if (out['x-forwarded-proto'] !== undefined) out['x-forwarded-proto'] = 'http'
95
+ if (out.forwarded !== undefined) {
96
+ out.forwarded = `for=127.0.0.1;host="${authority}";proto=http`
97
+ }
98
+ return out
99
+ }
100
+
101
+ /**
102
+ * The cookie the gateway used to mint for its own password gate. Browsers that
103
+ * signed in before that gate was removed still hold one; it must not be
104
+ * forwarded to dsh or any plugin, because it is a dead bearer token.
105
+ */
106
+ const LEGACY_SESSION_COOKIE = 'dsh_gateway_session'
107
+
108
+ /**
109
+ * Drop a leftover password-gate cookie from the `Cookie` header. Everything
110
+ * else — including the `dsh-auth-*` cookie dsh minted — is forwarded unchanged:
111
+ * the gateway no longer replaces the browser's credential with its own.
112
+ */
113
+ function stripLegacySessionCookie(headers) {
114
+ const raw = headers.cookie
115
+ if (typeof raw !== 'string' || raw === '') return headers
116
+ const kept = raw.split(';')
117
+ .map((segment) => segment.trim())
118
+ .filter((segment) => segment !== '' && !segment.startsWith(`${LEGACY_SESSION_COOKIE}=`))
119
+ const out = { ...headers }
120
+ if (kept.length === 0) delete out.cookie
121
+ else out.cookie = kept.join('; ')
122
+ return out
123
+ }
124
+
125
+ /**
126
+ * The browser-facing origin of a request, reconstructed from the headers a
127
+ * reverse proxy forwards. Used to translate absolute upstream redirects back
128
+ * to the public origin after request headers were rewritten to loopback.
129
+ */
130
+ export function browserOrigin(req) {
131
+ const host = req.headers.host
132
+ if (typeof host !== 'string' || host === '') return undefined
133
+ const origin = req.headers.origin
134
+ if (typeof origin === 'string' && origin !== '') {
135
+ try {
136
+ return new URL(origin).origin
137
+ } catch {
138
+ // Fall through to the forwarded/metadata hints.
139
+ }
140
+ }
141
+ const forwardedProto = req.headers['x-forwarded-proto']
142
+ const proto = typeof forwardedProto === 'string' && forwardedProto !== ''
143
+ ? forwardedProto.split(',', 1)[0].trim()
144
+ : 'http'
145
+ try {
146
+ return new URL(`${proto}://${host}`).origin
147
+ } catch {
148
+ return undefined
149
+ }
150
+ }
151
+
152
+ /** The cookie prefix dsh uses for its signed browser-session cookies. */
153
+ export const DSH_COOKIE_PREFIX = 'dsh-auth-'
154
+
155
+ /**
156
+ * The exact cookie name dsh mints for `authority`: the fixed prefix plus the
157
+ * base64url SHA-256 of the authority the cookie is bound to.
158
+ *
159
+ * The gateway needs it for one thing only — expiring that cookie on sign-out,
160
+ * because an `HttpOnly` cookie cannot be cleared from page JavaScript.
161
+ *
162
+ * @param authority - canonical `host:port` the request is forwarded under.
163
+ * @returns dsh's cookie name for that authority.
164
+ */
165
+ export function dshCookieName(authority) {
166
+ return DSH_COOKIE_PREFIX + createHash('sha256').update(authority).digest('base64url')
167
+ }
168
+
169
+ /**
170
+ * Add `Secure` to a dsh session cookie when the browser-facing hop is HTTPS.
171
+ *
172
+ * dsh marks its cookie `Secure` only when its own listener terminates TLS. A
173
+ * gateway behind an HTTPS reverse proxy speaks plain HTTP upstream, so without
174
+ * this the browser would be handed a non-`Secure` bearer cookie for an HTTPS
175
+ * origin. The cookie keeps every attribute dsh chose; only that one is added.
176
+ */
177
+ function secureSessionCookie(cookie, secure) {
178
+ if (!secure) return cookie
179
+ if (!String(cookie).trimStart().startsWith(DSH_COOKIE_PREFIX)) return cookie
180
+ if (/;\s*secure\b/i.test(cookie)) return cookie
181
+ return `${cookie}; Secure`
182
+ }
183
+
184
+ /** Whether the browser-facing origin uses HTTPS. */
185
+ function isSecureBrowserOrigin(req) {
186
+ const origin = browserOrigin(req)
187
+ return origin !== undefined && origin.startsWith('https://')
188
+ }
189
+
190
+ /**
191
+ * Translate response headers generated against the loopback upstream back to
192
+ * the browser-facing origin. Only absolute `Location` values pointing at the
193
+ * upstream loopback origin are changed; relative redirects stay untouched.
194
+ *
195
+ * Cookies are relayed as dsh sent them: the browser holds dsh's own
196
+ * authority-bound session cookie rather than a gateway session. The only edit
197
+ * is adding `Secure` when the public hop is HTTPS.
198
+ *
199
+ * @param headers - upstream response headers.
200
+ * @param req - the original browser request.
201
+ * @param target - the upstream `{ host, port }` tuple.
202
+ * @returns a new header object safe to send to the browser.
203
+ */
204
+ export function rewriteResponseHeaders(headers, req, target) {
205
+ const out = { ...headers }
206
+ const loopback = `http://${targetAuthority(target)}`
207
+ const publicOrigin = browserOrigin(req)
208
+ if (
209
+ publicOrigin !== undefined &&
210
+ typeof out.location === 'string' &&
211
+ /^https?:\/\//i.test(out.location)
212
+ ) {
213
+ try {
214
+ const location = new URL(out.location)
215
+ if (location.origin === loopback) {
216
+ out.location = `${publicOrigin}${location.pathname}${location.search}${location.hash}`
217
+ }
218
+ } catch {
219
+ // Leave malformed/unusual Location values to the upstream.
220
+ }
221
+ }
222
+
223
+ const raw = out['set-cookie']
224
+ if (raw !== undefined) {
225
+ const secure = isSecureBrowserOrigin(req)
226
+ const cookies = (Array.isArray(raw) ? raw : [raw]).map((cookie) => secureSessionCookie(cookie, secure))
227
+ out['set-cookie'] = Array.isArray(raw) ? cookies : cookies[0]
228
+ }
229
+ return out
230
+ }
231
+
232
+ /**
233
+ * Whether a request URL names an immutable, content-addressed asset.
234
+ *
235
+ * Vite assets carry their content hash in the filename. dsh's plugin bundle
236
+ * route puts the host-computed revision in the `rev` query parameter. Both can
237
+ * be cached for a year: a change always produces a different URL.
238
+ *
239
+ * @param rawUrl - a request URL or request target.
240
+ * @returns true when the URL is safe to cache immutably.
241
+ */
242
+ export function isImmutableAssetUrl(rawUrl) {
243
+ let url
244
+ try {
245
+ url = new URL(rawUrl ?? '/', 'http://dsh-gateway.invalid')
246
+ } catch {
247
+ return false
248
+ }
249
+ if (url.pathname.startsWith('/assets/')) return true
250
+ return url.pathname.startsWith('/plugins/') && /[?&]rev=/.test(url.search)
251
+ }
252
+
253
+ /** Merge one token into a `Vary` header without duplicating it. */
254
+ function addVary(headers, token) {
255
+ const current = headers.vary
256
+ const values = typeof current === 'string'
257
+ ? current.split(',').map((value) => value.trim()).filter((value) => value !== '')
258
+ : []
259
+ if (!values.some((value) => value.toLowerCase() === token.toLowerCase())) values.push(token)
260
+ headers.vary = values.join(', ')
261
+ }
262
+
263
+ /**
264
+ * Add cache policy to a proxied response.
265
+ *
266
+ * HTML is authenticated and rendered per request, so it must be revalidated on
267
+ * every navigation and must not enter a shared cache. Hashed assets are public
268
+ * and immutable. API traffic is never cacheable. Upstream dsh currently sends
269
+ * no cache headers for assets or the app shell, which is why a browser had no
270
+ * permission to persist them across reloads.
271
+ *
272
+ * @param req - the original browser request.
273
+ * @param headers - mutable response headers about to be written.
274
+ * @param statusCode - upstream response status; only successful immutable
275
+ * resources may receive the one-year cache header.
276
+ * @returns the same headers object.
277
+ */
278
+ export function applyCachePolicy(req, headers, statusCode = 200) {
279
+ if (isImmutableAssetUrl(req.url)) {
280
+ if (statusCode >= 200 && statusCode < 300) {
281
+ headers['cache-control'] = 'public, max-age=31536000, immutable'
282
+ } else if (statusCode >= 400) {
283
+ headers['cache-control'] = 'no-store'
284
+ }
285
+ return headers
286
+ }
287
+
288
+ let pathname = ''
289
+ try {
290
+ pathname = new URL(req.url ?? '/', 'http://dsh-gateway.invalid').pathname
291
+ } catch {
292
+ return headers
293
+ }
294
+ if (pathname === '/api' || pathname.startsWith('/api/')) {
295
+ headers['cache-control'] = 'no-store'
296
+ return headers
297
+ }
298
+ if (String(headers['content-type'] ?? '').includes('text/html')) {
299
+ headers['cache-control'] = 'private, no-cache'
300
+ addVary(headers, 'Cookie')
301
+ }
302
+ return headers
303
+ }
304
+
305
+ /**
306
+ * Whether a response is dsh's browser-session rejection rather than some other
307
+ * 401. dsh answers a missing/expired cookie with a fixed plain-text body.
308
+ */
309
+ export function isDshAuthRejection(upstreamRes, body) {
310
+ return upstreamRes.statusCode === 401 &&
311
+ String(upstreamRes.headers['content-type'] ?? '').includes('text/plain') &&
312
+ body.includes('dsh web authentication required')
313
+ }
314
+
315
+ /**
316
+ * Whether a request is a top-level HTML navigation whose body we may rewrite.
317
+ * Mirrors the headers dsh's own compression middleware keys on.
318
+ * @param req - the incoming browser request.
319
+ * @returns true for a document GET/HEAD that accepts HTML.
320
+ */
321
+ function isDocumentNavigation(req) {
322
+ if (req.method !== 'GET' && req.method !== 'HEAD') return false
323
+ if (!String(req.headers.accept ?? '').includes('text/html')) return false
324
+ const dest = req.headers['sec-fetch-dest']
325
+ return dest === undefined || dest === 'document' || dest === 'iframe'
326
+ }
327
+
328
+ /**
329
+ * Ask dsh whether a browser cookie authenticates a browser session.
330
+ *
331
+ * The gateway owns no credential of its own, and dsh exposes no "check this
332
+ * cookie" endpoint. The one place dsh verifies a browser cookie and answers
333
+ * something observable is the index route: it serves `index.html` to a valid
334
+ * session and `401` to anything else. A loopback `HEAD /` carrying the
335
+ * browser's cookie therefore asks dsh the exact question, under the authority
336
+ * the gateway forwards on, without transferring a page body. This is how the
337
+ * gateway's own settings API decides whether its caller is signed in.
338
+ *
339
+ * Never throws: an unreachable or refusing dsh means "not authenticated".
340
+ *
341
+ * @param target - the upstream `{ host, port }` tuple.
342
+ * @param cookieHeader - the browser's raw `Cookie` header, or undefined.
343
+ * @returns true only when dsh accepts that cookie for the loopback authority.
344
+ */
345
+ export function probeBrowserSession(target, cookieHeader) {
346
+ return new Promise((resolve) => {
347
+ const headers = loopbackHeaders({ accept: 'text/html' }, target)
348
+ if (typeof cookieHeader === 'string' && cookieHeader !== '') headers.cookie = cookieHeader
349
+ const probe = httpRequest({
350
+ hostname: target.host,
351
+ port: target.port,
352
+ path: '/',
353
+ method: 'HEAD',
354
+ headers
355
+ }, (probeRes) => {
356
+ probeRes.resume()
357
+ resolve(probeRes.statusCode === 200)
358
+ })
359
+ probe.on('error', () => resolve(false))
360
+ probe.end()
361
+ })
362
+ }
363
+
364
+ /** Issue one request to dsh; resolves with its response or rejects. */
365
+ function send(target, req, options) {
366
+ const headers = loopbackHeaders(stripLegacySessionCookie(filterHopByHop(req.headers)), target)
367
+ // dsh gzips HTML documents only for real browser navigations (Accept:
368
+ // text/html + Sec-Fetch-Dest: document). A compressed body cannot be
369
+ // rewritten, so ask for identity on exactly those requests; stylesheets,
370
+ // scripts and API payloads keep their compression.
371
+ const rewritesHtml = options.pwa !== false || options.hostMode === true
372
+ if (rewritesHtml && isDocumentNavigation(req)) {
373
+ delete headers['accept-encoding']
374
+ }
375
+ return new Promise((resolve, reject) => {
376
+ const upstream = httpRequest({
377
+ hostname: target.host,
378
+ port: target.port,
379
+ path: req.url,
380
+ method: req.method,
381
+ headers
382
+ }, resolve)
383
+ upstream.on('error', reject)
384
+ req.pipe(upstream)
385
+ })
386
+ }
387
+
388
+ /** Report an upstream connection failure to the client. */
389
+ function fail(res, message) {
390
+ if (res.headersSent) {
391
+ res.destroy()
392
+ return
393
+ }
394
+ res.writeHead(502, {
395
+ 'content-type': 'text/plain; charset=utf-8',
396
+ 'cache-control': 'no-store',
397
+ connection: 'close'
398
+ })
399
+ res.end(`dsh-gateway: upstream unavailable: ${message}`)
400
+ }
401
+
402
+ /** Whether this request/response pair is one we rewrite before relaying. */
403
+ function wantsRewrite(req, upstreamRes, options) {
404
+ if (req.method !== 'GET') return false
405
+ if ((upstreamRes.statusCode ?? 0) !== 200) return false
406
+ if (!String(upstreamRes.headers['content-type'] ?? '').includes('text/html')) return false
407
+ // A compressed body cannot be patched in place; send() drops Accept-Encoding
408
+ // for document navigations so this should always hold.
409
+ if (upstreamRes.headers['content-encoding'] !== undefined) return false
410
+ return options.pwa !== false || options.hostMode === true
411
+ }
412
+
413
+ /**
414
+ * Write one upstream response to the client, rewriting plain uncompressed HTML
415
+ * when enabled: PWA tags for the installable shell, and the Host-mode
416
+ * transport flag that lets the remote page use Host settings. Everything else
417
+ * streams through untouched.
418
+ */
419
+ function relay(req, upstreamRes, res, options) {
420
+ const statusCode = upstreamRes.statusCode ?? 502
421
+
422
+ if (!wantsRewrite(req, upstreamRes, options)) {
423
+ const headers = applyCachePolicy(req, rewriteResponseHeaders(upstreamRes.headers, req, options.target), statusCode)
424
+ res.writeHead(statusCode, upstreamRes.statusMessage, headers)
425
+ upstreamRes.pipe(res)
426
+ return
427
+ }
428
+
429
+ const chunks = []
430
+ upstreamRes.on('data', (chunk) => chunks.push(chunk))
431
+ upstreamRes.on('end', () => {
432
+ const headers = applyCachePolicy(req, rewriteResponseHeaders(upstreamRes.headers, req, options.target), statusCode)
433
+ delete headers['transfer-encoding']
434
+ let body = Buffer.concat(chunks).toString('utf8')
435
+ // Host mode first: it must precede every dsh script in the head.
436
+ if (options.hostMode === true) body = injectHostModeTag(body)
437
+ if (options.pwa !== false) body = injectPwaTags(body)
438
+ headers['content-length'] = Buffer.byteLength(body)
439
+ res.writeHead(statusCode, upstreamRes.statusMessage, headers)
440
+ res.end(body)
441
+ })
442
+ upstreamRes.on('error', (err) => {
443
+ if (!res.headersSent) {
444
+ res.writeHead(502, {
445
+ 'content-type': 'text/plain; charset=utf-8',
446
+ 'cache-control': 'no-store',
447
+ connection: 'close'
448
+ })
449
+ res.end(`dsh-gateway: upstream response error: ${err.message}`)
450
+ return
451
+ }
452
+ res.destroy()
453
+ })
454
+ }
455
+
456
+ /** The largest dsh rejection body the gateway will hold in memory. */
457
+ const AUTH_REJECTION_LIMIT_BYTES = 8192
458
+
459
+ /** Read at most `limit` bytes of a response; only small replies use this. */
460
+ function readSmallBody(upstreamRes, limit = AUTH_REJECTION_LIMIT_BYTES) {
461
+ return new Promise((resolve) => {
462
+ const chunks = []
463
+ let size = 0
464
+ upstreamRes.on('data', (chunk) => {
465
+ size += chunk.length
466
+ if (size <= limit) chunks.push(chunk)
467
+ })
468
+ const done = () => resolve(Buffer.concat(chunks))
469
+ upstreamRes.once('end', done)
470
+ upstreamRes.once('error', done)
471
+ })
472
+ }
473
+
474
+ /** Relay an already-buffered upstream response. */
475
+ function relayBuffered(req, upstreamRes, res, options, body) {
476
+ const statusCode = upstreamRes.statusCode ?? 502
477
+ const headers = applyCachePolicy(req, rewriteResponseHeaders(upstreamRes.headers, req, options.target), statusCode)
478
+ delete headers['transfer-encoding']
479
+ headers['content-length'] = String(body.length)
480
+ res.writeHead(statusCode, upstreamRes.statusMessage, headers)
481
+ res.end(body)
482
+ }
483
+
484
+ /**
485
+ * Forward one HTTP request to the dsh web server and pipe the response back.
486
+ *
487
+ * Authentication is dsh's: the browser's `dsh-auth-*` cookie is forwarded
488
+ * unchanged and dsh decides. The gateway only translates identity (so dsh and
489
+ * its plugins treat the request as local), rewrites HTML for the PWA/Host-mode
490
+ * features, and turns dsh's plain-text 401 into an explanatory page for a
491
+ * top-level navigation.
492
+ *
493
+ * When `options.pwa` is true (the default) and the upstream response is
494
+ * uncompressed HTML, the PWA tags are injected into the head before the
495
+ * response is sent back. Everything else is streamed through untouched.
496
+ *
497
+ * @param req - the incoming browser request.
498
+ * @param res - the response to write.
499
+ * @param target - the upstream `{ host, port }` tuple.
500
+ * @param options - `{ pwa, hostMode, loopback }` feature switches.
501
+ */
502
+ export async function proxyRequest(req, res, target, options = {}) {
503
+ let upstreamRes
504
+ try {
505
+ upstreamRes = await send(target, req, options)
506
+ } catch (error) {
507
+ fail(res, error?.message ?? error)
508
+ return
509
+ }
510
+
511
+ // dsh answers an unauthenticated navigation with a plain-text 401. Someone
512
+ // opening this gateway without the tokenized URL deserves an explanation
513
+ // instead of a bare line of text.
514
+ if (req.method === 'GET' && isDocumentNavigation(req) && upstreamRes.statusCode === 401) {
515
+ const body = await readSmallBody(upstreamRes)
516
+ if (isDshAuthRejection(upstreamRes, body)) {
517
+ const html = renderUnauthorizedPage({ pwa: options.pwa !== false })
518
+ res.writeHead(401, {
519
+ 'content-type': 'text/html; charset=utf-8',
520
+ 'cache-control': 'no-store',
521
+ vary: 'Cookie',
522
+ 'content-length': String(Buffer.byteLength(html))
523
+ })
524
+ res.end(html)
525
+ return
526
+ }
527
+ relayBuffered(req, upstreamRes, res, { ...options, target }, body)
528
+ return
529
+ }
530
+
531
+ relay(req, upstreamRes, res, { ...options, target })
532
+ }
533
+
534
+ /**
535
+ * Forward a WebSocket upgrade to the dsh web server. dsh authenticates the
536
+ * upgrade from the forwarded cookie and rejects it on its own when the
537
+ * credential is missing or expired; this only pipes bytes after that decision.
538
+ */
539
+ export function proxyUpgrade(req, socket, head, target, options = {}) {
540
+ // Keep Upgrade/Connection: they are what makes this an upgrade rather than an
541
+ // ordinary GET. Present the same loopback Host/Origin identity as ordinary
542
+ // HTTP requests and forward the browser's dsh cookie unchanged.
543
+ let headers = { ...req.headers }
544
+ delete headers['proxy-authorization']
545
+ delete headers['proxy-authenticate']
546
+ headers = stripLegacySessionCookie(headers)
547
+ if (options.loopback !== false) headers = loopbackHeaders(headers, target)
548
+
549
+ const upstream = httpRequest({
550
+ hostname: target.host,
551
+ port: target.port,
552
+ path: req.url,
553
+ method: 'GET',
554
+ headers
555
+ })
556
+
557
+ upstream.on('upgrade', (upstreamRes, upstreamSocket, upstreamHead) => {
558
+ const statusLine = `HTTP/${upstreamRes.httpVersion} ${upstreamRes.statusCode} ${upstreamRes.statusMessage}\r\n`
559
+ let headText = statusLine
560
+ for (const [name, value] of Object.entries(upstreamRes.headers)) {
561
+ if (value === undefined) continue
562
+ headText += `${name}: ${Array.isArray(value) ? value.join(', ') : value}\r\n`
563
+ }
564
+ headText += '\r\n'
565
+ socket.write(headText)
566
+ if (upstreamHead && upstreamHead.length > 0) socket.write(upstreamHead)
567
+ upstreamSocket.pipe(socket)
568
+ socket.pipe(upstreamSocket)
569
+
570
+ const teardown = () => {
571
+ upstreamSocket.destroy()
572
+ socket.destroy()
573
+ }
574
+ upstreamSocket.on('error', teardown)
575
+ socket.on('error', teardown)
576
+ upstreamSocket.on('close', () => socket.destroy())
577
+ socket.on('close', () => upstreamSocket.destroy())
578
+ })
579
+
580
+ upstream.on('response', (upstreamRes) => {
581
+ // dsh refused the upgrade (401/403/404). Relay its reply so the browser
582
+ // sees the real reason instead of a dropped socket.
583
+ const statusLine = `HTTP/${upstreamRes.httpVersion} ${upstreamRes.statusCode} ${upstreamRes.statusMessage}\r\n`
584
+ let headText = statusLine
585
+ for (const [name, value] of Object.entries(upstreamRes.headers)) {
586
+ if (value === undefined) continue
587
+ headText += `${name}: ${Array.isArray(value) ? value.join(', ') : value}\r\n`
588
+ }
589
+ headText += '\r\n'
590
+ socket.write(headText)
591
+ upstreamRes.pipe(socket)
592
+ })
593
+
594
+ upstream.on('error', () => {
595
+ socket.destroy()
596
+ })
597
+
598
+ upstream.end()
599
+ }