dsh-marker 0.0.0-stage → 0.1.2

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,428 @@
1
+ /**
2
+ * Publishing where this host is.
3
+ *
4
+ * A host whose port the launcher chose (`dsh --port 0`, DSH Desktop) cannot be
5
+ * found at a fixed address, so it says where it is in two places: a locator on
6
+ * a stable loopback port (see `locator.js`), and a record file under
7
+ * `$DSH_HOME` for a human, a script, or the popup's file import.
8
+ *
9
+ * Both answer *where*, never *whether*. The bridge token has exactly one home,
10
+ * `$DSH_HOME/ext-bridge-token`, and nothing here reads or copies it: an origin
11
+ * is already visible to any local process through `netstat`, while the token is
12
+ * the only admission check, so a second copy of it in JSON would be pure
13
+ * liability.
14
+ *
15
+ * The record is a snapshot, never authority. Whatever it says is verified
16
+ * against `/ext/anno/health` and the `hello` handshake before it is trusted,
17
+ * which is what lets a stale file be harmless.
18
+ *
19
+ * @module dsh-marker/discovery
20
+ */
21
+
22
+ import { randomBytes } from 'node:crypto'
23
+ import { chmod, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
24
+ import { join } from 'node:path'
25
+
26
+ import { dshHome } from './paths.js'
27
+ import { DISCOVERY_APP, ENDPOINT_FILE, PROTOCOL_VERSION, WS_PATH, isInstanceId } from './protocol.js'
28
+
29
+ /**
30
+ * The port a stock `dsh web` binds, and the one the extension already assumes.
31
+ *
32
+ * The locator's trigger is this number, deliberately, and not "is this the
33
+ * Desktop app": Desktop is only one way to land on another port, and a product
34
+ * marker would be an undocumented dependency that breaks silently the day the
35
+ * launcher changes.
36
+ */
37
+ export const DEFAULT_WEB_PORT = 3080
38
+
39
+ /** A canonical dotted-decimal octet: no leading zero, no sign, no padding. */
40
+ const OCTET = /^(?:0|[1-9]\d{0,2})$/
41
+
42
+ /** IPv4 and IPv6 disagree about what an address is, so only one is accepted. */
43
+ const MAX_PORT = 65_535
44
+
45
+ /**
46
+ * Whether a bind address is an IPv4 loopback literal, `127.0.0.1` through
47
+ * `127.255.255.255`.
48
+ *
49
+ * The locator binds IPv4 loopback only, because that is what the extension's
50
+ * host permissions cover and what a DNS-rebinding page cannot claim. `localhost`
51
+ * is refused rather than resolved: on a dual-stack Linux box it may become
52
+ * `::1`, and comparing strings is the only check that cannot disagree with what
53
+ * the browser will later do.
54
+ * @param {unknown} host
55
+ * @returns {boolean}
56
+ */
57
+ export function isIpv4Loopback(host) {
58
+ if (typeof host !== 'string') return false
59
+ const parts = host.split('.')
60
+ if (parts.length !== 4 || parts[0] !== '127') return false
61
+ // Leading zeros are refused as well: `0177.0.0.1` is octal to some resolvers,
62
+ // and an OS never hands us a padded address to begin with.
63
+ return parts.slice(1).every((part) => OCTET.test(part) && Number(part) <= 255)
64
+ }
65
+
66
+ /**
67
+ * Whether this host needs a locator.
68
+ *
69
+ * The trigger is the bound port, not the product (§9): a stock `dsh web` on
70
+ * {@link DEFAULT_WEB_PORT} is findable without one, and every other port — a
71
+ * launcher's choice, `--port 0`, an edited profile — is the same problem. A
72
+ * non-loopback bind gets no locator either, because the extension has no
73
+ * permission for those origins; the record and a manual address remain, which
74
+ * is why the record is written in every case.
75
+ * @param {{ port?: number, host?: string, mode?: 'auto' | 'off' }} [input]
76
+ * @returns {boolean}
77
+ */
78
+ export function shouldLocate({ port, host, mode = 'auto' } = {}) {
79
+ if (mode === 'off') return false
80
+ // `0` means "the OS picked one" and is what the launcher passed, not what the
81
+ // listener bound; the caller reads `webServer.port` after `listen` resolved.
82
+ if (typeof port !== 'number' || !Number.isInteger(port) || port <= 0 || port > MAX_PORT) return false
83
+ if (port === DEFAULT_WEB_PORT) return false
84
+ return isIpv4Loopback(host)
85
+ }
86
+
87
+ /**
88
+ * @typedef {object} AtomicWriteOptions
89
+ * @property {number} [mode] Permission bits for the new file; `0600` by default.
90
+ * @property {{ warn?: Function, debug?: Function }} [logger]
91
+ * @property {Function} [rename] Injected `rename(from, to)`, so tests can fail it.
92
+ * @property {Function} [writeFile] Injected `writeFile(path, text, options)`.
93
+ */
94
+
95
+ /**
96
+ * Put text in a file so a reader never sees it half-written.
97
+ *
98
+ * The temp file lives beside the target, so the rename stays on one filesystem
99
+ * and is atomic there; `0600` is chosen at creation, which is the only moment
100
+ * the permission can be set without a window in which the content is readable
101
+ * by others.
102
+ *
103
+ * Windows refuses to replace a file another handle holds open (`EPERM`), and
104
+ * that is usually transient — a virus scanner, an editor, the user's own `type`
105
+ * command. One retry covers the common case; a persistent failure falls back to
106
+ * writing the target in place, which is still correct content, just not atomic,
107
+ * and is reported as `false` so the caller can say so.
108
+ * @param {string} target file to replace
109
+ * @param {string} text exact bytes to write
110
+ * @param {AtomicWriteOptions} [options]
111
+ * @returns {Promise<boolean>} true only when a rename put the text in place.
112
+ */
113
+ export async function writeJsonAtomically(target, text, options = {}) {
114
+ const mode = options.mode ?? 0o600
115
+ const renameFile = options.rename ?? rename
116
+ const writeText = options.writeFile ?? writeFile
117
+ const temporary = `${target}.${process.pid}.tmp`
118
+ /** @param {string} reason */
119
+ const warn = (reason) => options.logger?.warn?.(`annotations: ${reason}`)
120
+
121
+ try {
122
+ await writeText(temporary, text, { mode })
123
+ } catch (error) {
124
+ // Nothing was replaced: the target still carries the previous, valid record,
125
+ // which is the better failure than a truncated file.
126
+ warn(`endpoint record not written (${messageOf(error)})`)
127
+ return false
128
+ }
129
+
130
+ let failure = await attemptRename(renameFile, temporary, target)
131
+ if (failure !== null && isRetryableRename(failure)) failure = await attemptRename(renameFile, temporary, target)
132
+ if (failure === null) {
133
+ await chmodQuietly(target, mode)
134
+ return true
135
+ }
136
+
137
+ try {
138
+ await writeText(target, text, { mode })
139
+ await unlinkQuietly(temporary)
140
+ await chmodQuietly(target, mode)
141
+ warn(`endpoint record replaced in place after a failed rename (${messageOf(failure)})`)
142
+ return false
143
+ } catch (error) {
144
+ await unlinkQuietly(temporary)
145
+ warn(`endpoint record not written (${messageOf(failure)}; in-place write failed: ${messageOf(error)})`)
146
+ return false
147
+ }
148
+ }
149
+
150
+ /**
151
+ * @param {Function} renameFile
152
+ * @param {string} from
153
+ * @param {string} to
154
+ * @returns {Promise<Error | null>} the failure, or null when the rename landed.
155
+ */
156
+ async function attemptRename(renameFile, from, to) {
157
+ try {
158
+ await renameFile(from, to)
159
+ return null
160
+ } catch (error) {
161
+ return error instanceof Error ? error : new Error(String(error))
162
+ }
163
+ }
164
+
165
+ /**
166
+ * The codes Node reports when another handle owns the destination. Anything
167
+ * else — a missing directory, a full disk — will not clear by waiting, so it
168
+ * falls straight through to the in-place write.
169
+ * @param {Error} error
170
+ * @returns {boolean}
171
+ */
172
+ function isRetryableRename(error) {
173
+ const code = /** @type {any} */ (error).code
174
+ return code === 'EPERM' || code === 'EACCES' || code === 'EBUSY'
175
+ }
176
+
177
+ /** @param {string} file @param {number} mode */
178
+ async function chmodQuietly(file, mode) {
179
+ try {
180
+ await chmod(file, mode)
181
+ } catch {
182
+ // Windows has no POSIX modes to set; the file inherits the profile's ACL,
183
+ // which is the same treatment the token file gets.
184
+ }
185
+ }
186
+
187
+ /** @param {string} file */
188
+ async function unlinkQuietly(file) {
189
+ try {
190
+ await unlink(file)
191
+ } catch {
192
+ // Already gone, or the rename consumed it: nothing to clean up either way.
193
+ }
194
+ }
195
+
196
+ /**
197
+ * @typedef {object} DiscoveryRecord
198
+ * @property {number} version `PROTOCOL_VERSION` of the running host.
199
+ * @property {string} app The discriminator; a record naming anything else is ignored.
200
+ * @property {string} instanceId 16 lowercase hex, fresh per process.
201
+ * @property {number} pid The process that wrote the record.
202
+ * @property {string | null} profile Display hint, or null when the host has none.
203
+ * @property {string | null} origin The bound origin, e.g. `http://127.0.0.1:51234`.
204
+ * @property {string | null} wsUrl The same authority with the bridge path.
205
+ * @property {string} startedAt ISO timestamp of this process's start.
206
+ */
207
+
208
+ /**
209
+ * @typedef {object} LocatorCard
210
+ * @property {string} app
211
+ * @property {number} version
212
+ * @property {string} instanceId
213
+ * @property {string | null} origin
214
+ * @property {string | null} wsUrl
215
+ * @property {string} startedAt
216
+ * @property {string | null} focusAt Latest Client focus report, or null.
217
+ * @property {string | null} profile
218
+ */
219
+
220
+ /**
221
+ * @typedef {object} PublishedEndpoint
222
+ * @property {string | null} origin
223
+ * @property {string | null} wsUrl
224
+ */
225
+
226
+ /**
227
+ * Create this process's published view of where it is.
228
+ *
229
+ * The origin is resolved once, at construction: the caller builds this from the
230
+ * inject callback that runs after `listen` resolved, so a host with no address
231
+ * at that moment will never have one for this process, and reading it lazily
232
+ * would only turn a construction-time bug into a `null` written to disk.
233
+ * `focusAt` is the opposite case and is read on every {@link LocatorCard}
234
+ * request, because the user changes Sessions while the host runs.
235
+ *
236
+ * Nothing here throws. Discovery is an optimisation for the client, so a
237
+ * filesystem failure is a warning and a `false`, never something that could
238
+ * take the host down.
239
+ * @param {object} options
240
+ * @param {any} options.webServer the DSH webserver service (`getOrigin()`, `.port`).
241
+ * @param {{ get: () => ({ sessionId: string, at: number } | null) } | undefined} [options.focus]
242
+ * @param {string} [options.home] defaults to `dshHome()`.
243
+ * @param {string | null} [options.profile]
244
+ * @param {{ warn?: Function, info?: Function, debug?: Function }} [options.logger]
245
+ * @param {string} [options.instanceId] test injection; default: 16 random hex.
246
+ * @param {number} [options.pid] test injection; default: `process.pid`.
247
+ * @param {() => Date} [options.now] test injection.
248
+ */
249
+ export function createDiscovery({ webServer, focus, home = dshHome(), profile, logger, instanceId, pid, now } = {}) {
250
+ const recordPath = join(home, ENDPOINT_FILE)
251
+ const processId = typeof pid === 'number' && Number.isInteger(pid) ? pid : process.pid
252
+ // A malformed id would never match itself in `remove()` and would be dropped
253
+ // by the extension's `isInstanceId` check, so an injected one is validated
254
+ // rather than trusted.
255
+ const id = isInstanceId(instanceId) ? instanceId : randomBytes(8).toString('hex')
256
+ const startedAt = startStamp(now)
257
+ const profileName = typeof profile === 'string' && profile !== '' ? profile : null
258
+ const endpoint = resolveEndpoint(webServer)
259
+
260
+ /**
261
+ * The latest known focus, as an ISO timestamp.
262
+ * @returns {string | null}
263
+ */
264
+ function focusAt() {
265
+ try {
266
+ const entry = focus?.get?.()
267
+ return isoOf(entry?.at)
268
+ } catch {
269
+ // A store that cannot answer is "no focus", not a failed request: the
270
+ // locator must still return an origin when focus reporting is broken.
271
+ return null
272
+ }
273
+ }
274
+
275
+ /** @returns {LocatorCard | null} */
276
+ function card() {
277
+ if (endpoint.origin === null) return null
278
+ return {
279
+ app: DISCOVERY_APP,
280
+ version: PROTOCOL_VERSION,
281
+ instanceId: id,
282
+ origin: endpoint.origin,
283
+ wsUrl: endpoint.wsUrl,
284
+ startedAt,
285
+ focusAt: focusAt(),
286
+ profile: profileName,
287
+ }
288
+ }
289
+
290
+ /** @returns {DiscoveryRecord | null} */
291
+ function record() {
292
+ if (endpoint.origin === null) return null
293
+ // Key order is part of the file's appearance in the docs, and this JSON is
294
+ // the thing a human reads in a support session.
295
+ return {
296
+ version: PROTOCOL_VERSION,
297
+ app: DISCOVERY_APP,
298
+ instanceId: id,
299
+ pid: processId,
300
+ profile: profileName,
301
+ origin: endpoint.origin,
302
+ wsUrl: endpoint.wsUrl,
303
+ startedAt,
304
+ }
305
+ }
306
+
307
+ /** @returns {Promise<boolean>} */
308
+ async function write() {
309
+ const body = record()
310
+ if (body === null) {
311
+ logger?.warn?.('annotations: endpoint record skipped — the webserver has no origin to publish')
312
+ return false
313
+ }
314
+ try {
315
+ await mkdir(home, { recursive: true })
316
+ return await writeJsonAtomically(recordPath, `${JSON.stringify(body, null, 2)}\n`, { logger })
317
+ } catch (error) {
318
+ // A read-only or otherwise unusable home is not a failure of the host:
319
+ // the locator still answers, so discovery degrades to "no file".
320
+ logger?.warn?.(`annotations: endpoint record not written (${messageOf(error)})`)
321
+ return false
322
+ }
323
+ }
324
+
325
+ /** @returns {Promise<void>} */
326
+ async function remove() {
327
+ try {
328
+ const parsed = JSON.parse(await readFile(recordPath, 'utf8'))
329
+ if (parsed?.instanceId !== id) {
330
+ // Two profiles share `$DSH_HOME`; the last writer owns the file, and an
331
+ // older instance shutting down must not delete a newer one's record.
332
+ logger?.debug?.('annotations: endpoint record belongs to another instance; left in place')
333
+ return
334
+ }
335
+ await unlink(recordPath)
336
+ } catch {
337
+ // Missing, unreadable, or torn: there is nothing this process may safely
338
+ // remove, and shutdown must not fail over a stale hint.
339
+ }
340
+ }
341
+
342
+ /** @returns {Promise<void>} */
343
+ async function dispose() {
344
+ await remove()
345
+ }
346
+
347
+ return {
348
+ instanceId: id,
349
+ startedAt,
350
+ profile: profileName,
351
+ pid: processId,
352
+ path: recordPath,
353
+ origin: endpoint.origin,
354
+ wsUrl: endpoint.wsUrl,
355
+ card,
356
+ record,
357
+ write,
358
+ remove,
359
+ dispose,
360
+ }
361
+ }
362
+
363
+ /**
364
+ * @param {() => Date} now
365
+ * @returns {string} an ISO timestamp, from the injected clock when it yields one.
366
+ */
367
+ function startStamp(now) {
368
+ try {
369
+ const value = new Date(now())
370
+ if (Number.isFinite(value.getTime())) return value.toISOString()
371
+ } catch {
372
+ // A clock that throws is still a host worth publishing; fall back to now.
373
+ }
374
+ return new Date().toISOString()
375
+ }
376
+
377
+ /**
378
+ * @param {unknown} value
379
+ * @returns {string | null} an ISO timestamp for a finite epoch-millisecond value.
380
+ */
381
+ function isoOf(value) {
382
+ if (typeof value !== 'number' || !Number.isFinite(value)) return null
383
+ const date = new Date(value)
384
+ // A finite number can still be outside the range `toISOString` accepts.
385
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null
386
+ }
387
+
388
+ /**
389
+ * The address this host is bound to, or a pair of nulls when it is not bound.
390
+ * @param {any} webServer
391
+ * @returns {PublishedEndpoint}
392
+ */
393
+ function resolveEndpoint(webServer) {
394
+ let origin
395
+ try {
396
+ origin = typeof webServer?.getOrigin === 'function' ? webServer.getOrigin() : undefined
397
+ } catch {
398
+ // Before `listen` resolves, `getOrigin()` throws instead of returning a
399
+ // half-built URL; "not bound yet" is the honest reading of that.
400
+ return { origin: null, wsUrl: null }
401
+ }
402
+ if (typeof origin !== 'string' || origin === '') return { origin: null, wsUrl: null }
403
+ return { origin, wsUrl: websocketUrl(origin) }
404
+ }
405
+
406
+ /**
407
+ * The websocket URL for an HTTP origin.
408
+ *
409
+ * The scheme is carried over rather than forced: a TLS listener, or a proxy
410
+ * advertising `https`, must publish `wss`, or the extension's first upgrade is
411
+ * refused. The authority is kept verbatim so an unusual port survives.
412
+ * @param {string} origin
413
+ * @returns {string | null}
414
+ */
415
+ function websocketUrl(origin) {
416
+ try {
417
+ const url = new URL(origin)
418
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
419
+ return `${url.protocol === 'https:' ? 'wss' : 'ws'}://${url.host}${WS_PATH}`
420
+ } catch {
421
+ return null
422
+ }
423
+ }
424
+
425
+ /** @param {unknown} error */
426
+ function messageOf(error) {
427
+ return error instanceof Error ? error.message : String(error)
428
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Endpoint negotiation for the bridge: "which URL should the browser use?"
3
+ *
4
+ * The host answers this question, so `/ext/anno/health` reports `secure` and a
5
+ * complete `wsUrl` instead of leaving the extension to guess. The negotiation
6
+ * exists for deployments where the bridge is *genuinely* served over TLS: `dsh
7
+ * web` configured with `tls`, or a TLS-terminating reverse proxy in front of a
8
+ * plain listener. The default local deployment is neither — a stock `dsh web`
9
+ * binds loopback and speaks plain HTTP, so it must keep advertising `ws://`,
10
+ * and the extension must keep requesting it. (A browser-side upgrade mechanism,
11
+ * such as the MV3 default `upgrade-insecure-requests`, is a policy bug on the
12
+ * extension side and is fixed in the manifest's explicit CSP, not here.)
13
+ *
14
+ * A client cannot infer the answer from the port, and guessing fails in both
15
+ * directions: `wss://` against a plain listener, and `ws://` against a TLS one.
16
+ *
17
+ * The decision has three inputs, in order of authority:
18
+ *
19
+ * 1. the serving socket (`request.socket.encrypted`), which is what node
20
+ * reports for a connection the listener terminated itself;
21
+ * 2. the listener configuration (`webServer.protocol` / `getOrigin()`), which
22
+ * covers TLS configured on the DSH webserver;
23
+ * 3. the forwarding headers a TLS-terminating reverse proxy sets
24
+ * (`x-forwarded-proto`, first value, then `x-forwarded-host`).
25
+ *
26
+ * @module dsh-marker/endpoint
27
+ */
28
+
29
+ import { WS_PATH } from './protocol.js'
30
+
31
+ /** Where a TLS-terminating proxy states the scheme the browser used. */
32
+ const FORWARDED_PROTO = 'x-forwarded-proto'
33
+ /** Where that proxy states the host the browser used. */
34
+ const FORWARDED_HOST = 'x-forwarded-host'
35
+
36
+ /**
37
+ * The first value of a comma-separated forwarding header, lower-cased.
38
+ *
39
+ * Proxies append to these headers as a request travels inward, so the leftmost
40
+ * value is the one the browser (the outermost hop) used. `https, http` therefore
41
+ * means "TLS from the browser to the first proxy"; a plain `Array.isArray`-safe
42
+ * read is not needed because node joins duplicate headers with commas.
43
+ * @param {unknown} value
44
+ * @returns {string}
45
+ */
46
+ export function firstForwardedValue(value) {
47
+ if (typeof value !== 'string') return ''
48
+ return value.split(',')[0].trim().toLowerCase()
49
+ }
50
+
51
+ /**
52
+ * Accept a `host[:port]` authority and reject everything else.
53
+ *
54
+ * `Host` and `X-Forwarded-Host` are client-controlled strings that end up inside
55
+ * the advertised URL, so the value is restricted to characters an authority can
56
+ * contain. IPv6 literals must be bracketed; a bare address with several colons
57
+ * is not a valid authority and is refused rather than guessed at.
58
+ * @param {unknown} value
59
+ * @returns {string | undefined}
60
+ */
61
+ export function sanitizeAuthority(value) {
62
+ if (typeof value !== 'string') return undefined
63
+ const first = value.split(',')[0].trim().toLowerCase()
64
+ if (first === '' || first.length > 255) return undefined
65
+ if (!/^[a-z0-9._:[\]-]+$/.test(first)) return undefined
66
+ if (first.startsWith('[')) {
67
+ const close = first.indexOf(']')
68
+ if (close === -1) return undefined
69
+ const rest = first.slice(close + 1)
70
+ if (rest !== '' && !validPortSuffix(rest)) return undefined
71
+ return first
72
+ }
73
+ if ((first.match(/:/g) ?? []).length > 1) return undefined
74
+ const colon = first.indexOf(':')
75
+ if (colon === -1) return first
76
+ if (colon === 0 || colon === first.length - 1) return undefined
77
+ if (!validPortSuffix(first.slice(colon))) return undefined
78
+ return first
79
+ }
80
+
81
+ /**
82
+ * @param {string} suffix a `:port` string
83
+ * @returns {boolean}
84
+ */
85
+ function validPortSuffix(suffix) {
86
+ if (!/^:\d{1,5}$/.test(suffix)) return false
87
+ const port = Number(suffix.slice(1))
88
+ return Number.isInteger(port) && port >= 1 && port <= 65535
89
+ }
90
+
91
+ /**
92
+ * The protocol the listener itself speaks, from configuration rather than from
93
+ * a request. `getOrigin()` is the fallback for DSH versions that predate the
94
+ * `protocol` getter; it throws before the listener binds, which a health request
95
+ * cannot hit but a unit test can.
96
+ * @param {any} webServer
97
+ * @returns {boolean}
98
+ */
99
+ export function listenerUsesTls(webServer) {
100
+ if (webServer === undefined || webServer === null) return false
101
+ if (webServer.protocol === 'https:') return true
102
+ try {
103
+ const origin = typeof webServer.getOrigin === 'function' ? webServer.getOrigin() : ''
104
+ return typeof origin === 'string' && /^https:/i.test(origin)
105
+ } catch {
106
+ return false
107
+ }
108
+ }
109
+
110
+ /**
111
+ * The authority the listener is bound to, for requests without a usable `Host`.
112
+ * @param {any} webServer
113
+ * @returns {string | undefined}
114
+ */
115
+ export function listenerAuthority(webServer) {
116
+ try {
117
+ const origin = typeof webServer?.getOrigin === 'function' ? webServer.getOrigin() : ''
118
+ if (typeof origin === 'string' && origin !== '') return sanitizeAuthority(new URL(origin).host)
119
+ } catch {
120
+ // Not bound yet, or no URL form: fall through to the configured pair.
121
+ }
122
+ const host = typeof webServer?.host === 'string' ? webServer.host : ''
123
+ const port = Number(webServer?.port)
124
+ if (host === '' || !Number.isInteger(port) || port <= 0) return undefined
125
+ return sanitizeAuthority(host.includes(':') ? `[${host}]:${port}` : `${host}:${port}`)
126
+ }
127
+
128
+ /**
129
+ * @typedef {object} BridgeEndpoint
130
+ * @property {boolean} secure Whether the browser must use `wss://`.
131
+ * @property {'ws' | 'wss'} scheme The websocket scheme to advertise.
132
+ * @property {string} wsUrl Complete websocket URL for this request.
133
+ * @property {string} authority The advertised `host[:port]`.
134
+ * @property {'tls-socket' | 'tls-listener' | 'forwarded-proto' | 'plain'} source
135
+ * Which evidence decided the scheme; useful when a proxy in front is
136
+ * misconfigured and the health response needs to explain itself.
137
+ */
138
+
139
+ /**
140
+ * Describe the endpoint a client reaching this request should connect to.
141
+ * @param {object} [input]
142
+ * @param {any} [input.request] node `IncomingMessage` of the health request.
143
+ * @param {any} [input.webServer] the DSH webserver service the bridge sits on.
144
+ * @param {string} [input.path] websocket path to append.
145
+ * @returns {BridgeEndpoint}
146
+ */
147
+ export function describeEndpoint({ request, webServer, path = WS_PATH } = {}) {
148
+ const tlsSocket = request?.socket?.encrypted === true
149
+ const tlsListener = !tlsSocket && listenerUsesTls(webServer)
150
+ const forwarded = firstForwardedValue(request?.headers?.[FORWARDED_PROTO])
151
+ const forwardedSecure = forwarded === 'https' || forwarded === 'wss'
152
+ const forwardedPlain = forwarded === 'http' || forwarded === 'ws'
153
+ const secure = tlsSocket || tlsListener || forwardedSecure
154
+ const scheme = secure ? 'wss' : 'ws'
155
+ const authority =
156
+ sanitizeAuthority(request?.headers?.[FORWARDED_HOST]) ??
157
+ sanitizeAuthority(request?.headers?.host) ??
158
+ listenerAuthority(webServer) ??
159
+ '127.0.0.1'
160
+ /** @type {BridgeEndpoint['source']} */
161
+ let source = 'plain'
162
+ if (tlsSocket) source = 'tls-socket'
163
+ else if (tlsListener) source = 'tls-listener'
164
+ else if (forwardedSecure || forwardedPlain) source = 'forwarded-proto'
165
+ return { secure, scheme, authority, source, wsUrl: `${scheme}://${authority}${path}` }
166
+ }