@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,317 @@
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
+ releaseRelayLease,
18
+ type RelayClaim,
19
+ type RelayClaimOutcome,
20
+ type RelayClaimRequest,
21
+ type RelayConnectorMode,
22
+ } from './relay-control.ts'
23
+ import type { RelayIdentity } from './relay-registry.ts'
24
+ import { createTunnelChildGuard } from './tunnel-orphan.ts'
25
+ import { TunnelManager, type TunnelInfo } from './tunnel.ts'
26
+
27
+ /**
28
+ * The crash-recovery record slot the idle named connector owns. Kept apart
29
+ * from the quick connector's slot so each connector's leftover child is reaped
30
+ * by the start that belongs to it instead of overwriting its sibling's record.
31
+ */
32
+ export function namedTunnelChildRecordFile(home: string = dshHome()): string {
33
+ return join(home, 'remote-web-ui-tunnel-child-named.json')
34
+ }
35
+
36
+ /**
37
+ * Read this plugin's own version from its package manifest (the claim reports
38
+ * it so the migration can measure adoption by released version).
39
+ *
40
+ * This module sits one level deeper than the source root (`src/host/`) while
41
+ * the bundle stays one level under the package root (`lib/index.js`), so the
42
+ * two depths are tried in order with the bundle's own first. A manifest that
43
+ * cannot be read at either depth is a miss, and the claim then carries no
44
+ * version at all.
45
+ * @returns the version, or undefined when the manifest cannot be read.
46
+ */
47
+ export function readPluginVersion(): string | undefined {
48
+ for (const candidate of ['../package.json', '../../package.json']) {
49
+ try {
50
+ const parsed = JSON.parse(readFileSync(new URL(candidate, import.meta.url), 'utf8')) as { version?: unknown }
51
+ if (typeof parsed.version === 'string' && parsed.version !== '') return parsed.version
52
+ } catch {
53
+ // Not at this depth (source tree or bundle); try the other one.
54
+ }
55
+ }
56
+ return undefined
57
+ }
58
+
59
+ /**
60
+ * The dedupe key of one claim trigger: the local origin port plus the quick
61
+ * tunnel URL the start reported. A settings sync re-runs the tunnel plan with
62
+ * the same key; a tunnel restart mints a new quick URL and therefore claims
63
+ * again (which is also what keeps the lease's `last_seen_at` inside the cron
64
+ * GC's TTL).
65
+ * @param port - the bound web server port, or undefined before it settles.
66
+ * @param target - the quick tunnel URL, or undefined while none is minted.
67
+ * @returns the key, or undefined when there is nothing to claim yet.
68
+ */
69
+ export function relayClaimKeyOf(port: number | undefined, target: string | undefined): string | undefined {
70
+ if (port === undefined) return undefined
71
+ return String(port) + '|' + (target ?? '')
72
+ }
73
+
74
+ /** The idle named connector: start, stop and report, nothing else. */
75
+ export interface NamedRelayConnector {
76
+ /** Run one named connector for the lease (token via the environment). */
77
+ start(token: string, hostname: string): void
78
+ /** Stop the connector (the relay half was disposed). */
79
+ stop(): void
80
+ readonly info: TunnelInfo
81
+ }
82
+
83
+ /**
84
+ * Build the named connector the relay keeps beside the quick tunnel.
85
+ *
86
+ * Health probing is off on purpose: while the wildcard Worker route answers
87
+ * the relay hostname, a probe of the idle connector's public URL sees the
88
+ * Worker's offline page and would declare a healthy connector dead, restarting
89
+ * it forever (the failure mode issue #1723 fixed for the quick tunnel).
90
+ * @param options - an existing manager (tests); defaults spawn the real one.
91
+ */
92
+ export function createNamedRelayConnector(options: { manager?: TunnelManager } = {}): NamedRelayConnector {
93
+ const manager = options.manager ?? new TunnelManager({
94
+ healthCheckIntervalMs: 0,
95
+ orphan: createTunnelChildGuard({ file: namedTunnelChildRecordFile() }),
96
+ })
97
+ return {
98
+ start(token: string, hostname: string): void {
99
+ manager.start({ kind: 'named', token, publicUrl: 'https://' + hostname })
100
+ },
101
+ stop(): void {
102
+ manager.stop()
103
+ },
104
+ get info(): TunnelInfo {
105
+ return manager.info
106
+ },
107
+ }
108
+ }
109
+
110
+ /** The lease half's observable state (logged, and read by the tests). */
111
+ export type RelayPairState =
112
+ | { state: 'idle' }
113
+ | { state: 'claiming' }
114
+ | { state: 'claimed'; mode: RelayConnectorMode; hostname: string }
115
+ | { state: 'failed'; error: string }
116
+
117
+ /** Everything the bridge connector needs to run for one accepted lease. */
118
+ export interface RelayBridgeStart {
119
+ claim: RelayClaim
120
+ identity: RelayIdentity
121
+ port: number
122
+ }
123
+
124
+ /** Injectable seams of the lease half (defaults are the real control plane). */
125
+ export interface RelayConnectorPairOptions {
126
+ /** One claim attempt. */
127
+ claim?: (request: RelayClaimRequest) => Promise<RelayClaimOutcome>
128
+ /** Start the named connector for one accepted lease. */
129
+ startNamed?: (token: string, hostname: string) => void
130
+ /** Stop the named connector. */
131
+ stopNamed?: () => void
132
+ /** Start (or restart) the bridge connector for one accepted lease. It runs
133
+ * beside the quick tunnel and idles while the instance's mode is quick, so a
134
+ * server-side flip needs no plugin restart. */
135
+ startBridge?: (start: RelayBridgeStart) => void
136
+ /** Stop the bridge connector. */
137
+ stopBridge?: () => void
138
+ /** Release the lease (the offline action, never a retire). */
139
+ release?: (identity: RelayIdentity) => Promise<void>
140
+ /** Observe the lease state (logs only — the card still renders the registry). */
141
+ onState?: (state: RelayPairState) => void
142
+ baseDelayMs?: number
143
+ maxDelayMs?: number
144
+ /** Schedule one retry; defaults to an unref'd node timer. */
145
+ timerFn?: (fn: () => void, ms: number) => { unref?: () => void }
146
+ }
147
+
148
+ /**
149
+ * Own the lease half of the relay: claim it on every tunnel start, bring the
150
+ * named connector up beside the quick one, and retry a failed claim with a
151
+ * capped backoff while the quick connector keeps serving.
152
+ */
153
+ export class RelayConnectorPair {
154
+ private stateValue: RelayPairState = { state: 'idle' }
155
+ private leaseValue: RelayClaim | undefined
156
+ private attempts = 0
157
+ private timer: { unref?: () => void } | undefined
158
+ private disposed = false
159
+
160
+ constructor(
161
+ private readonly identity: RelayIdentity,
162
+ private readonly options: RelayConnectorPairOptions = {},
163
+ ) {}
164
+
165
+ /** The lease half's current state. */
166
+ get state(): RelayPairState {
167
+ return this.stateValue
168
+ }
169
+
170
+ /** The connector the phone is served from, for the last accepted lease. */
171
+ get served(): RelayConnectorMode | undefined {
172
+ return this.leaseValue?.mode
173
+ }
174
+
175
+ /** The last accepted lease (undefined until one lands). */
176
+ get lease(): RelayClaim | undefined {
177
+ return this.leaseValue
178
+ }
179
+
180
+ /**
181
+ * Claim one lease and start (or restart) the named connector for it. A
182
+ * refusal is graded into a retry and never tears down the quick connector:
183
+ * the instance keeps the origin the registry already gave it.
184
+ * @param input - the local origin port and the reporting plugin version.
185
+ * @returns the accepted lease, or undefined when the attempt did not land.
186
+ */
187
+ async start(input: { port: number; pluginVersion?: string }): Promise<RelayClaim | undefined> {
188
+ // A disposed pair stays disposed: a pending retry must not resurrect it.
189
+ if (this.disposed) return undefined
190
+ this.clearTimer()
191
+ this.setState({ state: 'claiming' })
192
+ const claimFn = this.options.claim ?? ((request: RelayClaimRequest) => claimRelayLease(request))
193
+ let outcome: RelayClaimOutcome
194
+ try {
195
+ outcome = await claimFn({
196
+ id: this.identity.id,
197
+ secret: this.identity.secret,
198
+ newSecret: this.identity.fresh === true ? this.identity.secret : undefined,
199
+ port: input.port,
200
+ pluginVersion: input.pluginVersion,
201
+ })
202
+ } catch (error) {
203
+ outcome = { ok: false, status: 0, error: error instanceof Error ? error.message : String(error) }
204
+ }
205
+ if (this.disposed) return undefined
206
+ if (outcome.ok) {
207
+ // The row exists now: never claim a fresh id twice.
208
+ this.identity.fresh = false
209
+ this.attempts = 0
210
+ this.leaseValue = outcome.claim
211
+ this.startNamed(outcome.claim)
212
+ this.startBridge(outcome.claim, input.port)
213
+ this.setState({ state: 'claimed', mode: outcome.claim.mode, hostname: outcome.claim.hostname })
214
+ return outcome.claim
215
+ }
216
+ this.setState({ state: 'failed', error: outcome.error })
217
+ const retry = relayClaimRetryOf(outcome, this.attempts, {
218
+ baseDelayMs: this.options.baseDelayMs,
219
+ maxDelayMs: this.options.maxDelayMs,
220
+ })
221
+ if (retry.refreshIdentity) this.identity.fresh = true
222
+ if (retry.retry) this.scheduleRetry(input, retry.delayMs)
223
+ return undefined
224
+ }
225
+
226
+ /**
227
+ * The plugin's offline action (toggle off, profile unmount): release the
228
+ * lease and stop the idle connector. Never retires — the hostname is the
229
+ * phone's bookmark, and the tunnel behind it survives.
230
+ */
231
+ async release(): Promise<void> {
232
+ const releaseFn = this.options.release ?? ((identity: RelayIdentity) => releaseRelayLease(identity))
233
+ try {
234
+ await releaseFn(this.identity)
235
+ } catch {
236
+ // Best effort: an unreleased row is recovered by the 90-day GC.
237
+ }
238
+ this.stopNamed()
239
+ }
240
+
241
+ /** Stop retrying and drop the connector (the relay half was disposed). */
242
+ dispose(): void {
243
+ this.disposed = true
244
+ this.clearTimer()
245
+ this.stopNamed()
246
+ this.setState({ state: 'idle' })
247
+ }
248
+
249
+ private startNamed(claim: RelayClaim): void {
250
+ const startNamed = this.options.startNamed
251
+ // A bridged lease carries no tunnel: there is no token to run, and the
252
+ // transport is the bridge connector, so no second cloudflared starts.
253
+ if (startNamed === undefined || claim.tunnel === undefined) return
254
+ try {
255
+ startNamed(claim.tunnel.token, claim.hostname)
256
+ } catch (error) {
257
+ // The connector failing to spawn must not lose the accepted lease.
258
+ console.warn('remote-bridge: the named connector could not start (' + (error instanceof Error ? error.message : String(error)) + ')')
259
+ }
260
+ }
261
+
262
+ private stopNamed(): void {
263
+ try {
264
+ this.options.stopNamed?.()
265
+ } catch {
266
+ // Stopping an already-stopped connector is not an error worth surfacing.
267
+ }
268
+ try {
269
+ this.options.stopBridge?.()
270
+ } catch {
271
+ // Same for the bridge half.
272
+ }
273
+ }
274
+
275
+ /** Bring the bridge connector up for one accepted lease, if it carries one. */
276
+ private startBridge(claim: RelayClaim, port: number): void {
277
+ const startBridge = this.options.startBridge
278
+ if (startBridge === undefined || claim.bridge === undefined) return
279
+ try {
280
+ startBridge({ claim, identity: this.identity, port })
281
+ } catch (error) {
282
+ // The bridge failing to start must not lose the accepted lease: quick
283
+ // keeps serving, exactly as it does when the claim itself is refused.
284
+ console.warn('remote-bridge: the bridge connector could not start (' + (error instanceof Error ? error.message : String(error)) + ')')
285
+ }
286
+ }
287
+
288
+ private scheduleRetry(input: { port: number; pluginVersion?: string }, delayMs: number): void {
289
+ if (this.disposed) return
290
+ this.attempts += 1
291
+ const timerFn = this.options.timerFn ?? ((fn: () => void, ms: number) => {
292
+ const timer = setTimeout(fn, ms)
293
+ timer.unref?.()
294
+ return timer
295
+ })
296
+ this.timer = timerFn(() => {
297
+ this.timer = undefined
298
+ void this.start(input)
299
+ }, delayMs)
300
+ this.timer.unref?.()
301
+ }
302
+
303
+ private clearTimer(): void {
304
+ if (this.timer === undefined) return
305
+ clearTimeout(this.timer as unknown as NodeJS.Timeout)
306
+ this.timer = undefined
307
+ }
308
+
309
+ private setState(state: RelayPairState): void {
310
+ this.stateValue = state
311
+ try {
312
+ this.options.onState?.(state)
313
+ } catch {
314
+ // A throwing observer must not break the lease lifecycle.
315
+ }
316
+ }
317
+ }
@@ -0,0 +1,224 @@
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
+ /** The control-plane endpoints (market apex, never a relay hostname). */
17
+ export const RELAY_CLAIM_URL = 'https://dsh-market.com/api/relay/claim'
18
+ export const RELAY_RELEASE_URL = 'https://dsh-market.com/api/relay/release'
19
+
20
+ /** Which connector serves the relay hostname. `bridge` is the Durable Object
21
+ * meeting point (`relay-bridge-connector.ts`), `named` the instance's own cloud
22
+ * tunnel, `quick` today's Worker proxy path. */
23
+ export type RelayConnectorMode = 'named' | 'quick' | 'bridge'
24
+
25
+ /** What a bridge connector needs to dial: an endpoint and a credential to
26
+ * present. The credential is the lease's own long-lived id and secret -- the
27
+ * reply names it rather than repeating a secret in a body. */
28
+ export interface RelayBridgeGrant {
29
+ endpoint: string
30
+ instance: string
31
+ credential: 'lease-secret'
32
+ }
33
+
34
+ /** One accepted lease, as the control plane answers it. */
35
+ export interface RelayClaim {
36
+ mode: RelayConnectorMode
37
+ /** The instance's own tunnel. Absent for a bridged lease: there is nothing
38
+ * to run and no token to run it with. */
39
+ tunnel?: { id: string; token: string }
40
+ hostname: string
41
+ /** The CNAME target behind the hostname; absent for a bridged lease too. */
42
+ dns?: { target: string }
43
+ /** Present when the control plane can route this instance over the bridge. */
44
+ bridge?: RelayBridgeGrant
45
+ }
46
+
47
+ /** What one claim attempt resolved to. */
48
+ export type RelayClaimOutcome =
49
+ | { ok: true; claim: RelayClaim }
50
+ | { ok: false; status: number; error: string; retryAfterMs?: number }
51
+
52
+ /** One claim request (the lease the caller wants refreshed). */
53
+ export interface RelayClaimRequest {
54
+ id: string
55
+ secret: string
56
+ /** Carried only by a fresh identity: the first claim creates the row. */
57
+ newSecret?: string
58
+ /** Local origin port the lease ingress points at (`ctx.webServer.port`). */
59
+ port: number
60
+ /** The plugin version, for the adoption readout of the migration. */
61
+ pluginVersion?: string
62
+ }
63
+
64
+ /** The capped backoff a failed claim retries on. */
65
+ export const CLAIM_RETRY_BASE_MS = 5_000
66
+ export const CLAIM_RETRY_MAX_MS = 60_000
67
+
68
+ /** Build the claim body (an absent value is omitted, never sent as null). */
69
+ export function relayClaimBody(request: RelayClaimRequest): string {
70
+ return JSON.stringify({
71
+ id: request.id,
72
+ secret: request.secret,
73
+ new_secret: request.newSecret,
74
+ origin: { port: request.port },
75
+ plugin: request.pluginVersion === undefined ? undefined : { version: request.pluginVersion },
76
+ })
77
+ }
78
+
79
+ /** The tunnel of one accepted claim, or undefined when it carries none. */
80
+ function relayTunnelOf(value: unknown): { id: string; token: string } | undefined {
81
+ if (typeof value !== 'object' || value === null) return undefined
82
+ const tunnel = value as { id?: unknown; token?: unknown }
83
+ if (typeof tunnel.id !== 'string' || tunnel.id === '') return undefined
84
+ if (typeof tunnel.token !== 'string' || tunnel.token === '') return undefined
85
+ return { id: tunnel.id, token: tunnel.token }
86
+ }
87
+
88
+ /** The CNAME target of one accepted claim, or undefined when it carries none. */
89
+ function relayDnsTargetOf(value: unknown): string | undefined {
90
+ if (typeof value !== 'object' || value === null) return undefined
91
+ const target = (value as { target?: unknown }).target
92
+ return typeof target === 'string' && target !== '' ? target : undefined
93
+ }
94
+
95
+ /** One lease read back from an accepted claim, or undefined for a bad shape. */
96
+ export function relayClaimOf(value: unknown): RelayClaim | undefined {
97
+ if (typeof value !== 'object' || value === null) return undefined
98
+ const body = value as { mode?: unknown; tunnel?: unknown; hostname?: unknown; dns?: unknown; bridge?: unknown }
99
+ const mode = body.mode
100
+ if (mode !== 'named' && mode !== 'quick' && mode !== 'bridge') return undefined
101
+ if (typeof body.hostname !== 'string' || body.hostname === '') return undefined
102
+ const tunnel = relayTunnelOf(body.tunnel)
103
+ const target = relayDnsTargetOf(body.dns)
104
+ // The tunnel transports are served by that tunnel, so a reply without both
105
+ // halves is a protocol error. The bridge is the one transport whose lease
106
+ // owns no Cloudflare object, and its claim carries neither half.
107
+ if (mode !== 'bridge' && (tunnel === undefined || target === undefined)) return undefined
108
+ const bridge = relayBridgeGrantOf(body.bridge)
109
+ return {
110
+ mode,
111
+ ...(tunnel === undefined ? {} : { tunnel }),
112
+ hostname: body.hostname,
113
+ ...(target === undefined ? {} : { dns: { target } }),
114
+ ...(bridge === undefined ? {} : { bridge }),
115
+ }
116
+ }
117
+
118
+ /** The bridge grant of one accepted lease, or undefined when it carries none. */
119
+ export function relayBridgeGrantOf(value: unknown): RelayBridgeGrant | undefined {
120
+ if (typeof value !== 'object' || value === null) return undefined
121
+ const grant = value as { endpoint?: unknown; instance?: unknown; credential?: unknown }
122
+ if (typeof grant.endpoint !== 'string' || grant.endpoint === '') return undefined
123
+ if (typeof grant.instance !== 'string' || grant.instance === '') return undefined
124
+ if (grant.credential !== 'lease-secret') return undefined
125
+ return { endpoint: grant.endpoint, instance: grant.instance, credential: 'lease-secret' }
126
+ }
127
+
128
+ /** The error code and retry hint of a refused claim. */
129
+ function refusalOf(status: number, detail: unknown): Extract<RelayClaimOutcome, { ok: false }> {
130
+ const body = typeof detail === 'object' && detail !== null
131
+ ? detail as { error?: unknown; retryAfterMs?: unknown }
132
+ : {}
133
+ const error = typeof body.error === 'string' ? body.error : 'http-' + String(status)
134
+ const retryAfterMs = typeof body.retryAfterMs === 'number' && Number.isFinite(body.retryAfterMs)
135
+ ? body.retryAfterMs
136
+ : undefined
137
+ return retryAfterMs === undefined ? { ok: false, status, error } : { ok: false, status, error, retryAfterMs }
138
+ }
139
+
140
+ /**
141
+ * Claim one lease. A transport failure is graded like `502 cf-api-unavailable`
142
+ * (status 0) so the caller retries on the same path as a refused upstream.
143
+ * @param request - the lease to refresh.
144
+ * @param options - endpoint and fetch seams (defaults are the real ones).
145
+ */
146
+ export async function claimRelayLease(
147
+ request: RelayClaimRequest,
148
+ options: { url?: string; fetchFn?: typeof fetch } = {},
149
+ ): Promise<RelayClaimOutcome> {
150
+ const fetchFn = options.fetchFn ?? fetch
151
+ let response: Response
152
+ try {
153
+ response = await fetchFn(options.url ?? RELAY_CLAIM_URL, {
154
+ method: 'PUT',
155
+ headers: { 'content-type': 'application/json' },
156
+ body: relayClaimBody(request),
157
+ })
158
+ } catch (error) {
159
+ const detail = error instanceof Error ? error.message : String(error)
160
+ return { ok: false, status: 0, error: detail === '' ? 'network-error' : detail }
161
+ }
162
+ const detail: unknown = await response.json().catch(() => undefined)
163
+ if (!response.ok) return refusalOf(response.status, detail)
164
+ const claim = relayClaimOf(detail)
165
+ return claim === undefined
166
+ ? { ok: false, status: response.status, error: 'invalid-response' }
167
+ : { ok: true, claim }
168
+ }
169
+
170
+ /**
171
+ * Release one lease (the plugin's offline action: toggle off, profile
172
+ * unmount). Best-effort — a release that never lands only leaves the row
173
+ * marked active, which the 90-day GC recovers.
174
+ */
175
+ export async function releaseRelayLease(
176
+ identity: RelayIdentity,
177
+ options: { url?: string; fetchFn?: typeof fetch } = {},
178
+ ): Promise<void> {
179
+ const fetchFn = options.fetchFn ?? fetch
180
+ await fetchFn(options.url ?? RELAY_RELEASE_URL, {
181
+ method: 'POST',
182
+ headers: { 'content-type': 'application/json' },
183
+ body: JSON.stringify({ id: identity.id, secret: identity.secret }),
184
+ })
185
+ }
186
+
187
+ /** How one failed claim should be retried. */
188
+ export interface RelayClaimRetry {
189
+ /** Whether another attempt is worth making at all. */
190
+ retry: boolean
191
+ /** How long to wait before that attempt. */
192
+ delayMs: number
193
+ /**
194
+ * Whether the identity must be re-claimed with `new_secret`: the control
195
+ * plane lost the row (a D1 restore or a manual wipe), which is the one
196
+ * condition a fresh claim fixes.
197
+ */
198
+ refreshIdentity: boolean
199
+ }
200
+
201
+ /**
202
+ * Grade one failed claim into a retry decision.
203
+ *
204
+ * `403 auth-failed` is terminal: the id belongs to another secret and no
205
+ * number of retries can take it back. Everything else retries on a capped
206
+ * exponential backoff, with the control plane's own `retryAfterMs` (a 502
207
+ * names it) raising the floor so a retry cannot land inside a known outage.
208
+ * @param outcome - the refused attempt.
209
+ * @param attempt - how many attempts already failed (0 for the first).
210
+ * @param options - backoff bounds (defaults are the shipped ones).
211
+ */
212
+ export function relayClaimRetryOf(
213
+ outcome: Extract<RelayClaimOutcome, { ok: false }>,
214
+ attempt: number,
215
+ options: { baseDelayMs?: number; maxDelayMs?: number } = {},
216
+ ): RelayClaimRetry {
217
+ const base = options.baseDelayMs ?? CLAIM_RETRY_BASE_MS
218
+ const max = options.maxDelayMs ?? CLAIM_RETRY_MAX_MS
219
+ if (outcome.status === 403) return { retry: false, delayMs: 0, refreshIdentity: false }
220
+ const backoff = Math.min(base * 2 ** attempt, max)
221
+ const delayMs = Math.min(Math.max(backoff, outcome.retryAfterMs ?? 0), max)
222
+ const refreshIdentity = outcome.error === 'invalid-params' || outcome.error === 'unknown-id'
223
+ return { retry: true, delayMs, refreshIdentity }
224
+ }