@linxin666/dsh-remote-bridge 0.4.12 → 0.4.14

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 (65) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +53 -11
  3. package/README.zh.md +53 -11
  4. package/lib/client.js +112 -90
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18800 -334
  7. package/lib/types/client/PairPanel.d.ts +7 -0
  8. package/lib/types/client/locales.d.ts +13 -10
  9. package/lib/types/core/connection.d.ts +50 -0
  10. package/lib/types/core/devices.d.ts +80 -6
  11. package/lib/types/core/liveactivity.d.ts +7 -0
  12. package/lib/types/core/model-efforts.d.ts +83 -0
  13. package/lib/types/core/protocol.d.ts +24 -0
  14. package/lib/types/core/push.d.ts +70 -3
  15. package/lib/types/host/firewall.d.ts +74 -0
  16. package/lib/types/host/host-bind-capability.d.ts +90 -0
  17. package/lib/types/host/ingress-gate.d.ts +59 -0
  18. package/lib/types/host/ingress-sync.d.ts +429 -0
  19. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  20. package/lib/types/host/lan-bind.d.ts +106 -0
  21. package/lib/types/host/lan-forward.d.ts +112 -0
  22. package/lib/types/host/lan.d.ts +61 -0
  23. package/lib/types/host/pair-origin.d.ts +34 -19
  24. package/lib/types/host/relay-bridge-connector.d.ts +234 -0
  25. package/lib/types/host/relay-connector.d.ts +156 -0
  26. package/lib/types/host/relay-control.d.ts +195 -0
  27. package/lib/types/host/relay-registry.d.ts +123 -0
  28. package/lib/types/host/relay-secondary.d.ts +209 -0
  29. package/lib/types/host/relay.d.ts +170 -0
  30. package/lib/types/host/routes.d.ts +29 -1
  31. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  32. package/lib/types/host/tunnel-plan.d.ts +41 -0
  33. package/lib/types/host/tunnel.d.ts +289 -0
  34. package/lib/types/index.d.ts +488 -1
  35. package/package.json +4 -2
  36. package/src/client/PairPanel.tsx +21 -0
  37. package/src/client/locales.ts +19 -15
  38. package/src/client/panel.module.css +48 -1
  39. package/src/core/connection.ts +316 -11
  40. package/src/core/devices.ts +165 -16
  41. package/src/core/hub.ts +17 -5
  42. package/src/core/liveactivity.ts +16 -2
  43. package/src/core/model-efforts.ts +223 -0
  44. package/src/core/protocol.ts +27 -0
  45. package/src/core/push.ts +90 -5
  46. package/src/host/firewall.ts +230 -0
  47. package/src/host/host-bind-capability.ts +249 -0
  48. package/src/host/ingress-gate.ts +203 -0
  49. package/src/host/ingress-sync.ts +1074 -0
  50. package/src/host/lan-bind-plan.ts +134 -0
  51. package/src/host/lan-bind.ts +250 -0
  52. package/src/host/lan-forward.ts +321 -0
  53. package/src/host/lan.ts +142 -0
  54. package/src/host/pair-origin.ts +44 -38
  55. package/src/host/relay-bridge-connector.ts +849 -0
  56. package/src/host/relay-connector.ts +324 -0
  57. package/src/host/relay-control.ts +315 -0
  58. package/src/host/relay-registry.ts +275 -0
  59. package/src/host/relay-secondary.ts +478 -0
  60. package/src/host/relay.ts +294 -0
  61. package/src/host/routes.ts +57 -3
  62. package/src/host/tunnel-orphan.ts +325 -0
  63. package/src/host/tunnel-plan.ts +58 -0
  64. package/src/host/tunnel.ts +688 -0
  65. package/src/index.ts +1516 -23
