@gfean/react-native-bundle-drop 0.4.6 → 0.6.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 (102) hide show
  1. package/README.md +168 -4
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +69 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  6. package/ios/BundleDropBridge.m +18 -0
  7. package/ios/BundleDropLocator.swift +48 -2
  8. package/ios/BundleDropModule.swift +75 -0
  9. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  10. package/lib/CLI/cli.d.ts +1 -0
  11. package/lib/CLI/cli.js +166 -79
  12. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  13. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  14. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  15. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  16. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  17. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  18. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  19. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  20. package/lib/CLI/scripts/aipowered/init-project-config.js +228 -43
  21. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  22. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  23. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  24. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  25. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  26. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  27. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  28. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  29. package/lib/CLI/scripts/doctor.js +143 -22
  30. package/lib/CLI/scripts/expo/configure-expo.js +51 -60
  31. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  32. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  33. package/lib/CLI/scripts/init-config.d.ts +7 -7
  34. package/lib/CLI/scripts/init-config.js +246 -32
  35. package/lib/CLI/scripts/login-cli.js +35 -10
  36. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  37. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  38. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  39. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  40. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  41. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  42. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  43. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  44. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  45. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  46. package/lib/CLI/scripts/sight-artifacts.d.ts +17 -0
  47. package/lib/CLI/scripts/sight-artifacts.js +204 -0
  48. package/lib/CLI/scripts/sight-cli.d.ts +10 -0
  49. package/lib/CLI/scripts/sight-cli.js +127 -0
  50. package/lib/CLI/scripts/sight-session.d.ts +14 -0
  51. package/lib/CLI/scripts/sight-session.js +192 -0
  52. package/lib/api/clientApi.d.ts +3 -1
  53. package/lib/api/clientApi.js +14 -0
  54. package/lib/api/types.d.ts +39 -0
  55. package/lib/context.d.ts +1 -1
  56. package/lib/index.d.ts +2 -0
  57. package/lib/index.js +3 -1
  58. package/lib/install/installFromZip.d.ts +3 -0
  59. package/lib/install/installFromZip.js +10 -1
  60. package/lib/loadConfig.d.ts +17 -1
  61. package/lib/loadConfig.js +16 -0
  62. package/lib/manager/downloadAndInstall.d.ts +3 -2
  63. package/lib/manager/downloadAndInstall.js +111 -46
  64. package/lib/manager/rollbackState.d.ts +3 -1
  65. package/lib/manager/rollbackState.js +2 -2
  66. package/lib/manager/updateCheck.d.ts +1 -0
  67. package/lib/manager/updateCheck.js +218 -78
  68. package/lib/metro.d.ts +8 -1
  69. package/lib/metro.js +68 -19
  70. package/lib/native/bundleDropNative.js +2 -1
  71. package/lib/native/fs.d.ts +6 -0
  72. package/lib/native/fs.js +24 -0
  73. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  74. package/lib/patch-engine/installFromPatchSet.js +14 -3
  75. package/lib/patch-engine/patchTransport.d.ts +2 -0
  76. package/lib/patch-engine/patchTransport.js +9 -0
  77. package/lib/runtime/initState.d.ts +5 -0
  78. package/lib/runtime/initState.js +4 -0
  79. package/lib/runtime/service.js +60 -3
  80. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  81. package/lib/runtime-delivery/artifactCapability.js +32 -0
  82. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  83. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  84. package/lib/runtime-delivery/bootstrapConfig.d.ts +50 -0
  85. package/lib/runtime-delivery/bootstrapConfig.js +217 -0
  86. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  87. package/lib/runtime-delivery/diagnostics.js +58 -0
  88. package/lib/runtime-delivery/encoding.d.ts +5 -0
  89. package/lib/runtime-delivery/encoding.js +132 -0
  90. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  91. package/lib/runtime-delivery/heartbeat.js +88 -0
  92. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  93. package/lib/runtime-delivery/localResolver.js +81 -0
  94. package/lib/runtime-delivery/manifestState.d.ts +9 -0
  95. package/lib/runtime-delivery/manifestState.js +102 -0
  96. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  97. package/lib/runtime-delivery/manifestVerifier.js +329 -0
  98. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  99. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  100. package/lib/runtime-delivery/types.d.ts +87 -0
  101. package/lib/runtime-delivery/types.js +6 -0
  102. package/package.json +2 -2
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RUNTIME_DELIVERY_DIAGNOSTIC_NAMES = void 0;
4
+ exports.recordRuntimeDeliveryDiagnostic = recordRuntimeDeliveryDiagnostic;
5
+ exports.getRuntimeDeliveryDiagnosticCounters = getRuntimeDeliveryDiagnosticCounters;
6
+ exports.resetRuntimeDeliveryDiagnosticsForTests = resetRuntimeDeliveryDiagnosticsForTests;
7
+ const initState_1 = require("../runtime/initState");
8
+ exports.RUNTIME_DELIVERY_DIAGNOSTIC_NAMES = [
9
+ 'manifest_hit',
10
+ 'dynamic_manifest',
11
+ 'origin_fallback',
12
+ 'invalid_signature',
13
+ 'unknown_key',
14
+ 'lane_mismatch',
15
+ 'generation_regression',
16
+ 'generation_equivocation',
17
+ 'manifest_http_error',
18
+ 'manifest_network_error',
19
+ 'manifest_timeout',
20
+ 'manifest_too_large',
21
+ 'manifest_invalid',
22
+ 'manifest_stream_unavailable',
23
+ 'authority_lease_http_error',
24
+ 'authority_lease_network_error',
25
+ 'authority_lease_timeout',
26
+ 'authority_lease_too_large',
27
+ 'authority_lease_invalid',
28
+ 'authority_lease_invalid_signature',
29
+ 'authority_lease_unknown_key',
30
+ 'authority_lease_expired',
31
+ 'authority_lease_origin_mismatch',
32
+ 'authority_lease_disabled',
33
+ ];
34
+ const counters = Object.fromEntries(exports.RUNTIME_DELIVERY_DIAGNOSTIC_NAMES.map(name => [name, 0]));
35
+ function recordRuntimeDeliveryDiagnostic(name, details) {
36
+ counters[name] += 1;
37
+ const listener = (0, initState_1.getBundleDropRuntimeConfig)()?.onRuntimeDeliveryDiagnostic;
38
+ if (!listener)
39
+ return;
40
+ try {
41
+ listener({
42
+ name,
43
+ count: counters[name],
44
+ timestamp: new Date().toISOString(),
45
+ ...(details ? { details } : {}),
46
+ });
47
+ }
48
+ catch (error) {
49
+ console.warn('[BundleDrop] runtime-delivery diagnostic listener failed:', error);
50
+ }
51
+ }
52
+ function getRuntimeDeliveryDiagnosticCounters() {
53
+ return { ...counters };
54
+ }
55
+ function resetRuntimeDeliveryDiagnosticsForTests() {
56
+ for (const name of exports.RUNTIME_DELIVERY_DIAGNOSTIC_NAMES)
57
+ counters[name] = 0;
58
+ }
@@ -0,0 +1,5 @@
1
+ export declare function encodeBase64UrlUtf8(value: string): string;
2
+ export declare function decodeBase64UrlBytes(value: string): number[];
3
+ export declare function decodeBase64UrlUtf8(value: string): string;
4
+ export declare function decodeUtf8Bytes(bytes: ArrayLike<number>): string;
5
+ export declare function utf8ByteLength(value: string): number;
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.encodeBase64UrlUtf8 = encodeBase64UrlUtf8;
4
+ exports.decodeBase64UrlBytes = decodeBase64UrlBytes;
5
+ exports.decodeBase64UrlUtf8 = decodeBase64UrlUtf8;
6
+ exports.decodeUtf8Bytes = decodeUtf8Bytes;
7
+ exports.utf8ByteLength = utf8ByteLength;
8
+ const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
9
+ function utf8Bytes(value) {
10
+ const bytes = [];
11
+ for (const character of value) {
12
+ const codePoint = character.codePointAt(0);
13
+ if (codePoint <= 0x7f) {
14
+ bytes.push(codePoint);
15
+ }
16
+ else if (codePoint <= 0x7ff) {
17
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
18
+ }
19
+ else if (codePoint <= 0xffff) {
20
+ bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
21
+ }
22
+ else {
23
+ bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
24
+ }
25
+ }
26
+ return bytes;
27
+ }
28
+ function bytesToBase64(bytes) {
29
+ let result = '';
30
+ for (let index = 0; index < bytes.length; index += 3) {
31
+ const first = bytes[index];
32
+ const second = bytes[index + 1];
33
+ const third = bytes[index + 2];
34
+ const triple = (first << 16) | ((second || 0) << 8) | (third || 0);
35
+ result += BASE64_ALPHABET[(triple >> 18) & 0x3f];
36
+ result += BASE64_ALPHABET[(triple >> 12) & 0x3f];
37
+ result += second === undefined ? '=' : BASE64_ALPHABET[(triple >> 6) & 0x3f];
38
+ result += third === undefined ? '=' : BASE64_ALPHABET[triple & 0x3f];
39
+ }
40
+ return result;
41
+ }
42
+ function encodeBase64UrlUtf8(value) {
43
+ return bytesToBase64(utf8Bytes(value))
44
+ .replace(/=/g, '')
45
+ .replace(/\+/g, '-')
46
+ .replace(/\//g, '_');
47
+ }
48
+ function decodeBase64UrlBytes(value) {
49
+ if (!/^[A-Za-z0-9_-]*$/.test(value)) {
50
+ throw new Error('Invalid base64url value');
51
+ }
52
+ const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
53
+ const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4);
54
+ const bytes = [];
55
+ for (let index = 0; index < padded.length; index += 4) {
56
+ const a = BASE64_ALPHABET.indexOf(padded[index]);
57
+ const b = BASE64_ALPHABET.indexOf(padded[index + 1]);
58
+ const c = padded[index + 2] === '=' ? 0 : BASE64_ALPHABET.indexOf(padded[index + 2]);
59
+ const d = padded[index + 3] === '=' ? 0 : BASE64_ALPHABET.indexOf(padded[index + 3]);
60
+ if (a < 0 || b < 0 || c < 0 || d < 0)
61
+ throw new Error('Invalid base64url value');
62
+ const triple = (a << 18) | (b << 12) | (c << 6) | d;
63
+ bytes.push((triple >> 16) & 0xff);
64
+ if (padded[index + 2] !== '=')
65
+ bytes.push((triple >> 8) & 0xff);
66
+ if (padded[index + 3] !== '=')
67
+ bytes.push(triple & 0xff);
68
+ }
69
+ return bytes;
70
+ }
71
+ function decodeBase64UrlUtf8(value) {
72
+ return decodeUtf8Bytes(decodeBase64UrlBytes(value));
73
+ }
74
+ function decodeUtf8Bytes(bytes) {
75
+ let result = '';
76
+ let segment = '';
77
+ const flush = () => {
78
+ result += segment;
79
+ segment = '';
80
+ };
81
+ for (let index = 0; index < bytes.length;) {
82
+ const first = bytes[index];
83
+ let codePoint;
84
+ let width;
85
+ let minimum;
86
+ if (first <= 0x7f) {
87
+ codePoint = first;
88
+ width = 1;
89
+ minimum = 0;
90
+ }
91
+ else if (first >= 0xc2 && first <= 0xdf) {
92
+ codePoint = first & 0x1f;
93
+ width = 2;
94
+ minimum = 0x80;
95
+ }
96
+ else if (first >= 0xe0 && first <= 0xef) {
97
+ codePoint = first & 0x0f;
98
+ width = 3;
99
+ minimum = 0x800;
100
+ }
101
+ else if (first >= 0xf0 && first <= 0xf4) {
102
+ codePoint = first & 0x07;
103
+ width = 4;
104
+ minimum = 0x10000;
105
+ }
106
+ else {
107
+ throw new Error('Invalid UTF-8 payload');
108
+ }
109
+ if (index + width > bytes.length)
110
+ throw new Error('Invalid UTF-8 payload');
111
+ for (let offset = 1; offset < width; offset += 1) {
112
+ const continuation = bytes[index + offset];
113
+ if ((continuation & 0xc0) !== 0x80)
114
+ throw new Error('Invalid UTF-8 payload');
115
+ codePoint = (codePoint << 6) | (continuation & 0x3f);
116
+ }
117
+ if (codePoint < minimum ||
118
+ codePoint > 0x10ffff ||
119
+ (codePoint >= 0xd800 && codePoint <= 0xdfff)) {
120
+ throw new Error('Invalid UTF-8 payload');
121
+ }
122
+ segment += String.fromCodePoint(codePoint);
123
+ if (segment.length >= 8192)
124
+ flush();
125
+ index += width;
126
+ }
127
+ flush();
128
+ return result;
129
+ }
130
+ function utf8ByteLength(value) {
131
+ return utf8Bytes(value).length;
132
+ }
@@ -0,0 +1,3 @@
1
+ import type { OtaActiveInstallHeartbeat } from '../api/types';
2
+ export declare function reportActiveInstallWhenDue(projectSlug: string, payload: OtaActiveInstallHeartbeat): void;
3
+ export declare function resetRuntimeDeliveryHeartbeatForTests(): void;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.reportActiveInstallWhenDue = reportActiveInstallWhenDue;
7
+ exports.resetRuntimeDeliveryHeartbeatForTests = resetRuntimeDeliveryHeartbeatForTests;
8
+ const clientApi_1 = require("../api/clientApi");
9
+ const context_1 = require("../context");
10
+ const fsUtils_1 = require("../fs/fsUtils");
11
+ const fs_1 = __importDefault(require("../native/fs"));
12
+ const HEARTBEAT_STATE_PATH = `${context_1.BUNDLE_DROP_ROOT}/runtime-delivery-heartbeats.json`;
13
+ const STABLE_HEARTBEAT_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
14
+ const inFlight = new Set();
15
+ let stateMutation = Promise.resolve();
16
+ async function readState() {
17
+ try {
18
+ const parsed = JSON.parse(await fs_1.default.readFile(HEARTBEAT_STATE_PATH, 'utf8'));
19
+ if (parsed.schemaVersion === 1 && parsed.reportedAt && typeof parsed.reportedAt === 'object') {
20
+ return {
21
+ schemaVersion: 1,
22
+ reportedAt: parsed.reportedAt,
23
+ fingerprints: parsed.fingerprints && typeof parsed.fingerprints === 'object'
24
+ ? parsed.fingerprints
25
+ : {},
26
+ };
27
+ }
28
+ }
29
+ catch {
30
+ // A missing heartbeat cache means this install may report once.
31
+ }
32
+ return { schemaVersion: 1, reportedAt: {}, fingerprints: {} };
33
+ }
34
+ async function heartbeatFingerprint(payload) {
35
+ const userProperties = payload.userProperties
36
+ ? Object.fromEntries(Object.entries(payload.userProperties).sort(([left], [right]) => left.localeCompare(right)))
37
+ : null;
38
+ return fs_1.default.sha256String(JSON.stringify({
39
+ currentHash: payload.currentHash,
40
+ environment: payload.environment ?? null,
41
+ userProperties,
42
+ }));
43
+ }
44
+ function heartbeatKey(projectSlug, payload) {
45
+ return [
46
+ projectSlug,
47
+ payload.channelName,
48
+ payload.platform,
49
+ payload.runtimeVersion,
50
+ payload.installId,
51
+ ].map(encodeURIComponent).join('/');
52
+ }
53
+ function reportActiveInstallWhenDue(projectSlug, payload) {
54
+ const key = heartbeatKey(projectSlug, payload);
55
+ if (inFlight.has(key))
56
+ return;
57
+ inFlight.add(key);
58
+ void (async () => {
59
+ try {
60
+ const state = await readState();
61
+ const now = Date.now();
62
+ const fingerprint = await heartbeatFingerprint(payload);
63
+ if (state.fingerprints[key] === fingerprint &&
64
+ now - (state.reportedAt[key] || 0) < STABLE_HEARTBEAT_INTERVAL_MS) {
65
+ return;
66
+ }
67
+ await (0, clientApi_1.postOtaActiveInstallHeartbeat)(projectSlug, payload);
68
+ const mutation = stateMutation.then(async () => {
69
+ const latest = await readState();
70
+ latest.reportedAt[key] = now;
71
+ latest.fingerprints[key] = fingerprint;
72
+ await (0, fsUtils_1.atomicWriteJson)(HEARTBEAT_STATE_PATH, latest);
73
+ });
74
+ stateMutation = mutation.then(() => undefined, () => undefined);
75
+ await mutation;
76
+ }
77
+ catch (error) {
78
+ console.warn('⚠️ BundleDrop active-install heartbeat failed:', error);
79
+ }
80
+ finally {
81
+ inFlight.delete(key);
82
+ }
83
+ })();
84
+ }
85
+ function resetRuntimeDeliveryHeartbeatForTests() {
86
+ inFlight.clear();
87
+ stateMutation = Promise.resolve();
88
+ }
@@ -0,0 +1,23 @@
1
+ import type { RuntimeDeliveryLaneManifest, RuntimeDeliveryPatchEdge, RuntimeDeliveryRelease } from './types';
2
+ export type LocalResolution = {
3
+ action: 'NOOP';
4
+ reason: string;
5
+ } | {
6
+ action: 'ROLLBACK';
7
+ reason: string;
8
+ } | {
9
+ action: 'INSTALL';
10
+ target: RuntimeDeliveryRelease;
11
+ mode: 'full' | 'patch';
12
+ patchEdge?: RuntimeDeliveryPatchEdge;
13
+ };
14
+ export type LocalResolutionInput = {
15
+ currentHash: string | null;
16
+ rejectedHashes: string[];
17
+ installId: string;
18
+ patchAlgorithms: string[];
19
+ supportsContentAddressedAssets: boolean;
20
+ now?: number;
21
+ };
22
+ export declare function rolloutBucket(installId: string): Promise<number>;
23
+ export declare function resolveRuntimeDeliveryLane(manifest: RuntimeDeliveryLaneManifest, input: LocalResolutionInput): Promise<LocalResolution>;
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.rolloutBucket = rolloutBucket;
7
+ exports.resolveRuntimeDeliveryLane = resolveRuntimeDeliveryLane;
8
+ const fs_1 = __importDefault(require("../native/fs"));
9
+ function isUnexpired(expiresAt, now) {
10
+ return !expiresAt || Date.parse(expiresAt) > now;
11
+ }
12
+ async function rolloutBucket(installId) {
13
+ const digest = await fs_1.default.sha256String(installId);
14
+ if (!/^[a-f0-9]{64}$/.test(digest))
15
+ throw new Error('Native SHA-256 returned an invalid digest');
16
+ return Number.parseInt(digest.slice(0, 8), 16) % 100;
17
+ }
18
+ function selectPatchEdge(manifest, input, target, now) {
19
+ if (!manifest.patchPolicy.enabled || !input.currentHash)
20
+ return undefined;
21
+ if (input.rejectedHashes.includes(input.currentHash))
22
+ return undefined;
23
+ return manifest.patchEdges.find(edge => edge.baseHash === input.currentHash &&
24
+ edge.targetHash === target.bundleHash &&
25
+ input.patchAlgorithms.includes(edge.algorithm) &&
26
+ (!edge.missingAssetsHash || input.supportsContentAddressedAssets) &&
27
+ isUnexpired(edge.expiresAt, now) &&
28
+ edge.patchSizeBytes <= edge.fullBundleSizeBytes * manifest.patchPolicy.maxPatchToFullRatio);
29
+ }
30
+ async function resolveRuntimeDeliveryLane(manifest, input) {
31
+ if (manifest.resolutionMode !== 'local')
32
+ throw new Error('Dynamic lanes require server resolution');
33
+ if (!manifest.candidateSetComplete)
34
+ throw new Error('Incomplete candidate sets cannot resolve locally');
35
+ const now = input.now ?? Date.now();
36
+ const rejected = new Set(input.rejectedHashes);
37
+ const revoked = new Set(manifest.revokedHashes);
38
+ const currentRevoked = !!input.currentHash && revoked.has(input.currentHash);
39
+ const releasesByRef = new Map(manifest.releases.map(release => [release.releaseRef, release]));
40
+ const isSafe = (release) => release.available &&
41
+ !rejected.has(release.bundleHash) &&
42
+ !revoked.has(release.bundleHash) &&
43
+ isUnexpired(release.expiresAt, now);
44
+ let selected;
45
+ let noCandidateReason = 'NO_PUBLISHED_BUNDLE';
46
+ if (manifest.publishingMode === 'automatic') {
47
+ selected = manifest.releases.find(isSafe);
48
+ noCandidateReason = 'NO_COMPATIBLE_BUNDLE';
49
+ }
50
+ else {
51
+ const bucket = await rolloutBucket(input.installId);
52
+ for (const rollout of manifest.publishedRollouts) {
53
+ const release = releasesByRef.get(rollout.releaseRef);
54
+ if (!isSafe(release))
55
+ continue;
56
+ const eligible = rollout.rolloutPercentage >= 100 || bucket < rollout.rolloutPercentage;
57
+ if (eligible) {
58
+ selected = release;
59
+ break;
60
+ }
61
+ noCandidateReason = 'ROLLOUT_NOT_ELIGIBLE';
62
+ }
63
+ }
64
+ if (!selected) {
65
+ return currentRevoked
66
+ ? { action: 'ROLLBACK', reason: 'CURRENT_REVOKED_NO_COMPATIBLE_TARGET' }
67
+ : { action: 'NOOP', reason: noCandidateReason };
68
+ }
69
+ if (selected.bundleHash === input.currentHash) {
70
+ return currentRevoked
71
+ ? { action: 'ROLLBACK', reason: 'CURRENT_REVOKED_NO_COMPATIBLE_TARGET' }
72
+ : { action: 'NOOP', reason: 'UP_TO_DATE' };
73
+ }
74
+ const patchEdge = currentRevoked ? undefined : selectPatchEdge(manifest, input, selected, now);
75
+ return {
76
+ action: 'INSTALL',
77
+ target: selected,
78
+ mode: patchEdge ? 'patch' : 'full',
79
+ patchEdge,
80
+ };
81
+ }
@@ -0,0 +1,9 @@
1
+ import type { RuntimeDeliveryLaneIdentity, RuntimeDeliveryLaneManifest } from './types';
2
+ export type VerifiedLaneState = {
3
+ highestGeneration: number;
4
+ payloadSha256: string;
5
+ revokedHashes: string[];
6
+ verifiedAt: string;
7
+ };
8
+ export declare function readVerifiedLaneState(identity: RuntimeDeliveryLaneIdentity): Promise<VerifiedLaneState | null>;
9
+ export declare function recordVerifiedLaneManifest(manifest: RuntimeDeliveryLaneManifest, payloadSha256: string): Promise<void>;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readVerifiedLaneState = readVerifiedLaneState;
7
+ exports.recordVerifiedLaneManifest = recordVerifiedLaneManifest;
8
+ const context_1 = require("../context");
9
+ const fsUtils_1 = require("../fs/fsUtils");
10
+ const fs_1 = __importDefault(require("../native/fs"));
11
+ const STATE_PATH = `${context_1.BUNDLE_DROP_ROOT}/runtime-delivery-state.json`;
12
+ let stateMutation = Promise.resolve();
13
+ const SHA256_PATTERN = /^[a-f0-9]{64}$/;
14
+ function isRecord(value) {
15
+ return !!value && typeof value === 'object' && !Array.isArray(value);
16
+ }
17
+ function invalidState() {
18
+ throw new Error('Runtime delivery state is malformed or unsupported');
19
+ }
20
+ function parseState(raw) {
21
+ let parsed;
22
+ try {
23
+ parsed = JSON.parse(raw);
24
+ }
25
+ catch {
26
+ return invalidState();
27
+ }
28
+ if (!isRecord(parsed) || Object.keys(parsed).sort().join(',') !== 'lanes,schemaVersion') {
29
+ return invalidState();
30
+ }
31
+ if (parsed.schemaVersion !== 1 || !isRecord(parsed.lanes))
32
+ return invalidState();
33
+ for (const [key, lane] of Object.entries(parsed.lanes)) {
34
+ if (!key || !isRecord(lane))
35
+ return invalidState();
36
+ if (Object.keys(lane).sort().join(',') !==
37
+ 'highestGeneration,payloadSha256,revokedHashes,verifiedAt') {
38
+ return invalidState();
39
+ }
40
+ if (!Number.isSafeInteger(lane.highestGeneration) || lane.highestGeneration < 1) {
41
+ return invalidState();
42
+ }
43
+ if (typeof lane.payloadSha256 !== 'string' || !SHA256_PATTERN.test(lane.payloadSha256)) {
44
+ return invalidState();
45
+ }
46
+ if (!Array.isArray(lane.revokedHashes) ||
47
+ lane.revokedHashes.some(hash => typeof hash !== 'string' || !SHA256_PATTERN.test(hash)) ||
48
+ new Set(lane.revokedHashes).size !== lane.revokedHashes.length) {
49
+ return invalidState();
50
+ }
51
+ if (typeof lane.verifiedAt !== 'string' || !Number.isFinite(Date.parse(lane.verifiedAt))) {
52
+ return invalidState();
53
+ }
54
+ }
55
+ return parsed;
56
+ }
57
+ function laneStateKey(identity) {
58
+ return [identity.projectSlug, identity.channelName, identity.platform, identity.runtimeVersion]
59
+ .map(value => encodeURIComponent(value))
60
+ .join('/');
61
+ }
62
+ async function readState() {
63
+ if (!await fs_1.default.exists(STATE_PATH))
64
+ return { schemaVersion: 1, lanes: {} };
65
+ let raw;
66
+ try {
67
+ raw = await fs_1.default.readFile(STATE_PATH, 'utf8');
68
+ }
69
+ catch {
70
+ throw new Error('Unable to read existing runtime delivery state');
71
+ }
72
+ return parseState(raw);
73
+ }
74
+ async function readVerifiedLaneState(identity) {
75
+ const state = await readState();
76
+ return state.lanes[laneStateKey(identity)] || null;
77
+ }
78
+ async function recordVerifiedLaneManifest(manifest, payloadSha256) {
79
+ const mutation = stateMutation.then(async () => {
80
+ const identity = manifest;
81
+ const key = laneStateKey(identity);
82
+ const state = await readState();
83
+ const existing = state.lanes[key];
84
+ if (existing && existing.highestGeneration > manifest.generation) {
85
+ throw new Error('Manifest generation regressed while persisting verified state');
86
+ }
87
+ if (existing &&
88
+ existing.highestGeneration === manifest.generation &&
89
+ existing.payloadSha256 !== payloadSha256) {
90
+ throw new Error('Manifest generation equivocation detected');
91
+ }
92
+ state.lanes[key] = {
93
+ highestGeneration: manifest.generation,
94
+ payloadSha256,
95
+ revokedHashes: [...manifest.revokedHashes],
96
+ verifiedAt: new Date().toISOString(),
97
+ };
98
+ await (0, fsUtils_1.atomicWriteJson)(STATE_PATH, state);
99
+ });
100
+ stateMutation = mutation.then(() => undefined, () => undefined);
101
+ return mutation;
102
+ }
@@ -0,0 +1,13 @@
1
+ import { type RuntimeDeliveryLaneIdentity, type RuntimeDeliveryLaneManifest, type RuntimeDeliveryPublicKey } from './types';
2
+ export declare const MAX_RUNTIME_MANIFEST_BYTES: number;
3
+ export type RuntimeDeliveryManifestFailureCode = 'body_too_large' | 'http_error' | 'network_error' | 'timeout' | 'stream_unavailable' | 'invalid_manifest' | 'invalid_signature' | 'unknown_key' | 'lane_mismatch' | 'generation_regression' | 'generation_equivocation' | 'authority_body_too_large' | 'authority_http_error' | 'authority_network_error' | 'authority_timeout' | 'authority_stream_unavailable' | 'authority_invalid' | 'authority_invalid_signature' | 'authority_unknown_key' | 'authority_expired' | 'authority_origin_mismatch' | 'authority_disabled';
4
+ export declare class RuntimeDeliveryManifestError extends Error {
5
+ readonly code: RuntimeDeliveryManifestFailureCode;
6
+ readonly status?: number;
7
+ constructor(code: RuntimeDeliveryManifestFailureCode, message: string, options?: {
8
+ cause?: unknown;
9
+ status?: number;
10
+ });
11
+ }
12
+ export declare function verifyRuntimeDeliveryManifest(serializedJws: string, expectedIdentity: RuntimeDeliveryLaneIdentity, publicKeys: Record<string, RuntimeDeliveryPublicKey>): Promise<RuntimeDeliveryLaneManifest>;
13
+ export declare function verifyRuntimeDeliverySignedPayload(serializedJws: string, expectedType: string, publicKeys: Record<string, RuntimeDeliveryPublicKey>): Promise<string>;