@hot-updater/protocol 1.2.0-rc.4 → 1.2.0-rc.41

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.
@@ -284,6 +284,8 @@ const VERSION_NAME = 16843292;
284
284
  const NAME = 16842755;
285
285
  const VALUE = 16842788;
286
286
  const RESOURCE = 16842789;
287
+ const SCHEME = 16842791;
288
+ const COMPONENTS = /* @__PURE__ */ new Set(["activity", "activity-alias"]);
287
289
  const attributeOf = (element, resourceId, name) => element.attributes.find((attribute) => attribute.resourceId !== 0 ? attribute.resourceId === resourceId : attribute.name === name)?.value ?? null;
288
290
  /** The values of a parsed manifest that import reads. */
289
291
  const readAndroidManifest = (manifest) => {
@@ -292,17 +294,53 @@ const readAndroidManifest = (manifest) => {
292
294
  const versionCode = attributeOf(manifest, VERSION_CODE, "versionCode");
293
295
  const application = manifest.children.find(({ name }) => name === "application");
294
296
  const metaData = /* @__PURE__ */ new Map();
295
- for (const element of application?.children ?? []) {
296
- if (element.name !== "meta-data") continue;
297
+ const launchers = [];
298
+ const urlSchemes = /* @__PURE__ */ new Map();
299
+ const componentMetaData = /* @__PURE__ */ new Map();
300
+ const metaDataOf = (element, into) => {
297
301
  const name = attributeOf(element, NAME, "name");
298
302
  const value = attributeOf(element, VALUE, "value") ?? attributeOf(element, RESOURCE, "resource");
299
- if (name?.type === "string" && value !== null) metaData.set(name.value, value);
303
+ if (name?.type === "string" && value !== null) into.set(name.value, value);
304
+ };
305
+ const stringAttribute = (element, id, name) => {
306
+ const value = attributeOf(element, id, name);
307
+ return value?.type === "string" ? value.value : null;
308
+ };
309
+ for (const element of application?.children ?? []) {
310
+ if (COMPONENTS.has(element.name)) {
311
+ const component = stringAttribute(element, NAME, "name");
312
+ if (component === null) continue;
313
+ for (const item of element.children) {
314
+ if (item.name !== "meta-data") continue;
315
+ const own = componentMetaData.get(component) ?? /* @__PURE__ */ new Map();
316
+ metaDataOf(item, own);
317
+ componentMetaData.set(component, own);
318
+ }
319
+ for (const filter of element.children) {
320
+ if (filter.name !== "intent-filter") continue;
321
+ const named = (child) => filter.children.filter(({ name }) => name === child).map((part) => stringAttribute(part, NAME, "name"));
322
+ if (named("action").includes("android.intent.action.MAIN") && named("category").includes("android.intent.category.LAUNCHER") && !launchers.includes(component)) launchers.push(component);
323
+ if (!named("action").includes("android.intent.action.VIEW")) continue;
324
+ for (const data of filter.children) {
325
+ if (data.name !== "data") continue;
326
+ const scheme = stringAttribute(data, SCHEME, "scheme");
327
+ if (scheme === null) continue;
328
+ urlSchemes.set(component, [...urlSchemes.get(component) ?? [], scheme]);
329
+ }
330
+ }
331
+ continue;
332
+ }
333
+ if (element.name !== "meta-data") continue;
334
+ metaDataOf(element, metaData);
300
335
  }
301
336
  return {
302
337
  packageName: packageValue?.type === "string" ? packageValue.value : null,
303
338
  versionName: attributeOf(manifest, VERSION_NAME, "versionName"),
304
339
  versionCode: versionCode?.type === "int" ? versionCode.value : null,
305
- metaData
340
+ metaData,
341
+ launchers,
342
+ urlSchemes,
343
+ componentMetaData
306
344
  };
307
345
  };
308
346
  //#endregion
@@ -443,13 +481,30 @@ const ENTITIES = {
443
481
  const decodeEntities = (text) => text.replace(/&(#x[0-9a-f]+|#\d+|\w+);/giu, (whole, entity) => {
444
482
  if (entity[0] === "#") {
445
483
  const code = entity[1] === "x" || entity[1] === "X" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
484
+ if (code > 1114111) throw corrupt();
446
485
  return String.fromCodePoint(code);
447
486
  }
448
487
  return ENTITIES[entity] ?? whole;
449
488
  });
450
- /** An XML property list, as some tools leave an app's Info.plist. */
489
+ /**
490
+ * `text` without each `open`, what follows it, and its `close`. A scan, because
491
+ * a regular expression retries from every `open` that never closes, which on a
492
+ * crafted file takes minutes.
493
+ */
494
+ const withoutSpans = (text, open, close) => {
495
+ let kept = "";
496
+ let position = 0;
497
+ for (;;) {
498
+ const start = text.indexOf(open, position);
499
+ const end = start === -1 ? -1 : text.indexOf(close, start + open.length);
500
+ if (end === -1) return kept + text.slice(position);
501
+ kept += text.slice(position, start);
502
+ position = end + close.length;
503
+ }
504
+ };
505
+ /** An XML property list, as a provisioning profile holds one. */
451
506
  const parseXmlPlist = (text) => {
452
- const tokens = text.replace(/<!--[\s\S]*?-->/gu, "").replace(/<\?[\s\S]*?\?>/gu, "").replace(/<!DOCTYPE[^>]*>/giu, "").split(/(<[^>]+>)/u);
507
+ const tokens = withoutSpans(withoutSpans(text, "<!--", "-->"), "<?", "?>").replace(/<!DOCTYPE[^<>]*>/giu, "").split(/(<[^<>]+>)/u);
453
508
  let i = 0;
454
509
  const nextTag = () => {
455
510
  while (i < tokens.length) {
@@ -511,6 +566,156 @@ const parsePlist = (bytes) => {
511
566
  return parseXmlPlist(new TextDecoder().decode(bytes));
512
567
  };
513
568
  //#endregion
569
+ //#region src/nativeArtifact/sandbox.ts
570
+ /**
571
+ * What a sandbox build is, wherever it is built or read: `sandbox: true` on a
572
+ * `nativeBuild` scheme adds a native layer to the app, which a normal build
573
+ * never compiles.
574
+ */
575
+ /**
576
+ * The literal the sandbox layer's code holds, in `ios/HotUpdater/Sandbox` and
577
+ * `android/src/sandbox`: reading an artifact's strings finds it. Its length
578
+ * is its own among the lengths those reads keep.
579
+ */
580
+ const SANDBOX_CODE_MARKER = "HOT_UPDATER_SANDBOX_NATIVE_LAYER";
581
+ /** The Info.plist key an iOS sandbox build declares itself with. */
582
+ const SANDBOX_INFO_PLIST_KEY = "HOT_UPDATER_SANDBOX";
583
+ /**
584
+ * The Info.plist key that records the URL scheme an iOS sandbox build
585
+ * registers in its `SANDBOX_URL_TYPE_NAME` URL type: the build reads its own
586
+ * scheme from it, and a later patch knows which scheme is the sandbox's.
587
+ */
588
+ const SANDBOX_URL_SCHEME_INFO_PLIST_KEY = "HOT_UPDATER_SANDBOX_URL_SCHEME";
589
+ const URL_SCHEME_SYNTAX = /^[a-z][a-z0-9+.-]*$/;
590
+ /**
591
+ * Whether a value is a URL scheme in lower-case ASCII, as written: what a
592
+ * build records, read before any lower-casing.
593
+ */
594
+ const isRecordedUrlSchemeSyntax = (value) => typeof value === "string" && URL_SCHEME_SYNTAX.test(value);
595
+ /**
596
+ * The URL scheme an iOS sandbox build registers, by one rule its patch, its
597
+ * reader, and its own code apply alike. `recorded` is the Info.plist's
598
+ * `SANDBOX_URL_SCHEME_INFO_PLIST_KEY`, undefined when the key is absent, and
599
+ * `namedTypes` its URL types named `SANDBOX_URL_TYPE_NAME`.
600
+ * - Absent: a prerelease's build, which recorded none. Undefined: the caller
601
+ * reads it the way that build was read.
602
+ * - Present: a scheme in lower-case ASCII, as written, that the one URL type
603
+ * of the name holds alone. Anything else is null, with no fallback.
604
+ */
605
+ const recordedSandboxUrlScheme = (recorded, namedTypes) => {
606
+ if (recorded === void 0) return void 0;
607
+ if (!isRecordedUrlSchemeSyntax(recorded) || namedTypes.length !== 1) return null;
608
+ const schemes = namedTypes[0]?.CFBundleURLSchemes;
609
+ return Array.isArray(schemes) && schemes.length === 1 && schemes[0] === recorded ? recorded : null;
610
+ };
611
+ /** The `<meta-data>` an Android sandbox build declares itself with. */
612
+ const SANDBOX_META_DATA = "com.hotupdater.SANDBOX";
613
+ /** The activity that takes an Android sandbox build's launcher entry and links. */
614
+ const SANDBOX_ACTIVITY = "com.hotupdater.HotUpdaterSandboxActivity";
615
+ /** The `applicationIdSuffix` an Android sandbox build appends. */
616
+ const SANDBOX_APPLICATION_ID_SUFFIX = ".sandbox";
617
+ /**
618
+ * The `CFBundleURLName` of the URL type an iOS sandbox build registers its URL
619
+ * scheme with, which the build reads its own scheme from.
620
+ */
621
+ const SANDBOX_URL_TYPE_NAME = "hot-updater-sandbox";
622
+ /**
623
+ * The `<meta-data>` of `SANDBOX_ACTIVITY` that names the URL scheme an Android
624
+ * sandbox build registers, which the build reads its own scheme from.
625
+ */
626
+ const SANDBOX_URL_SCHEME_META_DATA = "com.hotupdater.sandbox.URL_SCHEME";
627
+ const SANDBOX_URL_SCHEME_PREFIX = "hu-sandbox-";
628
+ /**
629
+ * The URL scheme a sandbox build registers when its scheme sets none, derived
630
+ * from the app's ID: the app's own scheme would ask which app to open beside
631
+ * the store app.
632
+ */
633
+ const sandboxUrlSchemeOf = (appId) => `${SANDBOX_URL_SCHEME_PREFIX}${appId.toLowerCase().replace(/[^a-z0-9]+/gu, "-")}`;
634
+ /**
635
+ * Whether a URL scheme has the prefix of the derived one: how an artifact built
636
+ * before the URL scheme could be set is read, which registered no other.
637
+ */
638
+ const isSandboxUrlScheme = (scheme) => scheme.toLowerCase().startsWith(SANDBOX_URL_SCHEME_PREFIX);
639
+ const CONFIGURED_URL_SCHEME = /^[a-z][a-z0-9+.-]{0,63}$/u;
640
+ const RESERVED_URL_SCHEMES = /* @__PURE__ */ new Set([
641
+ "http",
642
+ "https",
643
+ "file",
644
+ "data",
645
+ "javascript",
646
+ "true",
647
+ "false"
648
+ ]);
649
+ /**
650
+ * Whether `sandbox: { urlScheme }` can name a URL scheme: lower case, a letter
651
+ * then up to 63 letters, digits, `+`, `.` or `-`, none the system or a browser
652
+ * owns, and neither `true` nor `false`, which Android's manifest can't hold as
653
+ * a string.
654
+ */
655
+ const isConfigurableSandboxUrlScheme = (urlScheme) => CONFIGURED_URL_SCHEME.test(urlScheme) && !RESERVED_URL_SCHEMES.has(urlScheme);
656
+ /**
657
+ * The link a preview QR holds. `urlScheme` is the one the sandbox build
658
+ * registered; without it, the one derived from `appId`, the scheme's
659
+ * `bundleIdentifier` or `packageName`: the ID before the Android sandbox's
660
+ * `.sandbox` suffix.
661
+ */
662
+ const createPreviewLink = ({ urlScheme, appId, channel, fingerprintHash, platform }) => {
663
+ require_uuid.assertCanonicalChannelName(channel);
664
+ if (platform !== void 0 && !PREVIEW_LINK_PLATFORMS.has(platform)) throw new Error(`A preview link's platform is ios or android, not ${platform}.`);
665
+ const link = `${(urlScheme ?? sandboxUrlSchemeOf(appId)).toLowerCase()}://hot-updater/preview?channel=${encodeURIComponent(channel)}&fingerprint=${encodeURIComponent(fingerprintHash)}`;
666
+ return platform === void 0 ? link : `${link}&platform=${platform}`;
667
+ };
668
+ /** Any URL scheme: which app's it is, the app that opens the link decides. */
669
+ const PREVIEW_LINK = /^([a-z][a-z0-9+.-]*):\/\/hot-updater\/preview\?([^#]*)$/iu;
670
+ /**
671
+ * A URL scheme in ASCII alone: case folding lets `/iu` match `K` (Kelvin) or
672
+ * `ſ` as a letter.
673
+ */
674
+ const ASCII_URL_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/;
675
+ const MAX_FINGERPRINT_LENGTH = 256;
676
+ const PREVIEW_LINK_PLATFORMS = /* @__PURE__ */ new Set(["ios", "android"]);
677
+ /**
678
+ * What a preview link says, or null for anything else: another shape, a
679
+ * repeated or missing parameter, or a channel no release can target. It takes
680
+ * any URL scheme: a sandbox build refuses a link of another scheme than its
681
+ * own. A `platform` other than `ios` or `android` reads as none. Native code
682
+ * parses it the same way before any JavaScript runs, in HotUpdaterSandboxLink,
683
+ * and shares the vectors in test-utils' `sandbox-preview-links.json`.
684
+ */
685
+ const parsePreviewLink = (link) => {
686
+ const match = PREVIEW_LINK.exec(link);
687
+ if (match === null || !ASCII_URL_SCHEME.test(match[1])) return null;
688
+ const parameters = /* @__PURE__ */ new Map();
689
+ for (const parameter of match[2].split("&")) {
690
+ const separator = parameter.indexOf("=");
691
+ if (separator === -1) return null;
692
+ const name = parameter.slice(0, separator);
693
+ if (parameters.has(name)) return null;
694
+ let value;
695
+ try {
696
+ value = decodeURIComponent(parameter.slice(separator + 1));
697
+ } catch {
698
+ return null;
699
+ }
700
+ parameters.set(name, value);
701
+ }
702
+ const channel = parameters.get("channel");
703
+ const fingerprintHash = parameters.get("fingerprint");
704
+ if (channel === void 0 || fingerprintHash === void 0 || fingerprintHash.length === 0 || fingerprintHash.length > MAX_FINGERPRINT_LENGTH) return null;
705
+ try {
706
+ require_uuid.assertCanonicalChannelName(channel);
707
+ } catch {
708
+ return null;
709
+ }
710
+ const platform = parameters.get("platform");
711
+ return {
712
+ urlScheme: match[1].toLowerCase(),
713
+ channel,
714
+ fingerprintHash,
715
+ ...platform !== void 0 && PREVIEW_LINK_PLATFORMS.has(platform) ? { platform } : {}
716
+ };
717
+ };
718
+ //#endregion
514
719
  //#region src/nativeArtifact/strings.ts
515
720
  const view$1 = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
516
721
  /** Bytes that are all ASCII, as text; null otherwise. */
@@ -656,7 +861,7 @@ const UINT32_MAX = 4294967295;
656
861
  const EOCD_SEARCH_LENGTH = 65557;
657
862
  /** How much compressed data one read takes. */
658
863
  const READ_CHUNK = 1048576;
659
- const MiB$1 = 1048576;
864
+ const MiB$2 = 1048576;
660
865
  /**
661
866
  * What an archive may hold before it is refused as no artifact: an upload is
662
867
  * untrusted, so a crafted directory or entry (a zip bomb) stops here, not
@@ -664,10 +869,10 @@ const MiB$1 = 1048576;
664
869
  */
665
870
  const ZIP_LIMITS = {
666
871
  /** The central directory. */
667
- directoryBytes: 64 * MiB$1,
872
+ directoryBytes: 64 * MiB$2,
668
873
  entries: 5e5,
669
874
  /** An entry streamed out whole, such as the built-in bundle. */
670
- entryBytes: 1024 * MiB$1
875
+ entryBytes: 1024 * MiB$2
671
876
  };
672
877
  const UNIX_HOST = 3;
673
878
  const S_IFMT = 61440;
@@ -775,7 +980,7 @@ const filterZipEntries = (entries, match) => {
775
980
  const assertReadable = (entry) => {
776
981
  if (entry.symlink) throw new NativeArtifactError("UNREADABLE", `The archive's ${entry.name} is a symbolic link, not a file.`);
777
982
  };
778
- const tooLarge = (entry, limit) => new NativeArtifactError("UNREADABLE", `The archive's ${entry.name} is larger than ${Math.round(limit / MiB$1)} MB, more than any artifact's.`);
983
+ const tooLarge = (entry, limit) => new NativeArtifactError("UNREADABLE", `The archive's ${entry.name} is larger than ${Math.round(limit / MiB$2)} MB, more than any artifact's.`);
779
984
  /** Where an entry's data starts, past its local header. */
780
985
  const dataOffsetOf = async (source, entry) => {
781
986
  const local = view(await source.read(entry.localHeaderOffset, 30));
@@ -860,13 +1065,13 @@ const readZipEntry = (source, entry, maxBytes, budget) => {
860
1065
  };
861
1066
  //#endregion
862
1067
  //#region src/nativeArtifact/readNativeArtifact.ts
863
- const MiB = 1048576;
1068
+ const MiB$1 = 1048576;
864
1069
  /** The most a manifest or an Info.plist holds. */
865
- const METADATA_BYTES = 16 * MiB;
1070
+ const METADATA_BYTES$1 = 16 * MiB$1;
866
1071
  /** The most one dex file holds. */
867
- const DEX_BYTES = 256 * MiB;
1072
+ const DEX_BYTES = 256 * MiB$1;
868
1073
  /** The most reading one artifact inflates, across every entry it reads. */
869
- const READ_BUDGET_BYTES = 2048 * MiB;
1074
+ const READ_BUDGET_BYTES$1 = 2048 * MiB$1;
870
1075
  /** How long reading one artifact may take. */
871
1076
  const DEFAULT_TIMEOUT_MS = 12e4;
872
1077
  /** Where each kind of artifact packs its built-in bundle. */
@@ -879,7 +1084,11 @@ const nativeArtifactKindOf = (fileName) => {
879
1084
  };
880
1085
  const UUID_LENGTH = 36;
881
1086
  const SHA256_HEX = /^[0-9a-f]{64}$/u;
882
- const LENGTHS = /* @__PURE__ */ new Set([UUID_LENGTH, 64]);
1087
+ const LENGTHS = /* @__PURE__ */ new Set([
1088
+ UUID_LENGTH,
1089
+ 64,
1090
+ 32
1091
+ ]);
883
1092
  const unique = (values) => [...new Set(values)].sort();
884
1093
  const candidatesOf = (strings) => {
885
1094
  const all = [...strings];
@@ -908,7 +1117,7 @@ const androidChannelOf = (value) => {
908
1117
  const readAndroid = async (source, kind, entries, budget) => {
909
1118
  const manifestEntry = findZipEntry(entries, kind === "aab" ? "base/manifest/AndroidManifest.xml" : "AndroidManifest.xml");
910
1119
  if (manifestEntry === void 0) throw new NativeArtifactError("UNREADABLE", `The ${kind === "aab" ? ".aab has no base/manifest/AndroidManifest.xml" : ".apk has no AndroidManifest.xml"}.`);
911
- const manifestBytes = await readZipEntry(source, manifestEntry, METADATA_BYTES, budget);
1120
+ const manifestBytes = await readZipEntry(source, manifestEntry, METADATA_BYTES$1, budget);
912
1121
  const manifest = readAndroidManifest(kind === "aab" ? parseProtoManifest(manifestBytes) : parseBinaryManifest(manifestBytes));
913
1122
  const strings = [];
914
1123
  const dexes = filterZipEntries(entries, (name) => kind === "aab" ? /^base\/dex\/classes\d*\.dex$/u.test(name) : /^classes\d*\.dex$/u.test(name));
@@ -924,19 +1133,63 @@ const readAndroid = async (source, kind, entries, budget) => {
924
1133
  channel: androidChannelOf(manifest.metaData.get("com.hotupdater.CHANNEL")),
925
1134
  minBundleIdCandidates: minBundleIds,
926
1135
  fingerprintCandidates: fingerprints,
1136
+ sandbox: {
1137
+ code: strings.includes(SANDBOX_CODE_MARKER),
1138
+ declared: manifest.metaData.has(SANDBOX_META_DATA)
1139
+ },
1140
+ entry: {
1141
+ launchers: manifest.launchers,
1142
+ sandboxUrlScheme: androidSandboxUrlScheme(manifest)
1143
+ },
927
1144
  builtInBundle: bundle === void 0 ? null : {
928
1145
  path: bundle.name,
929
1146
  byteSize: bundle.uncompressedSize
930
1147
  }
931
1148
  };
932
1149
  };
1150
+ /**
1151
+ * The URL scheme an Android sandbox build registers, or null: the one its
1152
+ * activity's `SANDBOX_URL_SCHEME_META_DATA` names, when the activity's `VIEW`
1153
+ * filters take it too. An artifact built before the meta-data takes the one
1154
+ * with the derived scheme's prefix.
1155
+ */
1156
+ const androidSandboxUrlScheme = (manifest) => {
1157
+ const schemes = manifest.urlSchemes.get("com.hotupdater.HotUpdaterSandboxActivity") ?? [];
1158
+ const declared = manifest.componentMetaData.get(SANDBOX_ACTIVITY)?.get(SANDBOX_URL_SCHEME_META_DATA);
1159
+ if (declared === void 0) return schemes.find(isSandboxUrlScheme) ?? null;
1160
+ if (declared.type !== "string") return null;
1161
+ return schemes.includes(declared.value) ? declared.value : null;
1162
+ };
1163
+ /**
1164
+ * The sandbox URL scheme of an Info.plist, or null: the one
1165
+ * `SANDBOX_URL_SCHEME_INFO_PLIST_KEY` records, by `recordedSandboxUrlScheme`'s
1166
+ * rule. A prerelease's artifact, with no key, gives its named URL type's one
1167
+ * scheme, or, with no named type, one with the derived scheme's prefix.
1168
+ */
1169
+ const sandboxUrlSchemeIn = (info) => {
1170
+ const types = info["CFBundleURLTypes"];
1171
+ if (!Array.isArray(types)) return null;
1172
+ const schemesOf = (type) => {
1173
+ const schemes = type?.CFBundleURLSchemes;
1174
+ return Array.isArray(schemes) ? schemes.filter((scheme) => typeof scheme === "string") : [];
1175
+ };
1176
+ const named = types.filter((type) => type?.CFBundleURLName === SANDBOX_URL_TYPE_NAME);
1177
+ const recorded = recordedSandboxUrlScheme("HOT_UPDATER_SANDBOX_URL_SCHEME" in info ? info[SANDBOX_URL_SCHEME_INFO_PLIST_KEY] : void 0, named);
1178
+ if (recorded !== void 0) return recorded;
1179
+ if (named.length > 1) return null;
1180
+ if (named.length === 1) {
1181
+ const schemes = schemesOf(named[0]);
1182
+ return schemes.length === 1 ? schemes[0] : null;
1183
+ }
1184
+ return types.flatMap(schemesOf).find(isSandboxUrlScheme) ?? null;
1185
+ };
933
1186
  const stringValue = (value) => typeof value === "string" && value !== "" ? value : null;
934
1187
  const readIos = async (source, kind, entries, budget) => {
935
1188
  const infoPlist = kind === "ipa" ? /^Payload\/[^/]+\.app\/Info\.plist$/u : /^[^/]+\.app\/Info\.plist$/u;
936
1189
  const plistEntry = findZipEntry(entries, (name) => infoPlist.test(name));
937
1190
  if (plistEntry === void 0) throw new NativeArtifactError("UNREADABLE", kind === "ipa" ? "The .ipa has no Payload/<App>.app/Info.plist." : "The .app.zip has no <App>.app/Info.plist at its root.");
938
1191
  const appDirectory = plistEntry.name.slice(0, -10);
939
- const plist = parsePlist(await readZipEntry(source, plistEntry, METADATA_BYTES, budget));
1192
+ const plist = parsePlist(await readZipEntry(source, plistEntry, METADATA_BYTES$1, budget));
940
1193
  if (plist === null || typeof plist !== "object" || Array.isArray(plist)) throw new NativeArtifactError("UNREADABLE", "The app's Info.plist is not a dictionary.");
941
1194
  const info = plist;
942
1195
  const machO = (entry) => readMachOStrings((start, end) => readZipEntryRange(source, entry, start, end, budget), LENGTHS);
@@ -964,6 +1217,14 @@ const readIos = async (source, kind, entries, budget) => {
964
1217
  channel: channel === void 0 || channel === "" ? null : typeof channel === "string" ? channel : { unreadable: "HOT_UPDATER_CHANNEL is not a string" },
965
1218
  minBundleIdCandidates: minBundleIds,
966
1219
  fingerprintCandidates: fingerprints,
1220
+ sandbox: {
1221
+ code: strings.includes(SANDBOX_CODE_MARKER),
1222
+ declared: info[SANDBOX_INFO_PLIST_KEY] !== void 0
1223
+ },
1224
+ entry: {
1225
+ launchers: [],
1226
+ sandboxUrlScheme: sandboxUrlSchemeIn(info)
1227
+ },
967
1228
  builtInBundle: bundle === void 0 ? null : {
968
1229
  path: bundle.name,
969
1230
  byteSize: bundle.uncompressedSize
@@ -981,7 +1242,7 @@ const readNativeArtifact = async (source, fileName, { timeoutMs = DEFAULT_TIMEOU
981
1242
  const kind = nativeArtifactKindOf(fileName);
982
1243
  if (kind === null) throw new NativeArtifactError("UNSUPPORTED_FILE", `${fileName} is not an .ipa, .aab, .apk or a simulator .app. Import the artifact of a release build.`);
983
1244
  const budget = {
984
- remaining: READ_BUDGET_BYTES,
1245
+ remaining: READ_BUDGET_BYTES$1,
985
1246
  deadline: Date.now() + timeoutMs
986
1247
  };
987
1248
  const timed = {
@@ -1003,6 +1264,28 @@ const readNativeArtifact = async (source, fileName, { timeoutMs = DEFAULT_TIMEOU
1003
1264
  //#region src/nativeArtifact/checkNativeArtifact.ts
1004
1265
  /** The channel an app without a default channel reports. */
1005
1266
  const DEFAULT_CHANNEL = "production";
1267
+ /**
1268
+ * Why an artifact can't register as what it is: the sandbox layer must be
1269
+ * whole or absent, and a sandbox build must have the URL scheme its links
1270
+ * open and the launcher its screen takes. A sandbox build registers on any
1271
+ * channel, as any build does.
1272
+ */
1273
+ const sandboxArtifactProblem = ({ kind, platform, sandbox, entry }) => {
1274
+ const declaration = platform === "ios" ? "Info.plist key" : "manifest meta-data";
1275
+ if (sandbox.code !== sandbox.declared) return {
1276
+ code: "SANDBOX_MISMATCH",
1277
+ message: sandbox.code ? `The .${kind} has the sandbox layer's code, but no sandbox ${declaration}.\nBuild it again with hot-updater native-build.` : `The .${kind} has a sandbox ${declaration}, but not the sandbox layer's code.\nBuild it again with hot-updater native-build.`
1278
+ };
1279
+ if (sandbox.code && entry.sandboxUrlScheme === null) return {
1280
+ code: "SANDBOX_MISMATCH",
1281
+ message: `The .${kind} is a sandbox build with no sandbox URL scheme, so no link can open it.\nBuild it again with hot-updater native-build.`
1282
+ };
1283
+ if (sandbox.code && platform === "android" && (entry.launchers.length !== 1 || entry.launchers[0] !== "com.hotupdater.HotUpdaterSandboxActivity")) return {
1284
+ code: "SANDBOX_MISMATCH",
1285
+ message: `The .${kind} is a sandbox build, but its launcher is ${entry.launchers.join(", ") || "missing"}.\nBuild it again with hot-updater native-build.`
1286
+ };
1287
+ return null;
1288
+ };
1006
1289
  const isUnreadable = (value) => typeof value === "object" && value !== null && "unreadable" in value;
1007
1290
  /**
1008
1291
  * Whether a read artifact can be imported as a native build, whose built-in
@@ -1053,6 +1336,8 @@ const checkNativeArtifact = (info, { updateStrategy, appIds = [], channel: chann
1053
1336
  refuse("INVALID_SCOPE", `The app's channel ${JSON.stringify(channel)} is no channel a release can target: ${error instanceof Error ? error.message : String(error)}.`);
1054
1337
  }
1055
1338
  }
1339
+ const sandboxProblem = sandboxArtifactProblem(info);
1340
+ if (sandboxProblem !== null) problems.push(sandboxProblem);
1056
1341
  if (appIds.length > 0 && info.appId !== null && !appIds.includes(info.appId)) warnings.push({
1057
1342
  code: "APP_ID_MISMATCH",
1058
1343
  message: `The app is ${info.appId}, which no ${info.platform} scheme in nativeBuild names (${appIds.join(", ")}): check that it is this project's build.`
@@ -1074,7 +1359,10 @@ const checkNativeArtifact = (info, { updateStrategy, appIds = [], channel: chann
1074
1359
  channel,
1075
1360
  fingerprintHash,
1076
1361
  appVersion,
1077
- builtInBundlePath: info.builtInBundle.path
1362
+ nativeAppVersion: typeof info.appVersion === "string" && info.appVersion.trim() ? info.appVersion : null,
1363
+ builtInBundlePath: info.builtInBundle.path,
1364
+ sandbox: info.sandbox.code,
1365
+ sandboxUrlScheme: info.sandbox.code ? info.entry.sandboxUrlScheme : null
1078
1366
  }
1079
1367
  };
1080
1368
  };
@@ -1088,11 +1376,188 @@ const alreadyImportedProblem = (minBundleId, nativeBuildId) => ({
1088
1376
  message: nativeBuildId === null ? `The built-in bundle ${minBundleId} is already registered, as a bundle that is no native build's.` : `This build is already registered as native build ${nativeBuildId} (built-in bundle ${minBundleId}).`
1089
1377
  });
1090
1378
  //#endregion
1379
+ //#region src/nativeArtifact/iosInstall.ts
1380
+ const MiB = 1048576;
1381
+ /** The most an app's Info.plist or a provisioning profile holds here. */
1382
+ const METADATA_BYTES = 1 * MiB;
1383
+ /** The most reading what an install needs inflates, across every entry. */
1384
+ const READ_BUDGET_BYTES = 8 * MiB;
1385
+ /** How long reading what an install needs may take. */
1386
+ const READ_TIMEOUT_MS = 3e4;
1387
+ /** The extensions an app may carry, each with a profile to read. */
1388
+ const MAX_NESTED_PROFILES = 16;
1389
+ const APP_INFO_PLIST = /^Payload\/[^/]+\.app\/Info\.plist$/u;
1390
+ /**
1391
+ * What installs with the app and must list the device too: not a Watch app's
1392
+ * profile, which lists watches and installs on one.
1393
+ */
1394
+ const NESTED_PROFILE = /^Payload\/[^/]+\.app\/(?:PlugIns|Extensions|AppClips)\/[^/]+\.(?:appex|app)\/embedded\.mobileprovision$/u;
1395
+ /** A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. */
1396
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
1397
+ /**
1398
+ * The form two UDIDs compare in, or null for text that isn't one. Apple writes
1399
+ * them in either case, and App Store Connect takes the device's own.
1400
+ */
1401
+ const normalizeIosUdid = (value) => {
1402
+ const trimmed = value.trim();
1403
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
1404
+ };
1405
+ /**
1406
+ * The bytes from `<?xml` through `</plist>`, or null without both: a CMS
1407
+ * message, as a provisioning profile and a Profile Service answer are, holds
1408
+ * its plist as plain text among binary bytes.
1409
+ */
1410
+ const sliceEmbeddedPlist = (bytes) => {
1411
+ const text = new TextDecoder("latin1").decode(bytes);
1412
+ const start = text.indexOf("<?xml");
1413
+ if (start === -1) return null;
1414
+ const end = text.indexOf("</plist>", start);
1415
+ return end === -1 ? null : bytes.subarray(start, end + 8);
1416
+ };
1417
+ /**
1418
+ * The UDID in a Profile Service answer's body, or null when it has no one
1419
+ * well-formed UDID. It only finds the text: nothing here verifies the signature
1420
+ * around it, so nothing automated may trust the result.
1421
+ */
1422
+ const readProfileServiceUdid = (body) => {
1423
+ const plist = sliceEmbeddedPlist(body);
1424
+ if (plist === null) return null;
1425
+ const matches = [...new TextDecoder().decode(plist).matchAll(/<key>\s*UDID\s*<\/key>\s*<string>([^<]*)<\/string>/gu)];
1426
+ if (matches.length !== 1) return null;
1427
+ const udid = matches[0][1].trim();
1428
+ return normalizeIosUdid(udid) === null ? null : udid;
1429
+ };
1430
+ const unreadable = (message) => new NativeArtifactError("UNREADABLE", message);
1431
+ const isDict = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Uint8Array);
1432
+ const readProfile = (bytes, name) => {
1433
+ const plistBytes = sliceEmbeddedPlist(bytes);
1434
+ if (plistBytes === null) throw unreadable(`The archive's ${name} holds no property list.`);
1435
+ const plist = parsePlist(plistBytes);
1436
+ if (!isDict(plist)) throw unreadable(`The archive's ${name} is corrupt.`);
1437
+ const listed = plist["ProvisionedDevices"];
1438
+ if (listed !== void 0 && !Array.isArray(listed)) throw unreadable(`The archive's ${name} is corrupt.`);
1439
+ const devices = listed?.map((device) => {
1440
+ if (typeof device !== "string") throw unreadable(`The archive's ${name} is corrupt.`);
1441
+ return device.trim().toLowerCase();
1442
+ });
1443
+ const expiration = plist["ExpirationDate"];
1444
+ const expiresAtMs = typeof expiration === "string" ? Date.parse(expiration) : null;
1445
+ if (expiresAtMs !== null && Number.isNaN(expiresAtMs)) throw unreadable(`The archive's ${name} is corrupt.`);
1446
+ const entitlements = plist["Entitlements"];
1447
+ const applicationId = isDict(entitlements) ? entitlements["application-identifier"] : void 0;
1448
+ const bundleId = typeof applicationId === "string" ? applicationId.slice(applicationId.indexOf(".") + 1) : null;
1449
+ const teams = plist["TeamIdentifier"];
1450
+ const team = Array.isArray(teams) ? teams[0] : void 0;
1451
+ const uuid = plist["UUID"];
1452
+ return {
1453
+ allDevices: plist["ProvisionsAllDevices"] === true,
1454
+ devices: devices === void 0 ? null : new Set(devices),
1455
+ getTaskAllow: isDict(entitlements) && entitlements["get-task-allow"] === true,
1456
+ expiresAtMs,
1457
+ bundleId: bundleId === null || bundleId.includes("*") ? null : bundleId,
1458
+ applicationIdentifier: typeof applicationId === "string" ? applicationId : null,
1459
+ teamId: typeof team === "string" && team !== "" ? team : null,
1460
+ xcodeManaged: plist["IsXcodeManaged"] === true,
1461
+ uuid: typeof uuid === "string" && uuid !== "" ? uuid : null
1462
+ };
1463
+ };
1464
+ const distributionOf = (profile) => {
1465
+ if (profile === null) return "store";
1466
+ if (profile.allDevices) return "enterprise";
1467
+ if (profile.devices === null) return "store";
1468
+ return profile.getTaskAllow ? "development" : "ad-hoc";
1469
+ };
1470
+ /**
1471
+ * What a provisioning profile's bytes (a `.mobileprovision`, a CMS message
1472
+ * around a plist) say: the same reading an `.ipa`'s profiles get. It verifies
1473
+ * no signature. Throws `NativeArtifactError` for one it can't read.
1474
+ */
1475
+ const readProvisioningProfile = (bytes) => {
1476
+ const profile = readProfile(bytes, "provisioning profile");
1477
+ return {
1478
+ uuid: profile.uuid,
1479
+ distribution: distributionOf(profile),
1480
+ teamId: profile.teamId,
1481
+ applicationIdentifier: profile.applicationIdentifier,
1482
+ xcodeManaged: profile.xcodeManaged,
1483
+ devices: [...profile.devices ?? []].sort(),
1484
+ expiresAtMs: profile.expiresAtMs
1485
+ };
1486
+ };
1487
+ /**
1488
+ * What an `.ipa` installs as, reading only its directory, its app's Info.plist
1489
+ * and its provisioning profiles: a few requests of a remote file, whatever its
1490
+ * size. The `.ipa` is untrusted, and each part is bounded before it is read.
1491
+ * Throws `NativeArtifactError` for one it can't read.
1492
+ */
1493
+ const readIpaInstallInfo = async (source) => {
1494
+ const entries = await readZipDirectory(source);
1495
+ const infoPlists = filterZipEntries(entries, (name) => APP_INFO_PLIST.test(name));
1496
+ const infoEntry = infoPlists[0];
1497
+ if (infoEntry === void 0 || infoPlists.length > 1) throw unreadable("The .ipa has no one Payload/<App>.app/Info.plist.");
1498
+ const budget = {
1499
+ remaining: READ_BUDGET_BYTES,
1500
+ deadline: Date.now() + READ_TIMEOUT_MS
1501
+ };
1502
+ const read = (entry) => readZipEntry(source, entry, METADATA_BYTES, budget);
1503
+ const info = parsePlist(await read(infoEntry));
1504
+ if (!isDict(info)) throw unreadable("The app's Info.plist is corrupt.");
1505
+ const bundleId = info["CFBundleIdentifier"];
1506
+ const bundleVersion = info["CFBundleVersion"];
1507
+ if (typeof bundleId !== "string" || bundleId === "") throw unreadable("The app's Info.plist has no CFBundleIdentifier.");
1508
+ if (typeof bundleVersion !== "string" || bundleVersion === "") throw unreadable("The app's Info.plist has no CFBundleVersion.");
1509
+ const displayName = info["CFBundleDisplayName"];
1510
+ const bundleName = info["CFBundleName"];
1511
+ const title = typeof displayName === "string" && displayName !== "" ? displayName : typeof bundleName === "string" && bundleName !== "" ? bundleName : bundleId;
1512
+ const appDirectory = infoEntry.name.slice(0, -10);
1513
+ const profileEntry = findZipEntry(entries, `${appDirectory}embedded.mobileprovision`);
1514
+ const nestedEntries = filterZipEntries(entries, (name) => name.startsWith(appDirectory) && NESTED_PROFILE.test(name));
1515
+ if (nestedEntries.length > MAX_NESTED_PROFILES) throw unreadable(`The app has more than ${MAX_NESTED_PROFILES} extensions with profiles.`);
1516
+ const profile = profileEntry === void 0 ? null : readProfile(await read(profileEntry), profileEntry.name);
1517
+ const nested = [];
1518
+ for (const entry of nestedEntries) nested.push(readProfile(await read(entry), entry.name));
1519
+ const distribution = distributionOf(profile);
1520
+ const profiles = profile === null ? nested : [profile, ...nested];
1521
+ const listDevices = distribution === "ad-hoc" || distribution === "development";
1522
+ const lists = profiles.flatMap(({ allDevices, devices }) => allDevices ? [] : [devices ?? /* @__PURE__ */ new Set()]);
1523
+ const expiries = profiles.flatMap(({ expiresAtMs }) => expiresAtMs === null ? [] : [expiresAtMs]);
1524
+ return {
1525
+ bundleId,
1526
+ bundleVersion,
1527
+ title,
1528
+ distribution,
1529
+ devices: listDevices ? [...lists[0] ?? []].filter((udid) => lists.every((list) => list.has(udid))).sort() : [],
1530
+ expiresAtMs: expiries.length === 0 ? null : Math.min(...expiries),
1531
+ profileBundleIds: [.../* @__PURE__ */ new Set([bundleId, ...profiles.flatMap((item) => item.bundleId ?? [])])],
1532
+ teamId: profile?.teamId ?? null
1533
+ };
1534
+ };
1535
+ //#endregion
1091
1536
  exports.NativeArtifactError = NativeArtifactError;
1537
+ exports.SANDBOX_ACTIVITY = SANDBOX_ACTIVITY;
1538
+ exports.SANDBOX_APPLICATION_ID_SUFFIX = SANDBOX_APPLICATION_ID_SUFFIX;
1539
+ exports.SANDBOX_CODE_MARKER = SANDBOX_CODE_MARKER;
1540
+ exports.SANDBOX_INFO_PLIST_KEY = SANDBOX_INFO_PLIST_KEY;
1541
+ exports.SANDBOX_META_DATA = SANDBOX_META_DATA;
1542
+ exports.SANDBOX_URL_SCHEME_INFO_PLIST_KEY = SANDBOX_URL_SCHEME_INFO_PLIST_KEY;
1543
+ exports.SANDBOX_URL_SCHEME_META_DATA = SANDBOX_URL_SCHEME_META_DATA;
1544
+ exports.SANDBOX_URL_TYPE_NAME = SANDBOX_URL_TYPE_NAME;
1092
1545
  exports.alreadyImportedProblem = alreadyImportedProblem;
1093
1546
  exports.blobSource = blobSource;
1094
1547
  exports.checkNativeArtifact = checkNativeArtifact;
1548
+ exports.createPreviewLink = createPreviewLink;
1095
1549
  exports.findZipEntry = findZipEntry;
1550
+ exports.isConfigurableSandboxUrlScheme = isConfigurableSandboxUrlScheme;
1551
+ exports.isRecordedUrlSchemeSyntax = isRecordedUrlSchemeSyntax;
1552
+ exports.isSandboxUrlScheme = isSandboxUrlScheme;
1553
+ exports.normalizeIosUdid = normalizeIosUdid;
1096
1554
  exports.openZipEntry = openZipEntry;
1555
+ exports.parsePreviewLink = parsePreviewLink;
1556
+ exports.readIpaInstallInfo = readIpaInstallInfo;
1097
1557
  exports.readNativeArtifact = readNativeArtifact;
1558
+ exports.readProfileServiceUdid = readProfileServiceUdid;
1559
+ exports.readProvisioningProfile = readProvisioningProfile;
1098
1560
  exports.readZipDirectory = readZipDirectory;
1561
+ exports.recordedSandboxUrlScheme = recordedSandboxUrlScheme;
1562
+ exports.sandboxArtifactProblem = sandboxArtifactProblem;
1563
+ exports.sandboxUrlSchemeOf = sandboxUrlSchemeOf;