@linxin666/dsh-remote-bridge 0.4.12 → 0.4.13

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.
Files changed (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -8
  3. package/README.zh.md +45 -8
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18031 -373
  7. package/lib/types/core/connection.d.ts +9 -0
  8. package/lib/types/core/devices.d.ts +27 -6
  9. package/lib/types/core/liveactivity.d.ts +7 -0
  10. package/lib/types/core/model-efforts.d.ts +83 -0
  11. package/lib/types/core/protocol.d.ts +2 -0
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/host/firewall.d.ts +74 -0
  14. package/lib/types/host/host-bind-capability.d.ts +90 -0
  15. package/lib/types/host/ingress-gate.d.ts +59 -0
  16. package/lib/types/host/ingress-sync.d.ts +429 -0
  17. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  18. package/lib/types/host/lan-bind.d.ts +106 -0
  19. package/lib/types/host/lan-forward.d.ts +112 -0
  20. package/lib/types/host/lan.d.ts +61 -0
  21. package/lib/types/host/pair-origin.d.ts +34 -19
  22. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  23. package/lib/types/host/relay-connector.d.ts +152 -0
  24. package/lib/types/host/relay-control.d.ts +124 -0
  25. package/lib/types/host/relay-registry.d.ts +114 -0
  26. package/lib/types/host/relay.d.ts +170 -0
  27. package/lib/types/host/routes.d.ts +24 -1
  28. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  29. package/lib/types/host/tunnel-plan.d.ts +41 -0
  30. package/lib/types/host/tunnel.d.ts +289 -0
  31. package/lib/types/index.d.ts +426 -1
  32. package/package.json +4 -2
  33. package/src/client/panel.module.css +16 -1
  34. package/src/core/connection.ts +206 -11
  35. package/src/core/devices.ts +31 -6
  36. package/src/core/hub.ts +17 -5
  37. package/src/core/liveactivity.ts +16 -2
  38. package/src/core/model-efforts.ts +223 -0
  39. package/src/core/protocol.ts +3 -0
  40. package/src/core/push.ts +70 -4
  41. package/src/host/firewall.ts +230 -0
  42. package/src/host/host-bind-capability.ts +249 -0
  43. package/src/host/ingress-gate.ts +203 -0
  44. package/src/host/ingress-sync.ts +1074 -0
  45. package/src/host/lan-bind-plan.ts +134 -0
  46. package/src/host/lan-bind.ts +250 -0
  47. package/src/host/lan-forward.ts +321 -0
  48. package/src/host/lan.ts +142 -0
  49. package/src/host/pair-origin.ts +44 -38
  50. package/src/host/relay-bridge-connector.ts +783 -0
  51. package/src/host/relay-connector.ts +317 -0
  52. package/src/host/relay-control.ts +224 -0
  53. package/src/host/relay-registry.ts +263 -0
  54. package/src/host/relay.ts +294 -0
  55. package/src/host/routes.ts +47 -3
  56. package/src/host/tunnel-orphan.ts +325 -0
  57. package/src/host/tunnel-plan.ts +58 -0
  58. package/src/host/tunnel.ts +688 -0
  59. package/src/index.ts +1280 -22
@@ -0,0 +1,1074 @@
1
+ /**
2
+ * Update-only Cloudflare tunnel ingress sync (issue #1948).
3
+ *
4
+ * A named tunnel's public hostname is permanent — that is the whole point of
5
+ * the mode — but the ingress rule behind it names a fixed local port. When
6
+ * `dsh web` listens on another port (an operator changed `--port`, a profile
7
+ * carries a different value, a second instance took the old one), the hostname
8
+ * keeps resolving and answers 502 while this plugin still believes it is
9
+ * published. This module converges exactly that one number and nothing else:
10
+ *
11
+ * - a read (GET) is the only request a healthy start makes;
12
+ * - the plan proves the whole document except the matched rule's `service`
13
+ * string is unchanged, and refuses (a conflict) anything it cannot prove —
14
+ * no added or removed rule, no moved ingress entry, no touched top-level
15
+ * key, no invented catch-all;
16
+ * - the service it retargets has to be this machine's own: loopback, or one of
17
+ * this host's LAN addresses. Another host's address is a conflict, never a
18
+ * write, because the port there belongs to whatever that address serves;
19
+ * - only a proven drift is written, as one full-document PUT (the API offers
20
+ * no patch for a single rule);
21
+ * - the write is read back once. A disagreement is a conflict, never an
22
+ * automatic rewrite: one tunnel document has one writer, and a deployment
23
+ * whose dashboard or another sync owns it has to be reconciled by a human.
24
+ *
25
+ * Everything is offline-testable: the HTTP call and the timers are injected
26
+ * seams, and the default seam itself refuses to send the account token to any
27
+ * origin but `https://api.cloudflare.com`. The token never enters a log line,
28
+ * a status frame, a child process argument, or any browser-visible state — it
29
+ * exists only inside the `Authorization` header of the two requests that need
30
+ * it.
31
+ */
32
+
33
+ import { createHash } from 'node:crypto'
34
+ import { lanIPv4Addresses } from './lan.ts'
35
+
36
+ /** The only origin the Cloudflare API token is ever sent to. */
37
+ export const CLOUDFLARE_API_ORIGIN = 'https://api.cloudflare.com'
38
+
39
+ /** One JSON object as the API document holds it. */
40
+ export type JsonObject = Record<string, unknown>
41
+
42
+ /** Whether a value is a JSON object (not an array, not null). */
43
+ function isJsonObject(value: unknown): value is JsonObject {
44
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
45
+ }
46
+
47
+ /**
48
+ * The configurations endpoint of one tunnel. The account and tunnel ids are
49
+ * opaque path segments, so they are encoded rather than interpolated raw.
50
+ * @param accountId - the Cloudflare account id.
51
+ * @param tunnelId - the named tunnel id (never the tunnel's token).
52
+ * @returns the absolute API URL the sync reads and writes.
53
+ */
54
+ export function ingressConfigUrl(accountId: string, tunnelId: string): string {
55
+ return `${CLOUDFLARE_API_ORIGIN}/client/v4/accounts/${encodeURIComponent(accountId)}/cfd_tunnel/${encodeURIComponent(tunnelId)}/configurations`
56
+ }
57
+
58
+ /**
59
+ * The lower-cased hostname a configured public base names. Wildcards are not
60
+ * supported by this sync (the target rule must match one exact hostname), so a
61
+ * wildcard base is refused here rather than matched loosely later.
62
+ * @param publicBaseUrl - the configured public base URL.
63
+ * @returns the hostname to match in the ingress, or undefined when the value
64
+ * is missing, unparsable, not http(s), or a wildcard.
65
+ */
66
+ export function hostnameOf(publicBaseUrl: string | undefined): string | undefined {
67
+ if (publicBaseUrl === undefined || publicBaseUrl.trim() === '') return undefined
68
+ try {
69
+ const url = new URL(publicBaseUrl)
70
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined
71
+ const hostname = url.hostname.toLowerCase()
72
+ if (hostname === '' || hostname.includes('*')) return undefined
73
+ return hostname
74
+ } catch {
75
+ return undefined
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Retarget one tunnel service string at a port, changing nothing else. The
81
+ * authority's host (including an IPv6 literal and any userinfo), the path, the
82
+ * query, and the fragment are preserved byte for byte, so the plan can prove
83
+ * the only difference in the document is the port digits.
84
+ * @param service - the rule's current service string (e.g. `http://127.0.0.1:3080`).
85
+ * @param port - the port this host's web server actually bound.
86
+ * @returns the retargeted service, or undefined when the value is not an
87
+ * http(s) origin this sync can safely rewrite.
88
+ */
89
+ export function serviceWithPort(service: string, port: number): string | undefined {
90
+ if (!Number.isInteger(port) || port < 1 || port > 65_535) return undefined
91
+ const match = /^(https?:\/\/)([^/?#]*)([\s\S]*)$/.exec(service)
92
+ if (match === null) return undefined
93
+ const scheme = match[1] as string
94
+ const authority = match[2] as string
95
+ const rest = match[3] as string
96
+ const at = authority.lastIndexOf('@')
97
+ const userinfo = at >= 0 ? authority.slice(0, at + 1) : ''
98
+ const hostPart = authority.slice(at + 1)
99
+ let host: string
100
+ if (hostPart.startsWith('[')) {
101
+ const end = hostPart.indexOf(']')
102
+ if (end < 0) return undefined
103
+ host = hostPart.slice(0, end + 1)
104
+ const after = hostPart.slice(end + 1)
105
+ if (after !== '' && !/^:\d*$/.test(after)) return undefined
106
+ } else {
107
+ const colon = hostPart.lastIndexOf(':')
108
+ const after = colon >= 0 ? hostPart.slice(colon) : ''
109
+ if (after !== '' && !/^:\d*$/.test(after)) return undefined
110
+ host = colon >= 0 ? hostPart.slice(0, colon) : hostPart
111
+ }
112
+ if (host === '' || host === '[]') return undefined
113
+ return `${scheme}${userinfo}${host}:${String(port)}${rest}`
114
+ }
115
+
116
+ /**
117
+ * The authority host of one service string, with IPv6 brackets kept. The port
118
+ * and any userinfo are dropped, so the host can be judged on its own.
119
+ * @param service - the rule's service string.
120
+ * @returns the host, or undefined when the value is not an http(s) origin.
121
+ */
122
+ export function serviceHostOf(service: string): string | undefined {
123
+ const match = /^(https?:\/\/)([^/?#]*)([\s\S]*)$/.exec(service)
124
+ if (match === null) return undefined
125
+ const authority = match[2] as string
126
+ const hostPart = authority.slice(authority.lastIndexOf('@') + 1)
127
+ if (hostPart.startsWith('[')) {
128
+ const end = hostPart.indexOf(']')
129
+ return end < 0 ? undefined : hostPart.slice(0, end + 1)
130
+ }
131
+ const colon = hostPart.lastIndexOf(':')
132
+ const host = colon >= 0 ? hostPart.slice(0, colon) : hostPart
133
+ return host === '' ? undefined : host
134
+ }
135
+
136
+ /**
137
+ * One service string with its userinfo removed, for everything that leaves
138
+ * this process. A tunnel service may carry `user:password@`, and the
139
+ * update-only write has to preserve that byte for byte — but an audit frame, a
140
+ * log line, or the settings card has no business showing a credential the
141
+ * operator put there for the origin.
142
+ * @param service - the rule's service string.
143
+ * @returns the same service with any `userinfo@` dropped.
144
+ */
145
+ export function redactServiceUserinfo(service: string): string {
146
+ const match = /^(https?:\/\/)([^/?#]*)([\s\S]*)$/.exec(service)
147
+ if (match === null) return service
148
+ const scheme = match[1] as string
149
+ const authority = match[2] as string
150
+ const rest = match[3] as string
151
+ const at = authority.lastIndexOf('@')
152
+ return at < 0 ? service : `${scheme}${authority.slice(at + 1)}${rest}`
153
+ }
154
+
155
+ /** Whether one dotted-quad segment is a decimal octet (0-255), not a sign or a space. */
156
+ function isIpv4Octet(segment: string): boolean {
157
+ return /^\d{1,3}$/.test(segment) && Number(segment) <= 255
158
+ }
159
+
160
+ /**
161
+ * Whether one service authority host is a target this host may own: a loopback
162
+ * literal (any 127.0.0.0/8 address, `::1`, or `localhost`) or one of this
163
+ * machine's own LAN IPv4 addresses. A service pointing anywhere else — another
164
+ * machine, a DNS name, a NAS — is not this plugin's to retarget, and rewriting
165
+ * its port would break whatever service that address actually is.
166
+ * @param host - the authority host of the service (brackets kept for IPv6).
167
+ * @param lanHosts - this machine's LAN IPv4 addresses.
168
+ * @returns whether the service may be retargeted.
169
+ */
170
+ export function isRetargetableHost(host: string, lanHosts: readonly string[] = []): boolean {
171
+ const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host
172
+ const name = bare.toLowerCase()
173
+ if (name === '') return false
174
+ if (name === 'localhost' || name === '::1') return true
175
+ // 127.0.0.0/8 is the whole loopback block, not just 127.0.0.1 — but each
176
+ // dotted segment still has to be a real octet, or `127.999.999.999` would
177
+ // read as loopback and this sync would retarget a service nobody owns.
178
+ const octets = name.split('.')
179
+ if (octets.length === 4 && octets[0] === '127' && octets.every(isIpv4Octet)) return true
180
+ return lanHosts.some(candidate => candidate.toLowerCase() === name)
181
+ }
182
+
183
+ /** The marker a stripped service string is replaced with, for the proof below. */
184
+ const STRIPPED_SERVICE = '\u0000remote-web-ui:ingress-service\u0000'
185
+
186
+ /**
187
+ * One document with the target rule's `service` string replaced by a marker.
188
+ * Two documents whose stripped forms are identical differ at that one key and
189
+ * nowhere else — which is the invariant the plan must prove before it writes.
190
+ * @param document - the tunnel configuration document.
191
+ * @param ruleIndex - the ingress rule the sync owns.
192
+ * @returns the canonical JSON of the stripped document.
193
+ */
194
+ export function withoutTargetService(document: unknown, ruleIndex: number): string {
195
+ const copy = structuredClone(document) as JsonObject
196
+ const ingress = copy.ingress
197
+ if (Array.isArray(ingress)) {
198
+ const rule = ingress[ruleIndex]
199
+ if (isJsonObject(rule)) rule.service = STRIPPED_SERVICE
200
+ }
201
+ return JSON.stringify(copy)
202
+ }
203
+
204
+ /** Why a plan refuses to write. Every code is a zero-write verdict. */
205
+ export type IngressConflictCode =
206
+ | 'hostname'
207
+ | 'config-shape'
208
+ | 'ingress-shape'
209
+ | 'rule-shape'
210
+ | 'wildcard'
211
+ | 'missing'
212
+ | 'duplicate'
213
+ | 'no-catch-all'
214
+ | 'service-shape'
215
+ | 'service-host'
216
+
217
+ /** What one document read asks the plan to converge on. */
218
+ export interface IngressTarget {
219
+ /** The lower-cased public hostname of the named tunnel. */
220
+ hostname: string
221
+ /** The port this host's web server actually bound. */
222
+ port: number
223
+ /**
224
+ * The LAN IPv4 addresses this machine owns (`lanIPv4Addresses()`). The plan
225
+ * refuses a service that points anywhere but loopback or one of these, so an
226
+ * update-only write can never retarget a service that belongs to another host.
227
+ */
228
+ allowedHosts?: readonly string[]
229
+ }
230
+
231
+ /** The verdict of one plan: read-only, one write, or a refusal. */
232
+ export type IngressPlan =
233
+ | {
234
+ outcome: 'unchanged'
235
+ hostname: string
236
+ ruleIndex: number
237
+ ruleCount: number
238
+ service: string
239
+ }
240
+ | {
241
+ outcome: 'apply'
242
+ hostname: string
243
+ ruleIndex: number
244
+ ruleCount: number
245
+ from: string
246
+ to: string
247
+ /** The full document to PUT: identical to the read document except one service. */
248
+ document: JsonObject
249
+ }
250
+ | {
251
+ outcome: 'conflict'
252
+ code: IngressConflictCode
253
+ hostname: string
254
+ detail: string
255
+ }
256
+
257
+ /**
258
+ * Plan one update-only ingress change against a document read from the API.
259
+ *
260
+ * The supported shape is a Cloudflare tunnel configuration: an object whose
261
+ * `ingress` is an array of rule objects, exactly one of which carries the
262
+ * target hostname, and whose last rule is a catch-all (no `hostname`). A
263
+ * document outside that shape — a missing `ingress`, a wildcard anywhere, a
264
+ * duplicated hostname, no catch-all, a rule that is not an object, a service
265
+ * that is not an http(s) origin, or a service whose host is not this machine —
266
+ * is a conflict and produces no document, so the caller cannot accidentally
267
+ * write. The two service strings the verdict reports are redacted of userinfo:
268
+ * they are audit facts, and the write itself is carried by the document.
269
+ * @param config - the `result.config` document read from the API.
270
+ * @param target - the hostname, the port, and this machine's own addresses.
271
+ * @returns unchanged (one read is enough), apply (the document to PUT), or a
272
+ * conflict with the reason.
273
+ */
274
+ export function planIngressUpdate(config: unknown, target: IngressTarget): IngressPlan {
275
+ const conflict = (code: IngressConflictCode, detail: string): IngressPlan => ({ outcome: 'conflict', code, hostname: target.hostname, detail })
276
+ if (!isJsonObject(config)) return conflict('config-shape', 'the tunnel configuration is not an object')
277
+ const ingress = config.ingress
278
+ if (!Array.isArray(ingress)) return conflict('config-shape', 'the tunnel configuration carries no ingress array')
279
+ if (ingress.length === 0) return conflict('no-catch-all', 'the ingress list is empty, so it has no catch-all rule')
280
+ let matches = 0
281
+ let matchIndex: number | undefined
282
+ for (let index = 0; index < ingress.length; index += 1) {
283
+ const rule = ingress[index]
284
+ if (!isJsonObject(rule)) return conflict('rule-shape', `ingress rule ${String(index)} is not an object`)
285
+ const hostname = rule.hostname
286
+ if (hostname === undefined) continue
287
+ if (typeof hostname !== 'string') return conflict('rule-shape', `ingress rule ${String(index)} carries a hostname that is not a string`)
288
+ if (hostname.includes('*')) {
289
+ return conflict('wildcard', `ingress rule ${String(index)} uses the wildcard hostname ${JSON.stringify(hostname)}, which this sync never matches`)
290
+ }
291
+ if (hostname.toLowerCase() === target.hostname) {
292
+ matches += 1
293
+ matchIndex = index
294
+ }
295
+ }
296
+ const last = ingress[ingress.length - 1]
297
+ if (!isJsonObject(last) || typeof last.hostname === 'string') {
298
+ return conflict('no-catch-all', 'the last ingress rule carries a hostname, so the list has no catch-all')
299
+ }
300
+ if (matches === 0) return conflict('missing', `no ingress rule names ${target.hostname}`)
301
+ if (matches > 1 || matchIndex === undefined) {
302
+ return conflict('duplicate', `${String(matches)} ingress rules name ${target.hostname}, so this sync cannot tell which one it owns`)
303
+ }
304
+ const rule = ingress[matchIndex]
305
+ if (!isJsonObject(rule)) return conflict('rule-shape', `ingress rule ${String(matchIndex)} is not an object`)
306
+ const service = rule.service
307
+ if (typeof service !== 'string' || service === '') {
308
+ return conflict('service-shape', `ingress rule ${String(matchIndex)} carries no service string`)
309
+ }
310
+ const serviceHost = serviceHostOf(service)
311
+ if (serviceHost === undefined) {
312
+ return conflict('service-shape', `ingress rule ${String(matchIndex)} service ${JSON.stringify(redactServiceUserinfo(service))} is not an http(s) origin this sync can retarget`)
313
+ }
314
+ // Update-only has to mean "this host's own service": retargeting the port of
315
+ // another machine's address, or of a DNS name that resolves elsewhere, would
316
+ // silently break a service this plugin does not own.
317
+ if (!isRetargetableHost(serviceHost, target.allowedHosts ?? [])) {
318
+ return conflict('service-host', `ingress rule ${String(matchIndex)} points at ${JSON.stringify(serviceHost)}, which is neither loopback nor one of this machine's LAN addresses`)
319
+ }
320
+ const next = serviceWithPort(service, target.port)
321
+ if (next === undefined) {
322
+ return conflict('service-shape', `ingress rule ${String(matchIndex)} service ${JSON.stringify(redactServiceUserinfo(service))} is not an http(s) origin this sync can retarget`)
323
+ }
324
+ if (next === service) {
325
+ return { outcome: 'unchanged', hostname: target.hostname, ruleIndex: matchIndex, ruleCount: ingress.length, service: redactServiceUserinfo(service) }
326
+ }
327
+ const document = structuredClone(config) as JsonObject
328
+ const rules = document.ingress as unknown[]
329
+ const cloned = rules[matchIndex]
330
+ if (!isJsonObject(cloned)) return conflict('rule-shape', `ingress rule ${String(matchIndex)} is not an object`)
331
+ cloned.service = next
332
+ if (withoutTargetService(config, matchIndex) !== withoutTargetService(document, matchIndex)) {
333
+ return conflict('config-shape', 'the rewrite would touch a part of the document outside the target rule service')
334
+ }
335
+ return {
336
+ outcome: 'apply',
337
+ hostname: target.hostname,
338
+ ruleIndex: matchIndex,
339
+ ruleCount: ingress.length,
340
+ // Audit labels only: the document above carries the userinfo untouched, so
341
+ // the write is byte-identical to the read apart from the port.
342
+ from: redactServiceUserinfo(service),
343
+ to: redactServiceUserinfo(next),
344
+ document,
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Read the tunnel configuration out of one API envelope. The API answers
350
+ * `{ success, result: { config: {...} }, errors }`; a body that shapes
351
+ * differently is reported, never guessed at.
352
+ * @param body - the parsed response body.
353
+ * @returns the config document, or undefined when the envelope carries none.
354
+ */
355
+ export function configOfEnvelope(body: unknown): JsonObject | undefined {
356
+ if (!isJsonObject(body)) return undefined
357
+ const result = body.result
358
+ if (!isJsonObject(result)) return undefined
359
+ const config = result.config
360
+ return isJsonObject(config) ? config : undefined
361
+ }
362
+
363
+ /**
364
+ * The API's own error messages from one envelope, joined for the audit frame.
365
+ * Cloudflare answers 4xx/5xx with a populated `errors` array; the messages are
366
+ * safe to show (they name the credential's missing permission, never its value).
367
+ * @param body - the parsed response body.
368
+ * @returns a short joined summary, or undefined when the envelope carries none.
369
+ */
370
+ export function errorsOfEnvelope(body: unknown): string | undefined {
371
+ if (!isJsonObject(body)) return undefined
372
+ const errors = body.errors
373
+ if (!Array.isArray(errors)) return undefined
374
+ const messages: string[] = []
375
+ for (const entry of errors) {
376
+ if (!isJsonObject(entry)) continue
377
+ const message = entry.message
378
+ if (typeof message === 'string' && message !== '') messages.push(message)
379
+ }
380
+ return messages.length === 0 ? undefined : messages.join(' ')
381
+ }
382
+
383
+ /** One HTTP call the sync makes. */
384
+ export interface IngressHttpRequest {
385
+ method: 'GET' | 'PUT'
386
+ url: string
387
+ headers: Record<string, string>
388
+ body?: string
389
+ }
390
+
391
+ /** One HTTP answer the sync reads. */
392
+ export interface IngressHttpResponse {
393
+ status: number
394
+ /** The parsed JSON body (or the raw text when it was not JSON). */
395
+ body: unknown
396
+ }
397
+
398
+ /** The injected HTTP seam: tests never reach a real API through it. */
399
+ export type IngressFetch = (request: IngressHttpRequest) => Promise<IngressHttpResponse>
400
+
401
+ /**
402
+ * The default seam: one `fetch` round trip, and a hard refusal to send the
403
+ * account token outside the Cloudflare API even if a caller builds such a URL.
404
+ * @param request - the call to make.
405
+ * @returns the status and parsed body.
406
+ */
407
+ export const defaultIngressFetch: IngressFetch = async (request) => {
408
+ if (!request.url.startsWith(`${CLOUDFLARE_API_ORIGIN}/`)) {
409
+ throw new Error('remote-web-ui: refusing to send the Cloudflare API token outside api.cloudflare.com')
410
+ }
411
+ const response = await fetch(request.url, {
412
+ method: request.method,
413
+ headers: request.headers,
414
+ ...(request.body !== undefined ? { body: request.body } : {}),
415
+ })
416
+ const text = await response.text()
417
+ let body: unknown
418
+ if (text === '') {
419
+ body = undefined
420
+ } else {
421
+ try {
422
+ body = JSON.parse(text) as unknown
423
+ } catch {
424
+ body = text
425
+ }
426
+ }
427
+ return { status: response.status, body }
428
+ }
429
+
430
+ /** Timer seam (injected in tests; a synchronous double makes a run immediate). */
431
+ export interface IngressTimer {
432
+ setTimeout(fn: () => void, ms: number): unknown
433
+ clearTimeout(handle: unknown): void
434
+ }
435
+
436
+ /** The observable state one sync reports. */
437
+ export type IngressSyncState = 'off' | 'waiting' | 'applied' | 'failed' | 'conflict'
438
+
439
+ /**
440
+ * One audit frame. It carries the public hostname, the local port, the two
441
+ * service strings, the rule position, and a failure reason — never the token,
442
+ * never the credential's account id, and never a response body.
443
+ */
444
+ export interface IngressSyncFrame {
445
+ state: IngressSyncState
446
+ /** The public hostname read from `publicBaseUrl`. */
447
+ hostname?: string
448
+ /** The port this host's web server actually bound. */
449
+ port?: number
450
+ /** The service string the remote rule holds after the last run. */
451
+ service?: string
452
+ /** The service string an apply moved away from. */
453
+ previousService?: string
454
+ /** How many ingress rules the read document carried. */
455
+ ruleCount?: number
456
+ /** Index of the rule this sync owns. */
457
+ ruleIndex?: number
458
+ /** Whether the last run actually wrote the document. */
459
+ changed?: boolean
460
+ /** Machine-readable reason of a failed or conflict frame. */
461
+ code?: string
462
+ /** Human-readable detail (hostname, port, status, API message) — no secret. */
463
+ detail?: string
464
+ /** When this state was reached (ms epoch). */
465
+ at: number
466
+ }
467
+
468
+ /** What one {@link IngressSync.schedule} call asks the runner to converge on. */
469
+ export interface IngressSyncInput {
470
+ /** The master switch AND the ingress toggle; false makes no request at all. */
471
+ enabled: boolean
472
+ /** The lower-cased public hostname (`hostnameOf(publicBaseUrl)`). */
473
+ hostname: string | undefined
474
+ /** The bound web server port; undefined before the listener binds. */
475
+ port: number | undefined
476
+ /** Account-level API token (secret; only ever in the Authorization header). */
477
+ token: string | undefined
478
+ /** Cloudflare account id. */
479
+ accountId: string | undefined
480
+ /** Named tunnel id. */
481
+ tunnelId: string | undefined
482
+ }
483
+
484
+ /** Injectable seams and timings. */
485
+ export interface IngressSyncOptions {
486
+ /** HTTP seam; defaults to the guarded real `fetch`. */
487
+ fetch?: IngressFetch
488
+ /** Clock (injected in tests). */
489
+ now?: () => number
490
+ /** Short debounce before a scheduled run starts (ms). */
491
+ debounceMs?: number
492
+ /** First backoff step of a transient failure (ms; doubles per retry). */
493
+ retryBaseMs?: number
494
+ /** Retries after the first attempt; bounded for the whole run. */
495
+ maxRetries?: number
496
+ /** Timer seam (injected in tests). */
497
+ timer?: IngressTimer
498
+ /**
499
+ * This machine's LAN IPv4 addresses (injected in tests; the live list by
500
+ * default). The plan refuses to retarget a service hosted anywhere else.
501
+ */
502
+ lanHosts?: () => readonly string[]
503
+ /** Frame sink (the host writes it into the pairing snapshot). */
504
+ onFrame?: (frame: IngressSyncFrame) => void
505
+ }
506
+
507
+ /** Debounce before a scheduled run: a port settle and a settings save coalesce. */
508
+ export const DEFAULT_INGRESS_DEBOUNCE_MS = 300
509
+ /** First backoff step of a retried request. */
510
+ export const DEFAULT_INGRESS_RETRY_BASE_MS = 500
511
+ /** Retries after the first attempt of one request (so three attempts at most). */
512
+ export const DEFAULT_INGRESS_MAX_RETRIES = 2
513
+
514
+ /** Node timers. */
515
+ const nodeTimer: IngressTimer = {
516
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
517
+ clearTimeout: (handle) => { clearTimeout(handle as Parameters<typeof clearTimeout>[0]) },
518
+ }
519
+
520
+ /** Cap one audit detail so a chatty API message cannot bloat a status frame. */
521
+ function tidy(text: string): string {
522
+ return text.length <= 240 ? text : `${text.slice(0, 237)}...`
523
+ }
524
+
525
+ /** The API's own messages as a parenthetical, when the envelope carries any. */
526
+ function errorsText(body: unknown): string {
527
+ const errors = errorsOfEnvelope(body)
528
+ return errors === undefined ? '' : ` (${tidy(errors)})`
529
+ }
530
+
531
+ /**
532
+ * Two audit frames that describe the same state (the timestamp is not part of
533
+ * it). The pairing snapshot dedupe uses this, so a re-read that proves the same
534
+ * convergence never emits a second event.
535
+ * @param a - one frame.
536
+ * @param b - the other frame.
537
+ * @returns whether both describe the same state.
538
+ */
539
+ export function sameIngressFrame(a: IngressSyncFrame, b: IngressSyncFrame): boolean {
540
+ return a.state === b.state && a.hostname === b.hostname && a.port === b.port
541
+ && a.service === b.service && a.previousService === b.previousService
542
+ && a.ruleCount === b.ruleCount && a.ruleIndex === b.ruleIndex
543
+ && a.changed === b.changed && a.code === b.code && a.detail === b.detail
544
+ }
545
+
546
+ /**
547
+ * A non-reversible label for the account token, so the settle identity changes
548
+ * when the credential does without the token itself ever entering a key, a
549
+ * frame, or a log line. Truncated: 64 bits is far more than a local dedupe
550
+ * needs and a full digest would be a needless copy of the credential's shape.
551
+ * @param token - the account-level API token.
552
+ * @returns a truncated SHA-256 hex digest.
553
+ */
554
+ function tokenDigest(token: string): string {
555
+ return createHash('sha256').update(token).digest('hex').slice(0, 16)
556
+ }
557
+
558
+ /**
559
+ * The identity a converged read is recorded under: the target, the tunnel, and
560
+ * a digest of the credential. A same-port save with a different token is a
561
+ * different identity and is read again; the same one is not read again.
562
+ * @param hostname - the matched public hostname.
563
+ * @param port - the bound port.
564
+ * @param accountId - the Cloudflare account id.
565
+ * @param tunnelId - the named tunnel id.
566
+ * @param token - the account-level API token (digested, never stored).
567
+ * @returns the settle key.
568
+ */
569
+ function settleKeyOf(hostname: string, port: number, accountId: string, tunnelId: string, token: string): string {
570
+ return `${hostname}|${String(port)}|${accountId}|${tunnelId}|${tokenDigest(token)}`
571
+ }
572
+
573
+ /** Which required settings are still missing (an explicit failure, not a retry). */
574
+ function missingConfig(input: IngressSyncInput): string[] {
575
+ const missing: string[] = []
576
+ if (input.token === undefined || input.token === '') missing.push('cfApiToken')
577
+ if (input.accountId === undefined || input.accountId === '') missing.push('cfAccountId')
578
+ if (input.tunnelId === undefined || input.tunnelId === '') missing.push('cfTunnelId')
579
+ return missing
580
+ }
581
+
582
+ /** The resolved plugin settings this adapter reads (nothing else is consulted). */
583
+ export interface IngressSettingsSlice {
584
+ /** The plugin master switch. */
585
+ enabled: boolean
586
+ /** The ingress-sync switch. */
587
+ ingressSync?: boolean
588
+ /** Whether the quick tunnel runs (it owns the public base and mints its own hostname). */
589
+ autoTunnel?: boolean
590
+ /** The fixed public hostname of the named tunnel. */
591
+ publicBaseUrl?: string
592
+ /** Account-level API token (a settings secret). */
593
+ cfApiToken?: string
594
+ /** Cloudflare account id. */
595
+ cfAccountId?: string
596
+ /** Named tunnel id. */
597
+ cfTunnelId?: string
598
+ }
599
+
600
+ /** One configured string, or undefined when it is missing or blank. */
601
+ function blankToUndefined(value: string | undefined): string | undefined {
602
+ if (value === undefined) return undefined
603
+ const trimmed = value.trim()
604
+ return trimmed === '' ? undefined : trimmed
605
+ }
606
+
607
+ /**
608
+ * Normalize one web server port into a target or into nothing. A recompose pass
609
+ * can hand the plugin a half-read webServer whose port is `NaN` or
610
+ * `Infinity`; that is not a port, and treating it as one would either mint a
611
+ * `127.0.0.1:NaN` target or leave the caller waiting forever. The host reads
612
+ * the port through this, so a non-finite value takes exactly the path an
613
+ * unbound one does: the existing port-settle retry re-plans it.
614
+ * @param port - the live `ctx.webServer.port`.
615
+ * @returns the port, or undefined when it is not a finite number.
616
+ */
617
+ export function livePortOf(port: number | undefined): number | undefined {
618
+ return typeof port === 'number' && Number.isFinite(port) ? port : undefined
619
+ }
620
+
621
+ /**
622
+ * The one place resolved settings become a sync input, so "which switch turns
623
+ * this on" is testable without a cordis context. Three conditions, all
624
+ * required: the master switch, the ingress toggle, and the quick tunnel being
625
+ * off — a quick tunnel mints a new hostname per start and owns the public base,
626
+ * so that deployment has no named tunnel to update and the sync reads as off
627
+ * instead of editing an unrelated tunnel.
628
+ * @param value - the resolved settings.
629
+ * @param port - the bound web server port, undefined before the listener binds.
630
+ * @returns the input to schedule.
631
+ */
632
+ export function ingressInputOf(value: IngressSettingsSlice, port: number | undefined): IngressSyncInput {
633
+ return {
634
+ enabled: value.enabled && value.ingressSync === true && value.autoTunnel !== true,
635
+ hostname: hostnameOf(value.publicBaseUrl),
636
+ // A compose pass can hand a half-read webServer through: NaN or Infinity is
637
+ // not a target, it is a wait for the port-settle re-plan that delivers it.
638
+ port: livePortOf(port),
639
+ token: blankToUndefined(value.cfApiToken),
640
+ accountId: blankToUndefined(value.cfAccountId),
641
+ tunnelId: blankToUndefined(value.cfTunnelId),
642
+ }
643
+ }
644
+
645
+ /** The first run's terminal reason for one request, when it is not retryable. */
646
+ type RequestFailure = { ok: false; code: string; detail: string }
647
+
648
+ /**
649
+ * Converge one named tunnel's ingress service onto this host's actual port.
650
+ *
651
+ * Scheduling is single-flight and generation-guarded: a later schedule (a
652
+ * settings save, a port settle) supersedes an in-flight run at its next
653
+ * checkpoint — before every request attempt, so a running backoff cannot
654
+ * outlive its target, and again immediately before the single PUT. Ports
655
+ * arrive late, and a half-read webServer can hand a non-finite number: neither
656
+ * one schedules anything, so no request is made and the caller's existing
657
+ * port-settle re-plan delivers the real port.
658
+ */
659
+ export class IngressSync {
660
+ private readonly http: IngressFetch
661
+ private readonly now: () => number
662
+ private readonly debounceMs: number
663
+ private readonly retryBaseMs: number
664
+ private readonly maxRetries: number
665
+ private readonly timer: IngressTimer
666
+ private readonly onFrame: (frame: IngressSyncFrame) => void
667
+ private readonly lanHosts: () => readonly string[]
668
+
669
+ private current: IngressSyncFrame
670
+ private input: IngressSyncInput | undefined
671
+ private generation = 0
672
+ private pending = false
673
+ private debounce: unknown
674
+ /** The serialized run chain: one run at a time, queued schedules after it. */
675
+ private chain: Promise<void> = Promise.resolve()
676
+ /** Whether the chain currently holds a live run (a later schedule only queues). */
677
+ private running = false
678
+ /** Whether the sink has been told about a state yet (the first one always goes out). */
679
+ private emitted = false
680
+ /** The `hostname|port|account|tunnel|token-digest` a read last proved converged. */
681
+ private settledKey: string | undefined
682
+ /** Backoff waits in flight, so a dispose can cut them short. */
683
+ private readonly waits = new Set<{ handle: unknown; resolve: () => void }>()
684
+ private disposed = false
685
+
686
+ /**
687
+ * @param options - seams, timings, and the frame sink.
688
+ */
689
+ constructor(options: IngressSyncOptions = {}) {
690
+ this.http = options.fetch ?? defaultIngressFetch
691
+ this.now = options.now ?? (() => Date.now())
692
+ this.debounceMs = options.debounceMs ?? DEFAULT_INGRESS_DEBOUNCE_MS
693
+ this.retryBaseMs = options.retryBaseMs ?? DEFAULT_INGRESS_RETRY_BASE_MS
694
+ this.maxRetries = options.maxRetries ?? DEFAULT_INGRESS_MAX_RETRIES
695
+ this.timer = options.timer ?? nodeTimer
696
+ this.onFrame = options.onFrame ?? (() => undefined)
697
+ this.lanHosts = options.lanHosts ?? lanIPv4Addresses
698
+ this.current = { state: 'off', at: this.now() }
699
+ }
700
+
701
+ /** The latest audit frame. */
702
+ get frame(): IngressSyncFrame {
703
+ return this.current
704
+ }
705
+
706
+ /**
707
+ * Ask the sync to converge on one input. Safe to call on every settings save
708
+ * and every port settle: an already-converged target is a no-op, and an
709
+ * unchanged schedule does not repeat its frame.
710
+ * @param input - the switch, the target, and the credentials to use.
711
+ */
712
+ schedule(input: IngressSyncInput): void {
713
+ if (this.disposed) return
714
+ this.input = input
715
+ if (!input.enabled) {
716
+ this.invalidate()
717
+ this.publish({ state: 'off', at: this.now() })
718
+ return
719
+ }
720
+ if (input.hostname === undefined) {
721
+ // No hostname is no target: the in-flight run has to lose its claim the
722
+ // same way a switch-off does, or it could still write (and report an
723
+ // applied frame) for a target the operator has already unset.
724
+ this.invalidate()
725
+ this.publish({
726
+ state: 'failed',
727
+ code: 'hostname',
728
+ detail: 'ingress sync needs publicBaseUrl to name the fixed public hostname of the named tunnel',
729
+ at: this.now(),
730
+ })
731
+ return
732
+ }
733
+ const port = input.port
734
+ // A port that is not a finite number is not a target: a compose pass can
735
+ // hand NaN/Infinity through a half-read webServer, and that must wait for
736
+ // the settle re-plan instead of becoming a "conflict" about our own config.
737
+ if (typeof port !== 'number' || !Number.isFinite(port)) {
738
+ // No listener yet: make no request. The caller re-schedules once the port
739
+ // settles (its existing retry), so waiting is the whole behavior here —
740
+ // and the in-flight run is invalidated so it cannot write without one.
741
+ this.invalidate()
742
+ this.publish({ state: 'waiting', hostname: input.hostname, at: this.now() })
743
+ return
744
+ }
745
+ const missing = missingConfig(input)
746
+ if (missing.length > 0) {
747
+ this.invalidate()
748
+ this.publish({
749
+ state: 'failed',
750
+ code: 'not-configured',
751
+ hostname: input.hostname,
752
+ port,
753
+ detail: `ingress sync is on but these settings are empty: ${missing.join(', ')}`,
754
+ at: this.now(),
755
+ })
756
+ return
757
+ }
758
+ const key = settleKeyOf(input.hostname, port, input.accountId ?? '', input.tunnelId ?? '', input.token ?? '')
759
+ if (key === this.settledKey && this.current.state === 'applied') return
760
+ this.generation += 1
761
+ this.pending = true
762
+ this.publish({ state: 'waiting', hostname: input.hostname, port, at: this.now() })
763
+ this.armDebounce()
764
+ }
765
+
766
+ /**
767
+ * Await every run scheduled so far. A test seam: the host never awaits it,
768
+ * and a synchronous timer double makes the whole chain settle immediately.
769
+ * @returns the settled run chain.
770
+ */
771
+ settled(): Promise<void> {
772
+ return this.chain
773
+ }
774
+
775
+ /** Release the timers; an in-flight run finishes its checkpoints as no-ops. */
776
+ dispose(): void {
777
+ if (this.disposed) return
778
+ this.disposed = true
779
+ this.generation += 1
780
+ this.pending = false
781
+ this.input = undefined
782
+ this.settledKey = undefined
783
+ this.cancelDebounce()
784
+ this.cancelWaits()
785
+ }
786
+
787
+ /**
788
+ * Drop every claim this sync holds on a target: a newer generation (so an
789
+ * in-flight run cannot write, settle, or report an applied frame), no queued
790
+ * run, no converged identity, no pending debounce. Every branch of
791
+ * {@link schedule} that ends up without a target calls this, so "there is
792
+ * nothing to converge on" and "the switch is off" are one rule rather than
793
+ * four that can drift apart.
794
+ */
795
+ private invalidate(): void {
796
+ this.generation += 1
797
+ this.pending = false
798
+ this.settledKey = undefined
799
+ this.cancelDebounce()
800
+ }
801
+
802
+ private armDebounce(): void {
803
+ this.cancelDebounce()
804
+ this.debounce = this.timer.setTimeout(() => {
805
+ this.debounce = undefined
806
+ this.pump()
807
+ }, this.debounceMs)
808
+ }
809
+
810
+ private cancelDebounce(): void {
811
+ if (this.debounce === undefined) return
812
+ this.timer.clearTimeout(this.debounce)
813
+ this.debounce = undefined
814
+ }
815
+
816
+ /**
817
+ * Append one run to the serialized chain. The `running` flag is raised before
818
+ * the link starts, so a schedule that lands while a run is in flight only
819
+ * raises `pending` and the live loop picks it up with the newest generation
820
+ * instead of stacking a second link that would read again after it settled.
821
+ */
822
+ private pump(): void {
823
+ if (this.running) {
824
+ this.pending = true
825
+ return
826
+ }
827
+ this.running = true
828
+ this.chain = this.chain.then(async () => {
829
+ try {
830
+ if (this.disposed) return
831
+ do {
832
+ this.pending = false
833
+ await this.run(this.generation)
834
+ } while (this.pending && !this.disposed)
835
+ } finally {
836
+ this.running = false
837
+ }
838
+ }).catch((error: unknown) => {
839
+ // A programming error must not become an unhandled rejection: the request
840
+ // seam own its failures, so anything reaching here is a bug worth a line.
841
+ console.warn(`remote-web-ui: ingress sync run failed (${error instanceof Error ? error.message : String(error)})`)
842
+ })
843
+ }
844
+
845
+ /** One converge attempt toward the current target, superseded by any newer schedule. */
846
+ private async run(generation: number): Promise<void> {
847
+ const input = this.input
848
+ if (this.disposed || generation !== this.generation) return
849
+ if (input === undefined || !input.enabled) return
850
+ const hostname = input.hostname
851
+ const port = input.port
852
+ const token = input.token
853
+ const accountId = input.accountId
854
+ const tunnelId = input.tunnelId
855
+ if (hostname === undefined || port === undefined) return
856
+ if (token === undefined || accountId === undefined || tunnelId === undefined) return
857
+ const url = ingressConfigUrl(accountId, tunnelId)
858
+ // The live LAN list is read here, per run: a machine that changed networks
859
+ // must not be judged by the addresses it had when the process started.
860
+ const target: IngressTarget = { hostname, port, allowedHosts: this.lanHosts() }
861
+ // The same identity `schedule` dedupes on: a converged target is only
862
+ // skipped when the tunnel and a digest of the credential are unchanged too.
863
+ const key = settleKeyOf(hostname, port, accountId, tunnelId, token)
864
+ const audit = (extra: Omit<IngressSyncFrame, 'at' | 'hostname' | 'port'> & Partial<IngressSyncFrame>): IngressSyncFrame => ({
865
+ hostname,
866
+ port,
867
+ ...extra,
868
+ at: this.now(),
869
+ })
870
+
871
+ const read = await this.send('GET', url, token, generation)
872
+ if (this.disposed || generation !== this.generation) return
873
+ if (!read.ok) {
874
+ // A superseded target says nothing about the current one: the queued run
875
+ // reports instead of this one publishing a failure for a stale port.
876
+ if (read.code === 'stale' || read.code === 'disposed') return
877
+ this.publish(audit({ state: 'failed', code: read.code, detail: tidy(read.detail) }))
878
+ return
879
+ }
880
+ const config = configOfEnvelope(read.response.body)
881
+ if (config === undefined) {
882
+ this.publish(audit({
883
+ state: 'failed',
884
+ code: 'config-shape',
885
+ detail: tidy(`the Cloudflare API answered without a tunnel configuration${errorsText(read.response.body)}`),
886
+ }))
887
+ return
888
+ }
889
+ const plan = planIngressUpdate(config, target)
890
+ if (plan.outcome === 'conflict') {
891
+ this.publish(audit({ state: 'conflict', code: plan.code, detail: tidy(plan.detail) }))
892
+ return
893
+ }
894
+ if (plan.outcome === 'unchanged') {
895
+ this.converged(key, audit({
896
+ state: 'applied',
897
+ changed: false,
898
+ service: plan.service,
899
+ ruleCount: plan.ruleCount,
900
+ ruleIndex: plan.ruleIndex,
901
+ }))
902
+ return
903
+ }
904
+ // The one checkpoint that matters: a newer schedule or a dispose cancels
905
+ // the only write this run would make.
906
+ if (this.disposed || generation !== this.generation) return
907
+ const write = await this.send('PUT', url, token, generation, { config: plan.document })
908
+ if (this.disposed || generation !== this.generation) return
909
+ if (!write.ok) {
910
+ if (write.code === 'stale' || write.code === 'disposed') return
911
+ const state = write.code === 'write-rejected' ? 'conflict' : 'failed'
912
+ this.publish(audit({ state, code: write.code, detail: tidy(write.detail) }))
913
+ return
914
+ }
915
+ // Read the document back once. A disagreement is a conflict and is never
916
+ // rewritten here: one tunnel document has one writer.
917
+ const verify = await this.send('GET', url, token, generation)
918
+ if (this.disposed || generation !== this.generation) return
919
+ if (!verify.ok) {
920
+ if (verify.code === 'stale' || verify.code === 'disposed') return
921
+ this.publish(audit({
922
+ state: 'failed',
923
+ code: verify.code,
924
+ detail: tidy(`the write succeeded but its verification read failed: ${verify.detail}`),
925
+ service: plan.to,
926
+ previousService: plan.from,
927
+ ruleCount: plan.ruleCount,
928
+ ruleIndex: plan.ruleIndex,
929
+ changed: true,
930
+ }))
931
+ return
932
+ }
933
+ const verified = configOfEnvelope(verify.response.body)
934
+ const check = verified === undefined ? undefined : planIngressUpdate(verified, target)
935
+ if (check === undefined || check.outcome !== 'unchanged') {
936
+ this.publish(audit({
937
+ state: 'conflict',
938
+ code: 'verify-mismatch',
939
+ detail: tidy('the tunnel configuration read back does not hold the applied service; another writer may own this document, so it is not rewritten'),
940
+ service: plan.to,
941
+ previousService: plan.from,
942
+ ruleCount: plan.ruleCount,
943
+ ruleIndex: plan.ruleIndex,
944
+ changed: true,
945
+ }))
946
+ return
947
+ }
948
+ this.converged(key, audit({
949
+ state: 'applied',
950
+ changed: true,
951
+ service: plan.to,
952
+ previousService: plan.from,
953
+ ruleCount: plan.ruleCount,
954
+ ruleIndex: plan.ruleIndex,
955
+ }))
956
+ }
957
+
958
+ /** Record the converged target identity and publish the frame that says so. */
959
+ private converged(key: string, frame: IngressSyncFrame): void {
960
+ if (this.disposed) return
961
+ this.settledKey = key
962
+ this.publish(frame)
963
+ }
964
+
965
+ /**
966
+ * Publish one frame, dropping a repeat that describes the same state. The
967
+ * first publish always goes out, so a sink that starts from nothing learns
968
+ * the current state even when it is the initial `off`.
969
+ */
970
+ private publish(frame: IngressSyncFrame): void {
971
+ if (this.disposed) return
972
+ if (this.emitted && sameIngressFrame(this.current, frame)) return
973
+ this.current = frame
974
+ this.emitted = true
975
+ this.onFrame(frame)
976
+ }
977
+
978
+ /**
979
+ * One request with the bounded retry policy: 429, 5xx, and a network failure
980
+ * are retried at most {@link DEFAULT_INGRESS_MAX_RETRIES} times; 401/403 and
981
+ * any other 4xx are terminal, because repeating them cannot help.
982
+ *
983
+ * The run's generation is part of the request: it is checked before every
984
+ * attempt, retries included, so a target superseded while a 429/5xx/network
985
+ * backoff was running stops there instead of writing a document for a port
986
+ * this host no longer serves. The answer is `stale` (or `disposed`) and the
987
+ * caller drops it without publishing.
988
+ */
989
+ private async send(
990
+ method: 'GET' | 'PUT',
991
+ url: string,
992
+ token: string,
993
+ generation: number,
994
+ body?: JsonObject,
995
+ ): Promise<{ ok: true; response: IngressHttpResponse } | RequestFailure> {
996
+ const headers: Record<string, string> = {
997
+ authorization: `Bearer ${token}`,
998
+ accept: 'application/json',
999
+ }
1000
+ if (body !== undefined) headers['content-type'] = 'application/json'
1001
+ const payload = body === undefined ? undefined : JSON.stringify(body)
1002
+ let retries = 0
1003
+ let code = 'network'
1004
+ let detail = 'the request could not be made'
1005
+ for (;;) {
1006
+ if (this.disposed) return { ok: false, code: 'disposed', detail: 'the sync was disposed' }
1007
+ if (generation !== this.generation) {
1008
+ return { ok: false, code: 'stale', detail: 'a newer schedule superseded this request' }
1009
+ }
1010
+ let response: IngressHttpResponse | undefined
1011
+ try {
1012
+ response = await this.http({
1013
+ method,
1014
+ url,
1015
+ headers,
1016
+ ...(payload !== undefined ? { body: payload } : {}),
1017
+ })
1018
+ } catch (error) {
1019
+ response = undefined
1020
+ code = 'network'
1021
+ detail = error instanceof Error ? error.message : String(error)
1022
+ }
1023
+ if (response !== undefined) {
1024
+ const status = response.status
1025
+ if (status === 401) return { ok: false, code: 'unauthorized', detail: 'the Cloudflare API rejected the token (401)' }
1026
+ if (status === 403) return { ok: false, code: 'forbidden', detail: `the Cloudflare API refused this credential for the tunnel (403)${errorsText(response.body)}` }
1027
+ if (status < 400) return { ok: true, response }
1028
+ if (status !== 429 && status < 500) {
1029
+ return {
1030
+ ok: false,
1031
+ code: method === 'PUT' ? 'write-rejected' : 'http',
1032
+ detail: `the Cloudflare API answered ${String(status)}${errorsText(response.body)}`,
1033
+ }
1034
+ }
1035
+ code = 'http'
1036
+ detail = `the Cloudflare API answered ${String(status)}${errorsText(response.body)}`
1037
+ }
1038
+ if (retries >= this.maxRetries) return { ok: false, code, detail }
1039
+ retries += 1
1040
+ await this.wait(this.retryBaseMs * 2 ** (retries - 1))
1041
+ }
1042
+ }
1043
+
1044
+ /**
1045
+ * Wait one backoff step on the injected timer. The wait is tracked so a
1046
+ * dispose can release it at once: the interrupted run then wakes, sees the
1047
+ * dispose at its next attempt check, and stops instead of sleeping out a
1048
+ * backoff nobody is waiting for.
1049
+ * @param ms - how long the step lasts.
1050
+ * @returns a promise that settles when the step ends or is cancelled.
1051
+ */
1052
+ private wait(ms: number): Promise<void> {
1053
+ return new Promise((resolve) => {
1054
+ const entry: { handle: unknown; resolve: () => void } = { handle: undefined, resolve }
1055
+ // Registered before the timer is armed: a synchronous timer double fires
1056
+ // the callback during the arming call, and the entry must already exist
1057
+ // for that callback to retire it.
1058
+ this.waits.add(entry)
1059
+ entry.handle = this.timer.setTimeout(() => {
1060
+ this.waits.delete(entry)
1061
+ resolve()
1062
+ }, ms)
1063
+ })
1064
+ }
1065
+
1066
+ /** Release every pending backoff wait (dispose); the interrupted run aborts. */
1067
+ private cancelWaits(): void {
1068
+ for (const entry of [...this.waits]) {
1069
+ this.waits.delete(entry)
1070
+ this.timer.clearTimeout(entry.handle)
1071
+ entry.resolve()
1072
+ }
1073
+ }
1074
+ }