native-update-capacitor 0.0.0-stage → 4.4.0

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 (140) hide show
  1. package/AI-INTEGRATION-GUIDE.md +578 -0
  2. package/LICENSE +25 -0
  3. package/NativeUpdate.podspec +19 -0
  4. package/README.md +574 -2
  5. package/android/build.gradle +125 -0
  6. package/android/consumer-rules.pro +9 -0
  7. package/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  8. package/android/gradle.properties +17 -0
  9. package/android/manifest-additions.xml +28 -0
  10. package/android/proguard-rules.pro +26 -0
  11. package/android/settings.gradle +2 -0
  12. package/android/src/main/AndroidManifest.xml +13 -0
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/AppReviewPlugin.kt +159 -0
  14. package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +314 -0
  15. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +406 -0
  16. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +48 -0
  17. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +343 -0
  18. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +236 -0
  19. package/android/src/main/java/com/aoneahsan/nativeupdate/JsonOptional.kt +26 -0
  20. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +1249 -0
  21. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +404 -0
  22. package/android/src/main/java/com/aoneahsan/nativeupdate/NotificationActionReceiver.kt +107 -0
  23. package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +240 -0
  24. package/android/variables.gradle +5 -0
  25. package/cli/commands/backend-create.js +623 -0
  26. package/cli/commands/bundle-create.js +145 -0
  27. package/cli/commands/bundle-sign.js +64 -0
  28. package/cli/commands/bundle-verify.js +58 -0
  29. package/cli/commands/flutter-patch.js +107 -0
  30. package/cli/commands/init.js +146 -0
  31. package/cli/commands/keys-generate.js +58 -0
  32. package/cli/commands/monitor.js +89 -0
  33. package/cli/commands/remote-shared.js +264 -0
  34. package/cli/commands/remote.js +634 -0
  35. package/cli/commands/server-start.js +96 -0
  36. package/cli/index.js +625 -0
  37. package/cli/package.json +21 -0
  38. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  39. package/dist/esm/app-review/app-review-manager.js +194 -0
  40. package/dist/esm/app-review/index.d.ts +5 -0
  41. package/dist/esm/app-review/index.js +5 -0
  42. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  43. package/dist/esm/app-review/platform-review-handler.js +137 -0
  44. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  45. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  46. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  47. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  48. package/dist/esm/app-review/types.d.ts +41 -0
  49. package/dist/esm/app-review/types.js +1 -0
  50. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  51. package/dist/esm/app-update/app-update-checker.js +227 -0
  52. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  53. package/dist/esm/app-update/app-update-installer.js +134 -0
  54. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  55. package/dist/esm/app-update/app-update-manager.js +198 -0
  56. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  57. package/dist/esm/app-update/app-update-notifier.js +99 -0
  58. package/dist/esm/app-update/index.d.ts +6 -0
  59. package/dist/esm/app-update/index.js +6 -0
  60. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  61. package/dist/esm/app-update/platform-app-update.js +138 -0
  62. package/dist/esm/app-update/types.d.ts +58 -0
  63. package/dist/esm/app-update/types.js +11 -0
  64. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  65. package/dist/esm/background-update/background-scheduler.js +332 -0
  66. package/dist/esm/background-update/index.d.ts +3 -0
  67. package/dist/esm/background-update/index.js +2 -0
  68. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  69. package/dist/esm/background-update/notification-manager.js +88 -0
  70. package/dist/esm/config/support.d.ts +9 -0
  71. package/dist/esm/config/support.js +9 -0
  72. package/dist/esm/core/analytics.d.ts +83 -0
  73. package/dist/esm/core/analytics.js +151 -0
  74. package/dist/esm/core/cache-manager.d.ts +72 -0
  75. package/dist/esm/core/cache-manager.js +274 -0
  76. package/dist/esm/core/config.d.ts +69 -0
  77. package/dist/esm/core/config.js +107 -0
  78. package/dist/esm/core/errors.d.ts +56 -0
  79. package/dist/esm/core/errors.js +85 -0
  80. package/dist/esm/core/event-emitter.d.ts +30 -0
  81. package/dist/esm/core/event-emitter.js +80 -0
  82. package/dist/esm/core/logger.d.ts +21 -0
  83. package/dist/esm/core/logger.js +108 -0
  84. package/dist/esm/core/performance.d.ts +53 -0
  85. package/dist/esm/core/performance.js +153 -0
  86. package/dist/esm/core/plugin-manager.d.ts +88 -0
  87. package/dist/esm/core/plugin-manager.js +224 -0
  88. package/dist/esm/core/security.d.ts +123 -0
  89. package/dist/esm/core/security.js +361 -0
  90. package/dist/esm/core/update-check.d.ts +121 -0
  91. package/dist/esm/core/update-check.js +127 -0
  92. package/dist/esm/definitions.d.ts +872 -0
  93. package/dist/esm/definitions.js +104 -0
  94. package/dist/esm/index.d.ts +14 -0
  95. package/dist/esm/index.js +18 -0
  96. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  97. package/dist/esm/live-update/bundle-manager.js +344 -0
  98. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  99. package/dist/esm/live-update/certificate-pinning.js +77 -0
  100. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  101. package/dist/esm/live-update/delta-processor.js +257 -0
  102. package/dist/esm/live-update/download-manager.d.ts +106 -0
  103. package/dist/esm/live-update/download-manager.js +412 -0
  104. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  105. package/dist/esm/live-update/rollout-checker.js +304 -0
  106. package/dist/esm/live-update/update-manager.d.ts +63 -0
  107. package/dist/esm/live-update/update-manager.js +321 -0
  108. package/dist/esm/live-update/version-manager.d.ts +93 -0
  109. package/dist/esm/live-update/version-manager.js +390 -0
  110. package/dist/esm/plugin.d.ts +3 -0
  111. package/dist/esm/plugin.js +848 -0
  112. package/dist/esm/security/crypto.d.ts +88 -0
  113. package/dist/esm/security/crypto.js +228 -0
  114. package/dist/esm/security/validator.d.ts +60 -0
  115. package/dist/esm/security/validator.js +142 -0
  116. package/dist/esm/types/app-identity.d.ts +36 -0
  117. package/dist/esm/types/app-identity.js +1 -0
  118. package/dist/esm/types/rollout.d.ts +91 -0
  119. package/dist/esm/types/rollout.js +25 -0
  120. package/dist/esm/web.d.ts +130 -0
  121. package/dist/esm/web.js +981 -0
  122. package/dist/plugin.cjs +1 -0
  123. package/dist/plugin.esm.js +1 -0
  124. package/dist/plugin.js +2 -0
  125. package/docs/CHANGELOG.md +1016 -0
  126. package/docs/KNOWN_LIMITATIONS.md +240 -0
  127. package/docs/MIGRATION.md +391 -0
  128. package/docs/protocol/CLIENT-PROTOCOL.md +199 -0
  129. package/docs/server-requirements.md +211 -0
  130. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  131. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  133. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  134. package/ios/Plugin/Info.plist +43 -0
  135. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  136. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  137. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  138. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  139. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  140. package/package.json +133 -4
