@linxin666/dsh-remote-bridge 0.4.13 → 0.4.15

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 (41) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +17 -12
  3. package/README.zh.md +17 -12
  4. package/lib/client.js +160 -109
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +3053 -4804
  7. package/lib/types/client/PairPanel.d.ts +13 -1
  8. package/lib/types/client/locales.d.ts +18 -10
  9. package/lib/types/client/pair-token.d.ts +7 -0
  10. package/lib/types/core/connection.d.ts +41 -0
  11. package/lib/types/core/devices.d.ts +60 -7
  12. package/lib/types/core/pair-address.d.ts +25 -0
  13. package/lib/types/core/protocol.d.ts +22 -0
  14. package/lib/types/core/push.d.ts +19 -1
  15. package/lib/types/host/relay-bridge-connector.d.ts +19 -0
  16. package/lib/types/host/relay-connector.d.ts +4 -0
  17. package/lib/types/host/relay-control.d.ts +77 -6
  18. package/lib/types/host/relay-registry.d.ts +12 -3
  19. package/lib/types/host/relay-secondary.d.ts +209 -0
  20. package/lib/types/host/relay.d.ts +1 -1
  21. package/lib/types/host/routes.d.ts +5 -0
  22. package/lib/types/index.d.ts +65 -3
  23. package/package.json +16 -16
  24. package/src/client/PairEntry.tsx +1 -0
  25. package/src/client/PairPanel.tsx +44 -5
  26. package/src/client/locales.ts +25 -15
  27. package/src/client/pair-token.ts +17 -2
  28. package/src/client/panel.module.css +32 -0
  29. package/src/core/connection.ts +110 -0
  30. package/src/core/devices.ts +141 -17
  31. package/src/core/pair-address.ts +50 -0
  32. package/src/core/protocol.ts +24 -0
  33. package/src/core/push.ts +20 -1
  34. package/src/host/relay-bridge-connector.ts +68 -2
  35. package/src/host/relay-connector.ts +9 -2
  36. package/src/host/relay-control.ts +98 -7
  37. package/src/host/relay-registry.ts +17 -5
  38. package/src/host/relay-secondary.ts +478 -0
  39. package/src/host/relay.ts +1 -1
  40. package/src/host/routes.ts +22 -5
  41. package/src/index.ts +270 -35
@@ -30,6 +30,16 @@
30
30
  *
31
31
  * Frames mirror `market/worker/src/relay-bridge.js`: control frames are JSON
32
32
  * text, payload frames are `[kind:u8][streamId:u32be][payload]`.
33
+ *
34
+ * Flow control runs one way only, object to connector. A pause closes the
35
+ * object's window on one stream: this half stops sending that stream's payload
36
+ * frames and stops reading the upstream (a response body, a WebSocket socket),
37
+ * so the backlog waits in the kernel instead of in this process. A resume opens
38
+ * it again. A stream being abandoned arrives as close -- the frame this contract
39
+ * already used for a phone cancel -- and cancel is accepted as the same thing,
40
+ * because that is the name the frozen contract gives it. An object too old to
41
+ * send any of them leaves this half exactly as it was, and a frame this half has
42
+ * never heard of is ignored rather than answered.
33
43
  */
34
44
 
35
45
  import { randomBytes } from 'node:crypto'
@@ -320,6 +330,11 @@ interface BridgePeer {
320
330
  close: (code: number, reason: string) => void
321
331
  text: (body: string) => void
322
332
  binary: (body: Buffer) => void
333
+ /** Stop reading the upstream socket: the object's window on this stream is
334
+ * closed, so the backlog waits there rather than in this process. */
335
+ pause: () => void
336
+ /** Start reading it again. */
337
+ resume: () => void
323
338
  }
324
339
 
325
340
  /**
@@ -333,7 +348,11 @@ export class RelayBridgeConnector {
333
348
  private stateValue: RelayBridgeState = { state: 'idle' }
334
349
  private attempts = 0
335
350
  private disposed = false
351
+ /** HTTP streams still uploading: the request the object's frames feed. */
336
352
  private readonly requests = new Map<number, http.ClientRequest>()
353
+ /** HTTP streams whose head already arrived: the upstream response body a
354
+ * pause holds back and a stream being abandoned destroys. */
355
+ private readonly responses = new Map<number, http.IncomingMessage>()
337
356
  private readonly peers = new Map<number, BridgePeer>()
338
357
 
339
358
  private readonly options: RelayBridgeConnectorOptions
