grpc-dc 0.40.0 → 0.42.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,285 @@
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
+ // Rendezvous auth tokens: base64url(protobuf claims) + "." +
73
+ // base64url(HMAC-SHA256(secret, claims)). Claims wire layout
74
+ // (protobuf, no schema dependency): 1 sub, 2 iss, 3 aud
75
+ // (strings); 4 exp, 5 nbf, 6 iat (varint seconds); 7 scopes
76
+ // (repeated string); 8 jti (string). The same layout is
77
+ // implemented in the Go and Rust rendezvous servers, so one
78
+ // token verifies on every stack. Rendezvous-only by design:
79
+ // no protoc plugin option.
80
+
81
+ function b64urlEncode(bytes) {
82
+ let bin = "";
83
+ for (const b of bytes) bin += String.fromCharCode(b);
84
+ return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
85
+ }
86
+
87
+ function b64urlDecode(text) {
88
+ const bin = atob(text.replaceAll("-", "+").replaceAll("_", "/"));
89
+ const out = new Uint8Array(bin.length);
90
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
91
+ return out;
92
+ }
93
+
94
+ function pushVarint(out, value) {
95
+ let v = BigInt(value);
96
+ for (;;) {
97
+ const b = Number(v & 0x7fn);
98
+ v >>= 7n;
99
+ if (v === 0n) { out.push(b); return; }
100
+ out.push(b | 0x80);
101
+ }
102
+ }
103
+
104
+ function pushLenField(out, field, bytes) {
105
+ pushVarint(out, (field << 3) | 2);
106
+ pushVarint(out, bytes.length);
107
+ for (const b of bytes) out.push(b);
108
+ }
109
+
110
+ function pushVarintField(out, field, value) {
111
+ pushVarint(out, (field << 3) | 0);
112
+ pushVarint(out, value);
113
+ }
114
+
115
+ /** Serialize rendezvous claims to protobuf wire bytes. */
116
+ export function encodeRendezvousClaims(claims) {
117
+ const enc = new TextEncoder();
118
+ const out = [];
119
+ if (claims.sub) pushLenField(out, 1, enc.encode(claims.sub));
120
+ if (claims.iss) pushLenField(out, 2, enc.encode(claims.iss));
121
+ if (claims.aud) pushLenField(out, 3, enc.encode(claims.aud));
122
+ if (claims.exp) pushVarintField(out, 4, claims.exp);
123
+ if (claims.nbf) pushVarintField(out, 5, claims.nbf);
124
+ if (claims.iat) pushVarintField(out, 6, claims.iat);
125
+ for (const scope of claims.scopes ?? []) pushLenField(out, 7, enc.encode(scope));
126
+ if (claims.jti) pushLenField(out, 8, enc.encode(claims.jti));
127
+ return new Uint8Array(out);
128
+ }
129
+
130
+ /** Parse rendezvous claims from protobuf wire bytes. */
131
+ export function decodeRendezvousClaims(bytes) {
132
+ const dec = new TextDecoder();
133
+ const claims = { scopes: [] };
134
+ let pos = 0;
135
+ const readVarint = () => {
136
+ let v = 0n;
137
+ let shift = 0n;
138
+ for (;;) {
139
+ if (pos >= bytes.length) throw new Error("truncated varint");
140
+ const b = bytes[pos++];
141
+ v |= BigInt(b & 0x7f) << shift;
142
+ if ((b & 0x80) === 0) return v;
143
+ shift += 7n;
144
+ }
145
+ };
146
+ while (pos < bytes.length) {
147
+ const tag = Number(readVarint());
148
+ const field = tag >> 3;
149
+ const wire = tag & 7;
150
+ if (wire === 2) {
151
+ const len = Number(readVarint());
152
+ const slice = bytes.slice(pos, pos + len);
153
+ pos += len;
154
+ if (field === 1) claims.sub = dec.decode(slice);
155
+ else if (field === 2) claims.iss = dec.decode(slice);
156
+ else if (field === 3) claims.aud = dec.decode(slice);
157
+ else if (field === 7) claims.scopes.push(dec.decode(slice));
158
+ else if (field === 8) claims.jti = dec.decode(slice);
159
+ } else if (wire === 0) {
160
+ const v = Number(readVarint());
161
+ if (field === 4) claims.exp = v;
162
+ else if (field === 5) claims.nbf = v;
163
+ else if (field === 6) claims.iat = v;
164
+ } else {
165
+ throw new Error(`unsupported wire type ${wire}`);
166
+ }
167
+ }
168
+ return claims;
169
+ }
170
+
171
+ async function hmacKey(secret) {
172
+ const raw = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
173
+ return crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, [
174
+ "sign",
175
+ "verify",
176
+ ]);
177
+ }
178
+
179
+ /** Mint a rendezvous token for `claims` under `secret`. */
180
+ export async function issueRendezvousToken(secret, claims) {
181
+ const body = encodeRendezvousClaims(claims);
182
+ const key = await hmacKey(secret);
183
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, body));
184
+ return `${b64urlEncode(body)}.${b64urlEncode(sig)}`;
185
+ }
186
+
187
+ /**
188
+ * Verify a rendezvous token and return its claims. Throws on
189
+ * a malformed token, a bad signature, expiry (exp), a
190
+ * not-yet-valid token (nbf), or an issuer/audience mismatch
191
+ * when options.issuer / options.audience are set.
192
+ * options: { issuer, audience, nowSeconds }
193
+ */
194
+ export async function verifyRendezvousToken(secret, token, options = {}) {
195
+ const parts = String(token).split(".");
196
+ if (parts.length !== 2) throw new Error("malformed rendezvous token");
197
+ const body = b64urlDecode(parts[0]);
198
+ const sig = b64urlDecode(parts[1]);
199
+ const key = await hmacKey(secret);
200
+ const ok = await crypto.subtle.verify("HMAC", key, sig, body);
201
+ if (!ok) throw new Error("bad rendezvous token signature");
202
+ const claims = decodeRendezvousClaims(body);
203
+ const now = options.nowSeconds ?? Math.floor(Date.now() / 1000);
204
+ if (claims.exp && now >= claims.exp) throw new Error("rendezvous token expired");
205
+ if (claims.nbf && now < claims.nbf) throw new Error("rendezvous token not yet valid");
206
+ if (options.issuer && claims.iss !== options.issuer) {
207
+ throw new Error("rendezvous token issuer mismatch");
208
+ }
209
+ if (options.audience && claims.aud !== options.audience) {
210
+ throw new Error("rendezvous token audience mismatch");
211
+ }
212
+ return claims;
213
+ }
214
+
215
+ /**
216
+ * Fetch a rendezvous descriptor JSON from `url` (HTTPS in
217
+ * production; the well-known location
218
+ * /.well-known/grpc-dc-rendezvous.json with a short
219
+ * Cache-Control max-age is the rotation convention — see
220
+ * SPEC-WEBRTC.md). Returns the parsed descriptor object for
221
+ * rendezvousChannel.
222
+ *
223
+ * options: { fetchImpl }
224
+ */
225
+ export async function fetchRendezvousDescriptor(url, options = {}) {
226
+ const fetchImpl = options.fetchImpl ?? fetch;
227
+ const res = await fetchImpl(url, { headers: { accept: "application/json" } });
228
+ if (!res.ok) throw new Error(`rendezvous descriptor fetch failed: ${res.status}`);
229
+ const descriptor = await res.json();
230
+ for (const field of ["host", "port", "iceUfrag", "icePwd", "fingerprint"]) {
231
+ if (descriptor[field] === undefined) {
232
+ throw new Error(`rendezvous descriptor missing ${field}`);
233
+ }
234
+ }
235
+ return descriptor;
236
+ }
237
+
238
+ /**
239
+ * Dial a rendezvous endpoint and return a ready Channel.
240
+ * Waits for the "grpc" DataChannel to open, matching
241
+ * httpSignalingChannel's ready-to-use contract.
242
+ *
243
+ * options: { iceServers, iceTransportPolicy, timeoutMs, label,
244
+ * token, getToken }
245
+ * iceTransportPolicy "relay" (with TURN iceServers) is the
246
+ * symmetric-NAT shape: the browser nominates its relay
247
+ * candidate against the listener's published address.
248
+ */
249
+ export async function rendezvousChannel(descriptor, options = {}) {
250
+ const pc = new RTCPeerConnection({
251
+ iceServers: options.iceServers,
252
+ iceTransportPolicy: options.iceTransportPolicy,
253
+ });
254
+ const dc = pc.createDataChannel(options.label ?? "grpc");
255
+ try {
256
+ await pc.setRemoteDescription({
257
+ type: "offer",
258
+ sdp: synthesizeRendezvousOffer(descriptor),
259
+ });
260
+ const answer = await pc.createAnswer();
261
+ await pc.setLocalDescription(answer);
262
+ await waitRendezvousChannelOpen(dc, options.timeoutMs ?? 15000);
263
+ } catch (e) {
264
+ pc.close();
265
+ throw e;
266
+ }
267
+ const base = new Channel(dc);
268
+ base.peerConnection = pc;
269
+ base.dataChannel = dc;
270
+ base.closeRendezvous = () => pc.close();
271
+ // options.token (a string) or options.getToken (sync/async
272
+ // () => string) attaches `authorization: Bearer <token>` to
273
+ // every call on the returned channel; explicit per-call
274
+ // metadata still wins.
275
+ const getToken = options.getToken ?? (options.token ? () => options.token : null);
276
+ if (getToken === null) return base;
277
+ const channel = base.withMetadata(async () => {
278
+ const token = await getToken();
279
+ return token ? { authorization: `Bearer ${token}` } : {};
280
+ });
281
+ channel.peerConnection = pc;
282
+ channel.dataChannel = dc;
283
+ channel.closeRendezvous = () => pc.close();
284
+ return channel;
285
+ }
@@ -0,0 +1,56 @@
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
+ import { verifyRendezvousToken } from "./rendezvous.js";
13
+
14
+ export { RendezvousListener } from "../../webrtc/js/rendezvous.js";
15
+
16
+ /**
17
+ * Serve this gRPC Server to rendezvous browsers.
18
+ *
19
+ * options: { address, port, family, localIps, iceUfrag,
20
+ * icePwd, certificate, onError, consentIntervalMs,
21
+ * consentExpiryMs, mux } — fix iceUfrag/icePwd/
22
+ * certificate and the published descriptor stays stable
23
+ * across restarts; ephemeral values rotate per process.
24
+ * With `mux` (a PeerMux, e.g. the one a signalingHandler
25
+ * uses via options.mux), the listener shares the mux's UDP
26
+ * socket instead of binding its own: one port serves both
27
+ * HTTP-signaled and rendezvous browsers.
28
+ * Returns the RendezvousListener (call .descriptor(host)
29
+ * and .close()).
30
+ */
31
+ export async function serveRendezvous(grpcServer, options = {}) {
32
+ // options.auth {secret, scopes, issuer, audience} requires a
33
+ // rendezvous bearer token on every call (see rendezvous.js):
34
+ // bad/missing/expired -> UNAUTHENTICATED, under-scoped ->
35
+ // PERMISSION_DENIED, verified claims on ctx.claims.
36
+ if (options.auth) {
37
+ const { secret, scopes, issuer, audience } = options.auth;
38
+ grpcServer.requireRendezvousAuth(
39
+ (token) => verifyRendezvousToken(secret, token, { issuer, audience }),
40
+ scopes ?? {},
41
+ );
42
+ }
43
+ const listener = await RendezvousListener.bind({
44
+ ...options,
45
+ onChannel: (channel, peer) => {
46
+ if (channel.label === "grpc") {
47
+ grpcServer.serve(channel);
48
+ channel.onclose = () => peer.close().catch(() => {});
49
+ } else {
50
+ channel.close();
51
+ }
52
+ },
53
+ });
54
+ grpcServer.closeRendezvous = () => listener.close();
55
+ return listener;
56
+ }
package/src/server.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // on an endpoint and dispatches HEADERS by path.
5
5
 
