grpc-dc 0.41.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.
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.42.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",
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;
@@ -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
+
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,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,