@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,106 @@
1
+ /**
2
+ * The lan-bind block this plugin used to write, and its removal (issue #1917).
3
+ *
4
+ * Up to 0.4.8 the toggle pinned the LAN address into the profile's
5
+ * `cordis.patch.yml` as a managed `- id: webserver` row. That approach is
6
+ * retired for two measured reasons:
7
+ *
8
+ * 1. A same-id patch row REPLACES the whole row config, so the block silently
9
+ * swallowed the official row's own bind expression; the CLI `--host` /
10
+ * `--port` never reached the running row, and the machine's port came from
11
+ * a literal this plugin guessed.
12
+ * 2. The profile patch is exactly what the Host's HMR config watcher refreshes
13
+ * from, so writing it recomposed the running process and rebound the live
14
+ * listener - the "takes effect on the next start" premise was false, and a
15
+ * write made mid-session moved the bind under the running host.
16
+ *
17
+ * LAN reachability now comes from a runtime forwarder instead (lan-forward.ts),
18
+ * so the host always listens on loopback and this module's only remaining job
19
+ * is to remove the block older versions left behind. The removal is
20
+ * strip-only: no write appends anything, so the official webserver row (and
21
+ * every other row) stays byte-identical. The block discipline (markers, atomic
22
+ * write) follows the dsh-LAN reference implementation (MIT).
23
+ */
24
+ export declare const LAN_BIND_BLOCK_BEGIN = "# --- remote-web-ui lan-bind block (managed - do not edit) ---";
25
+ export declare const LAN_BIND_BLOCK_END = "# --- end remote-web-ui lan-bind block ---";
26
+ /**
27
+ * A bind host the managed block may pin. `'0.0.0.0'` only on a host whose
28
+ * webserver schema still accepts the wildcard, `'127.0.0.1'` for the toggle
29
+ * off, and otherwise one concrete interface address of this machine (see
30
+ * lan-bind-plan.ts / host-bind-capability.ts, issue #1893).
31
+ */
32
+ export type LanBindHost = string;
33
+ /**
34
+ * The absolute path of the profile patch file this toggle manages. The value
35
+ * is config-controlled (and the runtime/environment fallbacks bypass schema
36
+ * validation entirely), so the path is guarded twice: the profile must be a
37
+ * single safe path segment, and the resolved file must stay under the
38
+ * profiles directory.
39
+ */
40
+ export declare function profilePatchFile(profile: string, home?: string): string;
41
+ /**
42
+ * Remove the managed block (its markers and the webserver row this plugin
43
+ * wrote) from patch content, keeping every other row.
44
+ *
45
+ * The markers travel with the file through writers that append rows through
46
+ * the YAML document API: the appended rows land at the end of the sequence,
47
+ * which is BEFORE a trailing END comment, so the region between the markers
48
+ * can hold rows this plugin never wrote. Deleting the whole region silently
49
+ * removed the user's model, plugin and remote-control rows on the next rewrite
50
+ * - the remote-control row carries the LAN toggle itself, so the feature reset
51
+ * to `undefined` and the phone was locked out again after a restart (DSH
52
+ * Desktop report, 2026-09-30). Only the managed item is removed here; every
53
+ * foreign row is kept in place and the fresh block is appended after them (the
54
+ * same-id row last wins).
55
+ * @param content - the patch file text.
56
+ * @returns the text with the markers and the managed row removed.
57
+ */
58
+ export declare function stripManagedBlock(content: string): string;
59
+ /** The bind state a managed block pinned (undefined when there is no block). */
60
+ export interface ManagedBindState {
61
+ host: LanBindHost | (string & {});
62
+ port: number | undefined;
63
+ }
64
+ /**
65
+ * Parse the block's pinned bind out of patch content. A block whose values
66
+ * were hand-edited reports the literals as-is so the card can surface them
67
+ * instead of silently claiming one of the two known states.
68
+ */
69
+ export declare function managedBindOf(content: string): ManagedBindState | undefined;
70
+ /** File-level state of a patch file a previous version wrote to. */
71
+ export declare function lanBindState(profile: string, home?: string): {
72
+ blockPresent: boolean;
73
+ host?: string;
74
+ port?: number;
75
+ };
76
+ /** What one legacy-block cleanup did, for the settings card and the log. */
77
+ export interface LegacyBlockCleanup {
78
+ /** Whether the file actually carried the managed block. */
79
+ removed: boolean;
80
+ /** The bind the removed block pinned, when it could be read. */
81
+ host: string | undefined;
82
+ /** The port the removed block pinned, when it could be read. */
83
+ port: number | undefined;
84
+ }
85
+ /**
86
+ * Remove the managed block a previous version wrote, and nothing else.
87
+ *
88
+ * The file is rewritten atomically (unique temp file + rename, so a concurrent
89
+ * reader never sees a half-written patch) with its original permissions
90
+ * preserved, and only when the block is actually there: a second run finds no
91
+ * markers, writes nothing, and leaves the bytes identical, which is what makes
92
+ * the plugin's once-per-boot call idempotent.
93
+ *
94
+ * The official `- id: webserver` row every profile carries is a FOREIGN row -
95
+ * the strip keeps it verbatim (see stripManagedBlock). Nothing is appended, so
96
+ * the profile keeps the row's own bind expression and the CLI flags keep
97
+ * reaching it.
98
+ *
99
+ * A failure (an unreadable file, a read-only profile) is NOT swallowed here:
100
+ * callers report it, because a silent failure leaves a block that keeps
101
+ * swallowing the bind on every later start.
102
+ * @param profile - the managed profile name.
103
+ * @param home - DSH home (test seam).
104
+ * @returns what was removed; `removed: false` when there was nothing to do.
105
+ */
106
+ export declare function removeManagedBlock(profile: string, home?: string): LegacyBlockCleanup;
@@ -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,234 @@
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
+ * Flow control runs one way only, object to connector. A pause closes the
35
+ * object's window on one stream: this half stops sending that stream's payload
36
+ * frames and stops reading the upstream (a response body, a WebSocket socket),
37
+ * so the backlog waits in the kernel instead of in this process. A resume opens
38
+ * it again. A stream being abandoned arrives as close -- the frame this contract
39
+ * already used for a phone cancel -- and cancel is accepted as the same thing,
40
+ * because that is the name the frozen contract gives it. An object too old to
41
+ * send any of them leaves this half exactly as it was, and a frame this half has
42
+ * never heard of is ignored rather than answered.
43
+ */
44
+ import type { RelayBridgeStart } from './relay-connector.ts';
45
+ /** The upgrade carries the lease secret here, never in the URL. */
46
+ export declare const BRIDGE_AUTH_HEADER = "authorization";
47
+ /** Response frames this connector will not forward upstream. */
48
+ export declare const BRIDGE_HOP_BY_HOP: Set<string>;
49
+ /** Where a dropped socket restarts: fast first, then patient. */
50
+ export declare const BRIDGE_RETRY_BASE_MS = 1000;
51
+ export declare const BRIDGE_RETRY_MAX_MS = 30000;
52
+ /** The body every refused inbound stream is answered with. */
53
+ export declare const BRIDGE_NOT_FOUND_BODY = "{\"error\":\"not-found\"}";
54
+ /**
55
+ * Whether one bridged stream may reach the upstream at all.
56
+ *
57
+ * Only the protocol's own upgrade path is served. The comparison is on the
58
+ * path, not the whole URL, because the pairing link carries its one-shot
59
+ * ticket in the query (`WS_PATH?token=...`); everything else — another path,
60
+ * a path that merely starts the same way, an empty URL — is refused.
61
+ * @param url - the `url` one bridged frame names.
62
+ * @returns true when the path is exactly `WS_PATH`.
63
+ */
64
+ export declare function isBridgeInboundPath(url: string): boolean;
65
+ /** One header pair as the frame contract carries it. */
66
+ export type BridgeHeaderPairs = ReadonlyArray<readonly [string, string]>;
67
+ /** The upgrade URL one instance dials (the id is not a secret). */
68
+ export declare function relayBridgeDialUrl(endpoint: string, id: string): string;
69
+ /**
70
+ * The `Host` one bridged request travels with.
71
+ * @param frameHost - the public origin the object read from the request URL.
72
+ * @param hostname - this instance's claimed relay hostname.
73
+ * @returns a public origin, never the upstream authority this connector dials.
74
+ */
75
+ export declare function bridgeUpstreamHost(frameHost: unknown, hostname: string): string;
76
+ /**
77
+ * The upstream headers of one bridged request: the phone's own, minus the hops
78
+ * this transport owns, with the public `Host` put back explicitly.
79
+ */
80
+ export declare function bridgeUpstreamHeaders(frameHeaders: unknown, host: string): Record<string, string>;
81
+ /** The headers of the bridge socket's own upgrade. */
82
+ export declare function bridgeUpgradeHeaders(endpoint: string, secret: string): Record<string, string>;
83
+ /** One client frame, masked as RFC 6455 requires of the dialing side. */
84
+ export declare function encodeBridgeFrame(opcode: number, payload: Uint8Array): Uint8Array;
85
+ /** One frame of a WebSocket the connector dialed. */
86
+ export interface BridgeFrame {
87
+ opcode: number;
88
+ payload: Buffer;
89
+ }
90
+ /**
91
+ * A frame reader for the connector's own client side, reassembling fragmented
92
+ * messages and unmasking nothing: only servers send unmasked frames here.
93
+ */
94
+ export declare function createBridgeFrameParser(onFrame: (frame: BridgeFrame) => void): (incoming: Buffer) => void;
95
+ /** The connector's observable state (logged, and read by the tests). */
96
+ export type RelayBridgeState = {
97
+ state: 'idle';
98
+ } | {
99
+ state: 'dialing';
100
+ } | {
101
+ state: 'connected';
102
+ instance: string;
103
+ } | {
104
+ state: 'failed';
105
+ error: string;
106
+ };
107
+ /**
108
+ * What the connector records on disk: its state plus the lease it dials.
109
+ * The Desktop host runs this plugin in a process whose stdout nobody reads, so
110
+ * without this record a connector that never attached (or a lease that never
111
+ * claimed) leaves no trace at all.
112
+ */
113
+ export interface RelayBridgeStateRecord {
114
+ state: RelayBridgeState['state'];
115
+ instance: string;
116
+ hostname: string;
117
+ endpoint: string;
118
+ upstream: string;
119
+ /** When the record was written (ISO 8601). */
120
+ at: string;
121
+ /** The dial failure, for a `failed` record. */
122
+ error?: string;
123
+ }
124
+ /** Where the connector records its state (`$DSH_HOME/remote-web-ui-relay-bridge.json`). */
125
+ export declare function relayBridgeStateFile(home?: string): string;
126
+ /**
127
+ * Record one connector state. Best effort on purpose: a home that cannot be
128
+ * written must never take the socket down with it.
129
+ * @param file - the record path (see `relayBridgeStateFile`).
130
+ * @param record - the state and the lease it belongs to.
131
+ */
132
+ export declare function writeRelayBridgeState(file: string, record: RelayBridgeStateRecord): void;
133
+ /** Everything one bridge connector needs to run. */
134
+ export interface RelayBridgeConnectorOptions {
135
+ /** The upgrade endpoint the claim reported. */
136
+ endpoint: string;
137
+ /** The relay identity id. */
138
+ id: string;
139
+ /** The relay identity secret (the same long-lived credential). */
140
+ secret: string;
141
+ /** This instance's relay hostname, the fallback public origin. */
142
+ hostname: string;
143
+ /** The local origin the connector serves, `http://127.0.0.1:<port>`. */
144
+ upstream: string;
145
+ baseDelayMs?: number;
146
+ maxDelayMs?: number;
147
+ /** Schedule one retry; defaults to an unref'd node timer. */
148
+ timerFn?: (fn: () => void, ms: number) => {
149
+ unref?: () => void;
150
+ };
151
+ onState?: (state: RelayBridgeState) => void;
152
+ }
153
+ /**
154
+ * The connector itself: one socket to the object, one upstream request or
155
+ * WebSocket per stream id, and a reconnect that keeps the same credential.
156
+ */
157
+ export declare class RelayBridgeConnector {
158
+ private socket;
159
+ private parser;
160
+ private timer;
161
+ private stateValue;
162
+ private attempts;
163
+ private disposed;
164
+ /** HTTP streams still uploading: the request the object's frames feed. */
165
+ private readonly requests;
166
+ /** HTTP streams whose head already arrived: the upstream response body a
167
+ * pause holds back and a stream being abandoned destroys. */
168
+ private readonly responses;
169
+ private readonly peers;
170
+ private readonly options;
171
+ constructor(options: RelayBridgeConnectorOptions);
172
+ /** The connector's current state. */
173
+ get state(): RelayBridgeState;
174
+ /** Whether a bridge socket is attached right now. */
175
+ get connected(): boolean;
176
+ /** Dial the object (or schedule the next attempt if the dial fails). */
177
+ start(): void;
178
+ /** Close the socket and stop retrying (the relay half was disposed). */
179
+ stop(): void;
180
+ private dial;
181
+ private attach;
182
+ /** Send one control frame: a text frame, which is how the object tells a
183
+ * control frame from a payload chunk. */
184
+ private sendText;
185
+ /** Send one payload frame: a binary frame carrying a chunk. */
186
+ private sendChunk;
187
+ private write;
188
+ private onBridgeFrame;
189
+ private onControl;
190
+ /** Close the object's window on one stream: a paused response body emits no
191
+ * more data events and a paused socket leaves its bytes in the kernel. */
192
+ private pauseStream;
193
+ /** Reopen that window. */
194
+ private resumeStream;
195
+ /**
196
+ * Answer one bridged stream with 404 without dialing anything: the refusal is
197
+ * complete here, so a non-whitelisted path costs the upstream nothing.
198
+ * @param id - the stream the object opened.
199
+ */
200
+ private refuseNotFound;
201
+ /** Start one upstream HTTP request for a bridged stream. */
202
+ private startHttp;
203
+ /** Open one upstream WebSocket for a phone's upgrade. */
204
+ private openSocket;
205
+ /** Report one failed dial and retry with the same credential. */
206
+ private fail;
207
+ private scheduleRetry;
208
+ private clearTimer;
209
+ /** Drop every stream this socket carried: the object re-opens them. */
210
+ private teardown;
211
+ private setState;
212
+ }
213
+ /** The plugin-side owner of one bridge connector. */
214
+ export interface RelayBridgeRunner {
215
+ /** Start (or restart) the connector for one accepted lease. */
216
+ start(start: RelayBridgeStart): void;
217
+ /** Stop it (the relay half was disposed). */
218
+ stop(): void;
219
+ readonly state: RelayBridgeState;
220
+ }
221
+ /**
222
+ * Build the runner the relay pair drives: one connector per accepted lease,
223
+ * rebuilt when a later claim names a different endpoint, and stopped with the
224
+ * relay half. The bridge keeps its socket up while the instance's mode is
225
+ * quick, so a server-side flip needs no plugin restart.
226
+ * @param options - a state observer (logs and the on-disk record).
227
+ */
228
+ export declare function createRelayBridgeRunner(options?: {
229
+ onState?: (state: RelayBridgeState) => void;
230
+ /** Where to record the state; `null` keeps the runner in memory only. */
231
+ stateFile?: string | null;
232
+ /** The clock the record timestamps with (tests pass a fixed one). */
233
+ now?: () => string;
234
+ }): RelayBridgeRunner;