@linxin666/dsh-remote-bridge 0.4.13 → 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.
@@ -14,6 +14,7 @@ import { dshHome } from './dsh-home.ts'
14
14
  import {
15
15
  claimRelayLease,
16
16
  relayClaimRetryOf,
17
+ relayControlEndpointOf,
17
18
  releaseRelayLease,
18
19
  type RelayClaim,
19
20
  type RelayClaimOutcome,
@@ -137,6 +138,10 @@ export interface RelayConnectorPairOptions {
137
138
  stopBridge?: () => void
138
139
  /** Release the lease (the offline action, never a retire). */
139
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
140
145
  /** Observe the lease state (logs only — the card still renders the registry). */
141
146
  onState?: (state: RelayPairState) => void
142
147
  baseDelayMs?: number
@@ -189,7 +194,8 @@ export class RelayConnectorPair {
189
194
  if (this.disposed) return undefined
190
195
  this.clearTimer()
191
196
  this.setState({ state: 'claiming' })
192
- const claimFn = this.options.claim ?? ((request: RelayClaimRequest) => claimRelayLease(request))
197
+ const claimFn = this.options.claim
198
+ ?? ((request: RelayClaimRequest) => claimRelayLease(request, { url: relayControlEndpointOf('claim', this.options.controlUrl) }))
193
199
  let outcome: RelayClaimOutcome
194
200
  try {
195
201
  outcome = await claimFn({
@@ -229,7 +235,8 @@ export class RelayConnectorPair {
229
235
  * phone's bookmark, and the tunnel behind it survives.
230
236
  */
231
237
  async release(): Promise<void> {
232
- const releaseFn = this.options.release ?? ((identity: RelayIdentity) => releaseRelayLease(identity))
238
+ const releaseFn = this.options.release
239
+ ?? ((identity: RelayIdentity) => releaseRelayLease(identity, { url: relayControlEndpointOf('release', this.options.controlUrl) }))
233
240
  try {
234
241
  await releaseFn(this.identity)
235
242
  } catch {
@@ -13,9 +13,35 @@
13
13
 
14
14
  import type { RelayIdentity } from './relay-registry.ts'
15
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'
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')
19
45
 
20
46
  /** Which connector serves the relay hostname. `bridge` is the Durable Object
21
47
  * meeting point (`relay-bridge-connector.ts`), `named` the instance's own cloud
@@ -59,20 +85,73 @@ export interface RelayClaimRequest {
59
85
  port: number
60
86
  /** The plugin version, for the adoption readout of the migration. */
61
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
62
98
  }
63
99
 
64
- /** The capped backoff a failed claim retries on. */
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
+ */
65
106
  export const CLAIM_RETRY_BASE_MS = 5_000
66
- export const CLAIM_RETRY_MAX_MS = 60_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
67
142
 
68
143
  /** Build the claim body (an absent value is omitted, never sent as null). */
69
144
  export function relayClaimBody(request: RelayClaimRequest): string {
145
+ const grant = request.grant
70
146
  return JSON.stringify({
71
147
  id: request.id,
72
148
  secret: request.secret,
73
149
  new_secret: request.newSecret,
74
150
  origin: { port: request.port },
75
151
  plugin: request.pluginVersion === undefined ? undefined : { version: request.pluginVersion },
152
+ // 没有授权就不带这个键,也不写 null:第二会合点把「没有授权」与「授权验不过」
153
+ // 分成两个答案,而 null 只会掉进后者。
154
+ ...(typeof grant === 'string' && grant !== '' ? { grant } : {}),
76
155
  })
77
156
  }
78
157
 
@@ -202,7 +281,11 @@ export interface RelayClaimRetry {
202
281
  * Grade one failed claim into a retry decision.
203
282
  *
204
283
  * `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
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
206
289
  * exponential backoff, with the control plane's own `retryAfterMs` (a 502
207
290
  * names it) raising the floor so a retry cannot land inside a known outage.
208
291
  * @param outcome - the refused attempt.
@@ -216,7 +299,15 @@ export function relayClaimRetryOf(
216
299
  ): RelayClaimRetry {
217
300
  const base = options.baseDelayMs ?? CLAIM_RETRY_BASE_MS
218
301
  const max = options.maxDelayMs ?? CLAIM_RETRY_MAX_MS
219
- if (outcome.status === 403) return { retry: false, delayMs: 0, refreshIdentity: false }
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
+ }
220
311
  const backoff = Math.min(base * 2 ** attempt, max)
221
312
  const delayMs = Math.min(Math.max(backoff, outcome.retryAfterMs ?? 0), max)
222
313
  const refreshIdentity = outcome.error === 'invalid-params' || outcome.error === 'unknown-id'
@@ -19,14 +19,20 @@ import { randomBytes } from 'node:crypto'
19
19
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
20
20
  import { dirname, join } from 'node:path'
21
21
  import { dshHome } from './dsh-home.ts'
22
+ import { relayControlEndpointOf } from './relay-control.ts'
22
23
 
24
+ // The registration endpoints are the control plane's own paths: one configured
25
+ // base (`relayControlUrl`) moves all four endpoints, these two included.
23
26
  /** The market worker's registration endpoints (dsh-market.com edge API). */
24
- export const RELAY_REGISTER_URL = 'https://dsh-market.com/api/relay/register'
25
- export const RELAY_UNREGISTER_URL = 'https://dsh-market.com/api/relay/unregister'
27
+ export const RELAY_REGISTER_URL = relayControlEndpointOf('register')
28
+ export const RELAY_UNREGISTER_URL = relayControlEndpointOf('unregister')
26
29
  /**
27
30
  * The public origin template: one stable single-label subdomain per
28
31
  * registration id. Single label on purpose — Universal SSL covers exactly
29
32
  * one subdomain level, so a two-level hostname would get no certificate.
33
+ *
34
+ * This constant is the one home of the shipped default suffix; a self-hosted
35
+ * meeting point sets `relayPublicSuffix` and the hostname template follows.
30
36
  */
31
37
  export const RELAY_BASE_SUFFIX = '.dsh-market.com'
32
38
 
@@ -148,9 +154,12 @@ export async function unregisterRelay(
148
154
  /**
149
155
  * The stable relay base for one identity — the origin the QR and the phone
150
156
  * bookmark use while (or after) the registration is accepted.
157
+ * @param identity - the registration identity.
158
+ * @param publicSuffix - the configured suffix; undefined means the shipped one.
159
+ * @returns the origin, with no path of its own.
151
160
  */
152
- export function relayBaseOf(identity: RelayIdentity): string {
153
- return `https://${identity.id}${RELAY_BASE_SUFFIX}`
161
+ export function relayBaseOf(identity: RelayIdentity, publicSuffix: string = RELAY_BASE_SUFFIX): string {
162
+ return `https://${identity.id}${publicSuffix}`
154
163
  }
155
164
 
156
165
  /**
@@ -171,6 +180,9 @@ export class RelayRegistrar {
171
180
  fetchFn?: typeof fetch
172
181
  registerUrl?: string
173
182
  unregisterUrl?: string
183
+ /** The public suffix the hostname template uses (default
184
+ * {@link RELAY_BASE_SUFFIX}). */
185
+ publicSuffix?: string
174
186
  baseDelayMs?: number
175
187
  maxDelayMs?: number
176
188
  timerFn?: (fn: () => void, ms: number) => NodeJS.Timeout
@@ -179,7 +191,7 @@ export class RelayRegistrar {
179
191
 
180
192
  /** The stable relay base for the QR while registered. */
181
193
  get baseUrl(): string {
182
- return relayBaseOf(this.identity)
194
+ return relayBaseOf(this.identity, this.options.publicSuffix)
183
195
  }
184
196
 
185
197
  /** The last registration failure detail (undefined while healthy). */