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,104 @@
1
+ // Core plugin interface will be defined later after other interfaces
2
+ /**
3
+ * Enums
4
+ */
5
+ export var BackgroundUpdateType;
6
+ (function (BackgroundUpdateType) {
7
+ BackgroundUpdateType["APP_UPDATE"] = "app_update";
8
+ BackgroundUpdateType["LIVE_UPDATE"] = "live_update";
9
+ BackgroundUpdateType["BOTH"] = "both";
10
+ })(BackgroundUpdateType || (BackgroundUpdateType = {}));
11
+ export var NotificationPriority;
12
+ (function (NotificationPriority) {
13
+ NotificationPriority["MIN"] = "min";
14
+ NotificationPriority["LOW"] = "low";
15
+ NotificationPriority["DEFAULT"] = "default";
16
+ NotificationPriority["HIGH"] = "high";
17
+ NotificationPriority["MAX"] = "max";
18
+ })(NotificationPriority || (NotificationPriority = {}));
19
+ export var UpdateStrategy;
20
+ (function (UpdateStrategy) {
21
+ UpdateStrategy["IMMEDIATE"] = "immediate";
22
+ UpdateStrategy["BACKGROUND"] = "background";
23
+ UpdateStrategy["MANUAL"] = "manual";
24
+ })(UpdateStrategy || (UpdateStrategy = {}));
25
+ export var UpdateMode;
26
+ (function (UpdateMode) {
27
+ UpdateMode["IMMEDIATE"] = "immediate";
28
+ UpdateMode["ON_NEXT_RESTART"] = "on_next_restart";
29
+ UpdateMode["ON_NEXT_RESUME"] = "on_next_resume";
30
+ })(UpdateMode || (UpdateMode = {}));
31
+ export var InstallMode;
32
+ (function (InstallMode) {
33
+ InstallMode["IMMEDIATE"] = "immediate";
34
+ InstallMode["ON_NEXT_RESTART"] = "on_next_restart";
35
+ InstallMode["ON_NEXT_RESUME"] = "on_next_resume";
36
+ })(InstallMode || (InstallMode = {}));
37
+ export var ChecksumAlgorithm;
38
+ (function (ChecksumAlgorithm) {
39
+ ChecksumAlgorithm["SHA256"] = "SHA-256";
40
+ ChecksumAlgorithm["SHA512"] = "SHA-512";
41
+ })(ChecksumAlgorithm || (ChecksumAlgorithm = {}));
42
+ export var SyncStatus;
43
+ (function (SyncStatus) {
44
+ SyncStatus["UP_TO_DATE"] = "UP_TO_DATE";
45
+ SyncStatus["UPDATE_AVAILABLE"] = "UPDATE_AVAILABLE";
46
+ SyncStatus["UPDATE_INSTALLED"] = "UPDATE_INSTALLED";
47
+ SyncStatus["ERROR"] = "ERROR";
48
+ })(SyncStatus || (SyncStatus = {}));
49
+ export var BundleStatus;
50
+ (function (BundleStatus) {
51
+ BundleStatus["PENDING"] = "PENDING";
52
+ BundleStatus["DOWNLOADING"] = "DOWNLOADING";
53
+ BundleStatus["READY"] = "READY";
54
+ BundleStatus["ACTIVE"] = "ACTIVE";
55
+ BundleStatus["FAILED"] = "FAILED";
56
+ })(BundleStatus || (BundleStatus = {}));
57
+ export var InstallStatus;
58
+ (function (InstallStatus) {
59
+ InstallStatus["UNKNOWN"] = "UNKNOWN";
60
+ InstallStatus["PENDING"] = "PENDING";
61
+ InstallStatus["DOWNLOADING"] = "DOWNLOADING";
62
+ InstallStatus["DOWNLOADED"] = "DOWNLOADED";
63
+ InstallStatus["INSTALLING"] = "INSTALLING";
64
+ InstallStatus["INSTALLED"] = "INSTALLED";
65
+ InstallStatus["FAILED"] = "FAILED";
66
+ InstallStatus["CANCELED"] = "CANCELED";
67
+ })(InstallStatus || (InstallStatus = {}));
68
+ export var UpdateErrorCode;
69
+ (function (UpdateErrorCode) {
70
+ // Network errors
71
+ UpdateErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
72
+ UpdateErrorCode["SERVER_ERROR"] = "SERVER_ERROR";
73
+ UpdateErrorCode["TIMEOUT_ERROR"] = "TIMEOUT_ERROR";
74
+ // Download errors
75
+ UpdateErrorCode["DOWNLOAD_ERROR"] = "DOWNLOAD_ERROR";
76
+ UpdateErrorCode["STORAGE_ERROR"] = "STORAGE_ERROR";
77
+ UpdateErrorCode["SIZE_LIMIT_EXCEEDED"] = "SIZE_LIMIT_EXCEEDED";
78
+ // Security errors
79
+ UpdateErrorCode["VERIFICATION_ERROR"] = "VERIFICATION_ERROR";
80
+ UpdateErrorCode["CHECKSUM_ERROR"] = "CHECKSUM_ERROR";
81
+ UpdateErrorCode["SIGNATURE_ERROR"] = "SIGNATURE_ERROR";
82
+ UpdateErrorCode["INSECURE_URL"] = "INSECURE_URL";
83
+ UpdateErrorCode["INVALID_CERTIFICATE"] = "INVALID_CERTIFICATE";
84
+ UpdateErrorCode["PATH_TRAVERSAL"] = "PATH_TRAVERSAL";
85
+ // Installation errors
86
+ UpdateErrorCode["INSTALL_ERROR"] = "INSTALL_ERROR";
87
+ UpdateErrorCode["ROLLBACK_ERROR"] = "ROLLBACK_ERROR";
88
+ UpdateErrorCode["VERSION_MISMATCH"] = "VERSION_MISMATCH";
89
+ // Permission errors
90
+ UpdateErrorCode["PERMISSION_DENIED"] = "PERMISSION_DENIED";
91
+ // App update errors
92
+ UpdateErrorCode["UPDATE_NOT_AVAILABLE"] = "UPDATE_NOT_AVAILABLE";
93
+ UpdateErrorCode["UPDATE_IN_PROGRESS"] = "UPDATE_IN_PROGRESS";
94
+ UpdateErrorCode["UPDATE_CANCELLED"] = "UPDATE_CANCELLED";
95
+ UpdateErrorCode["PLATFORM_NOT_SUPPORTED"] = "PLATFORM_NOT_SUPPORTED";
96
+ // Review errors
97
+ UpdateErrorCode["REVIEW_NOT_SUPPORTED"] = "REVIEW_NOT_SUPPORTED";
98
+ UpdateErrorCode["QUOTA_EXCEEDED"] = "QUOTA_EXCEEDED";
99
+ UpdateErrorCode["CONDITIONS_NOT_MET"] = "CONDITIONS_NOT_MET";
100
+ // General errors
101
+ UpdateErrorCode["INVALID_CONFIG"] = "INVALID_CONFIG";
102
+ UpdateErrorCode["NOT_CONFIGURED"] = "NOT_CONFIGURED";
103
+ UpdateErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
104
+ })(UpdateErrorCode || (UpdateErrorCode = {}));
@@ -0,0 +1,14 @@
1
+ export { NativeUpdate } from './plugin';
2
+ export { BackgroundUpdateType, NotificationPriority, UpdateStrategy, UpdateMode, InstallMode, ChecksumAlgorithm, SyncStatus, BundleStatus, InstallStatus, UpdateErrorCode, } from './definitions';
3
+ export type { NativeUpdatePlugin, NativeUpdateCombinedPlugin, NativeUpdateListeners, LiveUpdatePlugin, AppUpdatePlugin, AppReviewPlugin, PluginConfig, UpdateConfig, LiveUpdateConfig, AppUpdateConfig, AppReviewConfig, BundleInfo, DownloadOptions, DownloadProgressEvent, SyncOptions, SyncResult, DeleteOptions, LatestVersion, ValidateOptions, ValidationResult, CheckForUpdateResult, DownloadUpdateOptions, AppIdentity, AppUpdateInfo, OpenAppStoreOptions, ReviewResult, CanRequestReviewResult, UpdateStateChangedEvent, AppUpdateStateChangedEvent, AppUpdateProgressEvent, AppUpdateAvailableEvent, AppUpdateReadyEvent, AppUpdateFailedEvent, AppUpdateNotificationClickedEvent, AppUpdateInstallClickedEvent, BackgroundUpdateProgressEvent, BackgroundUpdateNotificationEvent, UpdateError, BackgroundUpdatePlugin, BackgroundUpdateConfig, BackgroundUpdateStatus, BackgroundCheckResult, NotificationPreferences, NotificationPermissionStatus, SecurityConfig, SecurityInfo, CertificatePinning, CertificatePin, PluginInitConfig, PluginListenerHandle, } from './definitions';
4
+ export type { RolloutConfig, RolloutTargetSegments, RolloutSchedule, RolloutTimestamp, DeviceInfo, UpdateCheckResponse, } from './types/rollout';
5
+ export { ErrorCode, NativeUpdateError, ConfigurationError, DownloadError, ValidationError, StorageError, UpdateError as UpdateErrorClass, } from './core/errors';
6
+ export { ConfigManager } from './core/config';
7
+ export { Logger, LogLevel } from './core/logger';
8
+ export { SecurityValidator } from './core/security';
9
+ export { PluginManager } from './core/plugin-manager';
10
+ export { CacheManager } from './core/cache-manager';
11
+ export { BundleManager } from './live-update/bundle-manager';
12
+ export { DownloadManager } from './live-update/download-manager';
13
+ export { VersionManager } from './live-update/version-manager';
14
+ export { UpdateManager } from './live-update/update-manager';
@@ -0,0 +1,18 @@
1
+ // Main plugin export
2
+ export { NativeUpdate } from './plugin';
3
+ // Runtime enums — MUST be `export {}` not `export type {}` so they survive
4
+ // TypeScript erasure and reach the published bundle.
5
+ export { BackgroundUpdateType, NotificationPriority, UpdateStrategy, UpdateMode, InstallMode, ChecksumAlgorithm, SyncStatus, BundleStatus, InstallStatus, UpdateErrorCode, } from './definitions';
6
+ // Error exports
7
+ export { ErrorCode, NativeUpdateError, ConfigurationError, DownloadError, ValidationError, StorageError, UpdateError as UpdateErrorClass, } from './core/errors';
8
+ // Core exports for advanced users
9
+ export { ConfigManager } from './core/config';
10
+ export { Logger, LogLevel } from './core/logger';
11
+ export { SecurityValidator } from './core/security';
12
+ export { PluginManager } from './core/plugin-manager';
13
+ export { CacheManager } from './core/cache-manager';
14
+ // Manager exports for advanced users
15
+ export { BundleManager } from './live-update/bundle-manager';
16
+ export { DownloadManager } from './live-update/download-manager';
17
+ export { VersionManager } from './live-update/version-manager';
18
+ export { UpdateManager } from './live-update/update-manager';
@@ -0,0 +1,102 @@
1
+ import type { BundleInfo } from '../definitions';
2
+ import type { DownloadManager } from './download-manager';
3
+ /**
4
+ * Manages bundle storage and lifecycle
5
+ */
6
+ export declare class BundleManager {
7
+ private readonly STORAGE_KEY;
8
+ private readonly ACTIVE_BUNDLE_KEY;
9
+ private preferences;
10
+ private readonly logger;
11
+ private readonly configManager;
12
+ private cache;
13
+ private cacheExpiry;
14
+ private downloadManager;
15
+ constructor();
16
+ /**
17
+ * Wire the DownloadManager so deleteBundle can also remove the
18
+ * persisted bundle file. Without this, deleted bundles leave their
19
+ * blob on disk forever.
20
+ */
21
+ setDownloadManager(downloadManager: DownloadManager): void;
22
+ /**
23
+ * Initialize the bundle manager with preferences
24
+ */
25
+ initialize(): Promise<void>;
26
+ /**
27
+ * Load cache from preferences
28
+ */
29
+ private loadCache;
30
+ /**
31
+ * Save cache to preferences
32
+ */
33
+ private saveCache;
34
+ /**
35
+ * Save bundle information
36
+ */
37
+ saveBundleInfo(bundle: BundleInfo): Promise<void>;
38
+ /**
39
+ * Validate bundle information
40
+ */
41
+ private validateBundleInfo;
42
+ /**
43
+ * Get all bundles
44
+ */
45
+ getAllBundles(): Promise<BundleInfo[]>;
46
+ /**
47
+ * Get bundle by ID
48
+ */
49
+ getBundle(bundleId: string): Promise<BundleInfo | null>;
50
+ /**
51
+ * Delete bundle
52
+ */
53
+ deleteBundle(bundleId: string): Promise<void>;
54
+ /**
55
+ * Get active bundle
56
+ */
57
+ getActiveBundle(): Promise<BundleInfo | null>;
58
+ /**
59
+ * Set active bundle
60
+ */
61
+ setActiveBundle(bundleId: string): Promise<void>;
62
+ /**
63
+ * Get active bundle ID
64
+ */
65
+ getActiveBundleId(): Promise<string | null>;
66
+ /**
67
+ * Clear active bundle
68
+ */
69
+ clearActiveBundle(): Promise<void>;
70
+ /**
71
+ * Clear all bundles
72
+ */
73
+ clearAllBundles(): Promise<void>;
74
+ /**
75
+ * Clean up old bundles
76
+ */
77
+ cleanupOldBundles(keepCount: number): Promise<void>;
78
+ /**
79
+ * Get bundles older than specified time
80
+ */
81
+ getBundlesOlderThan(timestamp: number): Promise<BundleInfo[]>;
82
+ /**
83
+ * Mark bundle as verified
84
+ */
85
+ markBundleAsVerified(bundleId: string): Promise<void>;
86
+ /**
87
+ * Get total storage used by bundles
88
+ */
89
+ getTotalStorageUsed(): Promise<number>;
90
+ /**
91
+ * Check if storage limit is exceeded
92
+ */
93
+ isStorageLimitExceeded(additionalSize?: number): Promise<boolean>;
94
+ /**
95
+ * Create default bundle
96
+ */
97
+ createDefaultBundle(): BundleInfo;
98
+ /**
99
+ * Clean expired cache entries
100
+ */
101
+ cleanExpiredBundles(): Promise<void>;
102
+ }
@@ -0,0 +1,344 @@
1
+ import { ConfigManager } from '../core/config';
2
+ import { Logger } from '../core/logger';
3
+ import { StorageError, ErrorCode } from '../core/errors';
4
+ /**
5
+ * Manages bundle storage and lifecycle
6
+ */
7
+ export class BundleManager {
8
+ constructor() {
9
+ this.STORAGE_KEY = 'capacitor_native_update_bundles';
10
+ this.ACTIVE_BUNDLE_KEY = 'capacitor_native_update_active';
11
+ this.preferences = null;
12
+ this.cache = new Map();
13
+ this.cacheExpiry = 0;
14
+ this.downloadManager = null;
15
+ this.logger = Logger.getInstance();
16
+ this.configManager = ConfigManager.getInstance();
17
+ }
18
+ /**
19
+ * Wire the DownloadManager so deleteBundle can also remove the
20
+ * persisted bundle file. Without this, deleted bundles leave their
21
+ * blob on disk forever.
22
+ */
23
+ setDownloadManager(downloadManager) {
24
+ this.downloadManager = downloadManager;
25
+ }
26
+ /**
27
+ * Initialize the bundle manager with preferences
28
+ */
29
+ async initialize() {
30
+ this.preferences = this.configManager.get('preferences');
31
+ if (!this.preferences) {
32
+ throw new StorageError(ErrorCode.MISSING_DEPENDENCY, 'Preferences not configured. Please configure the plugin first.');
33
+ }
34
+ await this.loadCache();
35
+ }
36
+ /**
37
+ * Load cache from preferences
38
+ */
39
+ async loadCache() {
40
+ if (Date.now() < this.cacheExpiry) {
41
+ return; // Cache still valid
42
+ }
43
+ try {
44
+ const { value } = await this.preferences.get({ key: this.STORAGE_KEY });
45
+ if (value) {
46
+ const bundles = JSON.parse(value);
47
+ this.cache.clear();
48
+ bundles.forEach((bundle) => this.cache.set(bundle.bundleId, bundle));
49
+ }
50
+ this.cacheExpiry = Date.now() + 5000; // 5 second cache
51
+ }
52
+ catch (error) {
53
+ this.logger.error('Failed to load bundles from storage', error);
54
+ this.cache.clear();
55
+ }
56
+ }
57
+ /**
58
+ * Save cache to preferences
59
+ */
60
+ async saveCache() {
61
+ try {
62
+ const bundles = Array.from(this.cache.values());
63
+ await this.preferences.set({
64
+ key: this.STORAGE_KEY,
65
+ value: JSON.stringify(bundles),
66
+ });
67
+ this.logger.debug('Saved bundles to storage', { count: bundles.length });
68
+ }
69
+ catch (error) {
70
+ throw new StorageError(ErrorCode.STORAGE_FULL, 'Failed to save bundles to storage', undefined, error);
71
+ }
72
+ }
73
+ /**
74
+ * Save bundle information
75
+ */
76
+ async saveBundleInfo(bundle) {
77
+ this.validateBundleInfo(bundle);
78
+ this.cache.set(bundle.bundleId, bundle);
79
+ await this.saveCache();
80
+ this.logger.info('Bundle saved', {
81
+ bundleId: bundle.bundleId,
82
+ version: bundle.version,
83
+ });
84
+ }
85
+ /**
86
+ * Validate bundle information
87
+ */
88
+ validateBundleInfo(bundle) {
89
+ if (!bundle.bundleId || typeof bundle.bundleId !== 'string') {
90
+ throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle ID');
91
+ }
92
+ if (!bundle.version || typeof bundle.version !== 'string') {
93
+ throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle version');
94
+ }
95
+ if (!bundle.path || typeof bundle.path !== 'string') {
96
+ throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle path');
97
+ }
98
+ if (typeof bundle.size !== 'number' || bundle.size < 0) {
99
+ throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Invalid bundle size');
100
+ }
101
+ }
102
+ /**
103
+ * Get all bundles
104
+ */
105
+ async getAllBundles() {
106
+ await this.loadCache();
107
+ return Array.from(this.cache.values());
108
+ }
109
+ /**
110
+ * Get bundle by ID
111
+ */
112
+ async getBundle(bundleId) {
113
+ if (!bundleId) {
114
+ throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');
115
+ }
116
+ await this.loadCache();
117
+ return this.cache.get(bundleId) || null;
118
+ }
119
+ /**
120
+ * Delete bundle
121
+ */
122
+ async deleteBundle(bundleId) {
123
+ if (!bundleId) {
124
+ throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');
125
+ }
126
+ await this.loadCache();
127
+ const bundle = this.cache.get(bundleId);
128
+ if (!bundle) {
129
+ this.logger.warn('Attempted to delete non-existent bundle', { bundleId });
130
+ return;
131
+ }
132
+ this.cache.delete(bundleId);
133
+ await this.saveCache();
134
+ // If this was the active bundle, clear it
135
+ const activeBundleId = await this.getActiveBundleId();
136
+ if (activeBundleId === bundleId) {
137
+ await this.clearActiveBundle();
138
+ }
139
+ // Remove the persisted bundle file from filesystem. Failure to delete
140
+ // metadata earlier was a storage leak: the on-disk zip stayed forever
141
+ // because deleteBundle only cleaned the metadata cache.
142
+ if (this.downloadManager) {
143
+ try {
144
+ await this.downloadManager.deleteBlob(bundleId);
145
+ }
146
+ catch (error) {
147
+ this.logger.warn('Failed to delete bundle file', { bundleId, error });
148
+ }
149
+ }
150
+ this.logger.info('Bundle deleted', { bundleId });
151
+ }
152
+ /**
153
+ * Get active bundle
154
+ */
155
+ async getActiveBundle() {
156
+ const activeBundleId = await this.getActiveBundleId();
157
+ if (!activeBundleId)
158
+ return null;
159
+ return this.getBundle(activeBundleId);
160
+ }
161
+ /**
162
+ * Set active bundle
163
+ */
164
+ async setActiveBundle(bundleId) {
165
+ if (!bundleId) {
166
+ throw new StorageError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');
167
+ }
168
+ const bundle = await this.getBundle(bundleId);
169
+ if (!bundle) {
170
+ throw new StorageError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);
171
+ }
172
+ // Update previous active bundle status
173
+ const previousActive = await this.getActiveBundle();
174
+ if (previousActive && previousActive.bundleId !== bundleId) {
175
+ previousActive.status = 'READY';
176
+ await this.saveBundleInfo(previousActive);
177
+ }
178
+ // Set new active bundle
179
+ bundle.status = 'ACTIVE';
180
+ await this.saveBundleInfo(bundle);
181
+ await this.preferences.set({
182
+ key: this.ACTIVE_BUNDLE_KEY,
183
+ value: bundleId,
184
+ });
185
+ this.logger.info('Active bundle set', {
186
+ bundleId,
187
+ version: bundle.version,
188
+ });
189
+ }
190
+ /**
191
+ * Get active bundle ID
192
+ */
193
+ async getActiveBundleId() {
194
+ try {
195
+ const { value } = await this.preferences.get({
196
+ key: this.ACTIVE_BUNDLE_KEY,
197
+ });
198
+ return value;
199
+ }
200
+ catch (error) {
201
+ this.logger.error('Failed to get active bundle ID', error);
202
+ return null;
203
+ }
204
+ }
205
+ /**
206
+ * Clear active bundle
207
+ */
208
+ async clearActiveBundle() {
209
+ await this.preferences.remove({ key: this.ACTIVE_BUNDLE_KEY });
210
+ this.logger.info('Active bundle cleared');
211
+ }
212
+ /**
213
+ * Clear all bundles
214
+ */
215
+ async clearAllBundles() {
216
+ await this.preferences.remove({ key: this.STORAGE_KEY });
217
+ await this.preferences.remove({ key: this.ACTIVE_BUNDLE_KEY });
218
+ this.cache.clear();
219
+ this.cacheExpiry = 0;
220
+ this.logger.info('All bundles cleared');
221
+ }
222
+ /**
223
+ * Clean up old bundles
224
+ */
225
+ async cleanupOldBundles(keepCount) {
226
+ if (keepCount < 1) {
227
+ throw new StorageError(ErrorCode.INVALID_CONFIG, 'Keep count must be at least 1');
228
+ }
229
+ const bundles = await this.getAllBundles();
230
+ const activeBundleId = await this.getActiveBundleId();
231
+ // Sort by download time (newest first)
232
+ const sorted = bundles.sort((a, b) => b.downloadTime - a.downloadTime);
233
+ // Keep the active bundle and the most recent ones
234
+ const toKeep = new Set();
235
+ if (activeBundleId) {
236
+ toKeep.add(activeBundleId);
237
+ }
238
+ let kept = toKeep.size;
239
+ for (const bundle of sorted) {
240
+ if (kept >= keepCount)
241
+ break;
242
+ if (!toKeep.has(bundle.bundleId)) {
243
+ toKeep.add(bundle.bundleId);
244
+ kept++;
245
+ }
246
+ }
247
+ // Delete bundles not in the keep set
248
+ let deletedCount = 0;
249
+ for (const bundle of bundles) {
250
+ if (!toKeep.has(bundle.bundleId)) {
251
+ await this.deleteBundle(bundle.bundleId);
252
+ deletedCount++;
253
+ }
254
+ }
255
+ if (deletedCount > 0) {
256
+ this.logger.info('Cleaned up old bundles', {
257
+ deleted: deletedCount,
258
+ kept,
259
+ });
260
+ }
261
+ }
262
+ /**
263
+ * Get bundles older than specified time
264
+ */
265
+ async getBundlesOlderThan(timestamp) {
266
+ if (timestamp < 0) {
267
+ throw new StorageError(ErrorCode.INVALID_CONFIG, 'Timestamp must be non-negative');
268
+ }
269
+ const bundles = await this.getAllBundles();
270
+ return bundles.filter((b) => b.downloadTime < timestamp);
271
+ }
272
+ /**
273
+ * Mark bundle as verified
274
+ */
275
+ async markBundleAsVerified(bundleId) {
276
+ const bundle = await this.getBundle(bundleId);
277
+ if (!bundle) {
278
+ throw new StorageError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);
279
+ }
280
+ bundle.verified = true;
281
+ await this.saveBundleInfo(bundle);
282
+ this.logger.info('Bundle marked as verified', { bundleId });
283
+ }
284
+ /**
285
+ * Get total storage used by bundles
286
+ */
287
+ async getTotalStorageUsed() {
288
+ const bundles = await this.getAllBundles();
289
+ return bundles.reduce((total, bundle) => total + bundle.size, 0);
290
+ }
291
+ /**
292
+ * Check if storage limit is exceeded
293
+ */
294
+ async isStorageLimitExceeded(additionalSize = 0) {
295
+ const totalUsed = await this.getTotalStorageUsed();
296
+ // Try to get actual device storage quota
297
+ let maxStorage = this.configManager.get('maxBundleSize') * 3; // Default: 3x max bundle size
298
+ try {
299
+ if ('storage' in navigator && 'estimate' in navigator.storage) {
300
+ const estimate = await navigator.storage.estimate();
301
+ if (estimate.quota) {
302
+ // Use actual quota, but keep 100MB buffer for system
303
+ const bufferBytes = 100 * 1024 * 1024; // 100MB
304
+ maxStorage = Math.max(maxStorage, estimate.quota - bufferBytes);
305
+ }
306
+ }
307
+ }
308
+ catch (_a) {
309
+ // Storage API not available, use config-based limit
310
+ this.logger.warn('Storage API not available for quota check, using config limit');
311
+ }
312
+ return totalUsed + additionalSize > maxStorage;
313
+ }
314
+ /**
315
+ * Create default bundle
316
+ */
317
+ createDefaultBundle() {
318
+ return {
319
+ bundleId: 'default',
320
+ version: '1.0.0',
321
+ path: '/',
322
+ downloadTime: Date.now(),
323
+ size: 0,
324
+ status: 'ACTIVE',
325
+ checksum: '',
326
+ verified: true,
327
+ };
328
+ }
329
+ /**
330
+ * Clean expired cache entries
331
+ */
332
+ async cleanExpiredBundles() {
333
+ const expirationTime = this.configManager.get('cacheExpiration');
334
+ const cutoffTime = Date.now() - expirationTime;
335
+ const expiredBundles = await this.getBundlesOlderThan(cutoffTime);
336
+ for (const bundle of expiredBundles) {
337
+ // Don't delete active bundle
338
+ const activeBundleId = await this.getActiveBundleId();
339
+ if (bundle.bundleId !== activeBundleId) {
340
+ await this.deleteBundle(bundle.bundleId);
341
+ }
342
+ }
343
+ }
344
+ }
@@ -0,0 +1,38 @@
1
+ export interface CertificatePin {
2
+ /**
3
+ * Hostname to pin certificates for (e.g., "api.example.com")
4
+ */
5
+ hostname: string;
6
+ /**
7
+ * Array of SHA-256 certificate fingerprints in the format "sha256/base64hash"
8
+ */
9
+ sha256: string[];
10
+ }
11
+ export interface CertificatePinningConfig {
12
+ /**
13
+ * Enable certificate pinning
14
+ */
15
+ enabled: boolean;
16
+ /**
17
+ * Array of certificate pins
18
+ */
19
+ pins: CertificatePin[];
20
+ }
21
+ /**
22
+ * Certificate pinning utilities
23
+ */
24
+ export declare class CertificatePinning {
25
+ /**
26
+ * Generate SHA-256 fingerprint from certificate
27
+ * Note: This is a utility for generating pins, not for runtime validation
28
+ */
29
+ static generateFingerprint(certificatePem: string): Promise<string>;
30
+ /**
31
+ * Validate certificate pinning configuration
32
+ */
33
+ static validateConfig(config: CertificatePinningConfig): void;
34
+ /**
35
+ * Example configuration
36
+ */
37
+ static example(): CertificatePinningConfig;
38
+ }