grpc-dc 0.41.0 → 0.43.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.
package/index.js CHANGED
@@ -51,9 +51,13 @@ export {
51
51
  signalViaHttp,
52
52
  } from "./src/signaling.js";
53
53
  export {
54
+ decodeRendezvousClaims,
55
+ encodeRendezvousClaims,
54
56
  fetchRendezvousDescriptor,
57
+ issueRendezvousToken,
55
58
  rendezvousChannel,
56
59
  synthesizeRendezvousOffer,
60
+ verifyRendezvousToken,
57
61
  } from "./src/rendezvous.js";
58
62
  // The rendezvous server (src/rendezvous_server.js) is Node-only
59
63
  // (node:dgram via webrtc/js/rendezvous.js) and is not re-exported
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grpc-dc",
3
- "version": "0.41.0",
3
+ "version": "0.43.0",
4
4
  "description": "gRPC in the browser over WebRTC DataChannels: dependency-free generated gRPC clients & servers for JavaScript \u2014 no grpc-web proxy, no external runtime",
5
5
  "keywords": [
6
6
  "grpc",
@@ -34,7 +34,8 @@
34
34
  "./rendezvous": "./src/rendezvous.js",
35
35
  "./rendezvous_server": "./src/rendezvous_server.js",
36
36
  "./http2": "./src/http2.js",
37
- "./eventbus_gitlog": "./src/eventbus_gitlog.js"
37
+ "./eventbus_gitlog": "./src/eventbus_gitlog.js",
38
+ "./stdio": "./src/stdio.js"
38
39
  },
