@onekeyfe/react-native-image 6.7.0-alpha.449 → 6.7.0-alpha.464

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -802,7 +802,7 @@ internal class OneKeyImageSafetyVersionedKey(
802
802
  override fun hashCode(): Int = 31 * delegate.hashCode() + CACHE_VERSION.hashCode()
803
803
 
804
804
  companion object {
805
- internal const val CACHE_VERSION = "onekey-image-safety-v2"
805
+ internal const val CACHE_VERSION = "onekey-image-safety-v4"
806
806
  private val VERSION_BYTES = CACHE_VERSION.toByteArray(Key.CHARSET)
807
807
  }
808
808
  }
@@ -2,13 +2,246 @@ package com.margelo.nitro.onekeyimage
2
2
 
3
3
  import android.graphics.Bitmap
4
4
  import android.graphics.Canvas
5
+ import android.graphics.BitmapFactory
5
6
  import com.caverock.androidsvg.SVG
6
7
  import java.io.InputStream
8
+ import java.io.IOException
9
+ import java.io.StringWriter
10
+ import javax.xml.parsers.DocumentBuilderFactory
11
+ import javax.xml.parsers.SAXParserFactory
12
+ import javax.xml.transform.TransformerFactory
13
+ import javax.xml.transform.OutputKeys
14
+ import javax.xml.transform.dom.DOMSource
15
+ import javax.xml.transform.stream.StreamResult
16
+ import kotlin.io.encoding.Base64
17
+ import kotlin.io.encoding.ExperimentalEncodingApi
18
+ import org.w3c.dom.Element
19
+ import org.w3c.dom.Node
20
+ import org.xml.sax.SAXException
21
+ import org.xml.sax.Attributes
22
+ import org.xml.sax.helpers.DefaultHandler
7
23
 
8
24
  /** Synchronous per-request document; loaders retain scheduling and cancellation. */
9
25
  object OneKeySVG {
10
26
  fun decode(source: InputStream): OneKeySVGDocument = OneKeySVGDocument(parse(source))
11
- internal fun parse(source: InputStream): SVG = SVG.getFromInputStream(source)
27
+ internal fun parse(source: InputStream): SVG {
28
+ val data = OneKeyLimitedInputStream(source).readBytes()
29
+ val normalized = normalize(data) { png, readPixels ->
30
+ val decoded = BitmapFactory.decodeByteArray(png, 0, png.size)
31
+ ?: throw IOException("Invalid PNG in SVG foreignObject")
32
+ try {
33
+ if (readPixels) IntArray(decoded.width * decoded.height).also {
34
+ decoded.getPixels(it, 0, decoded.width, 0, 0, decoded.width, decoded.height)
35
+ } else null
36
+ } finally { decoded.recycle() }
37
+ }
38
+ return SVG.getFromInputStream(normalized.inputStream())
39
+ }
40
+
41
+ @OptIn(ExperimentalEncodingApi::class)
42
+ internal fun normalize(data: ByteArray, decodePNG: (ByteArray, Boolean) -> IntArray?): ByteArray {
43
+ val xml = when {
44
+ data.size >= 2 && ((data[0] == 0xff.toByte() && data[1] == 0xfe.toByte()) ||
45
+ (data[0] == 0xfe.toByte() && data[1] == 0xff.toByte())) -> String(data, Charsets.UTF_16)
46
+ data.size >= 4 && data[0] == '<'.code.toByte() && data[1] == 0.toByte() &&
47
+ data[2] != 0.toByte() && data[3] == 0.toByte() -> String(data, Charsets.UTF_16LE)
48
+ data.size >= 4 && data[0] == 0.toByte() && data[1] == '<'.code.toByte() &&
49
+ data[2] == 0.toByte() && data[3] != 0.toByte() -> String(data, Charsets.UTF_16BE)
50
+ else -> String(data, Charsets.UTF_8)
51
+ }
52
+ if (!xml.contains("foreignObject")) return data
53
+ fun unsupported(): Nothing = throw IOException("Unsupported SVG foreignObject")
54
+ if (data.size > 8 * 1024 * 1024 || xml.contains("<!DOCTYPE", ignoreCase = true) ||
55
+ xml.contains("<!ENTITY", ignoreCase = true)) unsupported()
56
+ var elementCount = 0
57
+ var elementDepth = 0
58
+ SAXParserFactory.newInstance().newSAXParser().parse(data.inputStream(), object : DefaultHandler() {
59
+ override fun startElement(uri: String?, localName: String?, qName: String?, attributes: Attributes?) {
60
+ if (++elementCount > 10000 || ++elementDepth > 64) unsupported()
61
+ }
62
+ override fun endElement(uri: String?, localName: String?, qName: String?) { elementDepth-- }
63
+ })
64
+ val factory = DocumentBuilderFactory.newInstance().apply {
65
+ isNamespaceAware = true
66
+ isExpandEntityReferences = false
67
+ }
68
+ val builder = factory.newDocumentBuilder()
69
+ builder.setEntityResolver { _, _ -> throw SAXException("External SVG entities are disabled") }
70
+ val document = builder.parse(data.inputStream())
71
+ if (document.documentElement.localName != "svg") unsupported()
72
+ if (document.getElementsByTagNameNS("*", "foreignObject").length == 0) return data
73
+ var nodes = 0
74
+ var objects = 0
75
+ var imageBytes = 0L
76
+ var imagePixels = 0L
77
+ var hasImageRendering = false
78
+ var nearestNeighbor = false
79
+ var pixelRuns = 0
80
+ var pathCharacters = 0
81
+ val allowed = setOf("x", "y", "width", "height", "transform", "opacity", "clip-path", "mask", "id")
82
+ val imageAllowed = setOf("xmlns", "src", "width", "height", "alt")
83
+ fun children(node: Node) = (0 until node.childNodes.length).map { node.childNodes.item(it) }
84
+ fun validateStyle(element: Element) {
85
+ val css = children(element).joinToString("") {
86
+ if (it.nodeType != Node.TEXT_NODE && it.nodeType != Node.CDATA_SECTION_NODE) unsupported()
87
+ it.nodeValue
88
+ }
89
+ val rule = Regex("([^{}]+)\\{([^{}]*)\\}")
90
+ // These selectors cannot match converted containers or generated pixel paths.
91
+ val svgSelectors = setOf("rect", "circle", "ellipse", "line", "polyline", "polygon", "text", "tspan", "stop")
92
+ var cursor = 0
93
+ while (cursor < css.length) {
94
+ val match = rule.matchAt(css, cursor) ?: run {
95
+ if (css.substring(cursor).isBlank()) return
96
+ unsupported()
97
+ }
98
+ cursor = match.range.last + 1
99
+ val selector = match.groupValues[1].trim()
100
+ if (selector.split(',').all { it.trim() in svgSelectors }) continue
101
+ if (selector != "img") unsupported()
102
+ val body = match.groupValues[2]
103
+ for (declaration in body.split(';').map(String::trim).filter(String::isNotEmpty)) {
104
+ val parts = declaration.split(':').map(String::trim)
105
+ if (parts.size != 2) unsupported()
106
+ val (key, value) = parts
107
+ if (key in setOf("width", "height") && value == "100%") continue
108
+ if (key == "image-rendering") {
109
+ val smooth = value in setOf("auto", "smooth", "optimizeQuality")
110
+ val nearest = value in setOf("optimizeSpeed", "-moz-crisp-edges",
111
+ "-o-crisp-edges", "-webkit-optimize-contrast", "optimize-contrast", "crisp-edges", "pixelated")
112
+ if (!smooth && !nearest) unsupported()
113
+ hasImageRendering = true
114
+ nearestNeighbor = nearest
115
+ continue
116
+ }
117
+ if (key == "-ms-interpolation-mode" && value == "nearest-neighbor") {
118
+ if (!hasImageRendering) nearestNeighbor = true
119
+ continue
120
+ }
121
+ unsupported()
122
+ }
123
+ }
124
+ }
125
+ fun collectStyles(node: Node) {
126
+ if (node is Element && node.localName == "style") validateStyle(node)
127
+ else children(node).forEach(::collectStyles)
128
+ }
129
+ collectStyles(document)
130
+ fun convert(node: Node, depth: Int) {
131
+ if (depth > 64) unsupported()
132
+ if (node.nodeType == Node.PROCESSING_INSTRUCTION_NODE) unsupported()
133
+ if (node !is Element) return
134
+ if (++nodes > 10000) unsupported()
135
+ for (key in listOf("fill", "stroke", "stop-color", "flood-color", "lighting-color", "color")) {
136
+ val value = node.getAttribute(key)
137
+ if (!Regex("#[0-9a-fA-F]{8}").matches(value)) continue
138
+ val rgba = value.substring(1).toLong(16)
139
+ val alpha = (rgba and 255) / 255.0
140
+ node.setAttribute(key, "rgba(${(rgba shr 24) and 255},${(rgba shr 16) and 255},${(rgba shr 8) and 255},$alpha)")
141
+ }
142
+ if (node.localName == "style") return
143
+ if (node.localName != "foreignObject") {
144
+ children(node).forEach { convert(it, depth + 1) }
145
+ return
146
+ }
147
+ if (++objects > 16) unsupported()
148
+ for (index in 0 until node.attributes.length) {
149
+ if (node.attributes.item(index).nodeName !in allowed) unsupported()
150
+ }
151
+ for (key in listOf("width", "height")) {
152
+ val number = node.getAttribute(key).toDoubleOrNull() ?: unsupported()
153
+ if (!number.isFinite() || number <= 0 || number > 32768) unsupported()
154
+ }
155
+ val content = children(node).filter {
156
+ when (it.nodeType) {
157
+ Node.COMMENT_NODE -> false
158
+ Node.TEXT_NODE, Node.CDATA_SECTION_NODE -> {
159
+ if (it.nodeValue.isNotBlank()) unsupported()
160
+ false
161
+ }
162
+ else -> true
163
+ }
164
+ }
165
+ val image = content.singleOrNull() as? Element ?: unsupported()
166
+ if (image.tagName != "img" || image.namespaceURI != "http://www.w3.org/1999/xhtml") unsupported()
167
+ for (index in 0 until image.attributes.length) {
168
+ if (image.attributes.item(index).nodeName !in imageAllowed) unsupported()
169
+ }
170
+ for (key in listOf("width", "height")) {
171
+ if (image.hasAttribute(key) && image.getAttribute(key) != "100%") unsupported()
172
+ }
173
+ if (children(image).any { it.nodeType != Node.TEXT_NODE || it.nodeValue.isNotBlank() }) unsupported()
174
+ val source = image.getAttribute("src")
175
+ val prefix = "data:image/png;base64,"
176
+ if (!source.startsWith(prefix, ignoreCase = true) || source.length - prefix.length > 11184812) unsupported()
177
+ val png = try { Base64.Default.decode(source.substring(prefix.length)) }
178
+ catch (_: IllegalArgumentException) { unsupported() }
179
+ imageBytes += png.size
180
+ if (imageBytes > 8 * 1024 * 1024 || png.size < 24 ||
181
+ !png.copyOfRange(0, 8).contentEquals(byteArrayOf(137.toByte(), 80, 78, 71, 13, 10, 26, 10))) unsupported()
182
+ val metadata = OneKeyEncodedImageInspector.inspect(png.inputStream())
183
+ val width = metadata.width.toLong()
184
+ val height = metadata.height.toLong()
185
+ imagePixels += width * height
186
+ if (metadata.animated || width <= 0 || height <= 0 || width > 8192 || height > 8192 ||
187
+ imagePixels > 4194304) unsupported()
188
+ val pixels = decodePNG(png, nearestNeighbor)
189
+ val replacement = document.createElementNS("http://www.w3.org/2000/svg", if (nearestNeighbor) "svg" else "image")
190
+ for (index in 0 until node.attributes.length) {
191
+ val attribute = node.attributes.item(index)
192
+ replacement.setAttribute(attribute.nodeName, attribute.nodeValue)
193
+ }
194
+ replacement.setAttribute("preserveAspectRatio", "none")
195
+ replacement.setAttribute("image-rendering", if (nearestNeighbor) "optimizeSpeed" else "optimizeQuality")
196
+ if (nearestNeighbor) {
197
+ // Paint(0) still filters bitmaps on Android Q+. Preserve pixel edges as
198
+ // bounded vector geometry instead of depending on the library's hint.
199
+ if (pixels == null || pixels.size.toLong() != width * height) unsupported()
200
+ val paths = linkedMapOf<Int, StringBuilder>()
201
+ val rasterWidth = width.toInt()
202
+ for (y in 0 until height.toInt()) {
203
+ var x = 0
204
+ while (x < rasterWidth) {
205
+ val color = pixels[y * rasterWidth + x]
206
+ var end = x + 1
207
+ while (end < rasterWidth && pixels[y * rasterWidth + end] == color) end++
208
+ if (color ushr 24 != 0) {
209
+ if (++pixelRuns > 16384) unsupported()
210
+ val path = paths.getOrPut(color) {
211
+ if (++elementCount > 10000) unsupported()
212
+ StringBuilder()
213
+ }
214
+ val run = "M$x ${y}h${end - x}v1H${x}z"
215
+ pathCharacters += run.length
216
+ if (pathCharacters > 512 * 1024) unsupported()
217
+ path.append(run)
218
+ }
219
+ x = end
220
+ }
221
+ }
222
+ replacement.setAttribute("viewBox", "0 0 $width $height")
223
+ replacement.setAttribute("overflow", "hidden")
224
+ for ((color, path) in paths) {
225
+ val shape = document.createElementNS("http://www.w3.org/2000/svg", "path")
226
+ shape.setAttribute("d", path.toString())
227
+ shape.setAttribute("stroke", "none")
228
+ shape.setAttribute("fill", "rgb(${(color ushr 16) and 255},${(color ushr 8) and 255},${color and 255})")
229
+ shape.setAttribute("fill-opacity", ((color ushr 24) / 255.0).toString())
230
+ replacement.appendChild(shape)
231
+ }
232
+ } else {
233
+ replacement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink")
234
+ replacement.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", prefix + source.substring(prefix.length))
235
+ }
236
+ node.parentNode.replaceChild(replacement, node)
237
+ }
238
+ children(document).forEach { convert(it, 1) }
239
+ val output = StringWriter()
240
+ TransformerFactory.newInstance().newTransformer().apply {
241
+ setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes")
242
+ }.transform(DOMSource(document), StreamResult(output))
243
+ return output.toString().toByteArray(Charsets.UTF_8)
244
+ }
12
245
  }
