@capgo/capacitor-updater 8.53.1 → 8.54.1

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.
@@ -158,45 +158,27 @@ public struct CryptoCipher {
158
158
  }
159
159
 
160
160
  public static func calcChecksum(filePath: URL) -> String {
161
- let bufferSize = checksumBufferBytes()
162
- var sha256 = SHA256()
163
-
164
- let fileHandle: FileHandle
165
161
  do {
166
- fileHandle = try FileHandle(forReadingFrom: filePath)
162
+ return try calcChecksumOrThrow(filePath: filePath)
167
163
  } catch {
168
- logger.error("Cannot open file for checksum calculation")
164
+ logger.error("Cannot calculate checksum")
169
165
  logger.debug("Path: \(filePath.path), Error: \(error)")
170
166
  return ""
171
167
  }
168
+ }
172
169
 
173
- defer {
174
- do {
175
- try fileHandle.close()
176
- } catch {
177
- logger.error("Error closing file during checksum")
178
- logger.debug("Error: \(error)")
170
+ static func calcChecksumOrThrow(filePath: URL) throws -> String {
171
+ let file = try FileHandle(forReadingFrom: filePath)
172
+ defer { try? file.close() }
173
+ var sha256 = SHA256()
174
+ while true {
175
+ let count = try autoreleasepool {
176
+ let data = try file.read(upToCount: checksumBufferBytes()) ?? Data()
177
+ sha256.update(data: data)
178
+ return data.count
179
179
  }
180
+ if count == 0 { break }
180
181
  }
181
-
182
- while autoreleasepool(invoking: {
183
- let fileData: Data
184
- do {
185
- fileData = try fileHandle.read(upToCount: bufferSize) ?? Data()
186
- } catch {
187
- logger.error("Error reading file during checksum")
188
- logger.debug("Error: \(error)")
189
- return false
190
- }
191
-
192
- if fileData.count > 0 {
193
- sha256.update(data: fileData)
194
- return true // Continue
195
- } else {
196
- return false // End of file
197
- }
198
- }) {}
199
-
200
182
  return hexString(from: sha256)
201
183
  }
202
184
 
@@ -238,7 +220,45 @@ public struct CryptoCipher {
238
220
  logger.info("Encryption not set, no public key or session, ignored")
239
221
  return
240
222
  }
223
+ try DecryptionSession(publicKey: publicKey, sessionKey: sessionKey).decryptFile(filePath: filePath)
224
+ }
225
+
226
+ // Scoped to one manifest. Key material is immutable; CBC state stays local to each file.
227
+ final class DecryptionSession {
228
+ private let publicKey: String
229
+ private let sessionKey: String
230
+ private let lock = NSLock()
231
+ private var prepared: Result<AES128Key, Error>?
232
+
233
+ init(publicKey: String, sessionKey: String) {
234
+ self.publicKey = publicKey
235
+ self.sessionKey = sessionKey
236
+ }
237
+
238
+ private func key() throws -> AES128Key {
239
+ lock.lock()
240
+ defer { lock.unlock() }
241
+ if let prepared { return try prepared.get() }
242
+ let result = Result { try CryptoCipher.prepareDecryptionKey(publicKey: publicKey, sessionKey: sessionKey) }
243
+ prepared = result
244
+ return try result.get()
245
+ }
246
+
247
+ var isEncrypted: Bool {
248
+ !publicKey.isEmpty
249
+ }
250
+
251
+ func decryptFile(filePath: URL) throws {
252
+ guard isEncrypted else {
253
+ CryptoCipher.logger.info("Encryption not set, no public key or session, ignored")
254
+ return
255
+ }
256
+ try CryptoCipher.decryptPreparedFile(filePath: filePath, aesPrivateKey: key())
257
+ }
258
+ }
241
259
 
260
+ private static func prepareDecryptionKey(publicKey: String, sessionKey: String) throws -> AES128Key {
261
+ guard isValidSessionKey(sessionKey) else { throw CustomError.cannotDecode }
242
262
  // The bundle is encrypted from here on: an unusable key must fail, never leave it encrypted.
243
263
  if !publicKey.hasPrefix("-----BEGIN RSA PUBLIC KEY-----") {
244
264
  logger.error("The public key is not a valid RSA Public key")
@@ -284,8 +304,15 @@ public struct CryptoCipher {
284
304
  throw NSError(domain: "Invalid decrypted session key", code: 5, userInfo: nil)
285
305
  }
286
306
 
287
- let aesPrivateKey = AES128Key(iv: ivData, aes128Key: sessionKeyDataDecrypted, logger: logger)
307
+ return AES128Key(iv: ivData, aes128Key: sessionKeyDataDecrypted, logger: logger)
308
+ } catch {
309
+ logger.error("File decryption failed")
310
+ throw CustomError.cannotDecode
311
+ }
312
+ }
288
313
 
314
+ private static func decryptPreparedFile(filePath: URL, aesPrivateKey: AES128Key) throws {
315
+ do {
289
316
  let encryptedSize = (try FileManager.default.attributesOfItem(atPath: filePath.path)[.size] as? NSNumber)?.uint64Value ?? 0
290
317
  if encryptedSize == 0 {
291
318
  logger.error("Encrypted file data is empty")
@@ -298,7 +325,6 @@ public struct CryptoCipher {
298
325
  logger.error("Decrypted data is empty")
299
326
  throw NSError(domain: "Empty decrypted data", code: 7, userInfo: nil)
300
327
  }
301
-
302
328
  } catch {
303
329
  logger.error("File decryption failed")
304
330
  throw CustomError.cannotDecode
@@ -428,25 +428,6 @@ extension CustomError: LocalizedError {
428
428
  }
429
429
  }
430
430
 
431
- /// Thread-safe atomic counter for concurrent operations
432
- final class AtomicCounter {
433
- private var value: Int = 0
434
- private let lock = NSLock()
435
-
436
- func increment() -> Int {
437
- lock.lock()
438
- defer { lock.unlock() }
439
- value += 1
440
- return value
441
- }
442
-
443
- var current: Int {
444
- lock.lock()
445
- defer { lock.unlock() }
446
- return value
447
- }
448
- }
449
-
450
431
  /// Thread-safe atomic boolean for concurrent operations
451
432
  final class AtomicBool {
452
433
  private var _value: Bool
@@ -11,6 +11,20 @@ import Foundation
11
11
  final class RedirectPolicyDelegate: NSObject, URLSessionTaskDelegate {
12
12
  private let lock = NSLock()
13
13
  private var allowDowngrade = false
14
+ private var httpsOnlyEnabled = true
15
+ /// When true every redirect target must be https, whatever `allowHttpsToHttpRedirect` says.
16
+ var httpsOnly: Bool {
17
+ get {
18
+ lock.lock()
19
+ defer { lock.unlock() }
20
+ return httpsOnlyEnabled
21
+ }
22
+ set {
23
+ lock.lock()
24
+ httpsOnlyEnabled = newValue
25
+ lock.unlock()
26
+ }
27
+ }
14
28
  /// Called when a downgrade redirect is refused. Must not retain the updater strongly.
15
29
  var onBlockedRedirect: ((URL?, URL?) -> Void)?
16
30
 
@@ -42,6 +56,12 @@ final class RedirectPolicyDelegate: NSObject, URLSessionTaskDelegate {
42
56
  completionHandler: @escaping (URLRequest?) -> Void
43
57
  ) {
44
58
  let source = response.url ?? task.currentRequest?.url
59
+ if httpsOnly && request.url?.scheme?.lowercased() != "https" {
60
+ onBlockedRedirect?(source, request.url)
61
+ completionHandler(nil)
62
+ task.cancel()
63
+ return
64
+ }
45
65
  if !allowHttpsToHttpRedirect && Self.isHttpsToHttpDowngrade(from: source, to: request.url) {
46
66
  onBlockedRedirect?(source, request.url)
47
67
  completionHandler(nil)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-updater",
3
- "version": "8.53.1",
3
+ "version": "8.54.1",
4
4
  "license": "MPL-2.0",
5
5
  "description": "Live update for capacitor apps",
6
6
  "main": "dist/plugin.cjs.js",
@@ -14,7 +14,10 @@
14
14
  "dist/",
15
15
  "ios/Sources/",
16
16
  "CapgoCapacitorUpdater.podspec",
17
- "Package.swift"
17
+ "Package.swift",
18
+ "scripts/builtin-hashes-lib.mjs",
19
+ "scripts/capacitor-builtin-hashes-hook.mjs",
20
+ "scripts/resolve-real-path.mjs"
18
21
  ],
19
22
  "author": "Martin Donadieu <martin@capgo.app>",
20
23
  "repository": {
@@ -71,7 +74,7 @@
71
74
  "clean": "rimraf ./dist",
72
75
  "watch": "tsc --watch",
73
76
  "prepublishOnly": "bun run build",
74
- "check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs && bun scripts/test-cli-crypto-output-guard.mjs",
77
+ "check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs && bun scripts/test-cli-crypto-output-guard.mjs && node scripts/test-builtin-hashes-hook.mjs",
75
78
  "check:cap9-deprecated": "bun scripts/check-cap9-deprecated.mjs",
76
79
  "changelog:ai": "node scripts/generate-ai-changelog.mjs",
77
80
  "example:install": "cd example-app && bun install --frozen-lockfile",
@@ -82,7 +85,8 @@
82
85
  "native:contract:cli:ios": "./scripts/test-ios.sh -only-testing:CapacitorUpdaterPluginTests/CliCryptoFixtureTests",
83
86
  "native:contract:cli:android": "cd android && ./gradlew testDebugUnitTest --tests ee.forgr.capacitor_updater.CliCryptoFixtureTest && cd ..",
84
87
  "generate:rsa-contract": "bun scripts/generate-rsa-contract-fixtures.mjs",
85
- "generate:cli-crypto": "bun scripts/generate-cli-crypto-fixtures.mjs"
88
+ "generate:cli-crypto": "bun scripts/generate-cli-crypto-fixtures.mjs",
89
+ "capacitor:copy:after": "node scripts/capacitor-builtin-hashes-hook.mjs"
86
90
  },
87
91
  "devDependencies": {
88
92
  "@capacitor/android": "^8.5.0",
@@ -0,0 +1,148 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import process from 'node:process';
5
+ import { resolveRealPath } from './resolve-real-path.mjs';
6
+
7
+ export const BUILTIN_HASHES_FILE_NAME = 'ota-builtin-hashes.json';
8
+
9
+ /** Android apps should list web asset extensions in aapt noCompress so sized rows can use openFd length checks. */
10
+
11
+ export function sha256File(file) {
12
+ const hash = createHash('sha256');
13
+ const fd = fs.openSync(file, 'r');
14
+ try {
15
+ const chunk = Buffer.alloc(1024 * 1024);
16
+ let bytesRead;
17
+ while ((bytesRead = fs.readSync(fd, chunk, 0, chunk.length, null)) > 0) {
18
+ hash.update(chunk.subarray(0, bytesRead));
19
+ }
20
+ } finally {
21
+ fs.closeSync(fd);
22
+ }
23
+ return hash.digest('hex');
24
+ }
25
+
26
+ /**
27
+ * Walk `webDir` and collect relativePath -> sha256 hex. Skips the manifest output file,
28
+ * symlinks (does not follow), and non-regular files.
29
+ */
30
+ export function collectWebBundleHashes(webDir, { outputFileAbs = null } = {}) {
31
+ const base = fs.realpathSync(webDir);
32
+ const resolvedOutput = outputFileAbs ? resolveRealPath(outputFileAbs) : null;
33
+ const skipNames = new Set([BUILTIN_HASHES_FILE_NAME]);
34
+ const files = {};
35
+
36
+ function recordRegularFile(resolvedFull) {
37
+ if (resolvedOutput && resolvedFull === resolvedOutput) {
38
+ return;
39
+ }
40
+ if (!pathContains(base, resolvedFull)) {
41
+ return;
42
+ }
43
+ const rel = path.relative(base, resolvedFull).split(path.sep).join('/');
44
+ const stat = fs.statSync(resolvedFull);
45
+ files[rel] = { sha256: sha256File(resolvedFull), size: stat.size };
46
+ }
47
+
48
+ function visitName(name, realDir, ancestors) {
49
+ if (skipNames.has(name)) {
50
+ return;
51
+ }
52
+ const full = path.join(realDir, name);
53
+ let stat;
54
+ try {
55
+ stat = fs.lstatSync(full);
56
+ } catch {
57
+ return;
58
+ }
59
+ if (stat.isSymbolicLink()) {
60
+ return;
61
+ }
62
+ if (stat.isDirectory()) {
63
+ walk(full, ancestors);
64
+ return;
65
+ }
66
+ if (!stat.isFile()) {
67
+ return;
68
+ }
69
+ recordRegularFile(fs.realpathSync(full));
70
+ }
71
+
72
+ function walk(dir, ancestors = new Set()) {
73
+ const realDir = fs.realpathSync(dir);
74
+ if (ancestors.has(realDir)) {
75
+ return;
76
+ }
77
+ ancestors.add(realDir);
78
+ try {
79
+ for (const name of fs.readdirSync(realDir)) {
80
+ visitName(name, realDir, ancestors);
81
+ }
82
+ } finally {
83
+ ancestors.delete(realDir);
84
+ }
85
+ }
86
+
87
+ walk(base);
88
+ return files;
89
+ }
90
+
91
+ export function pathContains(parent, descendant) {
92
+ const relative = path.relative(parent, descendant);
93
+ if (relative === '') {
94
+ return true;
95
+ }
96
+ if (path.isAbsolute(relative) || relative === '..' || relative.startsWith(`..${path.sep}`)) {
97
+ return false;
98
+ }
99
+ return true;
100
+ }
101
+
102
+ export function resolveIosPublicDir(rootDir, extConfig = {}) {
103
+ const platformDir = extConfig.ios?.path ?? 'ios';
104
+ const platformDirAbs = path.resolve(rootDir, platformDir);
105
+ const nativeProjectDirAbs = path.join(platformDirAbs, 'App');
106
+ const nativeTargetDirAbs = path.join(platformDirAbs, 'App', 'App');
107
+ const pbxprojPath = path.join(platformDirAbs, 'App', 'App.xcodeproj', 'project.pbxproj');
108
+ try {
109
+ const pbxproj = fs.readFileSync(pbxprojPath, 'utf8');
110
+ const re = /path\s=\spublic[\s\S]+?sourceTree\s=\s([^;]+)/;
111
+ const match = pbxproj.match(re);
112
+ if (match?.[1] === 'SOURCE_ROOT') {
113
+ return path.join(nativeProjectDirAbs, 'public');
114
+ }
115
+ } catch {
116
+ // ignore
117
+ }
118
+ return path.join(nativeTargetDirAbs, 'public');
119
+ }
120
+
121
+ export function resolveAndroidPublicDir(rootDir, extConfig = {}) {
122
+ const platformDir = extConfig.android?.path ?? 'android';
123
+ const platformDirAbs = path.resolve(rootDir, platformDir);
124
+ return path.join(platformDirAbs, 'app', 'src', 'main', 'assets', 'public');
125
+ }
126
+
127
+ export function resolveNativePublicDir(rootDir, platformName, extConfig = {}) {
128
+ if (platformName === 'android') {
129
+ return resolveAndroidPublicDir(rootDir, extConfig);
130
+ }
131
+ if (platformName === 'ios') {
132
+ return resolveIosPublicDir(rootDir, extConfig);
133
+ }
134
+ return null;
135
+ }
136
+
137
+ export function writeBuiltinHashesManifest(outputFile, files) {
138
+ const payload = `${JSON.stringify({ files }, null, 2)}\n`;
139
+ fs.mkdirSync(path.dirname(outputFile), { recursive: true });
140
+ const tmpFile = `${outputFile}.${process.pid}.tmp`;
141
+ try {
142
+ fs.writeFileSync(tmpFile, payload, 'utf8');
143
+ fs.renameSync(tmpFile, outputFile);
144
+ } catch (err) {
145
+ fs.rmSync(tmpFile, { force: true });
146
+ throw err;
147
+ }
148
+ }
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Capacitor plugin hook: runs on capacitor:copy:after (covers standalone copy and sync, which invokes copy).
4
+ * Writes ota-builtin-hashes.json into the native web public folder for the active platform.
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import process from 'node:process';
9
+ import {
10
+ BUILTIN_HASHES_FILE_NAME,
11
+ collectWebBundleHashes,
12
+ resolveNativePublicDir,
13
+ writeBuiltinHashesManifest,
14
+ } from './builtin-hashes-lib.mjs';
15
+
16
+ function readExtConfig() {
17
+ const raw = process.env.CAPACITOR_CONFIG;
18
+ if (!raw) {
19
+ return {};
20
+ }
21
+ try {
22
+ return JSON.parse(raw);
23
+ } catch {
24
+ return {};
25
+ }
26
+ }
27
+
28
+ function main() {
29
+ try {
30
+ const platformName = process.env.CAPACITOR_PLATFORM_NAME;
31
+ if (!platformName || platformName === 'web') {
32
+ return;
33
+ }
34
+
35
+ const rootDir = process.env.CAPACITOR_ROOT_DIR;
36
+ if (!rootDir) {
37
+ return;
38
+ }
39
+
40
+ const extConfig = readExtConfig();
41
+ const nativePublicDir = resolveNativePublicDir(rootDir, platformName, extConfig);
42
+ if (!nativePublicDir) {
43
+ return;
44
+ }
45
+
46
+ if (!fs.existsSync(nativePublicDir)) {
47
+ return;
48
+ }
49
+
50
+ const outputFile = path.join(nativePublicDir, BUILTIN_HASHES_FILE_NAME);
51
+ fs.rmSync(outputFile, { force: true });
52
+ try {
53
+ const files = collectWebBundleHashes(nativePublicDir, { outputFileAbs: outputFile });
54
+ writeBuiltinHashesManifest(outputFile, files);
55
+ } catch (err) {
56
+ const message = err instanceof Error ? err.message : String(err);
57
+ console.warn(`[capgo] ${BUILTIN_HASHES_FILE_NAME} not generated: ${message}`);
58
+ }
59
+ } catch (err) {
60
+ const message = err instanceof Error ? err.message : String(err);
61
+ console.warn(`[capgo] ${BUILTIN_HASHES_FILE_NAME} hook failed: ${message}`);
62
+ }
63
+ }
64
+
65
+ main();
@@ -0,0 +1,25 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /** Resolve symlinks; walk up to the nearest existing ancestor when target does not exist yet. */
5
+ export function resolveRealPath(target) {
6
+ const normalized = path.resolve(target);
7
+ const suffix = [];
8
+ let cursor = normalized;
9
+ while (true) {
10
+ try {
11
+ const real = fs.realpathSync(cursor);
12
+ return suffix.length === 0 ? real : path.join(real, ...suffix);
13
+ } catch (err) {
14
+ if (err?.code !== 'ENOENT') {
15
+ throw err;
16
+ }
17
+ suffix.unshift(path.basename(cursor));
18
+ const parent = path.dirname(cursor);
19
+ if (parent === cursor) {
20
+ throw err;
21
+ }
22
+ cursor = parent;
23
+ }
24
+ }
25
+ }