@linxin666/dsh-remote-bridge 0.4.12 → 0.4.13

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 (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -8
  3. package/README.zh.md +45 -8
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18031 -373
  7. package/lib/types/core/connection.d.ts +9 -0
  8. package/lib/types/core/devices.d.ts +27 -6
  9. package/lib/types/core/liveactivity.d.ts +7 -0
  10. package/lib/types/core/model-efforts.d.ts +83 -0
  11. package/lib/types/core/protocol.d.ts +2 -0
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/host/firewall.d.ts +74 -0
  14. package/lib/types/host/host-bind-capability.d.ts +90 -0
  15. package/lib/types/host/ingress-gate.d.ts +59 -0
  16. package/lib/types/host/ingress-sync.d.ts +429 -0
  17. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  18. package/lib/types/host/lan-bind.d.ts +106 -0
  19. package/lib/types/host/lan-forward.d.ts +112 -0
  20. package/lib/types/host/lan.d.ts +61 -0
  21. package/lib/types/host/pair-origin.d.ts +34 -19
  22. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  23. package/lib/types/host/relay-connector.d.ts +152 -0
  24. package/lib/types/host/relay-control.d.ts +124 -0
  25. package/lib/types/host/relay-registry.d.ts +114 -0
  26. package/lib/types/host/relay.d.ts +170 -0
  27. package/lib/types/host/routes.d.ts +24 -1
  28. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  29. package/lib/types/host/tunnel-plan.d.ts +41 -0
  30. package/lib/types/host/tunnel.d.ts +289 -0
  31. package/lib/types/index.d.ts +426 -1
  32. package/package.json +4 -2
  33. package/src/client/panel.module.css +16 -1
  34. package/src/core/connection.ts +206 -11
  35. package/src/core/devices.ts +31 -6
  36. package/src/core/hub.ts +17 -5
  37. package/src/core/liveactivity.ts +16 -2
  38. package/src/core/model-efforts.ts +223 -0
  39. package/src/core/protocol.ts +3 -0
  40. package/src/core/push.ts +70 -4
  41. package/src/host/firewall.ts +230 -0
  42. package/src/host/host-bind-capability.ts +249 -0
  43. package/src/host/ingress-gate.ts +203 -0
  44. package/src/host/ingress-sync.ts +1074 -0
  45. package/src/host/lan-bind-plan.ts +134 -0
  46. package/src/host/lan-bind.ts +250 -0
  47. package/src/host/lan-forward.ts +321 -0
  48. package/src/host/lan.ts +142 -0
  49. package/src/host/pair-origin.ts +44 -38
  50. package/src/host/relay-bridge-connector.ts +783 -0
  51. package/src/host/relay-connector.ts +317 -0
  52. package/src/host/relay-control.ts +224 -0
  53. package/src/host/relay-registry.ts +263 -0
  54. package/src/host/relay.ts +294 -0
  55. package/src/host/routes.ts +47 -3
  56. package/src/host/tunnel-orphan.ts +325 -0
  57. package/src/host/tunnel-plan.ts +58 -0
  58. package/src/host/tunnel.ts +688 -0
  59. package/src/index.ts +1280 -22
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The LAN edge the lan-bind toggle owns (issue #1917).
3
+ *
4
+ * The toggle used to pin the LAN address into the profile's webserver row. That
5
+ * row is the only place the harness takes its bind from, and rewriting it
6
+ * - replaced the official row's whole config (so the row's own
7
+ * `host: !!js ctx.webStartup.host ?? '127.0.0.1'` expression and the CLI
8
+ * `--host`/`--port` never reached it), and
9
+ * - the profile patch is watched by the Host's HMR config watcher, so the
10
+ * write recomposed the running process and rebound the live listener.
11
+ *
12
+ * This module keeps the host bound to loopback and gives LAN clients their own
13
+ * listener: a forwarder on the machine's LAN address, on the same port, that
14
+ * re-issues every request (HTTP and WebSocket upgrade alike) to
15
+ * `127.0.0.1:<port>`. Two consequences are load-bearing:
16
+ *
17
+ * 1. The upstream leg is loopback, so the socket alone would read as "the
18
+ * desktop". The forwarder therefore DROPS whatever Host the client sent and
19
+ * stamps the LAN authority it was reached at, plus `X-Forwarded-For`. Every
20
+ * fence that decides "is this the desktop" (`isLoopbackClient`, the pairing
21
+ * gate, the `/remote` gate) then keeps refusing the forwarded request, while
22
+ * the phone-facing fences still match the LAN authority the QR advertises.
23
+ * 2. A bind that cannot be taken (address gone after a network change, port
24
+ * taken) only loses the LAN edge: the loopback listener is never touched, so
25
+ * the host cannot be bricked and the failure is reported on the status
26
+ * frame.
27
+ *
28
+ * Nothing here writes a file: the forwarder is runtime state, so a network
29
+ * change needs no profile edit and no restart.
30
+ *
31
+ * @module dsh-remote-bridge/host/lan-forward
32
+ */
33
+ import { type IncomingMessage } from 'node:http';
34
+ /** The upstream the forwarder re-issues to: the process's own loopback listener. */
35
+ export declare const FORWARD_UPSTREAM_HOST = "127.0.0.1";
36
+ /** What the forwarder is doing right now, for the status frame and the logs. */
37
+ export interface LanForwardState {
38
+ /** Whether the LAN listener is bound. */
39
+ listening: boolean;
40
+ /** The LAN address it listens on (undefined when it never bound). */
41
+ address: string | undefined;
42
+ /** The port it listens on (the web server's own port). */
43
+ port: number | undefined;
44
+ /** The loopback port it re-issues to. */
45
+ upstreamPort: number | undefined;
46
+ /** Why the last bind attempt failed, when it did. */
47
+ error: string | undefined;
48
+ }
49
+ /** The idle state: nothing bound, nothing failed. */
50
+ export declare const IDLE_FORWARD_STATE: LanForwardState;
51
+ /**
52
+ * The `Host` authority a listener at `address:port` is reached at. IPv6
53
+ * literals are bracketed like any URL authority.
54
+ * @param address - the listen address (a literal).
55
+ * @param port - the listen port.
56
+ * @returns the authority text a request to that listener carries.
57
+ */
58
+ export declare function authorityOf(address: string, port: number): string;
59
+ /**
60
+ * The headers the loopback leg carries for one request: the client's own
61
+ * headers minus the hop-by-hop and forwarder-owned ones, plus the LAN authority
62
+ * the client actually reached and its address.
63
+ * @param request - the request as it arrived on the LAN listener.
64
+ * @param authority - the LAN authority the forwarder listens at.
65
+ * @param clientAddress - the client's socket address, when readable.
66
+ * @returns the headers for the loopback request.
67
+ */
68
+ export declare function forwardedHeaders(request: IncomingMessage, authority: string, clientAddress: string | undefined): Record<string, string>;
69
+ /**
70
+ * Rebuild a WebSocket handshake for the loopback leg. The client's own headers
71
+ * travel through verbatim (so `Sec-WebSocket-*` and any application protocol
72
+ * survive) except the ones the forwarder owns.
73
+ * @param request - the upgrade request as it arrived on the LAN listener.
74
+ * @param authority - the LAN authority the forwarder listens at.
75
+ * @param clientAddress - the client's socket address, when readable.
76
+ * @returns the handshake request head to write on the loopback leg.
77
+ */
78
+ export declare function forwardedHandshake(request: IncomingMessage, authority: string, clientAddress: string | undefined): string;
79
+ /** One listener, its live connections, and its last bind outcome. */
80
+ export declare class LanForwarder {
81
+ private server;
82
+ private config;
83
+ private state;
84
+ /** Every socket this forwarder opened on either leg. */
85
+ private readonly sockets;
86
+ /** Every in-flight loopback request, so a teardown cannot leave one running. */
87
+ private readonly upstreams;
88
+ /** What the forwarder is doing right now. */
89
+ snapshot(): LanForwardState;
90
+ /**
91
+ * Bind the LAN listener, or report why it could not be bound.
92
+ *
93
+ * Never throws: a bind failure is the ordinary outcome after a network change
94
+ * (the address is gone) or a port collision, and the loopback listener must
95
+ * keep serving regardless.
96
+ * @param address - the LAN address to listen on.
97
+ * @param port - the port to listen on (the web server's own port).
98
+ * @param upstreamPort - the loopback port to re-issue to; defaults to `port`.
99
+ * @returns the settled state.
100
+ */
101
+ start(address: string, port: number, upstreamPort?: number): Promise<LanForwardState>;
102
+ private bind;
103
+ /**
104
+ * Close the LAN listener and every connection it opened, then resolve once the
105
+ * port is released. Safe to call when nothing is bound.
106
+ */
107
+ stop(): Promise<void>;
108
+ private releaseSockets;
109
+ private trackUpstream;
110
+ private forwardHttp;
111
+ private forwardUpgrade;
112
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * LAN address derivation: every IPv4 interface literal this machine could
3
+ * advertise to a peer on the local network. Mirrors the dsh CLI's boot-time
4
+ * sampling shape (apps/cli/src/app-cli-entry.ts `resolveLanTrust`) — an
5
+ * external plugin cannot read the CLI's sampled snapshot, so the same
6
+ * non-internal IPv4 derivation is repeated here.
7
+ *
8
+ * The derivation is deliberately narrower than the CLI's: an advertised
9
+ * literal the peer can never reach costs that peer a whole connection attempt.
10
+ * A macOS host running a fake-IP proxy (Clash/Surge/Mihomo) samples its TUN
11
+ * gateway as `198.18.0.1`, which is a benchmarking-range address no LAN peer
12
+ * can route to; the old derivation advertised it like any other interface. The
13
+ * filter below drops the interface kinds and address ranges a peer cannot
14
+ * reach, and keeps everything else — RFC1918, ULA-side IPv4 and a routable
15
+ * public literal (a VPS whose NIC is its only reachable base must stay
16
+ * advertisable).
17
+ *
18
+ * Which trust fence, pairing link or settings surface consumes these literals
19
+ * is not this module's responsibility.
20
+ *
21
+ * @module dsh-remote-bridge/host/lan
22
+ */
23
+ import { networkInterfaces } from 'node:os';
24
+ /**
25
+ * Whether an interface name belongs to a tunnel, VPN adapter, or virtual
26
+ * machine/container bridge, so its address is not an authority a LAN peer
27
+ * can dial.
28
+ * @param name - the interface name from `os.networkInterfaces()`.
29
+ * @returns true when the interface must not be advertised.
30
+ */
31
+ export declare function isUnadvertisableInterface(name: string): boolean;
32
+ /**
33
+ * Whether an IPv4 literal can be advertised to a pairing peer.
34
+ * @param address - a dotted-quad IPv4 literal.
35
+ * @returns true when a peer could plausibly reach it.
36
+ */
37
+ export declare function isAdvertisableIPv4(address: string): boolean;
38
+ /** One sampled interface address. */
39
+ export interface LanCandidate {
40
+ /** The interface name the address was sampled from. */
41
+ iface: string;
42
+ /** The IPv4 literal. */
43
+ address: string;
44
+ }
45
+ /** The `networkInterfaces()` shape, injectable so the filter is testable. */
46
+ export type NetworkInterfaceMap = ReturnType<typeof networkInterfaces>;
47
+ /**
48
+ * Every IPv4 interface address this machine can advertise to a pairing peer:
49
+ * non-internal, on a non-tunnel and non-virtual interface, outside the ranges
50
+ * no peer can route to.
51
+ * @param interfaces - the sampled interface map (defaults to the live one).
52
+ * @returns the candidates in interface order (possibly empty).
53
+ */
54
+ export declare function lanIPv4Candidates(interfaces?: NetworkInterfaceMap): LanCandidate[];
55
+ /**
56
+ * Non-internal, reachable IPv4 interface addresses of this machine — the
57
+ * IP-literal authorities an all-interfaces bind is reachable by on the LAN.
58
+ * @param interfaces - the sampled interface map (defaults to the live one).
59
+ * @returns the addresses in interface order (possibly empty).
60
+ */
61
+ export declare function lanIPv4Addresses(interfaces?: NetworkInterfaceMap): string[];
@@ -3,42 +3,57 @@
3
3
  *
4
4
  * A pairing code is far better when it carries the address too: the phone then
5
5
  * needs one scan and no typing. This module is where that address comes from,
6
- * in the order the family already trusts:
6
+ * in the order this bridge can actually vouch for:
7
7
  *
8
- * 1. `DSH_REMOTE_PUBLIC_BASE_URL` — the same environment contract
8
+ * 1. **This bridge's own live public face**, handed in as a seam: a relay lease
9
+ * plus a landed Worker registration, or a tunnel that reports it is running.
10
+ * It is a fact about this process right now, so it answers first.
11
+ * 2. `DSH_REMOTE_PUBLIC_BASE_URL` — the same environment contract
9
12
  * `dsh-remote-web-ui` reads for its own public base.
10
- * 2. The relay registry row `$DSH_HOME/remote-web-ui-registry/<profile>.json`,
11
- * whose `id` is the stable `<id>.<relay>` subdomain that plugin registers
12
- * for this profile (see its `relay-registry.ts`). Reading that row is a
13
- * deliberate, documented data dependency: it is one small JSON file per
14
- * profile, it is written by the machine itself, and a missing or unreadable
15
- * row simply means "no origin known" rather than an error.
13
+ * 3. The LAN literal — this machine's own LAN address plus the bound port. A
14
+ * phone on the same network can dial it, which is the whole point of the
15
+ * pairing code.
16
16
  *
17
- * Nothing here reaches the network, and nothing here mints or spends anything.
17
+ * There is deliberately no fourth source. A relay identity file on disk would
18
+ * only prove that this machine once minted an id; it says nothing about whether
19
+ * the Worker's row points at something reachable (the registration may have
20
+ * failed, the lease may never have been claimed, the relay may be off), so
21
+ * turning it into an origin would hand the QR a subdomain that cannot answer.
22
+ * The live facts above already cover every state the bridge can be in, and
23
+ * dropping the file also drops this package's last data dependency on the
24
+ * sibling plugin's home directory.
25
+ *
26
+ * The live source arrives as a seam: this module stays a pure function of what
27
+ * it is handed and never reads a socket, a timer or a file. Nothing here
28
+ * reaches the network, and nothing here mints or spends anything.
18
29
  * @module dsh-remote-bridge/host/pair-origin
19
30
  */
20
- /** The relay's worker domain; a profile's stable origin is `<id>.<this>`. */
21
- export declare const RELAY_DOMAIN = "dsh-market.com";
22
- /** The registry directory `dsh-remote-web-ui` keeps its per-profile row in. */
23
- export declare const RELAY_REGISTRY_DIR = "remote-web-ui-registry";
24
31
  /** One discovered origin and the fact that produced it. */
25
32
  export interface PairOriginFacts {
26
33
  /** Origin only, no path: `wss://<id>.dsh-market.com`. */
27
34
  readonly origin: string;
28
35
  /** Where the answer came from, for the panel and the log. */
29
- readonly source: 'env' | 'registry';
36
+ readonly source: 'realtime' | 'env' | 'lan';
37
+ }
38
+ /** This machine's LAN address and the port a peer dials it on. */
39
+ export interface PairOriginLanTarget {
40
+ readonly address: string;
41
+ readonly port: number;
30
42
  }
31
43
  export interface DiscoverPairOriginOptions {
32
44
  /** Environment to read; defaults to `process.env`. */
33
45
  readonly env?: NodeJS.ProcessEnv;
34
- /** DSH home to look in; defaults to `resolveDshHome(env)`. */
35
- readonly home?: string;
36
- /** Profile whose registry row to read; defaults to `$DSH_PROFILE` or `desktop`. */
37
- readonly profile?: string;
46
+ /**
47
+ * This bridge's own live public origin (a relay lease's hostname or a running
48
+ * tunnel's URL); undefined while neither is up. Called at most once.
49
+ */
50
+ readonly realtime?: () => string | undefined;
51
+ /** The LAN literal to fall back to when no public origin is known. */
52
+ readonly lan?: () => PairOriginLanTarget | undefined;
38
53
  }
39
54
  /**
40
55
  * Discover the public origin of this instance.
41
- * @param options - environment, home and profile seams for tests.
56
+ * @param options - environment and the two live seams for tests.
42
57
  * @returns the origin and its source, or `undefined` when nothing is known.
43
58
  */
44
59
  export declare function discoverPairOrigin(options?: DiscoverPairOriginOptions): PairOriginFacts | undefined;
@@ -0,0 +1,215 @@
1
+ /**
2
+ * The bridge connector: the plugin side of the relay bridge, grown from the
3
+ * shadow-flight probe (`probe/relay-bridge/connector.mjs`).
4
+ *
5
+ * It dials the instance's Durable Object meeting point over WSS and serves
6
+ * every stream the object multiplexes onto that one socket -- HTTP requests
7
+ * with streamed bodies and responses, and the phone's own WebSocket upgrades.
8
+ *
9
+ * Three rules are not negotiable here:
10
+ *
11
+ * 1. The credential is the relay identity's own long-lived id and secret, sent
12
+ * in the upgrade's `authorization` header so it never appears in a URL. A
13
+ * dropped socket is re-dialed with the same credential; the object replaces
14
+ * the socket it already holds, so a reconnect needs no new ticket and no
15
+ * new instance.
16
+ * 2. The connector serves exactly one inbound path, the protocol's `WS_PATH`.
17
+ * Any other HTTP request is answered 404 by the connector itself, any other
18
+ * upgrade is refused the same way, and neither ever dials upstream. That
19
+ * whitelist -- not any header -- is what keeps the host's control plane off
20
+ * the public origin.
21
+ * 3. The connector forwards the public origin the phone dialed and never
22
+ * invents the authority it dials. The object reads the origin from the
23
+ * request URL and puts it in the frame; the fallback is this instance's
24
+ * claimed relay hostname. The loopback `Host` is stamped exactly once, and
25
+ * not here: the upstream this connector dials is the ingress gate, whose
26
+ * whole job is to rewrite the `Host` to the loopback authority and to serve
27
+ * nothing but `WS_PATH`. So the gate is the single place the rewrite
28
+ * happens, and rule 2 is the reason that rewrite cannot expose anything
29
+ * beyond the protocol's own route.
30
+ *
31
+ * Frames mirror `market/worker/src/relay-bridge.js`: control frames are JSON
32
+ * text, payload frames are `[kind:u8][streamId:u32be][payload]`.
33
+ */
34
+ import type { RelayBridgeStart } from './relay-connector.ts';
35
+ /** The upgrade carries the lease secret here, never in the URL. */
36
+ export declare const BRIDGE_AUTH_HEADER = "authorization";
37
+ /** Response frames this connector will not forward upstream. */
38
+ export declare const BRIDGE_HOP_BY_HOP: Set<string>;
39
+ /** Where a dropped socket restarts: fast first, then patient. */
40
+ export declare const BRIDGE_RETRY_BASE_MS = 1000;
41
+ export declare const BRIDGE_RETRY_MAX_MS = 30000;
42
+ /** The body every refused inbound stream is answered with. */
43
+ export declare const BRIDGE_NOT_FOUND_BODY = "{\"error\":\"not-found\"}";
44
+ /**
45
+ * Whether one bridged stream may reach the upstream at all.
46
+ *
47
+ * Only the protocol's own upgrade path is served. The comparison is on the
48
+ * path, not the whole URL, because the pairing link carries its one-shot
49
+ * ticket in the query (`WS_PATH?token=...`); everything else — another path,
50
+ * a path that merely starts the same way, an empty URL — is refused.
51
+ * @param url - the `url` one bridged frame names.
52
+ * @returns true when the path is exactly `WS_PATH`.
53
+ */
54
+ export declare function isBridgeInboundPath(url: string): boolean;
55
+ /** One header pair as the frame contract carries it. */
56
+ export type BridgeHeaderPairs = ReadonlyArray<readonly [string, string]>;
57
+ /** The upgrade URL one instance dials (the id is not a secret). */
58
+ export declare function relayBridgeDialUrl(endpoint: string, id: string): string;
59
+ /**
60
+ * The `Host` one bridged request travels with.
61
+ * @param frameHost - the public origin the object read from the request URL.
62
+ * @param hostname - this instance's claimed relay hostname.
63
+ * @returns a public origin, never the upstream authority this connector dials.
64
+ */
65
+ export declare function bridgeUpstreamHost(frameHost: unknown, hostname: string): string;
66
+ /**
67
+ * The upstream headers of one bridged request: the phone's own, minus the hops
68
+ * this transport owns, with the public `Host` put back explicitly.
69
+ */
70
+ export declare function bridgeUpstreamHeaders(frameHeaders: unknown, host: string): Record<string, string>;
71
+ /** The headers of the bridge socket's own upgrade. */
72
+ export declare function bridgeUpgradeHeaders(endpoint: string, secret: string): Record<string, string>;
73
+ /** One client frame, masked as RFC 6455 requires of the dialing side. */
74
+ export declare function encodeBridgeFrame(opcode: number, payload: Uint8Array): Uint8Array;
75
+ /** One frame of a WebSocket the connector dialed. */
76
+ export interface BridgeFrame {
77
+ opcode: number;
78
+ payload: Buffer;
79
+ }
80
+ /**
81
+ * A frame reader for the connector's own client side, reassembling fragmented
82
+ * messages and unmasking nothing: only servers send unmasked frames here.
83
+ */
84
+ export declare function createBridgeFrameParser(onFrame: (frame: BridgeFrame) => void): (incoming: Buffer) => void;
85
+ /** The connector's observable state (logged, and read by the tests). */
86
+ export type RelayBridgeState = {
87
+ state: 'idle';
88
+ } | {
89
+ state: 'dialing';
90
+ } | {
91
+ state: 'connected';
92
+ instance: string;
93
+ } | {
94
+ state: 'failed';
95
+ error: string;
96
+ };
97
+ /**
98
+ * What the connector records on disk: its state plus the lease it dials.
99
+ * The Desktop host runs this plugin in a process whose stdout nobody reads, so
100
+ * without this record a connector that never attached (or a lease that never
101
+ * claimed) leaves no trace at all.
102
+ */
103
+ export interface RelayBridgeStateRecord {
104
+ state: RelayBridgeState['state'];
105
+ instance: string;
106
+ hostname: string;
107
+ endpoint: string;
108
+ upstream: string;
109
+ /** When the record was written (ISO 8601). */
110
+ at: string;
111
+ /** The dial failure, for a `failed` record. */
112
+ error?: string;
113
+ }
114
+ /** Where the connector records its state (`$DSH_HOME/remote-web-ui-relay-bridge.json`). */
115
+ export declare function relayBridgeStateFile(home?: string): string;
116
+ /**
117
+ * Record one connector state. Best effort on purpose: a home that cannot be
118
+ * written must never take the socket down with it.
119
+ * @param file - the record path (see `relayBridgeStateFile`).
120
+ * @param record - the state and the lease it belongs to.
121
+ */
122
+ export declare function writeRelayBridgeState(file: string, record: RelayBridgeStateRecord): void;
123
+ /** Everything one bridge connector needs to run. */
124
+ export interface RelayBridgeConnectorOptions {
125
+ /** The upgrade endpoint the claim reported. */
126
+ endpoint: string;
127
+ /** The relay identity id. */
128
+ id: string;
129
+ /** The relay identity secret (the same long-lived credential). */
130
+ secret: string;
131
+ /** This instance's relay hostname, the fallback public origin. */
132
+ hostname: string;
133
+ /** The local origin the connector serves, `http://127.0.0.1:<port>`. */
134
+ upstream: string;
135
+ baseDelayMs?: number;
136
+ maxDelayMs?: number;
137
+ /** Schedule one retry; defaults to an unref'd node timer. */
138
+ timerFn?: (fn: () => void, ms: number) => {
139
+ unref?: () => void;
140
+ };
141
+ onState?: (state: RelayBridgeState) => void;
142
+ }
143
+ /**
144
+ * The connector itself: one socket to the object, one upstream request or
145
+ * WebSocket per stream id, and a reconnect that keeps the same credential.
146
+ */
147
+ export declare class RelayBridgeConnector {
148
+ private socket;
149
+ private parser;
150
+ private timer;
151
+ private stateValue;
152
+ private attempts;
153
+ private disposed;
154
+ private readonly requests;
155
+ private readonly peers;
156
+ private readonly options;
157
+ constructor(options: RelayBridgeConnectorOptions);
158
+ /** The connector's current state. */
159
+ get state(): RelayBridgeState;
160
+ /** Whether a bridge socket is attached right now. */
161
+ get connected(): boolean;
162
+ /** Dial the object (or schedule the next attempt if the dial fails). */
163
+ start(): void;
164
+ /** Close the socket and stop retrying (the relay half was disposed). */
165
+ stop(): void;
166
+ private dial;
167
+ private attach;
168
+ /** Send one control frame: a text frame, which is how the object tells a
169
+ * control frame from a payload chunk. */
170
+ private sendText;
171
+ /** Send one payload frame: a binary frame carrying a chunk. */
172
+ private sendChunk;
173
+ private write;
174
+ private onBridgeFrame;
175
+ private onControl;
176
+ /**
177
+ * Answer one bridged stream with 404 without dialing anything: the refusal is
178
+ * complete here, so a non-whitelisted path costs the upstream nothing.
179
+ * @param id - the stream the object opened.
180
+ */
181
+ private refuseNotFound;
182
+ /** Start one upstream HTTP request for a bridged stream. */
183
+ private startHttp;
184
+ /** Open one upstream WebSocket for a phone's upgrade. */
185
+ private openSocket;
186
+ /** Report one failed dial and retry with the same credential. */
187
+ private fail;
188
+ private scheduleRetry;
189
+ private clearTimer;
190
+ /** Drop every stream this socket carried: the object re-opens them. */
191
+ private teardown;
192
+ private setState;
193
+ }
194
+ /** The plugin-side owner of one bridge connector. */
195
+ export interface RelayBridgeRunner {
196
+ /** Start (or restart) the connector for one accepted lease. */
197
+ start(start: RelayBridgeStart): void;
198
+ /** Stop it (the relay half was disposed). */
199
+ stop(): void;
200
+ readonly state: RelayBridgeState;
201
+ }
202
+ /**
203
+ * Build the runner the relay pair drives: one connector per accepted lease,
204
+ * rebuilt when a later claim names a different endpoint, and stopped with the
205
+ * relay half. The bridge keeps its socket up while the instance's mode is
206
+ * quick, so a server-side flip needs no plugin restart.
207
+ * @param options - a state observer (logs and the on-disk record).
208
+ */
209
+ export declare function createRelayBridgeRunner(options?: {
210
+ onState?: (state: RelayBridgeState) => void;
211
+ /** Where to record the state; `null` keeps the runner in memory only. */
212
+ stateFile?: string | null;
213
+ /** The clock the record timestamps with (tests pass a fixed one). */
214
+ now?: () => string;
215
+ }): RelayBridgeRunner;
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The relay's two connectors. The quick tunnel keeps serving every instance
3
+ * that has not migrated, and the named connector is established beside it on
4
+ * the same relay hostname and left idle while the wildcard Worker route still
5
+ * shadows the CNAME. The control plane's `mode` names the connector the phone
6
+ * is meant to be served from; nothing here switches the edge — it only keeps
7
+ * both sides up, so a server-side flip needs no plugin restart and a rollback
8
+ * is the same flip back.
9
+ */
10
+ import { type RelayClaim, type RelayClaimOutcome, type RelayClaimRequest, type RelayConnectorMode } from './relay-control.ts';
11
+ import type { RelayIdentity } from './relay-registry.ts';
12
+ import { TunnelManager, type TunnelInfo } from './tunnel.ts';
13
+ /**
14
+ * The crash-recovery record slot the idle named connector owns. Kept apart
15
+ * from the quick connector's slot so each connector's leftover child is reaped
16
+ * by the start that belongs to it instead of overwriting its sibling's record.
17
+ */
18
+ export declare function namedTunnelChildRecordFile(home?: string): string;
19
+ /**
20
+ * Read this plugin's own version from its package manifest (the claim reports
21
+ * it so the migration can measure adoption by released version).
22
+ *
23
+ * This module sits one level deeper than the source root (`src/host/`) while
24
+ * the bundle stays one level under the package root (`lib/index.js`), so the
25
+ * two depths are tried in order with the bundle's own first. A manifest that
26
+ * cannot be read at either depth is a miss, and the claim then carries no
27
+ * version at all.
28
+ * @returns the version, or undefined when the manifest cannot be read.
29
+ */
30
+ export declare function readPluginVersion(): string | undefined;
31
+ /**
32
+ * The dedupe key of one claim trigger: the local origin port plus the quick
33
+ * tunnel URL the start reported. A settings sync re-runs the tunnel plan with
34
+ * the same key; a tunnel restart mints a new quick URL and therefore claims
35
+ * again (which is also what keeps the lease's `last_seen_at` inside the cron
36
+ * GC's TTL).
37
+ * @param port - the bound web server port, or undefined before it settles.
38
+ * @param target - the quick tunnel URL, or undefined while none is minted.
39
+ * @returns the key, or undefined when there is nothing to claim yet.
40
+ */
41
+ export declare function relayClaimKeyOf(port: number | undefined, target: string | undefined): string | undefined;
42
+ /** The idle named connector: start, stop and report, nothing else. */
43
+ export interface NamedRelayConnector {
44
+ /** Run one named connector for the lease (token via the environment). */
45
+ start(token: string, hostname: string): void;
46
+ /** Stop the connector (the relay half was disposed). */
47
+ stop(): void;
48
+ readonly info: TunnelInfo;
49
+ }
50
+ /**
51
+ * Build the named connector the relay keeps beside the quick tunnel.
52
+ *
53
+ * Health probing is off on purpose: while the wildcard Worker route answers
54
+ * the relay hostname, a probe of the idle connector's public URL sees the
55
+ * Worker's offline page and would declare a healthy connector dead, restarting
56
+ * it forever (the failure mode issue #1723 fixed for the quick tunnel).
57
+ * @param options - an existing manager (tests); defaults spawn the real one.
58
+ */
59
+ export declare function createNamedRelayConnector(options?: {
60
+ manager?: TunnelManager;
61
+ }): NamedRelayConnector;
62
+ /** The lease half's observable state (logged, and read by the tests). */
63
+ export type RelayPairState = {
64
+ state: 'idle';
65
+ } | {
66
+ state: 'claiming';
67
+ } | {
68
+ state: 'claimed';
69
+ mode: RelayConnectorMode;
70
+ hostname: string;
71
+ } | {
72
+ state: 'failed';
73
+ error: string;
74
+ };
75
+ /** Everything the bridge connector needs to run for one accepted lease. */
76
+ export interface RelayBridgeStart {
77
+ claim: RelayClaim;
78
+ identity: RelayIdentity;
79
+ port: number;
80
+ }
81
+ /** Injectable seams of the lease half (defaults are the real control plane). */
82
+ export interface RelayConnectorPairOptions {
83
+ /** One claim attempt. */
84
+ claim?: (request: RelayClaimRequest) => Promise<RelayClaimOutcome>;
85
+ /** Start the named connector for one accepted lease. */
86
+ startNamed?: (token: string, hostname: string) => void;
87
+ /** Stop the named connector. */
88
+ stopNamed?: () => void;
89
+ /** Start (or restart) the bridge connector for one accepted lease. It runs
90
+ * beside the quick tunnel and idles while the instance's mode is quick, so a
91
+ * server-side flip needs no plugin restart. */
92
+ startBridge?: (start: RelayBridgeStart) => void;
93
+ /** Stop the bridge connector. */
94
+ stopBridge?: () => void;
95
+ /** Release the lease (the offline action, never a retire). */
96
+ release?: (identity: RelayIdentity) => Promise<void>;
97
+ /** Observe the lease state (logs only — the card still renders the registry). */
98
+ onState?: (state: RelayPairState) => void;
99
+ baseDelayMs?: number;
100
+ maxDelayMs?: number;
101
+ /** Schedule one retry; defaults to an unref'd node timer. */
102
+ timerFn?: (fn: () => void, ms: number) => {
103
+ unref?: () => void;
104
+ };
105
+ }
106
+ /**
107
+ * Own the lease half of the relay: claim it on every tunnel start, bring the
108
+ * named connector up beside the quick one, and retry a failed claim with a
109
+ * capped backoff while the quick connector keeps serving.
110
+ */
111
+ export declare class RelayConnectorPair {
112
+ private readonly identity;
113
+ private readonly options;
114
+ private stateValue;
115
+ private leaseValue;
116
+ private attempts;
117
+ private timer;
118
+ private disposed;
119
+ constructor(identity: RelayIdentity, options?: RelayConnectorPairOptions);
120
+ /** The lease half's current state. */
121
+ get state(): RelayPairState;
122
+ /** The connector the phone is served from, for the last accepted lease. */
123
+ get served(): RelayConnectorMode | undefined;
124
+ /** The last accepted lease (undefined until one lands). */
125
+ get lease(): RelayClaim | undefined;
126
+ /**
127
+ * Claim one lease and start (or restart) the named connector for it. A
128
+ * refusal is graded into a retry and never tears down the quick connector:
129
+ * the instance keeps the origin the registry already gave it.
130
+ * @param input - the local origin port and the reporting plugin version.
131
+ * @returns the accepted lease, or undefined when the attempt did not land.
132
+ */
133
+ start(input: {
134
+ port: number;
135
+ pluginVersion?: string;
136
+ }): Promise<RelayClaim | undefined>;
137
+ /**
138
+ * The plugin's offline action (toggle off, profile unmount): release the
139
+ * lease and stop the idle connector. Never retires — the hostname is the
140
+ * phone's bookmark, and the tunnel behind it survives.
141
+ */
142
+ release(): Promise<void>;
143
+ /** Stop retrying and drop the connector (the relay half was disposed). */
144
+ dispose(): void;
145
+ private startNamed;
146
+ private stopNamed;
147
+ /** Bring the bridge connector up for one accepted lease, if it carries one. */
148
+ private startBridge;
149
+ private scheduleRetry;
150
+ private clearTimer;
151
+ private setState;
152
+ }