Commit d606f35 for jssip.net

commit d606f350015409e36401686a5e119fe18b3bdaa4
Author: José Luis Millán <jmillan@aliax.net>
Date:   Thu Dec 3 13:26:20 2026 +0100

    TS RTCSession/DTMF

diff --git a/jest.config.mjs b/jest.config.mjs
index 99fc7d4..79e95d7 100644
--- a/jest.config.mjs
+++ b/jest.config.mjs
@@ -3,7 +3,7 @@ const config = {
 	verbose: true,
 	preset: 'ts-jest',
 	testEnvironment: 'node',
-	testRegex: 'src/test/test-.*\\.ts',
+	testRegex: 'src/test/(.*/)?test-.*\\.ts',
 	transform: {
 		// NOTE: Since tsconfig.json has `isolatedModules: true`, ts-jest
 		// transpiles each file on its own without type checking it, so a TS error
diff --git a/src/RTCSession.js b/src/RTCSession.js
index 59c6b79..2a721c9 100644
--- a/src/RTCSession.js
+++ b/src/RTCSession.js
@@ -12,7 +12,7 @@ const Timers = require('./Timers');
 const SIPMessage = require('./SIPMessage');
 const { Dialog, Status: DialogStatus } = require('./Dialog');
 const { RequestSender } = require('./RequestSender');
-const RTCSession_DTMF = require('./RTCSession/DTMF');
+const { DTMF: RTCSession_DTMF, C: DTMF_C } = require('./RTCSession/DTMF');
 const { Info: RTCSession_Info } = require('./RTCSession/Info');
 const {
 	ReferNotifier: RTCSession_ReferNotifier,
@@ -947,17 +947,17 @@ module.exports = class RTCSession extends EventEmitter {
 		if (duration && !Utils.isDecimal(duration)) {
 			throw new TypeError(`Invalid tone duration: ${duration}`);
 		} else if (!duration) {
-			duration = RTCSession_DTMF.C.DEFAULT_DURATION;
-		} else if (duration < RTCSession_DTMF.C.MIN_DURATION) {
+			duration = DTMF_C.DEFAULT_DURATION;
+		} else if (duration < DTMF_C.MIN_DURATION) {
 			logger.debug(
-				`"duration" value is lower than the minimum allowed, setting it to ${RTCSession_DTMF.C.MIN_DURATION} milliseconds`
+				`"duration" value is lower than the minimum allowed, setting it to ${DTMF_C.MIN_DURATION} milliseconds`
 			);
-			duration = RTCSession_DTMF.C.MIN_DURATION;
-		} else if (duration > RTCSession_DTMF.C.MAX_DURATION) {
+			duration = DTMF_C.MIN_DURATION;
+		} else if (duration > DTMF_C.MAX_DURATION) {
 			logger.debug(
-				`"duration" value is greater than the maximum allowed, setting it to ${RTCSession_DTMF.C.MAX_DURATION} milliseconds`
+				`"duration" value is greater than the maximum allowed, setting it to ${DTMF_C.MAX_DURATION} milliseconds`
 			);
-			duration = RTCSession_DTMF.C.MAX_DURATION;
+			duration = DTMF_C.MAX_DURATION;
 		} else {
 			duration = Math.abs(duration);
 		}
@@ -967,12 +967,12 @@ module.exports = class RTCSession extends EventEmitter {
 		if (interToneGap && !Utils.isDecimal(interToneGap)) {
 			throw new TypeError(`Invalid interToneGap: ${interToneGap}`);
 		} else if (!interToneGap) {
-			interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP;
-		} else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) {
+			interToneGap = DTMF_C.DEFAULT_INTER_TONE_GAP;
+		} else if (interToneGap < DTMF_C.MIN_INTER_TONE_GAP) {
 			logger.debug(
-				`"interToneGap" value is lower than the minimum allowed, setting it to ${RTCSession_DTMF.C.MIN_INTER_TONE_GAP} milliseconds`
+				`"interToneGap" value is lower than the minimum allowed, setting it to ${DTMF_C.MIN_INTER_TONE_GAP} milliseconds`
 			);
-			interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP;
+			interToneGap = DTMF_C.MIN_INTER_TONE_GAP;
 		} else {
 			interToneGap = Math.abs(interToneGap);
 		}
diff --git a/src/RTCSession/DTMF.js b/src/RTCSession/DTMF.js
deleted file mode 100644
index 1f96950..0000000
--- a/src/RTCSession/DTMF.js
+++ /dev/null
@@ -1,163 +0,0 @@
-const EventEmitter = require('events').EventEmitter;
-const { Logger } = require('../Logger');
-const JsSIP_C = require('../Constants');
-const Exceptions = require('../Exceptions');
-const Utils = require('../Utils');
-
-const logger = new Logger('RTCSession:DTMF');
-
-const C = {
-	MIN_DURATION: 70,
-	MAX_DURATION: 6000,
-	DEFAULT_DURATION: 100,
-	MIN_INTER_TONE_GAP: 50,
-	DEFAULT_INTER_TONE_GAP: 500,
-};
-
-module.exports = class DTMF extends EventEmitter {
-	constructor(session) {
-		super();
-
-		this._session = session;
-		this._direction = null;
-		this._tone = null;
-		this._duration = null;
-		this._request = null;
-	}
-
-	get tone() {
-		return this._tone;
-	}
-
-	get duration() {
-		return this._duration;
-	}
-
-	send(tone, options = {}) {
-		if (tone === undefined) {
-			throw new TypeError('Not enough arguments');
-		}
-
-		this._direction = 'outgoing';
-
-		// Check RTCSession Status.
-		if (
-			this._session.status !== this._session.C.STATUS_CONFIRMED &&
-			this._session.status !== this._session.C.STATUS_WAITING_FOR_ACK &&
-			this._session.status !== this._session.C.STATUS_1XX_RECEIVED
-		) {
-			throw new Exceptions.InvalidStateError(this._session.status);
-		}
-
-		const extraHeaders = Utils.cloneArray(options.extraHeaders);
-
-		this.eventHandlers = Utils.cloneObject(options.eventHandlers);
-
-		// Check tone type.
-		if (typeof tone === 'string') {
-			tone = tone.toUpperCase();
-		} else if (typeof tone === 'number') {
-			tone = tone.toString();
-		} else {
-			throw new TypeError(`Invalid tone: ${tone}`);
-		}
-
-		// Check tone value.
-		if (!tone.match(/^[0-9A-DR#*]$/)) {
-			throw new TypeError(`Invalid tone: ${tone}`);
-		} else {
-			this._tone = tone;
-		}
-
-		// Duration is checked/corrected in RTCSession.
-		this._duration = options.duration;
-
-		extraHeaders.push('Content-Type: application/dtmf-relay');
-
-		let body = `Signal=${this._tone}\r\n`;
-
-		body += `Duration=${this._duration}`;
-
-		this._session.newDTMF({
-			originator: 'local',
-			dtmf: this,
-			request: this._request,
-		});
-
-		this._session.sendRequest(JsSIP_C.INFO, {
-			extraHeaders,
-			eventHandlers: {
-				onSuccessResponse: response => {
-					this.emit('succeeded', {
-						originator: 'remote',
-						response,
-					});
-				},
-				onErrorResponse: response => {
-					if (this.eventHandlers.onFailed) {
-						this.eventHandlers.onFailed();
-					}
-
-					this.emit('failed', {
-						originator: 'remote',
-						response,
-					});
-				},
-				onRequestTimeout: () => {
-					this._session.onRequestTimeout();
-				},
-				onTransportError: () => {
-					this._session.onTransportError();
-				},
-				onDialogError: () => {
-					this._session.onDialogError();
-				},
-			},
-			body,
-		});
-	}
-
-	init_incoming(request) {
-		const reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;
-		const reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
-
-		this._direction = 'incoming';
-		this._request = request;
-
-		request.reply(200);
-
-		if (request.body) {
-			const body = request.body.split('\n');
-
-			if (body.length >= 1) {
-				if (reg_tone.test(body[0])) {
-					this._tone = body[0].replace(reg_tone, '$2');
-				}
-			}
-			if (body.length >= 2) {
-				if (reg_duration.test(body[1])) {
-					this._duration = parseInt(body[1].replace(reg_duration, '$2'), 10);
-				}
-			}
-		}
-
-		if (!this._duration) {
-			this._duration = C.DEFAULT_DURATION;
-		}
-
-		if (!this._tone) {
-			logger.debug('invalid INFO DTMF received, discarded');
-		} else {
-			this._session.newDTMF({
-				originator: 'remote',
-				dtmf: this,
-				request,
-			});
-		}
-	}
-};
-
-/**
- * Expose C object.
- */
-module.exports.C = C;
diff --git a/src/RTCSession/DTMF.ts b/src/RTCSession/DTMF.ts
new file mode 100644
index 0000000..61fdea3
--- /dev/null
+++ b/src/RTCSession/DTMF.ts
@@ -0,0 +1,289 @@
+import { EventEmitter } from 'events';
+
+import * as JsSIP_C from '../Constants';
+import type { Direction, Originator } from '../Constants';
+import type { DialogSendRequestOptions } from '../Dialog';
+import { InvalidStateError } from '../Exceptions';
+import { Logger } from '../Logger';
+import type { IncomingRequest, IncomingResponse } from '../SIPMessage';
+import * as Utils from '../Utils';
+
+const logger = new Logger('RTCSession:DTMF');
+
+/**
+ * Bounds the library applies to the duration of a tone and to the gap between
+ * tones, all in milliseconds.
+ */
+export const C = {
+	MIN_DURATION: 70,
+	MAX_DURATION: 6000,
+	DEFAULT_DURATION: 100,
+	MIN_INTER_TONE_GAP: 50,
+	DEFAULT_INTER_TONE_GAP: 500,
+};
+
+/**
+ * Reported when the INFO carrying the tone got a final response.
+ */
+export type DTMFEvent = {
+	originator: Originator;
+	response: IncomingResponse;
+};
+
+/**
+ * The events a {@link DTMF} emits.
+ */
+export type DTMFEventMap = {
+	succeeded: (event: DTMFEvent) => void;
+	failed: (event: DTMFEvent) => void;
+};
+
+/**
+ * Callbacks the `RTCSession` gives a tone it sends.
+ *
+ * @internal
+ */
+export type DTMFEventHandlers = {
+	onFailed?: () => void;
+};
+
+/**
+ * Options accepted by `send()`.
+ */
+export type SendDTMFOptions = {
+	/**
+	 * Whole `Name: value` header field lines to add to the INFO.
+	 */
+	extraHeaders?: string[] | null;
+	/**
+	 * How long (in milliseconds) the tone lasts, announced in the body.
+	 *
+	 * @remarks
+	 * - Clamped by `RTCSession` to between {@link C.MIN_DURATION} and
+	 *   {@link C.MAX_DURATION}.
+	 */
+	duration?: number;
+	/**
+	 * @internal
+	 */
+	eventHandlers?: DTMFEventHandlers | null;
+};
+
+/**
+ * The `RTCSession` surface a tone depends on.
+ *
+ * TODO: Replace with `import type { RTCSession } from '../RTCSession'` once
+ * `RTCSession` is ported to TypeScript.
+ */
+export interface DTMFSession {
+	readonly status: number;
+	readonly C: {
+		STATUS_CONFIRMED: number;
+		STATUS_WAITING_FOR_ACK: number;
+		STATUS_1XX_RECEIVED: number;
+	};
+
+	sendRequest(method: string, options?: DialogSendRequestOptions): void;
+	newDTMF(data: {
+		originator: Originator;
+		dtmf: DTMF;
+		request: IncomingRequest | null;
+	}): void;
+	onTransportError(): void;
+	onRequestTimeout(): void;
+	onDialogError(): void;
+}
+
+/**
+ * Sends and receives a DTMF tone within a session, carried in an INFO
+ * request with an `application/dtmf-relay` body.
+ *
+ * @remarks
+ * - This is the `INFO` transport of
+ *   {@link Constants.DTMF_TRANSPORT}. The `RFC2833` one travels in the media
+ *   stream instead and never reaches this class.
+ */
+export class DTMF extends EventEmitter {
+	#session: DTMFSession;
+	#direction: Direction | null;
+	#tone?: string;
+	#duration?: number;
+	#request: IncomingRequest | null;
+
+	/**
+	 * Callbacks given by the `RTCSession` that is sending a string of tones.
+	 *
+	 * @internal
+	 */
+	eventHandlers: DTMFEventHandlers = {};
+
+	constructor(session: DTMFSession) {
+		super();
+
+		this.#session = session;
+		this.#direction = null;
+		this.#request = null;
+	}
+
+	/**
+	 * Whether the tone was sent or received.
+	 */
+	get direction(): Direction | null {
+		return this.#direction;
+	}
+
+	/**
+	 * The tone itself, one of `0` to `9`, `A` to `D`, `R`, `#` or `*`.
+	 */
+	get tone(): string | undefined {
+		return this.#tone;
+	}
+
+	/**
+	 * How long (in milliseconds) the tone lasts.
+	 */
+	get duration(): number | undefined {
+		return this.#duration;
+	}
+
+	/**
+	 * Send the given tone within the session.
+	 *
+	 * @throws
+	 * - `TypeError` if `tone` is not given, is not a string or a number, or is
+	 *   not one of the accepted tones.
+	 * - {@link InvalidStateError} if the session is neither confirmed, waiting
+	 *   for the ACK, nor in early state.
+	 */
+	send(tone: string | number, options: SendDTMFOptions = {}): void {
+		if (tone === undefined) {
+			throw new TypeError('Not enough arguments');
+		}
+
+		this.#direction = 'outgoing';
+
+		// Check RTCSession Status.
+		if (
+			this.#session.status !== this.#session.C.STATUS_CONFIRMED &&
+			this.#session.status !== this.#session.C.STATUS_WAITING_FOR_ACK &&
+			this.#session.status !== this.#session.C.STATUS_1XX_RECEIVED
+		) {
+			throw new InvalidStateError(this.#session.status);
+		}
+
+		const extraHeaders = Utils.cloneArray(options.extraHeaders);
+
+		this.eventHandlers = Utils.cloneObject(options.eventHandlers);
+
+		// Check tone type.
+		if (typeof tone === 'string') {
+			tone = tone.toUpperCase();
+		} else if (typeof tone === 'number') {
+			tone = tone.toString();
+		} else {
+			throw new TypeError(`Invalid tone: ${String(tone)}`);
+		}
+
+		// Check tone value.
+		if (!tone.match(/^[0-9A-DR#*]$/)) {
+			throw new TypeError(`Invalid tone: ${tone}`);
+		} else {
+			this.#tone = tone;
+		}
+
+		// Duration is checked/corrected in RTCSession.
+		this.#duration = options.duration;
+
+		extraHeaders.push('Content-Type: application/dtmf-relay');
+
+		let body = `Signal=${this.#tone}\r\n`;
+
+		body += `Duration=${this.#duration}`;
+
+		this.#session.newDTMF({
+			originator: 'local',
+			dtmf: this,
+			request: this.#request,
+		});
+
+		this.#session.sendRequest(JsSIP_C.INFO, {
+			extraHeaders,
+			eventHandlers: {
+				onSuccessResponse: response => {
+					this.emit('succeeded', {
+						originator: 'remote',
+						response,
+					});
+				},
+				onErrorResponse: response => {
+					if (this.eventHandlers.onFailed) {
+						this.eventHandlers.onFailed();
+					}
+
+					this.emit('failed', {
+						originator: 'remote',
+						response,
+					});
+				},
+				onRequestTimeout: () => {
+					this.#session.onRequestTimeout();
+				},
+				onTransportError: () => {
+					this.#session.onTransportError();
+				},
+				onDialogError: () => {
+					this.#session.onDialogError();
+				},
+			},
+			body,
+		});
+	}
+
+	/**
+	 * Take over a received INFO request carrying a tone, answering it with a
+	 * 200.
+	 *
+	 * @remarks
+	 * - Called by the `RTCSession`. The application must not call it.
+	 * - A request whose body carries no recognizable tone is discarded, so no
+	 *   event is reported for it.
+	 */
+	init_incoming(request: IncomingRequest): void {
+		const reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;
+		const reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
+
+		this.#direction = 'incoming';
+		this.#request = request;
+
+		request.reply(200);
+
+		if (request.body) {
+			const body = request.body.split('\n');
+
+			if (body.length >= 1) {
+				if (reg_tone.test(body[0]!)) {
+					this.#tone = body[0]!.replace(reg_tone, '$2');
+				}
+			}
+			if (body.length >= 2) {
+				if (reg_duration.test(body[1]!)) {
+					this.#duration = parseInt(body[1]!.replace(reg_duration, '$2'), 10);
+				}
+			}
+		}
+
+		if (!this.#duration) {
+			this.#duration = C.DEFAULT_DURATION;
+		}
+
+		if (!this.#tone) {
+			logger.debug('invalid INFO DTMF received, discarded');
+		} else {
+			this.#session.newDTMF({
+				originator: 'remote',
+				dtmf: this,
+				request,
+			});
+		}
+	}
+}
diff --git a/src/test/RTCSession/test-DTMF.ts b/src/test/RTCSession/test-DTMF.ts
new file mode 100644
index 0000000..f930c3a
--- /dev/null
+++ b/src/test/RTCSession/test-DTMF.ts
@@ -0,0 +1,529 @@
+import type { EventEmitter } from 'events';
+import { once } from 'events';
+import { setTimeout as delay } from 'timers/promises';
+
+import '../include/common';
+import {
+	body,
+	buildRequest,
+	buildResponse,
+	header,
+	method,
+	status,
+} from '../include/sipMessage';
+import TestSocket from '../include/TestSocket';
+import { installWebRTC, sdp } from '../include/webrtc';
+import { startUA, stopUA } from '../include/ua';
+
+import type { Originator } from '../../Constants';
+import type { DialogSendRequestOptions } from '../../Dialog';
+import { InvalidStateError } from '../../Exceptions';
+import type { DTMFSession } from '../../RTCSession/DTMF';
+import { C, DTMF } from '../../RTCSession/DTMF';
+import type { RTCSession } from '../../RTCSession';
+import type { IncomingRequest, IncomingResponse } from '../../SIPMessage';
+import { UA } from '../../JsSIP';
+
+const CONTENT_TYPE = 'application/dtmf-relay';
+
+/**
+ * What a session reports through 'newDTMF'.
+ */
+type NewDTMFEvent = {
+	originator: Originator;
+	dtmf: DTMF;
+};
+
+// A response is only handed around, so nothing has to be in it.
+const RESPONSE = {} as IncomingResponse;
+
+// The RTCSession status codes a tone looks at. The values are the ones
+// RTCSession gives them, though the tone only ever compares the status it is
+// told against these.
+const STATUS = {
+	STATUS_1XX_RECEIVED: 2,
+	STATUS_WAITING_FOR_ACK: 6,
+	STATUS_TERMINATED: 8,
+	STATUS_CONFIRMED: 9,
+};
+
+/**
+ * Stands in for the `RTCSession` a tone belongs to, recording what the tone
+ * asks of it.
+ */
+class FakeSession implements DTMFSession {
+	status: number = STATUS.STATUS_CONFIRMED;
+
+	readonly C = STATUS;
+
+	// Every request the tone has asked to be sent, in order.
+	readonly sent: { method: string; options: DialogSendRequestOptions }[] = [];
+
+	// The tones reported through newDTMF().
+	readonly reported: NewDTMFEvent[] = [];
+
+	// The failures the tone has handed back, in order.
+	readonly failures: string[] = [];
+
+	sendRequest(name: string, options: DialogSendRequestOptions = {}): void {
+		this.sent.push({ method: name, options });
+	}
+
+	newDTMF(data: NewDTMFEvent): void {
+		this.reported.push(data);
+	}
+
+	onTransportError(): void {
+		this.failures.push('transport');
+	}
+
+	onRequestTimeout(): void {
+		this.failures.push('timeout');
+	}
+
+	onDialogError(): void {
+		this.failures.push('dialog');
+	}
+
+	/**
+	 * The INFO the tone sent, as the request sender sees it.
+	 */
+	get info(): DialogSendRequestOptions {
+		return this.sent[0]!.options;
+	}
+
+	/**
+	 * The callbacks the request sender would invoke on the INFO.
+	 */
+	get handlers(): NonNullable<DialogSendRequestOptions['eventHandlers']> {
+		return this.info.eventHandlers!;
+	}
+}
+
+/**
+ * Stands in for a received INFO, of which a tone only reads the body and
+ * which it only answers.
+ */
+class FakeRequest {
+	// Status codes this request has been answered with, in order.
+	readonly replies: number[] = [];
+
+	readonly body: string;
+
+	constructor(payload: string) {
+		this.body = payload;
+	}
+
+	reply(code: number): void {
+		this.replies.push(code);
+	}
+
+	get asRequest(): IncomingRequest {
+		return this as unknown as IncomingRequest;
+	}
+}
+
+describe('DTMF.send()', () => {
+	test('the INFO carries the tone and the duration', () => {
+		const session = new FakeSession();
+
+		new DTMF(session).send('1', { duration: 250 });
+
+		expect(session.sent).toHaveLength(1);
+		expect(session.sent[0]!.method).toBe('INFO');
+		expect(session.info.extraHeaders).toEqual([
+			`Content-Type: ${CONTENT_TYPE}`,
+		]);
+		expect(session.info.body).toBe('Signal=1\r\nDuration=250');
+	});
+
+	test('extra header fields are kept ahead of the content type', () => {
+		const session = new FakeSession();
+
+		new DTMF(session).send('1', {
+			duration: 100,
+			extraHeaders: ['X-Foo: bar'],
+		});
+
+		expect(session.info.extraHeaders).toEqual([
+			'X-Foo: bar',
+			`Content-Type: ${CONTENT_TYPE}`,
+		]);
+	});
+
+	test('a lowercase tone is sent uppercased', () => {
+		const session = new FakeSession();
+		const dtmf = new DTMF(session);
+
+		dtmf.send('d', { duration: 100 });
+
+		expect(dtmf.tone).toBe('D');
+		expect(session.info.body).toBe('Signal=D\r\nDuration=100');
+	});
+
+	test('a numeric tone is sent as its digit', () => {
+		const session = new FakeSession();
+		const dtmf = new DTMF(session);
+
+		dtmf.send(7, { duration: 100 });
+
+		expect(dtmf.tone).toBe('7');
+	});
+
+	test('the tone is reported as outgoing before the INFO goes out', () => {
+		const session = new FakeSession();
+		const dtmf = new DTMF(session);
+
+		expect(dtmf.direction).toBeNull();
+
+		dtmf.send('1', { duration: 100 });
+
+		expect(session.reported).toHaveLength(1);
+		expect(session.reported[0]!.originator).toBe('local');
+		expect(session.reported[0]!.dtmf).toBe(dtmf);
+		expect(dtmf.direction).toBe('outgoing');
+	});
+
+	test('a tone that is not a DTMF symbol is refused', () => {
+		const session = new FakeSession();
+
+		for (const tone of ['X', '12', '', ' 1']) {
+			expect(() => new DTMF(session).send(tone)).toThrow(TypeError);
+		}
+
+		// Anything that is neither a string nor a number is refused outright.
+		expect(() => new DTMF(session).send(null as unknown as string)).toThrow(
+			TypeError
+		);
+
+		expect(session.sent).toHaveLength(0);
+	});
+
+	test('no tone at all is refused', () => {
+		const session = new FakeSession();
+
+		expect(() =>
+			new DTMF(session).send(undefined as unknown as string)
+		).toThrow(TypeError);
+	});
+
+	test('a session in no state to send is refused', () => {
+		const session = new FakeSession();
+
+		session.status = STATUS.STATUS_TERMINATED;
+
+		expect(() => new DTMF(session).send('1')).toThrow(InvalidStateError);
+		expect(session.sent).toHaveLength(0);
+	});
+
+	test('a final positive response reports "succeeded"', () => {
+		const session = new FakeSession();
+		const dtmf = new DTMF(session);
+
+		const outcomes: unknown[] = [];
+
+		dtmf.on('succeeded', event => outcomes.push(event));
+		dtmf.on('failed', event => outcomes.push(event));
+
+		dtmf.send('1', { duration: 100 });
+		session.handlers.onSuccessResponse!(RESPONSE);
+
+		expect(outcomes).toEqual([{ originator: 'remote', response: RESPONSE }]);
+	});
+
+	test('a negative response reports "failed" and calls onFailed back', () => {
+		const session = new FakeSession();
+		const dtmf = new DTMF(session);
+
+		const outcomes: unknown[] = [];
+
+		let failed = false;
+
+		dtmf.on('failed', event => outcomes.push(event));
+
+		dtmf.send('1', {
+			duration: 100,
+			eventHandlers: {
+				onFailed: () => {
+					failed = true;
+				},
+			},
+		});
+
+		session.handlers.onErrorResponse!(RESPONSE);
+
+		expect(failed).toBe(true);
+		expect(outcomes).toEqual([{ originator: 'remote', response: RESPONSE }]);
+	});
+
+	test('a failure of the request itself is handed back to the session', () => {
+		const session = new FakeSession();
+
+		new DTMF(session).send('1', { duration: 100 });
+
+		session.handlers.onTransportError!();
+		session.handlers.onRequestTimeout!();
+		session.handlers.onDialogError!(RESPONSE);
+
+		expect(session.failures).toEqual(['transport', 'timeout', 'dialog']);
+	});
+});
+
+describe('DTMF.init_incoming()', () => {
+	test('the INFO is answered and the tone reported', () => {
+		const session = new FakeSession();
+		const dtmf = new DTMF(session);
+		const request = new FakeRequest('Signal=5\r\nDuration=250');
+
+		dtmf.init_incoming(request.asRequest);
+
+		expect(request.replies).toEqual([200]);
+		expect(dtmf.direction).toBe('incoming');
+		expect(dtmf.tone).toBe('5');
+		expect(dtmf.duration).toBe(250);
+		expect(session.reported).toHaveLength(1);
+		expect(session.reported[0]!.originator).toBe('remote');
+		expect(session.reported[0]!.dtmf).toBe(dtmf);
+	});
+
+	test('a body without a duration falls back to the default one', () => {
+		const session = new FakeSession();
+		const dtmf = new DTMF(session);
+
+		dtmf.init_incoming(new FakeRequest('Signal=*').asRequest);
+
+		expect(dtmf.tone).toBe('*');
+		expect(dtmf.duration).toBe(C.DEFAULT_DURATION);
+	});
+
+	test('a body carrying no tone is answered but reported to nobody', () => {
+		const session = new FakeSession();
+		const request = new FakeRequest('what you will');
+
+		new DTMF(session).init_incoming(request.asRequest);
+
+		expect(request.replies).toEqual([200]);
+		expect(session.reported).toHaveLength(0);
+	});
+});
+
+// What follows drives the tones through a real session, so that what the
+// tests above assert against a stand-in is known to match what RTCSession
+// asks of a tone and what it does with the result.
+
+const LOCAL_URI = 'sip:alice@example.com';
+const LOCAL_CONTACT = 'sip:alice@abcdefabcdef.invalid;transport=ws';
+const PEER_URI = 'sip:bob@example.com';
+const PEER_CONTACT = 'sip:bob@192.0.2.1:5060';
+const PEER_TAG = 'peertag';
+
+/**
+ * A socket that plays the party being called: it answers the INVITE, answers
+ * every INFO with the given status code and takes the BYE. It can also send
+ * an INFO of its own within the established dialog.
+ */
+class PeerSocket extends TestSocket {
+	// CSeq of the last request the peer sent within the dialog.
+	private cseq = 0;
+
+	constructor(private readonly toInfo: number = 200) {
+		super();
+	}
+
+	protected override onRequest(request: string): void {
+		switch (method(request)) {
+			case 'INVITE': {
+				this.receive(
+					...[100, 180, 200].map(code => this.answer(request, code))
+				);
+				break;
+			}
+
+			case 'INFO': {
+				this.receive(this.answer(request, this.toInfo));
+				break;
+			}
+
+			case 'BYE': {
+				this.receive(this.answer(request, 200));
+				break;
+			}
+		}
+	}
+
+	/**
+	 * Sends an INFO within the dialog the INVITE established.
+	 */
+	sendInfo(payload: string): void {
+		const invite = this.requests('INVITE')[0]!;
+
+		this.receive(
+			buildRequest('INFO', LOCAL_CONTACT, {
+				// The dialog as the peer sees it: its own URI and tag in the From,
+				// ours in the To.
+				from: `${header(invite, 'To')};tag=${PEER_TAG}`,
+				to: header(invite, 'From'),
+				callId: header(invite, 'Call-ID'),
+				cseq: ++this.cseq,
+				contentType: CONTENT_TYPE,
+				body: payload,
+			})
+		);
+	}
+
+	private answer(request: string, code: number): string {
+		const invite = method(request) === 'INVITE';
+		const answersTheOffer = invite && code === 200;
+
+		return buildResponse(request, code, {
+			// A 100 Trying creates nothing, so it gets no tag of ours.
+			toTag: code > 100 ? PEER_TAG : undefined,
+			extraHeaders: invite ? [`Contact: <${PEER_CONTACT}>`] : [],
+			contentType: answersTheOffer ? 'application/sdp' : undefined,
+			body: answersTheOffer ? sdp(1) : undefined,
+		});
+	}
+}
+
+/**
+ * Places a call and resolves once it is confirmed.
+ */
+async function establish(socket: PeerSocket): Promise<[UA, RTCSession]> {
+	const ua = new UA({
+		sockets: socket,
+		uri: LOCAL_URI,
+		contact_uri: LOCAL_CONTACT,
+		register: false,
+	});
+
+	await startUA(ua);
+
+	const session = ua.call(PEER_URI, {
+		mediaConstraints: { audio: true, video: false },
+	});
+
+	await once(session, 'confirmed');
+
+	return [ua, session];
+}
+
+/**
+ * Hangs the call up and stops the UA.
+ */
+async function hangUp(ua: UA, session: RTCSession): Promise<void> {
+	// 'ended' is emitted from within terminate(), so listen before calling it.
+	const ended = once(session, 'ended');
+
+	session.terminate();
+
+	await ended;
+	await stopUA(ua);
+}
+
+/**
+ * Collects the tones a session reports, incoming and outgoing alike.
+ *
+ * @remarks
+ * - The hand-written declarations of `RTCSession` give 'newDTMF' a union of
+ *   listener types that no single signature satisfies, so this goes through
+ *   the plain `EventEmitter` until `RTCSession` is ported to TypeScript.
+ */
+function collectDTMF(session: RTCSession): NewDTMFEvent[] {
+	const reported: NewDTMFEvent[] = [];
+
+	(session as EventEmitter).on('newDTMF', (event: NewDTMFEvent) =>
+		reported.push(event)
+	);
+
+	return reported;
+}
+
+/**
+ * The INFO requests the UA has sent, once there are at least as many as
+ * asked for or the wait runs out.
+ */
+async function untilSent(socket: TestSocket, count: number): Promise<string[]> {
+	for (let i = 0; i < 100 && socket.requests('INFO').length < count; i++) {
+		await delay(10);
+	}
+
+	return socket.requests('INFO');
+}
+
+describe('DTMF within a session', () => {
+	// A fresh environment per test: a session stops the tracks it was given.
+	beforeEach(() => {
+		installWebRTC();
+	});
+
+	test('a string of tones goes out one INFO at a time', async () => {
+		const socket = new PeerSocket();
+		const [ua, session] = await establish(socket);
+
+		const reported = collectDTMF(session);
+
+		// A duration below the minimum, so that the clamping RTCSession does
+		// before handing the tone over shows up on the wire.
+		session.sendDTMF('1a#', { duration: 1, interToneGap: 50 });
+
+		const infos = await untilSent(socket, 3);
+
+		await hangUp(ua, session);
+
+		expect(infos.map(info => header(info, 'Content-Type'))).toEqual(
+			Array<string>(3).fill(CONTENT_TYPE)
+		);
+
+		expect(infos.map(info => body(info))).toEqual([
+			`Signal=1\r\nDuration=${C.MIN_DURATION}`,
+			`Signal=A\r\nDuration=${C.MIN_DURATION}`,
+			`Signal=#\r\nDuration=${C.MIN_DURATION}`,
+		]);
+
+		expect(reported.map(event => [event.originator, event.dtmf.tone])).toEqual([
+			['local', '1'],
+			['local', 'A'],
+			['local', '#'],
+		]);
+	});
+
+	test('a negative response drops the tones still queued', async () => {
+		const socket = new PeerSocket(488);
+		const [ua, session] = await establish(socket);
+
+		const reported = collectDTMF(session);
+
+		session.sendDTMF('123', { duration: 70, interToneGap: 50 });
+
+		const [outcome] = await once(reported[0]!.dtmf, 'failed');
+
+		// Long enough for the two remaining tones to have gone out.
+		await delay(300);
+
+		const infos = socket.requests('INFO');
+
+		await hangUp(ua, session);
+
+		expect(outcome).toMatchObject({ originator: 'remote' });
+		expect(infos.map(info => body(info))).toEqual(['Signal=1\r\nDuration=70']);
+	});
+
+	test('an incoming INFO is answered and reported', async () => {
+		const socket = new PeerSocket();
+		const [ua, session] = await establish(socket);
+
+		const reported = collectDTMF(session);
+
+		socket.sendInfo('Signal=5\r\nDuration=250');
+
+		await delay(50);
+		await hangUp(ua, session);
+
+		expect(reported).toHaveLength(1);
+		expect(reported[0]!.originator).toBe('remote');
+		expect(reported[0]!.dtmf.direction).toBe('incoming');
+		expect(reported[0]!.dtmf.tone).toBe('5');
+		expect(reported[0]!.dtmf.duration).toBe(250);
+		expect(socket.responses('INFO').map(status)).toEqual([200]);
+	});
+});