@hot-updater/protocol 1.2.0-rc.3 → 1.2.0-rc.31

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,165 @@ 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_CHANNEL_PREFIX = "sandbox-";
628
+ const SANDBOX_URL_SCHEME_PREFIX = "hu-sandbox-";
629
+ /**
630
+ * The channel a scheme's sandbox build registers on. `sandbox-*` is reserved:
631
+ * only a sandbox build registers there, and the registry records `sandbox` on
632
+ * it.
633
+ */
634
+ const sandboxChannelOf = (scheme) => `${SANDBOX_CHANNEL_PREFIX}${scheme}`;
635
+ /** Whether a channel is reserved for sandbox builds. */
636
+ const isSandboxChannel = (channel) => channel.startsWith(SANDBOX_CHANNEL_PREFIX);
637
+ /**
638
+ * The URL scheme a sandbox build registers when its scheme sets none, derived
639
+ * from the app's ID: the app's own scheme would ask which app to open beside
640
+ * the store app.
641
+ */
642
+ const sandboxUrlSchemeOf = (appId) => `${SANDBOX_URL_SCHEME_PREFIX}${appId.toLowerCase().replace(/[^a-z0-9]+/gu, "-")}`;
643
+ /**
644
+ * Whether a URL scheme has the prefix of the derived one: how an artifact built
645
+ * before the URL scheme could be set is read, which registered no other.
646
+ */
647
+ const isSandboxUrlScheme = (scheme) => scheme.toLowerCase().startsWith(SANDBOX_URL_SCHEME_PREFIX);
648
+ const CONFIGURED_URL_SCHEME = /^[a-z][a-z0-9+.-]{0,63}$/u;
649
+ const RESERVED_URL_SCHEMES = /* @__PURE__ */ new Set([
650
+ "http",
651
+ "https",
652
+ "file",
653
+ "data",
654
+ "javascript",
655
+ "true",
656
+ "false"
657
+ ]);
658
+ /**
659
+ * Whether `sandbox: { urlScheme }` can name a URL scheme: lower case, a letter
660
+ * then up to 63 letters, digits, `+`, `.` or `-`, none the system or a browser
661
+ * owns, and neither `true` nor `false`, which Android's manifest can't hold as
662
+ * a string.
663
+ */
664
+ const isConfigurableSandboxUrlScheme = (urlScheme) => CONFIGURED_URL_SCHEME.test(urlScheme) && !RESERVED_URL_SCHEMES.has(urlScheme);
665
+ /**
666
+ * The link a preview QR holds. `urlScheme` is the one the sandbox build
667
+ * registered; without it, the one derived from `appId`, the scheme's
668
+ * `bundleIdentifier` or `packageName`: the ID before the Android sandbox's
669
+ * `.sandbox` suffix.
670
+ */
671
+ const createPreviewLink = ({ urlScheme, appId, channel, fingerprintHash, platform }) => {
672
+ require_uuid.assertCanonicalChannelName(channel);
673
+ if (platform !== void 0 && !PREVIEW_LINK_PLATFORMS.has(platform)) throw new Error(`A preview link's platform is ios or android, not ${platform}.`);
674
+ const link = `${(urlScheme ?? sandboxUrlSchemeOf(appId)).toLowerCase()}://hot-updater/preview?channel=${encodeURIComponent(channel)}&fingerprint=${encodeURIComponent(fingerprintHash)}`;
675
+ return platform === void 0 ? link : `${link}&platform=${platform}`;
676
+ };
677
+ /** Any URL scheme: which app's it is, the app that opens the link decides. */
678
+ const PREVIEW_LINK = /^([a-z][a-z0-9+.-]*):\/\/hot-updater\/preview\?([^#]*)$/iu;
679
+ /**
680
+ * A URL scheme in ASCII alone: case folding lets `/iu` match `K` (Kelvin) or
681
+ * `ſ` as a letter.
682
+ */
683
+ const ASCII_URL_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/;
684
+ const MAX_FINGERPRINT_LENGTH = 256;
685
+ const PREVIEW_LINK_PLATFORMS = /* @__PURE__ */ new Set(["ios", "android"]);
686
+ /**
687
+ * What a preview link says, or null for anything else: another shape, a
688
+ * repeated or missing parameter, or a channel no release can target. It takes
689
+ * any URL scheme: a sandbox build refuses a link of another scheme than its
690
+ * own. A `platform` other than `ios` or `android` reads as none. Native code
691
+ * parses it the same way before any JavaScript runs, in HotUpdaterSandboxLink,
692
+ * and shares the vectors in test-utils' `sandbox-preview-links.json`.
693
+ */
694
+ const parsePreviewLink = (link) => {
695
+ const match = PREVIEW_LINK.exec(link);
696
+ if (match === null || !ASCII_URL_SCHEME.test(match[1])) return null;
697
+ const parameters = /* @__PURE__ */ new Map();
698
+ for (const parameter of match[2].split("&")) {
699
+ const separator = parameter.indexOf("=");
700
+ if (separator === -1) return null;
701
+ const name = parameter.slice(0, separator);
702
+ if (parameters.has(name)) return null;
703
+ let value;
704
+ try {
705
+ value = decodeURIComponent(parameter.slice(separator + 1));
706
+ } catch {
707
+ return null;
708
+ }
709
+ parameters.set(name, value);
710
+ }
711
+ const channel = parameters.get("channel");
712
+ const fingerprintHash = parameters.get("fingerprint");
713
+ if (channel === void 0 || fingerprintHash === void 0 || fingerprintHash.length === 0 || fingerprintHash.length > MAX_FINGERPRINT_LENGTH) return null;
714
+ try {
715
+ require_uuid.assertCanonicalChannelName(channel);
716
+ } catch {
717
+ return null;
718
+ }
719
+ const platform = parameters.get("platform");
720
+ return {
721
+ urlScheme: match[1].toLowerCase(),
722
+ channel,
723
+ fingerprintHash,
724
+ ...platform !== void 0 && PREVIEW_LINK_PLATFORMS.has(platform) ? { platform } : {}
725
+ };
726
+ };
727
+ //#endregion
514
728
  //#region src/nativeArtifact/strings.ts
515
729
  const view$1 = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
516
730
  /** Bytes that are all ASCII, as text; null otherwise. */
@@ -656,7 +870,7 @@ const UINT32_MAX = 4294967295;
656
870
  const EOCD_SEARCH_LENGTH = 65557;
657
871
  /** How much compressed data one read takes. */
658
872
  const READ_CHUNK = 1048576;
659
- const MiB$1 = 1048576;
873
+ const MiB$2 = 1048576;
660
874
  /**
661
875
  * What an archive may hold before it is refused as no artifact: an upload is
662
876
  * untrusted, so a crafted directory or entry (a zip bomb) stops here, not
@@ -664,10 +878,10 @@ const MiB$1 = 1048576;
664
878
  */
665
879
  const ZIP_LIMITS = {
666
880
  /** The central directory. */
667
- directoryBytes: 64 * MiB$1,
881
+ directoryBytes: 64 * MiB$2,
668
882
  entries: 5e5,
669
883
  /** An entry streamed out whole, such as the built-in bundle. */
670
- entryBytes: 1024 * MiB$1
884
+ entryBytes: 1024 * MiB$2
671
885
  };
672
886
  const UNIX_HOST = 3;
673
887
  const S_IFMT = 61440;
@@ -775,7 +989,7 @@ const filterZipEntries = (entries, match) => {
775
989
  const assertReadable = (entry) => {
776
990
  if (entry.symlink) throw new NativeArtifactError("UNREADABLE", `The archive's ${entry.name} is a symbolic link, not a file.`);
777
991
  };
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.`);
992
+ 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
993
  /** Where an entry's data starts, past its local header. */
780
994
  const dataOffsetOf = async (source, entry) => {
781
995
  const local = view(await source.read(entry.localHeaderOffset, 30));
@@ -860,13 +1074,13 @@ const readZipEntry = (source, entry, maxBytes, budget) => {
860
1074
  };
861
1075
  //#endregion
862
1076
  //#region src/nativeArtifact/readNativeArtifact.ts
863
- const MiB = 1048576;
1077
+ const MiB$1 = 1048576;
864
1078
  /** The most a manifest or an Info.plist holds. */
865
- const METADATA_BYTES = 16 * MiB;
1079
+ const METADATA_BYTES$1 = 16 * MiB$1;
866
1080
  /** The most one dex file holds. */
867
- const DEX_BYTES = 256 * MiB;
1081
+ const DEX_BYTES = 256 * MiB$1;
868
1082
  /** The most reading one artifact inflates, across every entry it reads. */
869
- const READ_BUDGET_BYTES = 2048 * MiB;
1083
+ const READ_BUDGET_BYTES$1 = 2048 * MiB$1;
870
1084
  /** How long reading one artifact may take. */
871
1085
  const DEFAULT_TIMEOUT_MS = 12e4;
872
1086
  /** Where each kind of artifact packs its built-in bundle. */
@@ -879,7 +1093,11 @@ const nativeArtifactKindOf = (fileName) => {
879
1093
  };
880
1094
  const UUID_LENGTH = 36;
881
1095
  const SHA256_HEX = /^[0-9a-f]{64}$/u;
882
- const LENGTHS = /* @__PURE__ */ new Set([UUID_LENGTH, 64]);
1096
+ const LENGTHS = /* @__PURE__ */ new Set([
1097
+ UUID_LENGTH,
1098
+ 64,
1099
+ 32
1100
+ ]);
883
1101
  const unique = (values) => [...new Set(values)].sort();
884
1102
  const candidatesOf = (strings) => {
885
1103
  const all = [...strings];
@@ -908,7 +1126,7 @@ const androidChannelOf = (value) => {
908
1126
  const readAndroid = async (source, kind, entries, budget) => {
909
1127
  const manifestEntry = findZipEntry(entries, kind === "aab" ? "base/manifest/AndroidManifest.xml" : "AndroidManifest.xml");
910
1128
  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);
1129
+ const manifestBytes = await readZipEntry(source, manifestEntry, METADATA_BYTES$1, budget);
912
1130
  const manifest = readAndroidManifest(kind === "aab" ? parseProtoManifest(manifestBytes) : parseBinaryManifest(manifestBytes));
913
1131
  const strings = [];
914
1132
  const dexes = filterZipEntries(entries, (name) => kind === "aab" ? /^base\/dex\/classes\d*\.dex$/u.test(name) : /^classes\d*\.dex$/u.test(name));
@@ -924,19 +1142,63 @@ const readAndroid = async (source, kind, entries, budget) => {
924
1142
  channel: androidChannelOf(manifest.metaData.get("com.hotupdater.CHANNEL")),
925
1143
  minBundleIdCandidates: minBundleIds,
926
1144
  fingerprintCandidates: fingerprints,
1145
+ sandbox: {
1146
+ code: strings.includes(SANDBOX_CODE_MARKER),
1147
+ declared: manifest.metaData.has(SANDBOX_META_DATA)
1148
+ },
1149
+ entry: {
1150
+ launchers: manifest.launchers,
1151
+ sandboxUrlScheme: androidSandboxUrlScheme(manifest)
1152
+ },
927
1153
  builtInBundle: bundle === void 0 ? null : {
928
1154
  path: bundle.name,
929
1155
  byteSize: bundle.uncompressedSize
930
1156
  }
931
1157
  };
932
1158
  };
1159
+ /**
1160
+ * The URL scheme an Android sandbox build registers, or null: the one its
1161
+ * activity's `SANDBOX_URL_SCHEME_META_DATA` names, when the activity's `VIEW`
1162
+ * filters take it too. An artifact built before the meta-data takes the one
1163
+ * with the derived scheme's prefix.
1164
+ */
1165
+ const androidSandboxUrlScheme = (manifest) => {
1166
+ const schemes = manifest.urlSchemes.get("com.hotupdater.HotUpdaterSandboxActivity") ?? [];
1167
+ const declared = manifest.componentMetaData.get(SANDBOX_ACTIVITY)?.get(SANDBOX_URL_SCHEME_META_DATA);
1168
+ if (declared === void 0) return schemes.find(isSandboxUrlScheme) ?? null;
1169
+ if (declared.type !== "string") return null;
1170
+ return schemes.includes(declared.value) ? declared.value : null;
1171
+ };
1172
+ /**
1173
+ * The sandbox URL scheme of an Info.plist, or null: the one
1174
+ * `SANDBOX_URL_SCHEME_INFO_PLIST_KEY` records, by `recordedSandboxUrlScheme`'s
1175
+ * rule. A prerelease's artifact, with no key, gives its named URL type's one
1176
+ * scheme, or, with no named type, one with the derived scheme's prefix.
1177
+ */
1178
+ const sandboxUrlSchemeIn = (info) => {
1179
+ const types = info["CFBundleURLTypes"];
1180
+ if (!Array.isArray(types)) return null;
1181
+ const schemesOf = (type) => {
1182
+ const schemes = type?.CFBundleURLSchemes;
1183
+ return Array.isArray(schemes) ? schemes.filter((scheme) => typeof scheme === "string") : [];
1184
+ };
1185
+ const named = types.filter((type) => type?.CFBundleURLName === SANDBOX_URL_TYPE_NAME);
1186
+ const recorded = recordedSandboxUrlScheme("HOT_UPDATER_SANDBOX_URL_SCHEME" in info ? info[SANDBOX_URL_SCHEME_INFO_PLIST_KEY] : void 0, named);
1187
+ if (recorded !== void 0) return recorded;
1188
+ if (named.length > 1) return null;
1189
+ if (named.length === 1) {
1190
+ const schemes = schemesOf(named[0]);
1191
+ return schemes.length === 1 ? schemes[0] : null;
1192
+ }
1193
+ return types.flatMap(schemesOf).find(isSandboxUrlScheme) ?? null;
1194
+ };
933
1195
  const stringValue = (value) => typeof value === "string" && value !== "" ? value : null;
934
1196
  const readIos = async (source, kind, entries, budget) => {
935
1197
  const infoPlist = kind === "ipa" ? /^Payload\/[^/]+\.app\/Info\.plist$/u : /^[^/]+\.app\/Info\.plist$/u;
936
1198
  const plistEntry = findZipEntry(entries, (name) => infoPlist.test(name));
937
1199
  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
1200
  const appDirectory = plistEntry.name.slice(0, -10);
939
- const plist = parsePlist(await readZipEntry(source, plistEntry, METADATA_BYTES, budget));
1201
+ const plist = parsePlist(await readZipEntry(source, plistEntry, METADATA_BYTES$1, budget));
940
1202
  if (plist === null || typeof plist !== "object" || Array.isArray(plist)) throw new NativeArtifactError("UNREADABLE", "The app's Info.plist is not a dictionary.");
941
1203
  const info = plist;
942
1204
  const machO = (entry) => readMachOStrings((start, end) => readZipEntryRange(source, entry, start, end, budget), LENGTHS);
@@ -964,6 +1226,14 @@ const readIos = async (source, kind, entries, budget) => {
964
1226
  channel: channel === void 0 || channel === "" ? null : typeof channel === "string" ? channel : { unreadable: "HOT_UPDATER_CHANNEL is not a string" },
965
1227
  minBundleIdCandidates: minBundleIds,
966
1228
  fingerprintCandidates: fingerprints,
1229
+ sandbox: {
1230
+ code: strings.includes(SANDBOX_CODE_MARKER),
1231
+ declared: info[SANDBOX_INFO_PLIST_KEY] !== void 0
1232
+ },
1233
+ entry: {
1234
+ launchers: [],
1235
+ sandboxUrlScheme: sandboxUrlSchemeIn(info)
1236
+ },
967
1237
  builtInBundle: bundle === void 0 ? null : {
968
1238
  path: bundle.name,
969
1239
  byteSize: bundle.uncompressedSize
@@ -981,7 +1251,7 @@ const readNativeArtifact = async (source, fileName, { timeoutMs = DEFAULT_TIMEOU
981
1251
  const kind = nativeArtifactKindOf(fileName);
982
1252
  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
1253
  const budget = {
984
- remaining: READ_BUDGET_BYTES,
1254
+ remaining: READ_BUDGET_BYTES$1,
985
1255
  deadline: Date.now() + timeoutMs
986
1256
  };
987
1257
  const timed = {
@@ -1003,6 +1273,34 @@ const readNativeArtifact = async (source, fileName, { timeoutMs = DEFAULT_TIMEOU
1003
1273
  //#region src/nativeArtifact/checkNativeArtifact.ts
1004
1274
  /** The channel an app without a default channel reports. */
1005
1275
  const DEFAULT_CHANNEL = "production";
1276
+ /**
1277
+ * Why an artifact can't register on `channel`: the sandbox layer must be whole
1278
+ * or absent, and only a sandbox build registers on a `sandbox-*` channel.
1279
+ */
1280
+ const sandboxArtifactProblem = ({ kind, platform, sandbox, entry }, channel) => {
1281
+ const declaration = platform === "ios" ? "Info.plist key" : "manifest meta-data";
1282
+ if (sandbox.code !== sandbox.declared) return {
1283
+ code: "SANDBOX_MISMATCH",
1284
+ 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.`
1285
+ };
1286
+ if (sandbox.code && entry.sandboxUrlScheme === null) return {
1287
+ code: "SANDBOX_MISMATCH",
1288
+ 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.`
1289
+ };
1290
+ if (sandbox.code && platform === "android" && (entry.launchers.length !== 1 || entry.launchers[0] !== "com.hotupdater.HotUpdaterSandboxActivity")) return {
1291
+ code: "SANDBOX_MISMATCH",
1292
+ message: `The .${kind} is a sandbox build, but its launcher is ${entry.launchers.join(", ") || "missing"}.\nBuild it again with hot-updater native-build.`
1293
+ };
1294
+ if (sandbox.code && !isSandboxChannel(channel)) return {
1295
+ code: "SANDBOX_MISMATCH",
1296
+ message: `The .${kind} is a sandbox build, which can't register on channel ${channel}.\nUse a sandbox-<scheme> channel.`
1297
+ };
1298
+ if (!sandbox.code && isSandboxChannel(channel)) return {
1299
+ code: "SANDBOX_MISMATCH",
1300
+ message: `Channel ${channel} is reserved for sandbox builds, and the .${kind} isn't one.\nUse another channel, or build it with sandbox: true.`
1301
+ };
1302
+ return null;
1303
+ };
1006
1304
  const isUnreadable = (value) => typeof value === "object" && value !== null && "unreadable" in value;
1007
1305
  /**
1008
1306
  * Whether a read artifact can be imported as a native build, whose built-in
@@ -1053,6 +1351,8 @@ const checkNativeArtifact = (info, { updateStrategy, appIds = [], channel: chann
1053
1351
  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
1352
  }
1055
1353
  }
1354
+ const sandboxProblem = sandboxArtifactProblem(info, channel);
1355
+ if (sandboxProblem !== null) problems.push(sandboxProblem);
1056
1356
  if (appIds.length > 0 && info.appId !== null && !appIds.includes(info.appId)) warnings.push({
1057
1357
  code: "APP_ID_MISMATCH",
1058
1358
  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 +1374,10 @@ const checkNativeArtifact = (info, { updateStrategy, appIds = [], channel: chann
1074
1374
  channel,
1075
1375
  fingerprintHash,
1076
1376
  appVersion,
1077
- builtInBundlePath: info.builtInBundle.path
1377
+ nativeAppVersion: typeof info.appVersion === "string" && info.appVersion.trim() ? info.appVersion : null,
1378
+ builtInBundlePath: info.builtInBundle.path,
1379
+ sandbox: info.sandbox.code,
1380
+ sandboxUrlScheme: info.sandbox.code ? info.entry.sandboxUrlScheme : null
1078
1381
  }
1079
1382
  };
1080
1383
  };
@@ -1088,11 +1391,190 @@ const alreadyImportedProblem = (minBundleId, nativeBuildId) => ({
1088
1391
  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
1392
  });
1090
1393
  //#endregion
1394
+ //#region src/nativeArtifact/iosInstall.ts
1395
+ const MiB = 1048576;
1396
+ /** The most an app's Info.plist or a provisioning profile holds here. */
1397
+ const METADATA_BYTES = 1 * MiB;
1398
+ /** The most reading what an install needs inflates, across every entry. */
1399
+ const READ_BUDGET_BYTES = 8 * MiB;
1400
+ /** How long reading what an install needs may take. */
1401
+ const READ_TIMEOUT_MS = 3e4;
1402
+ /** The extensions an app may carry, each with a profile to read. */
1403
+ const MAX_NESTED_PROFILES = 16;
1404
+ const APP_INFO_PLIST = /^Payload\/[^/]+\.app\/Info\.plist$/u;
1405
+ /**
1406
+ * What installs with the app and must list the device too: not a Watch app's
1407
+ * profile, which lists watches and installs on one.
1408
+ */
1409
+ const NESTED_PROFILE = /^Payload\/[^/]+\.app\/(?:PlugIns|Extensions|AppClips)\/[^/]+\.(?:appex|app)\/embedded\.mobileprovision$/u;
1410
+ /** A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. */
1411
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
1412
+ /**
1413
+ * The form two UDIDs compare in, or null for text that isn't one. Apple writes
1414
+ * them in either case, and App Store Connect takes the device's own.
1415
+ */
1416
+ const normalizeIosUdid = (value) => {
1417
+ const trimmed = value.trim();
1418
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
1419
+ };
1420
+ /**
1421
+ * The bytes from `<?xml` through `</plist>`, or null without both: a CMS
1422
+ * message, as a provisioning profile and a Profile Service answer are, holds
1423
+ * its plist as plain text among binary bytes.
1424
+ */
1425
+ const sliceEmbeddedPlist = (bytes) => {
1426
+ const text = new TextDecoder("latin1").decode(bytes);
1427
+ const start = text.indexOf("<?xml");
1428
+ if (start === -1) return null;
1429
+ const end = text.indexOf("</plist>", start);
1430
+ return end === -1 ? null : bytes.subarray(start, end + 8);
1431
+ };
1432
+ /**
1433
+ * The UDID in a Profile Service answer's body, or null when it has no one
1434
+ * well-formed UDID. It only finds the text: nothing here verifies the signature
1435
+ * around it, so nothing automated may trust the result.
1436
+ */
1437
+ const readProfileServiceUdid = (body) => {
1438
+ const plist = sliceEmbeddedPlist(body);
1439
+ if (plist === null) return null;
1440
+ const matches = [...new TextDecoder().decode(plist).matchAll(/<key>\s*UDID\s*<\/key>\s*<string>([^<]*)<\/string>/gu)];
1441
+ if (matches.length !== 1) return null;
1442
+ const udid = matches[0][1].trim();
1443
+ return normalizeIosUdid(udid) === null ? null : udid;
1444
+ };
1445
+ const unreadable = (message) => new NativeArtifactError("UNREADABLE", message);
1446
+ const isDict = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Uint8Array);
1447
+ const readProfile = (bytes, name) => {
1448
+ const plistBytes = sliceEmbeddedPlist(bytes);
1449
+ if (plistBytes === null) throw unreadable(`The archive's ${name} holds no property list.`);
1450
+ const plist = parsePlist(plistBytes);
1451
+ if (!isDict(plist)) throw unreadable(`The archive's ${name} is corrupt.`);
1452
+ const listed = plist["ProvisionedDevices"];
1453
+ if (listed !== void 0 && !Array.isArray(listed)) throw unreadable(`The archive's ${name} is corrupt.`);
1454
+ const devices = listed?.map((device) => {
1455
+ if (typeof device !== "string") throw unreadable(`The archive's ${name} is corrupt.`);
1456
+ return device.trim().toLowerCase();
1457
+ });
1458
+ const expiration = plist["ExpirationDate"];
1459
+ const expiresAtMs = typeof expiration === "string" ? Date.parse(expiration) : null;
1460
+ if (expiresAtMs !== null && Number.isNaN(expiresAtMs)) throw unreadable(`The archive's ${name} is corrupt.`);
1461
+ const entitlements = plist["Entitlements"];
1462
+ const applicationId = isDict(entitlements) ? entitlements["application-identifier"] : void 0;
1463
+ const bundleId = typeof applicationId === "string" ? applicationId.slice(applicationId.indexOf(".") + 1) : null;
1464
+ const teams = plist["TeamIdentifier"];
1465
+ const team = Array.isArray(teams) ? teams[0] : void 0;
1466
+ const uuid = plist["UUID"];
1467
+ return {
1468
+ allDevices: plist["ProvisionsAllDevices"] === true,
1469
+ devices: devices === void 0 ? null : new Set(devices),
1470
+ getTaskAllow: isDict(entitlements) && entitlements["get-task-allow"] === true,
1471
+ expiresAtMs,
1472
+ bundleId: bundleId === null || bundleId.includes("*") ? null : bundleId,
1473
+ applicationIdentifier: typeof applicationId === "string" ? applicationId : null,
1474
+ teamId: typeof team === "string" && team !== "" ? team : null,
1475
+ xcodeManaged: plist["IsXcodeManaged"] === true,
1476
+ uuid: typeof uuid === "string" && uuid !== "" ? uuid : null
1477
+ };
1478
+ };
1479
+ const distributionOf = (profile) => {
1480
+ if (profile === null) return "store";
1481
+ if (profile.allDevices) return "enterprise";
1482
+ if (profile.devices === null) return "store";
1483
+ return profile.getTaskAllow ? "development" : "ad-hoc";
1484
+ };
1485
+ /**
1486
+ * What a provisioning profile's bytes (a `.mobileprovision`, a CMS message
1487
+ * around a plist) say: the same reading an `.ipa`'s profiles get. It verifies
1488
+ * no signature. Throws `NativeArtifactError` for one it can't read.
1489
+ */
1490
+ const readProvisioningProfile = (bytes) => {
1491
+ const profile = readProfile(bytes, "provisioning profile");
1492
+ return {
1493
+ uuid: profile.uuid,
1494
+ distribution: distributionOf(profile),
1495
+ teamId: profile.teamId,
1496
+ applicationIdentifier: profile.applicationIdentifier,
1497
+ xcodeManaged: profile.xcodeManaged,
1498
+ devices: [...profile.devices ?? []].sort(),
1499
+ expiresAtMs: profile.expiresAtMs
1500
+ };
1501
+ };
1502
+ /**
1503
+ * What an `.ipa` installs as, reading only its directory, its app's Info.plist
1504
+ * and its provisioning profiles: a few requests of a remote file, whatever its
1505
+ * size. The `.ipa` is untrusted, and each part is bounded before it is read.
1506
+ * Throws `NativeArtifactError` for one it can't read.
1507
+ */
1508
+ const readIpaInstallInfo = async (source) => {
1509
+ const entries = await readZipDirectory(source);
1510
+ const infoPlists = filterZipEntries(entries, (name) => APP_INFO_PLIST.test(name));
1511
+ const infoEntry = infoPlists[0];
1512
+ if (infoEntry === void 0 || infoPlists.length > 1) throw unreadable("The .ipa has no one Payload/<App>.app/Info.plist.");
1513
+ const budget = {
1514
+ remaining: READ_BUDGET_BYTES,
1515
+ deadline: Date.now() + READ_TIMEOUT_MS
1516
+ };
1517
+ const read = (entry) => readZipEntry(source, entry, METADATA_BYTES, budget);
1518
+ const info = parsePlist(await read(infoEntry));
1519
+ if (!isDict(info)) throw unreadable("The app's Info.plist is corrupt.");
1520
+ const bundleId = info["CFBundleIdentifier"];
1521
+ const bundleVersion = info["CFBundleVersion"];
1522
+ if (typeof bundleId !== "string" || bundleId === "") throw unreadable("The app's Info.plist has no CFBundleIdentifier.");
1523
+ if (typeof bundleVersion !== "string" || bundleVersion === "") throw unreadable("The app's Info.plist has no CFBundleVersion.");
1524
+ const displayName = info["CFBundleDisplayName"];
1525
+ const bundleName = info["CFBundleName"];
1526
+ const title = typeof displayName === "string" && displayName !== "" ? displayName : typeof bundleName === "string" && bundleName !== "" ? bundleName : bundleId;
1527
+ const appDirectory = infoEntry.name.slice(0, -10);
1528
+ const profileEntry = findZipEntry(entries, `${appDirectory}embedded.mobileprovision`);
1529
+ const nestedEntries = filterZipEntries(entries, (name) => name.startsWith(appDirectory) && NESTED_PROFILE.test(name));
1530
+ if (nestedEntries.length > MAX_NESTED_PROFILES) throw unreadable(`The app has more than ${MAX_NESTED_PROFILES} extensions with profiles.`);
1531
+ const profile = profileEntry === void 0 ? null : readProfile(await read(profileEntry), profileEntry.name);
1532
+ const nested = [];
1533
+ for (const entry of nestedEntries) nested.push(readProfile(await read(entry), entry.name));
1534
+ const distribution = distributionOf(profile);
1535
+ const profiles = profile === null ? nested : [profile, ...nested];
1536
+ const listDevices = distribution === "ad-hoc" || distribution === "development";
1537
+ const lists = profiles.flatMap(({ allDevices, devices }) => allDevices ? [] : [devices ?? /* @__PURE__ */ new Set()]);
1538
+ const expiries = profiles.flatMap(({ expiresAtMs }) => expiresAtMs === null ? [] : [expiresAtMs]);
1539
+ return {
1540
+ bundleId,
1541
+ bundleVersion,
1542
+ title,
1543
+ distribution,
1544
+ devices: listDevices ? [...lists[0] ?? []].filter((udid) => lists.every((list) => list.has(udid))).sort() : [],
1545
+ expiresAtMs: expiries.length === 0 ? null : Math.min(...expiries),
1546
+ profileBundleIds: [.../* @__PURE__ */ new Set([bundleId, ...profiles.flatMap((item) => item.bundleId ?? [])])],
1547
+ teamId: profile?.teamId ?? null
1548
+ };
1549
+ };
1550
+ //#endregion
1091
1551
  exports.NativeArtifactError = NativeArtifactError;