@@ -0,0 +1,324 @@
1
+ /**
2
+ * The relay's two connectors. The quick tunnel keeps serving every instance
3
+ * that has not migrated, and the named connector is established beside it on
4
+ * the same relay hostname and left idle while the wildcard Worker route still
5
+ * shadows the CNAME. The control plane's `mode` names the connector the phone
6
+ * is meant to be served from; nothing here switches the edge — it only keeps
7
+ * both sides up, so a server-side flip needs no plugin restart and a rollback
8
+ * is the same flip back.
9
+ */
10
+
11
+ import { readFileSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+ import { dshHome } from './dsh-home.ts'
14
+ import {
15
+ claimRelayLease,
16
+ relayClaimRetryOf,
17
+ relayControlEndpointOf,
18
+ releaseRelayLease,
19
+ type RelayClaim,
20
+ type RelayClaimOutcome,
21
+ type RelayClaimRequest,
22
+ type RelayConnectorMode,
23
+ } from './relay-control.ts'
24
+ import type { RelayIdentity } from './relay-registry.ts'
25
+ import { createTunnelChildGuard } from './tunnel-orphan.ts'
26
+ import { TunnelManager, type TunnelInfo } from './tunnel.ts'
27
+
28
+ /**
29
+ * The crash-recovery record slot the idle named connector owns. Kept apart
30
+ * from the quick connector's slot so each connector's leftover child is reaped
31
+ * by the start that belongs to it instead of overwriting its sibling's record.
32
+ */
33
+ export function namedTunnelChildRecordFile(home: string = dshHome()): string {
34
+ return join(home, 'remote-web-ui-tunnel-child-named.json')
35
+ }
36
+
37
+ /**
38
+ * Read this plugin's own version from its package manifest (the claim reports
39
+ * it so the migration can measure adoption by released version).
40
+ *
41
+ * This module sits one level deeper than the source root (`src/host/`) while
42
+ * the bundle stays one level under the package root (`lib/index.js`), so the
43
+ * two depths are tried in order with the bundle's own first. A manifest that
44
+ * cannot be read at either depth is a miss, and the claim then carries no
45
+ * version at all.
46
+ * @returns the version, or undefined when the manifest cannot be read.
47
+ */
48
+ export function readPluginVersion(): string | undefined {
49
+ for (const candidate of ['../package.json', '../../package.json']) {
50
+ try {
51
+ const parsed = JSON.parse(readFileSync(new URL(candidate, import.meta.url), 'utf8')) as { version?: unknown }
52
+ if (typeof parsed.version === 'string' && parsed.version !== '') return parsed.version
53
+ } catch {
54
+ // Not at this depth (source tree or bundle); try the other one.
55
+ }
56
+ }
57
+ return undefined
58
+ }
59
+
60
+ /**
61
+ * The dedupe key of one claim trigger: the local origin port plus the quick
62
+ * tunnel URL the start reported. A settings sync re-runs the tunnel plan with
63
+ * the same key; a tunnel restart mints a new quick URL and therefore claims
64
+ * again (which is also what keeps the lease's `last_seen_at` inside the cron
65
+ * GC's TTL).
66
+ * @param port - the bound web server port, or undefined before it settles.
67
+ * @param target - the quick tunnel URL, or undefined while none is minted.
68
+ * @returns the key, or undefined when there is nothing to claim yet.
69
+ */
70
+ export function relayClaimKeyOf(port: number | undefined, target: string | undefined): string | undefined {
71
+ if (port === undefined) return undefined
72
+ return String(port) + '|' + (target ?? '')
73
+ }
74
+
75
+ /** The idle named connector: start, stop and report, nothing else. */
76
+ export interface NamedRelayConnector {
77
+ /** Run one named connector for the lease (token via the environment). */
78
+ start(token: string, hostname: string): void
79
+ /** Stop the connector (the relay half was disposed). */
80
+ stop(): void
81
+ readonly info: TunnelInfo
82
+ }
83
+
84
+ /**
85
+ * Build the named connector the relay keeps beside the quick tunnel.
86
+ *
87
+ * Health probing is off on purpose: while the wildcard Worker route answers
88
+ * the relay hostname, a probe of the idle connector's public URL sees the
89
+ * Worker's offline page and would declare a healthy connector dead, restarting
90
+ * it forever (the failure mode issue #1723 fixed for the quick tunnel).
91
+ * @param options - an existing manager (tests); defaults spawn the real one.
92
+ */
93
+ export function createNamedRelayConnector(options: { manager?: TunnelManager } = {}): NamedRelayConnector {
94
+ const manager = options.manager ?? new TunnelManager({
95
+ healthCheckIntervalMs: 0,
96
+ orphan: createTunnelChildGuard({ file: namedTunnelChildRecordFile() }),
97
+ })
98
+ return {
99
+ start(token: string, hostname: string): void {
100
+ manager.start({ kind: 'named', token, publicUrl: 'https://' + hostname })
101
+ },
102
+ stop(): void {
103
+ manager.stop()
104
+ },
105
+ get info(): TunnelInfo {
106
+ return manager.info
107
+ },
108
+ }
109
+ }
110
+
111
+ /** The lease half's observable state (logged, and read by the tests). */
112
+ export type RelayPairState =
113
+ | { state: 'idle' }
114
+ | { state: 'claiming' }
115
+ | { state: 'claimed'; mode: RelayConnectorMode; hostname: string }
116
+ | { state: 'failed'; error: string }
117
+
118
+ /** Everything the bridge connector needs to run for one accepted lease. */
119
+ export interface RelayBridgeStart {
120
+ claim: RelayClaim
121
+ identity: RelayIdentity
122
+ port: number
123
+ }
124
+
125
+ /** Injectable seams of the lease half (defaults are the real control plane). */
126
+ export interface RelayConnectorPairOptions {
127
+ /** One claim attempt. */
128
+ claim?: (request: RelayClaimRequest) => Promise<RelayClaimOutcome>
129
+ /** Start the named connector for one accepted lease. */
130
+ startNamed?: (token: string, hostname: string) => void
131
+ /** Stop the named connector. */
132
+ stopNamed?: () => void
133
+ /** Start (or restart) the bridge connector for one accepted lease. It runs
134
+ * beside the quick tunnel and idles while the instance's mode is quick, so a
135
+ * server-side flip needs no plugin restart. */
136
+ startBridge?: (start: RelayBridgeStart) => void
137
+ /** Stop the bridge connector. */
138
+ stopBridge?: () => void
139
+ /** Release the lease (the offline action, never a retire). */
140
+ release?: (identity: RelayIdentity) => Promise<void>
141
+ /** The control-plane base the two lease endpoints hang off. The defaults
142
+ * below derive `claim` and `release` from it, so a host that configures
143
+ * nothing dials exactly the shipped market URLs. */
144
+ controlUrl?: string
145
+ /** Observe the lease state (logs only — the card still renders the registry). */
146
+ onState?: (state: RelayPairState) => void
147
+ baseDelayMs?: number
148
+ maxDelayMs?: number
149
+ /** Schedule one retry; defaults to an unref'd node timer. */
150
+ timerFn?: (fn: () => void, ms: number) => { unref?: () => void }
151
+ }
152
+
153
+ /**
154
+ * Own the lease half of the relay: claim it on every tunnel start, bring the
155
+ * named connector up beside the quick one, and retry a failed claim with a
156
+ * capped backoff while the quick connector keeps serving.
157
+ */
158
+ export class RelayConnectorPair {
159
+ private stateValue: RelayPairState = { state: 'idle' }
160
+ private leaseValue: RelayClaim | undefined
161
+ private attempts = 0
162
+ private timer: { unref?: () => void } | undefined
163
+ private disposed = false
164
+
165
+ constructor(
166
+ private readonly identity: RelayIdentity,
167
+ private readonly options: RelayConnectorPairOptions = {},
168
+ ) {}
169
+
170
+ /** The lease half's current state. */
171
+ get state(): RelayPairState {
172
+ return this.stateValue
173
+ }
174
+
175
+ /** The connector the phone is served from, for the last accepted lease. */
176
+ get served(): RelayConnectorMode | undefined {
177
+ return this.leaseValue?.mode
178
+ }
179
+
180
+ /** The last accepted lease (undefined until one lands). */
181
+ get lease(): RelayClaim | undefined {
182
+ return this.leaseValue
183
+ }
184
+
185
+ /**
186
+ * Claim one lease and start (or restart) the named connector for it. A
187
+ * refusal is graded into a retry and never tears down the quick connector:
188
+ * the instance keeps the origin the registry already gave it.
189
+ * @param input - the local origin port and the reporting plugin version.
190
+ * @returns the accepted lease, or undefined when the attempt did not land.
191
+ */
192
+ async start(input: { port: number; pluginVersion?: string }): Promise<RelayClaim | undefined> {
193
+ // A disposed pair stays disposed: a pending retry must not resurrect it.
194
+ if (this.disposed) return undefined
195
+ this.clearTimer()
196
+ this.setState({ state: 'claiming' })
197
+ const claimFn = this.options.claim
198
+ ?? ((request: RelayClaimRequest) => claimRelayLease(request, { url: relayControlEndpointOf('claim', this.options.controlUrl) }))
199
+ let outcome: RelayClaimOutcome
200
+ try {
201
+ outcome = await claimFn({
202
+ id: this.identity.id,
203
+ secret: this.identity.secret,
204
+ newSecret: this.identity.fresh === true ? this.identity.secret : undefined,
205
+ port: input.port,
206
+ pluginVersion: input.pluginVersion,
207
+ })
208
+ } catch (error) {
209
+ outcome = { ok: false, status: 0, error: error instanceof Error ? error.message : String(error) }
210
+ }
211
+ if (this.disposed) return undefined
212
+ if (outcome.ok) {
213
+ // The row exists now: never claim a fresh id twice.
214
+ this.identity.fresh = false
215
+ this.attempts = 0
216
+ this.leaseValue = outcome.claim
217
+ this.startNamed(outcome.claim)
218
+ this.startBridge(outcome.claim, input.port)
219
+ this.setState({ state: 'claimed', mode: outcome.claim.mode, hostname: outcome.claim.hostname })
220
+ return outcome.claim
221
+ }
222
+ this.setState({ state: 'failed', error: outcome.error })
223
+ const retry = relayClaimRetryOf(outcome, this.attempts, {
224
+ baseDelayMs: this.options.baseDelayMs,
225
+ maxDelayMs: this.options.maxDelayMs,
226
+ })
227
+ if (retry.refreshIdentity) this.identity.fresh = true
228
+ if (retry.retry) this.scheduleRetry(input, retry.delayMs)
229
+ return undefined
230
+ }
231
+
232
+ /**
233
+ * The plugin's offline action (toggle off, profile unmount): release the
234
+ * lease and stop the idle connector. Never retires — the hostname is the
235
+ * phone's bookmark, and the tunnel behind it survives.
236
+ */
237
+ async release(): Promise<void> {
238
+ const releaseFn = this.options.release
239
+ ?? ((identity: RelayIdentity) => releaseRelayLease(identity, { url: relayControlEndpointOf('release', this.options.controlUrl) }))
240
+ try {
241
+ await releaseFn(this.identity)
242
+ } catch {
243
+ // Best effort: an unreleased row is recovered by the 90-day GC.
244
+ }
245
+ this.stopNamed()
246
+ }
247
+
248
+ /** Stop retrying and drop the connector (the relay half was disposed). */
249
+ dispose(): void {
250
+ this.disposed = true
251
+ this.clearTimer()
252
+ this.stopNamed()
253
+ this.setState({ state: 'idle' })
254
+ }
255
+
256
+ private startNamed(claim: RelayClaim): void {
257
+ const startNamed = this.options.startNamed
258
+ // A bridged lease carries no tunnel: there is no token to run, and the
259
+ // transport is the bridge connector, so no second cloudflared starts.
260
+ if (startNamed === undefined || claim.tunnel === undefined) return
261
+ try {
262
+ startNamed(claim.tunnel.token, claim.hostname)
263
+ } catch (error) {
264
+ // The connector failing to spawn must not lose the accepted lease.
265
+ console.warn('remote-bridge: the named connector could not start (' + (error instanceof Error ? error.message : String(error)) + ')')
266
+ }
267
+ }
268
+
269
+ private stopNamed(): void {
270
+ try {
271
+ this.options.stopNamed?.()
272
+ } catch {
273
+ // Stopping an already-stopped connector is not an error worth surfacing.
274
+ }
275
+ try {
276
+ this.options.stopBridge?.()
277
+ } catch {
278
+ // Same for the bridge half.
279
+ }
280
+ }
281
+
282
+ /** Bring the bridge connector up for one accepted lease, if it carries one. */
283
+ private startBridge(claim: RelayClaim, port: number): void {
284
+ const startBridge = this.options.startBridge
285
+ if (startBridge === undefined || claim.bridge === undefined) return
286
+ try {
287
+ startBridge({ claim, identity: this.identity, port })
288
+ } catch (error) {
289
+ // The bridge failing to start must not lose the accepted lease: quick
290
+ // keeps serving, exactly as it does when the claim itself is refused.
291
+ console.warn('remote-bridge: the bridge connector could not start (' + (error instanceof Error ? error.message : String(error)) + ')')
292
+ }
293
+ }
294
+
295
+ private scheduleRetry(input: { port: number; pluginVersion?: string }, delayMs: number): void {
296
+ if (this.disposed) return
297
+ this.attempts += 1
298
+ const timerFn = this.options.timerFn ?? ((fn: () => void, ms: number) => {
299
+ const timer = setTimeout(fn, ms)
300
+ timer.unref?.()
301
+ return timer
302
+ })
303
+ this.timer = timerFn(() => {
304
+ this.timer = undefined
305
+ void this.start(input)
306
+ }, delayMs)
307
+ this.timer.unref?.()
308
+ }
309
+
310
+ private clearTimer(): void {
311
+ if (this.timer === undefined) return
312
+ clearTimeout(this.timer as unknown as NodeJS.Timeout)
313
+ this.timer = undefined
314
+ }
315
+
316
+ private setState(state: RelayPairState): void {
317
+ this.stateValue = state
318
+ try {
319
+ this.options.onState?.(state)
320
+ } catch {
321
+ // A throwing observer must not break the lease lifecycle.
322
+ }
323
+ }
324
+ }
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Relay control-plane client: the lease claim that turns one relay identity
3
+ * into a lease row (the tunnel transports get a tunnel, its ingress, a CNAME
4
+ * and the per-instance connector token; the bridge transport gets neither
5
+ * block, because its data plane owns no Cloudflare object) plus the release
6
+ * bookkeeping.
7
+ *
8
+ * Claiming is best-effort and additive. Every failure is graded into a retry
9
+ * decision instead of breaking the quick tunnel that already serves the phone:
10
+ * the control plane answers `mode`, so an instance whose claim cannot land
11
+ * keeps the origin the registry gave it.
12
+ */
13
+
14
+ import type { RelayIdentity } from './relay-registry.ts'
15
+
16
+ /**
17
+ * The control-plane base every lease and registry endpoint hangs off: the
18
+ * market apex, never a relay hostname.
19
+ *
20
+ * This constant is the one home of the shipped default. A self-hosted meeting
21
+ * point sets the `relayControlUrl` config field, and its `claim`, `release`,
22
+ * `register` and `unregister` paths all move with that one base.
23
+ */
24
+ export const RELAY_CONTROL_URL = 'https://dsh-market.com/api/relay'
25
+
26
+ /** The paths one control-plane base serves. */
27
+ export type RelayControlEndpoint = 'claim' | 'release' | 'register' | 'unregister'
28
+
29
+ /**
30
+ * One endpoint of a control-plane base.
31
+ *
32
+ * The base arrives from a hand-written profile YAML, so its trailing slashes
33
+ * are trimmed instead of doubling the separator this adds.
34
+ * @param endpoint - the path below the base.
35
+ * @param controlUrl - the base; undefined means the shipped market apex.
36
+ * @returns the absolute endpoint URL.
37
+ */
38
+ export function relayControlEndpointOf(endpoint: RelayControlEndpoint, controlUrl?: string): string {
39
+ return (controlUrl ?? RELAY_CONTROL_URL).replace(/\/+$/, '') + '/' + endpoint
40
+ }
41
+
42
+ /** The default lease endpoints (market apex, never a relay hostname). */
43
+ export const RELAY_CLAIM_URL = relayControlEndpointOf('claim')
44
+ export const RELAY_RELEASE_URL = relayControlEndpointOf('release')
45
+
46
+ /** Which connector serves the relay hostname. `bridge` is the Durable Object
47
+ * meeting point (`relay-bridge-connector.ts`), `named` the instance's own cloud
48
+ * tunnel, `quick` today's Worker proxy path. */
49
+ export type RelayConnectorMode = 'named' | 'quick' | 'bridge'
50
+
51
+ /** What a bridge connector needs to dial: an endpoint and a credential to
52
+ * present. The credential is the lease's own long-lived id and secret -- the
53
+ * reply names it rather than repeating a secret in a body. */
54
+ export interface RelayBridgeGrant {
55
+ endpoint: string
56
+ instance: string
57
+ credential: 'lease-secret'
58
+ }
59
+
60
+ /** One accepted lease, as the control plane answers it. */
61
+ export interface RelayClaim {
62
+ mode: RelayConnectorMode
63
+ /** The instance's own tunnel. Absent for a bridged lease: there is nothing
64
+ * to run and no token to run it with. */
65
+ tunnel?: { id: string; token: string }
66
+ hostname: string
67
+ /** The CNAME target behind the hostname; absent for a bridged lease too. */
68
+ dns?: { target: string }
69
+ /** Present when the control plane can route this instance over the bridge. */
70
+ bridge?: RelayBridgeGrant
71
+ }
72
+
73
+ /** What one claim attempt resolved to. */
74
+ export type RelayClaimOutcome =
75
+ | { ok: true; claim: RelayClaim }
76
+ | { ok: false; status: number; error: string; retryAfterMs?: number }
77
+
78
+ /** One claim request (the lease the caller wants refreshed). */
79
+ export interface RelayClaimRequest {
80
+ id: string
81
+ secret: string
82
+ /** Carried only by a fresh identity: the first claim creates the row. */
83
+ newSecret?: string
84
+ /** Local origin port the lease ingress points at (`ctx.webServer.port`). */
85
+ port: number
86
+ /** The plugin version, for the adoption readout of the migration. */
87
+ pluginVersion?: string
88
+ /**
89
+ * The account service's relay grant, when this bridge holds one.
90
+ *
91
+ * Absent is the claim a host makes when no phone has handed a grant over yet,
92
+ * and the key is then left out of the body entirely: the second meeting point
93
+ * grades "no grant" as `tier-required`, which is a different answer from "this
94
+ * grant does not verify" (`grant-invalid`), and `null` would be read as the
95
+ * latter.
96
+ */
97
+ grant?: string
98
+ }
99
+
100
+ /**
101
+ * The capped backoff a failed claim retries on. The cap is the whole Cloudflare
102
+ * rate-limit window: a spent account request budget answers `retryAfterMs:
103
+ * 300000` because that budget is counted over 300 seconds, so a shorter cap
104
+ * only brings the instance back inside the same spent window.
105
+ */
106
+ export const CLAIM_RETRY_BASE_MS = 5_000
107
+ export const CLAIM_RETRY_MAX_MS = 300_000
108
+
109
+ /**
110
+ * The control plane's refusal code for a claim whose grant does not reach the
111
+ * tier this meeting point admits. It is not an authentication answer — the id
112
+ * and secret verified — so it is graded apart from `auth-failed`.
113
+ */
114
+ export const RELAY_TIER_REQUIRED = 'tier-required'
115
+
116
+ /**
117
+ * The control plane's refusal code for a grant it will not vouch for: a bad
118
+ * signature, the wrong scope, or — the case that is not an error at all — a grant
119
+ * that has simply reached the end of its 30 days.
120
+ *
121
+ * It shares {@link RELAY_TIER_REQUIRED}'s branch because it is the same kind of
122
+ * fact: the id and the secret are fine, the admission this host was given is not,
123
+ * and the repair is a fresh grant (which the phone hands over) or another
124
+ * evaluation after the plan or the clock moved. `auth-failed` stays the one
125
+ * terminal 403.
126
+ */
127
+ export const RELAY_GRANT_INVALID = 'grant-invalid'
128
+
129
+ /**
130
+ * How long a claim refused for its admission (`tier-required` or
131
+ * `grant-invalid`) waits before the next attempt: six hours.
132
+ *
133
+ * Deliberately outside {@link CLAIM_RETRY_MAX_MS}. That cap exists because a
134
+ * spent rate-limit budget is counted over one 300-second window, so retrying
135
+ * faster lands inside the same spent window. An admission refusal is not a
136
+ * window: it is a fact about the plan or about the grant's own 30-day lifetime.
137
+ * Six hours is the interval the lease refresh itself runs on, so a downgrade is
138
+ * noticed at the next refresh, while an upgrade needs no wait at all: the phone
139
+ * hands the new grant over (`relay.tier.v1`) and that re-claims immediately.
140
+ */
141
+ export const CLAIM_TIER_REQUIRED_DELAY_MS = 21_600_000
142
+
143
+ /** Build the claim body (an absent value is omitted, never sent as null). */
144
+ export function relayClaimBody(request: RelayClaimRequest): string {
145
+ const grant = request.grant
146
+ return JSON.stringify({
147
+ id: request.id,
148
+ secret: request.secret,
149
+ new_secret: request.newSecret,
150
+ origin: { port: request.port },
151
+ plugin: request.pluginVersion === undefined ? undefined : { version: request.pluginVersion },
152
+ // 没有授权就不带这个键,也不写 null:第二会合点把「没有授权」与「授权验不过」
153
+ // 分成两个答案,而 null 只会掉进后者。
154
+ ...(typeof grant === 'string' && grant !== '' ? { grant } : {}),
155
+ })
156
+ }
157
+
158
+ /** The tunnel of one accepted claim, or undefined when it carries none. */
159
+ function relayTunnelOf(value: unknown): { id: string; token: string } | undefined {
160
+ if (typeof value !== 'object' || value === null) return undefined
161
+ const tunnel = value as { id?: unknown; token?: unknown }
162
+ if (typeof tunnel.id !== 'string' || tunnel.id === '') return undefined
163
+ if (typeof tunnel.token !== 'string' || tunnel.token === '') return undefined
164
+ return { id: tunnel.id, token: tunnel.token }
165
+ }
166
+
167
+ /** The CNAME target of one accepted claim, or undefined when it carries none. */
168
+ function relayDnsTargetOf(value: unknown): string | undefined {
169
+ if (typeof value !== 'object' || value === null) return undefined
170
+ const target = (value as { target?: unknown }).target
171
+ return typeof target === 'string' && target !== '' ? target : undefined
172
+ }
173
+
174
+ /** One lease read back from an accepted claim, or undefined for a bad shape. */
175
+ export function relayClaimOf(value: unknown): RelayClaim | undefined {
176
+ if (typeof value !== 'object' || value === null) return undefined
177
+ const body = value as { mode?: unknown; tunnel?: unknown; hostname?: unknown; dns?: unknown; bridge?: unknown }
178
+ const mode = body.mode
179
+ if (mode !== 'named' && mode !== 'quick' && mode !== 'bridge') return undefined
180
+ if (typeof body.hostname !== 'string' || body.hostname === '') return undefined
181
+ const tunnel = relayTunnelOf(body.tunnel)
182
+ const target = relayDnsTargetOf(body.dns)
183
+ // The tunnel transports are served by that tunnel, so a reply without both
184
+ // halves is a protocol error. The bridge is the one transport whose lease
185
+ // owns no Cloudflare object, and its claim carries neither half.
186
+ if (mode !== 'bridge' && (tunnel === undefined || target === undefined)) return undefined
187
+ const bridge = relayBridgeGrantOf(body.bridge)
188
+ return {
189
+ mode,
190
+ ...(tunnel === undefined ? {} : { tunnel }),
191
+ hostname: body.hostname,
192
+ ...(target === undefined ? {} : { dns: { target } }),
193
+ ...(bridge === undefined ? {} : { bridge }),
194
+ }
195
+ }
196
+
197
+ /** The bridge grant of one accepted lease, or undefined when it carries none. */
198
+ export function relayBridgeGrantOf(value: unknown): RelayBridgeGrant | undefined {
199
+ if (typeof value !== 'object' || value === null) return undefined
200
+ const grant = value as { endpoint?: unknown; instance?: unknown; credential?: unknown }
201
+ if (typeof grant.endpoint !== 'string' || grant.endpoint === '') return undefined
202
+ if (typeof grant.instance !== 'string' || grant.instance === '') return undefined
203
+ if (grant.credential !== 'lease-secret') return undefined
204
+ return { endpoint: grant.endpoint, instance: grant.instance, credential: 'lease-secret' }
205
+ }
206
+
207
+ /** The error code and retry hint of a refused claim. */
208
+ function refusalOf(status: number, detail: unknown): Extract<RelayClaimOutcome, { ok: false }> {
209
+ const body = typeof detail === 'object' && detail !== null
210
+ ? detail as { error?: unknown; retryAfterMs?: unknown }
211
+ : {}
212
+ const error = typeof body.error === 'string' ? body.error : 'http-' + String(status)
213
+ const retryAfterMs = typeof body.retryAfterMs === 'number' && Number.isFinite(body.retryAfterMs)
214
+ ? body.retryAfterMs
215
+ : undefined
216
+ return retryAfterMs === undefined ? { ok: false, status, error } : { ok: false, status, error, retryAfterMs }
217
+ }
218
+
219
+ /**
220
+ * Claim one lease. A transport failure is graded like `502 cf-api-unavailable`
221
+ * (status 0) so the caller retries on the same path as a refused upstream.
222
+ * @param request - the lease to refresh.
223
+ * @param options - endpoint and fetch seams (defaults are the real ones).
224
+ */
225
+ export async function claimRelayLease(
226
+ request: RelayClaimRequest,
227
+ options: { url?: string; fetchFn?: typeof fetch } = {},
228
+ ): Promise<RelayClaimOutcome> {
229
+ const fetchFn = options.fetchFn ?? fetch
230
+ let response: Response
231
+ try {
232
+ response = await fetchFn(options.url ?? RELAY_CLAIM_URL, {
233
+ method: 'PUT',
234
+ headers: { 'content-type': 'application/json' },
235
+ body: relayClaimBody(request),
236
+ })
237
+ } catch (error) {
238
+ const detail = error instanceof Error ? error.message : String(error)
239
+ return { ok: false, status: 0, error: detail === '' ? 'network-error' : detail }
240
+ }
241
+ const detail: unknown = await response.json().catch(() => undefined)
242
+ if (!response.ok) return refusalOf(response.status, detail)
243
+ const claim = relayClaimOf(detail)
244
+ return claim === undefined
245
+ ? { ok: false, status: response.status, error: 'invalid-response' }
246
+ : { ok: true, claim }
247
+ }
248
+
249
+ /**
250
+ * Release one lease (the plugin's offline action: toggle off, profile
251
+ * unmount). Best-effort — a release that never lands only leaves the row
252
+ * marked active, which the 90-day GC recovers.
253
+ */
254
+ export async function releaseRelayLease(
255
+ identity: RelayIdentity,
256
+ options: { url?: string; fetchFn?: typeof fetch } = {},
257
+ ): Promise<void> {
258
+ const fetchFn = options.fetchFn ?? fetch
259
+ await fetchFn(options.url ?? RELAY_RELEASE_URL, {
260
+ method: 'POST',
261
+ headers: { 'content-type': 'application/json' },
262
+ body: JSON.stringify({ id: identity.id, secret: identity.secret }),
263
+ })
264
+ }
265
+
266
+ /** How one failed claim should be retried. */
267
+ export interface RelayClaimRetry {
268
+ /** Whether another attempt is worth making at all. */
269
+ retry: boolean
270
+ /** How long to wait before that attempt. */
271
+ delayMs: number
272
+ /**
273
+ * Whether the identity must be re-claimed with `new_secret`: the control
274
+ * plane lost the row (a D1 restore or a manual wipe), which is the one
275
+ * condition a fresh claim fixes.
276
+ */
277
+ refreshIdentity: boolean
278
+ }
279
+
280
+ /**
281
+ * Grade one failed claim into a retry decision.
282
+ *
283
+ * `403 auth-failed` is terminal: the id belongs to another secret and no
284
+ * number of retries can take it back. The two admission 403s —
285
+ * `tier-required` and `grant-invalid` — are the ones that are not: the id and
286
+ * the secret verified and only the admission is missing, so both retry on the
287
+ * same fixed wait ({@link CLAIM_TIER_REQUIRED_DELAY_MS}) that the cap below
288
+ * deliberately does not clamp. Everything else retries on a capped
289
+ * exponential backoff, with the control plane's own `retryAfterMs` (a 502
290
+ * names it) raising the floor so a retry cannot land inside a known outage.
291
+ * @param outcome - the refused attempt.
292
+ * @param attempt - how many attempts already failed (0 for the first).
293
+ * @param options - backoff bounds (defaults are the shipped ones).
294
+ */
295
+ export function relayClaimRetryOf(
296
+ outcome: Extract<RelayClaimOutcome, { ok: false }>,
297
+ attempt: number,
298
+ options: { baseDelayMs?: number; maxDelayMs?: number } = {},
299
+ ): RelayClaimRetry {
300
+ const base = options.baseDelayMs ?? CLAIM_RETRY_BASE_MS
301
+ const max = options.maxDelayMs ?? CLAIM_RETRY_MAX_MS
302
+ if (outcome.status === 403) {
303
+ // No identity refresh on any 403: the id and secret are not what the
304
+ // control plane refused, and re-claiming the id under a new secret would
305
+ // strand every phone paired to it.
306
+ if (outcome.error === RELAY_TIER_REQUIRED || outcome.error === RELAY_GRANT_INVALID) {
307
+ return { retry: true, delayMs: CLAIM_TIER_REQUIRED_DELAY_MS, refreshIdentity: false }
308
+ }
309
+ return { retry: false, delayMs: 0, refreshIdentity: false }
310
+ }
311
+ const backoff = Math.min(base * 2 ** attempt, max)
312
+ const delayMs = Math.min(Math.max(backoff, outcome.retryAfterMs ?? 0), max)
313
+ const refreshIdentity = outcome.error === 'invalid-params' || outcome.error === 'unknown-id'
314
+ return { retry: true, delayMs, refreshIdentity }
315
+ }