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

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