6
6
  import {
7
+ StatusCode,
7
8
  StatusError,
8
9
  StatusName,
9
10
  parseTimeout,
@@ -36,6 +37,8 @@ async function firstRequest(requests) {
36
37
 
37
38
  export class Server {
38
39
  #methods = new Map();
40
+ #authVerifier = null;
41
+ #authScopes = {};
39
42
 
40
43
  addService(definition) {
41
44
  for (const [name, method] of Object.entries(definition.methods)) {
@@ -47,6 +50,21 @@ export class Server {
47
50
  return this;
48
51
  }
49
52
 
53
+ /**
54
+ * Require rendezvous bearer auth on every call: `verifier`
55
+ * is an async (token) => claims function that throws on a
56
+ * bad, missing or expired token; `scopes` maps a method path
57
+ * to the scopes it requires (no entry = any authenticated
58
+ * caller). Verified claims land on ctx.claims. Installed by
59
+ * serveRendezvous when options.auth is set; rendezvous-only
60
+ * by design (no protoc plugin option).
61
+ */
62
+ requireRendezvousAuth(verifier, scopes = {}) {
63
+ this.#authVerifier = verifier;
64
+ this.#authScopes = scopes ?? {};
65
+ return this;
66
+ }
67
+
50
68
  /** Attach to an endpoint (or raw channel, wrapped with even parity). */
51
69
  serve(dcOrEndpoint, options) {
52
70
  const endpoint =
@@ -64,6 +82,32 @@ export class Server {
64
82
  throw StatusError.unimplemented(`unknown method ${path}`);
65
83
  }
66
84
  const metadata = headers.metadata ?? {};
85
+ let claims = null;
86
+ if (this.#authVerifier !== null) {
87
+ const header = metadata.authorization ?? "";
88
+ const match = /^Bearer (.+)$/.exec(header);
89
+ if (!match) {
90
+ throw new StatusError(StatusCode.UNAUTHENTICATED, "missing bearer token");
91
+ }
92
+ try {
93
+ claims = await this.#authVerifier(match[1]);
94
+ } catch (e) {
95
+ throw new StatusError(
96
+ StatusCode.UNAUTHENTICATED,
97
+ e instanceof Error ? e.message : "invalid bearer token",
98
+ );
99
+ }
100
+ const required = this.#authScopes[path] ?? [];
101
+ const granted = new Set(claims?.scopes ?? []);
102
+ for (const scope of required) {
103
+ if (!granted.has(scope)) {
104
+ throw new StatusError(
105
+ StatusCode.PERMISSION_DENIED,
106
+ `missing required scope ${scope}`,
107
+ );
108
+ }
109
+ }
110
+ }
67
111
  const timeoutMs = parseTimeout(metadata["grpc-timeout"]);
68
112
  const deadline = timeoutMs === null ? null : Date.now() + timeoutMs;
69
113
  // Initial/trailing metadata the handler accumulates via
@@ -91,6 +135,7 @@ export class Server {
91
135
  const ctx = {
92
136
  path,
93
137
  metadata,
138
+ claims,
94
139
  service: method.service,
95
140
  method: method.method,
96
141
  deadline,
@@ -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
+ }