@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,275 @@
1
+ /**
2
+ * Relay registry client: a stable `https://<id>.dsh-market.com` origin in
3
+ * front of the plugin-managed quick tunnel, so a paired phone keeps one
4
+ * bookmark and one cookie context across `dsh web` restarts.
5
+ *
6
+ * The plugin mints an id + secret on first run and persists them per profile
7
+ * under `$DSH_HOME/remote-web-ui-registry/`; every tunnel (re)start
8
+ * re-registers the current quick URL with the market worker. Registration is
9
+ * best-effort: a registry outage never blocks the tunnel — the QR just falls
10
+ * back to the raw quick URL for that session (the pre-relay behavior).
11
+ *
12
+ * Not to be confused with `./relay.ts`, the bridge's own APNs push sender: the
13
+ * relay in this file is the Cloudflare-side one that fronts the tunnel. The
14
+ * persisted directory and file names below keep their historical spelling on
15
+ * purpose, so an existing profile keeps the identity it already paired with.
16
+ */
17
+
18
+ import { randomBytes } from 'node:crypto'
19
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
20
+ import { dirname, join } from 'node:path'
21
+ import { dshHome } from './dsh-home.ts'
22
+ import { relayControlEndpointOf } from './relay-control.ts'
23
+
24
+ // The registration endpoints are the control plane's own paths: one configured
25
+ // base (`relayControlUrl`) moves all four endpoints, these two included.
26
+ /** The market worker's registration endpoints (dsh-market.com edge API). */
27
+ export const RELAY_REGISTER_URL = relayControlEndpointOf('register')
28
+ export const RELAY_UNREGISTER_URL = relayControlEndpointOf('unregister')
29
+ /**
30
+ * The public origin template: one stable single-label subdomain per
31
+ * registration id. Single label on purpose — Universal SSL covers exactly
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.
36
+ */
37
+ export const RELAY_BASE_SUFFIX = '.dsh-market.com'
38
+
39
+ export const RELAY_ID_RE = /^[a-z0-9]{16}$/
40
+ export const RELAY_SECRET_RE = /^[A-Za-z0-9_-]{43}$/
41
+
42
+ /** Persisted per-profile relay identity. */
43
+ export interface RelayIdentity {
44
+ id: string
45
+ secret: string
46
+ /**
47
+ * True only for an identity minted in this process that has never been
48
+ * accepted by the registry: the first register carries `new_secret` so
49
+ * the endpoint may create the row; refreshes authenticate with `secret`
50
+ * alone and must not re-claim an id that already exists.
51
+ */
52
+ fresh?: boolean
53
+ }
54
+
55
+ /** The observable relay lifecycle the settings card renders. */
56
+ export type RelayState =
57
+ | { state: 'off' }
58
+ | { state: 'registering' }
59
+ | { state: 'running'; url: string }
60
+ | { state: 'failed'; error: string }
61
+
62
+ /** Registry storage layout: one file per profile under the relay directory. */
63
+ export function relayIdentityFile(profile: string, home: string = dshHome()): string {
64
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(profile)) {
65
+ throw new Error(`relay registry: profile ${JSON.stringify(profile)} is not a safe path segment`)
66
+ }
67
+ return join(home, 'remote-web-ui-registry', `${profile}.json`)
68
+ }
69
+
70
+ /** Generate one identity pair (id: 8-byte hex slug; secret: 32-byte base64url). */
71
+ export function generateRelayIdentity(random: (size: number) => Buffer = randomBytes): RelayIdentity {
72
+ return {
73
+ id: random(8).toString('hex'),
74
+ secret: random(32).toString('base64url'),
75
+ fresh: true,
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Load (or lazily mint) the per-profile relay identity. The file is written
81
+ * owner-only on first mint; a corrupt file is reminted (the phone then
82
+ * re-pairs once — the same cost as losing the devices file).
83
+ */
84
+ export function loadRelayIdentity(profile: string, home: string = dshHome(), random: (size: number) => Buffer = randomBytes): RelayIdentity {
85
+ const file = relayIdentityFile(profile, home)
86
+ try {
87
+ if (existsSync(file)) {
88
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RelayIdentity>
89
+ if (typeof parsed.id === 'string' && RELAY_ID_RE.test(parsed.id)
90
+ && typeof parsed.secret === 'string' && RELAY_SECRET_RE.test(parsed.secret)) {
91
+ // A persisted identity has certainly been registered before.
92
+ return { id: parsed.id, secret: parsed.secret }
93
+ }
94
+ console.warn(`relay registry: ${file} is malformed — reminting the identity (paired devices must scan the QR once more)`)
95
+ }
96
+ } catch (error) {
97
+ console.warn(`relay registry: could not read ${file} (${error instanceof Error ? error.message : String(error)}) — reminting`)
98
+ }
99
+ const identity = generateRelayIdentity(random)
100
+ mkdirSync(dirname(file), { recursive: true })
101
+ writeFileSync(file, JSON.stringify({ id: identity.id, secret: identity.secret }, null, 2) + '\n', { mode: 0o600 })
102
+ return identity
103
+ }
104
+
105
+ /**
106
+ * 读一份**已经存在**的身份,绝不生成。
107
+ *
108
+ * 与 {@link loadRelayIdentity} 的唯一区别就在这里:文件不在、或读不出合法的
109
+ * id/secret 时返回 undefined,既不 mint 也不写盘,目录也不会被创建。关掉 relay 的
110
+ * 挂载路径靠它收掉上一次挂载留下的注册行与租约——挂载本身不是「申请一份新身份」的
111
+ * 理由,一个从没配过 relay 的宿主不该因为挂载就在 $DSH_HOME 里落下一份密钥文件。
112
+ * 坏文件同样原样留在盘上:等 relay 真的打开时由 loadRelayIdentity 按既有语义重新生成。
113
+ * @param profile - 受管 profile。
114
+ * @param home - DSH home(测试注入)。
115
+ * @returns 已存在的身份,或 undefined(没有可用身份,且什么都没写)。
116
+ */
117
+ export function readExistingRelayIdentity(profile: string, home: string = dshHome()): RelayIdentity | undefined {
118
+ const file = relayIdentityFile(profile, home)
119
+ try {
120
+ if (!existsSync(file)) return undefined
121
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RelayIdentity>
122
+ if (typeof parsed.id !== 'string' || !RELAY_ID_RE.test(parsed.id)) return undefined
123
+ if (typeof parsed.secret !== 'string' || !RELAY_SECRET_RE.test(parsed.secret)) return undefined
124
+ return { id: parsed.id, secret: parsed.secret }
125
+ } catch {
126
+ // 读不出来就是没有可用身份:这条路径什么都不做,也不写盘。
127
+ return undefined
128
+ }
129
+ }
130
+
131
+ /** Build the registration request body for one identity + tunnel target. */
132
+ function registrationBody(identity: RelayIdentity, target: string): string {
133
+ return JSON.stringify({
134
+ id: identity.id,
135
+ secret: identity.secret,
136
+ new_secret: identity.fresh === true ? identity.secret : undefined,
137
+ target,
138
+ })
139
+ }
140
+
141
+ /** Best-effort removal of the mapping (used on disable; errors are swallowed). */
142
+ export async function unregisterRelay(
143
+ identity: RelayIdentity,
144
+ endpoint: string = RELAY_UNREGISTER_URL,
145
+ fetchFn: typeof fetch = fetch,
146
+ ): Promise<void> {
147
+ await fetchFn(endpoint, {
148
+ method: 'POST',
149
+ headers: { 'content-type': 'application/json' },
150
+ body: JSON.stringify({ id: identity.id, secret: identity.secret }),
151
+ })
152
+ }
153
+
154
+ /**
155
+ * The stable relay base for one identity — the origin the QR and the phone
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.
160
+ */
161
+ export function relayBaseOf(identity: RelayIdentity, publicSuffix: string = RELAY_BASE_SUFFIX): string {
162
+ return `https://${identity.id}${publicSuffix}`
163
+ }
164
+
165
+ /**
166
+ * Registration loop with capped exponential backoff. Re-registration happens
167
+ * on every tunnel start (the quick URL can change after a crash-restart);
168
+ * failures retry with backoff and surface the last error to the card.
169
+ */
170
+ export class RelayRegistrar {
171
+ private timer: NodeJS.Timeout | undefined
172
+ private attempts = 0
173
+ private lastError: string | undefined
174
+ private disposed = false
175
+
176
+ constructor(
177
+ private readonly identity: RelayIdentity,
178
+ private readonly setState: (state: RelayState) => void,
179
+ private readonly options: {
180
+ fetchFn?: typeof fetch
181
+ registerUrl?: string
182
+ unregisterUrl?: string
183
+ /** The public suffix the hostname template uses (default
184
+ * {@link RELAY_BASE_SUFFIX}). */
185
+ publicSuffix?: string
186
+ baseDelayMs?: number
187
+ maxDelayMs?: number
188
+ timerFn?: (fn: () => void, ms: number) => NodeJS.Timeout
189
+ } = {},
190
+ ) {}
191
+
192
+ /** The stable relay base for the QR while registered. */
193
+ get baseUrl(): string {
194
+ return relayBaseOf(this.identity, this.options.publicSuffix)
195
+ }
196
+
197
+ /** The last registration failure detail (undefined while healthy). */
198
+ get error(): string | undefined {
199
+ return this.lastError
200
+ }
201
+
202
+ /** Push one tunnel target; resolves the stable base once accepted. */
203
+ async announce(target: string): Promise<string | undefined> {
204
+ // A disposed registrar stays disposed: a pending retry timer must not
205
+ // resurrect it (re-enabling creates a fresh registrar instead).
206
+ if (this.disposed) return undefined
207
+ if (this.timer !== undefined) {
208
+ clearTimeout(this.timer)
209
+ this.timer = undefined
210
+ }
211
+ this.setState({ state: 'registering' })
212
+ try {
213
+ const fetchFn = this.options.fetchFn ?? fetch
214
+ const response = await fetchFn(this.options.registerUrl ?? RELAY_REGISTER_URL, {
215
+ method: 'PUT',
216
+ headers: { 'content-type': 'application/json' },
217
+ body: registrationBody(this.identity, target),
218
+ })
219
+ if (!response.ok) {
220
+ const detail = await response.json().catch(() => undefined)
221
+ const error = detail && typeof detail.error === 'string' ? detail.error : `HTTP ${String(response.status)}`
222
+ throw new Error(error)
223
+ }
224
+ // The row exists now: never claim a fresh id twice.
225
+ this.identity.fresh = false
226
+ this.attempts = 0
227
+ this.lastError = undefined
228
+ this.setState({ state: 'running', url: this.baseUrl })
229
+ return this.baseUrl
230
+ } catch (error) {
231
+ this.lastError = error instanceof Error ? error.message : String(error)
232
+ if (this.lastError === 'invalid-params' && this.identity.fresh !== true) {
233
+ // The registry lost the row (a D1 restore or manual wipe): re-claim
234
+ // the id with a fresh claim on the next retry. A 403 auth-failed
235
+ // means the id is owned by another secret and stays failed.
236
+ this.identity.fresh = true
237
+ }
238
+ this.setState({ state: 'failed', error: this.lastError })
239
+ this.scheduleRetry(target)
240
+ return undefined
241
+ }
242
+ }
243
+
244
+ /** Best-effort removal of the registry row (the relay toggle turned off). */
245
+ async unregister(): Promise<void> {
246
+ await unregisterRelay(this.identity, this.options.unregisterUrl, this.options.fetchFn)
247
+ }
248
+
249
+ private scheduleRetry(target: string): void {
250
+ if (this.disposed) return
251
+ const base = this.options.baseDelayMs ?? 5_000
252
+ const max = this.options.maxDelayMs ?? 60_000
253
+ const delay = Math.min(base * 2 ** this.attempts, max)
254
+ this.attempts += 1
255
+ const timerFn = this.options.timerFn ?? ((fn: () => void, ms: number) => {
256
+ const timer = setTimeout(fn, ms)
257
+ timer.unref?.()
258
+ return timer
259
+ })
260
+ this.timer = timerFn(() => {
261
+ this.timer = undefined
262
+ void this.announce(target)
263
+ }, delay)
264
+ }
265
+
266
+ /** Stop retrying and clear the card state (tunnel stopped or disabled). */
267
+ dispose(): void {
268
+ this.disposed = true
269
+ if (this.timer !== undefined) {
270
+ clearTimeout(this.timer)
271
+ this.timer = undefined
272
+ }
273
+ this.setState({ state: 'off' })
274
+ }
275
+ }