grpc-dc 0.40.0 → 0.41.0

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.
@@ -0,0 +1,127 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Rendezvous browser channel: connect to a pre-published,
4
+ // fixed WebRTC endpoint with no signaling exchange at all.
5
+ //
6
+ // A rendezvous descriptor ({host, port, iceUfrag, icePwd,
7
+ // fingerprint}) is published beforehand by the server —
8
+ // hardcoded, in a config file, served from any static URL.
9
+ // This helper synthesizes that endpoint's SDP offer locally,
10
+ // answers it in-page, and lets the browser run ICE as the
11
+ // controlling agent (the descriptor is ICE-lite) with DTLS
12
+ // setup passive (the server presents the fingerprinted
13
+ // certificate). host must be an IP literal: candidate lines
14
+ // carry addresses, not names.
15
+
16
+ import { Channel } from "./channel.js";
17
+
18
+ function waitRendezvousChannelOpen(dc, timeoutMs) {
19
+ if (dc.readyState === "open") return Promise.resolve();
20
+ return new Promise((resolve, reject) => {
21
+ const timer = setTimeout(() => {
22
+ cleanup();
23
+ reject(new Error("rendezvous: data channel did not open"));
24
+ }, timeoutMs);
25
+ function cleanup() {
26
+ clearTimeout(timer);
27
+ dc.removeEventListener?.("open", onOpen);
28
+ dc.removeEventListener?.("error", onError);
29
+ }
30
+ function onOpen() {
31
+ cleanup();
32
+ resolve();
33
+ }
34
+ function onError() {
35
+ cleanup();
36
+ reject(new Error("rendezvous: data channel error"));
37
+ }
38
+ dc.addEventListener("open", onOpen);
39
+ dc.addEventListener("error", onError);
40
+ });
41
+ }
42
+
43
+ /**
44
+ * The endpoint's SDP offer, synthesized from a rendezvous
45
+ * descriptor. Exported for tests and debugging.
46
+ */
47
+ export function synthesizeRendezvousOffer(descriptor) {
48
+ const { host, port } = descriptor;
49
+ return [
50
+ "v=0",
51
+ "o=- 4611733050433952912 2 IN IP4 127.0.0.1",
52
+ "s=-",
53
+ "t=0 0",
54
+ "a=group:BUNDLE 0",
55
+ "a=ice-lite",
56
+ `m=application ${port} UDP/DTLS/SCTP webrtc-datachannel`,
57
+ "c=IN IP4 0.0.0.0",
58
+ `a=candidate:1 1 udp 2130706431 ${host} ${port} typ host generation 0`,
59
+ "a=end-of-candidates",
60
+ `a=ice-ufrag:${descriptor.iceUfrag}`,
61
+ `a=ice-pwd:${descriptor.icePwd}`,
62
+ `a=fingerprint:sha-256 ${descriptor.fingerprint}`,
63
+ `a=setup:${descriptor.setup ?? "passive"}`,
64
+ "a=mid:0",
65
+ "a=sctp-port:5000",
66
+ "a=max-message-size:262144",
67
+ "",
68
+ ].join("\r\n");
69
+ }
70
+
71
+ /**
72
+ * Fetch a rendezvous descriptor JSON from `url` (HTTPS in
73
+ * production; the well-known location
74
+ * /.well-known/grpc-dc-rendezvous.json with a short
75
+ * Cache-Control max-age is the rotation convention — see
76
+ * SPEC-WEBRTC.md). Returns the parsed descriptor object for
77
+ * rendezvousChannel.
78
+ *
79
+ * options: { fetchImpl }
80
+ */
81
+ export async function fetchRendezvousDescriptor(url, options = {}) {
82
+ const fetchImpl = options.fetchImpl ?? fetch;
83
+ const res = await fetchImpl(url, { headers: { accept: "application/json" } });
84
+ if (!res.ok) throw new Error(`rendezvous descriptor fetch failed: ${res.status}`);
85
+ const descriptor = await res.json();
86
+ for (const field of ["host", "port", "iceUfrag", "icePwd", "fingerprint"]) {
87
+ if (descriptor[field] === undefined) {
88
+ throw new Error(`rendezvous descriptor missing ${field}`);
89
+ }
90
+ }
91
+ return descriptor;
92
+ }
93
+
94
+ /**
95
+ * Dial a rendezvous endpoint and return a ready Channel.
96
+ * Waits for the "grpc" DataChannel to open, matching
97
+ * httpSignalingChannel's ready-to-use contract.
98
+ *
99
+ * options: { iceServers, iceTransportPolicy, timeoutMs, label }
100
+ * iceTransportPolicy "relay" (with TURN iceServers) is the
101
+ * symmetric-NAT shape: the browser nominates its relay
102
+ * candidate against the listener's published address.
103
+ */
104
+ export async function rendezvousChannel(descriptor, options = {}) {
105
+ const pc = new RTCPeerConnection({
106
+ iceServers: options.iceServers,
107
+ iceTransportPolicy: options.iceTransportPolicy,
108
+ });
109
+ const dc = pc.createDataChannel(options.label ?? "grpc");
110
+ try {
111
+ await pc.setRemoteDescription({
112
+ type: "offer",
113
+ sdp: synthesizeRendezvousOffer(descriptor),
114
+ });
115
+ const answer = await pc.createAnswer();
116
+ await pc.setLocalDescription(answer);
117
+ await waitRendezvousChannelOpen(dc, options.timeoutMs ?? 15000);
118
+ } catch (e) {
119
+ pc.close();
120
+ throw e;
121
+ }
122
+ const channel = new Channel(dc);
123
+ channel.peerConnection = pc;
124
+ channel.dataChannel = dc;
125
+ channel.closeRendezvous = () => pc.close();
126
+ return channel;
127
+ }
@@ -0,0 +1,44 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Rendezvous server: one fixed, pre-published WebRTC
4
+ // endpoint browsers dial with no signaling exchange.
5
+ // Wraps the WebRTC stack's RendezvousListener: one UDP
6
+ // socket, fixed ICE credentials and DTLS certificate.
7
+ // Publish listener.descriptor(host) wherever browsers can
8
+ // find it; serve HTTP signaling instead when the server
9
+ // address cannot be fixed in advance.
10
+
11
+ import { RendezvousListener } from "../../webrtc/js/rendezvous.js";
12
+
13
+ export { RendezvousListener } from "../../webrtc/js/rendezvous.js";
14
+
15
+ /**
16
+ * Serve this gRPC Server to rendezvous browsers.
17
+ *
18
+ * options: { address, port, family, localIps, iceUfrag,
19
+ * icePwd, certificate, onError, consentIntervalMs,
20
+ * consentExpiryMs, mux } — fix iceUfrag/icePwd/
21
+ * certificate and the published descriptor stays stable
22
+ * across restarts; ephemeral values rotate per process.
23
+ * With `mux` (a PeerMux, e.g. the one a signalingHandler
24
+ * uses via options.mux), the listener shares the mux's UDP
25
+ * socket instead of binding its own: one port serves both
26
+ * HTTP-signaled and rendezvous browsers.
27
+ * Returns the RendezvousListener (call .descriptor(host)
28
+ * and .close()).
29
+ */
30
+ export async function serveRendezvous(grpcServer, options = {}) {
31
+ const listener = await RendezvousListener.bind({
32
+ ...options,
33
+ onChannel: (channel, peer) => {
34
+ if (channel.label === "grpc") {
35
+ grpcServer.serve(channel);
36
+ channel.onclose = () => peer.close().catch(() => {});
37
+ } else {
38
+ channel.close();
39
+ }
40
+ },
41
+ });
42
+ grpcServer.closeRendezvous = () => listener.close();
43
+ return listener;
44
+ }
@@ -0,0 +1,224 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Browser HTTP/POST signaling client: one non-trickle exchange
4
+ // replaces a signaling server. The page creates an
5
+ // RTCPeerConnection, waits for ICE gathering to complete (so the
6
+ // offer SDP carries every candidate), POSTs it as JSON to the
7
+ // server's signaling endpoint, and applies the JSON answer.
8
+ // POST /grpc-dc/signal {"type":"offer","sdp":"v=0\r\n..."}
9
+ // 200 {"type":"answer","sdp":"v=0\r\n..."}
10
+ // Browser-safe: no Node imports. The server half is
11
+ // signaling_server.js (Node) plus the generated Go/Rust adapters,
12
+ // all implementing the same contract. Auth and CORS belong to
13
+ // the host application serving the page/endpoint, not here.
14
+
15
+ import { Channel } from "./channel.js";
16
+
17
+ export const SIGNAL_PATH = "/grpc-dc/signal";
18
+
19
+ function waitIceGathering(pc, timeoutMs) {
20
+ if (pc.iceGatheringState === "complete") return Promise.resolve();
21
+ return new Promise((resolve) => {
22
+ const timer = setTimeout(done, timeoutMs);
23
+ function done() {
24
+ clearTimeout(timer);
25
+ pc.removeEventListener?.("icegatheringstatechange", check);
26
+ resolve();
27
+ }
28
+ function check() {
29
+ if (pc.iceGatheringState === "complete") done();
30
+ }
31
+ pc.addEventListener("icegatheringstatechange", check);
32
+ });
33
+ }
34
+
35
+ function waitChannelOpen(dc, timeoutMs) {
36
+ if (dc.readyState === "open") return Promise.resolve();
37
+ return new Promise((resolve, reject) => {
38
+ const timer = setTimeout(() => {
39
+ cleanup();
40
+ reject(new Error("http-signaling: data channel did not open"));
41
+ }, timeoutMs);
42
+ function cleanup() {
43
+ clearTimeout(timer);
44
+ dc.removeEventListener?.("open", onOpen);
45
+ dc.removeEventListener?.("error", onError);
46
+ }
47
+ function onOpen() {
48
+ cleanup();
49
+ resolve();
50
+ }
51
+ function onError() {
52
+ cleanup();
53
+ reject(new Error("http-signaling: data channel error"));
54
+ }
55
+ dc.addEventListener("open", onOpen, { once: true });
56
+ dc.addEventListener("error", onError, { once: true });
57
+ });
58
+ }
59
+
60
+ /**
61
+ * POST one offer SDP to `url` and return the answer SDP string.
62
+ * Exported for callers managing their own RTCPeerConnection.
63
+ */
64
+ export async function signalViaHttp(url, offerSdp, fetchImpl = globalThis.fetch) {
65
+ const { sdp } = await signalSessionViaHttp(url, offerSdp, fetchImpl);
66
+ return sdp;
67
+ }
68
+
69
+ /**
70
+ * POST one offer SDP to `url` and return { sdp, session }:
71
+ * the answer SDP plus the session id for trickle candidates
72
+ * (signalCandidateViaHttp) and ICE restarts
73
+ * (signalRestartViaHttp). Servers without sessions return
74
+ * session: null.
75
+ */
76
+ export async function signalSessionViaHttp(url, offerSdp, fetchImpl = globalThis.fetch) {
77
+ if (typeof fetchImpl !== "function") {
78
+ throw new Error("http-signaling: fetch is not available");
79
+ }
80
+ const res = await fetchImpl(url, {
81
+ method: "POST",
82
+ headers: { "content-type": "application/json" },
83
+ body: JSON.stringify({ type: "offer", sdp: offerSdp }),
84
+ });
85
+ const body = await res.json().catch(() => null);
86
+ if (!res.ok || body?.type !== "answer" || typeof body?.sdp !== "string" || !body.sdp) {
87
+ throw new Error(`http-signaling: signaling POST failed (${res.status})`);
88
+ }
89
+ return { sdp: body.sdp, session: typeof body.session === "string" ? body.session : null };
90
+ }
91
+
92
+ async function postSignalingJson(fetchImpl, url, value) {
93
+ const res = await fetchImpl(url, {
94
+ method: "POST",
95
+ headers: { "content-type": "application/json" },
96
+ body: JSON.stringify(value),
97
+ });
98
+ const body = await res.json().catch(() => null);
99
+ if (!res.ok) {
100
+ throw new Error(`http-signaling: POST ${url} failed (${res.status})`);
101
+ }
102
+ return body;
103
+ }
104
+
105
+ /** Trickle one ICE candidate (or "" for end-of-candidates). */
106
+ export async function signalCandidateViaHttp(url, session, candidate, fetchImpl = globalThis.fetch) {
107
+ await postSignalingJson(fetchImpl, `${url}/candidate`, { session, candidate });
108
+ }
109
+
110
+ /** ICE-restart an existing session; returns the answer SDP. */
111
+ export async function signalRestartViaHttp(url, session, offerSdp, fetchImpl = globalThis.fetch) {
112
+ const body = await postSignalingJson(fetchImpl, `${url}/restart`, {
113
+ session,
114
+ type: "offer",
115
+ sdp: offerSdp,
116
+ });
117
+ if (body?.type !== "answer" || typeof body?.sdp !== "string" || !body.sdp) {
118
+ throw new Error("http-signaling: restart POST returned no answer");
119
+ }
120
+ return body.sdp;
121
+ }
122
+
123
+ /**
124
+ * Connect a browser gRPC client to a server exposing the
125
+ * HTTP/POST signaling endpoint and return a Channel for
126
+ * generated clients: `new EchoClient(await
127
+ * httpSignalingChannel("/grpc-dc/signal"))`.
128
+ * Options: iceServers, iceGatherTimeoutMs (default 10000),
129
+ * connectTimeoutMs (default 30000), label (default "grpc"),
130
+ * trickle (default false: skip the ICE-gathering wait and
131
+ * POST each candidate to <url>/candidate as it arrives),
132
+ * fetchImpl / RTCPeerConnectionImpl for tests and embedding.
133
+ * The returned Channel carries .peerConnection, .dataChannel
134
+ * and .signalingSession; call channel.closeSignaling() to
135
+ * tear the peer down, or channel.restartSignaling() for an
136
+ * ICE restart over the same session (candidates trickle the
137
+ * same way when trickle is on).
138
+ */
139
+ export async function httpSignalingChannel(url, options = {}) {
140
+ const {
141
+ iceServers = [],
142
+ iceGatherTimeoutMs = 10000,
143
+ connectTimeoutMs = 30000,
144
+ label = "grpc",
145
+ trickle = false,
146
+ fetchImpl = globalThis.fetch,
147
+ RTCPeerConnectionImpl = globalThis.RTCPeerConnection,
148
+ } = options;
149
+ if (typeof RTCPeerConnectionImpl !== "function") {
150
+ throw new Error("http-signaling: RTCPeerConnection is not available");
151
+ }
152
+ const pc = new RTCPeerConnectionImpl({ iceServers });
153
+ try {
154
+ const dc = pc.createDataChannel(label);
155
+ let session = null;
156
+ let candidateQueue = [];
157
+ let signalingChain = Promise.resolve();
158
+ let holdCandidates = false;
159
+ const sendCandidate = (candidate) => {
160
+ if (!trickle) return;
161
+ if (!session || holdCandidates) {
162
+ candidateQueue.push(candidate);
163
+ return;
164
+ }
165
+ signalingChain = signalingChain
166
+ .then(() => signalCandidateViaHttp(url, session, candidate, fetchImpl))
167
+ .catch(() => {});
168
+ };
169
+ pc.addEventListener?.("icecandidate", (event) => {
170
+ sendCandidate(event.candidate ? event.candidate.candidate : "");
171
+ });
172
+ if (typeof pc === "object" && "onicecandidate" in pc && !pc.addEventListener) {
173
+ pc.onicecandidate = (event) => {
174
+ sendCandidate(event.candidate ? event.candidate.candidate : "");
175
+ };
176
+ }
177
+ const offer = await pc.createOffer();
178
+ await pc.setLocalDescription(offer);
179
+ if (!trickle) await waitIceGathering(pc, iceGatherTimeoutMs);
180
+ const answer = await signalSessionViaHttp(url, pc.localDescription.sdp, fetchImpl);
181
+ session = answer.session;
182
+ await pc.setRemoteDescription({ type: "answer", sdp: answer.sdp });
183
+ if (trickle && session) {
184
+ const queued = candidateQueue;
185
+ candidateQueue = [];
186
+ for (const candidate of queued) sendCandidate(candidate);
187
+ await signalingChain;
188
+ }
189
+ await waitChannelOpen(dc, connectTimeoutMs);
190
+ const channel = new Channel(dc);
191
+ channel.peerConnection = pc;
192
+ channel.dataChannel = dc;
193
+ channel.signalingSession = session;
194
+ channel.closeSignaling = () => {
195
+ try { dc.close(); } catch { /* already closed */ }
196
+ try { pc.close(); } catch { /* already closed */ }
197
+ };
198
+ channel.restartSignaling = async () => {
199
+ if (!session) throw new Error("http-signaling: server returned no session");
200
+ holdCandidates = true;
201
+ candidateQueue = [];
202
+ try {
203
+ await signalingChain;
204
+ const restartOffer = await pc.createOffer({ iceRestart: true });
205
+ await pc.setLocalDescription(restartOffer);
206
+ if (!trickle) await waitIceGathering(pc, iceGatherTimeoutMs);
207
+ const restartAnswer = await signalRestartViaHttp(url, session, pc.localDescription.sdp, fetchImpl);
208
+ await pc.setRemoteDescription({ type: "answer", sdp: restartAnswer });
209
+ } finally {
210
+ holdCandidates = false;
211
+ }
212
+ if (trickle) {
213
+ const queued = candidateQueue;
214
+ candidateQueue = [];
215
+ for (const candidate of queued) sendCandidate(candidate);
216
+ await signalingChain;
217
+ }
218
+ };
219
+ return channel;
220
+ } catch (e) {
221
+ try { pc.close(); } catch { /* already closed */ }
222
+ throw e;
223
+ }
224
+ }
@@ -0,0 +1,212 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Node HTTP/POST signaling server: the server half of the
4
+ // browser signaling contract in signaling.js. Each POST creates
5
+ // a fresh Peer on the handler's shared PeerMux (one UDP socket
6
+ // for every session; options.mux supplies a process-wide one),
7
+ // answers the offer, returns the answer JSON immediately, then
8
+ // connects in the background and serves the browser's "grpc"
9
+ // DataChannel with the given generated Server. Non-trickle: the answer
10
+ // carries the peer's host candidates as created; configure
11
+ // peerOptions (localIps / stunServers / turnServers) when the
12
+ // host candidates in the answer are not reachable as-is.
13
+ // Auth and CORS belong to the host application: mount
14
+ // signalingHandler on your own HTTP server behind them, or use
15
+ // serveHttpSignaling for the standalone no-auth shape.
16
+
17
+ import { createServer } from "node:http";
18
+
19
+ import { PeerMux } from "../../webrtc/js/mux.js";
20
+
21
+ export const SIGNAL_PATH = "/grpc-dc/signal";
22
+ const MAX_SIGNAL_BODY = 1 << 20;
23
+
24
+ function sendJson(res, status, value) {
25
+ const body = JSON.stringify(value);
26
+ res.writeHead(status, {
27
+ "content-type": "application/json",
28
+ "content-length": Buffer.byteLength(body),
29
+ });
30
+ res.end(body);
31
+ }
32
+
33
+ async function readBody(req) {
34
+ const chunks = [];
35
+ let size = 0;
36
+ for await (const chunk of req) {
37
+ size += chunk.length;
38
+ if (size > MAX_SIGNAL_BODY) throw new Error("signaling body too large");
39
+ chunks.push(chunk);
40
+ }
41
+ return Buffer.concat(chunks).toString("utf8");
42
+ }
43
+
44
+ /**
45
+ * HTTP handler for the signaling contract. Returns true when
46
+ * the request path matched (and was handled), false otherwise,
47
+ * so hosts can mount it alongside their own routes:
48
+ * const signal = signalingHandler(grpcServer);
49
+ * createServer((req, res) => signal(req, res).then(h => ...));
50
+ */
51
+ export function signalingHandler(grpcServer, options = {}) {
52
+ const path = options.path ?? SIGNAL_PATH;
53
+ const peerOptions = options.peerOptions ?? {};
54
+ const onError = options.onError ?? ((e) => console.error("http-signaling:", e));
55
+ const peers = new Set();
56
+ const sessions = new Map(); // session id -> peer (trickle/restart)
57
+ // All session peers share one PeerMux UDP socket for the
58
+ // life of this handler (created lazily on first POST, or
59
+ // supplied by the host via options.mux so several signaling
60
+ // servers in one process share one socket; a host-supplied
61
+ // mux stays host-owned and is never closed here).
62
+ let muxPromise = options.mux ? Promise.resolve(options.mux) : null;
63
+ let ownsMux = !options.mux;
64
+ const getMux = () => {
65
+ if (!muxPromise) {
66
+ muxPromise = PeerMux.bind(options.muxBind ?? {});
67
+ }
68
+ return muxPromise;
69
+ };
70
+ const handler = async (req, res) => {
71
+ let pathname;
72
+ try {
73
+ pathname = new URL(req.url, "http://localhost").pathname;
74
+ } catch {
75
+ return false;
76
+ }
77
+ const isSignal = pathname === path;
78
+ const isCandidate = pathname === `${path}/candidate`;
79
+ const isRestart = pathname === `${path}/restart`;
80
+ if (!isSignal && !isCandidate && !isRestart) return false;
81
+ if (req.method !== "POST") {
82
+ sendJson(res, 405, { error: "method not allowed" });
83
+ return true;
84
+ }
85
+ let peer = null;
86
+ try {
87
+ const parsed = JSON.parse(await readBody(req));
88
+ if (isCandidate || isRestart) {
89
+ const sessionPeer = sessions.get(parsed?.session);
90
+ if (!sessionPeer) {
91
+ sendJson(res, 404, { error: "unknown session" });
92
+ return true;
93
+ }
94
+ if (isCandidate) {
95
+ if (typeof parsed?.candidate !== "string") {
96
+ sendJson(res, 400, { error: "expected {\"session\",\"candidate\":...}" });
97
+ return true;
98
+ }
99
+ sessionPeer.addRemoteCandidate(parsed.candidate);
100
+ sendJson(res, 200, { ok: true });
101
+ return true;
102
+ }
103
+ if (parsed?.type !== "offer" || typeof parsed?.sdp !== "string" || !parsed.sdp) {
104
+ sendJson(res, 400, { error: "expected {\"session\",\"type\":\"offer\",\"sdp\":...}" });
105
+ return true;
106
+ }
107
+ try {
108
+ const answer = sessionPeer.handleRestartOffer(parsed.sdp);
109
+ sendJson(res, 200, { type: "answer", sdp: answer, session: parsed.session });
110
+ } catch {
111
+ sendJson(res, 400, { error: "invalid restart offer SDP" });
112
+ }
113
+ return true;
114
+ }
115
+ if (parsed?.type !== "offer" || typeof parsed?.sdp !== "string" || !parsed.sdp) {
116
+ sendJson(res, 400, { error: "expected {\"type\":\"offer\",\"sdp\":...}" });
117
+ return true;
118
+ }
119
+ peer = await (await getMux()).createPeer(peerOptions);
120
+ peers.add(peer);
121
+ let answer;
122
+ try {
123
+ answer = peer.handleOffer(parsed.sdp);
124
+ } catch {
125
+ await peer.close().catch(() => {});
126
+ peers.delete(peer);
127
+ peer = null;
128
+ sendJson(res, 400, { error: "invalid offer SDP" });
129
+ return true;
130
+ }
131
+ const session = globalThis.crypto?.randomUUID?.() ?? `s${Date.now()}-${sessions.size}`;
132
+ sessions.set(session, peer);
133
+ sendJson(res, 200, { type: "answer", sdp: answer, session });
134
+ // Background: run ICE/DTLS, then serve the grpc channel.
135
+ const serving = peer;
136
+ void (async () => {
137
+ try {
138
+ const endpoint = await serving.connect();
139
+ endpoint.onchannel = (channel) => {
140
+ if ((channel.label ?? "grpc") === "grpc") {
141
+ grpcServer.serve(channel);
142
+ // One signaling POST owns one peer: when its grpc
143
+ // channel closes, tear the peer (socket, timers)
144
+ // down with it instead of leaking it per request.
145
+ channel.addEventListener?.(
146
+ "close",
147
+ () => {
148
+ peers.delete(serving);
149
+ sessions.delete(session);
150
+ void serving.close().catch(() => {});
151
+ },
152
+ { once: true },
153
+ );
154
+ }
155
+ };
156
+ } catch (e) {
157
+ onError(e);
158
+ sessions.delete(session);
159
+ await serving.close().catch(() => {});
160
+ }
161
+ })();
162
+ return true;
163
+ } catch (e) {
164
+ if (peer) {
165
+ peers.delete(peer);
166
+ await peer.close().catch(() => {});
167
+ }
168
+ if (!res.headersSent) sendJson(res, 500, { error: "signaling failed" });
169
+ return true;
170
+ }
171
+ };
172
+ // Hosts/tests can tear down every peer created so far (each
173
+ // grpc channel close already closes its own peer; this is
174
+ // the bulk shutdown path). Also exposed as closeSignaling
175
+ // on serveHttpSignaling's returned server.
176
+ handler.closePeers = async () => {
177
+ const all = [...peers];
178
+ peers.clear();
179
+ sessions.clear();
180
+ await Promise.all(all.map((p) => p.close().catch(() => {})));
181
+ if (ownsMux && muxPromise) {
182
+ const mux = await muxPromise.catch(() => null);
183
+ muxPromise = null;
184
+ try { mux?.close(); } catch { /* already closed */ }
185
+ }
186
+ };
187
+ handler.peers = peers;
188
+ // The shared PeerMux every session peer was created on
189
+ // (host-supplied via options.mux, or bound lazily here).
190
+ handler.getMux = getMux;
191
+ return handler;
192
+ }
193
+
194
+ /**
195
+ * Standalone signaling HTTP server on host:port (defaults
196
+ * 127.0.0.1:8080). Requests outside the signaling path get a
197
+ * 404 JSON body. Returns the node:http Server (await its
198
+ * "listening" event; close() to stop). Host applications that
199
+ * need auth/CORS should mount signalingHandler instead.
200
+ */
201
+ export function serveHttpSignaling(grpcServer, options = {}) {
202
+ const handler = signalingHandler(grpcServer, options);
203
+ const server = createServer((req, res) => {
204
+ void handler(req, res).then((handled) => {
205
+ if (!handled && !res.headersSent) sendJson(res, 404, { error: "not found" });
206
+ });
207
+ });
208
+ server.closeSignaling = handler.closePeers;
209
+ server.getSignalingMux = handler.getMux;
210
+ server.listen(options.port ?? 8080, options.host ?? "127.0.0.1");
211
+ return server;
212
+ }