react-native-audio-browser 0.2.0-next.1 → 0.2.0-next.11

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.
Files changed (290) hide show
  1. package/README.md +22 -18
  2. package/android/build.gradle +13 -10
  3. package/android/gradle.properties +2 -2
  4. package/android/src/main/AndroidManifest.xml +3 -1
  5. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +76 -21
  6. package/android/src/main/java/com/audiobrowser/AudioBrowserLifecycleModule.kt +38 -0
  7. package/android/src/main/java/com/audiobrowser/AudioBrowserPackage.kt +18 -2
  8. package/android/src/main/java/com/audiobrowser/ServiceBinding.kt +48 -0
  9. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +1 -2
  10. package/android/src/main/java/com/audiobrowser/browser/BrowserUrlResolution.kt +1 -2
  11. package/android/src/main/java/com/audiobrowser/browser/SectionScope.kt +6 -7
  12. package/android/src/main/java/com/audiobrowser/http/HttpClient.kt +20 -3
  13. package/android/src/main/java/com/audiobrowser/model/PlayerUpdateOptions.kt +11 -11
  14. package/android/src/main/java/com/audiobrowser/player/CapabilityControls.kt +111 -58
  15. package/android/src/main/java/com/audiobrowser/player/MediaSessionCallback.kt +9 -5
  16. package/android/src/main/java/com/audiobrowser/player/MediaSessionCommandManager.kt +218 -252
  17. package/android/src/main/java/com/audiobrowser/player/NowPlayingUpdater.kt +0 -1
  18. package/android/src/main/java/com/audiobrowser/player/PlaybackStateStore.kt +2 -4
  19. package/android/src/main/java/com/audiobrowser/player/Player.kt +30 -8
  20. package/android/src/main/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicy.kt +2 -1
  21. package/android/src/main/java/com/audiobrowser/player/TransformingDataSource.kt +2 -1
  22. package/android/src/main/java/com/audiobrowser/tls/AiaCertChaser.kt +67 -11
  23. package/android/src/main/java/com/audiobrowser/tls/AiaChasingExtendedTrustManager.kt +168 -0
  24. package/android/src/main/java/com/audiobrowser/tls/AiaChasingTrustManager.kt +58 -14
  25. package/android/src/main/java/com/audiobrowser/tls/AiaTls.kt +35 -7
  26. package/android/src/main/java/com/audiobrowser/tls/CachingCertificateFetcher.kt +278 -59
  27. package/android/src/main/java/com/audiobrowser/util/ArtworkVariant.kt +7 -9
  28. package/android/src/main/java/com/audiobrowser/util/TrackFactory.kt +8 -7
  29. package/android/src/test/java/com/audiobrowser/ServiceBindingTest.kt +87 -0
  30. package/android/src/test/java/com/audiobrowser/TestFixtures.kt +52 -1
  31. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerLayerResolutionTest.kt +6 -0
  32. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerTest.kt +167 -8
  33. package/android/src/test/java/com/audiobrowser/browser/JsonArtworkTest.kt +2 -1
  34. package/android/src/test/java/com/audiobrowser/browser/SectionScopeTest.kt +2 -4
  35. package/android/src/test/java/com/audiobrowser/player/CapabilityControlsTest.kt +100 -56
  36. package/android/src/test/java/com/audiobrowser/player/MediaSessionSlotMappingTest.kt +45 -0
  37. package/android/src/test/java/com/audiobrowser/player/PlaybackErrorClassifierTest.kt +3 -4
  38. package/android/src/test/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicyTest.kt +3 -3
  39. package/android/src/test/java/com/audiobrowser/tls/AiaCertChaserTest.kt +197 -7
  40. package/android/src/test/java/com/audiobrowser/tls/AiaChasingTrustManagerTest.kt +325 -4
  41. package/android/src/test/java/com/audiobrowser/tls/CachingCertificateFetcherCallSiteTest.kt +322 -0
  42. package/android/src/test/java/com/audiobrowser/tls/CachingCertificateFetcherTest.kt +83 -0
  43. package/ios/Browser/BrowserManager.swift +2 -27
  44. package/ios/Browser/SearchDrillIn.swift +1 -1
  45. package/ios/CarPlay/RNABMediaAddHandler.swift +6 -6
  46. package/ios/CarPlay/RNABMediaAffinityHandler.swift +2 -2
  47. package/ios/CarPlay/RNABMediaIntentHandler.swift +16 -16
  48. package/ios/HybridAudioBrowser.swift +87 -56
  49. package/ios/Model/NitroTypeStubs.swift +18 -2
  50. package/ios/Model/RemoteCommand.swift +18 -0
  51. package/ios/Model/TrackPlayerError.swift +2 -2
  52. package/ios/Option/SessionCategories.swift +3 -2
  53. package/ios/Player/MediaIntentCriteria.swift +4 -4
  54. package/ios/Player/MediaLoader.swift +3 -1
  55. package/ios/Player/PlaybackCoordinator.swift +4 -1
  56. package/ios/Player/PlaybackErrorHandler.swift +4 -4
  57. package/ios/Player/QueueManager.swift +10 -3
  58. package/ios/Player/RetryManager.swift +79 -18
  59. package/ios/Player/ShuffleOrder.swift +10 -0
  60. package/ios/Player/SleepTimerManager.swift +43 -15
  61. package/ios/RemoteCommand/RemoteCommandCallbacks.swift +47 -0
  62. package/ios/RemoteCommand/RemoteCommandController.swift +9 -6
  63. package/ios/Tests/LRUCacheTests.swift +111 -0
  64. package/ios/Tests/LoadSeekCoordinatorTests.swift +3 -1
  65. package/ios/Tests/MediaIntentCriteriaTests.swift +2 -2
  66. package/ios/Tests/MediaLoaderTests.swift +10 -13
  67. package/ios/Tests/PlaybackCoordinatorTests.swift +10 -7
  68. package/ios/Tests/PlaybackErrorHandlerTests.swift +3 -1
  69. package/ios/Tests/PlayerTimeObserverTests.swift +37 -0
  70. package/ios/Tests/QueueManagerTests.swift +50 -4
  71. package/ios/Tests/RemoteCommandControllerTests.swift +156 -0
  72. package/ios/Tests/RemoteCommandTests.swift +67 -0
  73. package/ios/Tests/RetryManagerTests.swift +89 -0
  74. package/ios/Tests/SectionScopeTests.swift +2 -2
  75. package/ios/Tests/SleepTimerManagerTests.swift +22 -19
  76. package/ios/Tests/Support/ManualSleepTimerScheduler.swift +47 -0
  77. package/ios/Tests/Support/TestTypes.swift +1 -1
  78. package/ios/Tests/TabBarEntriesTests.swift +7 -7
  79. package/ios/TrackPlayer.swift +6 -1
  80. package/ios/TrackPlayerCallbacks.swift +5 -38
  81. package/ios/Util/LRUCache.swift +4 -1
  82. package/lib/commonjs/AudioBrowser.js +0 -11
  83. package/lib/commonjs/AudioBrowser.js.map +1 -1
  84. package/lib/commonjs/CLAUDE.md +52 -0
  85. package/lib/commonjs/features/browser.js +1 -1
  86. package/lib/commonjs/features/browser.js.map +1 -1
  87. package/lib/commonjs/features/carConnection.js +1 -1
  88. package/lib/commonjs/features/equalizer.js +1 -1
  89. package/lib/commonjs/features/errors.js +3 -3
  90. package/lib/commonjs/features/favorites.js +1 -1
  91. package/lib/commonjs/features/gate.js +16 -1
  92. package/lib/commonjs/features/gate.js.map +1 -1
  93. package/lib/commonjs/features/metadata.js +20 -3
  94. package/lib/commonjs/features/metadata.js.map +1 -1
  95. package/lib/commonjs/features/network.js +1 -1
  96. package/lib/commonjs/features/nowPlaying.js +1 -1
  97. package/lib/commonjs/features/output.js +1 -1
  98. package/lib/commonjs/features/playback/playWhenReady.js +1 -1
  99. package/lib/commonjs/features/playback/playing.js +1 -1
  100. package/lib/commonjs/features/playback/progress.js +1 -1
  101. package/lib/commonjs/features/playback/state.js +1 -1
  102. package/lib/commonjs/features/playback/trackPlaybackTime.js +0 -6
  103. package/lib/commonjs/features/playback/trackPlaybackTime.js.map +1 -1
  104. package/lib/commonjs/features/playback/volume.js +1 -1
  105. package/lib/commonjs/features/player/options.js +48 -34
  106. package/lib/commonjs/features/player/options.js.map +1 -1
  107. package/lib/commonjs/features/player/setup.js +15 -8
  108. package/lib/commonjs/features/player/setup.js.map +1 -1
  109. package/lib/commonjs/features/player/validateOptions.js +21 -0
  110. package/lib/commonjs/features/player/validateOptions.js.map +1 -0
  111. package/lib/commonjs/features/queue/activeTrack.js +1 -1
  112. package/lib/commonjs/features/queue/queue.js +2 -2
  113. package/lib/commonjs/features/queue/repeatMode.js +1 -1
  114. package/lib/commonjs/features/queue/shuffle.js +1 -1
  115. package/lib/commonjs/features/remoteControls.js +13 -92
  116. package/lib/commonjs/features/remoteControls.js.map +1 -1
  117. package/lib/commonjs/features/sleepTimer.js +13 -1
  118. package/lib/commonjs/features/sleepTimer.js.map +1 -1
  119. package/lib/commonjs/test-utils/reactNativeStub.js +65 -0
  120. package/lib/commonjs/test-utils/reactNativeStub.js.map +1 -0
  121. package/lib/commonjs/utils/LazyNativeEmitter.js +8 -5
  122. package/lib/commonjs/utils/LazyNativeEmitter.js.map +1 -1
  123. package/lib/commonjs/web/NativeAudioBrowser.js +1 -1
  124. package/lib/commonjs/web/NativeAudioBrowser.js.map +1 -1
  125. package/lib/commonjs/web/browser/BrowserManager.js +1 -1
  126. package/lib/module/AudioBrowser.js +1 -1
  127. package/lib/module/AudioBrowser.js.map +1 -1
  128. package/lib/module/CLAUDE.md +52 -0
  129. package/lib/module/features/browser.js +1 -1
  130. package/lib/module/features/browser.js.map +1 -1
  131. package/lib/module/features/carConnection.js +1 -1
  132. package/lib/module/features/equalizer.js +1 -1
  133. package/lib/module/features/errors.js +3 -3
  134. package/lib/module/features/favorites.js +1 -1
  135. package/lib/module/features/gate.js +16 -1
  136. package/lib/module/features/gate.js.map +1 -1
  137. package/lib/module/features/metadata.js +20 -3
  138. package/lib/module/features/metadata.js.map +1 -1
  139. package/lib/module/features/network.js +1 -1
  140. package/lib/module/features/nowPlaying.js +1 -1
  141. package/lib/module/features/output.js +1 -1
  142. package/lib/module/features/playback/playWhenReady.js +1 -1
  143. package/lib/module/features/playback/playing.js +1 -1
  144. package/lib/module/features/playback/progress.js +1 -1
  145. package/lib/module/features/playback/state.js +1 -1
  146. package/lib/module/features/playback/trackPlaybackTime.js +0 -5
  147. package/lib/module/features/playback/trackPlaybackTime.js.map +1 -1
  148. package/lib/module/features/playback/volume.js +1 -1
  149. package/lib/module/features/player/options.js +47 -32
  150. package/lib/module/features/player/options.js.map +1 -1
  151. package/lib/module/features/player/setup.js +14 -7
  152. package/lib/module/features/player/setup.js.map +1 -1
  153. package/lib/module/features/player/validateOptions.js +17 -0
  154. package/lib/module/features/player/validateOptions.js.map +1 -0
  155. package/lib/module/features/queue/activeTrack.js +1 -1
  156. package/lib/module/features/queue/queue.js +2 -2
  157. package/lib/module/features/queue/repeatMode.js +1 -1
  158. package/lib/module/features/queue/shuffle.js +1 -1
  159. package/lib/module/features/remoteControls.js +13 -92
  160. package/lib/module/features/remoteControls.js.map +1 -1
  161. package/lib/module/features/sleepTimer.js +13 -1
  162. package/lib/module/features/sleepTimer.js.map +1 -1
  163. package/lib/module/test-utils/reactNativeStub.js +58 -0
  164. package/lib/module/test-utils/reactNativeStub.js.map +1 -0
  165. package/lib/module/utils/LazyNativeEmitter.js +8 -5
  166. package/lib/module/utils/LazyNativeEmitter.js.map +1 -1
  167. package/lib/module/web/NativeAudioBrowser.js +1 -1
  168. package/lib/module/web/NativeAudioBrowser.js.map +1 -1
  169. package/lib/module/web/browser/BrowserManager.js +1 -1
  170. package/lib/typescript/src/AudioBrowser.d.ts +0 -1
  171. package/lib/typescript/src/AudioBrowser.d.ts.map +1 -1
  172. package/lib/typescript/src/features/carConnection.d.ts +1 -1
  173. package/lib/typescript/src/features/equalizer.d.ts +1 -1
  174. package/lib/typescript/src/features/errors.d.ts +3 -3
  175. package/lib/typescript/src/features/favorites.d.ts +1 -1
  176. package/lib/typescript/src/features/gate.d.ts +18 -2
  177. package/lib/typescript/src/features/gate.d.ts.map +1 -1
  178. package/lib/typescript/src/features/metadata.d.ts +20 -3
  179. package/lib/typescript/src/features/metadata.d.ts.map +1 -1
  180. package/lib/typescript/src/features/network.d.ts +1 -1
  181. package/lib/typescript/src/features/nowPlaying.d.ts +1 -1
  182. package/lib/typescript/src/features/output.d.ts +1 -1
  183. package/lib/typescript/src/features/playback/playWhenReady.d.ts +1 -1
  184. package/lib/typescript/src/features/playback/playing.d.ts +1 -1
  185. package/lib/typescript/src/features/playback/progress.d.ts +1 -1
  186. package/lib/typescript/src/features/playback/state.d.ts +1 -1
  187. package/lib/typescript/src/features/playback/volume.d.ts +1 -1
  188. package/lib/typescript/src/features/player/options.d.ts +87 -37
  189. package/lib/typescript/src/features/player/options.d.ts.map +1 -1
  190. package/lib/typescript/src/features/player/setup.d.ts +14 -4
  191. package/lib/typescript/src/features/player/setup.d.ts.map +1 -1
  192. package/lib/typescript/src/features/player/validateOptions.d.ts +9 -0
  193. package/lib/typescript/src/features/player/validateOptions.d.ts.map +1 -0
  194. package/lib/typescript/src/features/queue/activeTrack.d.ts +1 -1
  195. package/lib/typescript/src/features/queue/queue.d.ts +2 -2
  196. package/lib/typescript/src/features/queue/repeatMode.d.ts +1 -1
  197. package/lib/typescript/src/features/queue/shuffle.d.ts +1 -1
  198. package/lib/typescript/src/features/remoteControls.d.ts +23 -22
  199. package/lib/typescript/src/features/remoteControls.d.ts.map +1 -1
  200. package/lib/typescript/src/features/sleepTimer.d.ts +1 -1
  201. package/lib/typescript/src/features/sleepTimer.d.ts.map +1 -1
  202. package/lib/typescript/src/test-utils/reactNativeStub.d.ts +36 -0
  203. package/lib/typescript/src/test-utils/reactNativeStub.d.ts.map +1 -0
  204. package/lib/typescript/src/utils/LazyNativeEmitter.d.ts +8 -4
  205. package/lib/typescript/src/utils/LazyNativeEmitter.d.ts.map +1 -1
  206. package/nitrogen/generated/android/AudioBrowser+autolinking.cmake +1 -1
  207. package/nitrogen/generated/android/c++/JAndroidOptions.hpp +10 -10
  208. package/nitrogen/generated/android/c++/JFunc_void_Options.hpp +5 -5
  209. package/nitrogen/generated/android/c++/JHybridAudioBrowserSpec.cpp +11 -11
  210. package/nitrogen/generated/android/c++/JHybridAudioBrowserSpec.hpp +1 -1
  211. package/nitrogen/generated/android/c++/JNativeSetupPlayerOptions.hpp +5 -5
  212. package/nitrogen/generated/android/c++/JNativeUpdateOptions.hpp +5 -5
  213. package/nitrogen/generated/android/c++/JNitroAndroidUpdateOptions.hpp +10 -10
  214. package/nitrogen/generated/android/c++/JOptions.hpp +5 -5
  215. package/nitrogen/generated/android/c++/{JNotificationButton.hpp → JRemoteButton.hpp} +19 -19
  216. package/nitrogen/generated/android/c++/JRemoteButtonLayout.hpp +86 -0
  217. package/nitrogen/generated/android/c++/JVariant_NullType_RemoteButtonLayout.cpp +26 -0
  218. package/nitrogen/generated/android/c++/JVariant_NullType_RemoteButtonLayout.hpp +75 -0
  219. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/AndroidOptions.kt +3 -3
  220. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/HybridAudioBrowserSpec.kt +1 -1
  221. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/NitroAndroidUpdateOptions.kt +3 -3
  222. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/{NotificationButton.kt → RemoteButton.kt} +3 -3
  223. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/RemoteButtonLayout.kt +44 -0
  224. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/{Variant_NullType_NotificationButtonLayout.kt → Variant_NullType_RemoteButtonLayout.kt} +9 -9
  225. package/nitrogen/generated/ios/AudioBrowser-Swift-Cxx-Bridge.hpp +36 -51
  226. package/nitrogen/generated/ios/AudioBrowser-Swift-Cxx-Umbrella.hpp +6 -6
  227. package/nitrogen/generated/ios/c++/HybridAudioBrowserSpecSwift.hpp +8 -8
  228. package/nitrogen/generated/ios/swift/AndroidOptions.swift +12 -12
  229. package/nitrogen/generated/ios/swift/HybridAudioBrowserSpec.swift +1 -1
  230. package/nitrogen/generated/ios/swift/HybridAudioBrowserSpec_cxx.swift +2 -2
  231. package/nitrogen/generated/ios/swift/NitroAndroidUpdateOptions.swift +12 -12
  232. package/nitrogen/generated/ios/swift/{NotificationButton.swift → RemoteButton.swift} +6 -6
  233. package/nitrogen/generated/ios/swift/RemoteButtonLayout.swift +57 -0
  234. package/nitrogen/generated/ios/swift/{Variant_NullType_NotificationButtonLayout.swift → Variant_NullType_RemoteButtonLayout.swift} +3 -3
  235. package/nitrogen/generated/shared/c++/AndroidOptions.hpp +8 -8
  236. package/nitrogen/generated/shared/c++/HybridAudioBrowserSpec.cpp +1 -1
  237. package/nitrogen/generated/shared/c++/HybridAudioBrowserSpec.hpp +1 -1
  238. package/nitrogen/generated/shared/c++/NitroAndroidUpdateOptions.hpp +8 -8
  239. package/nitrogen/generated/shared/c++/{NotificationButton.hpp → RemoteButton.hpp} +19 -19
  240. package/nitrogen/generated/shared/c++/RemoteButtonLayout.hpp +94 -0
  241. package/package.json +12 -4
  242. package/src/AudioBrowser.ts +1 -1
  243. package/src/CLAUDE.md +52 -0
  244. package/src/features/battery.test.ts +79 -0
  245. package/src/features/browser.ts +1 -1
  246. package/src/features/carConnection.ts +1 -1
  247. package/src/features/equalizer.ts +1 -1
  248. package/src/features/errors.ts +3 -3
  249. package/src/features/favorites.ts +1 -1
  250. package/src/features/gate.ts +16 -1
  251. package/src/features/hook-wiring.test.ts +254 -0
  252. package/src/features/metadata.ts +20 -3
  253. package/src/features/network.ts +1 -1
  254. package/src/features/nowPlaying.ts +1 -1
  255. package/src/features/output.ts +1 -1
  256. package/src/features/playback/playWhenReady.ts +1 -1
  257. package/src/features/playback/playing.ts +1 -1
  258. package/src/features/playback/progress.test.ts +169 -0
  259. package/src/features/playback/progress.ts +1 -1
  260. package/src/features/playback/state.ts +1 -1
  261. package/src/features/playback/trackPlaybackTime.test.ts +16 -6
  262. package/src/features/playback/trackPlaybackTime.ts +0 -5
  263. package/src/features/playback/volume.ts +1 -1
  264. package/src/features/player/options.ts +99 -57
  265. package/src/features/player/setup.test.ts +12 -4
  266. package/src/features/player/setup.ts +19 -9
  267. package/src/features/player/validateOptions.ts +19 -0
  268. package/src/features/queue/activeTrack.ts +1 -1
  269. package/src/features/queue/queue.ts +2 -2
  270. package/src/features/queue/repeatMode.ts +1 -1
  271. package/src/features/queue/shuffle.ts +1 -1
  272. package/src/features/remoteControls.ts +13 -92
  273. package/src/features/sleepTimer.test.ts +172 -0
  274. package/src/features/sleepTimer.ts +9 -1
  275. package/src/nitro-stub-drift.test.ts +237 -0
  276. package/src/public-surface.test.ts +107 -0
  277. package/src/specs/audio-browser.nitro.ts +1 -1
  278. package/src/test-utils/reactNativeStub.ts +60 -0
  279. package/src/utils/LazyNativeEmitter.ts +9 -6
  280. package/src/utils/useDebug.test.ts +182 -0
  281. package/src/utils/useNativeUpdatedValue.test.ts +103 -0
  282. package/src/web/NativeAudioBrowser.ts +1 -1
  283. package/src/web/browser/BrowserManager.ts +1 -1
  284. package/ios/Model/MediaURL.swift +0 -67
  285. package/nitrogen/generated/android/c++/JNotificationButtonLayout.hpp +0 -94
  286. package/nitrogen/generated/android/c++/JVariant_NullType_NotificationButtonLayout.cpp +0 -26
  287. package/nitrogen/generated/android/c++/JVariant_NullType_NotificationButtonLayout.hpp +0 -75
  288. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/NotificationButtonLayout.kt +0 -50
  289. package/nitrogen/generated/ios/swift/NotificationButtonLayout.swift +0 -92
  290. package/nitrogen/generated/shared/c++/NotificationButtonLayout.hpp +0 -102
