werift 0.24.3 → 0.24.4

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.
@@ -93,8 +93,9 @@ class Event {
93
93
  configurable: true,
94
94
  writable: true,
95
95
  value: () => {
96
+ // complete() 後の再呼び出しを許容し、close 経路での二重クリーンアップを安全にする
96
97
  if (this.ended) {
97
- throw new Error("event completed");
98
+ return;
98
99
  }
99
100
  this.event = {
100
101
  stack: [],
@@ -1 +1 @@
1
- {"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../common/src/event.ts"],"names":[],"mappings":";;;AAqBA,MAAa,KAAK;IAAlB;QACU;;;;mBAAmB;gBACzB,KAAK,EAAE,EAAE;gBACT,YAAY,EAAE,EAAE;gBAChB,OAAO,EAAE,CAAC;aACX;WAAC;QACF;;;;mBAAQ,KAAK;WAAC;QACd;;;;;WAAqB;QACrB;;;;mBAAU,CAAC,CAAM,EAAE,EAAE,GAAE,CAAC;WAAC;QAEzB;;;;mBAAU,CAAC,GAAG,IAAO,EAAE,EAAE;gBACvB,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;oBACf,OAAO;gBACT,CAAC;gBAED,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;oBACpC,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;gBACxB,CAAC;gBAED,CAAC,KAAK,IAAI,EAAE;oBACV,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC;wBAC3C,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;oBAC9B,CAAC;gBACH,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;oBACf,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;gBAClB,CAAC,CAAC,CAAC;YACL,CAAC;WAAC;QAEF;;;;mBAAW,GAAG,EAAE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CAAC;IARC,IAAI,CAAC,QAAoB;QACvB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC;IAED,OAAO;QACL,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAXD,sCAWC","sourcesContent":["type EventExecute<T extends any[]> = (...args: T) => void;\ntype PromiseEventExecute<T extends any[]> = (...args: T) => Promise<void>;\ntype EventComplete = () => void;\ntype EventError = (e: any) => void;\ninterface Stack<T extends any[]> {\n execute: EventExecute<T>;\n complete?: EventComplete;\n error?: EventError;\n id: number;\n}\ninterface IEvent<T extends any[]> {\n stack: Stack<T>[];\n promiseStack: {\n execute: PromiseEventExecute<T>;\n complete?: EventComplete;\n error?: EventError;\n id: number;\n }[];\n eventId: number;\n}\n\nexport class Event<T extends any[]> {\n private event: IEvent<T> = {\n stack: [],\n promiseStack: [],\n eventId: 0,\n };\n ended = false;\n onended?: () => void;\n onerror = (e: any) => {};\n\n execute = (...args: T) => {\n if (this.ended) {\n return;\n }\n\n for (const item of this.event.stack) {\n item.execute(...args);\n }\n\n (async () => {\n for (const item of this.event.promiseStack) {\n await item.execute(...args);\n }\n })().catch((e) => {\n this.onerror(e);\n });\n };\n\n complete = () => {\n if (this.ended) {\n return;\n }\n\n for (const item of this.event.stack) {\n if (item.complete) {\n item.complete();\n }\n }\n this.allUnsubscribe();\n this.ended = true;\n if (this.onended) {\n this.onended();\n this.onended = undefined;\n }\n };\n\n error = (e: any) => {\n if (this.ended) {\n return;\n }\n\n for (const item of this.event.stack) {\n if (item.error) {\n item.error(e);\n }\n }\n this.allUnsubscribe();\n };\n\n allUnsubscribe = () => {\n if (this.ended) {\n throw new Error(\"event completed\");\n }\n\n this.event = {\n stack: [],\n promiseStack: [],\n eventId: 0,\n };\n };\n\n subscribe = (\n execute: EventExecute<T>,\n complete?: EventComplete,\n error?: EventError,\n ) => {\n const id = this.event.eventId;\n this.event.stack.push({ execute, id, complete, error });\n this.event.eventId++;\n\n const unSubscribe = () => {\n this.event.stack = this.event.stack.filter(\n (item) => item.id !== id && item,\n );\n };\n\n const disposer = (disposer: EventDisposer) => {\n disposer.push(unSubscribe);\n };\n\n return { unSubscribe, disposer };\n };\n\n pipe(e: Event<T>) {\n this.subscribe((...args) => {\n e.execute(...args);\n });\n }\n\n queuingSubscribe = (\n execute: PromiseEventExecute<T>,\n complete?: EventComplete,\n error?: EventError,\n ) => {\n if (this.ended) throw new Error(\"event completed\");\n\n const id = this.event.eventId;\n this.event.promiseStack.push({ execute, id, complete, error });\n this.event.eventId++;\n\n const unSubscribe = () => {\n this.event.stack = this.event.stack.filter(\n (item) => item.id !== id && item,\n );\n };\n\n const disposer = (disposer: EventDisposer) => {\n disposer.push(unSubscribe);\n };\n\n return { unSubscribe, disposer };\n };\n\n once = (\n execute: EventExecute<T>,\n complete?: EventComplete,\n error?: EventError,\n ) => {\n const off = this.subscribe(\n (...args) => {\n off.unSubscribe();\n execute(...args);\n },\n complete,\n error,\n );\n };\n\n watch = (cb: (...args: T) => boolean, timeLimit?: number) =>\n new Promise<T>((resolve, reject) => {\n const timeout =\n timeLimit &&\n setTimeout(() => {\n reject(\"Event watch timeout\");\n }, timeLimit);\n\n const { unSubscribe } = this.subscribe((...args) => {\n const done = cb(...args);\n if (done) {\n if (timeout) clearTimeout(timeout);\n unSubscribe();\n resolve(args);\n }\n });\n });\n\n asPromise = (timeLimit?: number) =>\n new Promise<T>((resolve, reject) => {\n const timeout =\n timeLimit &&\n setTimeout(() => {\n reject(\"Event asPromise timeout\");\n }, timeLimit);\n\n this.once(\n (...args) => {\n if (timeout) clearTimeout(timeout);\n resolve(args);\n },\n () => {\n if (timeout) clearTimeout(timeout);\n resolve([] as any);\n },\n (err) => {\n if (timeout) clearTimeout(timeout);\n reject(err);\n },\n );\n });\n\n get returnTrigger() {\n const { execute, error, complete } = this;\n return { execute, error, complete };\n }\n\n get returnListener() {\n const { subscribe, once, asPromise } = this;\n return { subscribe, once, asPromise };\n }\n\n get length() {\n return this.event.stack.length;\n }\n}\n\nexport class EventDisposer {\n private _disposer: (() => void)[] = [];\n\n push(disposer: () => void) {\n this._disposer.push(disposer);\n }\n\n dispose() {\n this._disposer.forEach((d) => d());\n this._disposer = [];\n }\n}\n"]}
1
+ {"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../common/src/event.ts"],"names":[],"mappings":";;;AAqBA,MAAa,KAAK;IAAlB;QACU;;;;mBAAmB;gBACzB,KAAK,EAAE,EAAE;gBACT,YAAY,EAAE,EAAE;gBAChB,OAAO,EAAE,CAAC;aACX;WAAC;QACF;;;;mBAAQ,KAAK;WAAC;QACd;;;;;WAAqB;QACrB;;;;mBAAU,CAAC,CAAM,EAAE,EAAE,GAAE,CAAC;WAAC;QAEzB;;;;mBAAU,CAAC,GAAG,IAAO,EAAE,EAAE;gBACvB,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;oBACf,OAAO;gBACT,CAAC;gBAED,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;oBACpC,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;gBACxB,CAAC;gBAED,CAAC,KAAK,IAAI,EAAE;oBACV,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC;wBAC3C,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;oBAC9B,CAAC;gBACH,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;oBACf,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;gBAClB,CAAC,CAAC,CAAC;YACL,CAAC;WAAC;QAEF;;;;mBAAW,GAAG,EAAE;gBACd,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;oB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C,QAAQ,CAAC,CAAC;IAChC,CAAC;IAED,OAAO;QACL,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF;AAXD,sCAWC","sourcesContent":["type EventExecute<T extends any[]> = (...args: T) => void;\ntype PromiseEventExecute<T extends any[]> = (...args: T) => Promise<void>;\ntype EventComplete = () => void;\ntype EventError = (e: any) => void;\ninterface Stack<T extends any[]> {\n execute: EventExecute<T>;\n complete?: EventComplete;\n error?: EventError;\n id: number;\n}\ninterface IEvent<T extends any[]> {\n stack: Stack<T>[];\n promiseStack: {\n execute: PromiseEventExecute<T>;\n complete?: EventComplete;\n error?: EventError;\n id: number;\n }[];\n eventId: number;\n}\n\nexport class Event<T extends any[]> {\n private event: IEvent<T> = {\n stack: [],\n promiseStack: [],\n eventId: 0,\n };\n ended = false;\n onended?: () => void;\n onerror = (e: any) => {};\n\n execute = (...args: T) => {\n if (this.ended) {\n return;\n }\n\n for (const item of this.event.stack) {\n item.execute(...args);\n }\n\n (async () => {\n for (const item of this.event.promiseStack) {\n await item.execute(...args);\n }\n })().catch((e) => {\n this.onerror(e);\n });\n };\n\n complete = () => {\n if (this.ended) {\n return;\n }\n\n for (const item of this.event.stack) {\n if (item.complete) {\n item.complete();\n }\n }\n this.allUnsubscribe();\n this.ended = true;\n if (this.onended) {\n this.onended();\n this.onended = undefined;\n }\n };\n\n error = (e: any) => {\n if (this.ended) {\n return;\n }\n\n for (const item of this.event.stack) {\n if (item.error) {\n item.error(e);\n }\n }\n this.allUnsubscribe();\n };\n\n allUnsubscribe = () => {\n // complete() 後の再呼び出しを許容し、close 経路での二重クリーンアップを安全にする\n if (this.ended) {\n return;\n }\n\n this.event = {\n stack: [],\n promiseStack: [],\n eventId: 0,\n };\n };\n\n subscribe = (\n execute: EventExecute<T>,\n complete?: EventComplete,\n error?: EventError,\n ) => {\n const id = this.event.eventId;\n this.event.stack.push({ execute, id, complete, error });\n this.event.eventId++;\n\n const unSubscribe = () => {\n this.event.stack = this.event.stack.filter(\n (item) => item.id !== id && item,\n );\n };\n\n const disposer = (disposer: EventDisposer) => {\n disposer.push(unSubscribe);\n };\n\n return { unSubscribe, disposer };\n };\n\n pipe(e: Event<T>) {\n this.subscribe((...args) => {\n e.execute(...args);\n });\n }\n\n queuingSubscribe = (\n execute: PromiseEventExecute<T>,\n complete?: EventComplete,\n error?: EventError,\n ) => {\n if (this.ended) throw new Error(\"event completed\");\n\n const id = this.event.eventId;\n this.event.promiseStack.push({ execute, id, complete, error });\n this.event.eventId++;\n\n const unSubscribe = () => {\n this.event.stack = this.event.stack.filter(\n (item) => item.id !== id && item,\n );\n };\n\n const disposer = (disposer: EventDisposer) => {\n disposer.push(unSubscribe);\n };\n\n return { unSubscribe, disposer };\n };\n\n once = (\n execute: EventExecute<T>,\n complete?: EventComplete,\n error?: EventError,\n ) => {\n const off = this.subscribe(\n (...args) => {\n off.unSubscribe();\n execute(...args);\n },\n complete,\n error,\n );\n };\n\n watch = (cb: (...args: T) => boolean, timeLimit?: number) =>\n new Promise<T>((resolve, reject) => {\n const timeout =\n timeLimit &&\n setTimeout(() => {\n reject(\"Event watch timeout\");\n }, timeLimit);\n\n const { unSubscribe } = this.subscribe((...args) => {\n const done = cb(...args);\n if (done) {\n if (timeout) clearTimeout(timeout);\n unSubscribe();\n resolve(args);\n }\n });\n });\n\n asPromise = (timeLimit?: number) =>\n new Promise<T>((resolve, reject) => {\n const timeout =\n timeLimit &&\n setTimeout(() => {\n reject(\"Event asPromise timeout\");\n }, timeLimit);\n\n this.once(\n (...args) => {\n if (timeout) clearTimeout(timeout);\n resolve(args);\n },\n () => {\n if (timeout) clearTimeout(timeout);\n resolve([] as any);\n },\n (err) => {\n if (timeout) clearTimeout(timeout);\n reject(err);\n },\n );\n });\n\n get returnTrigger() {\n const { execute, error, complete } = this;\n return { execute, error, complete };\n }\n\n get returnListener() {\n const { subscribe, once, asPromise } = this;\n return { subscribe, once, asPromise };\n }\n\n get length() {\n return this.event.stack.length;\n }\n}\n\nexport class EventDisposer {\n private _disposer: (() => void)[] = [];\n\n push(disposer: () => void) {\n this._disposer.push(disposer);\n }\n\n dispose() {\n this._disposer.forEach((d) => d());\n this._disposer = [];\n }\n}\n"]}
@@ -3,6 +3,13 @@ import { type Address, Event, type InterfaceAddresses, type TlsConnectionOptions
3
3
  import { Message } from "../stun/message";
4
4
  import { Transaction } from "../stun/transaction";
5
5
  import type { Protocol, TransactionRequestOptions } from "../types/model";
6
+ /** Channel binding state for a single peer transport address. */
7
+ export interface TurnChannel {
8
+ number: number;
9
+ address: Address;
10
+ /** Unix seconds when this channel should be refreshed. */
11
+ refreshAt: number;
12
+ }
6
13
  export declare class StunOverTurnProtocol implements Protocol {
7
14
  turn: TurnProtocol;
8
15
  static type: string;
@@ -49,11 +56,24 @@ export declare class TurnProtocol implements Protocol {
49
56
  private addrByChannel;
50
57
  /**sec */
51
58
  private channelRefreshTime;
52
- private channelBinding?;
53
- private channelRefreshAt;
59
+ /**
60
+ * Serializes ChannelBind requests so allocation-wide auth state
61
+ * (nonce/realm/integrityKey) is not updated concurrently. Rejections
62
+ * must not poison this tail — see channelBindQueue assignment sites.
63
+ */
64
+ private channelBindQueue;
65
+ /** In-flight ChannelBind per peer transport address (dedupe concurrent). */
66
+ private channelBindingByAddr;
54
67
  private tcpBuffer;
68
+ /** Permission cache keyed by peer IP only (RFC 8656). */
55
69
  private permissionByAddr;
56
- private creatingPermission;
70
+ /**
71
+ * Serializes CreatePermission requests (auth state race avoidance).
72
+ * Rejections must not poison this tail.
73
+ */
74
+ private permissionQueue;
75
+ /** In-flight CreatePermission per peer IP (dedupe concurrent). */
76
+ private creatingPermissionByAddr;
57
77
  constructor(server: Address, username: string, password: string, lifetime: number, transport: Transport, options?: {
58
78
  /**sec */
59
79
  channelRefreshTime?: number;
@@ -68,11 +88,23 @@ export declare class TurnProtocol implements Protocol {
68
88
  request(request: Message, addr: Address, _integrityKey?: Buffer, retransmissionsOrOptions?: number | TransactionRequestOptions, onRequestSent?: (attempt: number) => void): Promise<[Message, Address]>;
69
89
  requestWithRetry(request: Message, addr: Address): Promise<[Message, Address]>;
70
90
  sendData(data: Buffer, addr: Address): Promise<void>;
91
+ /**
92
+ * Ensure a CreatePermission exists for the peer IP.
93
+ * Peer failures are isolated: a rejection for peer A does not poison peer B.
94
+ */
71
95
  getPermission(addr: Address): Promise<void>;
72
- getChannel(addr: Address): Promise<{
73
- number: number;
74
- address: Address;
75
- }>;
96
+ /**
97
+ * Ensure a ChannelBind exists for the peer transport address.
98
+ * Peer failures are isolated; concurrent same-peer calls share one Promise.
99
+ */
100
+ getChannel(addr: Address): Promise<TurnChannel>;
101
+ /**
102
+ * Create or refresh a channel for addr. Provisional mapping is installed
103
+ * before the request so early ChannelData can be decoded; only a failed
104
+ * *initial* bind rolls the mapping back. Failed channel numbers are never
105
+ * reused.
106
+ */
107
+ private ensureChannel;
76
108
  private channelBind;
77
109
  sendStun(message: Message, addr: Address): Promise<void>;
78
110
  close(): Promise<void>;
@@ -20,6 +20,14 @@ const UDP_TRANSPORT = 0x11000000;
20
20
  function isStreamTransport(transport) {
21
21
  return transport.type === "tcp" || transport.type === "tls";
22
22
  }
23
+ /** Permission is peer-IP scoped (RFC 8656). */
24
+ function permissionKey(addr) {
25
+ return addr[0];
26
+ }
27
+ /** ChannelBind is peer transport-address scoped (IP + port). */
28
+ function channelKey(addr) {
29
+ return JSON.stringify(addr);
30
+ }
23
31
  class StunOverTurnProtocol {
24
32
  constructor(turn) {
25
33
  Object.defineProperty(this, "turn", {
@@ -278,17 +286,23 @@ class TurnProtocol {
278
286
  writable: true,
279
287
  value: void 0
280
288
  });
281
- Object.defineProperty(this, "channelBinding", {
289
+ /**
290
+ * Serializes ChannelBind requests so allocation-wide auth state
291
+ * (nonce/realm/integrityKey) is not updated concurrently. Rejections
292
+ * must not poison this tail — see channelBindQueue assignment sites.
293
+ */
294
+ Object.defineProperty(this, "channelBindQueue", {
282
295
  enumerable: true,
283
296
  configurable: true,
284
297
  writable: true,
285
- value: void 0
298
+ value: Promise.resolve()
286
299
  });
287
- Object.defineProperty(this, "channelRefreshAt", {
300
+ /** In-flight ChannelBind per peer transport address (dedupe concurrent). */
301
+ Object.defineProperty(this, "channelBindingByAddr", {
288
302
  enumerable: true,
289
303
  configurable: true,
290
304
  writable: true,
291
- value: 0
305
+ value: new Map()
292
306
  });
293
307
  Object.defineProperty(this, "tcpBuffer", {
294
308
  enumerable: true,
@@ -296,18 +310,30 @@ class TurnProtocol {
296
310
  writable: true,
297
311
  value: Buffer.alloc(0)
298
312
  });
313
+ /** Permission cache keyed by peer IP only (RFC 8656). */
299
314
  Object.defineProperty(this, "permissionByAddr", {
300
315
  enumerable: true,
301
316
  configurable: true,
302
317
  writable: true,
303
318
  value: {}
304
319
  });
305
- Object.defineProperty(this, "creatingPermission", {
320
+ /**
321
+ * Serializes CreatePermission requests (auth state race avoidance).
322
+ * Rejections must not poison this tail.
323
+ */
324
+ Object.defineProperty(this, "permissionQueue", {
306
325
  enumerable: true,
307
326
  configurable: true,
308
327
  writable: true,
309
328
  value: Promise.resolve()
310
329
  });
330
+ /** In-flight CreatePermission per peer IP (dedupe concurrent). */
331
+ Object.defineProperty(this, "creatingPermissionByAddr", {
332
+ enumerable: true,
333
+ configurable: true,
334
+ writable: true,
335
+ value: new Map()
336
+ });
311
337
  Object.defineProperty(this, "refresh", {
312
338
  enumerable: true,
313
339
  configurable: true,
@@ -432,10 +458,8 @@ class TurnProtocol {
432
458
  .setAttribute("USERNAME", this.username)
433
459
  .setAttribute("REALM", this.realm)
434
460
  .setAttribute("NONCE", this.nonce);
435
- await this.request(request, this.server).catch((e) => {
436
- request;
437
- throw e;
438
- });
461
+ // Use requestWithRetry for stale-nonce (438) consistency with ChannelBind.
462
+ await this.requestWithRetry(request, this.server);
439
463
  }
440
464
  async request(request, addr, _integrityKey, retransmissionsOrOptions, onRequestSent) {
441
465
  if (this.transactions[request.transactionIdHex]) {
@@ -499,10 +523,15 @@ class TurnProtocol {
499
523
  return [message, address];
500
524
  }
501
525
  async sendData(data, addr) {
502
- const channel = await this.getChannel(addr).catch((e) => {
503
- return new Error("channelBind error");
504
- });
505
- if (channel instanceof Error) {
526
+ let channel;
527
+ try {
528
+ channel = await this.getChannel(addr);
529
+ }
530
+ catch (e) {
531
+ // Keep original ChannelBind error for diagnostics (403/438/timeout).
532
+ log("channelBind error; falling back to Send Indication", e);
533
+ }
534
+ if (!channel) {
506
535
  await this.getPermission(addr);
507
536
  const indicate = new message_1.Message(const_1.methods.SEND, const_1.classes.INDICATION)
508
537
  .setAttribute("DATA", data)
@@ -512,50 +541,116 @@ class TurnProtocol {
512
541
  }
513
542
  await this.send((0, frame_1.encodeChannelData)(channel.number, data), this.server);
514
543
  }
544
+ /**
545
+ * Ensure a CreatePermission exists for the peer IP.
546
+ * Peer failures are isolated: a rejection for peer A does not poison peer B.
547
+ */
515
548
  async getPermission(addr) {
516
- await this.creatingPermission;
517
- const permitted = this.permissionByAddr[addr.join(":")];
518
- if (!permitted) {
519
- this.creatingPermission = this.createPermission(addr);
520
- this.permissionByAddr[addr.join(":")] = true;
521
- await this.creatingPermission.catch((e) => {
522
- log("createPermission error", e);
523
- throw e;
524
- });
549
+ const key = permissionKey(addr);
550
+ if (this.permissionByAddr[key]) {
551
+ return;
552
+ }
553
+ const existing = this.creatingPermissionByAddr.get(key);
554
+ if (existing) {
555
+ return existing;
556
+ }
557
+ const operation = this.permissionQueue.then(async () => {
558
+ // Another caller may have succeeded while we waited on the queue.
559
+ if (this.permissionByAddr[key]) {
560
+ return;
561
+ }
562
+ await this.createPermission(addr);
563
+ // Cache only after successful CreatePermission.
564
+ this.permissionByAddr[key] = true;
565
+ });
566
+ // Do not let rejection poison subsequent peers on the shared queue.
567
+ this.permissionQueue = operation.then(() => undefined, () => undefined);
568
+ this.creatingPermissionByAddr.set(key, operation);
569
+ try {
570
+ await operation;
571
+ }
572
+ catch (error) {
573
+ log("createPermission error", error);
574
+ throw error;
575
+ }
576
+ finally {
577
+ if (this.creatingPermissionByAddr.get(key) === operation) {
578
+ this.creatingPermissionByAddr.delete(key);
579
+ }
525
580
  }
526
581
  }
582
+ /**
583
+ * Ensure a ChannelBind exists for the peer transport address.
584
+ * Peer failures are isolated; concurrent same-peer calls share one Promise.
585
+ */
527
586
  async getChannel(addr) {
528
- if (this.channelBinding) {
529
- await this.channelBinding;
587
+ const key = channelKey(addr);
588
+ const existing = this.channelBindingByAddr.get(key);
589
+ if (existing) {
590
+ return existing;
591
+ }
592
+ // Fast path: bound and not due for refresh.
593
+ const cached = this.channelByAddr[key];
594
+ const now = (0, common_1.int)(Date.now() / 1000);
595
+ if (cached && cached.refreshAt > now) {
596
+ return cached;
530
597
  }
531
- let channel = this.channelByAddr[addr.join(":")];
598
+ const operation = this.channelBindQueue.then(() => this.ensureChannel(addr));
599
+ // Do not let rejection poison subsequent peers on the shared queue.
600
+ this.channelBindQueue = operation.then(() => undefined, () => undefined);
601
+ this.channelBindingByAddr.set(key, operation);
602
+ try {
603
+ return await operation;
604
+ }
605
+ catch (error) {
606
+ log("channelBind error", error);
607
+ throw error;
608
+ }
609
+ finally {
610
+ if (this.channelBindingByAddr.get(key) === operation) {
611
+ this.channelBindingByAddr.delete(key);
612
+ }
613
+ }
614
+ }
615
+ /**
616
+ * Create or refresh a channel for addr. Provisional mapping is installed
617
+ * before the request so early ChannelData can be decoded; only a failed
618
+ * *initial* bind rolls the mapping back. Failed channel numbers are never
619
+ * reused.
620
+ */
621
+ async ensureChannel(addr) {
622
+ const key = channelKey(addr);
623
+ const now = (0, common_1.int)(Date.now() / 1000);
624
+ let channel = this.channelByAddr[key];
625
+ if (channel && channel.refreshAt > now) {
626
+ return channel;
627
+ }
628
+ const isNew = !channel;
532
629
  if (!channel) {
533
- this.channelByAddr[addr.join(":")] = {
630
+ channel = {
534
631
  number: this.channelNumber++,
535
632
  address: addr,
633
+ refreshAt: 0,
536
634
  };
537
- channel = this.channelByAddr[addr.join(":")];
635
+ // Provisional mapping for ChannelData that may arrive before success.
636
+ this.channelByAddr[key] = channel;
538
637
  this.addrByChannel[channel.number] = addr;
539
- this.channelBinding = this.channelBind(channel.number, addr);
540
- await this.channelBinding.catch((e) => {
541
- log("channelBind error", e);
542
- throw e;
543
- });
544
- this.channelRefreshAt = (0, common_1.int)(Date.now() / 1000) + this.channelRefreshTime;
545
- this.channelBinding = undefined;
546
- log("channelBind", channel);
547
- }
548
- else if (this.channelRefreshAt < (0, common_1.int)(Date.now() / 1000)) {
549
- this.channelBinding = this.channelBind(channel.number, addr);
550
- this.channelRefreshAt = (0, common_1.int)(Date.now() / 1000) + this.channelRefreshTime;
551
- await this.channelBinding.catch((e) => {
552
- log("channelBind error", e);
553
- throw e;
554
- });
555
- this.channelBinding = undefined;
556
- log("channelBind refresh", channel);
557
- }
558
- return channel;
638
+ }
639
+ try {
640
+ await this.channelBind(channel.number, addr);
641
+ channel.refreshAt = (0, common_1.int)(Date.now() / 1000) + this.channelRefreshTime;
642
+ log(isNew ? "channelBind" : "channelBind refresh", channel);
643
+ return channel;
644
+ }
645
+ catch (error) {
646
+ if (isNew) {
647
+ // Roll back provisional mapping only for a failed initial bind.
648
+ delete this.channelByAddr[key];
649
+ delete this.addrByChannel[channel.number];
650
+ // Do not reuse the channel number (no channelNumber--).
651
+ }
652
+ throw error;
653
+ }
559
654
  }
560
655
  async channelBind(channelNumber, addr) {
561
656
  const request = new message_1.Message(const_1.methods.CHANNEL_BIND, const_1.classes.REQUEST);
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../../../ice/src/turn/protocol.ts"],"names":[],"mappings":";;;AAmgBA,4CA+BC;AAED,4DA2CC;AAED,4CAMC;AAvlBD,8CAA6C;AAE7C,4DAAyE;AAEzE,8CAAkD;AAClD,sCAA6E;AAC7E,8CAa2B;AAC3B,yCAAiD;AACjD,6CAAuE;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AAC,OAAO,CAAC;YAClC,CAAC,CAAC,MAAM,qBAAY,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;IAErD,MAAM,IAAI,GAAG,IAAI,YAAY,CAC3B,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,SAAS,CACV,CAAC;IAEF,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;IAC5B,OAAO,IAAI,CAAC;AACd,CAAC;AAEM,KAAK,UAAU,wBAAwB,CAC5C,EACE,OAAO,EACP,QAAQ,EACR,QAAQ,GAKT,EACD,EACE,QAAQ,EACR,SAAS,EACT,kBAAkB,EAClB,GAAG,EACH,UAAU,EACV,SAAS,EAAE,aAAa,MAQtB,EAAE;IAEN,MAAM,IAAI,GAAG,MAAM,gBAAgB,CACjC;QACE,OAAO;QACP,QAAQ;QACR,QAAQ;KACT,EACD;QACE,QAAQ;QACR,SAAS;QACT,kBAAkB;QAClB,GAAG;QACH,UAAU;QACV,SAAS,EAAE,aAAa;KACzB,CACF,CAAC;IACF,MAAM,aAAa,GAAG,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACrD,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,SAAgB,gBAAgB,CAC9B,QAAgB,EAChB,KAAa,EACb,QAAgB;IAEhB,OAAO,IAAA,2BAAoB,EAAC,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACzD,CAAC","sourcesContent":["import { setTimeout } from \"timers/promises\";\n\nimport { makeTurnIntegrityKey } from \"../../../ice-server/src/turn/auth\";\nimport type { Candidate } from \"../candidate\";\nimport { TransactionFailed } from \"../exceptions\";\nimport { type Cancelable, cancelable, randomTransactionId } from \"../helper\";\nimport {\n type Address,\n Event,\n EventDisposer,\n type InterfaceAddresses,\n TcpTransport,\n type TlsConnectionOptions,\n TlsTransport,\n type Transport,\n UdpTransport,\n bufferReader,\n debug,\n int,\n} from \"../imports/common\";\nimport { classes, methods } from \"../stun/const\";\nimport { Message, paddingLength, parseMessage } from \"../stun/message\";\nimport {\n Transaction,\n buildTransactionOptions,\n resolveRequestAddress,\n} from \"../stun/transaction\";\nimport type { Protocol, TransactionRequestOptions } from \"../types/model\";\nimport {\n decodeChannelData,\n encodeChannelData,\n isChannelData,\n padTurnFrame,\n splitTurnTcpFrames,\n} from \"./frame\";\n\nconst log = debug(\"werift-ice:packages/ice/src/turn/protocol.ts\");\n\nconst DEFAULT_CHANNEL_REFRESH_TIME = 500;\nconst DEFAULT_ALLOCATION_LIFETIME = 600;\nconst UDP_TRANSPORT = 0x11000000;\n\nfunction isStreamTransport(transport: Transport) {\n return transport.type === \"tcp\" || transport.type === \"tls\";\n}\n\nexport class StunOverTurnProtocol implements Protocol {\n static type = \"turn\";\n readonly type = StunOverTurnProtocol.type;\n localCandidate!: Candidate;\n private disposer = new EventDisposer();\n onRequestReceived: Event<[Message, Address, Buffer]> = new Event();\n onDataReceived: Event<[Buffer]> = new Event();\n\n constructor(public turn: TurnProtocol) {\n turn.onData\n .subscribe((data, addr) => {\n this.handleStunMessage(data, addr);\n })\n .disposer(this.disposer);\n }\n\n private handleStunMessage = (data: Buffer, addr: Address) => {\n try {\n const message = parseMessage(data);\n if (!message) {\n this.onDataReceived.execute(data);\n return;\n }\n\n if (\n message.messageClass === classes.RESPONSE ||\n message.messageClass === classes.ERROR\n ) {\n const transaction = this.turn.transactions[message.transactionIdHex];\n if (transaction) {\n const verified = transaction.integrityKey\n ? parseMessage(data, transaction.integrityKey)\n : message;\n if (!verified) {\n log(\"STUN over TURN response failed MESSAGE-INTEGRITY check\");\n return;\n }\n transaction.responseReceived(verified, addr);\n }\n } else if (message.messageClass === classes.REQUEST) {\n this.onRequestReceived.execute(message, addr, data);\n }\n } catch (error) {\n log(\"datagramReceived error\", error);\n }\n };\n\n async request(\n request: Message,\n addr: Address,\n integrityKey?: Buffer,\n retransmissionsOrOptions?: number | TransactionRequestOptions,\n onRequestSent?: (attempt: number) => void,\n ) {\n if (this.turn.transactions[request.transactionIdHex]) {\n throw new Error(\"exist\");\n }\n\n if (integrityKey) {\n request.addMessageIntegrity(integrityKey);\n request.addFingerprint();\n }\n\n // Peer-facing STUN over TURN must honor retransmissions/responseTimeout\n // (consent uses retransmissions: 0). Do not confuse with TURN server\n // allocation/refresh policy on TurnProtocol.\n // Peer addresses are already IPs from candidates; resolve for safety.\n const resolvedAddr = await resolveRequestAddress(addr);\n const options = buildTransactionOptions(\n integrityKey,\n retransmissionsOrOptions,\n onRequestSent,\n );\n const transaction = new Transaction(request, resolvedAddr, this, options);\n this.turn.transactions[request.transactionIdHex] = transaction;\n\n try {\n return await transaction.run();\n } catch (e) {\n throw e;\n } finally {\n delete this.turn.transactions[request.transactionIdHex];\n }\n }\n async connectionMade() {}\n async sendData(data: Buffer, addr: Address) {\n await this.turn.sendData(data, addr);\n }\n async sendStun(message: Message, addr: Address) {\n await this.turn.sendData(message.bytes, addr);\n }\n async close() {\n this.disposer.dispose();\n return this.turn.close();\n }\n}\n\nexport class TurnProtocol implements Protocol {\n static type = \"turn\";\n readonly type = TurnProtocol.type;\n readonly onData = new Event<[Buffer, Address]>();\n onRequestReceived: Event<[Message, Address, Buffer]> = new Event();\n onDataReceived: Event<[Buffer]> = new Event();\n integrityKey?: Buffer;\n nonce?: Buffer;\n realm?: string;\n relayedAddress!: Address;\n mappedAddress!: Address;\n localCandidate!: Candidate;\n transactions: { [hexId: string]: Transaction } = {};\n private refreshHandle?: Cancelable<void>;\n private channelNumber = 0x4000;\n private channelByAddr: {\n [addr: string]: { number: number; address: Address };\n } = {};\n private addrByChannel: { [channel: number]: Address } = {};\n /**sec */\n private channelRefreshTime: number;\n private channelBinding?: Promise<void>;\n private channelRefreshAt = 0;\n private tcpBuffer: Buffer = Buffer.alloc(0);\n private permissionByAddr: { [addr: string]: boolean } = {};\n private creatingPermission: Promise<void> = Promise.resolve();\n\n constructor(\n public server: Address,\n public username: string,\n public password: string,\n public lifetime: number,\n public transport: Transport,\n public options: {\n /**sec */\n channelRefreshTime?: number;\n } = {},\n ) {\n this.channelRefreshTime =\n this.options.channelRefreshTime ?? DEFAULT_CHANNEL_REFRESH_TIME;\n }\n\n async connectionMade() {\n this.transport.onData = (data, addr) => {\n this.dataReceived(data, addr);\n };\n\n const request = new Message(methods.ALLOCATE, classes.REQUEST);\n request\n .setAttribute(\"LIFETIME\", this.lifetime)\n .setAttribute(\"REQUESTED-TRANSPORT\", UDP_TRANSPORT);\n\n const [response] = await this.requestWithRetry(request, this.server).catch(\n (e) => {\n log(\"connect error\", e);\n throw e;\n },\n );\n this.relayedAddress = response.getAttributeValue(\"XOR-RELAYED-ADDRESS\");\n this.mappedAddress = response.getAttributeValue(\"XOR-MAPPED-ADDRESS\");\n const exp = response.getAttributeValue(\"LIFETIME\");\n log(\"connect\", this.relayedAddress, this.mappedAddress, { exp });\n\n this.refresh(exp);\n }\n\n private handleChannelData(data: Buffer) {\n const decoded = decodeChannelData(data);\n const addr = decoded && this.addrByChannel[decoded.channelNumber];\n\n if (addr && decoded) {\n this.onData.execute(decoded.data, addr);\n }\n }\n\n private handleSTUNMessage(data: Buffer, addr: Address) {\n try {\n const message = parseMessage(data);\n if (!message) {\n throw new Error(\"not stun message\");\n }\n\n if (\n message.messageClass === classes.RESPONSE ||\n message.messageClass === classes.ERROR\n ) {\n const transaction = this.transactions[message.transactionIdHex];\n if (transaction) {\n const verified = transaction.integrityKey\n ? parseMessage(data, transaction.integrityKey)\n : message;\n if (!verified) {\n log(\"TURN STUN response failed MESSAGE-INTEGRITY check\");\n return;\n }\n transaction.responseReceived(verified, addr);\n }\n } else if (message.messageClass === classes.REQUEST) {\n this.onData.execute(data, addr);\n }\n\n if (message.getAttributeValue(\"DATA\")) {\n const buf: Buffer = message.getAttributeValue(\"DATA\");\n const peerAddress =\n message.getAttributeValue(\"XOR-PEER-ADDRESS\") ?? addr;\n this.onData.execute(buf, peerAddress);\n }\n } catch (error) {\n log(\"parse error\", data.toString());\n }\n }\n\n private dataReceived(data: Buffer, addr: Address) {\n const datagramReceived = (data: Buffer, addr: Address) => {\n if (data.length >= 4 && isChannelData(data)) {\n this.handleChannelData(data);\n } else {\n this.handleSTUNMessage(data, addr);\n }\n };\n\n if (isStreamTransport(this.transport)) {\n this.tcpBuffer = Buffer.concat([this.tcpBuffer, data]);\n const { frames, rest } = splitTurnTcpFrames(this.tcpBuffer);\n this.tcpBuffer = rest;\n for (const frame of frames) {\n datagramReceived(frame, addr);\n }\n } else {\n datagramReceived(data, addr);\n }\n }\n\n private async send(data: Buffer, addr: Address) {\n if (this.transport.closed) {\n return;\n }\n\n await this.transport.send(\n isStreamTransport(this.transport) ? padTurnFrame(data) : data,\n addr,\n );\n }\n\n private async createPermission(peerAddress: Address) {\n const request = new Message(methods.CREATE_PERMISSION, classes.REQUEST);\n request\n .setAttribute(\"XOR-PEER-ADDRESS\", peerAddress)\n .setAttribute(\"USERNAME\", this.username)\n .setAttribute(\"REALM\", this.realm)\n .setAttribute(\"NONCE\", this.nonce);\n await this.request(request, this.server).catch((e) => {\n request;\n throw e;\n });\n }\n\n private refresh = (exp: number) => {\n this.refreshHandle = cancelable<void>(async (_, __, onCancel) => {\n let run = true;\n onCancel.once(() => {\n run = false;\n });\n\n while (run) {\n // refresh before expire\n const delay = (5 / 6) * exp * 1000;\n log(\"refresh delay\", delay, { exp });\n await setTimeout(delay);\n\n const request = new Message(methods.REFRESH, classes.REQUEST);\n request.setAttribute(\"LIFETIME\", exp);\n\n try {\n const [message] = await this.requestWithRetry(request, this.server);\n exp = message.getAttributeValue(\"LIFETIME\");\n log(\"refresh\", { exp });\n } catch (error) {\n log(\"refresh error\", error);\n }\n }\n });\n };\n\n async request(\n request: Message,\n addr: Address,\n _integrityKey?: Buffer,\n retransmissionsOrOptions?: number | TransactionRequestOptions,\n onRequestSent?: (attempt: number) => void,\n ): Promise<[Message, Address]> {\n if (this.transactions[request.transactionIdHex]) {\n throw new Error(\"exist\");\n }\n if (this.integrityKey) {\n request\n .setAttribute(\"USERNAME\", this.username)\n .setAttribute(\"REALM\", this.realm)\n .setAttribute(\"NONCE\", this.nonce)\n .addMessageIntegrity(this.integrityKey)\n .addFingerprint();\n }\n\n // TURN server allocation/refresh uses default STUN retry policy unless\n // callers pass explicit options. Peer consent goes through StunOverTurnProtocol.\n // Prefer the TURN session integrity key for response verification.\n const resolvedAddr = await resolveRequestAddress(addr);\n const options = buildTransactionOptions(\n this.integrityKey,\n retransmissionsOrOptions,\n onRequestSent,\n );\n const transaction = new Transaction(request, resolvedAddr, this, options);\n this.transactions[request.transactionIdHex] = transaction;\n\n try {\n return await transaction.run();\n } catch (e) {\n throw e;\n } finally {\n delete this.transactions[request.transactionIdHex];\n }\n }\n\n async requestWithRetry(\n request: Message,\n addr: Address,\n ): Promise<[Message, Address]> {\n let message: Message, address: Address;\n try {\n [message, address] = await this.request(request, addr);\n } catch (error) {\n if (error instanceof TransactionFailed == false) {\n log(\"requestWithRetry error\", error);\n throw error;\n }\n\n // resolve dns address\n this.server = error.addr;\n\n const [errorCode] = error.response.getAttributeValue(\"ERROR-CODE\");\n const nonce = error.response.getAttributeValue(\"NONCE\");\n const realm = error.response.getAttributeValue(\"REALM\");\n\n if (\n ((errorCode === 401 && realm) || (errorCode === 438 && this.realm)) &&\n nonce\n ) {\n log(\"retry with nonce\", errorCode);\n\n this.nonce = nonce;\n if (errorCode === 401) {\n this.realm = realm;\n }\n this.integrityKey = makeIntegrityKey(\n this.username,\n this.realm!,\n this.password,\n );\n\n request.transactionId = randomTransactionId();\n [message, address] = await this.request(request, this.server);\n } else {\n throw error;\n }\n }\n return [message!, address!];\n }\n\n async sendData(data: Buffer, addr: Address) {\n const channel = await this.getChannel(addr).catch((e) => {\n return new Error(\"channelBind error\");\n });\n\n if (channel instanceof Error) {\n await this.getPermission(addr);\n const indicate = new Message(methods.SEND, classes.INDICATION)\n .setAttribute(\"DATA\", data)\n .setAttribute(\"XOR-PEER-ADDRESS\", addr);\n\n await this.sendStun(indicate, this.server);\n return;\n }\n\n await this.send(encodeChannelData(channel.number, data), this.server);\n }\n\n async getPermission(addr: Address) {\n await this.creatingPermission;\n\n const permitted = this.permissionByAddr[addr.join(\":\")];\n if (!permitted) {\n this.creatingPermission = this.createPermission(addr);\n this.permissionByAddr[addr.join(\":\")] = true;\n await this.creatingPermission.catch((e) => {\n log(\"createPermission error\", e);\n throw e;\n });\n }\n }\n\n async getChannel(addr: Address) {\n if (this.channelBinding) {\n await this.channelBinding;\n }\n\n let channel = this.channelByAddr[addr.join(\":\")];\n\n if (!channel) {\n this.channelByAddr[addr.join(\":\")] = {\n number: this.channelNumber++,\n address: addr,\n };\n channel = this.channelByAddr[addr.join(\":\")];\n this.addrByChannel[channel.number] = addr;\n\n this.channelBinding = this.channelBind(channel.number, addr);\n await this.channelBinding.catch((e) => {\n log(\"channelBind error\", e);\n throw e;\n });\n this.channelRefreshAt = int(Date.now() / 1000) + this.channelRefreshTime;\n this.channelBinding = undefined;\n log(\"channelBind\", channel);\n } else if (this.channelRefreshAt < int(Date.now() / 1000)) {\n this.channelBinding = this.channelBind(channel.number, addr);\n this.channelRefreshAt = int(Date.now() / 1000) + this.channelRefreshTime;\n await this.channelBinding.catch((e) => {\n log(\"channelBind error\", e);\n throw e;\n });\n this.channelBinding = undefined;\n log(\"channelBind refresh\", channel);\n }\n return channel;\n }\n\n private async channelBind(channelNumber: number, addr: Address) {\n const request = new Message(methods.CHANNEL_BIND, classes.REQUEST);\n request\n .setAttribute(\"CHANNEL-NUMBER\", channelNumber)\n .setAttribute(\"XOR-PEER-ADDRESS\", addr);\n const [response] = await this.requestWithRetry(request, this.server);\n if (response.messageMethod !== methods.CHANNEL_BIND) {\n throw new Error(\"should be CHANNEL_BIND\");\n }\n }\n\n async sendStun(message: Message, addr: Address) {\n await this.send(message.bytes, addr);\n }\n\n async close() {\n this.refreshHandle?.resolve?.();\n await this.transport.close();\n }\n}\n\nexport interface TurnClientConfig {\n address: Address;\n username: string;\n password: string;\n}\nexport interface TurnClientOptions {\n lifetime?: number;\n ssl?: boolean;\n transport?: \"udp\" | \"tcp\" | \"tls\";\n tlsOptions?: TlsConnectionOptions;\n portRange?: [number, number];\n interfaceAddresses?: InterfaceAddresses;\n}\n\nexport async function createTurnClient(\n { address, username, password }: TurnClientConfig,\n {\n lifetime,\n portRange,\n interfaceAddresses,\n ssl,\n tlsOptions,\n transport: transportType,\n }: TurnClientOptions = {},\n) {\n lifetime ??= DEFAULT_ALLOCATION_LIFETIME;\n transportType ??= ssl ? \"tls\" : \"udp\";\n\n const transport =\n transportType === \"udp\"\n ? await UdpTransport.init(\"udp4\", { portRange, interfaceAddresses })\n : transportType === \"tcp\"\n ? await TcpTransport.init(address)\n : await TlsTransport.init(address, tlsOptions);\n\n const turn = new TurnProtocol(\n address,\n username,\n password,\n lifetime,\n transport,\n );\n\n await turn.connectionMade();\n return turn;\n}\n\nexport async function createStunOverTurnClient(\n {\n address,\n username,\n password,\n }: {\n address: Address;\n username: string;\n password: string;\n },\n {\n lifetime,\n portRange,\n interfaceAddresses,\n ssl,\n tlsOptions,\n transport: transportType,\n }: {\n lifetime?: number;\n ssl?: boolean;\n transport?: \"udp\" | \"tcp\" | \"tls\";\n tlsOptions?: TlsConnectionOptions;\n portRange?: [number, number];\n interfaceAddresses?: InterfaceAddresses;\n } = {},\n) {\n const turn = await createTurnClient(\n {\n address,\n username,\n password,\n },\n {\n lifetime,\n portRange,\n interfaceAddresses,\n ssl,\n tlsOptions,\n transport: transportType,\n },\n );\n const turnTransport = new StunOverTurnProtocol(turn);\n return turnTransport;\n}\n\nexport function makeIntegrityKey(\n username: string,\n realm: string,\n password: string,\n) {\n return makeTurnIntegrityKey(username, realm, password);\n}\n"]}
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../../../ice/src/turn/protocol.ts"],"names":[],"mappings":";;;AAsnBA,4CA+BC;AAED,4DA2CC;AAED,4CAMC;AA1sBD,8CAA6C;AAE7C,4DAAyE;AAEzE,8CAAkD;AAClD,sCAA6E;AAC7E,8CAa2B;AAC3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AClB,GAAG;QACH,UAAU;QACV,SAAS,EAAE,aAAa;KACzB,CACF,CAAC;IACF,MAAM,aAAa,GAAG,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACrD,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,SAAgB,gBAAgB,CAC9B,QAAgB,EAChB,KAAa,EACb,QAAgB;IAEhB,OAAO,IAAA,2BAAoB,EAAC,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACzD,CAAC","sourcesContent":["import { setTimeout } from \"timers/promises\";\n\nimport { makeTurnIntegrityKey } from \"../../../ice-server/src/turn/auth\";\nimport type { Candidate } from \"../candidate\";\nimport { TransactionFailed } from \"../exceptions\";\nimport { type Cancelable, cancelable, randomTransactionId } from \"../helper\";\nimport {\n type Address,\n Event,\n EventDisposer,\n type InterfaceAddresses,\n TcpTransport,\n type TlsConnectionOptions,\n TlsTransport,\n type Transport,\n UdpTransport,\n bufferReader,\n debug,\n int,\n} from \"../imports/common\";\nimport { classes, methods } from \"../stun/const\";\nimport { Message, paddingLength, parseMessage } from \"../stun/message\";\nimport {\n Transaction,\n buildTransactionOptions,\n resolveRequestAddress,\n} from \"../stun/transaction\";\nimport type { Protocol, TransactionRequestOptions } from \"../types/model\";\nimport {\n decodeChannelData,\n encodeChannelData,\n isChannelData,\n padTurnFrame,\n splitTurnTcpFrames,\n} from \"./frame\";\n\nconst log = debug(\"werift-ice:packages/ice/src/turn/protocol.ts\");\n\nconst DEFAULT_CHANNEL_REFRESH_TIME = 500;\nconst DEFAULT_ALLOCATION_LIFETIME = 600;\nconst UDP_TRANSPORT = 0x11000000;\n\n/** Channel binding state for a single peer transport address. */\nexport interface TurnChannel {\n number: number;\n address: Address;\n /** Unix seconds when this channel should be refreshed. */\n refreshAt: number;\n}\n\nfunction isStreamTransport(transport: Transport) {\n return transport.type === \"tcp\" || transport.type === \"tls\";\n}\n\n/** Permission is peer-IP scoped (RFC 8656). */\nfunction permissionKey(addr: Address): string {\n return addr[0];\n}\n\n/** ChannelBind is peer transport-address scoped (IP + port). */\nfunction channelKey(addr: Address): string {\n return JSON.stringify(addr);\n}\n\nexport class StunOverTurnProtocol implements Protocol {\n static type = \"turn\";\n readonly type = StunOverTurnProtocol.type;\n localCandidate!: Candidate;\n private disposer = new EventDisposer();\n onRequestReceived: Event<[Message, Address, Buffer]> = new Event();\n onDataReceived: Event<[Buffer]> = new Event();\n\n constructor(public turn: TurnProtocol) {\n turn.onData\n .subscribe((data, addr) => {\n this.handleStunMessage(data, addr);\n })\n .disposer(this.disposer);\n }\n\n private handleStunMessage = (data: Buffer, addr: Address) => {\n try {\n const message = parseMessage(data);\n if (!message) {\n this.onDataReceived.execute(data);\n return;\n }\n\n if (\n message.messageClass === classes.RESPONSE ||\n message.messageClass === classes.ERROR\n ) {\n const transaction = this.turn.transactions[message.transactionIdHex];\n if (transaction) {\n const verified = transaction.integrityKey\n ? parseMessage(data, transaction.integrityKey)\n : message;\n if (!verified) {\n log(\"STUN over TURN response failed MESSAGE-INTEGRITY check\");\n return;\n }\n transaction.responseReceived(verified, addr);\n }\n } else if (message.messageClass === classes.REQUEST) {\n this.onRequestReceived.execute(message, addr, data);\n }\n } catch (error) {\n log(\"datagramReceived error\", error);\n }\n };\n\n async request(\n request: Message,\n addr: Address,\n integrityKey?: Buffer,\n retransmissionsOrOptions?: number | TransactionRequestOptions,\n onRequestSent?: (attempt: number) => void,\n ) {\n if (this.turn.transactions[request.transactionIdHex]) {\n throw new Error(\"exist\");\n }\n\n if (integrityKey) {\n request.addMessageIntegrity(integrityKey);\n request.addFingerprint();\n }\n\n // Peer-facing STUN over TURN must honor retransmissions/responseTimeout\n // (consent uses retransmissions: 0). Do not confuse with TURN server\n // allocation/refresh policy on TurnProtocol.\n // Peer addresses are already IPs from candidates; resolve for safety.\n const resolvedAddr = await resolveRequestAddress(addr);\n const options = buildTransactionOptions(\n integrityKey,\n retransmissionsOrOptions,\n onRequestSent,\n );\n const transaction = new Transaction(request, resolvedAddr, this, options);\n this.turn.transactions[request.transactionIdHex] = transaction;\n\n try {\n return await transaction.run();\n } catch (e) {\n throw e;\n } finally {\n delete this.turn.transactions[request.transactionIdHex];\n }\n }\n async connectionMade() {}\n async sendData(data: Buffer, addr: Address) {\n await this.turn.sendData(data, addr);\n }\n async sendStun(message: Message, addr: Address) {\n await this.turn.sendData(message.bytes, addr);\n }\n async close() {\n this.disposer.dispose();\n return this.turn.close();\n }\n}\n\nexport class TurnProtocol implements Protocol {\n static type = \"turn\";\n readonly type = TurnProtocol.type;\n readonly onData = new Event<[Buffer, Address]>();\n onRequestReceived: Event<[Message, Address, Buffer]> = new Event();\n onDataReceived: Event<[Buffer]> = new Event();\n integrityKey?: Buffer;\n nonce?: Buffer;\n realm?: string;\n relayedAddress!: Address;\n mappedAddress!: Address;\n localCandidate!: Candidate;\n transactions: { [hexId: string]: Transaction } = {};\n private refreshHandle?: Cancelable<void>;\n private channelNumber = 0x4000;\n private channelByAddr: { [key: string]: TurnChannel } = {};\n private addrByChannel: { [channel: number]: Address } = {};\n /**sec */\n private channelRefreshTime: number;\n /**\n * Serializes ChannelBind requests so allocation-wide auth state\n * (nonce/realm/integrityKey) is not updated concurrently. Rejections\n * must not poison this tail — see channelBindQueue assignment sites.\n */\n private channelBindQueue: Promise<void> = Promise.resolve();\n /** In-flight ChannelBind per peer transport address (dedupe concurrent). */\n private channelBindingByAddr = new Map<string, Promise<TurnChannel>>();\n private tcpBuffer: Buffer = Buffer.alloc(0);\n /** Permission cache keyed by peer IP only (RFC 8656). */\n private permissionByAddr: { [peerIp: string]: boolean } = {};\n /**\n * Serializes CreatePermission requests (auth state race avoidance).\n * Rejections must not poison this tail.\n */\n private permissionQueue: Promise<void> = Promise.resolve();\n /** In-flight CreatePermission per peer IP (dedupe concurrent). */\n private creatingPermissionByAddr = new Map<string, Promise<void>>();\n\n constructor(\n public server: Address,\n public username: string,\n public password: string,\n public lifetime: number,\n public transport: Transport,\n public options: {\n /**sec */\n channelRefreshTime?: number;\n } = {},\n ) {\n this.channelRefreshTime =\n this.options.channelRefreshTime ?? DEFAULT_CHANNEL_REFRESH_TIME;\n }\n\n async connectionMade() {\n this.transport.onData = (data, addr) => {\n this.dataReceived(data, addr);\n };\n\n const request = new Message(methods.ALLOCATE, classes.REQUEST);\n request\n .setAttribute(\"LIFETIME\", this.lifetime)\n .setAttribute(\"REQUESTED-TRANSPORT\", UDP_TRANSPORT);\n\n const [response] = await this.requestWithRetry(request, this.server).catch(\n (e) => {\n log(\"connect error\", e);\n throw e;\n },\n );\n this.relayedAddress = response.getAttributeValue(\"XOR-RELAYED-ADDRESS\");\n this.mappedAddress = response.getAttributeValue(\"XOR-MAPPED-ADDRESS\");\n const exp = response.getAttributeValue(\"LIFETIME\");\n log(\"connect\", this.relayedAddress, this.mappedAddress, { exp });\n\n this.refresh(exp);\n }\n\n private handleChannelData(data: Buffer) {\n const decoded = decodeChannelData(data);\n const addr = decoded && this.addrByChannel[decoded.channelNumber];\n\n if (addr && decoded) {\n this.onData.execute(decoded.data, addr);\n }\n }\n\n private handleSTUNMessage(data: Buffer, addr: Address) {\n try {\n const message = parseMessage(data);\n if (!message) {\n throw new Error(\"not stun message\");\n }\n\n if (\n message.messageClass === classes.RESPONSE ||\n message.messageClass === classes.ERROR\n ) {\n const transaction = this.transactions[message.transactionIdHex];\n if (transaction) {\n const verified = transaction.integrityKey\n ? parseMessage(data, transaction.integrityKey)\n : message;\n if (!verified) {\n log(\"TURN STUN response failed MESSAGE-INTEGRITY check\");\n return;\n }\n transaction.responseReceived(verified, addr);\n }\n } else if (message.messageClass === classes.REQUEST) {\n this.onData.execute(data, addr);\n }\n\n if (message.getAttributeValue(\"DATA\")) {\n const buf: Buffer = message.getAttributeValue(\"DATA\");\n const peerAddress =\n message.getAttributeValue(\"XOR-PEER-ADDRESS\") ?? addr;\n this.onData.execute(buf, peerAddress);\n }\n } catch (error) {\n log(\"parse error\", data.toString());\n }\n }\n\n private dataReceived(data: Buffer, addr: Address) {\n const datagramReceived = (data: Buffer, addr: Address) => {\n if (data.length >= 4 && isChannelData(data)) {\n this.handleChannelData(data);\n } else {\n this.handleSTUNMessage(data, addr);\n }\n };\n\n if (isStreamTransport(this.transport)) {\n this.tcpBuffer = Buffer.concat([this.tcpBuffer, data]);\n const { frames, rest } = splitTurnTcpFrames(this.tcpBuffer);\n this.tcpBuffer = rest;\n for (const frame of frames) {\n datagramReceived(frame, addr);\n }\n } else {\n datagramReceived(data, addr);\n }\n }\n\n private async send(data: Buffer, addr: Address) {\n if (this.transport.closed) {\n return;\n }\n\n await this.transport.send(\n isStreamTransport(this.transport) ? padTurnFrame(data) : data,\n addr,\n );\n }\n\n private async createPermission(peerAddress: Address) {\n const request = new Message(methods.CREATE_PERMISSION, classes.REQUEST);\n request\n .setAttribute(\"XOR-PEER-ADDRESS\", peerAddress)\n .setAttribute(\"USERNAME\", this.username)\n .setAttribute(\"REALM\", this.realm)\n .setAttribute(\"NONCE\", this.nonce);\n // Use requestWithRetry for stale-nonce (438) consistency with ChannelBind.\n await this.requestWithRetry(request, this.server);\n }\n\n private refresh = (exp: number) => {\n this.refreshHandle = cancelable<void>(async (_, __, onCancel) => {\n let run = true;\n onCancel.once(() => {\n run = false;\n });\n\n while (run) {\n // refresh before expire\n const delay = (5 / 6) * exp * 1000;\n log(\"refresh delay\", delay, { exp });\n await setTimeout(delay);\n\n const request = new Message(methods.REFRESH, classes.REQUEST);\n request.setAttribute(\"LIFETIME\", exp);\n\n try {\n const [message] = await this.requestWithRetry(request, this.server);\n exp = message.getAttributeValue(\"LIFETIME\");\n log(\"refresh\", { exp });\n } catch (error) {\n log(\"refresh error\", error);\n }\n }\n });\n };\n\n async request(\n request: Message,\n addr: Address,\n _integrityKey?: Buffer,\n retransmissionsOrOptions?: number | TransactionRequestOptions,\n onRequestSent?: (attempt: number) => void,\n ): Promise<[Message, Address]> {\n if (this.transactions[request.transactionIdHex]) {\n throw new Error(\"exist\");\n }\n if (this.integrityKey) {\n request\n .setAttribute(\"USERNAME\", this.username)\n .setAttribute(\"REALM\", this.realm)\n .setAttribute(\"NONCE\", this.nonce)\n .addMessageIntegrity(this.integrityKey)\n .addFingerprint();\n }\n\n // TURN server allocation/refresh uses default STUN retry policy unless\n // callers pass explicit options. Peer consent goes through StunOverTurnProtocol.\n // Prefer the TURN session integrity key for response verification.\n const resolvedAddr = await resolveRequestAddress(addr);\n const options = buildTransactionOptions(\n this.integrityKey,\n retransmissionsOrOptions,\n onRequestSent,\n );\n const transaction = new Transaction(request, resolvedAddr, this, options);\n this.transactions[request.transactionIdHex] = transaction;\n\n try {\n return await transaction.run();\n } catch (e) {\n throw e;\n } finally {\n delete this.transactions[request.transactionIdHex];\n }\n }\n\n async requestWithRetry(\n request: Message,\n addr: Address,\n ): Promise<[Message, Address]> {\n let message: Message, address: Address;\n try {\n [message, address] = await this.request(request, addr);\n } catch (error) {\n if (error instanceof TransactionFailed == false) {\n log(\"requestWithRetry error\", error);\n throw error;\n }\n\n // resolve dns address\n this.server = error.addr;\n\n const [errorCode] = error.response.getAttributeValue(\"ERROR-CODE\");\n const nonce = error.response.getAttributeValue(\"NONCE\");\n const realm = error.response.getAttributeValue(\"REALM\");\n\n if (\n ((errorCode === 401 && realm) || (errorCode === 438 && this.realm)) &&\n nonce\n ) {\n log(\"retry with nonce\", errorCode);\n\n this.nonce = nonce;\n if (errorCode === 401) {\n this.realm = realm;\n }\n this.integrityKey = makeIntegrityKey(\n this.username,\n this.realm!,\n this.password,\n );\n\n request.transactionId = randomTransactionId();\n [message, address] = await this.request(request, this.server);\n } else {\n throw error;\n }\n }\n return [message!, address!];\n }\n\n async sendData(data: Buffer, addr: Address) {\n let channel: TurnChannel | undefined;\n try {\n channel = await this.getChannel(addr);\n } catch (e) {\n // Keep original ChannelBind error for diagnostics (403/438/timeout).\n log(\"channelBind error; falling back to Send Indication\", e);\n }\n\n if (!channel) {\n await this.getPermission(addr);\n const indicate = new Message(methods.SEND, classes.INDICATION)\n .setAttribute(\"DATA\", data)\n .setAttribute(\"XOR-PEER-ADDRESS\", addr);\n\n await this.sendStun(indicate, this.server);\n return;\n }\n\n await this.send(encodeChannelData(channel.number, data), this.server);\n }\n\n /**\n * Ensure a CreatePermission exists for the peer IP.\n * Peer failures are isolated: a rejection for peer A does not poison peer B.\n */\n async getPermission(addr: Address) {\n const key = permissionKey(addr);\n\n if (this.permissionByAddr[key]) {\n return;\n }\n\n const existing = this.creatingPermissionByAddr.get(key);\n if (existing) {\n return existing;\n }\n\n const operation = this.permissionQueue.then(async () => {\n // Another caller may have succeeded while we waited on the queue.\n if (this.permissionByAddr[key]) {\n return;\n }\n\n await this.createPermission(addr);\n // Cache only after successful CreatePermission.\n this.permissionByAddr[key] = true;\n });\n\n // Do not let rejection poison subsequent peers on the shared queue.\n this.permissionQueue = operation.then(\n () => undefined,\n () => undefined,\n );\n\n this.creatingPermissionByAddr.set(key, operation);\n\n try {\n await operation;\n } catch (error) {\n log(\"createPermission error\", error);\n throw error;\n } finally {\n if (this.creatingPermissionByAddr.get(key) === operation) {\n this.creatingPermissionByAddr.delete(key);\n }\n }\n }\n\n /**\n * Ensure a ChannelBind exists for the peer transport address.\n * Peer failures are isolated; concurrent same-peer calls share one Promise.\n */\n async getChannel(addr: Address): Promise<TurnChannel> {\n const key = channelKey(addr);\n\n const existing = this.channelBindingByAddr.get(key);\n if (existing) {\n return existing;\n }\n\n // Fast path: bound and not due for refresh.\n const cached = this.channelByAddr[key];\n const now = int(Date.now() / 1000);\n if (cached && cached.refreshAt > now) {\n return cached;\n }\n\n const operation = this.channelBindQueue.then(() =>\n this.ensureChannel(addr),\n );\n\n // Do not let rejection poison subsequent peers on the shared queue.\n this.channelBindQueue = operation.then(\n () => undefined,\n () => undefined,\n );\n\n this.channelBindingByAddr.set(key, operation);\n\n try {\n return await operation;\n } catch (error) {\n log(\"channelBind error\", error);\n throw error;\n } finally {\n if (this.channelBindingByAddr.get(key) === operation) {\n this.channelBindingByAddr.delete(key);\n }\n }\n }\n\n /**\n * Create or refresh a channel for addr. Provisional mapping is installed\n * before the request so early ChannelData can be decoded; only a failed\n * *initial* bind rolls the mapping back. Failed channel numbers are never\n * reused.\n */\n private async ensureChannel(addr: Address): Promise<TurnChannel> {\n const key = channelKey(addr);\n const now = int(Date.now() / 1000);\n\n let channel = this.channelByAddr[key];\n if (channel && channel.refreshAt > now) {\n return channel;\n }\n\n const isNew = !channel;\n\n if (!channel) {\n channel = {\n number: this.channelNumber++,\n address: addr,\n refreshAt: 0,\n };\n // Provisional mapping for ChannelData that may arrive before success.\n this.channelByAddr[key] = channel;\n this.addrByChannel[channel.number] = addr;\n }\n\n try {\n await this.channelBind(channel.number, addr);\n channel.refreshAt = int(Date.now() / 1000) + this.channelRefreshTime;\n log(isNew ? \"channelBind\" : \"channelBind refresh\", channel);\n return channel;\n } catch (error) {\n if (isNew) {\n // Roll back provisional mapping only for a failed initial bind.\n delete this.channelByAddr[key];\n delete this.addrByChannel[channel.number];\n // Do not reuse the channel number (no channelNumber--).\n }\n throw error;\n }\n }\n\n private async channelBind(channelNumber: number, addr: Address) {\n const request = new Message(methods.CHANNEL_BIND, classes.REQUEST);\n request\n .setAttribute(\"CHANNEL-NUMBER\", channelNumber)\n .setAttribute(\"XOR-PEER-ADDRESS\", addr);\n const [response] = await this.requestWithRetry(request, this.server);\n if (response.messageMethod !== methods.CHANNEL_BIND) {\n throw new Error(\"should be CHANNEL_BIND\");\n }\n }\n\n async sendStun(message: Message, addr: Address) {\n await this.send(message.bytes, addr);\n }\n\n async close() {\n this.refreshHandle?.resolve?.();\n await this.transport.close();\n }\n}\n\nexport interface TurnClientConfig {\n address: Address;\n username: string;\n password: string;\n}\nexport interface TurnClientOptions {\n lifetime?: number;\n ssl?: boolean;\n transport?: \"udp\" | \"tcp\" | \"tls\";\n tlsOptions?: TlsConnectionOptions;\n portRange?: [number, number];\n interfaceAddresses?: InterfaceAddresses;\n}\n\nexport async function createTurnClient(\n { address, username, password }: TurnClientConfig,\n {\n lifetime,\n portRange,\n interfaceAddresses,\n ssl,\n tlsOptions,\n transport: transportType,\n }: TurnClientOptions = {},\n) {\n lifetime ??= DEFAULT_ALLOCATION_LIFETIME;\n transportType ??= ssl ? \"tls\" : \"udp\";\n\n const transport =\n transportType === \"udp\"\n ? await UdpTransport.init(\"udp4\", { portRange, interfaceAddresses })\n : transportType === \"tcp\"\n ? await TcpTransport.init(address)\n : await TlsTransport.init(address, tlsOptions);\n\n const turn = new TurnProtocol(\n address,\n username,\n password,\n lifetime,\n transport,\n );\n\n await turn.connectionMade();\n return turn;\n}\n\nexport async function createStunOverTurnClient(\n {\n address,\n username,\n password,\n }: {\n address: Address;\n username: string;\n password: string;\n },\n {\n lifetime,\n portRange,\n interfaceAddresses,\n ssl,\n tlsOptions,\n transport: transportType,\n }: {\n lifetime?: number;\n ssl?: boolean;\n transport?: \"udp\" | \"tcp\" | \"tls\";\n tlsOptions?: TlsConnectionOptions;\n portRange?: [number, number];\n interfaceAddresses?: InterfaceAddresses;\n } = {},\n) {\n const turn = await createTurnClient(\n {\n address,\n username,\n password,\n },\n {\n lifetime,\n portRange,\n interfaceAddresses,\n ssl,\n tlsOptions,\n transport: transportType,\n },\n );\n const turnTransport = new StunOverTurnProtocol(turn);\n return turnTransport;\n}\n\nexport function makeIntegrityKey(\n username: string,\n realm: string,\n password: string,\n) {\n return makeTurnIntegrityKey(username, realm, password);\n}\n"]}