1552
+ exports.SANDBOX_ACTIVITY = SANDBOX_ACTIVITY;
1553
+ exports.SANDBOX_APPLICATION_ID_SUFFIX = SANDBOX_APPLICATION_ID_SUFFIX;
1554
+ exports.SANDBOX_CODE_MARKER = SANDBOX_CODE_MARKER;
1555
+ exports.SANDBOX_INFO_PLIST_KEY = SANDBOX_INFO_PLIST_KEY;
1556
+ exports.SANDBOX_META_DATA = SANDBOX_META_DATA;
1557
+ exports.SANDBOX_URL_SCHEME_INFO_PLIST_KEY = SANDBOX_URL_SCHEME_INFO_PLIST_KEY;
1558
+ exports.SANDBOX_URL_SCHEME_META_DATA = SANDBOX_URL_SCHEME_META_DATA;
1559
+ exports.SANDBOX_URL_TYPE_NAME = SANDBOX_URL_TYPE_NAME;
1092
1560
  exports.alreadyImportedProblem = alreadyImportedProblem;
1093
1561
  exports.blobSource = blobSource;
1094
1562
  exports.checkNativeArtifact = checkNativeArtifact;
1563
+ exports.createPreviewLink = createPreviewLink;
1095
1564
  exports.findZipEntry = findZipEntry;
1565
+ exports.isConfigurableSandboxUrlScheme = isConfigurableSandboxUrlScheme;
1566
+ exports.isRecordedUrlSchemeSyntax = isRecordedUrlSchemeSyntax;
1567
+ exports.isSandboxChannel = isSandboxChannel;
1568
+ exports.isSandboxUrlScheme = isSandboxUrlScheme;
1569
+ exports.normalizeIosUdid = normalizeIosUdid;
1096
1570
  exports.openZipEntry = openZipEntry;
1571
+ exports.parsePreviewLink = parsePreviewLink;
1572
+ exports.readIpaInstallInfo = readIpaInstallInfo;
1097
1573
  exports.readNativeArtifact = readNativeArtifact;
1574
+ exports.readProfileServiceUdid = readProfileServiceUdid;
1575
+ exports.readProvisioningProfile = readProvisioningProfile;
1098
1576
  exports.readZipDirectory = readZipDirectory;
1577
+ exports.recordedSandboxUrlScheme = recordedSandboxUrlScheme;
1578
+ exports.sandboxArtifactProblem = sandboxArtifactProblem;
1579
+ exports.sandboxChannelOf = sandboxChannelOf;
1580
+ exports.sandboxUrlSchemeOf = sandboxUrlSchemeOf;