@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,209 @@
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
+ import { type RelayClaimOutcome, type RelayClaimRequest } from './relay-control.ts';
32
+ import { type RelayBridgeStart, type RelayPairState } from './relay-connector.ts';
33
+ import type { RelayIdentity } from './relay-registry.ts';
34
+ /**
35
+ * How often a held second lease is refreshed: six hours.
36
+ *
37
+ * The relay stops admitting a connector when the lease behind it has not been
38
+ * claimed within 24 hours, so the refresh has to run well inside that window, and
39
+ * six hours is the interval the design itself names (a downgrade is then noticed at
40
+ * the next refresh rather than at the next restart). The market edge has no such
41
+ * loop on purpose: its lease is refreshed by the plugin's own lifecycle events, and
42
+ * the default host must keep behaving exactly as it did.
43
+ */
44
+ export declare const SECONDARY_CLAIM_REFRESH_MS: number;
45
+ /**
46
+ * Where the second connector records its state
47
+ * (`$DSH_HOME/remote-web-ui-relay-bridge-secondary.json`).
48
+ *
49
+ * Its own file, never the first half's: two connectors that wrote one record would
50
+ * each overwrite the other's state, and the record exists precisely to say which
51
+ * meeting point served which lease.
52
+ * @param home - the DSH home (a test seam).
53
+ * @returns the absolute record path.
54
+ */
55
+ export declare function relaySecondaryBridgeStateFile(home?: string): string;
56
+ /** One configured second meeting point. */
57
+ export interface RelaySecondaryMeetingPoint {
58
+ /** The second control-plane base: its `claim` and `release` both hang off it. */
59
+ readonly controlUrl: string;
60
+ /** The public suffix the announced origin is built from, leading dot included. */
61
+ readonly publicSuffix: string;
62
+ }
63
+ /**
64
+ * The second meeting point one configuration names, or undefined.
65
+ *
66
+ * Both halves are required and neither has a default: an origin cannot be built
67
+ * from a control-plane base alone, and a control plane cannot be reached from a
68
+ * suffix alone. A profile that names only one of them therefore has no second
69
+ * meeting point at all rather than half of one, which keeps every consumer of this
70
+ * answer able to treat "undefined" as "this host has one meeting point".
71
+ * @param config - the resolved bridge configuration (read structurally).
72
+ * @returns the meeting point, or undefined when this host has none.
73
+ */
74
+ export declare function relaySecondaryOf(config: {
75
+ readonly relaySecondaryControlUrl?: string;
76
+ readonly relaySecondaryPublicSuffix?: string;
77
+ }): RelaySecondaryMeetingPoint | undefined;
78
+ /**
79
+ * The origin this host announces for its second meeting point.
80
+ *
81
+ * Built from the identity and the configured suffix, never from the hostname a
82
+ * claim answered with: the id is the one this host has held since it minted its
83
+ * identity, while the suffix is the operator's statement of where that identity's
84
+ * second meeting point is. Whether it is announced at all is a different question —
85
+ * {@link RelaySecondaryHalf.origin} answers it, and only while a fresh lease is held.
86
+ * @param identity - the one relay identity both meetings share.
87
+ * @param publicSuffix - the configured suffix, leading dot included.
88
+ * @returns the `wss://` origin the greeting carries.
89
+ */
90
+ export declare function relaySecondaryOriginOf(identity: RelayIdentity, publicSuffix: string): string;
91
+ /** What one second meeting point needs from the mount. */
92
+ export interface RelaySecondaryOptions {
93
+ /** The one relay identity both meeting points share. Never a second identity. */
94
+ readonly identity: RelayIdentity;
95
+ /** The second control-plane base. */
96
+ readonly controlUrl: string;
97
+ /** The public suffix the announced origin is built from. */
98
+ readonly publicSuffix: string;
99
+ /**
100
+ * The grant the roster currently holds, read once per claim.
101
+ *
102
+ * Read rather than captured because a phone may hand one over at any moment, and
103
+ * the claim that lands after that has to carry it.
104
+ */
105
+ grant: () => string | undefined;
106
+ /** The ingress gate port a claim reports, or undefined before it settles. */
107
+ port: () => number | undefined;
108
+ /** The plugin version a claim reports. */
109
+ pluginVersion?: () => string | undefined;
110
+ /** Start (or restart) the connector for one accepted lease. */
111
+ startBridge?: (start: RelayBridgeStart) => void;
112
+ /** Stop that connector. */
113
+ stopBridge?: () => void;
114
+ /** One claim attempt (defaults to the real control plane). */
115
+ claim?: (request: RelayClaimRequest) => Promise<RelayClaimOutcome>;
116
+ /** Release one lease (defaults to the real control plane). */
117
+ release?: (identity: RelayIdentity) => Promise<void>;
118
+ /** Observe the lease state (logged by the mount, driven by the suites). */
119
+ onState?: (state: RelayPairState) => void;
120
+ baseDelayMs?: number;
121
+ maxDelayMs?: number;
122
+ /** Schedule one retry; defaults to an unref'd node timer. */
123
+ timerFn?: (fn: () => void, ms: number) => {
124
+ unref?: () => void;
125
+ };
126
+ /** How often a held lease is refreshed (defaults to {@link SECONDARY_CLAIM_REFRESH_MS}). */
127
+ refreshMs?: number;
128
+ /**
129
+ * Start the periodic refresh and return its canceller.
130
+ *
131
+ * Defaults to an unref'd `setInterval`: the loop must never be a reason for the
132
+ * process to stay alive, and it must be cancelled by `dispose` and by `release`.
133
+ */
134
+ refreshTimer?: (tick: () => void, ms: number) => () => void;
135
+ log?: (message: string) => void;
136
+ }
137
+ /**
138
+ * Own the second meeting point's lease: claim it once per port and grant, follow
139
+ * the grant the phone hands over, and answer the origin `hello` announces.
140
+ *
141
+ * Built on {@link RelayConnectorPair} on purpose — the claim/retry/release
142
+ * lifecycle is the same one the market edge runs — but with its own injected claim
143
+ * (which adds the grant) and its own connector and release, so the two halves share
144
+ * the identity and nothing else.
145
+ */
146
+ export declare class RelaySecondaryHalf {
147
+ #private;
148
+ constructor(options: RelaySecondaryOptions);
149
+ /** The lease half's current state (the market edge's own vocabulary). */
150
+ get state(): RelayPairState;
151
+ /**
152
+ * Claim the second meeting point once for the current port and grant.
153
+ *
154
+ * One claim per `port|grant` pair: a settings sync re-plans with the same key and
155
+ * must not turn into a claim per plan, while a settled port or a grant the phone
156
+ * just handed over is a genuinely new fact and claims again.
157
+ * @returns whether a claim was started.
158
+ */
159
+ claim(): boolean;
160
+ /**
161
+ * A grant just landed in the roster: claim again right away.
162
+ *
163
+ * Unconditional on purpose — a phone that resends the grant it already handed over
164
+ * is asking this host to try again, and the pending wait (which may be the
165
+ * six-hour one a downgrade armed) is cleared by the claim itself.
166
+ * @returns when this attempt settled, so a suite can drive it deterministically.
167
+ */
168
+ grantReceived(): Promise<void>;
169
+ /**
170
+ * The second connector could not attach, so the lease it presents is claimed again.
171
+ *
172
+ * This is the stale-lease repair. The relay refuses a connector whose lease nobody
173
+ * has claimed inside the 24-hour window (`403 lease-stale`), which the six-hour
174
+ * refresh is meant to prevent — a suspended process, a long offline stretch or a
175
+ * clock that jumped can still produce one, and the repair is exactly one claim with
176
+ * the identity the connector was already presenting.
177
+ *
178
+ * Only a *refusal* counts: a dial timeout or a dropped socket is the connector's own
179
+ * backoff to sort out, and asking the control plane about it every 30 seconds would
180
+ * turn a network blip into a claim storm. Only a held lease counts too — once a
181
+ * refusal has told this half it holds nothing, its own wait (six hours, or none at
182
+ * all for a terminal answer) decides when to try again.
183
+ * @param error - the failure the bridge runner reported for its connector.
184
+ */
185
+ connectorFailed(error: string): void;
186
+ /**
187
+ * The origin this host may announce right now, or undefined.
188
+ *
189
+ * Announcement follows the lease, not the configuration: an advertised meeting
190
+ * point whose origin nobody serves is worse than no advertisement at all.
191
+ * @returns `wss://<id><suffix>` while a lease is held.
192
+ */
193
+ origin(): string | undefined;
194
+ /**
195
+ * Release the second lease and stop its connector.
196
+ *
197
+ * This never touches the first half: it releases against the second control plane
198
+ * only and stops the connector this object was handed.
199
+ */
200
+ release(): Promise<void>;
201
+ /** Stop retrying and drop the connector (plugin teardown, or the relay turned off). */
202
+ dispose(): void;
203
+ }
204
+ /**
205
+ * Build the second meeting point half.
206
+ * @param options - the identity, the meeting point and the mount's seams.
207
+ * @returns the half, ready to claim.
208
+ */
209
+ export declare function createRelaySecondaryHalf(options: RelaySecondaryOptions): RelaySecondaryHalf;
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The hosted relay this bridge hands a notification to when it holds no Apple key.
3
+ *
4
+ * §28's channel needs an Apple signing key, and a distributed App cannot get one
5
+ * onto every user's machine: the key would have to be shipped with the App's
6
+ * operator, which is the one thing a store release may not do. So the same event
7
+ * can be delivered two ways, and this file is the second one — one HTTPS POST to
8
+ * a service that signs with a key no deployment holds.
9
+ *
10
+ * Four rules, each of them borrowed from the direct path beside it:
11
+ *
12
+ * - the bridge sends the EVENT, not the state: `{event, sessionId, title, workspace}`
13
+ * for a notification and `{event: 'live-activity', sessionId, activityId,
14
+ * activityEvent, contentState, dismiss?}` for a card. It no longer decides the APNs
15
+ * headers, the bundle, the environment or the alert bodies — the service does,
16
+ * from the registration the App made directly with it;
17
+ * - a failure is a return value, never a rejection and never a retry: both callers
18
+ * sit on frame paths that must not learn about the network at all (§28.5);
19
+ * - the relay token is the phone's credential, scoped to this pairing's
20
+ * fingerprint. It is read off the roster row and put in one header; it is never
21
+ * logged, echoed in a frame, or written anywhere but that row;
22
+ * - the route is exclusive with the local key rather than a fallback chain. A
23
+ * machine that holds a key keeps signing for itself, so a developer's delivery
24
+ * never travels through the service and a hosted deployment never silently
25
+ * switches routes halfway through a session.
26
+ * @module dsh-remote-bridge/host/relay
27
+ */
28
+ import type { LiveActivityAddress, LiveActivityNotification, LiveActivitySender } from '../core/liveactivity.ts';
29
+ import type { PushAddress, PushNotification, PushRoute, PushSendResult, PushSender } from '../core/push.ts';
30
+ /**
31
+ * Where the hosted relay lives by default.
32
+ *
33
+ * The account service the App already signs into: one deployment, one hostname, so
34
+ * an operator with no relay of their own configures nothing at all.
35
+ */
36
+ export declare const RELAY_DEFAULT_URL = "https://account.chatwithai.icu";
37
+ /** The environment variable that moves the relay to another deployment. */
38
+ export declare const RELAY_ENV: {
39
+ readonly url: "DSH_REMOTE_BRIDGE_RELAY_URL";
40
+ };
41
+ /** The one path a delivery is posted to. */
42
+ export declare const RELAY_PATH = "/v1/push/relay";
43
+ /** How long one delivery may take before it is abandoned. */
44
+ export declare const RELAY_TIMEOUT_MS = 10000;
45
+ /**
46
+ * Read the relay's base address.
47
+ * @param env - the environment to read; defaults to this process's.
48
+ * @returns the trimmed base with no trailing slash, or {@link RELAY_DEFAULT_URL}.
49
+ */
50
+ export declare function relayUrlFromEnv(env?: NodeJS.ProcessEnv): string;
51
+ /** The notification body the relay accepts (contract v1, frozen). */
52
+ export interface RelayNotificationRequest {
53
+ readonly event: PushNotification['st'];
54
+ readonly sessionId: string;
55
+ /** The session's own name; the service substitutes its fixed line when absent. */
56
+ readonly title?: string;
57
+ /** The workspace's short name, which is a directory's basename and not a path. */
58
+ readonly workspace?: string;
59
+ }
60
+ /** The Live Activity body the relay accepts (contract v1, frozen). */
61
+ export interface RelayLiveActivityRequest {
62
+ readonly event: 'live-activity';
63
+ readonly sessionId: string;
64
+ readonly activityId: string;
65
+ readonly activityEvent: LiveActivityNotification['aps']['event'];
66
+ readonly contentState: LiveActivityNotification['aps']['content-state'];
67
+ /**
68
+ * Whether the card must go the moment this delivery lands, rather than at its
69
+ * `stale-date`. Only ever `true`: the key is absent when the card stays, because
70
+ * a `false` would be a second way to say the same thing and an older service
71
+ * would have to learn it. The dismissal date itself is the service's to write —
72
+ * it is the one that knows when the delivery landed (§29.3).
73
+ */
74
+ readonly dismiss?: boolean;
75
+ }
76
+ /**
77
+ * The notification one delivery becomes.
78
+ *
79
+ * Pure, and exported so the body can be asserted without a network. What crosses is
80
+ * exactly what §28.4 already allows on a lock screen — the event, the session id,
81
+ * the session's name and the workspace's short name — and nothing else: no message,
82
+ * no tool output, no path, no question body.
83
+ * @param notification - the payload the notifier built for the direct path.
84
+ * @returns the body to POST.
85
+ */
86
+ export declare function buildRelayNotification(notification: PushNotification): RelayNotificationRequest;
87
+ /**
88
+ * The Live Activity body one delivery becomes.
89
+ *
90
+ * The card's content state crosses verbatim: it is the App's own
91
+ * `SessionActivityState` (§29.3), already built by `core/liveactivity.ts` with its
92
+ * frozen key set and Apple-reference timestamps, and rebuilding it here would be a
93
+ * second answer to the same encoding question.
94
+ * @param target - the card being pushed to.
95
+ * @param notification - the payload the notifier built for the direct path.
96
+ * @returns the body to POST, or undefined when the card names no session.
97
+ */
98
+ export declare function buildRelayLiveActivity(target: LiveActivityAddress, notification: LiveActivityNotification): RelayLiveActivityRequest | undefined;
99
+ /** The 200 body the relay answers with (contract v1, frozen). */
100
+ export interface RelayAnswer {
101
+ readonly ok?: boolean;
102
+ /** How many devices took the delivery. */
103
+ readonly delivered?: number;
104
+ /** How many registrations the relay judged dead and cleaned up. */
105
+ readonly dead?: number;
106
+ }
107
+ /** The one request shape this file makes, with the answer narrowed to what it reads. */
108
+ export type RelayFetch = (url: string, init: {
109
+ readonly method: string;
110
+ readonly headers: Readonly<Record<string, string>>;
111
+ readonly body: string;
112
+ readonly signal: AbortSignal;
113
+ }) => Promise<{
114
+ readonly status: number;
115
+ text(): Promise<string>;
116
+ }>;
117
+ export interface RelaySenderOptions {
118
+ /** The relay's base address, from {@link relayUrlFromEnv}. */
119
+ readonly url: string;
120
+ /** The HTTP client; the global `fetch` by default, injectable so failures need no network. */
121
+ readonly fetch?: RelayFetch;
122
+ readonly timeoutMs?: number;
123
+ }
124
+ /**
125
+ * The relay half of the push channel.
126
+ *
127
+ * Every method resolves: a delivery that failed is a {@link PushSendResult} with
128
+ * `ok: false`, never a rejection, because both callers sit on frame paths that must
129
+ * not learn about the network at all. Nothing is retried — an alert that could not
130
+ * be delivered is one line in the log, and the next event is the next attempt.
131
+ */
132
+ export declare class RelaySender implements PushSender, LiveActivitySender {
133
+ #private;
134
+ constructor(options: RelaySenderOptions);
135
+ /** Deliver one notification, or report why it did not arrive. */
136
+ send(target: PushAddress, notification: PushNotification): Promise<PushSendResult>;
137
+ /** Deliver one Live Activity push, or report why it did not arrive. */
138
+ sendLiveActivity(target: LiveActivityAddress, notification: LiveActivityNotification): Promise<PushSendResult>;
139
+ }
140
+ /**
141
+ * Which road this bridge stands on, given the two credentials it could hold.
142
+ *
143
+ * A local key wins over a relay token, deliberately: the machine that can sign for
144
+ * itself must not route a developer's events through the hosted service, and the
145
+ * two routes never run side by side for one event.
146
+ * @param localKey - whether this machine holds a complete APNs credential.
147
+ * @param relayArmed - whether some paired row holds a relay token.
148
+ * @returns the route the channel is on.
149
+ */
150
+ export declare function pushRouteOf(localKey: boolean, relayArmed: boolean): PushRoute;
151
+ /** What the mount log needs to know to say where this bridge stands. */
152
+ export interface PushChannelDescription {
153
+ readonly route: PushRoute;
154
+ /** The key id of the local credential, when the route is `direct`. */
155
+ readonly keyId?: string;
156
+ /** The team that key belongs to, when the route is `direct`. */
157
+ readonly teamId?: string;
158
+ /** The relay's base address, when the route is `relay`. */
159
+ readonly relayUrl?: string;
160
+ }
161
+ /**
162
+ * The one line the mount log says about the push channel.
163
+ *
164
+ * Three routes, three lines, and the line names the credential each one reads: an
165
+ * operator reading a log has to be able to tell a bridge signing for itself from
166
+ * one asking a service to, without opening any file.
167
+ * @param description - the route and the parts of it worth naming.
168
+ * @returns the line to log.
169
+ */
170
+ export declare function pushChannelLine(description: PushChannelDescription): string;
@@ -14,9 +14,37 @@ import { type PairOriginFacts } from './pair-origin.ts';
14
14
  export interface PairTokenRouteDeps {
15
15
  readonly pairing: PairingService;
16
16
  readonly log: (message: string) => void;
17
- /** Origin discovery seam; defaults to {@link discoverPairOrigin}. */
17
+ /**
18
+ * 桥自己此刻的公网入口(relay 租约的 hostname 或隧道的 running URL),由接线方
19
+ * 注入:本模块不认识隧道与租约,只按顺序问地址。返回实时快照,不缓存。
20
+ */
21
+ readonly realtime?: () => string | undefined;
22
+ /** 无公网时的局域网兜底:本机地址与 webServer 端口。 */
23
+ readonly lan?: () => {
24
+ address: string;
25
+ port: number;
26
+ } | undefined;
27
+ /** Origin discovery seam; defaults to {@link discoverPairOrigin} over the two seams above. */
18
28
  readonly pairOrigin?: () => PairOriginFacts | undefined;
29
+ /**
30
+ * 桌面端打开配对面板(或本机请求一次性令牌)时的钩子:尚未配对任何设备且未开隧道的
31
+ * 宿主在此时按需触发一次租约申领,避免无人使用远程功能时后台空转。
32
+ */
33
+ readonly onPairTokenIssued?: () => void;
19
34
  }