39
40
  "bin": {
40
41
  "protoc-gen-grpc-dc-js": "plugin/protoc-gen-grpc-dc-js.mjs",
package/src/channel.js CHANGED
@@ -90,6 +90,7 @@ export class Channel {
90
90
  #endpoint;
91
91
  #traces = new Map();
92
92
  #traceContext = null;
93
+ #metadataProvider = null;
93
94
 
94
95
  // A Channel view sharing this endpoint whose outbound spans are
95
96
  // parented to traceContext (a server span context from
@@ -99,6 +100,19 @@ export class Channel {
99
100
  withTraceContext(traceContext) {
100
101
  const ch = new Channel(this.#endpoint);
101
102
  ch.#traceContext = traceContext ?? null;
103
+ ch.#metadataProvider = this.#metadataProvider;
104
+ return ch;
105
+ }
106
+
107
+ // A Channel view sharing this endpoint that merges metadata
108
+ // from `provider` (a map, or a function returning a map or a
109
+ // promise of one) into every call. Explicit per-call metadata
110
+ // still wins. Used by rendezvousChannel to attach the
111
+ // authorization bearer token per call.
112
+ withMetadata(provider) {
113
+ const ch = new Channel(this.#endpoint);
114
+ ch.#traceContext = this.#traceContext;
115
+ ch.#metadataProvider = provider ?? null;
102
116
  return ch;
103
117
  }
104
118
 
@@ -113,6 +127,13 @@ export class Channel {
113
127
  }
114
128
 
115
129
  async #open(path, metadata, timeout, signal = null) {
130
+ if (this.#metadataProvider !== null) {
131
+ const provided =
132
+ typeof this.#metadataProvider === "function"
133
+ ? await this.#metadataProvider()
134
+ : this.#metadataProvider;
135
+ if (provided) metadata = { ...provided, ...metadata };
136
+ }
116
137
  let deadline = null;
117
138
  if (timeout !== undefined && timeout !== null) {
118
139
  deadline = Date.now() + timeout;
package/src/http2.js CHANGED
@@ -27,6 +27,9 @@ export class Http2DataChannel {
27
27
  // still follows the LPM compressed flag.
28
28
  #compressOut = new Map();
29
29
  #decompressIn = new Map();
30
+ // HTTP/2 leg counters for LinkStats: translated
31
+ // HEADERS/DATA frames in each direction plus streams.
32
+ #stats = { framesSent: 0, framesReceived: 0, streamsOpened: 0 };
30
33
 
31
34
  constructor(authority, { secure = false, ...connectOptions } = {}) {
32
35
  this.readyState = "open";
@@ -78,9 +81,12 @@ export class Http2DataChannel {
78
81
  ...metadata,
79
82
  });
80
83
  this.#streams.set(id, stream);
84
+ this.#stats.streamsOpened += 1;
85
+ this.#stats.framesSent += 1;
81
86
  this.#buffers.set(id, Buffer.alloc(0));
82
87
  this.#compressOut.set(id, metadata["grpc-encoding"] === "gzip");
83
88
  stream.on("response", (headers, flags) => {
89
+ this.#stats.framesReceived += 1;
84
90
  this.#decompressIn.set(id, headers["grpc-encoding"] === "gzip");
85
91
  const trailersOnly =
86
92
  (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) !== 0 && headers["grpc-status"] !== undefined;
@@ -102,6 +108,7 @@ export class Http2DataChannel {
102
108
  }));
103
109
  });
104
110
  stream.on("data", (chunk) => {
111
+ this.#stats.framesReceived += 1;
105
112
  let buf = Buffer.concat([this.#buffers.get(id), chunk]);
106
113
  while (buf.length >= 5) {
107
114
  const len = buf.readUInt32BE(1);
@@ -125,6 +132,7 @@ export class Http2DataChannel {
125
132
  this.#emitFrame(FrameType.RST, id, JSON.stringify({ code: 8, message: "h2 stream error" }));
126
133
  });
127
134
  } else if (frame.type === FrameType.DATA) {
135
+ this.#stats.framesSent += 1;
128
136
  const stream = this.#streams.get(id);
129
137
  if (stream) {
130
138
  let payload = frame.payload;
@@ -146,6 +154,11 @@ export class Http2DataChannel {
146
154
  }
147
155
  }
148
156
 
157
+ /** HTTP/2 leg counter snapshot (LinkStats). */
158
+ stats() {
159
+ return { ...this.#stats };
160
+ }
161
+
149
162
  close() {
150
163
  this.session.close();
151
164
  }
@@ -153,5 +166,8 @@ export class Http2DataChannel {
153
166
 
154
167
  /** Channel over HTTP/2 to an official gRPC server. */
155
168
  export function http2Channel(authority, options) {
156
- return new Channel(new Http2DataChannel(authority, options));
169
+ const dc = new Http2DataChannel(authority, options);
170
+ const channel = new Channel(dc);
171
+ channel.http2Stats = () => dc.stats();
172
+ return channel;
157
173
  }
@@ -1,7 +1,7 @@
1
1
  // Generated code: use without restriction (see GENERATED-CODE-LICENSE.md).
2
2
  // @generated by protoc-gen-grpc-dc-js. DO NOT EDIT.
3
3
  // source: kafka.proto
4
- import { MetadataRequest, MetadataResponse, OpenProducerRequest, OpenProducerResponse, CloseProducerRequest, CloseProducerResponse, EndTransactionRequest, EndTransactionResponse, ProduceRequest, ProduceResponse, ConsumeRequest, ConsumeResponse, GroupSubscribeRequest, GroupSubscribeResponse, ListOffsetsRequest, ListOffsetsResponse, CommitOffsetRequest, CommitOffsetResponse, FetchOffsetRequest, FetchOffsetResponse, CreateTopicsRequest, CreateTopicsResponse, DeleteTopicsRequest, DeleteTopicsResponse, DescribeConfigsRequest, DescribeConfigsResponse, AlterConfigsRequest, AlterConfigsResponse, CreatePartitionsRequest, CreatePartitionsResponse, DeleteRecordsRequest, DeleteRecordsResponse, ListGroupsRequest, ListGroupsResponse, DescribeGroupsRequest, DescribeGroupsResponse, DeleteGroupsRequest, DeleteGroupsResponse, DeleteGroupOffsetsRequest, DeleteGroupOffsetsResponse, DescribeAclsRequest, DescribeAclsResponse, CreateAclsRequest, CreateAclsResponse, DeleteAclsRequest, DeleteAclsResponse, ListTransactionsRequest, ListTransactionsResponse, DescribeTransactionsRequest, DescribeTransactionsResponse, OpenShareGroupRequest, OpenShareGroupResponse, SharePollRequest, SharePollResponse, ShareAckRequest, ShareAckResponse, CloseShareGroupRequest, CloseShareGroupResponse } from "./kafka_pb.js";
4
+ import { MetadataRequest, MetadataResponse, OpenProducerRequest, OpenProducerResponse, CloseProducerRequest, CloseProducerResponse, EndTransactionRequest, EndTransactionResponse, ProduceRequest, ProduceResponse, ConsumeRequest, ConsumeResponse, GroupSubscribeRequest, GroupSubscribeResponse, ListOffsetsRequest, ListOffsetsResponse, CommitOffsetRequest, CommitOffsetResponse, FetchOffsetRequest, FetchOffsetResponse, CreateTopicsRequest, CreateTopicsResponse, DeleteTopicsRequest, DeleteTopicsResponse, DescribeConfigsRequest, DescribeConfigsResponse, AlterConfigsRequest, AlterConfigsResponse, CreatePartitionsRequest, CreatePartitionsResponse, DeleteRecordsRequest, DeleteRecordsResponse, ListGroupsRequest, ListGroupsResponse, DescribeGroupsRequest, DescribeGroupsResponse, DeleteGroupsRequest, DeleteGroupsResponse, DeleteGroupOffsetsRequest, DeleteGroupOffsetsResponse, DescribeAclsRequest, DescribeAclsResponse, CreateAclsRequest, CreateAclsResponse, DeleteAclsRequest, DeleteAclsResponse, ListTransactionsRequest, ListTransactionsResponse, DescribeTransactionsRequest, DescribeTransactionsResponse, OpenShareGroupRequest, OpenShareGroupResponse, SharePollRequest, SharePollResponse, ShareAckRequest, ShareAckResponse, CloseShareGroupRequest, CloseShareGroupResponse, DescribeShareGroupsRequest, DescribeShareGroupsResponse } from "./kafka_pb.js";
5
5
 
6
6
  export class KafkaClient {
7
7
  #channel;
@@ -93,6 +93,9 @@ export class KafkaClient {
93
93
  async closeShareGroup(request, options) {
94
94
  return this.#channel.unary("/grpcdc.kafka.v1.Kafka/CloseShareGroup", request, CloseShareGroupRequest, CloseShareGroupResponse, options);
95
95
  }
96
+ async describeShareGroups(request, options) {
97
+ return this.#channel.unary("/grpcdc.kafka.v1.Kafka/DescribeShareGroups", request, DescribeShareGroupsRequest, DescribeShareGroupsResponse, options);
98
+ }
96
99
  }
97
100
 
98
101
  export function createKafkaService(handlers) {
@@ -128,6 +131,7 @@ export function createKafkaService(handlers) {
128
131
  SharePoll: { path: "/grpcdc.kafka.v1.Kafka/SharePoll", kind: "unary", requestType: SharePollRequest, responseType: SharePollResponse, handler: handlers.sharePoll },
129
132
  ShareAck: { path: "/grpcdc.kafka.v1.Kafka/ShareAck", kind: "unary", requestType: ShareAckRequest, responseType: ShareAckResponse, handler: handlers.shareAck },
130
133
  CloseShareGroup: { path: "/grpcdc.kafka.v1.Kafka/CloseShareGroup", kind: "unary", requestType: CloseShareGroupRequest, responseType: CloseShareGroupResponse, handler: handlers.closeShareGroup },
134
+ DescribeShareGroups: { path: "/grpcdc.kafka.v1.Kafka/DescribeShareGroups", kind: "unary", requestType: DescribeShareGroupsRequest, responseType: DescribeShareGroupsResponse, handler: handlers.describeShareGroups },
131
135
  },
132
136
  };
133
137
  }
@@ -51,6 +51,11 @@ const UNARY = {
51
51
  DeleteAcls: "DeleteAclsResponse",
52
52
  ListTransactions: "ListTransactionsResponse",
53
53
  DescribeTransactions: "DescribeTransactionsResponse",
54
+ DescribeShareGroups: "DescribeShareGroupsResponse",
55
+ OpenShareGroup: "OpenShareGroupResponse",
56
+ SharePoll: "SharePollResponse",
57
+ ShareAck: "ShareAckResponse",
58
+ CloseShareGroup: "CloseShareGroupResponse",
54
59
  };
55
60
 
56
61
  const STREAMS = {
@@ -174,4 +179,9 @@ export class KafkaNativeClient {
174
179
  async deleteAcls(request) { return this.#call("DeleteAcls", request); }
175
180
  async listTransactions(request) { return this.#call("ListTransactions", request); }
176
181
  async describeTransactions(request) { return this.#call("DescribeTransactions", request); }
182
+ async describeShareGroups(request) { return this.#call("DescribeShareGroups", request); }
183
+ async openShareGroup(request) { return this.#call("OpenShareGroup", request); }
184
+ async sharePoll(request) { return this.#call("SharePoll", request); }
185
+ async shareAck(request) { return this.#call("ShareAck", request); }
186
+ async closeShareGroup(request) { return this.#call("CloseShareGroup", request); }
177
187
  }
package/src/kafka_pb.js CHANGED
@@ -2749,3 +2749,140 @@ export class CloseShareGroupResponse {
2749
2749
  }
2750
2750
  }
2751
2751
 
2752
+ export class ShareGroupMember {
2753
+ constructor({ memberId = "", memberEpoch = 0, clientId = "", clientHost = "", subscribedTopics = [], assignment = [] } = {}) {
2754
+ this.memberId = memberId;
2755
+ this.memberEpoch = memberEpoch;
2756
+ this.clientId = clientId;
2757
+ this.clientHost = clientHost;
2758
+ this.subscribedTopics = subscribedTopics;
2759
+ this.assignment = assignment;
2760
+ this.unknownFields = new Uint8Array(0);
2761
+ }
2762
+ static encode(msg) {
2763
+ const out = [];
2764
+ putStringField(out, 1, msg.memberId);
2765
+ putVarintField(out, 2, BigInt(msg.memberEpoch));
2766
+ putStringField(out, 3, msg.clientId);
2767
+ putStringField(out, 4, msg.clientHost);
2768
+ if (msg.subscribedTopics) for (const v of msg.subscribedTopics) putBytesField(out, 5, new TextEncoder().encode(v));
2769
+ if (msg.assignment) for (const v of msg.assignment) putBytesField(out, 6, TopicPartition.encode(v));
2770
+ putRaw(out, msg.unknownFields);
2771
+ return new Uint8Array(out);
2772
+ }
2773
+ static decode(bytes) {
2774
+ const msg = new ShareGroupMember();
2775
+ const reader = new Reader(bytes);
2776
+ let f;
2777
+ while ((f = reader.field()) !== null) {
2778
+ const [num, wire, value, raw] = f;
2779
+ switch (num) {
2780
+ case 1: msg.memberId = new TextDecoder().decode(value); break;
2781
+ case 2: msg.memberEpoch = Number(BigInt.asIntN(32, value)); break;
2782
+ case 3: msg.clientId = new TextDecoder().decode(value); break;
2783
+ case 4: msg.clientHost = new TextDecoder().decode(value); break;
2784
+ case 5: msg.subscribedTopics.push(new TextDecoder().decode(value)); break;
2785
+ case 6: msg.assignment.push(TopicPartition.decode(value)); break;
2786
+ default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
2787
+ }
2788
+ }
2789
+ return msg;
2790
+ }
2791
+ }
2792
+
2793
+ export class ShareGroupDescription {
2794
+ constructor({ groupId = "", errorCode = 0, state = "", groupEpoch = 0, assignmentEpoch = 0, members = [] } = {}) {
2795
+ this.groupId = groupId;
2796
+ this.errorCode = errorCode;
2797
+ this.state = state;
2798
+ this.groupEpoch = groupEpoch;
2799
+ this.assignmentEpoch = assignmentEpoch;
2800
+ this.members = members;
2801
+ this.unknownFields = new Uint8Array(0);
2802
+ }
2803
+ static encode(msg) {
2804
+ const out = [];
2805
+ putStringField(out, 1, msg.groupId);
2806
+ putVarintField(out, 2, BigInt(msg.errorCode));
2807
+ putStringField(out, 3, msg.state);
2808
+ putVarintField(out, 4, BigInt(msg.groupEpoch));
2809
+ putVarintField(out, 5, BigInt(msg.assignmentEpoch));
2810
+ if (msg.members) for (const v of msg.members) putBytesField(out, 6, ShareGroupMember.encode(v));
2811
+ putRaw(out, msg.unknownFields);
2812
+ return new Uint8Array(out);
2813
+ }
2814
+ static decode(bytes) {
2815
+ const msg = new ShareGroupDescription();
2816
+ const reader = new Reader(bytes);
2817
+ let f;
2818
+ while ((f = reader.field()) !== null) {
2819
+ const [num, wire, value, raw] = f;
2820
+ switch (num) {
2821
+ case 1: msg.groupId = new TextDecoder().decode(value); break;
2822
+ case 2: msg.errorCode = Number(BigInt.asIntN(32, value)); break;
2823
+ case 3: msg.state = new TextDecoder().decode(value); break;
2824
+ case 4: msg.groupEpoch = Number(BigInt.asIntN(32, value)); break;
2825
+ case 5: msg.assignmentEpoch = Number(BigInt.asIntN(32, value)); break;
2826
+ case 6: msg.members.push(ShareGroupMember.decode(value)); break;
2827
+ default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
2828
+ }
2829
+ }
2830
+ return msg;
2831
+ }
2832
+ }
2833
+
2834
+ export class DescribeShareGroupsRequest {
2835
+ constructor({ groupIds = [] } = {}) {
2836
+ this.groupIds = groupIds;
2837
+ this.unknownFields = new Uint8Array(0);
2838
+ }
2839
+ static encode(msg) {
2840
+ const out = [];
2841
+ if (msg.groupIds) for (const v of msg.groupIds) putBytesField(out, 1, new TextEncoder().encode(v));
2842
+ putRaw(out, msg.unknownFields);
2843
+ return new Uint8Array(out);
2844
+ }
2845
+ static decode(bytes) {
2846
+ const msg = new DescribeShareGroupsRequest();
2847
+ const reader = new Reader(bytes);
2848
+ let f;
2849
+ while ((f = reader.field()) !== null) {
2850
+ const [num, wire, value, raw] = f;
2851
+ switch (num) {
2852
+ case 1: msg.groupIds.push(new TextDecoder().decode(value)); break;
2853
+ default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
2854
+ }
2855
+ }
2856
+ return msg;
2857
+ }
2858
+ }
2859
+
2860
+ export class DescribeShareGroupsResponse {
2861
+ constructor({ groups = [], errorCode = 0 } = {}) {
2862
+ this.groups = groups;
2863
+ this.errorCode = errorCode;
2864
+ this.unknownFields = new Uint8Array(0);
2865
+ }
2866
+ static encode(msg) {
2867
+ const out = [];
2868
+ if (msg.groups) for (const v of msg.groups) putBytesField(out, 1, ShareGroupDescription.encode(v));
2869
+ putVarintField(out, 2, BigInt(msg.errorCode));
2870
+ putRaw(out, msg.unknownFields);
2871
+ return new Uint8Array(out);
2872
+ }
2873
+ static decode(bytes) {
2874
+ const msg = new DescribeShareGroupsResponse();
2875
+ const reader = new Reader(bytes);
2876
+ let f;
2877
+ while ((f = reader.field()) !== null) {
2878
+ const [num, wire, value, raw] = f;
2879
+ switch (num) {
2880
+ case 1: msg.groups.push(ShareGroupDescription.decode(value)); break;
2881
+ case 2: msg.errorCode = Number(BigInt.asIntN(32, value)); break;
2882
+ default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
2883
+ }
2884
+ }
2885
+ return msg;
2886
+ }
2887
+ }
2888
+
@@ -0,0 +1,49 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Registry discovery service (grpcdc.registry.v1.Registry):
4
+ // ListServices answers from the host Server's live
5
+ // registrations plus descriptor-only names recorded here;
6
+ // GetDescriptor returns FileDescriptorSet bytes registered
7
+ // for a name. The service's own descriptor set is embedded
8
+ // (proto/registry.proto), so no codegen is needed to serve
9
+ // or call it: parse it with parseDescriptorSet and use a
10
+ // DynamicClient.
11
+
12
+ import { GenericMessage, createDynamicService, parseDescriptorSet } from "./dynamic.js";
13
+ import { StatusCode, StatusError } from "./codec.js";
14
+
15
+ export const REGISTRY_DESCRIPTOR_SET = Uint8Array.from(
16
+ atob("CrkDCg5yZWdpc3RyeS5wcm90bxISZ3JwY2RjLnJlZ2lzdHJ5LnYxIhUKE0xpc3RTZXJ2aWNlc1JlcXVlc3QiMgoUTGlzdFNlcnZpY2VzUmVzcG9uc2USGgoIc2VydmljZXMYASADKAlSCHNlcnZpY2VzIioKFEdldERlc2NyaXB0b3JSZXF1ZXN0EhIKBG5hbWUYASABKAlSBG5hbWUiPgoVR2V0RGVzY3JpcHRvclJlc3BvbnNlEiUKDmRlc2NyaXB0b3Jfc2V0GAEgASgMUg1kZXNjcmlwdG9yU2V0MtMBCghSZWdpc3RyeRJhCgxMaXN0U2VydmljZXMSJy5ncnBjZGMucmVnaXN0cnkudjEuTGlzdFNlcnZpY2VzUmVxdWVzdBooLmdycGNkYy5yZWdpc3RyeS52MS5MaXN0U2VydmljZXNSZXNwb25zZRJkCg1HZXREZXNjcmlwdG9yEiguZ3JwY2RjLnJlZ2lzdHJ5LnYxLkdldERlc2NyaXB0b3JSZXF1ZXN0GikuZ3JwY2RjLnJlZ2lzdHJ5LnYxLkdldERlc2NyaXB0b3JSZXNwb25zZWIGcHJvdG8z"),
17
+ (c) => c.charCodeAt(0),
18
+ );
19
+
20
+ /**
21
+ * Create the Registry service definition for `server`.
22
+ * `descriptors` is a Map<string, Uint8Array> of service
23
+ * name to FileDescriptorSet bytes. Serve the result with
24
+ * server.addService(...) like any generated service.
25
+ */
26
+ export function createRegistryService(server, descriptors = new Map()) {
27
+ const model = parseDescriptorSet(REGISTRY_DESCRIPTOR_SET);
28
+ return createDynamicService(model, "grpcdc.registry.v1.Registry", {
29
+ async unary(ctx, method, req) {
30
+ const resp = new GenericMessage(method.output);
31
+ if (method.name === "ListServices") {
32
+ const names = new Set(server.registeredServices());
33
+ for (const name of descriptors.keys()) names.add(name);
34
+ for (const name of [...names].sort()) resp.add(1, name);
35
+ return resp;
36
+ }
37
+ if (method.name === "GetDescriptor") {
38
+ const name = req.getString(1);
39
+ const bytes = descriptors.get(name);
40
+ if (!bytes) {
41
+ throw new StatusError(StatusCode.NOT_FOUND, `no descriptor for ${name}`);
42
+ }
43
+ resp.set(1, bytes);
44
+ return resp;
45
+ }
46
+ throw new StatusError(StatusCode.UNIMPLEMENTED, "registry method");
47
+ },
48
+ });
49
+ }
package/src/rendezvous.js CHANGED
@@ -68,6 +68,150 @@ export function synthesizeRendezvousOffer(descriptor) {
68
68
  ].join("\r\n");
69
69
  }
70
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
+
71
215
  /**
72
216
  * Fetch a rendezvous descriptor JSON from `url` (HTTPS in
73
217
  * production; the well-known location
@@ -96,7 +240,8 @@ export async function fetchRendezvousDescriptor(url, options = {}) {
96
240
  * Waits for the "grpc" DataChannel to open, matching
97
241
  * httpSignalingChannel's ready-to-use contract.
98
242
  *
99
- * options: { iceServers, iceTransportPolicy, timeoutMs, label }
243
+ * options: { iceServers, iceTransportPolicy, timeoutMs, label,
244
+ * token, getToken }
100
245
  * iceTransportPolicy "relay" (with TURN iceServers) is the
101
246
  * symmetric-NAT shape: the browser nominates its relay
102
247
  * candidate against the listener's published address.
@@ -119,7 +264,20 @@ export async function rendezvousChannel(descriptor, options = {}) {
119
264
  pc.close();
120
265
  throw e;
121
266
  }
122
- const channel = new Channel(dc);
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
+ });
123
281
  channel.peerConnection = pc;
124
282
  channel.dataChannel = dc;
125
283
  channel.closeRendezvous = () => pc.close();
@@ -9,6 +9,7 @@
9
9
  // address cannot be fixed in advance.
10
10
 
11
11
  import { RendezvousListener } from "../../webrtc/js/rendezvous.js";
12
+ import { verifyRendezvousToken } from "./rendezvous.js";
12
13
 
13
14
  export { RendezvousListener } from "../../webrtc/js/rendezvous.js";
14
15
 
@@ -28,6 +29,17 @@ export { RendezvousListener } from "../../webrtc/js/rendezvous.js";
28
29
  * and .close()).
29
30
  */
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
+ }
31
43
  const listener = await RendezvousListener.bind({
32
44
  ...options,
33
45
  onChannel: (channel, peer) => {
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,9 @@ async function firstRequest(requests) {
36
37
 
37
38
  export class Server {
38
39
  #methods = new Map();
40
+ #authVerifier = null;
41
+ #authScopes = {};
42
+ #interceptors = [];
39
43
 
40
44
  addService(definition) {
41
45
  for (const [name, method] of Object.entries(definition.methods)) {
@@ -47,6 +51,49 @@ export class Server {
47
51
  return this;
48
52
  }
49
53
 
54
+ /**
55
+ * Require rendezvous bearer auth on every call: `verifier`
56
+ * is an async (token) => claims function that throws on a
57
+ * bad, missing or expired token; `scopes` maps a method path
58
+ * to the scopes it requires (no entry = any authenticated
59
+ * caller). Verified claims land on ctx.claims. Installed by
60
+ * serveRendezvous when options.auth is set; rendezvous-only
61
+ * by design (no protoc plugin option).
62
+ */
63
+ /** Remove every method of `name` (runtime unregistration). */
64
+ removeService(name) {
65
+ const prefix = `/${name}/`;
66
+ for (const path of [...this.#methods.keys()]) {
67
+ if (path.startsWith(prefix)) this.#methods.delete(path);
68
+ }
69
+ return this;
70
+ }
71
+
72
+ /** Names of registered services, sorted (discovery source). */
73
+ registeredServices() {
74
+ const names = new Set();
75
+ for (const { service } of this.#methods.values()) names.add(service);
76
+ return [...names].sort();
77
+ }
78
+
79
+ /**
80
+ * Install a server interceptor: `fn({path, metadata})` runs
81
+ * in install order before dispatch (after rendezvous auth
82
+ * when set). Throwing a StatusError ends the call with that
83
+ * status and the handler never runs. Return a claims object
84
+ * to expose it as ctx.claims when no auth claims are set.
85
+ */
86
+ addInterceptor(fn) {
87
+ this.#interceptors.push(fn);
88
+ return this;
89
+ }
90
+
91
+ requireRendezvousAuth(verifier, scopes = {}) {
92
+ this.#authVerifier = verifier;
93
+ this.#authScopes = scopes ?? {};
94
+ return this;
95
+ }
96
+
50
97
  /** Attach to an endpoint (or raw channel, wrapped with even parity). */
51
98
  serve(dcOrEndpoint, options) {
52
99
  const endpoint =
@@ -64,6 +111,38 @@ export class Server {
64
111
  throw StatusError.unimplemented(`unknown method ${path}`);
65
112
  }
66
113
  const metadata = headers.metadata ?? {};
114
+ let claims = null;
115
+ if (this.#authVerifier !== null) {
116
+ const header = metadata.authorization ?? "";
117
+ const match = /^Bearer (.+)$/.exec(header);
118
+ if (!match) {
119
+ throw new StatusError(StatusCode.UNAUTHENTICATED, "missing bearer token");
120
+ }
121
+ try {
122
+ claims = await this.#authVerifier(match[1]);
123
+ } catch (e) {
124
+ throw new StatusError(
125
+ StatusCode.UNAUTHENTICATED,
126
+ e instanceof Error ? e.message : "invalid bearer token",
127
+ );
128
+ }
129
+ const required = this.#authScopes[path] ?? [];
130
+ const granted = new Set(claims?.scopes ?? []);
131
+ for (const scope of required) {
132
+ if (!granted.has(scope)) {
133
+ throw new StatusError(
134
+ StatusCode.PERMISSION_DENIED,
135
+ `missing required scope ${scope}`,
136
+ );
137
+ }
138
+ }
139
+ }
140
+ for (const interceptor of this.#interceptors) {
141
+ const extra = await interceptor({ path, metadata });
142
+ if (claims === null && extra !== null && typeof extra === "object") {
143
+ claims = extra;
144
+ }
145
+ }
67
146
  const timeoutMs = parseTimeout(metadata["grpc-timeout"]);
68
147
  const deadline = timeoutMs === null ? null : Date.now() + timeoutMs;
69
148
  // Initial/trailing metadata the handler accumulates via
@@ -91,6 +170,7 @@ export class Server {
91
170
  const ctx = {
92
171
  path,
93
172
  metadata,
173
+ claims,
94
174
  service: method.service,
95
175
  method: method.method,
96
176
  deadline,
package/src/stdio.js ADDED
@@ -0,0 +1,80 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // IPC transports (Node only): stdio and Unix domain socket
4
+ // channels for host/plugin use. One message is a 4-byte
5
+ // big-endian length prefix plus the frame bytes — the same
6
+ // framing as the Rust StreamDc and Go SidecarTransport IPC
7
+ // forms, so a plugin process in any language can speak
8
+ // grpc-dc to a host without a WebRTC stack. Like
9
+ // rendezvous_server.js this module is Node-only and is not
10
+ // re-exported from index.js; import it directly:
11
+ // import { stdioChannel, udsChannel } from "grpc-dc/stdio";
12
+
13
+ import net from "node:net";
14
+ import { Duplex } from "node:stream";
15
+ import { Channel } from "./channel.js";
16
+
17
+ /** DataChannel-shaped IPC endpoint over a Duplex stream. */
18
+ export class StreamDataChannel extends EventTarget {
19
+ #inbox = Buffer.alloc(0);
20
+ #stream;
21
+
22
+ constructor(stream) {
23
+ super();
24
+ this.#stream = stream;
25
+ stream.on("data", (chunk) => {
26
+ this.#inbox = Buffer.concat([this.#inbox, chunk]);
27
+ for (;;) {
28
+ if (this.#inbox.length < 4) return;
29
+ const len = this.#inbox.readUInt32BE(0);
30
+ if (this.#inbox.length < 4 + len) return;
31
+ const frame = this.#inbox.subarray(4, 4 + len);
32
+ this.#inbox = this.#inbox.subarray(4 + len);
33
+ this.dispatchEvent(new MessageEvent("message", { data: frame }));
34
+ }
35
+ });
36
+ stream.on("error", (err) => {
37
+ this.dispatchEvent(new ErrorEvent("error", { error: err }));
38
+ });
39
+ }
40
+
41
+ send(frameBytes) {
42
+ const frame = Buffer.isBuffer(frameBytes) ? frameBytes : Buffer.from(frameBytes);
43
+ const prefix = Buffer.alloc(4);
44
+ prefix.writeUInt32BE(frame.length, 0);
45
+ this.#stream.write(Buffer.concat([prefix, frame]));
46
+ }
47
+
48
+ close() {
49
+ this.#stream.end();
50
+ }
51
+ }
52
+
53
+ /** Channel over this process's stdin/stdout (plugin side). */
54
+ export function stdioChannel() {
55
+ const stream = Duplex.from({ readable: process.stdin, writable: process.stdout });
56
+ return new Channel(new StreamDataChannel(stream));
57
+ }
58
+
59
+ /** Channel over a Unix domain socket at `path` (plugin side). */
60
+ export async function udsChannel(path) {
61
+ const socket = await new Promise((resolve, reject) => {
62
+ const s = net.createConnection(path);
63
+ s.once("connect", () => resolve(s));
64
+ s.once("error", reject);
65
+ });
66
+ return new Channel(new StreamDataChannel(socket));
67
+ }
68
+
69
+ /** Accept one Unix socket connection as a Channel (host side). */
70
+ export async function udsServerChannel(path) {
71
+ const socket = await new Promise((resolve, reject) => {
72
+ const server = net.createServer((s) => {
73
+ server.close();
74
+ resolve(s);
75
+ });
76
+ server.once("error", reject);
77
+ server.listen(path);
78
+ });
79
+ return new Channel(new StreamDataChannel(socket));
80
+ }