@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.
- package/README.i18n.yaml +2 -2
- package/README.md +13 -8
- package/README.zh.md +13 -8
- package/lib/client.js +112 -90
- package/lib/client.js.map +1 -1
- package/lib/index.js +873 -65
- package/lib/types/client/PairPanel.d.ts +7 -0
- package/lib/types/client/locales.d.ts +13 -10
- package/lib/types/core/connection.d.ts +41 -0
- package/lib/types/core/devices.d.ts +60 -7
- package/lib/types/core/protocol.d.ts +22 -0
- package/lib/types/core/push.d.ts +19 -1
- package/lib/types/host/relay-bridge-connector.d.ts +19 -0
- package/lib/types/host/relay-connector.d.ts +4 -0
- package/lib/types/host/relay-control.d.ts +77 -6
- package/lib/types/host/relay-registry.d.ts +12 -3
- package/lib/types/host/relay-secondary.d.ts +209 -0
- package/lib/types/host/relay.d.ts +1 -1
- package/lib/types/host/routes.d.ts +5 -0
- package/lib/types/index.d.ts +65 -3
- package/package.json +1 -1
- package/src/client/PairPanel.tsx +21 -0
- package/src/client/locales.ts +19 -15
- package/src/client/panel.module.css +32 -0
- package/src/core/connection.ts +110 -0
- package/src/core/devices.ts +141 -17
- package/src/core/protocol.ts +24 -0
- package/src/core/push.ts +20 -1
- package/src/host/relay-bridge-connector.ts +68 -2
- package/src/host/relay-connector.ts +9 -2
- package/src/host/relay-control.ts +98 -7
- package/src/host/relay-registry.ts +17 -5
- package/src/host/relay-secondary.ts +478 -0
- package/src/host/relay.ts +1 -1
- package/src/host/routes.ts +10 -0
- package/src/index.ts +270 -35
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The second meeting point: the self-hosted relay a configured host keeps beside
|
|
3
|
+
* the market edge.
|
|
4
|
+
*
|
|
5
|
+
* One relay identity serves both meetings — the id and the secret are minted once
|
|
6
|
+
* for this profile and never re-minted for a second endpoint — but everything else
|
|
7
|
+
* about the two halves is separate: their own claim, their own lease, their own
|
|
8
|
+
* connector and their own release. That separation is the reason this file exists.
|
|
9
|
+
* A second meeting point that refuses, times out or is switched off in the provider
|
|
10
|
+
* console must leave the lease that already serves the phone over `dsh-market.com`
|
|
11
|
+
* exactly as it stands, and the reverse holds as well.
|
|
12
|
+
*
|
|
13
|
+
* The half is off unless the mount is configured with both halves of a meeting
|
|
14
|
+
* point — a control-plane base and the public suffix its origin is built from —
|
|
15
|
+
* and {@link relaySecondaryOf} is the one place that decides it. A host that
|
|
16
|
+
* configures nothing therefore never constructs this object, never dials anything
|
|
17
|
+
* and never writes a grant into its roster, which is what keeps the default
|
|
18
|
+
* behaviour of `hello`, the roster and the network byte for byte what it was.
|
|
19
|
+
*
|
|
20
|
+
* The grant is the phone's, not this bridge's ({@link DeviceRoster.setRelayGrant}):
|
|
21
|
+
* this half only reads whatever the newest row holds and presents it to the second
|
|
22
|
+
* control plane. It learns "admitted" or "not admitted" and never learns a tier, a
|
|
23
|
+
* user or an account.
|
|
24
|
+
*
|
|
25
|
+
* A held lease is re-claimed every six hours ({@link SECONDARY_CLAIM_REFRESH_MS}),
|
|
26
|
+
* because the relay only admits a connector whose lease was claimed inside the last
|
|
27
|
+
* 24 hours — so what `hello` announces is a lease the relay admits right now, not one
|
|
28
|
+
* this host once obtained. The market edge has no such loop: its claim follows the
|
|
29
|
+
* plugin's own lifecycle events, and a default host keeps behaving exactly as it did.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { join } from 'node:path'
|
|
33
|
+
import { dshHome } from './dsh-home.ts'
|
|
34
|
+
import {
|
|
35
|
+
claimRelayLease,
|
|
36
|
+
releaseRelayLease,
|
|
37
|
+
relayControlEndpointOf,
|
|
38
|
+
RELAY_GRANT_INVALID,
|
|
39
|
+
RELAY_TIER_REQUIRED,
|
|
40
|
+
type RelayClaimOutcome,
|
|
41
|
+
type RelayClaimRequest,
|
|
42
|
+
} from './relay-control.ts'
|
|
43
|
+
import { RelayConnectorPair, type RelayBridgeStart, type RelayPairState } from './relay-connector.ts'
|
|
44
|
+
import type { RelayIdentity } from './relay-registry.ts'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The refusal codes that say this instance holds no second lease at all.
|
|
48
|
+
*
|
|
49
|
+
* `tier-required` is the entitlement answer, `grant-invalid` the grant the account
|
|
50
|
+
* service will not vouch for (an expired 30-day grant is this one), `auth-failed`
|
|
51
|
+
* the id that belongs to another secret on this meeting point. Every other refusal
|
|
52
|
+
* is transient by nature (a rate limit, an upstream outage, a socket that never
|
|
53
|
+
* answered) and keeps the announcement: the lease the relay already recorded runs
|
|
54
|
+
* on its own 24-hour clock and the connector behind it is still up, so withdrawing
|
|
55
|
+
* the origin on a failed refresh would flap a working phone path back to the market
|
|
56
|
+
* edge.
|
|
57
|
+
*/
|
|
58
|
+
const SECOND_LEASE_REFUSED: ReadonlySet<string> = new Set<string>([RELAY_TIER_REQUIRED, RELAY_GRANT_INVALID, 'auth-failed'])
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The subset of those refusals that also releases the lease and stops the connector.
|
|
62
|
+
*
|
|
63
|
+
* Exactly the two admission refusals: the host no longer has anything the relay
|
|
64
|
+
* admits, so the lease row it may still hold is withdrawn and the connector that
|
|
65
|
+
* would re-dial with it is stopped. `auth-failed` is deliberately NOT here — the
|
|
66
|
+
* release would be refused by the same credential check, so the only thing left to
|
|
67
|
+
* do is stop announcing, which the withdrawal above already did.
|
|
68
|
+
*/
|
|
69
|
+
const SECOND_LEASE_RELEASED: ReadonlySet<string> = new Set<string>([RELAY_TIER_REQUIRED, RELAY_GRANT_INVALID])
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* How often a held second lease is refreshed: six hours.
|
|
73
|
+
*
|
|
74
|
+
* The relay stops admitting a connector when the lease behind it has not been
|
|
75
|
+
* claimed within 24 hours, so the refresh has to run well inside that window, and
|
|
76
|
+
* six hours is the interval the design itself names (a downgrade is then noticed at
|
|
77
|
+
* the next refresh rather than at the next restart). The market edge has no such
|
|
78
|
+
* loop on purpose: its lease is refreshed by the plugin's own lifecycle events, and
|
|
79
|
+
* the default host must keep behaving exactly as it did.
|
|
80
|
+
*/
|
|
81
|
+
export const SECONDARY_CLAIM_REFRESH_MS = 6 * 60 * 60 * 1000
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* How a refused connector attach reads in the bridge runner's state line.
|
|
85
|
+
*
|
|
86
|
+
* The connector reports the status it was refused with (`refused with 403`), never
|
|
87
|
+
* the body, so `lease-stale` — the relay's answer to a lease nobody claimed inside
|
|
88
|
+
* the 24-hour window — cannot be read by name from this side. A credential refusal
|
|
89
|
+
* reads the same way (`401`), and both are repaired by the same act: claim again
|
|
90
|
+
* with the identity the connector presents.
|
|
91
|
+
*/
|
|
92
|
+
const ATTACH_REFUSED_RE = /(?:refused with|upgrade answered)\s+40[13]\b/
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Where the second connector records its state
|
|
96
|
+
* (`$DSH_HOME/remote-web-ui-relay-bridge-secondary.json`).
|
|
97
|
+
*
|
|
98
|
+
* Its own file, never the first half's: two connectors that wrote one record would
|
|
99
|
+
* each overwrite the other's state, and the record exists precisely to say which
|
|
100
|
+
* meeting point served which lease.
|
|
101
|
+
* @param home - the DSH home (a test seam).
|
|
102
|
+
* @returns the absolute record path.
|
|
103
|
+
*/
|
|
104
|
+
export function relaySecondaryBridgeStateFile(home: string = dshHome()): string {
|
|
105
|
+
return join(home, 'remote-web-ui-relay-bridge-secondary.json')
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** One configured second meeting point. */
|
|
109
|
+
export interface RelaySecondaryMeetingPoint {
|
|
110
|
+
/** The second control-plane base: its `claim` and `release` both hang off it. */
|
|
111
|
+
readonly controlUrl: string
|
|
112
|
+
/** The public suffix the announced origin is built from, leading dot included. */
|
|
113
|
+
readonly publicSuffix: string
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The second meeting point one configuration names, or undefined.
|
|
118
|
+
*
|
|
119
|
+
* Both halves are required and neither has a default: an origin cannot be built
|
|
120
|
+
* from a control-plane base alone, and a control plane cannot be reached from a
|
|
121
|
+
* suffix alone. A profile that names only one of them therefore has no second
|
|
122
|
+
* meeting point at all rather than half of one, which keeps every consumer of this
|
|
123
|
+
* answer able to treat "undefined" as "this host has one meeting point".
|
|
124
|
+
* @param config - the resolved bridge configuration (read structurally).
|
|
125
|
+
* @returns the meeting point, or undefined when this host has none.
|
|
126
|
+
*/
|
|
127
|
+
export function relaySecondaryOf(config: {
|
|
128
|
+
readonly relaySecondaryControlUrl?: string
|
|
129
|
+
readonly relaySecondaryPublicSuffix?: string
|
|
130
|
+
}): RelaySecondaryMeetingPoint | undefined {
|
|
131
|
+
const controlUrl = config.relaySecondaryControlUrl?.trim()
|
|
132
|
+
const suffix = config.relaySecondaryPublicSuffix?.trim()
|
|
133
|
+
if (controlUrl === undefined || controlUrl === '') return undefined
|
|
134
|
+
if (suffix === undefined || suffix === '') return undefined
|
|
135
|
+
// 主机名是 `<id>` 直接拼上这个后缀,所以缺了那个点就会拼出一个不存在的主机名。
|
|
136
|
+
// 配置是手写的,这里补上它,比让公告指向一个拨不通的地址好。
|
|
137
|
+
return { controlUrl, publicSuffix: suffix.startsWith('.') ? suffix : '.' + suffix }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The origin this host announces for its second meeting point.
|
|
142
|
+
*
|
|
143
|
+
* Built from the identity and the configured suffix, never from the hostname a
|
|
144
|
+
* claim answered with: the id is the one this host has held since it minted its
|
|
145
|
+
* identity, while the suffix is the operator's statement of where that identity's
|
|
146
|
+
* second meeting point is. Whether it is announced at all is a different question —
|
|
147
|
+
* {@link RelaySecondaryHalf.origin} answers it, and only while a fresh lease is held.
|
|
148
|
+
* @param identity - the one relay identity both meetings share.
|
|
149
|
+
* @param publicSuffix - the configured suffix, leading dot included.
|
|
150
|
+
* @returns the `wss://` origin the greeting carries.
|
|
151
|
+
*/
|
|
152
|
+
export function relaySecondaryOriginOf(identity: RelayIdentity, publicSuffix: string): string {
|
|
153
|
+
return 'wss://' + identity.id + publicSuffix
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** What one second meeting point needs from the mount. */
|
|
157
|
+
export interface RelaySecondaryOptions {
|
|
158
|
+
/** The one relay identity both meeting points share. Never a second identity. */
|
|
159
|
+
readonly identity: RelayIdentity
|
|
160
|
+
/** The second control-plane base. */
|
|
161
|
+
readonly controlUrl: string
|
|
162
|
+
/** The public suffix the announced origin is built from. */
|
|
163
|
+
readonly publicSuffix: string
|
|
164
|
+
/**
|
|
165
|
+
* The grant the roster currently holds, read once per claim.
|
|
166
|
+
*
|
|
167
|
+
* Read rather than captured because a phone may hand one over at any moment, and
|
|
168
|
+
* the claim that lands after that has to carry it.
|
|
169
|
+
*/
|
|
170
|
+
grant: () => string | undefined
|
|
171
|
+
/** The ingress gate port a claim reports, or undefined before it settles. */
|
|
172
|
+
port: () => number | undefined
|
|
173
|
+
/** The plugin version a claim reports. */
|
|
174
|
+
pluginVersion?: () => string | undefined
|
|
175
|
+
/** Start (or restart) the connector for one accepted lease. */
|
|
176
|
+
startBridge?: (start: RelayBridgeStart) => void
|
|
177
|
+
/** Stop that connector. */
|
|
178
|
+
stopBridge?: () => void
|
|
179
|
+
/** One claim attempt (defaults to the real control plane). */
|
|
180
|
+
claim?: (request: RelayClaimRequest) => Promise<RelayClaimOutcome>
|
|
181
|
+
/** Release one lease (defaults to the real control plane). */
|
|
182
|
+
release?: (identity: RelayIdentity) => Promise<void>
|
|
183
|
+
/** Observe the lease state (logged by the mount, driven by the suites). */
|
|
184
|
+
onState?: (state: RelayPairState) => void
|
|
185
|
+
baseDelayMs?: number
|
|
186
|
+
maxDelayMs?: number
|
|
187
|
+
/** Schedule one retry; defaults to an unref'd node timer. */
|
|
188
|
+
timerFn?: (fn: () => void, ms: number) => { unref?: () => void }
|
|
189
|
+
/** How often a held lease is refreshed (defaults to {@link SECONDARY_CLAIM_REFRESH_MS}). */
|
|
190
|
+
refreshMs?: number
|
|
191
|
+
/**
|
|
192
|
+
* Start the periodic refresh and return its canceller.
|
|
193
|
+
*
|
|
194
|
+
* Defaults to an unref'd `setInterval`: the loop must never be a reason for the
|
|
195
|
+
* process to stay alive, and it must be cancelled by `dispose` and by `release`.
|
|
196
|
+
*/
|
|
197
|
+
refreshTimer?: (tick: () => void, ms: number) => () => void
|
|
198
|
+
log?: (message: string) => void
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Own the second meeting point's lease: claim it once per port and grant, follow
|
|
203
|
+
* the grant the phone hands over, and answer the origin `hello` announces.
|
|
204
|
+
*
|
|
205
|
+
* Built on {@link RelayConnectorPair} on purpose — the claim/retry/release
|
|
206
|
+
* lifecycle is the same one the market edge runs — but with its own injected claim
|
|
207
|
+
* (which adds the grant) and its own connector and release, so the two halves share
|
|
208
|
+
* the identity and nothing else.
|
|
209
|
+
*/
|
|
210
|
+
export class RelaySecondaryHalf {
|
|
211
|
+
readonly #options: RelaySecondaryOptions
|
|
212
|
+
readonly #pair: RelayConnectorPair
|
|
213
|
+
/** Whether this instance currently holds a lease at the second meeting point. */
|
|
214
|
+
#held = false
|
|
215
|
+
/** The `port|grant` key of the last claim this half started. */
|
|
216
|
+
#claimedFor: string | undefined
|
|
217
|
+
/** The canceller of the running six-hour refresh, while there is one. */
|
|
218
|
+
#stopRefresh: (() => void) | undefined
|
|
219
|
+
/** The endpoint the running connector dials; undefined while no connector runs. */
|
|
220
|
+
#bridgeEndpoint: string | undefined
|
|
221
|
+
#disposed = false
|
|
222
|
+
|
|
223
|
+
constructor(options: RelaySecondaryOptions) {
|
|
224
|
+
this.#options = options
|
|
225
|
+
const claim = options.claim ?? (async (request: RelayClaimRequest) => await claimRelayLease(
|
|
226
|
+
request,
|
|
227
|
+
{ url: relayControlEndpointOf('claim', options.controlUrl) },
|
|
228
|
+
))
|
|
229
|
+
this.#pair = new RelayConnectorPair(options.identity, {
|
|
230
|
+
// 名册里那条授权是这一半自己的事实,不是某个申领实现的细节,所以它包在注入的
|
|
231
|
+
// 申领外面:不论测试还是挂载用哪一个,请求都带上授权,没有就整条键都不发
|
|
232
|
+
// (见 relayClaimBody)。
|
|
233
|
+
claim: async request => {
|
|
234
|
+
const grant = options.grant()
|
|
235
|
+
return await claim({ ...request, ...(grant === undefined ? {} : { grant }) })
|
|
236
|
+
},
|
|
237
|
+
release: options.release ?? (async identity => {
|
|
238
|
+
await releaseRelayLease(identity, { url: relayControlEndpointOf('release', options.controlUrl) })
|
|
239
|
+
}),
|
|
240
|
+
// A refresh claims a fresh lease, and the connector is already dialling the same
|
|
241
|
+
// meeting point with the same identity: restarting it would terminate every
|
|
242
|
+
// stream it carries once per interval. It is restarted only when the endpoint
|
|
243
|
+
// actually moves, or when it was stopped and something has to bring it back.
|
|
244
|
+
...(options.startBridge === undefined ? {} : {
|
|
245
|
+
startBridge: (start: RelayBridgeStart) => {
|
|
246
|
+
const endpoint = start.claim.bridge?.endpoint
|
|
247
|
+
if (endpoint !== undefined && endpoint === this.#bridgeEndpoint) return
|
|
248
|
+
this.#bridgeEndpoint = endpoint
|
|
249
|
+
options.startBridge?.(start)
|
|
250
|
+
},
|
|
251
|
+
}),
|
|
252
|
+
...(options.stopBridge === undefined ? {} : {
|
|
253
|
+
stopBridge: () => {
|
|
254
|
+
this.#bridgeEndpoint = undefined
|
|
255
|
+
options.stopBridge?.()
|
|
256
|
+
},
|
|
257
|
+
}),
|
|
258
|
+
...(options.baseDelayMs === undefined ? {} : { baseDelayMs: options.baseDelayMs }),
|
|
259
|
+
...(options.maxDelayMs === undefined ? {} : { maxDelayMs: options.maxDelayMs }),
|
|
260
|
+
...(options.timerFn === undefined ? {} : { timerFn: options.timerFn }),
|
|
261
|
+
onState: state => { this.#observe(state) },
|
|
262
|
+
})
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** The lease half's current state (the market edge's own vocabulary). */
|
|
266
|
+
get state(): RelayPairState {
|
|
267
|
+
return this.#pair.state
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Claim the second meeting point once for the current port and grant.
|
|
272
|
+
*
|
|
273
|
+
* One claim per `port|grant` pair: a settings sync re-plans with the same key and
|
|
274
|
+
* must not turn into a claim per plan, while a settled port or a grant the phone
|
|
275
|
+
* just handed over is a genuinely new fact and claims again.
|
|
276
|
+
* @returns whether a claim was started.
|
|
277
|
+
*/
|
|
278
|
+
claim(): boolean {
|
|
279
|
+
if (this.#disposed) return false
|
|
280
|
+
const port = this.#options.port()
|
|
281
|
+
if (port === undefined) return false
|
|
282
|
+
const key = this.#keyOf(port)
|
|
283
|
+
if (this.#claimedFor === key) return false
|
|
284
|
+
this.#claimedFor = key
|
|
285
|
+
this.#logFailure(this.#start(port))
|
|
286
|
+
return true
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* A grant just landed in the roster: claim again right away.
|
|
291
|
+
*
|
|
292
|
+
* Unconditional on purpose — a phone that resends the grant it already handed over
|
|
293
|
+
* is asking this host to try again, and the pending wait (which may be the
|
|
294
|
+
* six-hour one a downgrade armed) is cleared by the claim itself.
|
|
295
|
+
* @returns when this attempt settled, so a suite can drive it deterministically.
|
|
296
|
+
*/
|
|
297
|
+
async grantReceived(): Promise<void> {
|
|
298
|
+
if (this.#disposed) return
|
|
299
|
+
const port = this.#options.port()
|
|
300
|
+
if (port === undefined) return
|
|
301
|
+
this.#claimedFor = this.#keyOf(port)
|
|
302
|
+
await this.#start(port)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* The second connector could not attach, so the lease it presents is claimed again.
|
|
307
|
+
*
|
|
308
|
+
* This is the stale-lease repair. The relay refuses a connector whose lease nobody
|
|
309
|
+
* has claimed inside the 24-hour window (`403 lease-stale`), which the six-hour
|
|
310
|
+
* refresh is meant to prevent — a suspended process, a long offline stretch or a
|
|
311
|
+
* clock that jumped can still produce one, and the repair is exactly one claim with
|
|
312
|
+
* the identity the connector was already presenting.
|
|
313
|
+
*
|
|
314
|
+
* Only a *refusal* counts: a dial timeout or a dropped socket is the connector's own
|
|
315
|
+
* backoff to sort out, and asking the control plane about it every 30 seconds would
|
|
316
|
+
* turn a network blip into a claim storm. Only a held lease counts too — once a
|
|
317
|
+
* refusal has told this half it holds nothing, its own wait (six hours, or none at
|
|
318
|
+
* all for a terminal answer) decides when to try again.
|
|
319
|
+
* @param error - the failure the bridge runner reported for its connector.
|
|
320
|
+
*/
|
|
321
|
+
connectorFailed(error: string): void {
|
|
322
|
+
if (this.#disposed || !this.#held) return
|
|
323
|
+
if (!ATTACH_REFUSED_RE.test(error)) return
|
|
324
|
+
const port = this.#options.port()
|
|
325
|
+
if (port === undefined) return
|
|
326
|
+
// This claim replaces whatever the refresh had pending: it is the same act.
|
|
327
|
+
this.#claimedFor = this.#keyOf(port)
|
|
328
|
+
this.#logFailure(this.#start(port))
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* The origin this host may announce right now, or undefined.
|
|
333
|
+
*
|
|
334
|
+
* Announcement follows the lease, not the configuration: an advertised meeting
|
|
335
|
+
* point whose origin nobody serves is worse than no advertisement at all.
|
|
336
|
+
* @returns `wss://<id><suffix>` while a lease is held.
|
|
337
|
+
*/
|
|
338
|
+
origin(): string | undefined {
|
|
339
|
+
return this.#held ? relaySecondaryOriginOf(this.#options.identity, this.#options.publicSuffix) : undefined
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Release the second lease and stop its connector.
|
|
344
|
+
*
|
|
345
|
+
* This never touches the first half: it releases against the second control plane
|
|
346
|
+
* only and stops the connector this object was handed.
|
|
347
|
+
*/
|
|
348
|
+
async release(): Promise<void> {
|
|
349
|
+
this.#held = false
|
|
350
|
+
this.#stopRefreshNow()
|
|
351
|
+
await this.#pair.release()
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Stop retrying and drop the connector (plugin teardown, or the relay turned off). */
|
|
355
|
+
dispose(): void {
|
|
356
|
+
this.#disposed = true
|
|
357
|
+
this.#held = false
|
|
358
|
+
this.#stopRefreshNow()
|
|
359
|
+
this.#pair.dispose()
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Fire one claim attempt without letting its failure escape.
|
|
364
|
+
*
|
|
365
|
+
* A claim is a network round trip, so a failure is one line in the log and never an
|
|
366
|
+
* unhandled rejection — the same exit the market edge's claimer takes.
|
|
367
|
+
* @param attempt - the claim being fired.
|
|
368
|
+
*/
|
|
369
|
+
#logFailure(attempt: Promise<void>): void {
|
|
370
|
+
void attempt.catch((error: unknown) => {
|
|
371
|
+
this.#options.log?.('the second meeting point claim did not land: '
|
|
372
|
+
+ (error instanceof Error ? error.message : String(error)))
|
|
373
|
+
})
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* The key one claim is deduplicated on: the settled port plus the grant in force.
|
|
378
|
+
* @param port - the ingress gate port a claim reports.
|
|
379
|
+
* @returns the key.
|
|
380
|
+
*/
|
|
381
|
+
#keyOf(port: number): string {
|
|
382
|
+
return String(port) + '|' + (this.#options.grant() ?? '')
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** One claim attempt for one settled port. */
|
|
386
|
+
async #start(port: number): Promise<void> {
|
|
387
|
+
const version = this.#options.pluginVersion?.()
|
|
388
|
+
await this.#pair.start({ port, ...(version === undefined ? {} : { pluginVersion: version }) })
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Follow the lease lifecycle: this is the one place that decides what `hello`
|
|
393
|
+
* announces and what the relay is told when a lease ends.
|
|
394
|
+
* @param state - the state the pair just moved to.
|
|
395
|
+
*/
|
|
396
|
+
#observe(state: RelayPairState): void {
|
|
397
|
+
if (state.state === 'claimed') {
|
|
398
|
+
this.#held = true
|
|
399
|
+
this.#armRefresh()
|
|
400
|
+
} else if (state.state === 'idle') {
|
|
401
|
+
this.#held = false
|
|
402
|
+
this.#stopRefreshNow()
|
|
403
|
+
} else if (state.state === 'failed' && SECOND_LEASE_REFUSED.has(state.error)) {
|
|
404
|
+
this.#held = false
|
|
405
|
+
this.#stopRefreshNow()
|
|
406
|
+
if (SECOND_LEASE_RELEASED.has(state.error)) {
|
|
407
|
+
// 释放是无条件的:一个刚刚重新判定过这台宿主的会合点可能还握着上一次的租约
|
|
408
|
+
// 行,而这个宿主已经不再公告那个地址了;释放是幂等的,失败也只影响这一行。
|
|
409
|
+
void this.#releaseSecondLease()
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
try {
|
|
413
|
+
this.#options.onState?.(state)
|
|
414
|
+
} catch {
|
|
415
|
+
// A throwing observer must not break the lease lifecycle.
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Start the six-hour refresh, once.
|
|
421
|
+
*
|
|
422
|
+
* It runs exactly while this half holds a lease: the relay's own window is 24 hours,
|
|
423
|
+
* the design's refresh interval is six, and a half that was told it holds nothing
|
|
424
|
+
* leaves the retry to the decision that refusal produced.
|
|
425
|
+
*/
|
|
426
|
+
#armRefresh(): void {
|
|
427
|
+
if (this.#stopRefresh !== undefined || this.#disposed) return
|
|
428
|
+
const ms = this.#options.refreshMs ?? SECONDARY_CLAIM_REFRESH_MS
|
|
429
|
+
const start = this.#options.refreshTimer ?? ((tick: () => void, every: number) => {
|
|
430
|
+
const timer = setInterval(tick, every)
|
|
431
|
+
// The loop must never be a reason for the process to stay alive.
|
|
432
|
+
timer.unref?.()
|
|
433
|
+
return () => { clearInterval(timer) }
|
|
434
|
+
})
|
|
435
|
+
this.#stopRefresh = start(() => { this.#logFailure(this.#refresh()) }, ms)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Cancel the refresh, if one is running. */
|
|
439
|
+
#stopRefreshNow(): void {
|
|
440
|
+
const stop = this.#stopRefresh
|
|
441
|
+
if (stop === undefined) return
|
|
442
|
+
this.#stopRefresh = undefined
|
|
443
|
+
try {
|
|
444
|
+
stop()
|
|
445
|
+
} catch (error) {
|
|
446
|
+
this.#options.log?.('the second meeting point refresh could not be cancelled: '
|
|
447
|
+
+ (error instanceof Error ? error.message : String(error)))
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** One periodic refresh: claim the lease the relay is about to consider stale. */
|
|
452
|
+
async #refresh(): Promise<void> {
|
|
453
|
+
if (this.#disposed || !this.#held) return
|
|
454
|
+
const port = this.#options.port()
|
|
455
|
+
if (port === undefined) return
|
|
456
|
+
this.#claimedFor = this.#keyOf(port)
|
|
457
|
+
await this.#start(port)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Release the second lease, best effort; a failure only leaves a row for the GC. */
|
|
461
|
+
async #releaseSecondLease(): Promise<void> {
|
|
462
|
+
try {
|
|
463
|
+
await this.#pair.release()
|
|
464
|
+
} catch (error) {
|
|
465
|
+
this.#options.log?.('the second meeting point lease could not be released: '
|
|
466
|
+
+ (error instanceof Error ? error.message : String(error)))
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Build the second meeting point half.
|
|
473
|
+
* @param options - the identity, the meeting point and the mount's seams.
|
|
474
|
+
* @returns the half, ready to claim.
|
|
475
|
+
*/
|
|
476
|
+
export function createRelaySecondaryHalf(options: RelaySecondaryOptions): RelaySecondaryHalf {
|
|
477
|
+
return new RelaySecondaryHalf(options)
|
|
478
|
+
}
|
package/src/host/relay.ts
CHANGED
|
@@ -35,7 +35,7 @@ import type { PushAddress, PushNotification, PushRoute, PushSendResult, PushSend
|
|
|
35
35
|
* The account service the App already signs into: one deployment, one hostname, so
|
|
36
36
|
* an operator with no relay of their own configures nothing at all.
|
|
37
37
|
*/
|
|
38
|
-
export const RELAY_DEFAULT_URL = 'https://account.
|
|
38
|
+
export const RELAY_DEFAULT_URL = 'https://account.chatwithai.icu'
|
|
39
39
|
/** The environment variable that moves the relay to another deployment. */
|
|
40
40
|
export const RELAY_ENV = { url: 'DSH_REMOTE_BRIDGE_RELAY_URL' } as const
|
|
41
41
|
/** The one path a delivery is posted to. */
|
package/src/host/routes.ts
CHANGED
|
@@ -28,6 +28,11 @@ export interface PairTokenRouteDeps {
|
|
|
28
28
|
readonly lan?: () => { address: string; port: number } | undefined
|
|
29
29
|
/** Origin discovery seam; defaults to {@link discoverPairOrigin} over the two seams above. */
|
|
30
30
|
readonly pairOrigin?: () => PairOriginFacts | undefined
|
|
31
|
+
/**
|
|
32
|
+
* 桌面端打开配对面板(或本机请求一次性令牌)时的钩子:尚未配对任何设备且未开隧道的
|
|
33
|
+
* 宿主在此时按需触发一次租约申领,避免无人使用远程功能时后台空转。
|
|
34
|
+
*/
|
|
35
|
+
readonly onPairTokenIssued?: () => void
|
|
31
36
|
}
|
|
32
37
|
|
|
33
38
|
/** Write one JSON response. The family's shared reader/writer is not copied into this package. */
|
|
@@ -86,6 +91,11 @@ export function makePairTokenHandler(deps: PairTokenRouteDeps): WebRoute['handle
|
|
|
86
91
|
res.end()
|
|
87
92
|
return
|
|
88
93
|
}
|
|
94
|
+
try {
|
|
95
|
+
deps.onPairTokenIssued?.()
|
|
96
|
+
} catch {
|
|
97
|
+
// 触发后台租约申领失败绝不能影响本机取配对码。
|
|
98
|
+
}
|
|
89
99
|
const ticket = deps.pairing.issueToken()
|
|
90
100
|
// The link a client ON THIS MACHINE can open directly. The token rides the
|
|
91
101
|
// query because a WebSocket handshake started from a share sheet cannot set
|