From 5cd5d1af291e36b32514c64c378a4cbad53827f3 Mon Sep 17 00:00:00 2001
From: Matthias Mullie <git@mullie.eu>
Date: Mon, 10 Mar 2025 09:46:07 +0100
Subject: [PATCH] Abort initialization with unexpected DOM

Bug: T387691
Change-Id: I09b02dcc198466d0330285d0b375fefaee2b115b
---
 resources/filepage/StatementPanel.js | 4 ++++
 resources/filepage/init.js           | 8 ++++++++
 2 files changed, 12 insertions(+)

diff --git a/resources/filepage/StatementPanel.js b/resources/filepage/StatementPanel.js
index 40dc1cca..775d92e5 100644
--- a/resources/filepage/StatementPanel.js
+++ b/resources/filepage/StatementPanel.js
@@ -38,6 +38,10 @@ const StatementPanel = function StatementPanelConstructor( config ) {
 
 	if ( this.$element.attr( 'data-mw-formatvalue' ) ) {
 		this.populateFormatValueCache( JSON.parse( this.$element.attr( 'data-mw-formatvalue' ) || '{}' ) );
+	} else if ( this.$element.attr( 'data-formatvalue' ) ) {
+		// Fallback for when this attribute was named differently
+		// @see https://phabricator.wikimedia.org/T387691
+		this.populateFormatValueCache( JSON.parse( this.$element.attr( 'data-formatvalue' ) || '{}' ) );
 	}
 
 	this.licenseDialogWidget = new LicenseDialogWidget();
diff --git a/resources/filepage/init.js b/resources/filepage/init.js
index 236523ed..db329bac 100644
--- a/resources/filepage/init.js
+++ b/resources/filepage/init.js
@@ -172,6 +172,14 @@
 	 * @param {jQuery} content
 	 */
 	mw.hook( 'wikipage.content' ).add( ( $content ) => {
+		// eslint-disable-next-line no-jquery/no-global-selector
+		if ( $( '.wbmi-structured-data-header' ).length > 1 || $( '.wbmi-captions-header' ).length > 1 ) {
+			// abort initialization if we encounter more than of the expected DOM
+			// structured; in which case wikitext has likely been crafted maliciously,
+			// and it may be unsafe to proceed
+			return;
+		}
+
 		const linkNoticeWidget = new LinkNoticeWidget();
 		const protectionMsgWidget = new ProtectionMsgWidget();
 		const $statements = $content.find( '.wbmi-structured-data-header ~ .wbmi-entityview-statementsGroup' );
-- 
2.34.1