13
246
 
14
247
  class OneKeySVGDocument internal constructor(private val svg: SVG) {
@@ -237,7 +237,7 @@ class OneKeyImageSafetyTest {
237
237
 
238
238
  @Test
239
239
  fun safetyVersionParticipatesInMemoryAndDiskCacheIdentity() {
240
- assertEquals("onekey-image-safety-v2", OneKeyImageSafetyVersionedKey.CACHE_VERSION)
240
+ assertEquals("onekey-image-safety-v4", OneKeyImageSafetyVersionedKey.CACHE_VERSION)
241
241
  val original = ObjectKey("custom-cache-key")
242
242
  val first = OneKeyImageSafetyVersionedKey(original)
243
243
  val same = OneKeyImageSafetyVersionedKey(ObjectKey("custom-cache-key"))
@@ -0,0 +1,130 @@
1
+ package com.margelo.nitro.onekeyimage
2
+
3
+ import java.io.IOException
4
+ import org.junit.Assert.assertArrayEquals
5
+ import org.junit.Assert.assertFalse
6
+ import org.junit.Assert.assertThrows
7
+ import org.junit.Assert.assertTrue
8
+ import org.junit.Test
9
+
10
+ class OneKeySVGForeignObjectTest {
11
+ private val png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="
12
+ private val image = "<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"data:image/png;base64,$png\" width=\"100%\" height=\"100%\"></img>"
13
+ private fun foreign(body: String, attributes: String = "") =
14
+ "<foreignObject width=\"24\" height=\"24\" $attributes>$body</foreignObject>"
15
+ private fun document(body: String) =
16
+ "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">$body</svg>".toByteArray()
17
+
18
+ @Test
19
+ fun embeddedPNGConvertsToAndroidSVGImageWithoutChangingItsSource() {
20
+ val source = document("<style>img { width:100%; height:100%; }</style>" + foreign(image))
21
+ var validatedImages = 0
22
+ val normalized = OneKeySVG.normalize(source) { _, _ -> validatedImages++; null }.toString(Charsets.UTF_8)
23
+ assertFalse(normalized.contains("foreignObject"))
24
+ assertTrue(normalized.contains("xlink:href=\"data:image/png;base64,$png\""))
25
+ assertTrue(normalized.contains("preserveAspectRatio=\"none\""))
26
+ assertTrue(validatedImages == 1)
27
+ }
28
+
29
+ @Test
30
+ fun ordinarySVGKeepsItsExistingDecoderInput() {
31
+ val source = document("<rect width=\"24\" height=\"24\" fill=\"red\"/>")
32
+ assertArrayEquals(source, OneKeySVG.normalize(source) { _, _ -> throw AssertionError("Ordinary SVG must not decode embedded PNGs") })
33
+ val commented = document("<!-- foreignObject is not used --><style>rect { fill:red; }</style><rect width=\"24\" height=\"24\"/>")
34
+ assertArrayEquals(commented, OneKeySVG.normalize(commented) { _, _ -> null })
35
+ }
36
+
37
+ @Test
38
+ fun utf16ForeignObjectsCannotBypassConversionOrEntityRejection() {
39
+ val expected = OneKeySVG.normalize(document(foreign(image))) { _, _ -> null }
40
+ for (charset in listOf(Charsets.UTF_16LE, Charsets.UTF_16BE)) {
41
+ for (bom in listOf("", "\uFEFF")) {
42
+ val declaration = "<?xml version='1.0' encoding='${charset.name()}'?>"
43
+ val source = (bom + declaration + document(foreign(image)).toString(Charsets.UTF_8)).toByteArray(charset)
44
+ var decoded = 0
45
+ val actual = OneKeySVG.normalize(source) { _, _ -> decoded++; null }
46
+ assertTrue(decoded == 1)
47
+ assertArrayEquals(expected, actual)
48
+ val ordinary = (bom + declaration + document("<rect width='24' height='24'/>").toString(Charsets.UTF_8)).toByteArray(charset)
49
+ assertArrayEquals(ordinary, OneKeySVG.normalize(ordinary) { _, _ -> throw AssertionError("Ordinary SVG must not decode PNGs") })
50
+ val entity = (bom + declaration + "<!DOCTYPE svg [<!ENTITY image 'test'>]>" + document(foreign(image)).toString(Charsets.UTF_8)).toByteArray(charset)
51
+ assertThrows(IOException::class.java) { OneKeySVG.normalize(entity) { _, _ -> null } }
52
+ }
53
+ }
54
+ }
55
+
56
+ @Test
57
+ fun imageRenderingUsesDocumentOrderAndKeepsSmoothImagesSmooth() {
58
+ for ((css, expected) in listOf(
59
+ "" to "optimizeQuality",
60
+ "<style>img { image-rendering:pixelated; }</style>" to "optimizeSpeed",
61
+ "<style>img { image-rendering:pixelated; image-rendering:auto; -ms-interpolation-mode:nearest-neighbor; }</style>" to "optimizeQuality",
62
+ "<style>img { image-rendering:pixelated; }</style><style>img { image-rendering:smooth; }</style>" to "optimizeQuality",
63
+ "<style>img { -ms-interpolation-mode:nearest-neighbor; }</style>" to "optimizeSpeed",
64
+ )) {
65
+ val converted = OneKeySVG.normalize(document(foreign(image) + css)) { _, nearest ->
66
+ if (nearest) intArrayOf(0xffff0000.toInt()) else null
67
+ }.toString(Charsets.UTF_8)
68
+ assertTrue(converted.contains("image-rendering=\"$expected\""))
69
+ }
70
+ }
71
+
72
+ @Test
73
+ fun surroundingSVGStylesArePreservedWithoutChangingImageSampling() {
74
+ for ((css, nearest) in listOf(
75
+ "<style>rect, circle { fill:red; }</style>" to false,
76
+ "<style>rect, circle { fill:red; } img { image-rendering:pixelated; }</style>" to true,
77
+ "<style>img { image-rendering:pixelated; } rect { fill:red; }</style><style>img { image-rendering:smooth; }</style>" to false,
78
+ )) {
79
+ val output = OneKeySVG.normalize(document(css + foreign(image))) { _, actual ->
80
+ assertTrue(actual == nearest)
81
+ if (actual) intArrayOf(0xffff0000.toInt()) else null
82
+ }.toString(Charsets.UTF_8)
83
+ assertTrue(output.contains("fill:red;"))
84
+ assertTrue(output.contains("image-rendering=\"${if (nearest) "optimizeSpeed" else "optimizeQuality"}\""))
85
+ }
86
+ }
87
+
88
+ @Test
89
+ fun stylesThatCouldAffectConvertedContentStillFail() {
90
+ for (selector in listOf("*", ".art", "#art", "g", "svg", "image", "path", "img, rect", "rect img", "rect:hover")) {
91
+ assertThrows(IOException::class.java) {
92
+ OneKeySVG.normalize(document("<style>$selector { fill:red; }</style>" + foreign(image))) { _, _ -> null }
93
+ }
94
+ }
95
+ for (css in listOf("@media all { rect { fill:red; } }", "@import 'external.css'; rect { fill:red; }")) {
96
+ assertThrows(IOException::class.java) {
97
+ OneKeySVG.normalize(document("<style>$css</style>" + foreign(image))) { _, _ -> null }
98
+ }
99
+ }
100
+ }
101
+
102
+ @Test
103
+ fun embeddedRasterDecodeFailureIsNotAConvertedSuccess() {
104
+ assertThrows(IOException::class.java) {
105
+ OneKeySVG.normalize(document(foreign(image))) { _, _ -> throw IOException("Corrupt PNG pixels") }
106
+ }
107
+ }
108
+
109
+ @Test
110
+ fun unsupportedHTMLExternalSourcesAndLayoutFail() {
111
+ for (body in listOf(
112
+ foreign("<div xmlns=\"http://www.w3.org/1999/xhtml\">Unsupported</div>"),
113
+ foreign("<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"https://example.com/a.png\"/>"),
114
+ foreign(image + image),
115
+ foreign(image, "style=\"display:none\""),
116
+ foreign(image.replace("100%", "50%")),
117
+ "<style>img { object-fit:cover; }</style>" + foreign(image),
118
+ foreign("<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"data:image/png;base64,AAAA\"/>"),
119
+ )) assertThrows(IOException::class.java) { OneKeySVG.normalize(document(body)) { _, _ -> null } }
120
+ }
121
+
122
+ @Test
123
+ fun boundsAndEntitiesFailBeforeNativeRendering() {
124
+ val nested = "<g>".repeat(64) + foreign(image) + "</g>".repeat(64)
125
+ assertThrows(IOException::class.java) { OneKeySVG.normalize(document(nested)) { _, _ -> null } }
126
+ assertThrows(IOException::class.java) { OneKeySVG.normalize(document(foreign(image).repeat(17))) { _, _ -> null } }
127
+ val entity = "<!DOCTYPE svg [<!ENTITY image 'test'>]>".toByteArray() + document(foreign(image))
128
+ assertThrows(IOException::class.java) { OneKeySVG.normalize(entity) { _, _ -> null } }
129
+ }
130
+ }
@@ -3,6 +3,357 @@
3
3
  #import <SDWebImage/SDWebImage.h>
4
4
  #import <SDWebImageSVGCoder/SDImageSVGCoder.h>
5
5
  #import <SDWebImageWebPCoder/SDImageWebPCoder.h>
6
+ #import <ImageIO/ImageIO.h>
7
+
8
+ @interface OneKeySVGNode : NSObject
9
+ @property(nonatomic, copy) NSString *name;
10
+ @property(nonatomic, copy) NSDictionary<NSString *, NSString *> *attributes;
11
+ @property(nonatomic, strong) NSMutableArray *children;
12
+ @end
13
+ @implementation OneKeySVGNode
14
+ @end
15
+
16
+ // Only the static, full-viewport PNG subset is converted; HTML layout is never inferred.
17
+ @interface OneKeySVGNormalizer : NSObject <NSXMLParserDelegate>
18
+ @property(nonatomic, strong) OneKeySVGNode *root;
19
+ @property(nonatomic, strong) NSMutableArray<OneKeySVGNode *> *stack;
20
+ @property(nonatomic) NSUInteger nodeCount;
21
+ @property(nonatomic) NSUInteger foreignCount;
22
+ @property(nonatomic) NSUInteger imageBytes;
23
+ @property(nonatomic) uint64_t imagePixels;
24
+ @property(nonatomic) BOOL hasForeignObject;
25
+ @property(nonatomic) BOOL hasImageRendering;
26
+ @property(nonatomic) BOOL nearestNeighbor;
27
+ @property(nonatomic) NSUInteger pixelRuns;
28
+ @property(nonatomic) NSUInteger pathCharacters;
29
+ + (nullable NSData *)normalize:(NSData *)data;
30
+ @end
31
+
32
+ @implementation OneKeySVGNormalizer
33
+
34
+ static NSString *OneKeySVGLocalName(NSString *name) {
35
+ return [name componentsSeparatedByString:@":"].lastObject;
36
+ }
37
+
38
+ static NSString *OneKeySVGEscape(NSString *value) {
39
+ return [[[value stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"]
40
+ stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"]
41
+ stringByReplacingOccurrencesOfString:@"\"" withString:@"&quot;"];
42
+ }
43
+
44
+ static void OneKeySVGSerialize(OneKeySVGNode *node, NSMutableString *xml) {
45
+ [xml appendFormat:@"<%@", node.name];
46
+ for (NSString *key in [node.attributes.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
47
+ [xml appendFormat:@" %@=\"%@\"", key, OneKeySVGEscape(node.attributes[key])];
48
+ }
49
+ [xml appendString:@">"];
50
+ for (id child in node.children) {
51
+ if ([child isKindOfClass:NSString.class]) [xml appendString:OneKeySVGEscape(child)];
52
+ else OneKeySVGSerialize(child, xml);
53
+ }
54
+ [xml appendFormat:@"</%@>", node.name];
55
+ }
56
+
57
+ + (NSData *)normalize:(NSData *)data {
58
+ const unsigned char *bytes = data.bytes;
59
+ NSStringEncoding encoding = NSUTF8StringEncoding;
60
+ if (data.length >= 2 && ((bytes[0] == 0xff && bytes[1] == 0xfe) ||
61
+ (bytes[0] == 0xfe && bytes[1] == 0xff))) encoding = NSUTF16StringEncoding;
62
+ else if (data.length >= 4 && bytes[0] == '<' && bytes[1] == 0 && bytes[2] != 0 && bytes[3] == 0)
63
+ encoding = NSUTF16LittleEndianStringEncoding;
64
+ else if (data.length >= 4 && bytes[0] == 0 && bytes[1] == '<' && bytes[2] == 0 && bytes[3] != 0)
65
+ encoding = NSUTF16BigEndianStringEncoding;
66
+ NSString *xml = [[NSString alloc] initWithData:data encoding:encoding];
67
+ if (!xml) xml = [[NSString alloc] initWithData:data encoding:NSUTF16StringEncoding];
68
+ if (!xml) return nil;
69
+ if (![xml containsString:@"foreignObject"]) return data;
70
+ if (data.length > 8 * 1024 * 1024 ||
71
+ [xml rangeOfString:@"<!DOCTYPE" options:NSCaseInsensitiveSearch].location != NSNotFound ||
72
+ [xml rangeOfString:@"<!ENTITY" options:NSCaseInsensitiveSearch].location != NSNotFound) return nil;
73
+ OneKeySVGNormalizer *normalizer = [OneKeySVGNormalizer new];
74
+ normalizer.stack = [NSMutableArray new];
75
+ NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
76
+ parser.shouldResolveExternalEntities = NO;
77
+ parser.delegate = normalizer;
78
+ if (![parser parse] || !normalizer.root ||
79
+ ![OneKeySVGLocalName(normalizer.root.name) isEqualToString:@"svg"]) return nil;
80
+ if (!normalizer.hasForeignObject) return data;
81
+ if (![normalizer collectStyles:normalizer.root] || ![normalizer convert:normalizer.root]) return nil;
82
+ NSMutableString *output = [NSMutableString new];
83
+ OneKeySVGSerialize(normalizer.root, output);
84
+ return [output dataUsingEncoding:NSUTF8StringEncoding];
85
+ }
86
+
87
+ - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
88
+ namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
89
+ attributes:(NSDictionary<NSString *, NSString *> *)attributes {
90
+ if (++self.nodeCount > 10000 || self.stack.count >= 64) { [parser abortParsing]; return; }
91
+ if ([OneKeySVGLocalName(elementName) isEqualToString:@"foreignObject"]) self.hasForeignObject = YES;
92
+ OneKeySVGNode *node = [OneKeySVGNode new];
93
+ node.name = elementName;
94
+ node.attributes = attributes;
95
+ node.children = [NSMutableArray new];
96
+ if (self.stack.count) [self.stack.lastObject.children addObject:node];
97
+ else self.root = node;
98
+ [self.stack addObject:node];
99
+ }
100
+
101
+ - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
102
+ namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName {
103
+ [self.stack removeLastObject];
104
+ }
105
+
106
+ - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
107
+ if (self.stack.count) [self.stack.lastObject.children addObject:string];
108
+ }
109
+
110
+ - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock {
111
+ NSString *text = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
112
+ if (!text) [parser abortParsing];
113
+ else [self parser:parser foundCharacters:text];
114
+ }
115
+
116
+ - (void)parser:(NSXMLParser *)parser foundProcessingInstructionWithTarget:(NSString *)target data:(NSString *)data {
117
+ [parser abortParsing];
118
+ }
119
+
120
+ - (BOOL)validStylesheet:(OneKeySVGNode *)node {
121
+ NSMutableString *css = [NSMutableString new];
122
+ for (id child in node.children) {
123
+ if (![child isKindOfClass:NSString.class]) return NO;
124
+ [css appendString:child];
125
+ }
126
+ NSRegularExpression *rule = [NSRegularExpression regularExpressionWithPattern:@"([^{}]+)\\{([^{}]*)\\}" options:0 error:nil];
127
+ // These selectors cannot match converted containers or generated pixel paths.
128
+ NSArray *svgSelectors = @[@"rect", @"circle", @"ellipse", @"line", @"polyline", @"polygon", @"text", @"tspan", @"stop"];
129
+ NSUInteger cursor = 0;
130
+ while (cursor < css.length) {
131
+ NSTextCheckingResult *match = [rule firstMatchInString:css options:NSMatchingAnchored range:NSMakeRange(cursor, css.length - cursor)];
132
+ if (!match) return ![[css substringFromIndex:cursor] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length;
133
+ cursor = NSMaxRange(match.range);
134
+ NSString *selector = [[css substringWithRange:[match rangeAtIndex:1]] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
135
+ BOOL svgOnly = YES;
136
+ for (NSString *part in [selector componentsSeparatedByString:@","]) {
137
+ if (![svgSelectors containsObject:[part stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]]) svgOnly = NO;
138
+ }
139
+ if (svgOnly) continue;
140
+ if (![selector isEqualToString:@"img"]) return NO;
141
+ for (NSString *declaration in [[css substringWithRange:[match rangeAtIndex:2]] componentsSeparatedByString:@";"]) {
142
+ NSString *trimmed = [declaration stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
143
+ if (!trimmed.length) continue;
144
+ NSArray *parts = [trimmed componentsSeparatedByString:@":"];
145
+ if (parts.count != 2) return NO;
146
+ NSString *key = [parts[0] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
147
+ NSString *value = [parts[1] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
148
+ if (([key isEqualToString:@"width"] || [key isEqualToString:@"height"]) && [value isEqualToString:@"100%"]) continue;
149
+ if ([key isEqualToString:@"image-rendering"]) {
150
+ BOOL smooth = [@[@"auto", @"smooth", @"optimizeQuality"] containsObject:value];
151
+ BOOL nearest = [@[@"optimizeSpeed", @"-moz-crisp-edges", @"-o-crisp-edges", @"-webkit-optimize-contrast", @"optimize-contrast", @"crisp-edges", @"pixelated"] containsObject:value];
152
+ if (!smooth && !nearest) return NO;
153
+ self.hasImageRendering = YES;
154
+ self.nearestNeighbor = nearest;
155
+ continue;
156
+ }
157
+ if ([key isEqualToString:@"-ms-interpolation-mode"] && [value isEqualToString:@"nearest-neighbor"]) {
158
+ if (!self.hasImageRendering) self.nearestNeighbor = YES;
159
+ continue;
160
+ }
161
+ return NO;
162
+ }
163
+ }
164
+ return YES;
165
+ }
166
+
167
+ - (BOOL)collectStyles:(OneKeySVGNode *)node {
168
+ if ([OneKeySVGLocalName(node.name) isEqualToString:@"style"]) return [self validStylesheet:node];
169
+ for (id child in node.children) {
170
+ if ([child isKindOfClass:OneKeySVGNode.class] && ![self collectStyles:child]) return NO;
171
+ }
172
+ return YES;
173
+ }
174
+
175
+ // CoreSVG smooths embedded bitmaps regardless of image-rendering. Pixel runs
176
+ // retain the small raster's edges without replacing the surrounding SVG scene.
177
+ - (BOOL)convertPixels:(CGImageRef)image node:(OneKeySVGNode *)node {
178
+ size_t width = CGImageGetWidth(image), height = CGImageGetHeight(image);
179
+ NSMutableData *rgba = [NSMutableData dataWithLength:width * height * 4];
180
+ CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
181
+ if (!colorSpace) return NO;
182
+ if (!rgba) { CGColorSpaceRelease(colorSpace); return NO; }
183
+ CGContextRef context = CGBitmapContextCreate(rgba.mutableBytes, width, height, 8, width * 4,
184
+ colorSpace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast);
185
+ CGColorSpaceRelease(colorSpace);
186
+ if (!context) return NO;
187
+ CGContextSetInterpolationQuality(context, kCGInterpolationNone);
188
+ CGContextSetBlendMode(context, kCGBlendModeCopy);
189
+ CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
190
+ CGContextRelease(context);
191
+ NSMutableDictionary<NSNumber *, NSMutableString *> *paths = [NSMutableDictionary new];
192
+ const uint32_t *pixels = rgba.bytes;
193
+ for (size_t y = 0; y < height; y++) {
194
+ for (size_t x = 0; x < width;) {
195
+ uint32_t color = pixels[y * width + x];
196
+ size_t end = x + 1;
197
+ while (end < width && pixels[y * width + end] == color) end++;
198
+ const uint8_t *channels = (const uint8_t *)&color;
199
+ if (channels[3]) {
200
+ if (++self.pixelRuns > 16384) return NO;
201
+ NSNumber *key = @(color);
202
+ NSMutableString *path = paths[key];
203
+ if (!path) {
204
+ if (++self.nodeCount > 10000) return NO;
205
+ paths[key] = path = [NSMutableString new];
206
+ }
207
+ NSString *run = [NSString stringWithFormat:@"M%zu %zuh%zuv1H%zuz", x, y, end - x, x];
208
+ self.pathCharacters += run.length;
209
+ if (self.pathCharacters > 512 * 1024) return NO;
210
+ [path appendString:run];
211
+ }
212
+ x = end;
213
+ }
214
+ }
215
+ NSMutableDictionary *attributes = [node.attributes mutableCopy];
216
+ attributes[@"xmlns"] = @"http://www.w3.org/2000/svg";
217
+ attributes[@"viewBox"] = [NSString stringWithFormat:@"0 0 %zu %zu", width, height];
218
+ attributes[@"preserveAspectRatio"] = @"none";
219
+ attributes[@"overflow"] = @"hidden";
220
+ NSRange colon = [node.name rangeOfString:@":"];
221
+ node.name = colon.location == NSNotFound ? @"svg" : [[node.name substringToIndex:colon.location + 1] stringByAppendingString:@"svg"];
222
+ node.attributes = attributes;
223
+ [node.children removeAllObjects];
224
+ for (NSNumber *key in [paths.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
225
+ uint32_t color = key.unsignedIntValue;
226
+ const uint8_t *channels = (const uint8_t *)&color;
227
+ unsigned alpha = channels[3];
228
+ OneKeySVGNode *path = [OneKeySVGNode new];
229
+ path.name = @"path";
230
+ path.attributes = @{@"d": paths[key], @"stroke": @"none",
231
+ @"fill": [NSString stringWithFormat:@"rgb(%u,%u,%u)",
232
+ MIN(255u, (channels[0] * 255u + alpha / 2) / alpha),
233
+ MIN(255u, (channels[1] * 255u + alpha / 2) / alpha),
234
+ MIN(255u, (channels[2] * 255u + alpha / 2) / alpha)],
235
+ @"fill-opacity": [NSString stringWithFormat:@"%.8f", alpha / 255.0]};
236
+ path.children = [NSMutableArray new];
237
+ [node.children addObject:path];
238
+ }
239
+ return YES;
240
+ }
241
+
242
+ - (BOOL)convert:(OneKeySVGNode *)node {
243
+ NSMutableDictionary *colors = [node.attributes mutableCopy];
244
+ for (NSString *key in @[@"fill", @"stroke", @"stop-color", @"flood-color", @"lighting-color", @"color"]) {
245
+ NSString *value = colors[key];
246
+ if (value.length != 9 || ![value hasPrefix:@"#"]) continue;
247
+ NSScanner *scanner = [NSScanner scannerWithString:[value substringFromIndex:1]];
248
+ unsigned long long rgba = 0;
249
+ if ([scanner scanHexLongLong:&rgba] && scanner.isAtEnd) {
250
+ colors[key] = [NSString stringWithFormat:@"rgba(%llu,%llu,%llu,%.8f)",
251
+ (rgba >> 24) & 255, (rgba >> 16) & 255, (rgba >> 8) & 255, (rgba & 255) / 255.0];
252
+ }
253
+ }
254
+ node.attributes = colors;
255
+ NSString *localName = OneKeySVGLocalName(node.name);
256
+ if ([localName isEqualToString:@"style"]) return YES;
257
+ if (![localName isEqualToString:@"foreignObject"]) {
258
+ for (id child in node.children) {
259
+ if ([child isKindOfClass:OneKeySVGNode.class] && ![self convert:child]) return NO;
260
+ }
261
+ return YES;
262
+ }
263
+ if (++self.foreignCount > 16) return NO;
264
+ NSSet *allowed = [NSSet setWithArray:@[@"x", @"y", @"width", @"height", @"transform", @"opacity", @"clip-path", @"mask", @"id"]];
265
+ for (NSString *key in node.attributes) if (![allowed containsObject:key]) return NO;
266
+ for (NSString *key in @[@"width", @"height"]) {
267
+ NSString *value = node.attributes[key];
268
+ NSScanner *scanner = [NSScanner scannerWithString:value ?: @""];
269
+ double number = 0;
270
+ if (![scanner scanDouble:&number] || !scanner.isAtEnd || !isfinite(number) || number <= 0 || number > 32768) return NO;
271
+ }
272
+ OneKeySVGNode *image = nil;
273
+ for (id child in node.children) {
274
+ if ([child isKindOfClass:NSString.class]) {
275
+ if ([[child stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] length]) return NO;
276
+ } else if (image) return NO;
277
+ else image = child;
278
+ }
279
+ if (!image || ![image.name isEqualToString:@"img"] ||
280
+ ![image.attributes[@"xmlns"] isEqualToString:@"http://www.w3.org/1999/xhtml"]) return NO;
281
+ NSSet *imageAllowed = [NSSet setWithArray:@[@"xmlns", @"src", @"width", @"height", @"alt"]];
282
+ for (NSString *key in image.attributes) if (![imageAllowed containsObject:key]) return NO;
283
+ for (NSString *key in @[@"width", @"height"]) {
284
+ if (image.attributes[key] && ![image.attributes[key] isEqualToString:@"100%"]) return NO;
285
+ }
286
+ for (id child in image.children) {
287
+ if (![child isKindOfClass:NSString.class] || [[child stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] length]) return NO;
288
+ }
289
+ NSString *source = image.attributes[@"src"];
290
+ NSString *prefix = @"data:image/png;base64,";
291
+ if (![source.lowercaseString hasPrefix:prefix] || source.length - prefix.length > 11184812) return NO;
292
+ NSData *png = [[NSData alloc] initWithBase64EncodedString:[source substringFromIndex:prefix.length] options:0];
293
+ if (!png || self.imageBytes + png.length > 8 * 1024 * 1024) return NO;
294
+ const unsigned char signature[] = {137, 80, 78, 71, 13, 10, 26, 10};
295
+ if (png.length < sizeof(signature) || memcmp(png.bytes, signature, sizeof(signature))) return NO;
296
+ CGImageSourceRef metadata = CGImageSourceCreateWithData((__bridge CFDataRef)png,
297
+ (__bridge CFDictionaryRef)@{(__bridge NSString *)kCGImageSourceShouldCache: @NO});
298
+ if (!metadata) return NO;
299
+ NSDictionary *properties = CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(metadata, 0, NULL));
300
+ BOOL isStatic = CGImageSourceGetCount(metadata) == 1;
301
+ uint64_t width = [properties[(__bridge NSString *)kCGImagePropertyPixelWidth] unsignedLongLongValue];
302
+ uint64_t height = [properties[(__bridge NSString *)kCGImagePropertyPixelHeight] unsignedLongLongValue];
303
+ if (!isStatic || width == 0 || height == 0 || width > 8192 || height > 8192 ||
304
+ self.imagePixels + width * height > 4194304) { CFRelease(metadata); return NO; }
305
+ // A valid IHDR alone is not evidence that CoreSVG can paint the embedded raster.
306
+ CGImageRef decoded = CGImageSourceCreateImageAtIndex(metadata, 0,
307
+ (__bridge CFDictionaryRef)@{(__bridge NSString *)kCGImageSourceShouldCacheImmediately: @YES});
308
+ CFRelease(metadata);
309
+ if (!decoded) return NO;
310
+ BOOL convertedPixels = !self.nearestNeighbor || [self convertPixels:decoded node:node];
311
+ CGImageRelease(decoded);
312
+ if (!convertedPixels) return NO;
313
+ self.imageBytes += png.length;
314
+ self.imagePixels += width * height;
315
+ if (self.nearestNeighbor) return YES;
316
+ NSMutableDictionary *attributes = [node.attributes mutableCopy];
317
+ attributes[@"xmlns:xlink"] = @"http://www.w3.org/1999/xlink";
318
+ attributes[@"xlink:href"] = [prefix stringByAppendingString:[source substringFromIndex:prefix.length]];
319
+ attributes[@"preserveAspectRatio"] = @"none";
320
+ attributes[@"image-rendering"] = @"optimizeQuality";
321
+ NSRange colon = [node.name rangeOfString:@":"];
322
+ node.name = colon.location == NSNotFound ? @"image" : [[node.name substringToIndex:colon.location + 1] stringByAppendingString:@"image"];
323
+ node.attributes = attributes;
324
+ [node.children removeAllObjects];
325
+ return YES;
326
+ }
327
+ @end
328
+
329
+ @interface OneKeySVGCoder : SDImageSVGCoder
330
+ @end
331
+ @implementation OneKeySVGCoder
332
+ + (SDImageSVGCoder *)sharedCoder {
333
+ static OneKeySVGCoder *coder;
334
+ static dispatch_once_t onceToken;
335
+ dispatch_once(&onceToken, ^{ coder = [OneKeySVGCoder new]; });
336
+ return coder;
337
+ }
338
+ - (UIImage *)decodedImageWithData:(NSData *)data options:(SDImageCoderOptions *)options {
339
+ NSData *normalized = [OneKeySVGNormalizer normalize:data];
340
+ if (!normalized) return nil;
341
+ if (normalized != data && options[SDImageCoderDecodeThumbnailPixelSize]) {
342
+ // SVGCoder rasterizes point sizes with the screen scale; callers supply pixels.
343
+ CGSize pixels = [options[SDImageCoderDecodeThumbnailPixelSize] CGSizeValue];
344
+ if (isfinite(pixels.width) && isfinite(pixels.height) && pixels.width > 0 && pixels.height > 0) {
345
+ CGFloat ratio = MIN(1, sqrt(4194304.0 / pixels.width / pixels.height));
346
+ CGFloat scale = MAX(1, UIScreen.mainScreen.scale);
347
+ NSMutableDictionary *bounded = [options mutableCopy];
348
+ // Keep point-to-pixel roundoff from making UIGraphics ceil an extra pixel.
349
+ bounded[SDImageCoderDecodeThumbnailPixelSize] = [NSValue valueWithCGSize:
350
+ CGSizeMake(nextafter(pixels.width * ratio / scale, 0), nextafter(pixels.height * ratio / scale, 0))];
351
+ options = bounded;
352
+ }
353
+ }
354
+ return [super decodedImageWithData:normalized options:options];
355
+ }
356
+ @end
6
357
 
7
358
  @implementation OneKeyImageCoderBridge
8
359
 
@@ -12,12 +363,12 @@
12
363
  options = @{SDImageCoderDecodeThumbnailPixelSize: [NSValue valueWithCGSize:pixelSize],
13
364
  SDImageCoderDecodePreserveAspectRatio: @YES};
14
365
  }
15
- return [SDImageSVGCoder.sharedCoder decodedImageWithData:data options:options];
366
+ return [OneKeySVGCoder.sharedCoder decodedImageWithData:data options:options];
16
367
  }
17
368
 
18
369
  + (void)addCodersToManager:(id)manager {
19
370
  SDImageCodersManager *coderManager = (SDImageCodersManager *)manager;
20
- [coderManager addCoder:SDImageSVGCoder.sharedCoder];
371
+ [coderManager addCoder:OneKeySVGCoder.sharedCoder];
21
372
  [coderManager addCoder:SDImageWebPCoder.sharedCoder];
22
373
  }
23
374
 
@@ -706,7 +706,7 @@ enum OneKeyImageDecodeSizing {
706
706
  }
707
707
 
708
708
  enum OneKeyImageRequestContext {
709
- static let safetyCacheGeneration = "onekey-image-safety-v2"
709
+ static let safetyCacheGeneration = "onekey-image-safety-v4"
710
710
  static let renderOptions: SDWebImage.SDWebImageOptions = [.retryFailed]
711
711
  static let preloadOptions: SDWebImage.SDWebImageOptions = [
712
712
  .retryFailed, .lowPriority,
@@ -234,7 +234,7 @@ final class OneKeyImageInfrastructureTests: XCTestCase {
234
234
  let url = try XCTUnwrap(URL(string: "https://example.com/image.png"))
235
235
  XCTAssertEqual(
236
236
  OneKeyImageRequestContext.filteredCacheKey(for: url),
237
- "https://example.com/image.png|onekey-image-safety-v2"
237
+ "https://example.com/image.png|onekey-image-safety-v4"
238
238
  )
239
239
  let thumbnailOptions = OneKeyImageRequestContext.thumbnailOptions(pixelSize: size)
240
240
  XCTAssertEqual(
@@ -250,11 +250,11 @@ final class OneKeyImageInfrastructureTests: XCTestCase {
250
250
  String(describing: type(of: $0))
251
251
  }
252
252
  XCTAssertTrue(names.contains("SDImageWebPCoder"))
253
- XCTAssertTrue(names.contains("SDImageSVGCoder"))
253
+ XCTAssertTrue(names.contains("OneKeySVGCoder"))
254
254
  XCTAssertFalse(names.contains { $0.localizedCaseInsensitiveContains("AVIF") })
255
255
  XCTAssertTrue(
256
256
  (OneKeyImageCoderRegistry.coder.coders ?? []).contains {
257
- ($0 as AnyObject) === SDImageSVGCoder.shared
257
+ $0 is SDImageSVGCoder && ($0 as AnyObject) !== SDImageSVGCoder.shared
258
258
  })
259
259
  XCTAssertTrue(
260
260
  (SDImageCodersManager.shared.coders ?? []).contains {
@@ -0,0 +1,267 @@
1
+ import SDWebImage
2
+ import UIKit
3
+ import XCTest
4
+
5
+ @testable import OneKeyImage
6
+
7
+ final class OneKeySVGForeignObjectTests: XCTestCase {
8
+ private func document(_ body: String) -> Data {
9
+ Data("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\(body)</svg>".utf8)
10
+ }
11
+
12
+ private func embeddedImage() -> String {
13
+ let format = UIGraphicsImageRendererFormat()
14
+ format.scale = 1
15
+ let png = UIGraphicsImageRenderer(size: CGSize(width: 2, height: 2), format: format).image { context in
16
+ UIColor.red.setFill()
17
+ context.fill(CGRect(x: 0, y: 0, width: 2, height: 2))
18
+ }.pngData()!
19
+ return "<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"data:image/png;base64,\(png.base64EncodedString())\" width=\"100%\" height=\"100%\"></img>"
20
+ }
21
+
22
+ private func foreign(_ content: String, attributes: String = "") -> String {
23
+ "<foreignObject width=\"24\" height=\"24\" \(attributes)>\(content)</foreignObject>"
24
+ }
25
+
26
+ private func pixelImage(side: Int = 2) -> String {
27
+ let format = UIGraphicsImageRendererFormat()
28
+ format.scale = 1
29
+ let png = UIGraphicsImageRenderer(size: CGSize(width: side, height: side), format: format).image { context in
30
+ for y in 0..<side {
31
+ for x in 0..<side {
32
+ let color: UIColor = (x + y).isMultiple(of: 2) ? .red : .blue
33
+ color.setFill()
34
+ context.fill(CGRect(x: x, y: y, width: 1, height: 1))
35
+ }
36
+ }
37
+ }.pngData()!
38
+ return "<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"data:image/png;base64,\(png.base64EncodedString())\"/>"
39
+ }
40
+
41
+ private func pixels(_ source: Data, size: Int) throws -> [UInt8] {
42
+ let image = try XCTUnwrap(OneKeyImageCoderBridge.decodeSVG(
43
+ source, pixelSize: CGSize(width: size, height: size)))
44
+ let cgImage = try XCTUnwrap(image.cgImage)
45
+ XCTAssertEqual(cgImage.width, size)
46
+ XCTAssertEqual(cgImage.height, size)
47
+ var bytes = [UInt8](repeating: 0, count: size * size * 4)
48
+ let context = try XCTUnwrap(CGContext(data: &bytes, width: size, height: size,
49
+ bitsPerComponent: 8, bytesPerRow: size * 4, space: CGColorSpaceCreateDeviceRGB(),
50
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue))
51
+ context.interpolationQuality = .none
52
+ context.draw(cgImage, in: CGRect(x: 0, y: 0, width: size, height: size))
53
+ return bytes
54
+ }
55
+
56
+ func testPixelatedPNGKeepsHardEdgesAtIntegerAndFractionalSizes() throws {
57
+ // The stylesheet follows the image to exercise whole-document CSS resolution.
58
+ let source = document(foreign(pixelImage()) + "<style>img { image-rendering:pixelated; }</style>")
59
+ for size in [32, 37, 192, 480] {
60
+ let bytes = try pixels(source, size: size)
61
+ let left = size / 2 - (size.isMultiple(of: 2) ? 1 : 2)
62
+ let right = size / 2 + (size.isMultiple(of: 2) ? 0 : 1)
63
+ for (x, expected) in [(left, [255, 0, 0, 255]), (right, [0, 0, 255, 255])] {
64
+ let offset = (size / 4 * size + x) * 4
65
+ XCTAssertEqual(Array(bytes[offset..<offset + 4]), expected.map(UInt8.init), "size=\(size) x=\(x)")
66
+ }
67
+ }
68
+ }
69
+
70
+ func testPixelPathsIgnoreInheritedStrokeAndKeepSiblingStroke() throws {
71
+ let content = foreign(pixelImage(), attributes: "x=\"4\" y=\"4\" width=\"16\" height=\"16\"")
72
+ .replacingOccurrences(of: "width=\"24\" height=\"24\"", with: "")
73
+ let css = "<style>img { image-rendering:pixelated; }</style>"
74
+ let sibling = "<path d=\"M1 1H23\" fill=\"none\"/>"
75
+ let plain = try pixels(document(content + css), size: 96)
76
+ for inherited in [
77
+ Data(String(decoding: document(content + sibling + css), as: UTF8.self).replacingOccurrences(of: "viewBox=", with: "stroke=\"green\" stroke-width=\"0.2\" viewBox=").utf8),
78
+ document("<g stroke=\"green\" stroke-width=\"0.2\">" + content + sibling + "</g>" + css),
79
+ ] {
80
+ let output = try pixels(inherited, size: 96)
81
+ for y in 16..<80 {
82
+ for x in 16..<80 {
83
+ let offset = (y * 96 + x) * 4
84
+ XCTAssertEqual(Array(output[offset..<offset + 4]), Array(plain[offset..<offset + 4]))
85
+ }
86
+ }
87
+ XCTAssertGreaterThan(output[(4 * 96 + 48) * 4 + 1], 0)
88
+ XCTAssertEqual(plain[(4 * 96 + 48) * 4 + 3], 0)
89
+ }
90
+ }
91
+
92
+ func testSurroundingSVGStylesAndImageSamplingRenderTogether() throws {
93
+ let content = foreign(pixelImage(), attributes: "x=\"4\" y=\"4\" width=\"16\" height=\"16\"")
94
+ .replacingOccurrences(of: "width=\"24\" height=\"24\"", with: "")
95
+ for css in [
96
+ "<style>rect, circle { fill:red; }</style>",
97
+ "<style>rect, circle { fill:red; } img { image-rendering:pixelated; }</style>",
98
+ "<style>img { image-rendering:pixelated; } rect { fill:red; }</style><style>img { image-rendering:smooth; }</style>",
99
+ ] {
100
+ let output = try pixels(document(css + "<rect width=\"24\" height=\"24\"/>" + content), size: 96)
101
+ for (x, y, color) in [(8, 8, [255, 0, 0, 255]), (24, 24, [255, 0, 0, 255]), (64, 24, [0, 0, 255, 255])] {
102
+ let offset = (y * 96 + x) * 4
103
+ XCTAssertEqual(Array(output[offset..<offset + 4]), color.map(UInt8.init), css)
104
+ }
105
+ let edge = (24 * 96 + 47) * 4
106
+ if css.contains("smooth") || !css.contains("pixelated") {
107
+ XCTAssertTrue(output[edge] > 0 && output[edge] < 255)
108
+ } else {
109
+ XCTAssertEqual(Array(output[edge..<edge + 4]), [255, 0, 0, 255])
110
+ }
111
+ }
112
+ }
113
+
114
+ func testStylesThatCouldAffectConvertedContentStillFail() {
115
+ for selector in ["*", ".art", "#art", "g", "svg", "image", "path", "img, rect", "rect img", "rect:hover"] {
116
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(document("<style>\(selector) { fill:red; }</style>" + foreign(embeddedImage())), pixelSize: CGSize(width: 96, height: 96)))
117
+ }
118
+ for css in ["@media all { rect { fill:red; } }", "@import 'external.css'; rect { fill:red; }"] {
119
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(document("<style>\(css)</style>" + foreign(embeddedImage())), pixelSize: CGSize(width: 96, height: 96)))
120
+ }
121
+ }
122
+
123
+ func testSmoothDefaultAndLastStyleDeclarationAreRetained() throws {
124
+ for css in ["", "<style>img { image-rendering:pixelated; image-rendering:auto; -ms-interpolation-mode:nearest-neighbor; }</style>",
125
+ "<style>img { image-rendering:pixelated; }</style><style>img { image-rendering:smooth; }</style>"] {
126
+ let bytes = try pixels(document(foreign(pixelImage()) + css), size: 32)
127
+ let offset = (8 * 32 + 15) * 4
128
+ XCTAssertTrue(bytes[offset] > 0 && bytes[offset] < 255)
129
+ XCTAssertTrue(bytes[offset + 2] > 0 && bytes[offset + 2] < 255)
130
+ }
131
+ }
132
+
133
+ func testPixelRunsKeepGeometryClippingOpacityAndTransparentBackground() throws {
134
+ let foreground = foreign(embeddedImage(),
135
+ attributes: "x=\"6\" y=\"6\" transform=\"translate(1 0)\" opacity=\"0.5\" clip-path=\"url(#clip)\"")
136
+ let layers = "<defs><clipPath id=\"clip\"><rect width=\"12\" height=\"24\"/></clipPath></defs><rect width=\"24\" height=\"24\" fill=\"green\"/>" + foreground
137
+ let sharp = try pixels(document(layers + "<style>img { image-rendering:pixelated; }</style>"), size: 96)
138
+ let smooth = try pixels(document(layers), size: 96)
139
+ XCTAssertTrue(zip(sharp, smooth).allSatisfy { abs(Int($0) - Int($1)) <= 1 })
140
+
141
+ let format = UIGraphicsImageRendererFormat()
142
+ format.scale = 1
143
+ let png = UIGraphicsImageRenderer(size: CGSize(width: 2, height: 2), format: format).image { context in
144
+ UIColor.red.withAlphaComponent(0.5).setFill()
145
+ context.fill(CGRect(x: 1, y: 0, width: 1, height: 2))
146
+ }.pngData()!
147
+ let content = "<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"data:image/png;base64,\(png.base64EncodedString())\"/>"
148
+ let output = try pixels(document("<rect width=\"24\" height=\"24\" fill=\"#00ff00\"/>" + foreign(content) + "<style>img { image-rendering:pixelated; }</style>"), size: 32)
149
+ let clear = (8 * 32 + 8) * 4, alpha = (8 * 32 + 24) * 4
150
+ XCTAssertEqual(Array(output[clear..<clear + 4]), [0, 255, 0, 255])
151
+ XCTAssertTrue(abs(Int(output[alpha]) - 128) <= 1)
152
+ XCTAssertTrue(abs(Int(output[alpha + 1]) - 127) <= 1)
153
+ XCTAssertEqual(output[alpha + 3], 255)
154
+ let clipped = "<defs><clipPath id=\"box\" clipPathUnits=\"objectBoundingBox\"><rect width=\"0.5\" height=\"1\"/></clipPath></defs><rect width=\"24\" height=\"24\" fill=\"#00ff00\"/>" + foreign(content, attributes: "clip-path=\"url(#box)\"")
155
+ let clippedSharp = try pixels(document(clipped + "<style>img { image-rendering:pixelated; }</style>"), size: 32)
156
+ let outsideClip = (8 * 32 + 20) * 4
157
+ XCTAssertEqual(Array(clippedSharp[outsideClip..<outsideClip + 4]), [0, 255, 0, 255])
158
+ }
159
+
160
+ func testGeneratedPixelGeometryIsBoundedAcrossTheDocument() {
161
+ let css = "<style>img { image-rendering:pixelated; }</style>"
162
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(document(foreign(pixelImage(side: 129)) + css), pixelSize: CGSize(width: 64, height: 64)))
163
+ let repeated = foreign(pixelImage(side: 100)) + foreign(pixelImage(side: 100))
164
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(document(repeated + css), pixelSize: CGSize(width: 64, height: 64)))
165
+ }
166
+
167
+ func testEmbeddedPNGUsesTheRegisteredImageDecoderAndRendersPixels() throws {
168
+ let manager = SDImageCodersManager()
169
+ OneKeyImageCoderBridge.addCoders(to: manager)
170
+ let source = document(foreign(embeddedImage()))
171
+ let image = try XCTUnwrap(manager.decodedImage(with: source, options: [
172
+ .decodeThumbnailPixelSize: NSValue(cgSize: CGSize(width: 64, height: 64)),
173
+ ]))
174
+ let cgImage = try XCTUnwrap(image.cgImage)
175
+ XCTAssertEqual(cgImage.width, 64)
176
+ XCTAssertEqual(cgImage.height, 64)
177
+ var pixel = [UInt8](repeating: 0, count: 4)
178
+ let context = try XCTUnwrap(CGContext(data: &pixel, width: 1, height: 1,
179
+ bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(),
180
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
181
+ context.draw(cgImage, in: CGRect(x: 0, y: 0, width: 1, height: 1))
182
+ XCTAssertEqual(pixel, [255, 0, 0, 255])
183
+ }
184
+
185
+ func testUnsupportedHTMLAndExternalImagesFailInsteadOfReturningBackground() {
186
+ for content in [
187
+ "<div xmlns=\"http://www.w3.org/1999/xhtml\">Unsupported</div>",
188
+ "<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"https://example.com/image.png\"/>",
189
+ embeddedImage() + embeddedImage(),
190
+ ] {
191
+ let source = document("<rect width=\"24\" height=\"24\" fill=\"black\"/>" + foreign(content))
192
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(source, pixelSize: CGSize(width: 64, height: 64)))
193
+ }
194
+ }
195
+
196
+ func testUTF16ForeignObjectsMatchUTF8AndRejectEntities() throws {
197
+ for css in ["", "<style>img { image-rendering:pixelated; }</style>"] {
198
+ let source = String(decoding: document(foreign(pixelImage()) + css), as: UTF8.self)
199
+ let expected = try pixels(Data(source.utf8), size: 32)
200
+ for (encoding, name, bom) in [
201
+ (String.Encoding.utf16LittleEndian, "UTF-16LE", Data([0xff, 0xfe])),
202
+ (String.Encoding.utf16BigEndian, "UTF-16BE", Data([0xfe, 0xff])),
203
+ ] {
204
+ let declaration = "<?xml version='1.0' encoding='\(name)'?>"
205
+ for prefix in [Data(), bom] {
206
+ let encoded = try XCTUnwrap((declaration + source).data(using: encoding))
207
+ XCTAssertEqual(try pixels(prefix + encoded, size: 32), expected)
208
+ let entity = try XCTUnwrap((declaration + "<!DOCTYPE svg [<!ENTITY image 'test'>]>" + source).data(using: encoding))
209
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(prefix + entity, pixelSize: CGSize(width: 32, height: 32)))
210
+ }
211
+ }
212
+ }
213
+ }
214
+
215
+ func testDeeplyNestedLargeSmoothPNGMatchesShallowRendering() throws {
216
+ let side = 512
217
+ var bytes = [UInt8](repeating: 255, count: side * side * 4)
218
+ var seed: UInt64 = 51059
219
+ for index in bytes.indices where index % 4 != 3 {
220
+ seed ^= seed << 13
221
+ seed ^= seed >> 7
222
+ seed ^= seed << 17
223
+ bytes[index] = UInt8(truncatingIfNeeded: seed >> 24)
224
+ }
225
+ let provider = try XCTUnwrap(CGDataProvider(data: Data(bytes) as CFData))
226
+ let image = try XCTUnwrap(CGImage(width: side, height: side, bitsPerComponent: 8,
227
+ bitsPerPixel: 32, bytesPerRow: side * 4, space: CGColorSpaceCreateDeviceRGB(),
228
+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue),
229
+ provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent))
230
+ let png = try XCTUnwrap(UIImage(cgImage: image).pngData())
231
+ XCTAssertGreaterThan(png.count, 512 * 1024)
232
+ let content = foreign("<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"data:image/png;base64,\(png.base64EncodedString())\"/>")
233
+ let expected = try pixels(document(content), size: 64)
234
+ let nested = String(repeating: "<g>", count: 60) + content + String(repeating: "</g>", count: 60)
235
+ XCTAssertEqual(try pixels(document(nested), size: 64), expected)
236
+ }
237
+
238
+ func testConvertedThumbnailsBoundOutputCanvas() throws {
239
+ let image = try XCTUnwrap(OneKeyImageCoderBridge.decodeSVG(
240
+ document(foreign(embeddedImage())), pixelSize: CGSize(width: 4096, height: 4096)))
241
+ let pixels = try XCTUnwrap(image.cgImage)
242
+ XCTAssertEqual(pixels.width, 2048)
243
+ XCTAssertEqual(pixels.height, 2048)
244
+ }
245
+
246
+ func testUnsupportedLayoutStylesAndMalformedPNGFail() {
247
+ for body in [
248
+ foreign(embeddedImage(), attributes: "style=\"display:none\""),
249
+ "<style>img { object-fit: cover; }</style>" + foreign(embeddedImage()),
250
+ foreign("<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"data:image/png;base64,AAAA\"/>"),
251
+ foreign(embeddedImage().replacingOccurrences(of: "100%", with: "50%")),
252
+ ] {
253
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(document(body), pixelSize: CGSize(width: 64, height: 64)))
254
+ }
255
+ }
256
+
257
+ func testDocumentBoundsAndOrdinarySVG() {
258
+ let nested = String(repeating: "<g>", count: 64) + foreign(embeddedImage()) + String(repeating: "</g>", count: 64)
259
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(document(nested), pixelSize: .zero))
260
+ let tooMany = String(repeating: foreign(embeddedImage()), count: 17)
261
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(document(tooMany), pixelSize: .zero))
262
+ let entity = Data("<!DOCTYPE svg [<!ENTITY image 'test'>]>".utf8) + document(foreign(embeddedImage()))
263
+ XCTAssertNil(OneKeyImageCoderBridge.decodeSVG(entity, pixelSize: .zero))
264
+ XCTAssertNotNil(OneKeyImageCoderBridge.decodeSVG(document("<rect width=\"24\" height=\"24\" fill=\"red\"/>"), pixelSize: CGSize(width: 64, height: 64)))
265
+ XCTAssertNotNil(OneKeyImageCoderBridge.decodeSVG(document("<!-- foreignObject is not used --><style>rect { fill:red; }</style><rect width=\"24\" height=\"24\"/>"), pixelSize: CGSize(width: 64, height: 64)))
266
+ }
267
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-image",
3
- "version": "6.7.0-alpha.449",
3
+ "version": "6.7.0-alpha.464",
4
4
  "description": "High-performance native image view for OneKey",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",