@@ -478,6 +497,16 @@ export class RelayBridgeConnector {
478
497
  this.peers.get(id)?.close(typeof frame.code === 'number' ? frame.code : 1000, String(frame.reason ?? ''))
479
498
  this.peers.delete(id)
480
499
  return
500
+ case 'pause':
501
+ this.pauseStream(id)
502
+ return
503
+ case 'resume':
504
+ this.resumeStream(id)
505
+ return
506
+ // A stream being abandoned under either spelling reaches one release path:
507
+ // close is what this contract already sent for a phone cancel, and cancel
508
+ // is what the frozen frame vocabulary calls the same thing.
509
+ case 'cancel':
481
510
  case 'close': {
482
511
  const peer = this.peers.get(id)
483
512
  if (peer !== undefined) {
@@ -485,6 +514,11 @@ export class RelayBridgeConnector {
485
514
  peer.close(1000, String(frame.reason ?? 'closed'))
486
515
  return
487
516
  }
517
+ const response = this.responses.get(id)
518
+ if (response !== undefined) {
519
+ this.responses.delete(id)
520
+ response.destroy()
521
+ }
488
522
  const request = this.requests.get(id)
489
523
  if (request !== undefined) {
490
524
  this.requests.delete(id)
@@ -493,9 +527,25 @@ export class RelayBridgeConnector {
493
527
  return
494
528
  }
495
529
  default:
530
+ // A frame this build has never heard of: an older half ignores what a
531
+ // newer one adds, so there is nothing here to answer.
532
+ return
496
533
  }
497
534
  }
498
535
 
536
+ /** Close the object's window on one stream: a paused response body emits no
537
+ * more data events and a paused socket leaves its bytes in the kernel. */
538
+ private pauseStream(id: number): void {
539
+ this.responses.get(id)?.pause()
540
+ this.peers.get(id)?.pause()
541
+ }
542
+
543
+ /** Reopen that window. */
544
+ private resumeStream(id: number): void {
545
+ this.responses.get(id)?.resume()
546
+ this.peers.get(id)?.resume()
547
+ }
548
+
499
549
  /**
500
550
  * Answer one bridged stream with 404 without dialing anything: the refusal is
501
551
  * complete here, so a non-whitelisted path costs the upstream nothing.
@@ -536,6 +586,9 @@ export class RelayBridgeConnector {
536
586
  headers: bridgeUpstreamHeaders(frame.headers, host),
537
587
  }, (response: http.IncomingMessage) => {
538
588
  this.requests.delete(id)
589
+ // The body is what the object's window pauses and a cancel destroys, so
590
+ // the handle outlives this callback.
591
+ this.responses.set(id, response)
539
592
  this.sendText(JSON.stringify({
540
593
  t: 'res',
541
594
  id,
@@ -544,8 +597,15 @@ export class RelayBridgeConnector {
544
597
  headers: rawHeaderPairs(response.rawHeaders),
545
598
  }))
546
599
  response.on('data', (chunk: Buffer) => { this.sendChunk(encodeChunk(HTTP_BODY, id, chunk)) })
547
- response.on('end', () => { this.sendText(JSON.stringify({ t: 'fin', id })) })
548
- response.on('error', (error: Error) => { this.sendText(JSON.stringify({ t: 'fail', id, message: error.message })) })
600
+ response.on('close', () => { this.responses.delete(id) })
601
+ response.on('end', () => {
602
+ this.responses.delete(id)
603
+ this.sendText(JSON.stringify({ t: 'fin', id }))
604
+ })
605
+ response.on('error', (error: Error) => {
606
+ this.responses.delete(id)
607
+ this.sendText(JSON.stringify({ t: 'fail', id, message: error.message }))
608
+ })
549
609
  })
550
610
  request.on('error', (error: Error) => {
551
611
  this.requests.delete(id)
@@ -613,6 +673,8 @@ export class RelayBridgeConnector {
613
673
  binary: (body: Buffer) => {
614
674
  if (!peer.closed) dialed.socket.write(encodeBridgeFrame(0x2, body))
615
675
  },
676
+ pause: () => { dialed.socket.pause() },
677
+ resume: () => { dialed.socket.resume() },
616
678
  }
617
679
  const parse = createBridgeFrameParser((incoming) => {
618
680
  if (incoming.opcode === 0x1) {
@@ -682,6 +744,10 @@ export class RelayBridgeConnector {
682
744
 
683
745
  /** Drop every stream this socket carried: the object re-opens them. */
684
746
  private teardown(): void {
747
+ for (const [id, response] of this.responses) {
748
+ this.responses.delete(id)
749
+ response.destroy()
750
+ }
685
751
  for (const [id, request] of this.requests) {
686
752
  this.requests.delete(id)
687
753
  request.destroy()
@@ -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). */