Commit 55e9336 for jssip.net

commit 55e93362cc2217d9e5d358a2c264fb3cc3bef0d5
Author: José Luis Millán <jmillan@aliax.net>
Date:   Tue Dec 1 11:00:43 2026 +0100

    Subscriber: fix, initial NOTIFY arriving before the 2xx to SUBSCRIBE (#997)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6cf683..6123136 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@

 - Subscriber: Add 'response' to 'terminated' event and unsubscribe upon UA.stop() (#978). Thanks to @neutrino38.
 - ReferSubscriber: Fix, Replaces generation on Refer-To header field (#992). Thanks to @michele-lunardi-vianova.
+- Subscriber: Fix, accept the initial NOTIFY arriving before the 2xx response to the SUBSCRIBE (#993). Thanks to @hyponex and @AhmedElbashier for reporting.

 ### 3.13.9

diff --git a/src/Subscriber.d.ts b/src/Subscriber.d.ts
index c38c9e8..a2edc45 100644
--- a/src/Subscriber.d.ts
+++ b/src/Subscriber.d.ts
@@ -34,7 +34,7 @@ export interface MessageEventMap {

 interface SubscriberOptions {
 	expires?: number;
-	contentType: string;
+	contentType?: string;
 	allowEvents?: string;
 	// eslint-disable-next-line @typescript-eslint/no-explicit-any
 	params?: Record<string, any>;
@@ -47,7 +47,7 @@ export class Subscriber extends EventEmitter<MessageEventMap> {
 		target: string,
 		eventName: string,
 		accept: string,
-		options: SubscriberOptions
+		options?: SubscriberOptions
 	);
 	subscribe(body?: string): void;
 	terminate(body?: string): void;
diff --git a/src/Subscriber.js b/src/Subscriber.js
index 1530279..088ef9f 100644
--- a/src/Subscriber.js
+++ b/src/Subscriber.js
@@ -69,7 +69,7 @@ module.exports = class Subscriber extends EventEmitter {
 		target,
 		eventName,
 		accept,
-		{ expires, contentType, allowEvents, params, extraHeaders }
+		{ expires, contentType, allowEvents, params, extraHeaders } = {}
 	) {
 		logger.debug('new');

@@ -132,6 +132,13 @@ module.exports = class Subscriber extends EventEmitter {
 		// Dialog.
 		this._dialog = null;

+		// Whether the 2xx response to the initial SUBSCRIBE was already processed.
+		this._accepted = false;
+
+		// CSeq of the initial SUBSCRIBE. The dialog created by an early NOTIFY
+		// must continue this sequence (RFC 6665 4.1.2.4).
+		this._initial_cseq = null;
+
 		// To refresh subscription.
 		this._expires_timer = null;
 		this._expires_timestamp = null;
@@ -207,6 +214,54 @@ module.exports = class Subscriber extends EventEmitter {
 		this._terminateDialog(C.SUBSCRIBE_TRANSPORT_ERROR);
 	}

+	/**
+	 * Whether this subscriber is still waiting for the NOTIFY that creates the
+	 * subscription dialog and the given NOTIFY belongs to its initial SUBSCRIBE.
+	 *
+	 * RFC 6665 4.1.2.4: the first NOTIFY may arrive before the 2xx response to
+	 * the initial SUBSCRIBE, in which case it is the one creating the dialog.
+	 *
+	 * @param {string} call_id - Call-ID of the received NOTIFY.
+	 * @param {string} to_tag - To tag of the received NOTIFY.
+	 */
+	matchEarlyNotify(call_id, to_tag) {
+		return (
+			this._dialog === null &&
+			this._state === C.STATE_WAITING_NOTIFY &&
+			call_id === this._params.call_id &&
+			to_tag === this._params.from_tag
+		);
+	}
+
+	/**
+	 * UA callback. Process the NOTIFY that arrived before the 2xx response to
+	 * the initial SUBSCRIBE. It creates the subscription dialog (RFC 6665
+	 * 4.1.2.4).
+	 */
+	receiveEarlyNotify(request) {
+		const dialog = new Dialog(this, request, 'UAS');
+
+		if (dialog.error) {
+			// NOTIFY without Contact.
+			logger.warn(dialog.error);
+			request.reply(400);
+
+			return;
+		}
+
+		/* The dialog is created by an incoming request, so it has no local
+		 * sequence number yet. Continue the sequence of the initial SUBSCRIBE,
+		 * otherwise the refresh would use a random (possibly lower) CSeq.
+		 */
+		dialog.local_seqnum = this._initial_cseq;
+
+		this._dialog = dialog;
+
+		logger.debug('dialog created by the NOTIFY preceding the SUBSCRIBE 2xx');
+
+		dialog.receiveRequest(request);
+	}
+
 	/**
 	 * Dialog callback.
 	 */
@@ -421,6 +476,8 @@ module.exports = class Subscriber extends EventEmitter {
 			body
 		);

+		this._initial_cseq = request.cseq;
+
 		const request_sender = new RequestSender(this._ua, request, {
 			onRequestTimeout: () => {
 				this.onRequestTimeout();
@@ -428,6 +485,14 @@ module.exports = class Subscriber extends EventEmitter {
 			onTransportError: () => {
 				this.onTransportError();
 			},
+			onAuthenticated: authenticated_request => {
+				// The SUBSCRIBE is re-sent with an increased CSeq.
+				this._initial_cseq = authenticated_request.cseq;
+
+				if (this._dialog) {
+					this._dialog.local_seqnum = this._initial_cseq;
+				}
+			},
 			onReceiveResponse: response => {
 				this._receiveSubscribeResponse(response);
 			},
@@ -487,7 +552,7 @@ module.exports = class Subscriber extends EventEmitter {
 		}

 		if (response.status_code >= 200 && response.status_code < 300) {
-			// Create dialog.
+			// Create dialog, unless an early NOTIFY already created it.
 			if (this._dialog === null) {
 				const dialog = new Dialog(this, response, 'UAC');

@@ -505,13 +570,22 @@ module.exports = class Subscriber extends EventEmitter {
 				}

 				this._dialog = dialog;
+			}
+
+			// The initial SUBSCRIBE is accepted. Refreshes land here too.
+			if (!this._accepted) {
+				this._accepted = true;

 				logger.debug('emit "accepted"');

 				this.emit('accepted');

 				// Subsequent subscribes saved in the queue until dialog created.
-				for (const subscribe of this._queue) {
+				const queue = this._queue;
+
+				this._queue = [];
+
+				for (const subscribe of queue) {
 					logger.debug('dequeue subscribe');

 					this._sendSubsequentSubscribe(subscribe.body, subscribe.headers);
diff --git a/src/UA.js b/src/UA.js
index 287c4c1..30567cc 100644
--- a/src/UA.js
+++ b/src/UA.js
@@ -753,13 +753,20 @@ module.exports = class UA extends EventEmitter {
 				dialog.receiveRequest(request);
 			} else if (method === JsSIP_C.NOTIFY) {
 				session = this._findSession(request);
+
 				if (session) {
 					session.receiveRequest(request);
 				} else {
-					logger.debug(
-						'received NOTIFY request for a non existent subscription'
-					);
-					request.reply(481, 'Subscription does not exist');
+					const subscriber = this._findEarlyNotifySubscriber(request);
+
+					if (subscriber) {
+						subscriber.receiveEarlyNotify(request);
+					} else {
+						logger.debug(
+							'received NOTIFY request for a non existent subscription'
+						);
+						request.reply(481, 'Subscription does not exist');
+					}
 				}
 			} else if (method !== JsSIP_C.ACK) {
 				/* RFC3261 12.2.2
@@ -794,6 +801,24 @@ module.exports = class UA extends EventEmitter {
 		}
 	}

+	/**
+	 * Get the subscriber whose dialog is created by the given NOTIFY, if any.
+	 *
+	 * RFC 6665 4.1.2.4: the first NOTIFY of a subscription may arrive before
+	 * the 2xx response to the initial SUBSCRIBE, so there is no dialog yet.
+	 * Only a subscriber still waiting for that first NOTIFY matches; any later
+	 * NOTIFY is routed by `_findDialog()`.
+	 */
+	_findEarlyNotifySubscriber({ call_id, to_tag }) {
+		for (const subscriber of this._subscribers) {
+			if (subscriber.matchEarlyNotify(call_id, to_tag)) {
+				return subscriber;
+			}
+		}
+
+		return null;
+	}
+
 	/**
 	 * Get the dialog to which the request belongs to, if any.
 	 */
diff --git a/src/test/test-SubscriberNotifier.ts b/src/test/test-SubscriberNotifier.ts
index f457ffa..ab61da0 100644
--- a/src/test/test-SubscriberNotifier.ts
+++ b/src/test/test-SubscriberNotifier.ts
@@ -1,5 +1,6 @@
 import './include/common';
 import LoopSocket from './include/LoopSocket';
+import type { Socket } from '../Socket';

 // eslint-disable-next-line @typescript-eslint/no-require-imports
 const JsSIP = require('../JsSIP.js');
@@ -369,3 +370,258 @@ describe('subscriber/notifier communication', () => {
 			subscriberUA.start();
 		}));
 });
+
+// RFC 6665 4.1.2.4: the NOTIFY that creates the subscription dialog may reach
+// the subscriber before the 2xx response to the initial SUBSCRIBE.
+describe('subscriber receiving the initial NOTIFY', () => {
+	const EVENT_NAME = 'weather';
+	const CONTENT_TYPE = 'text/plain';
+	const WEATHER_REPORT = '+20..+24C, no precipitation, light wind';
+	const SUBSCRIBER_URI = 'sip:alice@example.com';
+	const SUBSCRIBER_CONTACT_URI = 'sip:alice@abcdefabcdef.invalid;transport=ws';
+	const NOTIFIER_URI = 'sip:ikq@example.com';
+	const NOTIFIER_CONTACT_URI = 'sip:ikq@fedcbafedcba.invalid;transport=ws';
+	const NOTIFIER_TAG = 'notifiertag';
+	const EXPIRES = 3600;
+
+	function header(message: string, name: string): string {
+		return new RegExp(`^${name}: (.*)$`, 'mi').exec(message)![1];
+	}
+
+	function startLine(message: string): string {
+		return message.substring(0, message.indexOf('\r\n'));
+	}
+
+	/**
+	 * A socket that plays the notifier role by itself, so that the test decides
+	 * whether the initial NOTIFY travels before or after the 2xx response to the
+	 * initial SUBSCRIBE.
+	 */
+	class NotifierSocket implements Socket {
+		url = 'ws://localhost:12345';
+		via_transport = 'WS';
+		sip_uri = 'sip:localhost:12345;transport=ws';
+
+		// Every message written by the UA into the socket.
+		readonly sent: string[] = [];
+
+		private notifyCount = 0;
+
+		constructor(private readonly notifyFirst: boolean) {}
+
+		connect(): void {
+			setTimeout(() => this.onconnect(), 0);
+		}
+
+		disconnect(): void {}
+
+		send(message: string): boolean {
+			this.sent.push(message);
+
+			if (message.startsWith('SUBSCRIBE ')) {
+				this.answerSubscribe(message);
+			}
+
+			return true;
+		}
+
+		isConnected(): boolean {
+			return true;
+		}
+
+		isConnecting(): boolean {
+			return false;
+		}
+
+		onconnect(): void {}
+
+		ondisconnect(): void {}
+
+		// eslint-disable-next-line @typescript-eslint/no-unused-vars
+		ondata(_data: string | ArrayBuffer): void {}
+
+		// The SUBSCRIBE requests sent by the UA.
+		get sentSubscribes(): string[] {
+			return this.sent.filter(message => message.startsWith('SUBSCRIBE '));
+		}
+
+		// Status lines of the responses the UA gave to the NOTIFY requests.
+		get notifyResponses(): string[] {
+			return this.sent
+				.filter(
+					message =>
+						message.startsWith('SIP/2.0') &&
+						/\r\nCSeq: \d+ NOTIFY/.test(message)
+				)
+				.map(startLine);
+		}
+
+		private answerSubscribe(subscribe: string): void {
+			const via = header(subscribe, 'Via');
+			const from = header(subscribe, 'From');
+			const callId = header(subscribe, 'Call-ID');
+			const cseq = header(subscribe, 'CSeq');
+			const expires = header(subscribe, 'Expires');
+			const initial = !/;tag=/i.test(header(subscribe, 'To'));
+			const to = initial
+				? `${header(subscribe, 'To')};tag=${NOTIFIER_TAG}`
+				: header(subscribe, 'To');
+
+			const ok = [
+				'SIP/2.0 200 OK',
+				`Via: ${via}`,
+				`From: ${from}`,
+				`To: ${to}`,
+				`Call-ID: ${callId}`,
+				`CSeq: ${cseq}`,
+				`Contact: <${NOTIFIER_CONTACT_URI}>`,
+				`Expires: ${expires}`,
+				'Content-Length: 0',
+				'',
+				'',
+			].join('\r\n');
+
+			// The notifier only sends the initial and the final NOTIFY.
+			const unsubscribe = expires === '0';
+			const messages = [ok];
+
+			if (initial || unsubscribe) {
+				const notifyCseq = ++this.notifyCount;
+				const body = unsubscribe ? '' : WEATHER_REPORT;
+
+				const notify = [
+					`NOTIFY ${SUBSCRIBER_CONTACT_URI} SIP/2.0`,
+					`Via: SIP/2.0/WS localhost:12345;branch=z9hG4bK.notify${notifyCseq}`,
+					'Max-Forwards: 69',
+					`From: ${to}`,
+					`To: ${from}`,
+					`Call-ID: ${callId}`,
+					`CSeq: ${notifyCseq} NOTIFY`,
+					`Event: ${EVENT_NAME}`,
+					unsubscribe
+						? 'Subscription-State: terminated;reason=timeout'
+						: `Subscription-State: active;expires=${EXPIRES}`,
+					`Contact: <${NOTIFIER_CONTACT_URI}>`,
+					`Content-Type: ${CONTENT_TYPE}`,
+					`Content-Length: ${body.length}`,
+					'',
+					body,
+				].join('\r\n');
+
+				if (initial && this.notifyFirst) {
+					messages.unshift(notify);
+				} else {
+					messages.push(notify);
+				}
+			}
+
+			messages.forEach((message, index) =>
+				setTimeout(() => this.ondata(message), index + 1)
+			);
+		}
+	}
+
+	type Result = {
+		accepted: number;
+		active: number;
+		notifies: (string | undefined)[];
+		notifyResponses: string[];
+		terminatedByFinalNotify: boolean;
+		// The SUBSCRIBE sent to refresh the subscription. Within the subscription
+		// dialog it is addressed to the notifier Contact, carries the remote tag
+		// and continues the CSeq of the initial SUBSCRIBE.
+		refreshRequestUri: string;
+		refreshToTag: string | undefined;
+		refreshCseqIncrement: number;
+	};
+
+	const ESTABLISHED_SUBSCRIPTION: Result = {
+		accepted: 1,
+		active: 1,
+		notifies: [WEATHER_REPORT],
+		// The initial and the final NOTIFY, both accepted.
+		notifyResponses: ['SIP/2.0 200 OK', 'SIP/2.0 200 OK'],
+		terminatedByFinalNotify: true,
+		refreshRequestUri: NOTIFIER_CONTACT_URI,
+		refreshToTag: NOTIFIER_TAG,
+		refreshCseqIncrement: 1,
+	};
+
+	function runSubscription(notifyFirst: boolean): Promise<Result> {
+		return new Promise<Result>(resolve => {
+			const socket = new NotifierSocket(notifyFirst);
+
+			const ua = new UA({
+				sockets: socket,
+				uri: SUBSCRIBER_URI,
+				contact_uri: SUBSCRIBER_CONTACT_URI,
+				register: false,
+			});
+
+			let accepted = 0;
+			let active = 0;
+			let terminatedByFinalNotify = false;
+			const notifies: (string | undefined)[] = [];
+
+			ua.on('connected', () => {
+				const subscriber = ua.subscribe(
+					NOTIFIER_URI,
+					EVENT_NAME,
+					CONTENT_TYPE,
+					{ expires: EXPIRES }
+				);
+
+				subscriber.on('accepted', () => accepted++);
+				subscriber.on('active', () => active++);
+				subscriber.on(
+					'notify',
+					(_isFinal: boolean, _request: unknown, body?: string) =>
+						notifies.push(body)
+				);
+				subscriber.on('terminated', (code: number) => {
+					terminatedByFinalNotify = code === subscriber.C.FINAL_NOTIFY_RECEIVED;
+
+					// Let the pending transactions die before closing the UA.
+					setTimeout(() => ua.stop(), 50);
+				});
+
+				subscriber.subscribe();
+
+				// Both the 2xx and the initial NOTIFY are delivered by then.
+				setTimeout(() => {
+					// Refresh. It must travel within the subscription dialog.
+					subscriber.subscribe();
+
+					setTimeout(() => subscriber.terminate(), 50);
+				}, 50);
+			});
+
+			ua.on('disconnected', () => {
+				const [initialSubscribe, refresh] = socket.sentSubscribes;
+				const cseq = (subscribe: string): number =>
+					Number(header(subscribe, 'CSeq').split(' ')[0]);
+
+				resolve({
+					accepted,
+					active,
+					notifies,
+					notifyResponses: socket.notifyResponses,
+					terminatedByFinalNotify,
+					refreshRequestUri: startLine(refresh).split(' ')[1],
+					refreshToTag: /;tag=([^;]+)/.exec(header(refresh, 'To'))?.[1],
+					refreshCseqIncrement: cseq(refresh) - cseq(initialSubscribe),
+				});
+			});
+
+			ua.start();
+		});
+	}
+
+	test('after the 2xx response to the initial SUBSCRIBE', async () => {
+		expect(await runSubscription(false)).toEqual(ESTABLISHED_SUBSCRIPTION);
+	});
+
+	test('before the 2xx response to the initial SUBSCRIBE', async () => {
+		expect(await runSubscription(true)).toEqual(ESTABLISHED_SUBSCRIPTION);
+	});
+});