Commit 8591d32 for jssip.net

commit 8591d32522ff9649b9fcdf9299b4f1d85e80ad93
Author: José Luis Millán <jmillan@aliax.net>
Date:   Tue Dec 1 11:27:24 2026 +0100

    UA: Fix, accept incoming requests whose Request-URI is a GRUU (#999)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a695c7..f905457 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@
 - 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.
 - Registrator: Add 'registrationRefreshed' event and report the granted expiry in 'registered' (#994). Thanks to @hyponex for reporting.
+- UA: Fix, accept incoming requests whose Request-URI is a GRUU granted by the registrar (#844). Thanks to @mtryfoss for reporting.

 ### 3.13.9

diff --git a/src/UA.js b/src/UA.js
index 8cb8b98..d96f046 100644
--- a/src/UA.js
+++ b/src/UA.js
@@ -587,10 +587,7 @@ module.exports = class UA extends EventEmitter {
 		const method = request.method;

 		// Check that request URI points to us.
-		if (
-			request.ruri.user !== this._configuration.uri.user &&
-			request.ruri.user !== this._contact.uri.user
-		) {
+		if (!this._doesRuriPointToUs(request.ruri)) {
 			logger.debug('Request-URI does not point to us');
 			if (request.method !== JsSIP_C.ACK) {
 				request.reply_sl(404);
@@ -790,6 +787,40 @@ module.exports = class UA extends EventEmitter {
 	// Utils.
 	// =================

+	/**
+	 * Whether the Request-URI of an incoming request addresses this UA.
+	 */
+	_doesRuriPointToUs(ruri) {
+		if (
+			ruri.user === this._configuration.uri.user ||
+			ruri.user === this._contact.uri.user
+		) {
+			return true;
+		}
+
+		/* The registrar is free to choose how the GRUUs it grants look (RFC
+		 * 5627, Appendix A), and this UA advertises them in the Contact header
+		 * of its outgoing requests, so requests targeted at them point to us.
+		 */
+		for (const gruu of [this._contact.pub_gruu, this._contact.temp_gruu]) {
+			const uri = gruu ? URI.parse(gruu) : undefined;
+
+			/* Compare AORs plus the 'gr' parameter, which is what identifies the
+			 * instance (RFC 5627, Section 3.1). Any other parameter a proxy may
+			 * have added on the way takes no part in the match.
+			 */
+			if (
+				uri &&
+				uri.toAor() === ruri.toAor() &&
+				uri.getParam('gr') === ruri.getParam('gr')
+			) {
+				return true;
+			}
+		}
+
+		return false;
+	}
+
 	/**
 	 * Get the session to which the request belongs to, if any.
 	 */
diff --git a/src/test/test-UA.ts b/src/test/test-UA.ts
index febf4ea..5e88b20 100644
--- a/src/test/test-UA.ts
+++ b/src/test/test-UA.ts
@@ -2,6 +2,7 @@

 import './include/common';
 import * as consts from './include/consts';
+import type { Socket } from '../Socket';

 // eslint-disable-next-line @typescript-eslint/no-require-imports
 const JsSIP = require('../JsSIP.js');
@@ -104,3 +105,173 @@ describe('UA', () => {
 		ua.stop();
 	});
 });
+
+const AOR = 'sip:AliCe@example.com';
+
+// The registrar builds the public GRUU out of a lowercased AOR, so its user
+// part matches neither the configured URI nor the Contact URI (issue #844).
+const PUB_GRUU =
+	'sip:alice@example.com;gr=urn:uuid:3d1b40b8-07e4-4f5e-9d5b-1c2d3e4f5a6b';
+const TEMP_GRUU = 'sip:uloc-65a69615-354ff-915-b804a376@example.com;gr';
+
+function header(message: string, name: string): string {
+	return new RegExp(`^${name}: (.*)$`, 'mi').exec(message)![1];
+}
+
+/**
+ * A socket that plays a registrar granting both a public and a temporary GRUU.
+ */
+class GruuRegistrarSocket implements Socket {
+	url = 'ws://localhost:12345';
+	via_transport = 'WS';
+	sip_uri = 'sip:localhost:12345;transport=ws';
+
+	private readonly sent: string[] = [];
+
+	connect(): void {
+		setTimeout(() => this.onconnect(), 0);
+	}
+
+	disconnect(): void {}
+
+	send(message: string): boolean {
+		this.sent.push(message);
+
+		if (message.startsWith('REGISTER ')) {
+			setTimeout(() => this.ondata(this.answerRegister(message)), 1);
+		}
+
+		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 {}
+
+	receive(message: string): void {
+		this.ondata(message);
+	}
+
+	/**
+	 * Status code of the response sent for the given Call-ID.
+	 */
+	statusFor(call_id: string): number | undefined {
+		const response = this.sent.find(
+			message =>
+				message.startsWith('SIP/2.0 ') && header(message, 'Call-ID') === call_id
+		);
+
+		return response ? Number(response.slice(8, 11)) : undefined;
+	}
+
+	private answerRegister(register: string): string {
+		// Echo the Contact back (RFC 3261 10.3), with the granted GRUUs.
+		const contact =
+			`${header(register, 'Contact')}` +
+			`;pub-gruu="${PUB_GRUU}";temp-gruu="${TEMP_GRUU}"`;
+
+		return [
+			'SIP/2.0 200 OK',
+			`Via: ${header(register, 'Via')}`,
+			`From: ${header(register, 'From')}`,
+			`To: ${header(register, 'To')};tag=registrartag`,
+			`Call-ID: ${header(register, 'Call-ID')}`,
+			`CSeq: ${header(register, 'CSeq')}`,
+			`Contact: ${contact}`,
+			'Content-Length: 0',
+			'',
+			'',
+		].join('\r\n');
+	}
+}
+
+function bye(ruri: string, call_id: string): string {
+	return [
+		`BYE ${ruri} SIP/2.0`,
+		`Via: SIP/2.0/WS proxy.example.com;branch=z9hG4bK${call_id}`,
+		'Max-Forwards: 69',
+		'From: <sip:bob@example.com>;tag=remotetag',
+		`To: <${AOR}>;tag=localtag`,
+		`Call-ID: ${call_id}`,
+		'CSeq: 102 BYE',
+		'Content-Length: 0',
+		'',
+		'',
+	].join('\r\n');
+}
+
+/**
+ * Registers, then feeds the UA an in-dialog BYE per given Request-URI and
+ * returns the status code each one is answered with.
+ */
+function runByes(
+	ruris: Record<string, string>
+): Promise<Record<string, number | undefined>> {
+	return new Promise(resolve => {
+		const socket = new GruuRegistrarSocket();
+
+		const ua = new UA({ sockets: socket, uri: AOR, register: true });
+
+		ua.on('registered', () => {
+			for (const name of Object.keys(ruris)) {
+				socket.receive(bye(ruris[name], name));
+			}
+
+			setTimeout(() => ua.stop(), 50);
+		});
+
+		ua.on('disconnected', () => {
+			const statuses: Record<string, number | undefined> = {};
+
+			for (const name of Object.keys(ruris)) {
+				statuses[name] = socket.statusFor(name);
+			}
+
+			resolve(statuses);
+		});
+
+		ua.start();
+	});
+}
+
+describe('UA Request-URI check', () => {
+	// 481 means the request got past the Request-URI check and was rejected for
+	// having no matching dialog, which is all this UA can say about a BYE it
+	// never had a session for.
+	test('accepts requests addressed to a granted GRUU', async () => {
+		await expect(
+			runByes({
+				'pub-gruu': PUB_GRUU,
+				'temp-gruu': TEMP_GRUU,
+				// Same GRUU as advertised, reached through a proxy that tacked a
+				// parameter onto the Request-URI.
+				'pub-gruu-with-param': `${PUB_GRUU};transport=ws`,
+			})
+		).resolves.toEqual({
+			'pub-gruu': 481,
+			'temp-gruu': 481,
+			'pub-gruu-with-param': 481,
+		});
+	});
+
+	test('rejects requests addressed to somebody else', async () => {
+		await expect(
+			runByes({
+				stranger: 'sip:carol@example.com',
+				// A GRUU for another instance of the same AOR.
+				'foreign-gruu': 'sip:alice@example.com;gr=urn:uuid:not-our-instance',
+			})
+		).resolves.toEqual({ stranger: 404, 'foreign-gruu': 404 });
+	});
+});