@@ -2,39 +2,75 @@ package com.audiobrowser.tls
2
2
 
3
3
  import java.io.ByteArrayInputStream
4
4
  import java.io.ByteArrayOutputStream
5
+ import java.io.InputStream
5
6
  import java.net.InetSocketAddress
6
7
  import java.net.Socket
7
8
  import java.net.URL
8
9
  import java.security.cert.CertificateFactory
9
10
  import java.security.cert.X509Certificate
10
- import java.util.concurrent.ConcurrentHashMap
11
+ import java.util.concurrent.atomic.AtomicBoolean
11
12
  import javax.net.ssl.HttpsURLConnection
12
13
  import javax.net.ssl.SSLContext
14
+ import javax.net.ssl.SSLSocket
13
15
  import javax.net.ssl.SSLSocketFactory
16
+ import kotlin.concurrent.thread
14
17
  import timber.log.Timber
15
18
 
16
19
  /**
17
20
  * Fetches and caches issuer certificates from AIA "CA Issuers" URLs. Used by
18
21
  * [AiaChasingTrustManager] to fill in intermediates a server failed to send.
19
22
  *
20
- * Runs on the TLS handshake thread, so it uses short timeouts and never throws — a failed or slow
21
- * fetch resolves to an empty list (the handshake then fails exactly as it would have without AIA
22
- * chasing). Only non-empty results are cached, so the (typically `http`) round-trip happens at most
23
- * once per intermediate for the process lifetime while transient failures stay retryable.
23
+ * Runs on the TLS handshake thread, so it is bounded on every axis and never throws — a failed,
24
+ * oversized or slow fetch resolves to an empty list, and the handshake then fails exactly as it
25
+ * would have without AIA chasing. Every input here is chosen by a server we are already failing to
26
+ * validate: the AIA extension names the host, port and path, and then that host chooses the
27
+ * response. So:
28
+ * - the URL is rejected unless it is free of control characters ([isSafeUrl]),
29
+ * - a response is capped at [MAX_RESPONSE_BYTES] and [MAX_RESPONSE_MILLIS],
30
+ * - at most [MAX_REDIRECTS] redirects are followed,
31
+ * - the cache holds at most [MAX_CACHE_ENTRIES], and only successful fetches, so a round trip
32
+ * happens at most once per intermediate while transient failures stay retryable,
33
+ * - the whole call — every connect, handshake, read and redirect hop — ends at the caller's
34
+ * `deadlineNanos`: each per-operation timeout is clipped to the time remaining, connect and read
35
+ * by their socket timeouts and the TLS handshake plus the exchange by a watchdog that closes the
36
+ * underlying transport, and once the deadline has passed nothing further is even started.
24
37
  *
25
- * `http` fetches go over a raw [Socket] rather than `HttpURLConnection`. CA "CA Issuers" URLs are
26
- * virtually always plain `http` (the CA/Browser Forum Baseline Requirements mandate it, to avoid a
27
- * chicken-and-egg TLS dependency when fetching the cert needed to complete a TLS chain), but
28
- * Android blocks cleartext `HttpURLConnection` traffic by default on apps targeting API 28+. A raw
29
- * socket is not subject to `NetworkSecurityPolicy`, so the fetch succeeds regardless of the host
30
- * app's cleartext setting — safely, because the fetched certificate is still cryptographically
31
- * verified to be the real issuer before [AiaChasingTrustManager] trusts it.
38
+ * The one step no deadline reaches is DNS: `InetSocketAddress` resolves synchronously and Java
39
+ * exposes no timeout for it, so a lookup begun just inside the deadline can overrun it by its own
40
+ * duration. A lookup is never *started* past the deadline, and [AiaCertChaser.MAX_URLS_PER_CERT]
41
+ * keeps the count down — a certificate can only make us resolve a few names, not a few hundred.
42
+ *
43
+ * Both schemes go over a raw [Socket] rather than `HttpURLConnection`. For `http` that is because
44
+ * CA "CA Issuers" URLs are virtually always plain `http` — the CA/Browser Forum Baseline
45
+ * Requirements mandate it, to avoid a chicken-and-egg TLS dependency when fetching the certificate
46
+ * needed to complete a TLS chain — while Android blocks cleartext `HttpURLConnection` traffic by
47
+ * default on apps targeting API 28+. A raw socket is not subject to `NetworkSecurityPolicy`, so the
48
+ * fetch succeeds regardless of the host app's cleartext setting; safely, because the fetched
49
+ * certificate is still cryptographically verified to be the real issuer before
50
+ * [AiaChasingTrustManager] trusts it.
51
+ *
52
+ * For `https` it is because `HttpURLConnection.getInputStream()` performs the connect, request and
53
+ * response *headers* before returning a stream, so a read cap applied to that stream bounds only
54
+ * the body: a server dripping header bytes just inside the per-read timeout would hold the
55
+ * handshake thread for as long as it liked. Reading the headers ourselves puts them inside the same
56
+ * budget as the body. It also keeps one redirect policy — the platform stack would otherwise follow
57
+ * its own, ignoring [MAX_REDIRECTS].
32
58
  */