@@ -0,0 +1,145 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import crypto from 'crypto';
5
+ import { ZipArchive } from 'archiver';
6
+ import { createWriteStream, createReadStream } from 'fs';
7
+ import { fileURLToPath } from 'url';
8
+ import { dirname, join } from 'path';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = dirname(__filename);
12
+
13
+ const NEVER_BUNDLE = ['node_modules', '.git', '.env', '.env.local', '.env.production'];
14
+
15
+ export async function createBundle(webDir, options) {
16
+ console.log(chalk.blue('🔨 Creating update bundle...'));
17
+
18
+ try {
19
+ // Validate input directory
20
+ const stats = await fs.stat(webDir);
21
+ if (!stats.isDirectory()) {
22
+ throw new Error(`${webDir} is not a directory`);
23
+ }
24
+
25
+ // Check for index.html
26
+ const indexPath = path.join(webDir, 'index.html');
27
+ try {
28
+ await fs.access(indexPath);
29
+ } catch {
30
+ throw new Error(`No index.html found in ${webDir}. Is this a valid web build directory?`);
31
+ }
32
+
33
+ // Refuse to bundle a project root by mistake — `node_modules`, `.git`,
34
+ // and `.env*` should never end up in an OTA bundle. Catches the common
35
+ // mistake of pointing at the project root instead of `dist/` or `www/`.
36
+ const entries = await fs.readdir(webDir);
37
+ const dangerous = entries.filter((e) => NEVER_BUNDLE.includes(e));
38
+ if (dangerous.length > 0) {
39
+ throw new Error(
40
+ `Refusing to bundle: ${webDir} contains ${dangerous.join(', ')}. ` +
41
+ `Point at your built web output (e.g. ./dist or ./www), not the project root.`
42
+ );
43
+ }
44
+
45
+ // Create output directory
46
+ const outputDir = path.resolve(options.output);
47
+ await fs.mkdir(outputDir, { recursive: true });
48
+
49
+ // Get version
50
+ let version = options.version;
51
+ if (!version) {
52
+ try {
53
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
54
+ const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));
55
+ version = packageJson.version;
56
+ } catch {
57
+ version = new Date().toISOString().split('T')[0].replace(/-/g, '.');
58
+ }
59
+ }
60
+
61
+ // Parse --metadata separately so we can give a clearer error than
62
+ // a bare "Unexpected token" if the user passes invalid JSON.
63
+ let extraMetadata = {};
64
+ if (options.metadata) {
65
+ try {
66
+ extraMetadata = JSON.parse(options.metadata);
67
+ } catch (e) {
68
+ throw new Error(`Invalid JSON in --metadata: ${e.message}`);
69
+ }
70
+ }
71
+
72
+ // Create bundle metadata
73
+ const metadata = {
74
+ version,
75
+ channel: options.channel,
76
+ created: new Date().toISOString(),
77
+ platform: 'web',
78
+ ...extraMetadata,
79
+ };
80
+
81
+ const bundleId = `${version}-${Date.now()}`;
82
+ const bundleFileName = `bundle-${bundleId}.zip`;
83
+ const bundlePath = path.join(outputDir, bundleFileName);
84
+ const metadataPath = path.join(outputDir, `bundle-${bundleId}.json`);
85
+
86
+ console.log(chalk.gray(` Version: ${version}`));
87
+ console.log(chalk.gray(` Channel: ${options.channel}`));
88
+ console.log(chalk.gray(` Output: ${bundlePath}`));
89
+
90
+ // Create zip archive
91
+ const output = createWriteStream(bundlePath);
92
+ const archive = new ZipArchive({
93
+ zlib: { level: 9 }
94
+ });
95
+
96
+ const archivePromise = new Promise((resolve, reject) => {
97
+ output.on('close', resolve);
98
+ archive.on('error', reject);
99
+ });
100
+
101
+ archive.pipe(output);
102
+
103
+ // Add all files from web directory
104
+ archive.directory(webDir, false);
105
+
106
+ await archive.finalize();
107
+ await archivePromise;
108
+
109
+ // Stream the bundle through the SHA-256 hasher so a 100MB+ bundle
110
+ // doesn't get slurped into RAM all at once. Size comes from fs.stat.
111
+ const bundleStat = await fs.stat(bundlePath);
112
+ const checksum = await new Promise((resolve, reject) => {
113
+ const hash = crypto.createHash('sha256');
114
+ createReadStream(bundlePath)
115
+ .on('data', (chunk) => hash.update(chunk))
116
+ .on('end', () => resolve(hash.digest('hex')))
117
+ .on('error', reject);
118
+ });
119
+
120
+ // Update metadata with file info
121
+ metadata.checksum = checksum;
122
+ metadata.size = bundleStat.size;
123
+ metadata.filename = bundleFileName;
124
+
125
+ // Save metadata
126
+ await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2));
127
+
128
+ console.log(chalk.green('✅ Bundle created successfully!'));
129
+ console.log('');
130
+ console.log(chalk.bold('Bundle Details:'));
131
+ console.log(chalk.gray(` File: ${bundlePath}`));
132
+ console.log(chalk.gray(` Size: ${(bundleStat.size / 1024 / 1024).toFixed(2)} MB`));
133
+ console.log(chalk.gray(` Checksum: ${checksum}`));
134
+ console.log(chalk.gray(` Metadata: ${metadataPath}`));
135
+ console.log('');
136
+ console.log(chalk.yellow('Next steps:'));
137
+ console.log(chalk.gray(' 1. Sign the bundle:'));
138
+ console.log(chalk.cyan(` npx native-update bundle sign ${bundlePath} --key ./keys/private.pem`));
139
+ console.log(chalk.gray(' 2. Upload to your update server'));
140
+
141
+ } catch (error) {
142
+ console.error(chalk.red('❌ Failed to create bundle:'), error.message);
143
+ process.exit(1);
144
+ }
145
+ }
@@ -0,0 +1,64 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import crypto from 'crypto';
5
+
6
+ export async function signBundle(bundlePath, options) {
7
+ console.log(chalk.blue('🔏 Signing bundle...'));
8
+
9
+ try {
10
+ // Validate bundle exists
11
+ await fs.access(bundlePath);
12
+
13
+ // Read private key
14
+ const privateKeyPem = await fs.readFile(options.key, 'utf-8');
15
+
16
+ // Read bundle
17
+ const bundleData = await fs.readFile(bundlePath);
18
+
19
+ // Create signature
20
+ const sign = crypto.createSign('RSA-SHA256');
21
+ sign.update(bundleData);
22
+ const signature = sign.sign(privateKeyPem, 'base64');
23
+
24
+ // Determine output path
25
+ const outputPath = options.output || bundlePath.replace('.zip', '.signed.zip');
26
+
27
+ // Create signed bundle metadata
28
+ const signedMetadata = {
29
+ originalBundle: path.basename(bundlePath),
30
+ // The bytes this signature actually covers. `deploy` refuses to upload a
31
+ // signature whose checksum does not match the bundle being sent — without
32
+ // it, a stale .sig ships happily and every device rejects the release
33
+ // with nothing visible server-side. See ISSUE-08.
34
+ bundleSha256: crypto.createHash('sha256').update(bundleData).digest('hex'),
35
+ signature,
36
+ signedAt: new Date().toISOString(),
37
+ algorithm: 'RSA-SHA256'
38
+ };
39
+
40
+ // Save signature file
41
+ const sigPath = outputPath.replace('.zip', '.sig');
42
+ await fs.writeFile(sigPath, JSON.stringify(signedMetadata, null, 2));
43
+
44
+ // Copy bundle to output path if different
45
+ if (outputPath !== bundlePath) {
46
+ await fs.copyFile(bundlePath, outputPath);
47
+ }
48
+
49
+ console.log(chalk.green('✅ Bundle signed successfully!'));
50
+ console.log('');
51
+ console.log(chalk.bold('Signed Bundle:'));
52
+ console.log(chalk.gray(` Bundle: ${outputPath}`));
53
+ console.log(chalk.gray(` Signature: ${sigPath}`));
54
+ console.log('');
55
+ console.log(chalk.yellow('Next steps:'));
56
+ console.log(chalk.gray(` npx native-update deploy ${outputPath} --app <your-app> --wait`));
57
+ console.log(chalk.gray(' The .sig beside the bundle is picked up automatically and'));
58
+ console.log(chalk.gray(' uploaded with it, so requireSignature: true is satisfied.'));
59
+
60
+ } catch (error) {
61
+ console.error(chalk.red('❌ Failed to sign bundle:'), error.message);
62
+ process.exit(1);
63
+ }
64
+ }
@@ -0,0 +1,58 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import crypto from 'crypto';
5
+
6
+ export async function verifyBundle(bundlePath, options) {
7
+ console.log(chalk.blue('🔍 Verifying bundle signature...'));
8
+
9
+ try {
10
+ // Check if bundle exists
11
+ await fs.access(bundlePath);
12
+
13
+ // Look for signature file
14
+ const sigPath = bundlePath.replace('.zip', '.sig');
15
+ let signatureData;
16
+
17
+ try {
18
+ const sigContent = await fs.readFile(sigPath, 'utf-8');
19
+ signatureData = JSON.parse(sigContent);
20
+ } catch {
21
+ throw new Error(`No signature file found at ${sigPath}`);
22
+ }
23
+ if (signatureData.algorithm !== 'RSA-SHA256' || typeof signatureData.signature !== 'string') {
24
+ throw new Error('Signature metadata must use RSA-SHA256');
25
+ }
26
+
27
+ // Read public key
28
+ const publicKeyPem = await fs.readFile(options.key, 'utf-8');
29
+
30
+ // Read bundle
31
+ const bundleData = await fs.readFile(bundlePath);
32
+
33
+ // Verify signature
34
+ const verify = crypto.createVerify('RSA-SHA256');
35
+ verify.update(bundleData);
36
+ const isValid = verify.verify(publicKeyPem, signatureData.signature, 'base64');
37
+
38
+ if (isValid) {
39
+ console.log(chalk.green('✅ Bundle signature is VALID'));
40
+ console.log('');
41
+ console.log(chalk.bold('Bundle Details:'));
42
+ console.log(chalk.gray(` Signed at: ${signatureData.signedAt}`));
43
+ console.log(chalk.gray(` Algorithm: ${signatureData.algorithm}`));
44
+ console.log('');
45
+ console.log(chalk.green('This bundle can be trusted and deployed safely.'));
46
+ } else {
47
+ console.log(chalk.red('❌ Bundle signature is INVALID'));
48
+ console.log('');
49
+ console.log(chalk.red('WARNING: This bundle may have been tampered with!'));
50
+ console.log(chalk.red('Do not deploy this bundle.'));
51
+ process.exit(1);
52
+ }
53
+
54
+ } catch (error) {
55
+ console.error(chalk.red('❌ Failed to verify bundle:'), error.message);
56
+ process.exit(1);
57
+ }
58
+ }
@@ -0,0 +1,107 @@
1
+ import chalk from 'chalk';
2
+ import crypto from 'crypto';
3
+ import fs from 'fs/promises';
4
+ import path from 'path';
5
+ import zlib from 'zlib';
6
+ import { ZipArchive } from 'archiver';
7
+ import { createWriteStream } from 'fs';
8
+
9
+ /**
10
+ * Reads the entries of a ZIP (an APK) from its central directory. Handles stored and deflated entries, which is
11
+ * everything the Android build tools write. Returns a Map of name -> { read(): Buffer }.
12
+ */
13
+ async function readZip(filePath) {
14
+ const buf = await fs.readFile(filePath);
15
+ const minEnd = Math.max(0, buf.length - 0xffff - 22);
16
+ let end = -1;
17
+ for (let i = buf.length - 22; i >= minEnd; i--) {
18
+ if (buf.readUInt32LE(i) === 0x06054b50) {
19
+ end = i;
20
+ break;
21
+ }
22
+ }
23
+ if (end < 0) throw new Error(`${filePath} is not a ZIP/APK file`);
24
+ const count = buf.readUInt16LE(end + 10);
25
+ let offset = buf.readUInt32LE(end + 16);
26
+ const entries = new Map();
27
+ for (let i = 0; i < count; i++) {
28
+ if (buf.readUInt32LE(offset) !== 0x02014b50) throw new Error('Corrupt ZIP central directory');
29
+ const method = buf.readUInt16LE(offset + 10);
30
+ const compressed = buf.readUInt32LE(offset + 20);
31
+ const nameLength = buf.readUInt16LE(offset + 28);
32
+ const extraLength = buf.readUInt16LE(offset + 30);
33
+ const commentLength = buf.readUInt16LE(offset + 32);
34
+ const local = buf.readUInt32LE(offset + 42);
35
+ const name = buf.toString('utf8', offset + 46, offset + 46 + nameLength);
36
+ entries.set(name, {
37
+ read() {
38
+ const localName = buf.readUInt16LE(local + 26);
39
+ const localExtra = buf.readUInt16LE(local + 28);
40
+ const start = local + 30 + localName + localExtra;
41
+ const data = buf.subarray(start, start + compressed);
42
+ if (method === 0) return Buffer.from(data);
43
+ if (method === 8) return zlib.inflateRawSync(data);
44
+ throw new Error(`Unsupported ZIP compression method ${method} for ${name}`);
45
+ },
46
+ });
47
+ offset += 46 + nameLength + extraLength + commentLength;
48
+ }
49
+ return entries;
50
+ }
51
+
52
+ const sha256 = (data) => crypto.createHash('sha256').update(data).digest('hex');
53
+
54
+ /**
55
+ * `native-update bundle flutter-patch <apk>`: turns a Flutter RELEASE APK into a Dart code update.
56
+ *
57
+ * The patch holds lib/<abi>/libapp.so for every architecture in the APK, plus the files of --assets. Next to it,
58
+ * <out>.runtime-keys lists the SHA-256 of each libflutter.so: a device is offered the patch only when its own engine
59
+ * is one of them, because compiled Dart code runs only on the engine it was built against. Build the patch APK from
60
+ * the same Flutter version and the same native plugins as the app build it updates.
61
+ */
62
+ export async function createFlutterPatch(apkPath, options) {
63
+ const entries = await readZip(apkPath);
64
+ const abis = [...entries.keys()]
65
+ .map((name) => /^lib\/([^/]+)\/libapp\.so$/.exec(name)?.[1])
66
+ .filter(Boolean);
67
+ if (abis.length === 0) {
68
+ throw new Error(
69
+ `${apkPath} has no lib/<abi>/libapp.so. Build it with \`flutter build apk --release\` (debug builds carry no compiled Dart code).`
70
+ );
71
+ }
72
+
73
+ const out = path.resolve(options.output ?? 'flutter-patch.zip');
74
+ const stage = await fs.mkdtemp(path.join(path.dirname(out), '.flutter-patch-'));
75
+ const keys = [];
76
+ try {
77
+ for (const abi of abis) {
78
+ const engine = entries.get(`lib/${abi}/libflutter.so`);
79
+ if (!engine) throw new Error(`${apkPath} has libapp.so for ${abi} but no libflutter.so`);
80
+ keys.push({ abi, key: sha256(engine.read()) });
81
+ await fs.mkdir(path.join(stage, 'lib', abi), { recursive: true });
82
+ await fs.writeFile(path.join(stage, 'lib', abi, 'libapp.so'), entries.get(`lib/${abi}/libapp.so`).read());
83
+ }
84
+ if (options.assets) {
85
+ await fs.cp(path.resolve(options.assets), stage, { recursive: true, filter: (src) => !src.includes(`${path.sep}lib${path.sep}`) });
86
+ }
87
+
88
+ await new Promise((resolve, reject) => {
89
+ const output = createWriteStream(out);
90
+ const zip = new ZipArchive({ zlib: { level: 9 } });
91
+ output.on('close', resolve);
92
+ zip.on('error', reject);
93
+ zip.pipe(output);
94
+ zip.directory(stage, false);
95
+ zip.finalize();
96
+ });
97
+ } finally {
98
+ await fs.rm(stage, { recursive: true, force: true });
99
+ }
100
+
101
+ await fs.writeFile(`${out}.runtime-keys`, keys.map((k) => k.key).join('\n') + '\n');
102
+ const size = (await fs.stat(out)).size;
103
+ console.log(chalk.green(`✓ Dart code patch: ${out} (${(size / 1024 / 1024).toFixed(2)} MB)`));
104
+ for (const { abi, key } of keys) console.log(chalk.gray(` ${abi.padEnd(12)} engine ${key}`));
105
+ console.log(chalk.gray(` Engine keys written to ${out}.runtime-keys; deploy picks them up:`));
106
+ console.log(chalk.gray(` npx native-update deploy ${path.relative(process.cwd(), out)} --app <app> --version <v> --payload-type dart_aot --wait`));
107
+ }
@@ -0,0 +1,146 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import prompts from 'prompts';
5
+
6
+ export async function init(options) {
7
+ console.log(chalk.blue('🚀 Initializing Native Update in your project...'));
8
+
9
+ try {
10
+ // Check if already initialized
11
+ try {
12
+ await fs.access('./native-update.config.js');
13
+ const { overwrite } = await prompts({
14
+ type: 'confirm',
15
+ name: 'overwrite',
16
+ message: 'Config file already exists. Overwrite?',
17
+ initial: false
18
+ });
19
+
20
+ if (!overwrite) {
21
+ console.log(chalk.yellow('Initialization cancelled.'));
22
+ return;
23
+ }
24
+ } catch {
25
+ // File doesn't exist, good
26
+ }
27
+
28
+ // Prompt for configuration
29
+ const config = await prompts([
30
+ {
31
+ type: 'text',
32
+ name: 'appId',
33
+ message: 'App ID (e.g., com.example.app):',
34
+ validate: value => value.length > 0
35
+ },
36
+ {
37
+ type: 'text',
38
+ name: 'serverUrl',
39
+ message: 'Update server URL:',
40
+ initial: 'https://your-update-server.com'
41
+ },
42
+ {
43
+ type: 'select',
44
+ name: 'channel',
45
+ message: 'Default update channel:',
46
+ choices: [
47
+ { title: 'Production', value: 'production' },
48
+ { title: 'Staging', value: 'staging' },
49
+ { title: 'Development', value: 'development' }
50
+ ]
51
+ },
52
+ {
53
+ type: 'confirm',
54
+ name: 'autoUpdate',
55
+ message: 'Enable automatic updates?',
56
+ initial: true
57
+ }
58
+ ]);
59
+
60
+ // Create config file
61
+ const configContent = `export default {
62
+ appId: '${config.appId}',
63
+ serverUrl: '${config.serverUrl}',
64
+ channel: '${config.channel}',
65
+ autoUpdate: ${config.autoUpdate},
66
+
67
+ // Security
68
+ publicKey: \`-----BEGIN PUBLIC KEY-----
69
+ YOUR_PUBLIC_KEY_HERE
70
+ -----END PUBLIC KEY-----\`,
71
+
72
+ // Update behavior
73
+ updateStrategy: 'immediate', // immediate, on-app-start, on-app-resume
74
+ checkInterval: 60 * 60 * 1000, // 1 hour
75
+
76
+ // Optional callbacks
77
+ onUpdateAvailable: (update) => {
78
+ console.log('Update available:', update.version);
79
+ },
80
+
81
+ onUpdateDownloaded: (update) => {
82
+ console.log('Update downloaded:', update.version);
83
+ },
84
+
85
+ onUpdateFailed: (error) => {
86
+ console.error('Update failed:', error);
87
+ }
88
+ };
89
+ `;
90
+
91
+ await fs.writeFile('./native-update.config.js', configContent);
92
+
93
+ // Create example integration if requested
94
+ if (options.example) {
95
+ const exampleCode = `import { NativeUpdate } from 'native-update';
96
+ import config from './native-update.config.js';
97
+
98
+ // Initialize on app start
99
+ export async function initializeUpdates() {
100
+ try {
101
+ // Configure the plugin
102
+ await NativeUpdate.configure(config);
103
+
104
+ // Check for updates
105
+ const update = await NativeUpdate.checkForUpdate();
106
+
107
+ if (update.available) {
108
+ console.log(\`Update available: \${update.version}\`);
109
+
110
+ // Download in background
111
+ await NativeUpdate.downloadUpdate();
112
+
113
+ // Apply on next restart
114
+ await NativeUpdate.installOnNextRestart();
115
+ }
116
+ } catch (error) {
117
+ console.error('Update check failed:', error);
118
+ }
119
+ }
120
+
121
+ // Call this in your app initialization
122
+ initializeUpdates();
123
+ `;
124
+
125
+ await fs.writeFile('./native-update-example.js', exampleCode);
126
+ console.log(chalk.gray(' Created: native-update-example.js'));
127
+ }
128
+
129
+ console.log(chalk.green('✅ Native Update initialized successfully!'));
130
+ console.log('');
131
+ console.log(chalk.bold('Next steps:'));
132
+ console.log(chalk.gray(' 1. Generate signing keys:'));
133
+ console.log(chalk.cyan(' npx native-update keys generate'));
134
+ console.log(chalk.gray(' 2. Add public key to native-update.config.js'));
135
+ console.log(chalk.gray(' 3. Import and use the config in your app'));
136
+
137
+ if (options.backend !== 'custom') {
138
+ console.log(chalk.gray(` 4. Create ${options.backend} backend:`));
139
+ console.log(chalk.cyan(` npx native-update backend create ${options.backend}`));
140
+ }
141
+
142
+ } catch (error) {
143
+ console.error(chalk.red('❌ Initialization failed:'), error.message);
144
+ process.exit(1);
145
+ }
146
+ }
@@ -0,0 +1,58 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import { generateKeyPairSync } from 'crypto';
5
+
6
+ export async function generateKeys(options) {
7
+ console.log(chalk.blue('🔑 Generating key pair...'));
8
+
9
+ try {
10
+ // Create output directory
11
+ const outputDir = path.resolve(options.output);
12
+ await fs.mkdir(outputDir, { recursive: true });
13
+
14
+ if (options.type !== 'rsa') {
15
+ throw new Error('Only RSA keys are supported by the RSA-SHA256 bundle contract');
16
+ }
17
+ const keySize = parseInt(options.size);
18
+ if (![2048, 4096].includes(keySize)) {
19
+ throw new Error('RSA key size must be 2048 or 4096');
20
+ }
21
+ const { publicKey, privateKey } = generateKeyPairSync('rsa', {
22
+ modulusLength: keySize,
23
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
24
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
25
+ });
26
+
27
+ // Save keys
28
+ const timestamp = Date.now();
29
+ const privateKeyPath = path.join(outputDir, `private-${timestamp}.pem`);
30
+ const publicKeyPath = path.join(outputDir, `public-${timestamp}.pem`);
31
+
32
+ await fs.writeFile(privateKeyPath, privateKey);
33
+ await fs.writeFile(publicKeyPath, publicKey);
34
+
35
+ // Set proper permissions on private key
36
+ await fs.chmod(privateKeyPath, 0o600);
37
+
38
+ console.log(chalk.green('✅ Key pair generated successfully!'));
39
+ console.log('');
40
+ console.log(chalk.bold('Key Files:'));
41
+ console.log(chalk.gray(` Private Key: ${privateKeyPath}`));
42
+ console.log(chalk.gray(` Public Key: ${publicKeyPath}`));
43
+ console.log('');
44
+ console.log(chalk.yellow('⚠️ Security Notes:'));
45
+ console.log(chalk.red(' • Keep your private key secure and never commit it to version control'));
46
+ console.log(chalk.gray(' • Add the public key to your app configuration'));
47
+ console.log(chalk.gray(' • Use the private key for signing bundles on your CI/CD server'));
48
+ console.log('');
49
+ console.log(chalk.yellow('Next steps:'));
50
+ console.log(chalk.gray(' 1. Add to .gitignore:'));
51
+ console.log(chalk.cyan(` echo "${path.basename(privateKeyPath)}" >> .gitignore`));
52
+ console.log(chalk.gray(' 2. Configure your app with the public key'));
53
+
54
+ } catch (error) {
55
+ console.error(chalk.red('❌ Failed to generate keys:'), error.message);
56
+ process.exit(1);
57
+ }
58
+ }
@@ -0,0 +1,89 @@
1
+ import chalk from 'chalk';
2
+ import ora from 'ora';
3
+
4
+ const POLL_MS = 5000;
5
+ const MAX_CONSECUTIVE_FAILURES = 5;
6
+
7
+ export async function monitor(options) {
8
+ if (!options.server) {
9
+ console.error(chalk.red('Error: --server URL is required'));
10
+ process.exit(1);
11
+ }
12
+
13
+ console.log(chalk.blue(`📊 Monitoring updates from ${options.server}...`));
14
+ console.log(chalk.gray('Press Ctrl+C to stop'));
15
+ console.log('');
16
+
17
+ const spinner = ora('Fetching update statistics...').start();
18
+ let intervalId = null;
19
+ let consecutiveFailures = 0;
20
+ let stopping = false;
21
+
22
+ const stop = (code = 0) => {
23
+ if (stopping) return;
24
+ stopping = true;
25
+ if (intervalId) clearInterval(intervalId);
26
+ if (spinner.isSpinning) spinner.stop();
27
+ process.exit(code);
28
+ };
29
+
30
+ process.on('SIGINT', () => stop(0));
31
+ process.on('SIGTERM', () => stop(0));
32
+
33
+ const headers = options.key ? { Authorization: `Bearer ${options.key}` } : {};
34
+
35
+ const tick = async () => {
36
+ try {
37
+ const response = await fetch(`${options.server}/api/stats`, { headers });
38
+ if (!response.ok) throw new Error(`Server returned ${response.status}`);
39
+
40
+ const stats = await response.json();
41
+ consecutiveFailures = 0;
42
+
43
+ spinner.stop();
44
+ console.clear();
45
+ console.log(chalk.blue(`📊 Update Monitor - ${new Date().toLocaleTimeString()}`));
46
+ console.log(chalk.gray('─'.repeat(50)));
47
+ console.log('');
48
+
49
+ console.log(chalk.bold('Current Version:'));
50
+ console.log(chalk.gray(` Latest: ${stats.latestVersion || 'N/A'}`));
51
+ console.log(chalk.gray(` Channel: ${stats.channel || 'production'}`));
52
+ console.log('');
53
+
54
+ console.log(chalk.bold('Download Statistics:'));
55
+ console.log(chalk.gray(` Total Downloads: ${stats.totalDownloads || 0}`));
56
+ console.log(chalk.gray(` Downloads Today: ${stats.downloadsToday || 0}`));
57
+ console.log(chalk.gray(` Active Installs: ${stats.activeInstalls || 0}`));
58
+ console.log('');
59
+
60
+ if (stats.recentActivity) {
61
+ console.log(chalk.bold('Recent Activity:'));
62
+ stats.recentActivity.forEach((activity) => {
63
+ console.log(chalk.gray(` ${activity.time} - ${activity.action} (${activity.version})`));
64
+ });
65
+ }
66
+
67
+ console.log('');
68
+ console.log(chalk.gray('Press Ctrl+C to stop'));
69
+
70
+ spinner.start('Updating...');
71
+ } catch (error) {
72
+ consecutiveFailures += 1;
73
+ spinner.fail(
74
+ `Failed to fetch stats (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}): ${error.message}`,
75
+ );
76
+ if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
77
+ console.error(
78
+ chalk.red(`\nGiving up after ${MAX_CONSECUTIVE_FAILURES} consecutive failures.`),
79
+ );
80
+ stop(1);
81
+ return;
82
+ }
83
+ spinner.start('Retrying...');
84
+ }
85
+ };
86
+
87
+ await tick();
88
+ intervalId = setInterval(tick, POLL_MS);
89
+ }