Commit 31b2450 for jssip.net
commit 31b2450679159cf00ac26453ab08faa632ce8a16
Author: José Luis Millán <jmillan@aliax.net>
Date: Tue Dec 1 13:41:35 2026 +0100
tests: RTCSession (#1001)
diff --git a/package-lock.json b/package-lock.json
index f9d242b..ff51cc3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "jssip",
- "version": "3.13.8",
+ "version": "3.13.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "jssip",
- "version": "3.13.8",
+ "version": "3.13.9",
"license": "MIT",
"dependencies": {
"debug": "^4.3.1",
@@ -26,6 +26,7 @@
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-jest": "^29.12.1",
"eslint-plugin-prettier": "^5.5.5",
+ "fake-mediastreamtrack": "^2.2.1",
"globals": "^17.0.0",
"jest": "^30.2.0",
"open-cli": "^8.0.0",
@@ -2018,6 +2019,29 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@lukeed/csprng": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz",
+ "integrity": "sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/@lukeed/uuid": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@lukeed/uuid/-/uuid-2.0.1.tgz",
+ "integrity": "sha512-qC72D4+CDdjGqJvkFMMEAtancHUQ7/d/tAiHf64z8MopFDmcrtbcJuerDtFceuAfQJ2pDSfCKCtbqoGBNnwg0w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@lukeed/csprng": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.12",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",
@@ -4449,6 +4473,19 @@
"node": ">=0.10.0"
}
},
+ "node_modules/fake-mediastreamtrack": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/fake-mediastreamtrack/-/fake-mediastreamtrack-2.2.1.tgz",
+ "integrity": "sha512-SITLc7UTDirSdgLGORrlmqjWLJtbtfIz/xO7DwVbJH3f0ds+NQok4ccl/WEzz49NSgiUlXf2wDW0+y5C+TO6EA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "@lukeed/uuid": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
diff --git a/package.json b/package.json
index 5fcc8e6..8dcf6f2 100644
--- a/package.json
+++ b/package.json
@@ -62,6 +62,7 @@
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-jest": "^29.12.1",
"eslint-plugin-prettier": "^5.5.5",
+ "fake-mediastreamtrack": "^2.2.1",
"globals": "^17.0.0",
"jest": "^30.2.0",
"open-cli": "^8.0.0",
diff --git a/src/test/include/webrtc.ts b/src/test/include/webrtc.ts
new file mode 100644
index 0000000..98a1ab2
--- /dev/null
+++ b/src/test/include/webrtc.ts
@@ -0,0 +1,172 @@
+// A WebRTC environment that answers RTCSession the way a browser would,
+// without any media. Install it with installWebRTC() before building a UA.
+//
+// It is deliberately minimal: it covers what RTCSession asks of the browser
+// and nothing else. ICE gathering is reported as already complete, so an
+// offer or an answer is ready as soon as it is created. The tracks are real
+// W3C MediaStreamTrack implementations, from 'fake-mediastreamtrack'.
+
+import { FakeMediaStreamTrack } from 'fake-mediastreamtrack';
+
+export { FakeMediaStreamTrack };
+
+export class MockMediaStream {
+ readonly id = `stream-${++streamCount}`;
+
+ constructor(private readonly tracks: FakeMediaStreamTrack[]) {}
+
+ getTracks(): FakeMediaStreamTrack[] {
+ return [...this.tracks];
+ }
+
+ getAudioTracks(): FakeMediaStreamTrack[] {
+ return this.tracks.filter(track => track.kind === 'audio');
+ }
+
+ getVideoTracks(): FakeMediaStreamTrack[] {
+ return this.tracks.filter(track => track.kind === 'video');
+ }
+}
+
+let streamCount = 0;
+
+export type Description = { type: string; sdp: string };
+
+/**
+ * The SDP the mock offers and answers with. One audio line, enough for
+ * sdp-transform to parse it and for RTCSession to mangle its direction when
+ * the call is put on hold.
+ */
+export function sdp(sessionId: number): string {
+ return [
+ 'v=0',
+ `o=- ${sessionId} ${sessionId} IN IP4 127.0.0.1`,
+ 's=-',
+ 't=0 0',
+ 'm=audio 10000 RTP/AVP 0',
+ 'c=IN IP4 127.0.0.1',
+ 'a=rtpmap:0 PCMU/8000',
+ 'a=sendrecv',
+ '',
+ ].join('\r\n');
+}
+
+type Listener = (event: unknown) => void;
+
+export class MockRTCPeerConnection {
+ signalingState = 'stable';
+ iceConnectionState = 'new';
+ iceGatheringState = 'complete';
+ connectionState = 'new';
+
+ localDescription: Description | null = null;
+ remoteDescription: Description | null = null;
+
+ // Every description this connection has produced, in order.
+ readonly created: Description[] = [];
+
+ private readonly senders: { track: FakeMediaStreamTrack }[] = [];
+ private readonly listeners: Map<string, Listener[]> = new Map();
+ private readonly id = ++connectionCount;
+
+ createOffer(): Promise<Description> {
+ return this.describe('offer');
+ }
+
+ createAnswer(): Promise<Description> {
+ return this.describe('answer');
+ }
+
+ setLocalDescription(description: Description): Promise<void> {
+ this.localDescription = description;
+ this.signalingState =
+ description.type === 'offer' ? 'have-local-offer' : 'stable';
+
+ return Promise.resolve();
+ }
+
+ setRemoteDescription(description: Description): Promise<void> {
+ this.remoteDescription = description;
+ this.signalingState =
+ description.type === 'offer' ? 'have-remote-offer' : 'stable';
+
+ return Promise.resolve();
+ }
+
+ addTrack(track: FakeMediaStreamTrack): { track: FakeMediaStreamTrack } {
+ const sender = { track };
+
+ this.senders.push(sender);
+
+ return sender;
+ }
+
+ getSenders(): { track: FakeMediaStreamTrack }[] {
+ return [...this.senders];
+ }
+
+ getReceivers(): { track: FakeMediaStreamTrack }[] {
+ return [];
+ }
+
+ addEventListener(type: string, listener: Listener): void {
+ this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]);
+ }
+
+ removeEventListener(type: string, listener: Listener): void {
+ this.listeners.set(
+ type,
+ (this.listeners.get(type) ?? []).filter(entry => entry !== listener)
+ );
+ }
+
+ close(): void {
+ this.signalingState = 'closed';
+ this.connectionState = 'closed';
+ }
+
+ private describe(type: 'offer' | 'answer'): Promise<Description> {
+ const description = { type, sdp: sdp(this.id) };
+
+ this.created.push(description);
+
+ return Promise.resolve(description);
+ }
+}
+
+let connectionCount = 0;
+
+/**
+ * Defines the globals RTCSession reaches for. Returns the media stream that
+ * getUserMedia() hands out, so that a test can check what was attached.
+ */
+export function installWebRTC(): MockMediaStream {
+ const stream = new MockMediaStream([
+ new FakeMediaStreamTrack({ kind: 'audio' }),
+ ]);
+
+ const globals = globalThis as Record<string, unknown>;
+
+ globals['RTCPeerConnection'] = MockRTCPeerConnection;
+ globals['RTCSessionDescription'] = class {
+ type: string;
+ sdp: string;
+
+ constructor({ type, sdp: body }: Description) {
+ this.type = type;
+ this.sdp = body;
+ }
+ };
+
+ // UA.receiveRequest() refuses an incoming INVITE without this one.
+ globals['window'] = { RTCPeerConnection: MockRTCPeerConnection };
+
+ globals['navigator'] = {
+ userAgent: '',
+ mediaDevices: {
+ getUserMedia: (): Promise<MockMediaStream> => Promise.resolve(stream),
+ },
+ };
+
+ return stream;
+}
diff --git a/src/test/test-RTCSession.ts b/src/test/test-RTCSession.ts
new file mode 100644
index 0000000..8b5497d
--- /dev/null
+++ b/src/test/test-RTCSession.ts
@@ -0,0 +1,252 @@
+import { once } from 'events';
+
+import './include/common';
+import TestSocket from './include/TestSocket';
+import { installWebRTC, sdp } from './include/webrtc';
+import { startUA, stopUA } from './include/ua';
+import { body, buildResponse, header, method, tag } from './include/sipMessage';
+
+import { C, UA } from '../JsSIP';
+
+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';
+
+/* The session events worth logging. 'failed' is among them so that a call
+ * that goes wrong shows up in the log instead of as a timeout.
+ */
+enum EVENT {
+ CONNECTING = 'connecting',
+ SENDING = 'sending',
+ PROGRESS = 'progress',
+ ACCEPTED = 'accepted',
+ CONFIRMED = 'confirmed',
+ ENDED = 'ended',
+ FAILED = 'failed',
+}
+
+// Rings and answers, which is what most of these tests want of the peer.
+const RINGS_AND_ANSWERS = [100, 180, 200];
+
+/**
+ * A socket that plays the party being called: it answers the initial INVITE
+ * with the given statuses, takes re-INVITEs and accepts the BYE.
+ */
+class PeerSocket extends TestSocket {
+ constructor(private readonly toInvite: number[] = RINGS_AND_ANSWERS) {
+ super();
+ }
+
+ protected override onRequest(request: string): void {
+ switch (method(request)) {
+ case 'INVITE': {
+ // A re-INVITE travels within the dialog: no ringing, just an answer.
+ const statuses = tag(header(request, 'To')) ? [200] : this.toInvite;
+
+ this.receive(...statuses.map(status => this.answer(request, status)));
+ break;
+ }
+
+ case 'BYE': {
+ this.receive(this.answer(request, 200));
+ break;
+ }
+ }
+ }
+
+ // Media directions of the SDP offers the UA has sent, in order.
+ directions(): (string | undefined)[] {
+ return this.requests('INVITE').map(
+ invite =>
+ /^a=(sendrecv|sendonly|recvonly|inactive)$/m.exec(body(invite))?.[1]
+ );
+ }
+
+ private answer(request: string, status: number): string {
+ // Only a 2xx to an INVITE carries the SDP answer.
+ const answersTheOffer = status >= 200 && status < 300 && isInvite(request);
+
+ return buildResponse(request, status, {
+ // A 100 Trying creates nothing, so it gets no tag of ours.
+ toTag: status > 100 ? PEER_TAG : undefined,
+ extraHeaders: isInvite(request) ? [`Contact: <${PEER_CONTACT}>`] : [],
+ contentType: answersTheOffer ? 'application/sdp' : undefined,
+ body: answersTheOffer ? sdp(1) : undefined,
+ });
+ }
+}
+
+function isInvite(request: string): boolean {
+ return method(request) === 'INVITE';
+}
+
+/**
+ * Runs hold(), unhold() or renegotiate() and waits for the re-INVITE they send
+ * to be answered, which is when they call their 'done' callback. They return
+ * false instead when the session is in no state to re-offer.
+ */
+function reoffer(start: (done: () => void) => boolean): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (!start(resolve)) {
+ reject(new Error('the session refused to re-offer'));
+ }
+ });
+}
+
+describe('RTCSession', () => {
+ // A fresh environment per test: a session stops the tracks it was given.
+ beforeEach(() => {
+ installWebRTC();
+ });
+
+ test('an outgoing call, answered and then hung up', async () => {
+ const socket = new PeerSocket();
+ const ua = new UA({
+ sockets: socket,
+ uri: LOCAL_URI,
+ contact_uri: LOCAL_CONTACT,
+ register: false,
+ });
+
+ await startUA(ua);
+
+ const events: EVENT[] = [];
+
+ const session = ua.call(PEER_URI, {
+ mediaConstraints: { audio: true, video: false },
+ });
+
+ for (const event of Object.values(EVENT)) {
+ session.on(event, () => events.push(event));
+ }
+
+ await once(session, 'confirmed');
+
+ // The offer the UA sent, and the answer it took in.
+ const invite = socket.requests('INVITE')[0]!;
+
+ const sent = {
+ offer: header(invite, 'Content-Type'),
+ acked: socket.requests('ACK').length,
+ };
+
+ // 'ended' is emitted from within terminate(), so listen before calling it.
+ const ended = once(session, 'ended');
+
+ session.terminate();
+
+ await ended;
+
+ /* This costs the whole UA close timeout: the INVITE client transaction
+ * stays in 'accepted' for Timer M (RFC 6026, Section 7.2), so the UA
+ * never looks idle.
+ */
+ await stopUA(ua);
+
+ expect(events).toEqual([
+ EVENT.CONNECTING,
+ EVENT.SENDING,
+ EVENT.PROGRESS,
+ EVENT.ACCEPTED,
+ EVENT.CONFIRMED,
+ EVENT.ENDED,
+ ]);
+
+ expect(sent).toEqual({ offer: 'application/sdp', acked: 1 });
+
+ // The peer's answer reached the peer connection.
+ expect(session.connection.remoteDescription).toEqual({
+ type: 'answer',
+ sdp: sdp(1),
+ });
+
+ expect(socket.requests('BYE')).toHaveLength(1);
+ });
+
+ test('hold and unhold re-offer the call with the right direction', async () => {
+ const socket = new PeerSocket();
+ 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');
+
+ const events: string[] = [];
+
+ session.on('hold', () => events.push('hold'));
+ session.on('unhold', () => events.push('unhold'));
+
+ await reoffer(done => session.hold({}, done));
+
+ const onHold = session.isOnHold();
+
+ await reoffer(done => session.unhold({}, done));
+
+ const ended = once(session, 'ended');
+
+ session.terminate();
+
+ await ended;
+ await stopUA(ua);
+
+ expect(events).toEqual(['hold', 'unhold']);
+ expect(onHold).toEqual({ local: true, remote: false });
+ expect(session.isOnHold()).toEqual({ local: false, remote: false });
+
+ // The initial offer, the one that holds, and the one that resumes.
+ expect(socket.directions()).toEqual(['sendrecv', 'sendonly', 'sendrecv']);
+ });
+
+ test('a call the peer is too busy to take', async () => {
+ const socket = new PeerSocket([100, 180, 486]);
+ const ua = new UA({
+ sockets: socket,
+ uri: LOCAL_URI,
+ contact_uri: LOCAL_CONTACT,
+ register: false,
+ });
+
+ await startUA(ua);
+
+ const events: EVENT[] = [];
+
+ const session = ua.call(PEER_URI, {
+ mediaConstraints: { audio: true, video: false },
+ });
+
+ for (const event of Object.values(EVENT)) {
+ session.on(event, () => events.push(event));
+ }
+
+ const [failure] = await once(session, 'failed');
+
+ await stopUA(ua);
+
+ expect(events).toEqual([
+ EVENT.CONNECTING,
+ EVENT.SENDING,
+ EVENT.PROGRESS,
+ EVENT.FAILED,
+ ]);
+
+ expect(failure).toMatchObject({
+ originator: 'remote',
+ cause: C.causes.BUSY,
+ });
+
+ // A failed INVITE is still acknowledged, and no BYE follows it.
+ expect(socket.requests('ACK')).toHaveLength(1);
+ expect(socket.requests('BYE')).toHaveLength(0);
+ });
+});
diff --git a/src/test/test-SubscriberNotifier.ts b/src/test/test-SubscriberNotifier.ts
index 2f54556..043ac46 100644
--- a/src/test/test-SubscriberNotifier.ts
+++ b/src/test/test-SubscriberNotifier.ts
@@ -16,8 +16,8 @@ import {
import { startUA, untilDisconnected } from './include/ua';
-import { UA } from '../JsSIP';
import type { Subscriber } from '../Subscriber';
+import { UA } from '../JsSIP';
import type { EventHeader, SubscriptionStateHeader } from '../Grammar';
/**