@hot-updater/protocol 1.2.0-rc.5 → 1.2.0-rc.50

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