@capgo/capacitor-updater 9.0.2 → 9.0.5

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.
@@ -159,7 +159,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
159
159
  static final int APPLICATION_EXIT_REASON_USER_REQUESTED = 10;
160
160
  static final int APPLICATION_EXIT_REASON_DEPENDENCY_DIED = 12;
161
161
 
162
- static final String PLUGIN_VERSION = "9.0.2";
162
+ // The release bump (capacitor-plugin-standard-version) rewrites only a private final String field named
163
+ // pluginVersion that holds a string literal, so the version lives in that form below. PLUGIN_VERSION
164
+ // exposes it to code that runs without a plugin instance.
165
+ private static final class VersionHolder {
166
+
167
+ private final String pluginVersion = "9.0.5";
168
+ }
169
+
170
+ static final String PLUGIN_VERSION = new VersionHolder().pluginVersion;
163
171
  // Set while a plugin instance (with its bridge) runs in this process. The headless update
164
172
  // check then leaves installing to that instance instead of swapping bundles under it.
165
173
  static final Object INSTANCE_LOADED_LOCK = new Object();
@@ -43,7 +43,14 @@ public class CryptoCipher {
43
43
  }
44
44
 
45
45
  public static byte[] decryptRSA(byte[] source, PublicKey publicKey)
46
- throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
46
+ throws
47
+ NoSuchPaddingException,
48
+ NoSuchAlgorithmException,
49
+ InvalidAlgorithmParameterException,
50
+ InvalidKeyException,
51
+ IllegalBlockSizeException,
52
+ BadPaddingException
53
+ {
47
54
  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
48
55
  cipher.init(Cipher.DECRYPT_MODE, publicKey);
49
56
  byte[] decryptedBytes = cipher.doFinal(source);
@@ -111,7 +118,8 @@ public class CryptoCipher {
111
118
  };
112
119
 
113
120
  private static PublicKey readPkcs1PublicKey(byte[] pkcs1Bytes)
114
- throws NoSuchAlgorithmException, InvalidKeySpecException, GeneralSecurityException {
121
+ throws NoSuchAlgorithmException, InvalidKeySpecException, GeneralSecurityException
122
+ {
115
123
  // convert the pkcs1 public key to an x509 favorable format
116
124
  byte[] keyBitString = createDEREncoding(BIT_STRING_TAG, joinPublic(NO_UNUSED_BITS, pkcs1Bytes));
117
125
  byte[] keyInfoValue = joinPublic(RSA_ALGORITHM_IDENTIFIER_SEQUENCE, keyBitString);
@@ -72,8 +72,11 @@ public class InternalUtils {
72
72
  }
73
73
 
74
74
  @SuppressWarnings("deprecation")
75
- private static PackageInfo getPackageInfoLegacy(PackageManager pm, String packageName, int flags)
76
- throws PackageManager.NameNotFoundException {
75
+ private static PackageInfo getPackageInfoLegacy(
76
+ PackageManager pm,
77
+ String packageName,
78
+ int flags
79
+ ) throws PackageManager.NameNotFoundException {
77
80
  return pm.getPackageInfo(packageName, flags);
78
81
  }
79
82
  }
@@ -95,7 +95,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
95
95
  deinit {
96
96
  implementation.shutdown()
97
97
  }
98
- private let pluginVersion: String = "9.0.2"
98
+ private let pluginVersion: String = "9.0.5"
99
99
  private let launchStartedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
100
100
  static let updateUrlDefault = "https://plugin.capgo.app/updates"
101
101
  static let statsUrlDefault = "https://plugin.capgo.app/stats"
@@ -26,7 +26,7 @@ final class BuiltinHashesTests: XCTestCase {
26
26
  override func tearDown() {
27
27
  try? FileManager.default.removeItem(at: builtinFolder)
28
28
  implementation = nil
29
- CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
29
+ CryptoCipher.setLogger(Logger.quietForTests())
30
30
  super.tearDown()
31
31
  }
32
32
 
@@ -19,12 +19,17 @@ private func channelSelfTestURL() throws -> URL {
19
19
 
20
20
  private func persistDefaultChannelTestUpdater(defaultChannel: String) -> ChannelRequestCapgoUpdater {
21
21
  let updater = ChannelRequestCapgoUpdater()
22
- updater.setLogger(Logger(withTag: "TestLogger"))
22
+ updater.setLogger(Logger.quietForTests())
23
23
  updater.defaultChannel = defaultChannel
24
24
  return updater
25
25
  }
26
26
 
27
27
  private class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
28
+ override init() {
29
+ super.init()
30
+ useQuietTestLogger()
31
+ }
32
+
28
33
  private(set) var notifiedEventNames: [String] = []
29
34
  private(set) var notifiedEventPayloads: [String: [String: Any]] = [:]
30
35
  private(set) var notifiedEventRetainValues: [String: Bool] = [:]
@@ -60,6 +65,11 @@ private class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
60
65
  }
61
66
 
62
67
  private final class RealSendReadyCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
68
+ override init() {
69
+ super.init()
70
+ useQuietTestLogger()
71
+ }
72
+
63
73
  private let eventLock = NSLock()
64
74
  private var _notifiedEventNames: [String] = []
65
75
  private var _notifiedEventPayloads: [String: [String: Any]] = [:]
@@ -801,7 +811,7 @@ class CapacitorUpdaterTests: XCTestCase {
801
811
  testPlugin.implementation = freshDownloadImplementation
802
812
  testPlugin.setAutoUpdateModeForTesting("onlyDownload")
803
813
  testPlugin.setUpdateUrlForTesting("https://example.com/channel")
804
- CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
814
+ CryptoCipher.setLogger(Logger.quietForTests())
805
815
 
806
816
  return (testPlugin, freshDownloadImplementation)
807
817
  }
@@ -826,7 +836,7 @@ class CapacitorUpdaterTests: XCTestCase {
826
836
  testPlugin.implementation = implementation
827
837
  testPlugin.setAutoUpdateModeForTesting("atBackground")
828
838
  testPlugin.setUpdateUrlForTesting("https://example.com/channel")
829
- CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
839
+ CryptoCipher.setLogger(Logger.quietForTests())
830
840
 
831
841
  return (testPlugin, implementation)
832
842
  }
@@ -843,7 +853,7 @@ class CapacitorUpdaterTests: XCTestCase {
843
853
  }
844
854
 
845
855
  private func makeDelayUpdateUtils() throws -> DelayUpdateUtils {
846
- let logger = Logger(withTag: "TestLogger")
856
+ let logger = Logger.quietForTests()
847
857
  let version = try CapgoSemanticVersion("1.0.0")
848
858
  return DelayUpdateUtils(currentVersionNative: version, logger: logger)
849
859
  }
@@ -1475,7 +1485,7 @@ class CapacitorUpdaterTests: XCTestCase {
1475
1485
 
1476
1486
  func testSetChannelRejectsNonSuccessStatusWithoutPersistingDefaultChannel() throws {
1477
1487
  let updater = ChannelRequestCapgoUpdater()
1478
- updater.setLogger(Logger(withTag: "TestLogger"))
1488
+ updater.setLogger(Logger.quietForTests())
1479
1489
  updater.channelUrl = channelSelfTestURLString
1480
1490
  updater.defaultChannel = "stable"
1481
1491
 
@@ -1507,7 +1517,7 @@ class CapacitorUpdaterTests: XCTestCase {
1507
1517
 
1508
1518
  func testUnsetChannelClearsOverrideWhenAllowed() {
1509
1519
  let updater = CapgoUpdater()
1510
- updater.setLogger(Logger(withTag: "TestLogger"))
1520
+ updater.setLogger(Logger.quietForTests())
1511
1521
  updater.defaultChannel = "beta"
1512
1522
 
1513
1523
  let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
@@ -1533,7 +1543,7 @@ class CapacitorUpdaterTests: XCTestCase {
1533
1543
 
1534
1544
  func testUnsetChannelRejectsWhenDisabledByConfig() {
1535
1545
  let updater = CapgoUpdater()
1536
- updater.setLogger(Logger(withTag: "TestLogger"))
1546
+ updater.setLogger(Logger.quietForTests())
1537
1547
  updater.defaultChannel = "beta"
1538
1548
 
1539
1549
  let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
@@ -1863,7 +1873,7 @@ class CapacitorUpdaterTests: XCTestCase {
1863
1873
 
1864
1874
  func testGetChannelPersistsServerChannelAsDefaultChannel() throws {
1865
1875
  let updater = ChannelRequestCapgoUpdater()
1866
- updater.setLogger(Logger(withTag: "TestLogger"))
1876
+ updater.setLogger(Logger.quietForTests())
1867
1877
  updater.channelUrl = channelSelfTestURLString
1868
1878
 
1869
1879
  let channelURL = try channelSelfTestURL()
@@ -1887,7 +1897,7 @@ class CapacitorUpdaterTests: XCTestCase {
1887
1897
 
1888
1898
  func testGetChannelDoesNotPersistBuiltinVersionNameAsDefaultChannel() {
1889
1899
  let updater = ChannelRequestCapgoUpdater()
1890
- updater.setLogger(Logger(withTag: "TestLogger"))
1900
+ updater.setLogger(Logger.quietForTests())
1891
1901
  updater.defaultChannel = "stable"
1892
1902
 
1893
1903
  let defaultsKey = "CapacitorUpdaterTests.defaultChannel.\(UUID().uuidString)"
@@ -1903,7 +1913,7 @@ class CapacitorUpdaterTests: XCTestCase {
1903
1913
 
1904
1914
  func testGetChannelDoesNotPersistDefaultStatusChannel() throws {
1905
1915
  let updater = ChannelRequestCapgoUpdater()
1906
- updater.setLogger(Logger(withTag: "TestLogger"))
1916
+ updater.setLogger(Logger.quietForTests())
1907
1917
  updater.channelUrl = channelSelfTestURLString
1908
1918
  updater.defaultChannel = ""
1909
1919
 
@@ -3424,7 +3434,7 @@ class CapacitorUpdaterTests: XCTestCase {
3424
3434
 
3425
3435
  private func makeSplashTimeoutPlugin(mode: String = "onLaunch") throws -> (SplashTimeoutCapacitorUpdaterPlugin, SplashTimeoutCapgoUpdater) {
3426
3436
  clearDelayStorage()
3427
- CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
3437
+ CryptoCipher.setLogger(Logger.quietForTests())
3428
3438
  let implementation = SplashTimeoutCapgoUpdater()
3429
3439
  implementation.currentBundleValue = makeOnlyDownloadBundle(id: "current-id", version: "1.0.0", status: .SUCCESS)
3430
3440
  implementation.latestResponse = makeOnlyDownloadLatest()
@@ -3686,10 +3696,13 @@ class CapacitorUpdaterTests: XCTestCase {
3686
3696
  _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3687
3697
  var installed = false
3688
3698
  let installDone = DispatchSemaphore(value: 0)
3689
- DispatchQueue.global().async {
3699
+ // A dedicated thread, not the shared global queue: earlier tests can leave its threads blocked in
3700
+ // app-ready waits, and on a loaded CI runner a queued job then may not start within the wait below.
3701
+ let installThread = Thread {
3690
3702
  installed = testPlugin.installNextForTesting()
3691
3703
  installDone.signal()
3692
3704
  }
3705
+ installThread.start()
3693
3706
  XCTAssertEqual(installDone.wait(timeout: .now() + 5), .success)
3694
3707
  XCTAssertTrue(installed)
3695
3708
  }
@@ -4106,6 +4119,12 @@ class CapacitorUpdaterTests: XCTestCase {
4106
4119
 
4107
4120
  // MARK: - Logger Tests
4108
4121
 
4122
+ /// Test plugins log errors only: info lines block the test thread when xcodebuild drains the output pipe late.
4123
+ func testTestPluginsLogErrorsOnly() {
4124
+ XCTAssertEqual(TestableCapacitorUpdaterPlugin().logger.level, .error)
4125
+ XCTAssertEqual(Logger.quietForTests().level, .error)
4126
+ }
4127
+
4109
4128
  func testLoggerInitialization() {
4110
4129
  let logger = Logger(withTag: "TestTag")
4111
4130
  XCTAssertNotNil(logger)
@@ -4394,7 +4413,7 @@ class CapacitorUpdaterTests: XCTestCase {
4394
4413
 
4395
4414
  func testDeleteRejectsPathTraversalOutsideBundleRoot() throws {
4396
4415
  let updater = CapgoUpdater()
4397
- updater.setLogger(Logger(withTag: "TestLogger"))
4416
+ updater.setLogger(Logger.quietForTests())
4398
4417
 
4399
4418
  let deleted = updater.delete(id: "../outside-target", removeInfo: true)
4400
4419
 
@@ -4403,7 +4422,7 @@ class CapacitorUpdaterTests: XCTestCase {
4403
4422
 
4404
4423
  func testDeleteRemovesLegitimateInSandboxBundle() throws {
4405
4424
  let updater = CapgoUpdater()
4406
- updater.setLogger(Logger(withTag: "TestLogger"))
4425
+ updater.setLogger(Logger.quietForTests())
4407
4426
  let bundleId = "sandbox-\(UUID().uuidString)"
4408
4427
  let bundleDir = try updater.getBundleDirectory(id: bundleId)
4409
4428
  try FileManager.default.createDirectory(at: bundleDir, withIntermediateDirectories: true)
@@ -4428,7 +4447,7 @@ class CapacitorUpdaterTests: XCTestCase {
4428
4447
 
4429
4448
  func testDeleteRejectsDotBundleId() throws {
4430
4449
  let updater = CapgoUpdater()
4431
- updater.setLogger(Logger(withTag: "TestLogger"))
4450
+ updater.setLogger(Logger.quietForTests())
4432
4451
 
4433
4452
  XCTAssertFalse(updater.delete(id: ".", removeInfo: true))
4434
4453
  }
@@ -6331,29 +6350,39 @@ class CapacitorUpdaterTests: XCTestCase {
6331
6350
 
6332
6351
  }
6333
6352
 
6353
+ /// A one-shot latch the test thread opens for download threads (or the reverse).
6354
+ /// Waiters poll a flag instead of blocking on a DispatchGroup, semaphore or condition. A blocking wait from a
6355
+ /// userInitiated download thread on a primitive created or entered by the Default-QoS test thread is a priority
6356
+ /// inversion for Xcode's Thread Performance Checker, which SwiftPM test runs inject. On CI, capturing and
6357
+ /// symbolicating each report stalled the process for 10-20s, so the coalescing tests' 5s waits timed out.
6334
6358
  private final class OnceSignal {
6359
+ private static let pollInterval: TimeInterval = 0.001
6335
6360
  private let lock = NSLock()
6336
- private let group = DispatchGroup()
6337
6361
  private var signaled = false
6338
6362
 
6339
- init() {
6340
- group.enter()
6363
+ private var isSignaled: Bool {
6364
+ lock.lock()
6365
+ defer { lock.unlock() }
6366
+ return signaled
6341
6367
  }
6342
6368
 
6343
6369
  @discardableResult
6344
6370
  func signal() -> Bool {
6345
6371
  lock.lock()
6346
- let shouldLeave = !signaled
6372
+ defer { lock.unlock() }
6373
+ let changed = !signaled
6347
6374
  signaled = true
6348
- lock.unlock()
6349
- if shouldLeave {
6350
- group.leave()
6351
- }
6352
- return shouldLeave
6375
+ return changed
6353
6376
  }
6354
6377
 
6355
6378
  func wait(timeout: DispatchTime) -> DispatchTimeoutResult {
6356
- group.wait(timeout: timeout)
6379
+ while !isSignaled {
6380
+ if DispatchTime.now() >= timeout {
6381
+ return isSignaled ? .success : .timedOut
6382
+ }
6383
+ Thread.sleep(forTimeInterval: Self.pollInterval)
6384
+ }
6385
+ return .success
6357
6386
  }
6358
6387
  }
6359
6388
 
@@ -47,6 +47,11 @@ final class ChecksumRequiredTests: XCTestCase {
47
47
  }
48
48
 
49
49
  private final class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
50
+ override init() {
51
+ super.init()
52
+ useQuietTestLogger()
53
+ }
54
+
50
55
  override func runBackgroundDownloadWork(_ work: @escaping () -> Void) {
51
56
  work()
52
57
  }
@@ -31,7 +31,7 @@ final class ListChannelsTests: XCTestCase {
31
31
  """.utf8)
32
32
  let requestResult = CapgoUpdater.RequestResult(data: responseData, response: response, error: nil, timedOut: false)
33
33
  let updater = ListChannelsRequestCapgoUpdater(requestResult: requestResult)
34
- updater.setLogger(Logger(withTag: "TestLogger"))
34
+ updater.setLogger(Logger.quietForTests())
35
35
  updater.channelUrl = channelURL.absoluteString
36
36
 
37
37
  let result = updater.listChannels()
@@ -55,7 +55,7 @@ final class ListChannelsTests: XCTestCase {
55
55
  """.utf8)
56
56
  let requestResult = CapgoUpdater.RequestResult(data: responseData, response: response, error: nil, timedOut: false)
57
57
  let updater = ListChannelsRequestCapgoUpdater(requestResult: requestResult)
58
- updater.setLogger(Logger(withTag: "TestLogger"))
58
+ updater.setLogger(Logger.quietForTests())
59
59
  updater.channelUrl = channelURL.absoluteString
60
60
 
61
61
  let result = updater.listChannels()
@@ -1,9 +1,13 @@
1
1
  import Foundation
2
- import Network
3
2
  import XCTest
4
3
  @testable import CapacitorUpdaterPlugin
5
4
 
6
5
  /// Minimal loopback HTTP/1.1 server so the real URLSession transport can be exercised without the network.
6
+ ///
7
+ /// It listens on a BSD socket that is bound and listening before `init` returns, so its port is known and the
8
+ /// kernel completes connections into the backlog even while this process is starved of CPU. An NWListener only
9
+ /// reports `.ready` asynchronously, and on loaded CI runners it was not ready within 5s, so a test could send its
10
+ /// request to port 0. `stop()` closes the socket synchronously, so later connections are refused at once.
7
11
  private final class LoopbackHTTPServer {
8
12
  struct Response {
9
13
  var status: Int
@@ -28,32 +32,56 @@ private final class LoopbackHTTPServer {
28
32
  var body: Data
29
33
  }
30
34
 
31
- private let listener: NWListener
32
- private let queue = DispatchQueue(label: "capgo.loopback-http")
35
+ enum SetupError: Error {
36
+ case socket(String, Int32)
37
+ }
38
+
39
+ private let listenSocket: Int32
40
+ private let port: UInt16
41
+ private let acceptQueue = DispatchQueue(label: "capgo.loopback-http.accept")
42
+ private let acceptSource: DispatchSourceRead
33
43
  private let lock = NSLock()
34
44
  private var handler: (RecordedRequest) -> Response = { _ in Response(status: 200, body: Data()) }
35
45
  private var recorded: [RecordedRequest] = []
36
46
  private var activeConnections = 0
47
+ private var stopped = false
48
+ private let listenerClosed = DispatchSemaphore(value: 0)
37
49
 
38
50
  init() throws {
39
- let parameters = NWParameters.tcp
40
- parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: .any)
41
- listener = try NWListener(using: parameters)
42
- listener.newConnectionHandler = { [weak self] connection in
43
- self?.accept(connection)
44
- }
45
- let ready = DispatchSemaphore(value: 0)
46
- listener.stateUpdateHandler = { state in
47
- if case .ready = state {
48
- ready.signal()
51
+ let socketFD = socket(AF_INET, SOCK_STREAM, 0)
52
+ guard socketFD >= 0 else {
53
+ throw SetupError.socket("socket", errno)
54
+ }
55
+ var reuse: Int32 = 1
56
+ setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuse, socklen_t(MemoryLayout<Int32>.size))
57
+ do {
58
+ port = try Self.bindLoopback(socketFD)
59
+ guard listen(socketFD, 64) == 0 else {
60
+ throw SetupError.socket("listen", errno)
49
61
  }
62
+ try Self.setNonBlocking(socketFD)
63
+ } catch {
64
+ close(socketFD)
65
+ throw error
66
+ }
67
+ listenSocket = socketFD
68
+ acceptSource = DispatchSource.makeReadSource(fileDescriptor: socketFD, queue: acceptQueue)
69
+ acceptSource.setEventHandler { [weak self] in
70
+ self?.acceptPendingConnections()
71
+ }
72
+ acceptSource.setCancelHandler { [listenerClosed] in
73
+ close(socketFD)
74
+ listenerClosed.signal()
50
75
  }
51
- listener.start(queue: queue)
52
- _ = ready.wait(timeout: .now() + 5)
76
+ acceptSource.resume()
77
+ }
78
+
79
+ deinit {
80
+ stop()
53
81
  }
54
82
 
55
83
  var baseURL: URL {
56
- return URL(string: "http://127.0.0.1:\(listener.port?.rawValue ?? 0)") ?? URL(fileURLWithPath: "/")
84
+ return URL(string: "http://127.0.0.1:\(port)") ?? URL(fileURLWithPath: "/")
57
85
  }
58
86
 
59
87
  var requests: [RecordedRequest] {
@@ -68,8 +96,20 @@ private final class LoopbackHTTPServer {
68
96
  lock.unlock()
69
97
  }
70
98
 
99
+ /// Stops accepting connections. The listening socket is closed before this returns, so a new connection to
100
+ /// the old port is refused instead of reaching a listener that is still shutting down.
71
101
  func stop() {
72
- listener.cancel()
102
+ lock.lock()
103
+ let wasStopped = stopped
104
+ stopped = true
105
+ lock.unlock()
106
+ guard !wasStopped else {
107
+ return
108
+ }
109
+ // The accept source's cancel handler closes the listening socket; wait for it so the port refuses
110
+ // new connections once stop() returns.
111
+ acceptSource.cancel()
112
+ listenerClosed.wait()
73
113
  }
74
114
 
75
115
  /// Waits until accepted connections finish or `timeout` elapses (stray URLSession tasks after invalidate).
@@ -86,55 +126,77 @@ private final class LoopbackHTTPServer {
86
126
  }
87
127
  }
88
128
 
89
- private func connectionOpened() {
90
- lock.lock()
91
- activeConnections += 1
92
- lock.unlock()
129
+ /// A loopback port with nothing listening on it: bind a socket to an ephemeral port, then close it.
130
+ /// Connecting to it is refused at once.
131
+ static func closedLoopbackPort() throws -> UInt16 {
132
+ let socketFD = socket(AF_INET, SOCK_STREAM, 0)
133
+ guard socketFD >= 0 else {
134
+ throw SetupError.socket("socket", errno)
135
+ }
136
+ defer { close(socketFD) }
137
+ return try bindLoopback(socketFD)
93
138
  }
94
139
 
95
- private func connectionClosed() {
96
- lock.lock()
97
- activeConnections = max(0, activeConnections - 1)
98
- lock.unlock()
140
+ private static func bindLoopback(_ socketFD: Int32) throws -> UInt16 {
141
+ var address = sockaddr_in()
142
+ address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
143
+ address.sin_family = sa_family_t(AF_INET)
144
+ address.sin_addr.s_addr = inet_addr("127.0.0.1")
145
+ address.sin_port = 0
146
+ var length = socklen_t(MemoryLayout<sockaddr_in>.size)
147
+ let bound = withUnsafeMutablePointer(to: &address) { pointer in
148
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketAddress in
149
+ bind(socketFD, socketAddress, length) == 0 && getsockname(socketFD, socketAddress, &length) == 0
150
+ }
151
+ }
152
+ guard bound else {
153
+ throw SetupError.socket("bind", errno)
154
+ }
155
+ return UInt16(bigEndian: address.sin_port)
99
156
  }
100
157
 
101
- private func accept(_ connection: NWConnection) {
102
- connectionOpened()
103
- connection.stateUpdateHandler = { [weak self] state in
104
- if case .cancelled = state {
105
- self?.connectionClosed()
106
- }
158
+ private static func setNonBlocking(_ socketFD: Int32) throws {
159
+ let flags = fcntl(socketFD, F_GETFL)
160
+ guard flags >= 0, fcntl(socketFD, F_SETFL, flags | O_NONBLOCK) == 0 else {
161
+ throw SetupError.socket("fcntl", errno)
107
162
  }
108
- connection.start(queue: queue)
109
- receive(on: connection, buffer: Data())
110
163
  }
111
164
 
112
- private func receive(on connection: NWConnection, buffer: Data) {
113
- connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, isComplete, error in
114
- guard let self else {
165
+ private func acceptPendingConnections() {
166
+ while true {
167
+ let connectionFD = accept(listenSocket, nil, nil)
168
+ guard connectionFD >= 0 else {
115
169
  return
116
170
  }
117
- var buffer = buffer
118
- if let data {
119
- buffer.append(data)
120
- }
121
- if let request = Self.parse(buffer) {
122
- self.lock.lock()
123
- self.recorded.append(request)
124
- let handler = self.handler
125
- self.lock.unlock()
126
- self.send(handler(request), on: connection)
127
- return
128
- }
129
- if isComplete || error != nil {
130
- connection.cancel()
131
- return
171
+ var noSigPipe: Int32 = 1
172
+ setsockopt(connectionFD, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout<Int32>.size))
173
+ // Accepted sockets inherit O_NONBLOCK from the listener on Darwin; the connection writes block.
174
+ let flags = fcntl(connectionFD, F_GETFL)
175
+ if flags >= 0 {
176
+ _ = fcntl(connectionFD, F_SETFL, flags & ~O_NONBLOCK)
132
177
  }
133
- self.receive(on: connection, buffer: buffer)
178
+ lock.lock()
179
+ activeConnections += 1
180
+ lock.unlock()
181
+ LoopbackConnection(socketFD: connectionFD, server: self).start()
134
182
  }
135
183
  }
136
184
 
137
- private static func parse(_ buffer: Data) -> RecordedRequest? {
185
+ fileprivate func connectionClosed() {
186
+ lock.lock()
187
+ activeConnections = max(0, activeConnections - 1)
188
+ lock.unlock()
189
+ }
190
+
191
+ fileprivate func handle(_ request: RecordedRequest) -> Response {
192
+ lock.lock()
193
+ recorded.append(request)
194
+ let handler = self.handler
195
+ lock.unlock()
196
+ return handler(request)
197
+ }
198
+
199
+ fileprivate static func parse(_ buffer: Data) -> RecordedRequest? {
138
200
  guard let headerEnd = buffer.range(of: Data("\r\n\r\n".utf8)),
139
201
  let head = String(data: buffer[buffer.startIndex..<headerEnd.lowerBound], encoding: .utf8) else {
140
202
  return nil
@@ -161,14 +223,60 @@ private final class LoopbackHTTPServer {
161
223
  body: Data(body.prefix(contentLength))
162
224
  )
163
225
  }
226
+ }
227
+
228
+ /// One accepted connection: reads a request, then writes the configured response on its own serial queue,
229
+ /// so a slow or paused response never delays another connection.
230
+ private final class LoopbackConnection {
231
+ private let socketFD: Int32
232
+ private let server: LoopbackHTTPServer
233
+ private let queue = DispatchQueue(label: "capgo.loopback-http.connection")
234
+ private var readSource: DispatchSourceRead?
235
+ private var buffer = Data()
236
+ private var answered = false
237
+ private var closed = false
238
+
239
+ init(socketFD: Int32, server: LoopbackHTTPServer) {
240
+ self.socketFD = socketFD
241
+ self.server = server
242
+ }
164
243
 
165
- /// Sends an HTTP response, optionally streaming the body in delayed chunks.
166
- private func send(_ response: Response, on connection: NWConnection) {
244
+ func start() {
245
+ let source = DispatchSource.makeReadSource(fileDescriptor: socketFD, queue: queue)
246
+ source.setEventHandler { [self] in
247
+ readAvailable()
248
+ }
249
+ readSource = source
250
+ source.resume()
251
+ }
252
+
253
+ private func readAvailable() {
254
+ var chunk = [UInt8](repeating: 0, count: 65536)
255
+ let count = read(socketFD, &chunk, chunk.count)
256
+ if count <= 0 {
257
+ // The peer closed the connection (or it failed); nothing more can be sent.
258
+ finish()
259
+ return
260
+ }
261
+ // One request per connection: bytes after it are ignored.
262
+ guard !answered else {
263
+ return
264
+ }
265
+ buffer.append(contentsOf: chunk[0..<count])
266
+ guard let request = LoopbackHTTPServer.parse(buffer) else {
267
+ return
268
+ }
269
+ answered = true
270
+ send(server.handle(request))
271
+ }
272
+
273
+ private func send(_ response: LoopbackHTTPServer.Response) {
167
274
  if response.dropConnection {
168
- connection.cancel()
275
+ finish()
169
276
  return
170
277
  }
171
- var head = "HTTP/1.1 \(response.status) Status\r\nContent-Length: \(response.body.count)\r\nConnection: close\r\n"
278
+ var head = "HTTP/1.1 \(response.status) Status\r\n"
279
+ head += "Content-Length: \(response.body.count)\r\nConnection: close\r\n"
172
280
  for (name, value) in response.headers {
173
281
  head += "\(name): \(value)\r\n"
174
282
  }
@@ -176,73 +284,91 @@ private final class LoopbackHTTPServer {
176
284
  let bodyData = response.truncateBodyAt.map { Data(response.body.prefix($0)) } ?? response.body
177
285
 
178
286
  if let chunkSize = response.chunkSize, chunkSize > 0, bodyData.count > chunkSize {
179
- connection.send(content: Data(head.utf8), completion: .contentProcessed { [weak self] _ in
180
- self?.sendChunks(
181
- of: bodyData, offset: 0, chunkSize: chunkSize, delay: response.chunkDelay,
182
- waitBeforeContinuingBody: response.waitBeforeContinuingBody,
183
- waitTimeout: response.waitBeforeContinuingBodyTimeout, on: connection
184
- )
185
- })
287
+ guard write(Data(head.utf8)) else {
288
+ finish()
289
+ return
290
+ }
291
+ sendChunks(of: bodyData, offset: 0, chunkSize: chunkSize, response: response)
186
292
  return
187
293
  }
188
-
189
294
  if response.truncateBodyAt != nil {
190
- // Send headers and body in separate writes so a truncated body is a real mid-stream drop,
295
+ // Headers and body go out in separate writes so a truncated body is a real mid-stream drop,
191
296
  // not one atomic read containing a short body with Content-Length still outstanding.
192
- let headerData = Data(head.utf8)
193
- connection.send(content: headerData, isComplete: false, completion: .contentProcessed { error in
194
- if error != nil {
195
- connection.cancel()
196
- return
197
- }
198
- connection.send(content: bodyData, isComplete: true, completion: .contentProcessed { _ in
199
- connection.cancel()
200
- })
201
- })
297
+ if write(Data(head.utf8)) {
298
+ _ = write(bodyData)
299
+ }
300
+ finish()
202
301
  return
203
302
  }
204
-
205
303
  var payload = Data(head.utf8)
206
304
  payload.append(bodyData)
207
- connection.send(content: payload, completion: .contentProcessed { _ in
208
- connection.cancel()
209
- })
305
+ _ = write(payload)
306
+ finish()
210
307
  }
211
308
 
212
- /// Recursively writes slices of `body` over `connection` separated by `delay`.
213
- private func sendChunks(
214
- of body: Data, offset: Int, chunkSize: Int, delay: TimeInterval,
215
- waitBeforeContinuingBody: (() -> Bool)?, waitTimeout: TimeInterval, on connection: NWConnection
216
- ) {
217
- guard offset < body.count else {
218
- connection.cancel()
309
+ /// Writes slices of `body` separated by the response's chunk delay, then closes the connection.
310
+ private func sendChunks(of body: Data, offset: Int, chunkSize: Int, response: LoopbackHTTPServer.Response) {
311
+ let end = min(offset + chunkSize, body.count)
312
+ guard write(body.subdata(in: offset..<end)), end < body.count else {
313
+ finish()
219
314
  return
220
315
  }
221
- let end = min(offset + chunkSize, body.count)
222
- let chunk = body.subdata(in: offset..<end)
223
- connection.send(content: chunk, completion: .contentProcessed { [weak self] _ in
224
- guard let self else {
225
- connection.cancel()
226
- return
316
+ queue.asyncAfter(deadline: .now() + response.chunkDelay) { [self] in
317
+ if let wait = response.waitBeforeContinuingBody {
318
+ let deadline = Date().addingTimeInterval(response.waitBeforeContinuingBodyTimeout)
319
+ while !wait() && Date() < deadline {
320
+ Thread.sleep(forTimeInterval: 0.005)
321
+ }
227
322
  }
228
- if end < body.count {
229
- self.queue.asyncAfter(deadline: .now() + delay) {
230
- if let wait = waitBeforeContinuingBody {
231
- let deadline = Date().addingTimeInterval(waitTimeout)
232
- while !wait() && Date() < deadline {
233
- Thread.sleep(forTimeInterval: 0.005)
234
- }
323
+ sendChunks(of: body, offset: end, chunkSize: chunkSize, response: response)
324
+ }
325
+ }
326
+
327
+ /// Blocking write of all of `data`; false once the peer has gone away.
328
+ private func write(_ data: Data) -> Bool {
329
+ guard !closed else {
330
+ return false
331
+ }
332
+ return data.withUnsafeBytes { raw -> Bool in
333
+ guard var pointer = raw.baseAddress else {
334
+ return true
335
+ }
336
+ var remaining = raw.count
337
+ while remaining > 0 {
338
+ let written = Darwin.write(socketFD, pointer, remaining)
339
+ if written < 0 {
340
+ if errno == EINTR {
341
+ continue
235
342
  }
236
- self.sendChunks(
237
- of: body, offset: end, chunkSize: chunkSize, delay: delay,
238
- waitBeforeContinuingBody: waitBeforeContinuingBody, waitTimeout: waitTimeout,
239
- on: connection
240
- )
343
+ return false
241
344
  }
242
- } else {
243
- connection.cancel()
345
+ remaining -= written
346
+ pointer += written
244
347
  }
245
- })
348
+ return true
349
+ }
350
+ }
351
+
352
+ private func finish() {
353
+ guard !closed else {
354
+ return
355
+ }
356
+ closed = true
357
+ // Close the socket from the read source's cancel handler, so the source is gone before the descriptor
358
+ // number can be reused by another connection.
359
+ let socketFD = self.socketFD
360
+ let server = self.server
361
+ guard let source = readSource else {
362
+ close(socketFD)
363
+ server.connectionClosed()
364
+ return
365
+ }
366
+ readSource = nil
367
+ source.setCancelHandler {
368
+ close(socketFD)
369
+ server.connectionClosed()
370
+ }
371
+ source.cancel()
246
372
  }
247
373
  }
248
374
 
@@ -793,10 +919,10 @@ final class NetworkTransportTests: XCTestCase {
793
919
  }
794
920
 
795
921
  func testPerformRequestWrapsTransportErrors() throws {
796
- let port = server.baseURL.port
797
- server.stop()
798
- server.drain(timeout: 0.5)
799
- var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(port ?? 1)/closed")))
922
+ // A port that was never listening refuses the connection at once. Reusing the test server's port after
923
+ // stop() could still reach the listener while it shuts down, and that connection never gets a reply.
924
+ let port = try LoopbackHTTPServer.closedLoopbackPort()
925
+ var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(port)/closed")))
800
926
  request.timeoutInterval = 5
801
927
 
802
928
  let result = makeUpdater().performRequest(request, label: "test")
@@ -99,7 +99,7 @@ final class PopulateDeltaCacheTests: XCTestCase {
99
99
  // CryptoCipher's logger is shared/static with no getter to snapshot the prior
100
100
  // value, so restore a normal (non-silent) default rather than leaving other
101
101
  // test suites silenced by this one.
102
- CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
102
+ CryptoCipher.setLogger(Logger.quietForTests())
103
103
  super.tearDown()
104
104
  }
105
105
 
@@ -94,6 +94,11 @@ final class SessionKeyRequiredTests: XCTestCase {
94
94
  }
95
95
 
96
96
  private final class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
97
+ override init() {
98
+ super.init()
99
+ useQuietTestLogger()
100
+ }
101
+
97
102
  override func runBackgroundDownloadWork(_ work: @escaping () -> Void) {
98
103
  work()
99
104
  }
@@ -0,0 +1,17 @@
1
+ @testable import CapacitorUpdaterPlugin
2
+
3
+ extension Logger {
4
+ /// Logger for tests: errors only. Info and debug lines are written synchronously to the test runner's
5
+ /// stdout/stderr, and xcodebuild drains that pipe. On a busy CI runner xcodebuild reads it late, the pipe
6
+ /// fills, and the test thread blocks inside a log call (a core-b test stalled 17 s and 27 s this way).
7
+ static func quietForTests(_ tag: String = "TestLogger") -> Logger {
8
+ Logger(withTag: tag, options: Logger.Options(level: .error))
9
+ }
10
+ }
11
+
12
+ extension CapacitorUpdaterPlugin {
13
+ /// Plugins built in tests have no bridge, so their default logger logs every info line. Keep it to errors.
14
+ func useQuietTestLogger() {
15
+ logger = Logger.quietForTests("✨ CapgoUpdater")
16
+ }
17
+ }
@@ -198,7 +198,7 @@ final class UpdateLifecycleTests: XCTestCase {
198
198
  plugin.implementation = updater
199
199
  plugin.setUpdateUrlForTesting(updateUrl.absoluteString)
200
200
  plugin.setDelayUpdateUtilsForTesting(
201
- DelayUpdateUtils(currentVersionNative: try CapgoSemanticVersion("1.0.0"), logger: Logger(withTag: "UpdateLifecycleTests"))
201
+ DelayUpdateUtils(currentVersionNative: try CapgoSemanticVersion("1.0.0"), logger: Logger.quietForTests("UpdateLifecycleTests"))
202
202
  )
203
203
  UserDefaults.standard.removeObject(forKey: delayPreferencesKey)
204
204
  UserDefaults.standard.removeObject(forKey: delayConditionModeKey)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-updater",
3
- "version": "9.0.2",
3
+ "version": "9.0.5",
4
4
  "license": "MPL-2.0",
5
5
  "description": "Live update for capacitor apps",
6
6
  "main": "dist/plugin.cjs.js",
@@ -76,7 +76,7 @@
76
76
  "clean": "rimraf ./dist",
77
77
  "watch": "tsc --watch",
78
78
  "prepublishOnly": "bun run build",
79
- "check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs && bun scripts/test-release-workflows.mjs && bun scripts/test-cli-crypto-output-guard.mjs && node scripts/test-builtin-hashes-hook.mjs && node scripts/check-ios-test-shards.mjs && node scripts/maestro/test-helpers.mjs && node scripts/maestro/test-smoke-sequence.mjs && bun scripts/maestro/test-deferred-flow.mjs && bun scripts/maestro/test-startup-update-flow.mjs && node scripts/maestro/test-local-plugin-manifest.mjs && node scripts/maestro/test-runner-attempt-cleanup.mjs",
79
+ "check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs && bun scripts/test-release-workflows.mjs && bun scripts/test-cli-crypto-output-guard.mjs && node scripts/test-builtin-hashes-hook.mjs && node scripts/check-ios-test-shards.mjs && node scripts/maestro/test-helpers.mjs && node scripts/maestro/test-smoke-sequence.mjs && bun scripts/maestro/test-deferred-flow.mjs && bun scripts/maestro/test-startup-update-flow.mjs && node scripts/maestro/test-local-plugin-manifest.mjs && node scripts/maestro/test-runner-attempt-cleanup.mjs && bash scripts/maestro/test-android-app-liveness.sh && bash scripts/maestro/test-android-scroll-gesture.sh",
80
80
  "check:cap9-deprecated": "bun scripts/check-cap9-deprecated.mjs",
81
81
  "changelog:ai": "node scripts/generate-ai-changelog.mjs",
82
82
  "example:install": "cd example-app && bun install --frozen-lockfile",