From d504b73dc801a9f33f00766fa6f0fa385828efe0 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Fri, 17 Apr 2026 00:40:10 -0300 Subject: [PATCH] fix(xml): preserve UTF-8 declaration in signed DPS output Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Xml/DpsSigner.php | 8 +++++++- tests/Unit/Xml/DpsSignerTest.php | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Xml/DpsSigner.php b/src/Xml/DpsSigner.php index 712e2c8..0267489 100644 --- a/src/Xml/DpsSigner.php +++ b/src/Xml/DpsSigner.php @@ -271,6 +271,12 @@ private function signXml(string $xml, string $privateKeyPem, string $certificate $keyInfo->appendChild($x509Data); $sig->appendChild($keyInfo); - return $doc->saveXML() ?: $xml; + $serializedDocument = $doc->saveXML($doc->documentElement); + + if ($serializedDocument === false || $serializedDocument === '') { + return $xml; + } + + return "\n" . $serializedDocument; } } diff --git a/tests/Unit/Xml/DpsSignerTest.php b/tests/Unit/Xml/DpsSignerTest.php index af1dfae..93a97f9 100644 --- a/tests/Unit/Xml/DpsSignerTest.php +++ b/tests/Unit/Xml/DpsSignerTest.php @@ -122,6 +122,13 @@ public function testSignedXmlIsStillValidXml(): void self::assertTrue($doc->loadXML($signed), 'Signed output must be valid XML'); } + public function testSignedXmlIncludesExplicitUtf8EncodingDeclaration(): void + { + $signed = $this->signer->sign($this->testXml, $this->testCnpj); + + self::assertStringStartsWith('', $signed); + } + public function testSignatureElementIsAppendedToDpsRoot(): void { $signed = $this->signer->sign($this->testXml, $this->testCnpj);