35
+ /**
36
+ * The WebSocket URL a phone dials for one one-shot ticket.
37
+ *
38
+ * `origin` names where this host is reachable (`https://<id>.dsh-market.com`,
39
+ * `http://192.168.1.5:3080`), but the handshake this URL opens is a WebSocket
40
+ * one: the scheme follows the transport, so https becomes wss and http becomes
41
+ * ws. Keeping the origin's own scheme would hand the client an HTTP URL and ask
42
+ * it to dial a socket with it.
43
+ * @param origin - the discovered origin, with or without the scheme.
44
+ * @param token - the one-shot ticket to carry in the query.
45
+ * @returns the URL the pairing QR encodes.
46
+ */
47
+ export declare function pairingDialUrlOf(origin: string, token: string): string;
20
48
  /**
21
49
  * Build the handler for `GET /remote-bridge/pair/token`.
22
50
  * @param deps - the pairing service that mints the token, plus the Host log.
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Crash recovery for the tunnel's cloudflared child. A host that dies without
3
+ * tearing its tunnel down hands the child over to launchd/systemd, where it
4
+ * keeps its edge registration forever: the next host then runs a second
5
+ * connector beside an orphan nobody serves, and the old process holds a
6
+ * hostname no tunnel answers on any more.
7
+ *
8
+ * The manager records the spawned child under the DSH home right after the
9
+ * spawn (pid plus the exact command line ps/proc reports) and drops the record
10
+ * when that child is stopped, so a record only outlives the process that wrote
11
+ * it when that process crashed. The next start reaps exactly that pid, and
12
+ * only while it is still alive AND its command line still equals the recorded
13
+ * one: a recycled pid or a rewritten record can therefore never make the
14
+ * plugin signal a process it did not spawn. Nothing here matches by pattern,
15
+ * by process name, or by any pid this plugin did not record itself.
16
+ *
17
+ * A record also carries the pid of the host that spawned the child. Two live
18
+ * hosts can share one DSH home (two profiles, or a plugin reload inside one
19
+ * host), and each owns its own child; only a host that is gone leaves a child
20
+ * behind, so a record whose owner is still running is left untouched.
21
+ */
22
+ /**
23
+ * The spawned child as its tunnel handle exposes it (node's `ChildProcess`
24
+ * fits: `pid` plus the argv it was spawned with).
25
+ */
26
+ export interface TunnelChildProcess {
27
+ /** The child's pid. */
28
+ pid?: number;
29
+ /** The argv the child was spawned with, executable first. */
30
+ spawnargs?: readonly string[];
31
+ }
32
+ /** What the plugin records about one child it spawned. */
33
+ export interface TunnelChildRecord {
34
+ /** The child's pid. */
35
+ pid: number;
36
+ /**
37
+ * The child's full argv joined with single spaces — the same line `ps`
38
+ * prints. Anything else (a wrapper, a rewritten command) is a mismatch.
39
+ */
40
+ command: string;
41
+ /** The host process that spawned the child; a live owner keeps it. */
42
+ ownerPid: number;
43
+ /** ISO timestamp of the recording (diagnostics only). */
44
+ recordedAt: string;
45
+ }
46
+ /** How one recorded leftover was settled. */
47
+ export type TunnelOrphanVerdict =
48
+ /** There was no usable record. */
49
+ 'none'
50
+ /** The record did not identify a live child this plugin spawned: only the file was dropped. */
51
+ | 'stale'
52
+ /** The recorded child still belongs to a running host: it was left alone. */
53
+ | 'owned'
54
+ /** The recorded orphan was signalled away and the record dropped. */
55
+ | 'reaped';
56
+ /** Injectable seams of the reaper (defaults read the real process table). */
57
+ export interface TunnelOrphanSeams {
58
+ /** Whether a pid is still alive. */
59
+ alive?: (pid: number) => boolean;
60
+ /** Read a pid's exact command line, or undefined when it cannot be read. */
61
+ command?: (pid: number) => Promise<string | undefined>;
62
+ /** Signal one recorded pid (never a pattern). */
63
+ signal?: (pid: number, signal: NodeJS.Signals) => void;
64
+ /** Bounded wait between liveness polls. */
65
+ wait?: (ms: number) => Promise<void>;
66
+ /** How long the signalled child gets to honour SIGTERM before SIGKILL. */
67
+ graceMs?: number;
68
+ }
69
+ /** The crash-recovery face the tunnel manager drives. */
70
+ export interface TunnelChildGuard {
71
+ /** Reap the leftover child a crashed host recorded; resolves once settled. */
72
+ reap(): Promise<TunnelOrphanVerdict>;
73
+ /**
74
+ * Record a freshly spawned child so the next host start can reap it.
75
+ * @returns whether a record was written (a handle without its OS process, or
76
+ * an unwritable home, writes nothing and must not clear a sibling's record).
77
+ */
78
+ record(child: TunnelChildProcess | undefined): boolean;
79
+ /** Drop the record: the child is stopped, so nothing is left to reap. */
80
+ clear(): void;
81
+ }
82
+ /** How long an orphan gets to honour SIGTERM before it is killed. */
83
+ export declare const DEFAULT_ORPHAN_GRACE_MS = 3000;
84
+ /** The record file this plugin owns: `$DSH_HOME/remote-web-ui-tunnel-child.json`. */
85
+ export declare function tunnelChildRecordFile(home?: string): string;
86
+ /**
87
+ * Read one record, ignoring a file that cannot identify a child (`pid` and
88
+ * `command` absent or malformed): only a well-formed record may ever lead to a
89
+ * signal.
90
+ * @param file - the record file.
91
+ * @returns the record, or undefined when there is none to trust.
92
+ */
93
+ export declare function readTunnelChildRecord(file: string): TunnelChildRecord | undefined;
94
+ /**
95
+ * Write one record owner-only, creating the DSH home when it is missing.
96
+ * @param file - the record file.
97
+ * @param record - what to record about the spawned child.
98
+ */
99
+ export declare function recordTunnelChild(file: string, record: TunnelChildRecord): void;
100
+ /** Drop one record; an absent file is not an error. */
101
+ export declare function clearTunnelChildRecord(file: string): void;
102
+ /**
103
+ * Whether a pid is still in the process table. `EPERM` means the process
104
+ * exists but belongs to another user, which still counts as alive.
105
+ * @param pid - the pid to probe.
106
+ * @returns whether the pid exists.
107
+ */
108
+ export declare function processAlive(pid: number): boolean;
109
+ /**
110
+ * Read one pid's exact command line: `/proc/<pid>/cmdline` on Linux,
111
+ * `ps -ww -o command=` elsewhere. Arguments are joined with single spaces in
112
+ * both cases, which is exactly how a recorded argv is stored.
113
+ * @param pid - the pid to read.
114
+ * @returns the command line, or undefined when it cannot be read.
115
+ */
116
+ export declare function processCommandLine(pid: number): Promise<string | undefined>;
117
+ /**
118
+ * Turn one `/proc/<pid>/cmdline` read (argv, NUL-separated, usually with a
119
+ * trailing NUL) into the line `ps` prints, so both platforms compare against
120
+ * the same recorded shape.
121
+ * @param raw - the raw `/proc/<pid>/cmdline` text.
122
+ * @returns the joined command line, or undefined for an empty file.
123
+ */
124
+ export declare function parseProcCommandLine(raw: string): string | undefined;
125
+ /**
126
+ * Settle one recorded leftover: reap exactly the recorded child when it is
127
+ * still the process that record describes, and leave every other process
128
+ * strictly alone.
129
+ * @param file - the record file.
130
+ * @param seams - process-table and signal seams (defaults read the real table).
131
+ * @returns which way the record was settled.
132
+ */
133
+ export declare function reapRecordedTunnelChild(file: string, seams?: TunnelOrphanSeams): Promise<TunnelOrphanVerdict>;
134
+ /** Seams of the file-backed guard (the record file defaults to the DSH home). */
135
+ export interface TunnelChildGuardOptions extends TunnelOrphanSeams {
136
+ /** The record file; resolved per call so a changed DSH home is honoured. */
137
+ file?: string;
138
+ }
139
+ /**
140
+ * Build the file-backed crash-recovery guard the tunnel manager uses: the
141
+ * record lives at {@link tunnelChildRecordFile} unless a file is given.
142
+ * @param options - record file and process seams (all optional).
143
+ * @returns the guard.
144
+ */
145
+ export declare function createTunnelChildGuard(options?: TunnelChildGuardOptions): TunnelChildGuard;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Pure planner for the settings-sync tunnel branch: given the resolved
3
+ * settings slice, decide which tunnel mode runs and with what target. Kept
4
+ * free of cordis types so the precedence matrix is unit-testable without a
5
+ * host context.
6
+ */
7
+ /** Whether a configured public base is a parseable http(s) URL with a host. */
8
+ export declare function isHttpUrl(value: string): boolean;
9
+ /** How the settings sync should drive the tunnel for one resolved value. */
10
+ export type TunnelPlan = {
11
+ mode: 'off';
12
+ } | {
13
+ mode: 'quick';
14
+ targetUrl: string;
15
+ ignored: Array<'tunnelToken' | 'publicBaseUrl'>;
16
+ } | {
17
+ mode: 'named';
18
+ token: string;
19
+ publicUrl: string;
20
+ };
21
+ /**
22
+ * Decide the tunnel mode and target from one resolved settings value.
23
+ * Precedence: the quick tunnel wins when `autoTunnel` is on (anything else
24
+ * configured is reported as ignored); the named tunnel runs only with a
25
+ * token AND a valid public hostname (the token does not carry the hostname,
26
+ * so the plan would have no public URL to report without it); otherwise no
27
+ * tunnel and the manual public base applies.
28
+ *
29
+ * The quick target URL names the local webServer port, so a plan made before
30
+ * the listener binds cannot be quick: it comes back `off` and the caller —
31
+ * which can observe the port settle — re-plans. The planner itself never
32
+ * emits an `http://127.0.0.1:undefined` target.
33
+ * @param value - the resolved settings slice that drives the tunnel.
34
+ * @param port - the local webServer port the tunnel forwards to (undefined
35
+ * before the listener binds).
36
+ */
37
+ export declare function tunnelPlanOf(value: {
38
+ autoTunnel?: boolean;
39
+ tunnelToken?: string;
40
+ publicBaseUrl?: string;
41
+ }, port: number | undefined): TunnelPlan;