33
59
  class CachingCertificateFetcher(
34
60
  private val connectTimeoutMs: Int = 5_000,
35
61
  private val readTimeoutMs: Int = 5_000,
62
+ private val nowNanos: () -> Long = System::nanoTime,
36
63
  ) {
37
- private val cache = ConcurrentHashMap<String, List<X509Certificate>>()
64
+ /**
65
+ * Bounded, least-recently-used. An attacker can name any URL and serve any parseable certificate
66
+ * from it, so an unbounded map would retain a megabyte per hostile handshake for the process
67
+ * lifetime. A real app needs a handful of intermediates.
68
+ */
69
+ private val cache =
70
+ object : LinkedHashMap<String, List<X509Certificate>>(16, 0.75f, true) {
71
+ override fun removeEldestEntry(eldest: Map.Entry<String, List<X509Certificate>>) =
72
+ size > MAX_CACHE_ENTRIES
73
+ }
38
74
 
39
75
  /**
40
76
  * A plain system-default socket factory for `https` AIA fetches. Without it the fetch would use
@@ -45,80 +81,230 @@ class CachingCertificateFetcher(
45
81
  SSLContext.getInstance("TLS").apply { init(null, null, null) }.socketFactory
46
82
  }
47
83
 
48
- fun fetch(url: String): List<X509Certificate> {
49
- cache[url]?.let {
50
- return it
51
- }
52
- val certs = download(url)?.let { parseCertificates(it) }.orEmpty()
53
- if (certs.isNotEmpty()) cache[url] = certs
84
+ /**
85
+ * Fetches the certificates served at [url], giving up no later than [deadlineNanos] — absolute,
86
+ * on [nowNanos]'s origin. [AiaCertChaser.completeChain] passes its whole-walk deadline here, so
87
+ * one budget bounds the sum of every fetch it makes. The default covers a standalone call.
88
+ *
89
+ * A cache hit is answered even past the deadline — it costs no I/O.
90
+ */
91
+ fun fetch(
92
+ url: String,
93
+ deadlineNanos: Long = nowNanos() + AiaCertChaser.MAX_CHASE_MILLIS * 1_000_000,
94
+ ): List<X509Certificate> {
95
+ synchronized(cache) { cache[url] }
96
+ ?.let {
97
+ return it
98
+ }
99
+ val certs = download(url, deadlineNanos)?.let { parseCertificates(it) }.orEmpty()
100
+ if (certs.isNotEmpty()) synchronized(cache) { cache[url] = certs }
54
101
  return certs
55
102
  }
56
103
 
57
- private fun download(url: String, redirectsLeft: Int = MAX_REDIRECTS): ByteArray? =
104
+ /** Milliseconds until [deadlineNanos]; zero or negative once it has passed. */
105
+ private fun remainingMs(deadlineNanos: Long): Long = (deadlineNanos - nowNanos()) / 1_000_000
106
+
107
+ private fun download(
108
+ url: String,
109
+ deadlineNanos: Long,
110
+ redirectsLeft: Int = MAX_REDIRECTS,
111
+ ): ByteArray? =
58
112
  try {
113
+ // Checked before anything is started — DNS included, since it is the one step below that
114
+ // no timeout reaches. Redirects recurse through here, so every hop re-checks.
115
+ require(remainingMs(deadlineNanos) > 0) { "AIA chase budget exhausted" }
116
+ require(isSafeUrl(url)) { "AIA URL contains characters that are not valid in a URL" }
59
117
  val parsed = URL(url)
60
118
  when (parsed.protocol) {
61
- "http" -> downloadCleartext(parsed, redirectsLeft)
62
- "https" -> downloadHttps(parsed)
63
- else -> null // restrict to http/https — file:, ftp: etc. are never valid CA-issuer sources
119
+ // restrict to http/https — file:, ftp: etc. are never valid CA-issuer sources
120
+ "http" -> fetchOverSocket(parsed, deadlineNanos, redirectsLeft, secure = false)
121
+ "https" -> fetchOverSocket(parsed, deadlineNanos, redirectsLeft, secure = true)
122
+ else -> null
64
123
  }
65
124
  } catch (e: Exception) {
66
- Timber.w(e, "AIA CA-issuer fetch failed: %s", url)
125
+ // The URL is attacker-supplied text and this is the one place it survives the safety
126
+ // check, so it is escaped rather than handed to the log verbatim.
127
+ Timber.w(e, "AIA CA-issuer fetch failed: %s", sanitizeForLog(url))
67
128
  null
68
129
  }
69
130
 
70
131
  /**
71
- * `https` AIA fetch over the platform HTTP stack. `https` is never subject to Android's cleartext
72
- * policy, so `HttpsURLConnection` is fine here; the plain socket factory keeps the fetch's own
73
- * handshake from recursing into AIA chasing.
132
+ * A connected socket to speak HTTP over, plus the plain TCP transport underneath it. They differ
133
+ * for `https`: closing an `SSLSocket` writes a `close_notify` alert, which can itself block
134
+ * against a peer that stopped reading — so anything that needs to *unblock* a stalled call must
135
+ * close [transport], whose close is immediate and fails every read layered above it.
74
136
  */
75
- private fun downloadHttps(url: URL): ByteArray? {
76
- val connection = url.openConnection() as? HttpsURLConnection ?: return null
77
- connection.connectTimeout = connectTimeoutMs
78
- connection.readTimeout = readTimeoutMs
79
- connection.sslSocketFactory = plainSslSocketFactory
80
- return connection.inputStream.use { it.readBytes() }
81
- }
137
+ private class Connection(val socket: Socket, val transport: Socket)
82
138
 
83
- /**
84
- * `http` AIA fetch over a raw socket — see the class doc for why this bypasses
85
- * `HttpURLConnection`.
86
- */
87
- private fun downloadCleartext(url: URL, redirectsLeft: Int): ByteArray? {
139
+ /** One HTTP/1.0 exchange over a socket, TLS-wrapped when [secure], then redirects. */
140
+ private fun fetchOverSocket(
141
+ url: URL,
142
+ deadlineNanos: Long,
143
+ redirectsLeft: Int,
144
+ secure: Boolean,
145
+ ): ByteArray? {
88
146
  val host = url.host
89
- val port = if (url.port != -1) url.port else 80
147
+ val port = if (url.port != -1) url.port else if (secure) 443 else 80
90
148
  val path = url.file.ifEmpty { "/" } // URL.file is path + query
149
+ val connection = connect(host, port, secure, deadlineNanos)
91
150
  val raw =
92
- Socket().use { socket ->
93
- socket.connect(InetSocketAddress(host, port), connectTimeoutMs)
94
- socket.soTimeout = readTimeoutMs
95
- // HTTP/1.0 + `Connection: close` so the server closes after the body and we can read to EOF
96
- // without parsing Content-Length.
97
- val request =
98
- "GET $path HTTP/1.0\r\n" +
99
- "Host: $host\r\n" +
100
- "Connection: close\r\n" +
101
- "User-Agent: react-native-audio-browser\r\n" +
102
- "Accept: */*\r\n\r\n"
103
- socket.getOutputStream().apply {
104
- write(request.toByteArray(Charsets.ISO_8859_1))
105
- flush()
151
+ try {
152
+ withWatchdog(
153
+ minOf(remainingMs(deadlineNanos), connectTimeoutMs + MAX_RESPONSE_MILLIS),
154
+ abort = { connection.transport.close() },
155
+ ) {
156
+ val socket = connection.socket
157
+ socket.soTimeout = timeoutMs(deadlineNanos, readTimeoutMs)
158
+ // HTTP/1.0 + `Connection: close` so the server closes after the body and we can read
159
+ // to EOF without parsing Content-Length. A non-default port belongs in Host, or a
160
+ // name-based virtual host answers for the wrong site.
161
+ val hostHeader = if (port == (if (secure) 443 else 80)) host else "$host:$port"
162
+ val request =
163
+ "GET $path HTTP/1.0\r\n" +
164
+ "Host: $hostHeader\r\n" +
165
+ "Connection: close\r\n" +
166
+ "User-Agent: react-native-audio-browser\r\n" +
167
+ "Accept: */*\r\n\r\n"
168
+ socket.getOutputStream().apply {
169
+ write(request.toByteArray(Charsets.ISO_8859_1))
170
+ flush()
171
+ }
172
+ socket.getInputStream().use {
173
+ readCapped(
174
+ it,
175
+ budgetMs = minOf(remainingMs(deadlineNanos), MAX_RESPONSE_MILLIS),
176
+ nowNanos = nowNanos,
177
+ )
178
+ }
106
179
  }
107
- socket.getInputStream().use { it.readBytes() }
108
- }
180
+ } finally {
181
+ // Transport first: its close never blocks and unblocks anything above it, so the
182
+ // SSLSocket's close_notify attempt afterwards fails fast instead of stalling.
183
+ runCatching { connection.transport.close() }
184
+ runCatching { connection.socket.close() }
185
+ } ?: return null
109
186
  val response = parseHttpResponse(raw) ?: return null
110
187
  return when {
111
188
  response.status in 200..299 -> response.body
112
189
  response.status in 300..399 && response.location != null && redirectsLeft > 0 ->
113
- // Follow CA-issuer redirects (rare). A redirect to `https` falls through to the https path.
114
- download(URL(url, response.location).toString(), redirectsLeft - 1)
190
+ // Follow CA-issuer redirects (rare). `download` is the recursion point, so the target
191
+ // goes through the same URL check and the same deadline.
192
+ download(URL(url, response.location).toString(), deadlineNanos, redirectsLeft - 1)
115
193
  else -> null
116
194
  }
117
195
  }
118
196
 
197
+ /**
198
+ * Connects to [host]:[port], wrapping in TLS when [secure]. Both the connect and the TLS
199
+ * handshake are clipped to the caller's deadline.
200
+ *
201
+ * The TLS socket verifies the hostname explicitly. A raw `SSLSocket` does not do it on its own,
202
+ * and `SSLParameters.setEndpointIdentificationAlgorithm` is API 24+, so the platform's default
203
+ * verifier is applied against the negotiated session instead — which works on every supported
204
+ * level and is the same check `HttpsURLConnection` would have made.
205
+ */
206
+ private fun connect(host: String, port: Int, secure: Boolean, deadlineNanos: Long): Connection {
207
+ val plain = Socket()
208
+ // Everything from here on closes `plain` if it throws. Android's Socket.connect, unlike
209
+ // modern OpenJDK's, does not close itself on failure once the descriptor is allocated, so
210
+ // every unreachable AIA host would otherwise leak one until finalization.
211
+ var wrapper: SSLSocket? = null
212
+ return try {
213
+ plain.connect(InetSocketAddress(host, port), timeoutMs(deadlineNanos, connectTimeoutMs))
214
+ if (!secure) return Connection(plain, plain)
215
+ // The handshake is bounded by a watchdog, not by soTimeout: soTimeout is per-read, so a
216
+ // server drip-feeding handshake bytes would stretch it indefinitely. The watchdog closes
217
+ // `plain`, the transport — closing the SSLSocket instead would write a close_notify that
218
+ // can block against the very peer that caused the stall.
219
+ withWatchdog(
220
+ minOf(remainingMs(deadlineNanos), connectTimeoutMs + MAX_RESPONSE_MILLIS),
221
+ abort = { plain.close() },
222
+ ) {
223
+ val ssl = plainSslSocketFactory.createSocket(plain, host, port, true) as SSLSocket
224
+ wrapper = ssl
225
+ ssl.soTimeout = timeoutMs(deadlineNanos, readTimeoutMs)
226
+ ssl.startHandshake()
227
+ require(HttpsURLConnection.getDefaultHostnameVerifier().verify(host, ssl.session)) {
228
+ "AIA host $host does not match its certificate"
229
+ }
230
+ Connection(ssl, plain)
231
+ }
232
+ } catch (e: Exception) {
233
+ runCatching { plain.close() }
234
+ // The orphaned TLS wrapper too — with the transport already gone its close_notify attempt
235
+ // fails fast, and this releases the wrapper's own buffers rather than waiting on the GC.
236
+ runCatching { wrapper?.close() }
237
+ throw e
238
+ }
239
+ }
240
+
241
+ /**
242
+ * A per-operation socket timeout: [perOperationMs] clipped to the deadline, and never 0 ("no
243
+ * timeout" to a socket) — an already-expired deadline still gets a 1 ms timeout and fails at
244
+ * once.
245
+ */
246
+ private fun timeoutMs(deadlineNanos: Long, perOperationMs: Int): Int =
247
+ minOf(remainingMs(deadlineNanos), perOperationMs.toLong())
248
+ .coerceIn(1, Int.MAX_VALUE.toLong())
249
+ .toInt()
250
+
251
+ /**
252
+ * Runs [body] with a watchdog thread that invokes [abort] once [budgetMs] elapses — unless the
253
+ * body has already finished, which the done flag makes visible to a watchdog waking at just that
254
+ * moment, so a successful exchange cannot have its socket closed out from under it.
255
+ *
256
+ * The socket timeouts are per-operation and so cannot bound a peer that keeps every individual
257
+ * read just inside them; [abort] — closing the underlying transport — is what actually ends a
258
+ * stalled handshake or exchange: the blocked call throws, and a failed fetch is already handled
259
+ * as "no AIA".
260
+ */
261
+ private inline fun <T> withWatchdog(
262
+ budgetMs: Long,
263
+ crossinline abort: () -> Unit,
264
+ body: () -> T,
265
+ ): T {
266
+ val done = AtomicBoolean(false)
267
+ val watchdog =
268
+ thread(isDaemon = true, name = "aia-fetch-watchdog") {
269
+ runCatching { Thread.sleep(budgetMs.coerceAtLeast(0)) }
270
+ .onSuccess { if (!done.get()) runCatching { abort() } }
271
+ }
272
+ try {
273
+ return body()
274
+ } finally {
275
+ done.set(true)
276
+ watchdog.interrupt()
277
+ }
278
+ }
279
+
119
280
  companion object {
120
281
  private const val MAX_REDIRECTS = 5
121
282
 
283
+ /** Ceiling on how many fetched issuer certificates are retained. */
284
+ const val MAX_CACHE_ENTRIES = 32
285
+
286
+ /** Ceiling on a single AIA response, headers included. */
287
+ const val MAX_RESPONSE_BYTES = 1 shl 20 // 1 MiB
288
+
289
+ /** Ceiling on the wall-clock time spent reading one AIA response. */
290
+ const val MAX_RESPONSE_MILLIS = 10_000L
291
+
292
+ /**
293
+ * Whether [url] is free of characters that have no business in a URL.
294
+ *
295
+ * The fetch writes the path into a request line on a raw socket, and the URL is an IA5String
296
+ * copied verbatim out of a certificate a hostile server presented. `java.net.URL` preserves
297
+ * control characters — `URL("http://host:6379/\r\nSET foo bar")` parses to that host and port
298
+ * with the CRLF intact in `file` — so without this check a certificate could inject request
299
+ * lines of its own, to any host and port the device can reach. Space is excluded too: it would
300
+ * split the request line's target from its HTTP version.
301
+ */
302
+ fun isSafeUrl(url: String): Boolean = url.none { it.code <= 0x20 || it.code == 0x7F }
303
+
304
+ /** [text] with anything non-printable replaced, so a log line cannot be forged. */
305
+ fun sanitizeForLog(text: String): String =
306
+ text.map { if (it.code <= 0x20 || it.code == 0x7F) '?' else it }.joinToString("")
307
+
122
308
  /**
123
309
  * Parses every certificate from the bytes a CA-Issuers URL serves — a single DER certificate
124
310
  * (e.g. Let's Encrypt), a PEM file, or a PKCS#7 "certs-only" bundle. Empty if the bytes are not
@@ -133,6 +319,37 @@ class CachingCertificateFetcher(
133
319
  emptyList()
134
320
  }
135
321
 
322
+ /**
323
+ * Reads [input] to EOF, or returns null once it exceeds [limit] bytes or [budgetMs] of
324
+ * wall-clock time. Null rather than a truncated buffer: a cut-off certificate is not parseable
325
+ * anyway, and "too big" or "too slow" is a failed fetch, which the caller already knows how to
326
+ * treat as "no AIA".
327
+ *
328
+ * The byte cap alone would not bound the time. The socket's timeout is per-read, so a server
329
+ * returning one byte just inside it resets the clock on every iteration and holds the handshake
330
+ * thread for as long as it likes — a slow-drip stall in place of the unbounded buffer. Both
331
+ * limits are needed, and the deadline is checked against [nowNanos] (injectable so a test need
332
+ * not actually wait).
333
+ */
334
+ fun readCapped(
335
+ input: InputStream,
336
+ limit: Int = MAX_RESPONSE_BYTES,
337
+ budgetMs: Long = MAX_RESPONSE_MILLIS,
338
+ nowNanos: () -> Long = System::nanoTime,
339
+ ): ByteArray? {
340
+ val deadline = nowNanos() + budgetMs * 1_000_000
341
+ val out = ByteArrayOutputStream()
342
+ val chunk = ByteArray(8 * 1024)
343
+ while (true) {
344
+ val read = input.read(chunk)
345
+ if (read < 0) return out.toByteArray()
346
+ if (out.size() + read > limit) return null
347
+ out.write(chunk, 0, read)
348
+ // Subtraction, not `>`: overflow-safe across nanoTime's arbitrary origin.
349
+ if (nowNanos() - deadline >= 0) return null
350
+ }
351
+ }
352
+
136
353
  /** Status code, `Location` header (if any), and decoded body of a raw HTTP response. */
137
354
  data class HttpResponse(val status: Int, val location: String?, val body: ByteArray)
138
355
 
@@ -175,7 +392,9 @@ class CachingCertificateFetcher(
175
392
  .substringBefore(';')
176
393
  .trim()
177
394
  .toIntOrNull(16) ?: break
178
- if (size == 0) break // last chunk
395
+ // `<= 0`, not `== 0`: toIntOrNull accepts a leading `-`, and a negative size would move
396
+ // `pos` backwards — the same rewinding-cursor loop the DER reader had.
397
+ if (size <= 0) break // last chunk, or malformed
179
398
  val dataStart = eol + 2
180
399
  if (dataStart + size > body.size) break
181
400
  out.write(body, dataStart, size)
@@ -5,11 +5,10 @@ import com.margelo.nitro.audiobrowser.Variant_String_ArtworkVariants
5
5
  /**
6
6
  * Reading `Track.artwork`, which is either one URL or a URL per appearance.
7
7
  *
8
- * Android Auto is dark-only, so there is nothing here to choose: a pair always
9
- * resolves to its dark URL, which is also what a single-URL track would have
10
- * shipped. The per-appearance half of the feature is iOS/CarPlay only — see
11
- * `ios/Extension/Variant+Artwork.swift`, where both URLs are kept so a
12
- * `UIImageAsset` can swap them without a re-fetch.
8
+ * Android Auto is dark-only, so there is nothing here to choose: a pair always resolves to its dark
9
+ * URL, which is also what a single-URL track would have shipped. The per-appearance half of the
10
+ * feature is iOS/CarPlay only — see `ios/Extension/Variant+Artwork.swift`, where both URLs are kept
11
+ * so a `UIImageAsset` can swap them without a re-fetch.
13
12
  */
14
13
  val Variant_String_ArtworkVariants.url: String
15
14
  get() = match(first = { it }, second = { it.dark })
@@ -17,10 +16,9 @@ val Variant_String_ArtworkVariants.url: String
17
16
  /**
18
17
  * Wraps a plain URL as the single-URL side of the union.
19
18
  *
20
- * For the places that build a `Track` from something that only ever has one
21
- * image — restored persistence, a `MediaMetadata` handed back by the platform.
22
- * Restoring collapses a pair to its dark URL, which costs nothing here: Android
23
- * Auto would have rendered that one anyway.
19
+ * For the places that build a `Track` from something that only ever has one image — restored
20
+ * persistence, a `MediaMetadata` handed back by the platform. Restoring collapses a pair to its
21
+ * dark URL, which costs nothing here: Android Auto would have rendered that one anyway.
24
22
  */
25
23
  fun artworkOf(url: String?): Variant_String_ArtworkVariants? =
26
24
  url?.let { Variant_String_ArtworkVariants.First(it) }
@@ -26,12 +26,12 @@ object TrackFactory {
26
26
  }
27
27
 
28
28
  /**
29
- * Android Auto has no image-row rendering; its closest equivalent is a grid of artwork
30
- * tiles. A track carrying `imageRow` expands into its items as grid-styled rows (the
31
- * per-item content-style hint — hosts that ignore it fall back to list rows) grouped under
32
- * the row's title, followed by the row itself as a browsable "view all" link when it has a
33
- * `url` (a url-less row is a pure preview and contributes only its items). Tracks without
34
- * an `imageRow` pass through unchanged.
29
+ * Android Auto has no image-row rendering; its closest equivalent is a grid of artwork tiles. A
30
+ * track carrying `imageRow` expands into its items as grid-styled rows (the per-item
31
+ * content-style hint — hosts that ignore it fall back to list rows) grouped under the row's
32
+ * title, followed by the row itself as a browsable "view all" link when it has a `url` (a
33
+ * url-less row is a pure preview and contributes only its items). Tracks without an `imageRow`
34
+ * pass through unchanged.
35
35
  */
36
36
  fun expandImageRows(tracks: List<Track>): List<Track> =
37
37
  tracks.flatMap { track ->
@@ -95,7 +95,8 @@ object TrackFactory {
95
95
  val scheme = rawUrl?.let { Uri.parse(it).scheme?.lowercase() }
96
96
  val builder = metadataBuilder(track)
97
97
  if (rawUrl != null && (scheme == "http" || scheme == "https")) {
98
- val isSvg = SvgArtworkRenderer.isSvgUrl(rawUrl) || SvgArtworkRenderer.isSvgUrl(track.artwork?.url)
98
+ val isSvg =
99
+ SvgArtworkRenderer.isSvgUrl(rawUrl) || SvgArtworkRenderer.isSvgUrl(track.artwork?.url)
99
100
  val token = ArtworkUris.tokenFor(rawUrl)
100
101
  registry.register(token, ResolvedArtwork(rawUrl, track.artworkSource?.headers, isSvg))
101
102
  builder.setArtworkUri(ArtworkUris.contentUri(authority, token).toUri())
@@ -0,0 +1,87 @@
1
+ package com.audiobrowser
2
+
3
+ import android.content.ComponentName
4
+ import android.content.Intent
5
+ import android.content.ServiceConnection
6
+ import android.os.IBinder
7
+ import org.junit.Assert.assertEquals
8
+ import org.junit.Assert.assertFalse
9
+ import org.junit.Assert.assertTrue
10
+ import org.junit.Test
11
+ import org.junit.runner.RunWith
12
+ import org.robolectric.RobolectricTestRunner
13
+ import org.robolectric.RuntimeEnvironment
14
+ import org.robolectric.Shadows.shadowOf
15
+
16
+ // Robolectric: bindService/unbindService only exist under the framework, and ShadowApplication
17
+ // records both sides — which is precisely the leak being guarded against.
18
+ @RunWith(RobolectricTestRunner::class)
19
+ class ServiceBindingTest {
20
+
21
+ private val app = RuntimeEnvironment.getApplication()
22
+ private val intent = Intent(app, Service::class.java)
23
+
24
+ private val connection =
25
+ object : ServiceConnection {
26
+ override fun onServiceConnected(name: ComponentName?, service: IBinder?) = Unit
27
+
28
+ override fun onServiceDisconnected(name: ComponentName?) = Unit
29
+ }
30
+
31
+ /** Both the auto-bind at construction and setup's bind reach the same object. */
32
+ @Test
33
+ fun bindingTwiceTakesOnlyOneBinding() {
34
+ val binding = ServiceBinding(app)
35
+
36
+ assertTrue(binding.bind(intent, connection))
37
+ assertTrue(binding.bind(intent, connection))
38
+
39
+ assertEquals(1, shadowOf(app).boundServiceConnections.size)
40
+
41
+ binding.unbind(connection)
42
+
43
+ assertTrue(shadowOf(app).boundServiceConnections.isEmpty())
44
+ assertEquals(1, shadowOf(app).unboundServiceConnections.size)
45
+ }
46
+
47
+ /** dispose() must not throw, and Android throws when unbinding a connection it never had. */
48
+ @Test
49
+ fun unbindWithoutBindIsANoOp() {
50
+ val binding = ServiceBinding(app)
51
+
52
+ binding.unbind(connection)
53
+
54
+ assertFalse(binding.isBound)
55
+ assertTrue(shadowOf(app).unboundServiceConnections.isEmpty())
56
+ }
57
+
58
+ /**
59
+ * Android registers the connection before it asks the ActivityManager, so a false return still
60
+ * leaves a binding to release. Treating false as "nothing bound" strands it permanently — the
61
+ * leak this class exists to prevent.
62
+ */
63
+ @Test
64
+ fun failedBindStillHoldsAConnectionToRelease() {
65
+ val binding = ServiceBinding(app)
66
+ shadowOf(app).declareActionUnbindable("unbindable")
67
+
68
+ assertFalse(binding.bind(Intent("unbindable"), connection))
69
+
70
+ assertTrue(binding.isBound)
71
+
72
+ binding.unbind(connection)
73
+
74
+ assertEquals(1, shadowOf(app).unboundServiceConnections.size)
75
+ }
76
+
77
+ @Test
78
+ fun unbindIsIdempotent() {
79
+ val binding = ServiceBinding(app)
80
+ binding.bind(intent, connection)
81
+
82
+ binding.unbind(connection)
83
+ binding.unbind(connection)
84
+
85
+ assertEquals(1, shadowOf(app).unboundServiceConnections.size)
86
+ }
87
+ }
@@ -1,12 +1,13 @@
1
1
  package com.audiobrowser
2
2
 
3
3
  import com.audiobrowser.util.artworkOf
4
-
5
4
  import com.margelo.nitro.audiobrowser.ArtworkRequestConfig
6
5
  import com.margelo.nitro.audiobrowser.ImageQueryParams
7
6
  import com.margelo.nitro.audiobrowser.ImageRowItem
8
7
  import com.margelo.nitro.audiobrowser.ImageSource
9
8
  import com.margelo.nitro.audiobrowser.MediaRequestConfig
9
+ import com.margelo.nitro.audiobrowser.NativeRouteEntry
10
+ import com.margelo.nitro.audiobrowser.ResolvedTrack
10
11
  import com.margelo.nitro.audiobrowser.Track
11
12
  import com.margelo.nitro.audiobrowser.TransformableRequestConfig
12
13
 
@@ -142,6 +143,56 @@ object TestFixtures {
142
143
  imageRow = null,
143
144
  )
144
145
 
146
+ /** A container [ResolvedTrack] — what a browse route hands back for a path. */
147
+ fun resolvedTrack(
148
+ url: String = "/container",
149
+ title: String = "Container",
150
+ children: Array<Track>? = null,
151
+ imageRow: Array<ImageRowItem>? = null,
152
+ ) =
153
+ ResolvedTrack(
154
+ url = url,
155
+ children = children,
156
+ carPlaySiriListButton = null,
157
+ id = null,
158
+ src = null,
159
+ artwork = null,
160
+ artworkSource = null,
161
+ request = null,
162
+ artworkCarPlayTinted = null,
163
+ title = title,
164
+ subtitle = null,
165
+ artist = null,
166
+ albumUrl = null,
167
+ album = null,
168
+ description = null,
169
+ genre = null,
170
+ duration = null,
171
+ style = null,
172
+ childrenStyle = null,
173
+ favorited = null,
174
+ groupTitle = null,
175
+ live = null,
176
+ imageRow = imageRow,
177
+ )
178
+
179
+ /**
180
+ * A route serving [browseStatic] verbatim. `browseStatic` is the only one of the three browse
181
+ * arms (callback > config > static) that needs neither the JNI bridge nor HTTP, so it is how a
182
+ * unit test gives [com.audiobrowser.browser.BrowserManager] page content to resolve.
183
+ */
184
+ fun staticRoute(path: String, browseStatic: ResolvedTrack) =
185
+ NativeRouteEntry(
186
+ path = path,
187
+ browseCallback = null,
188
+ browseConfig = null,
189
+ browseStatic = browseStatic,
190
+ searchCallback = null,
191
+ searchConfig = null,
192
+ media = null,
193
+ artwork = null,
194
+ )
195
+
145
196
  fun artworkConfig(
146
197
  path: String? = null,
147
198
  query: Map<String, String>? = null,
@@ -8,6 +8,8 @@ import org.junit.Assert.assertNull
8
8
  import org.junit.Assert.assertSame
9
9
  import org.junit.Before
10
10
  import org.junit.Test
11
+ import org.junit.runner.RunWith
12
+ import org.robolectric.RobolectricTestRunner
11
13
 
12
14
  /**
13
15
  * Tests the request/browse layer resolution + caching introduced for resolver thunks.
@@ -26,7 +28,11 @@ import org.junit.Test
26
28
  * bump, no in-flight cache) is identical for the static and resolver paths — `resolveLayer` only
27
29
  * differs in how it produces the `TransformableRequestConfig` — so the guard is fully covered here.
28
30
  * The resolver-await path is covered by the TS/web-stub tests and on iOS.
31
+ *
32
+ * Runs under Robolectric for [BrowserManager]'s `android.util.LruCache` fields: `clearContentCache`
33
+ * calls `evictAll()`, which a plain JVM test cannot execute.
29
34
  */
35
+ @RunWith(RobolectricTestRunner::class)
30
36
  class BrowserManagerLayerResolutionTest {
31
37
 
32
38
  private lateinit var browserManager: BrowserManager