@adea-ai/app-framework-release-tools 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -39,7 +39,10 @@ __export(exports_src, {
39
39
  inspectDailyBatch: () => inspectDailyBatch,
40
40
  inspectDailyPreSigning: () => inspectDailyPreSigning,
41
41
  inspectStagedStep: () => inspectStagedStep,
42
+ packageChannelNames: () => packageChannelNames,
43
+ parsePackageChannelManifest: () => parsePackageChannelManifest,
42
44
  planDailyReleaseMatrix: () => planDailyReleaseMatrix,
45
+ planPackageChannels: () => planPackageChannels,
43
46
  planQualificationRun: () => planQualificationRun2,
44
47
  planReleaseAssets: () => planReleaseAssets2,
45
48
  promoteDailyBatch: () => promoteDailyBatch,
@@ -77,20 +80,26 @@ import { Effect as Effect32 } from "effect";
77
80
  // ../../src/installer/hosted-runner.ts
78
81
  import { isAbsolute } from "path";
79
82
  var JOB_NUMBER = /^[1-9]\d{0,19}$/;
80
- function isHostedRunner(env) {
83
+ function hostedRunnerRefusal(env) {
81
84
  if (env.CI !== "true")
82
- return false;
85
+ return "CI is not true";
83
86
  if (env.GITHUB_ACTIONS === "true")
84
- return env.RUNNER_ENVIRONMENT === "github-hosted";
87
+ return env.RUNNER_ENVIRONMENT === "github-hosted" ? undefined : "RUNNER_ENVIRONMENT is not github-hosted";
85
88
  if (env.FRAMEWORK_DISPOSABLE_RUNNER !== "true")
86
- return false;
89
+ return "FRAMEWORK_DISPOSABLE_RUNNER is not true";
87
90
  if (env.GITLAB_CI === "true")
88
- return JOB_NUMBER.test(env.CI_JOB_ID ?? "");
89
- return env.CIRCLECI === "true" && JOB_NUMBER.test(env.CIRCLE_BUILD_NUM ?? "");
91
+ return JOB_NUMBER.test(env.CI_JOB_ID ?? "") ? undefined : "CI_JOB_ID is not a job number";
92
+ if (env.CIRCLECI !== "true")
93
+ return "neither GITLAB_CI nor CIRCLECI is true";
94
+ return JOB_NUMBER.test(env.CIRCLE_BUILD_NUM ?? "") ? undefined : "CIRCLE_BUILD_NUM is not a job number";
95
+ }
96
+ function isHostedRunner(env) {
97
+ return hostedRunnerRefusal(env) === undefined;
90
98
  }
91
99
  function assertHostedRunner(env, subject) {
92
- if (!isHostedRunner(env))
93
- throw new Error(`${subject} requires a disposable hosted runner`);
100
+ const refusal = hostedRunnerRefusal(env);
101
+ if (refusal !== undefined)
102
+ throw new Error(`${subject} requires a disposable hosted runner (${refusal})`);
94
103
  }
95
104
  function runnerTemp(env) {
96
105
  const path = env.GITHUB_ACTIONS === "true" ? env.RUNNER_TEMP : env.TMPDIR;
@@ -316,10 +325,18 @@ function assertPayloadLayout(options) {
316
325
  if (!entries.includes(fold ? name.toLowerCase() : name))
317
326
  throw new Error(`Payload missing ${name}`);
318
327
  }
319
- const containsCef = entries.some((name) => /(?:^|\/)(?:chromium embedded framework|libcef\.dll|libcef\.so)$/i.test(name));
320
- if (containsCef !== (renderer === "cef"))
328
+ if (payloadRenderer(entries) !== renderer)
321
329
  throw new Error("Payload does not match selected renderer");
322
330
  }
331
+ function payloadRenderer(entries) {
332
+ return entries.some((name) => /(?:^|\/)(?:chromium embedded framework|libcef\.dll|libcef\.so)$/i.test(name)) ? "cef" : "native";
333
+ }
334
+ function acceptedUpdateRenderers(renderer, accepted) {
335
+ const all = [renderer, ...accepted ?? []];
336
+ if (all.some((item) => item !== "native" && item !== "cef"))
337
+ throw new Error("Invalid installer profile");
338
+ return [...new Set(all)];
339
+ }
323
340
  function assertInstallerLayout(platform, appName, entries) {
324
341
  assertPortableAppName(appName);
325
342
  if (platform !== "windows-x64" && platform !== "linux-x64" && platform !== "linux-arm64")
@@ -1069,6 +1086,10 @@ import { Cause, Data, Effect, Exit } from "effect";
1069
1086
 
1070
1087
  class ReleaseFailure extends Data.TaggedError("ReleaseFailure") {
1071
1088
  }
1089
+
1090
+ class PublicReleaseError extends Error {
1091
+ name = "PublicReleaseError";
1092
+ }
1072
1093
  var refuse = (reason, message) => Effect.fail(new ReleaseFailure({ reason, message }));
1073
1094
  var fail = (message) => refuse("refused", message);
1074
1095
  var stepFailure = (error) => new ReleaseFailure({
@@ -3707,11 +3728,24 @@ async function promoteDailyBatch(store, candidate, signer, keys) {
3707
3728
  throw new Error("Daily promotion could not be read back");
3708
3729
  return selected;
3709
3730
  }
3731
+ async function readDailyBatchByDigest(store, target, manifestDigest) {
3732
+ if (!app.test(target.appId) || !feedApp.test(target.feedApp) || !hex2.test(manifestDigest))
3733
+ throw new Error("Invalid Daily batch target");
3734
+ const bytes = await readSmall(await store.readObject(`${prefix(target.feedApp, manifestDigest)}/manifest.json`), 262144);
3735
+ if (hash(bytes) !== manifestDigest)
3736
+ throw new Error("Daily batch manifest changed");
3737
+ const manifest = parseManifest(parseJson(bytes));
3738
+ if (manifest.identity.appId !== target.appId || manifest.identity.feedApp !== target.feedApp)
3739
+ throw new Error("Daily batch app mismatch");
3740
+ return Object.freeze({ version: "", sequence: 0, manifestDigest, manifest });
3741
+ }
3710
3742
  async function rollbackDailyBatch(store, current, target, signer, keys) {
3711
3743
  const appId = current.manifest.identity.appId;
3712
3744
  const slug = current.manifest.identity.feedApp;
3713
3745
  if (target.manifest.identity.appId !== appId || target.manifest.identity.feedApp !== slug || !hex2.test(target.manifestDigest))
3714
3746
  throw new Error("Invalid rollback target");
3747
+ if (target.manifestDigest === current.manifestDigest)
3748
+ throw new Error("Rollback target is the current Daily batch");
3715
3749
  const selected = await readDailyBatch(store, { appId, feedApp: slug }, keys);
3716
3750
  if (!selected || selected.version !== current.version)
3717
3751
  throw new Error("Daily pointer changed during rollback");
@@ -4548,6 +4582,8 @@ function planDailyReleaseMatrix(config, tag) {
4548
4582
  const requirements = parsed.requirements(tag);
4549
4583
  const profile = config.dailyReleaseProfile;
4550
4584
  const expanded = profile === expandedDesktopDailyProfile;
4585
+ requireThat(config.dailyInstallerSigning === undefined || config.dailyInstallerSigning === "required", 'dailyInstallerSigning must be "required" when present');
4586
+ const installerSigning = expanded || config.dailyInstallerSigning === "required";
4551
4587
  const checks = [];
4552
4588
  const primaryAssets = [];
4553
4589
  for (const platform of expanded ? expandedPlatforms : platforms) {
@@ -4592,10 +4628,12 @@ function planDailyReleaseMatrix(config, tag) {
4592
4628
  discoveryPolicies(config, tag);
4593
4629
  const all = [...primaryAssets, ...requirements.releaseAssets];
4594
4630
  requireThat(new Set(all).size === all.length, "Daily release assets are not unique");
4595
- return { appId: config.appId, profile, assets: all, checks };
4631
+ return { appId: config.appId, profile, installerSigning, assets: all, checks };
4596
4632
  }
4597
- function requiresDailyInstallerSigning(profile, check) {
4598
- return profile === expandedDesktopDailyProfile && (check.format === "dmg" || check.format === "windows-setup");
4633
+ function requiresDailyInstallerSigning(matrix, check) {
4634
+ if (!matrix.installerSigning)
4635
+ return false;
4636
+ return matrix.profile === expandedDesktopDailyProfile ? check.format === "dmg" || check.format === "windows-setup" : check.format === "dmg";
4599
4637
  }
4600
4638
  function priorDailyInstallerNames(config, tag, check) {
4601
4639
  const plan = planDailyReleaseMatrix(config, tag);
@@ -4676,7 +4714,7 @@ var verifiedMatrix = (options, verifyPrior) => Effect16.gen(function* () {
4676
4714
  const valid = yield* attempt(() => validateDailyNativeEvidence(raw.value, "framework/daily-native-receipt/v2", {
4677
4715
  appId: matrix.appId,
4678
4716
  profile: matrix.profile,
4679
- signing: requiresDailyInstallerSigning(matrix.profile, check) ? installerSigningPolicy(config, check) : undefined,
4717
+ signing: requiresDailyInstallerSigning(matrix, check) ? installerSigningPolicy(config, check) : undefined,
4680
4718
  identity,
4681
4719
  check,
4682
4720
  assets: check.assets.map((name) => inventory.get(name)),
@@ -4875,7 +4913,7 @@ var createDailyNativeReceiptEffect = (options, worker, observedSigning) => Effec
4875
4913
  const [os, arch] = platformTargets[check.platform];
4876
4914
  if (worker.os !== os || worker.arch !== arch)
4877
4915
  return yield* fail(`Daily native check requires ${check.platform}`);
4878
- const signing = requiresDailyInstallerSigning(matrix.profile, check) ? yield* attempt(() => installerSigningPolicy(config, check)) : undefined;
4916
+ const signing = requiresDailyInstallerSigning(matrix, check) ? yield* attempt(() => installerSigningPolicy(config, check)) : undefined;
4879
4917
  if (signing && !observedSigning)
4880
4918
  return yield* fail("Expanded Daily installers require proof from the live native observer");
4881
4919
  const fs = yield* ReleaseFs;
@@ -5921,6 +5959,72 @@ var stageLocalReleaseEffect = (options) => Effect21.gen(function* () {
5921
5959
  };
5922
5960
  return yield* writeStagedTree(options.out, feed, uploads, releaseDocuments(feed, updated, release));
5923
5961
  });
5962
+ var linuxPackageFormats = [
5963
+ {
5964
+ extension: ".deb",
5965
+ magic: (head) => head.subarray(0, 8).toString("latin1") === `!<arch>
5966
+ `
5967
+ },
5968
+ {
5969
+ extension: ".AppImage",
5970
+ magic: (head) => head.subarray(0, 4).equals(Buffer.from([127, 69, 76, 70])) && head.subarray(8, 11).equals(Buffer.from([65, 73, 2]))
5971
+ }
5972
+ ];
5973
+ var stageLocalPackagesEffect = (options) => Effect21.gen(function* () {
5974
+ const fs = yield* ReleaseFs;
5975
+ const { tag, sourceSha } = options;
5976
+ const local = localConfig(options.config);
5977
+ const feed = local.feed;
5978
+ const requirements = local.requirements(tag);
5979
+ const allowed = new Map;
5980
+ for (const platform of ["linux-x64", "linux-arm64"])
5981
+ for (const archive of requirements.platforms[platform] ?? [])
5982
+ if (archive.endsWith(".tar.zst"))
5983
+ for (const { extension } of linuxPackageFormats)
5984
+ allowed.set(archive.slice(0, -".tar.zst".length) + extension, archive);
5985
+ const directory = resolve9(options.directory);
5986
+ const entries = yield* step(() => fs.readdir(directory, { withFileTypes: true }));
5987
+ if (!entries.length || entries.some((entry) => !entry.isFile() || !allowed.has(entry.name)))
5988
+ return yield* fail("Staged directory holds files that are not this tag's Linux packages");
5989
+ const names = entries.map((entry) => entry.name).toSorted();
5990
+ const staged = yield* Effect21.forEach(names, (name) => fileIdentityEffect(join15(directory, name), name), { concurrency: "unbounded" });
5991
+ for (const name of names) {
5992
+ const format = linuxPackageFormats.find(({ extension }) => name.endsWith(extension));
5993
+ const head = Buffer.alloc(16);
5994
+ const file = yield* step(() => fs.open(join15(directory, name), "r"));
5995
+ yield* step(() => file.read(head, 0, 16, 0)).pipe(Effect21.ensuring(Effect21.promise(() => file.close().catch(() => {
5996
+ return;
5997
+ }))));
5998
+ if (!format.magic(head))
5999
+ return yield* fail(`Not a ${format.extension} package: ${name}`);
6000
+ }
6001
+ const [ledger, remote] = yield* Effect21.all([readFeedLedgerEffect(feed), readFeedReleaseEffect(feed, tag)], { concurrency: "unbounded" });
6002
+ const entry = ledger.releases.find((item) => item.tag === tag);
6003
+ if (!entry || !remote || entry.kind !== remote.channel || Date.parse(entry.publishedAt) !== Date.parse(remote.publishedAt))
6004
+ return yield* fail("The feed has not published this tag; publish its release first");
6005
+ if (entry.sourceSha !== sourceSha)
6006
+ return yield* fail("The feed publishes this tag from another source commit");
6007
+ const merged = [...remote.assets];
6008
+ const uploads = [];
6009
+ for (const artifact of staged) {
6010
+ if (!merged.some((asset) => asset.name === allowed.get(artifact.name)))
6011
+ return yield* fail(`The feed has no ${allowed.get(artifact.name)} for ${artifact.name}`);
6012
+ const existing = merged.find((asset) => asset.name === artifact.name);
6013
+ if (existing) {
6014
+ if (existing.size !== artifact.size || "sha256:" + existing.sha256 !== artifact.digest)
6015
+ return yield* fail(`Immutable asset conflict: ${artifact.name}`);
6016
+ continue;
6017
+ }
6018
+ merged.push({ name: artifact.name, size: artifact.size, sha256: artifact.digest.slice(7) });
6019
+ uploads.push({
6020
+ key: feedAssetKey(feed, tag, artifact.name),
6021
+ path: join15(directory, artifact.name),
6022
+ artifact
6023
+ });
6024
+ }
6025
+ const release = { ...remote, assets: merged };
6026
+ return yield* writeStagedTree(options.out, feed, uploads, releaseDocuments(feed, ledger, release));
6027
+ });
5924
6028
  function stablePlatforms(config) {
5925
6029
  const value = isRecord(config) ? config.stablePlatforms : undefined;
5926
6030
  if (value === undefined)
@@ -7779,7 +7883,8 @@ async function extractVerifiedUpdate(options) {
7779
7883
  return extractBoundArchive(options, descriptor, async (file) => verifyReleaseStream(file.createReadStream({ autoClose: false, start: 0 }), descriptor));
7780
7884
  }
7781
7885
  async function extractBoundArchive(options, descriptor, verifyBeforeExtraction) {
7782
- const { archive, platform, renderer, appName, maxCompressedBytes, maxExpandedBytes } = options;
7886
+ const { archive, platform, appName, maxCompressedBytes, maxExpandedBytes } = options;
7887
+ const accepted = acceptedUpdateRenderers(options.renderer, options.acceptedRenderers);
7783
7888
  if (!isAbsolute6(archive) || !isAbsolute6(options.directory) || !Number.isSafeInteger(maxCompressedBytes) || maxCompressedBytes < 1 || !Number.isSafeInteger(descriptor.asset.size) || descriptor.asset.size < 1 || descriptor.asset.size > maxCompressedBytes || !/^[a-f0-9]{64}$/.test(descriptor.asset.sha256) || !Number.isSafeInteger(maxExpandedBytes) || maxExpandedBytes < 1)
7784
7889
  throw new Error("Invalid update extraction context");
7785
7890
  assertPortableAppName(appName);
@@ -7865,7 +7970,7 @@ async function extractBoundArchive(options, descriptor, verifyBeforeExtraction)
7865
7970
  if (seen.has(key) || seen.size >= 200000)
7866
7971
  return reject();
7867
7972
  const relative = normalized.slice(archiveRoot.length + 1), linkTarget = typeof entry.linkpath === "string" ? entry.linkpath : "";
7868
- const cefLink = (platform === "linux-x64" || platform === "linux-arm64") && renderer === "cef" && entry.type === "SymbolicLink" && isLinuxCefLibraryLink(relative, linkTarget);
7973
+ const cefLink = (platform === "linux-x64" || platform === "linux-arm64") && accepted.includes("cef") && entry.type === "SymbolicLink" && isLinuxCefLibraryLink(relative, linkTarget);
7869
7974
  if (entry.type !== "File" && entry.type !== "Directory" && !cefLink)
7870
7975
  return reject();
7871
7976
  seen.add(key);
@@ -7930,6 +8035,9 @@ async function extractBoundArchive(options, descriptor, verifyBeforeExtraction)
7930
8035
  }
7931
8036
  }
7932
8037
  await rm8(decompressed);
8038
+ const renderer = payloadRenderer(entries);
8039
+ if (!accepted.includes(renderer))
8040
+ throw new Error("Payload does not match selected renderer");
7933
8041
  assertPayloadLayout({ platform, renderer, appName, entries, sidecars });
7934
8042
  const prefix = isMacInstallerPlatform(platform) ? join22(`${appName}.app`, "Contents") : appName.replaceAll(" ", "");
7935
8043
  const resources = join22(payloadRoot, prefix, "Resources");
@@ -8761,6 +8869,7 @@ async function stageUpdateSwap(options) {
8761
8869
  directory: preparing,
8762
8870
  platform: plan.platform,
8763
8871
  renderer: plan.renderer,
8872
+ ...options.acceptedRenderers ? { acceptedRenderers: options.acceptedRenderers } : {},
8764
8873
  appName: plan.appName,
8765
8874
  maxCompressedBytes: options.maxCompressedBytes,
8766
8875
  maxExpandedBytes: options.maxExpandedBytes,
@@ -10347,6 +10456,7 @@ import { basename as basename17, isAbsolute as isAbsolute8, join as join39, reso
10347
10456
  import { promisify as promisify5 } from "util";
10348
10457
 
10349
10458
  // src/library/windows-standalone-bootstrap.ts
10459
+ var WINDOWS_PACKAGE_MANAGER_SWITCH = "--package-manager=winget";
10350
10460
  var windowsBootstrapSource = String.raw`
10351
10461
  #define WIN32_LEAN_AND_MEAN
10352
10462
  #include <windows.h>
@@ -10405,10 +10515,28 @@ static BOOL write_exclusive(const wchar_t *path, const unsigned char *bytes, DWO
10405
10515
  return CloseHandle(file) && ok;
10406
10516
  }
10407
10517
 
10518
+ // Marks the installed app root as package-manager owned. The root must already exist as a real
10519
+ // directory (the inner Setup created it); the marker is replaced, never followed through a link.
10520
+ static BOOL write_package_manager_marker(void) {
10521
+ wchar_t local[MAX_PATH], root[MAX_PATH], marker[MAX_PATH];
10522
+ DWORD n = GetEnvironmentVariableW(L"LOCALAPPDATA", local, MAX_PATH);
10523
+ if (!n || n >= MAX_PATH) return FALSE;
10524
+ int m = swprintf(root, MAX_PATH, L"%ls\\%ls\\stable\\app", local, APP_ID);
10525
+ if (m <= 0 || m >= MAX_PATH || !join_path(marker, root, L".package-manager")) return FALSE;
10526
+ DWORD attributes = GetFileAttributesW(root);
10527
+ if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)
10528
+ || (attributes & FILE_ATTRIBUTE_REPARSE_POINT)) return FALSE;
10529
+ DeleteFileW(marker);
10530
+ static const unsigned char owner[] = "winget\n";
10531
+ return write_exclusive(marker, owner, sizeof owner - 1);
10532
+ }
10533
+
10408
10534
  int WINAPI wWinMain(HINSTANCE instance, HINSTANCE previous, LPWSTR command, int show) {
10409
10535
  (void)instance; (void)previous; (void)show;
10410
- // No undocumented silent or arbitrary installer arguments are forwarded.
10411
- if (command[0]) {
10536
+ // No undocumented silent or arbitrary installer arguments are forwarded. The only option is
10537
+ // the exact package-manager switch, which is not forwarded either: it marks the install.
10538
+ BOOL package_manager = wcscmp(command, L"${WINDOWS_PACKAGE_MANAGER_SWITCH}") == 0;
10539
+ if (command[0] && !package_manager) {
10412
10540
  MessageBoxW(NULL, L"This installer accepts no command-line options.", APP_NAME, MB_OK | MB_ICONERROR);
10413
10541
  return 2;
10414
10542
  }
@@ -10460,6 +10588,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE previous, LPWSTR command, int
10460
10588
  cleanup:
10461
10589
  DeleteFileW(archive); DeleteFileW(meta); DeleteFileW(child);
10462
10590
  RemoveDirectoryW(hidden); CloseHandle(guard); RemoveDirectoryW(work);
10591
+ if (code == 0 && package_manager && !write_package_manager_marker()) code = 2;
10463
10592
  if (code == 0) return 0;
10464
10593
  fail:
10465
10594
  MessageBoxW(NULL, L"Installation did not complete.", APP_NAME, MB_OK | MB_ICONERROR);
@@ -10600,6 +10729,7 @@ async function buildStandaloneWindowsExe(options) {
10600
10729
  throw new Error("Unexpected pinned Zig compiler version");
10601
10730
  await writeFile14(join39(work, "app.h"), [
10602
10731
  `#define APP_NAME L"${appName}"`,
10732
+ `#define APP_ID L"${appId}"`,
10603
10733
  `#define SETUP_SIZE ${setup.size}u`,
10604
10734
  `#define METADATA_SIZE ${metadata.size}u`,
10605
10735
  `#define ARCHIVE_SIZE ${archive.size}u`
@@ -10647,6 +10777,554 @@ async function buildStandaloneWindowsExe(options) {
10647
10777
  await rm13(work, { recursive: true, force: true });
10648
10778
  }
10649
10779
  }
10780
+ // src/library/package-channels.ts
10781
+ var packageChannelNames = [
10782
+ "homebrew",
10783
+ "winget",
10784
+ "apt",
10785
+ "pacman",
10786
+ "rpm",
10787
+ "flatpak"
10788
+ ];
10789
+ function ensure(ok, message) {
10790
+ if (!ok)
10791
+ throw new Error(message);
10792
+ }
10793
+ function object(value, label) {
10794
+ ensure(typeof value === "object" && value !== null && !Array.isArray(value), `Expected ${label} to be a JSON object`);
10795
+ return value;
10796
+ }
10797
+ function keys2(row, label, required, optional = []) {
10798
+ for (const key of required)
10799
+ ensure(Object.hasOwn(row, key), `Missing ${label}.${key}`);
10800
+ for (const key of Object.keys(row))
10801
+ ensure(required.includes(key) || optional.includes(key), `Unknown ${label}.${key}`);
10802
+ }
10803
+ function text3(value, label, pattern, max = 200) {
10804
+ ensure(typeof value === "string" && value.length > 0 && value.length <= max && !Array.from(value).some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127) && (!pattern || pattern.test(value)), `Invalid ${label}`);
10805
+ return value;
10806
+ }
10807
+ function https(value, label, directory) {
10808
+ const url = new URL(text3(value, label, undefined, 500));
10809
+ ensure(url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash, `Expected canonical HTTPS URL for ${label}`);
10810
+ ensure(url.href === value, `Expected canonical HTTPS URL for ${label}`);
10811
+ ensure(url.pathname.endsWith("/") === directory, `Expected ${label} to ${directory ? "" : "not "}end in /`);
10812
+ return url;
10813
+ }
10814
+ var tagPattern3 = /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
10815
+ var sha256Pattern = /^[a-f0-9]{64}$/;
10816
+ var gitShaPattern = /^[a-f0-9]{40}$/;
10817
+ var filePattern = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
10818
+ var templatePattern = /^[A-Za-z0-9][A-Za-z0-9._-]*\{tag\}[A-Za-z0-9._-]*$/;
10819
+ var packagePattern = /^[a-z0-9][a-z0-9+.-]{0,62}$/;
10820
+ var reverseDns = /^[A-Za-z_][A-Za-z0-9_-]*(\.[A-Za-z_][A-Za-z0-9_-]*){2,}$/;
10821
+ var relativePath2 = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
10822
+ var quoted = JSON.stringify;
10823
+ var ruby = (value) => JSON.stringify(value).replace(/#(?=[{@$])/g, "\\#");
10824
+ var shell = (value) => `'${value.replaceAll("'", "'\\''")}'`;
10825
+ function parseAsset(value) {
10826
+ const row = object(value, "manifest asset");
10827
+ const size = row.size;
10828
+ ensure(typeof size === "number" && Number.isSafeInteger(size) && size > 0, "Invalid asset size");
10829
+ const sha256 = row.sha256 ?? row.digest;
10830
+ return {
10831
+ name: text3(row.name, "asset name", filePattern),
10832
+ size,
10833
+ sha256: text3(sha256, "asset SHA-256", sha256Pattern)
10834
+ };
10835
+ }
10836
+ function parsePackageChannelManifest(value) {
10837
+ const doc = object(value, "manifest");
10838
+ let raw;
10839
+ let manifest;
10840
+ if (doc.schema === "framework/daily-batch/v1") {
10841
+ const identity = object(doc.identity, "manifest identity");
10842
+ ensure(Array.isArray(doc.artifacts), "Expected Daily batch artifacts");
10843
+ raw = doc.artifacts;
10844
+ manifest = {
10845
+ appId: text3(identity.appId, "manifest appId"),
10846
+ tag: text3(identity.tag, "release tag", tagPattern3),
10847
+ channel: "daily",
10848
+ sourceSha: text3(identity.sourceSha, "source SHA", gitShaPattern)
10849
+ };
10850
+ } else {
10851
+ ensure(doc.schema === undefined, "Unsupported manifest schema");
10852
+ ensure(doc.channel === "daily" || doc.channel === "stable", "Expected release channel");
10853
+ ensure(Array.isArray(doc.assets), "Expected release assets");
10854
+ raw = doc.assets;
10855
+ manifest = {
10856
+ appId: null,
10857
+ tag: text3(doc.tag, "release tag", tagPattern3),
10858
+ channel: doc.channel,
10859
+ sourceSha: null
10860
+ };
10861
+ }
10862
+ ensure(raw.length > 0 && raw.length <= 512, "Expected a bounded asset inventory");
10863
+ const assets = new Map;
10864
+ for (const entry of raw) {
10865
+ const asset = parseAsset(entry);
10866
+ ensure(!assets.has(asset.name), `Duplicate manifest asset ${asset.name}`);
10867
+ assets.set(asset.name, asset);
10868
+ }
10869
+ return { ...manifest, assets };
10870
+ }
10871
+ function exact2(context, template, label, suffixes) {
10872
+ const name = text3(template, `${label} artifact template`, templatePattern).replace("{tag}", context.manifest.tag);
10873
+ ensure(suffixes.some((suffix) => name.endsWith(suffix)), `Expected ${label} artifact ending in ${suffixes.join(" or ")}`);
10874
+ const asset = context.manifest.assets.get(name);
10875
+ ensure(asset, `The manifest has no ${name}`);
10876
+ return {
10877
+ ...asset,
10878
+ url: new URL(`${context.manifest.tag}/${name}`, context.common.releaseBase).href
10879
+ };
10880
+ }
10881
+ function stageInput(context, asset) {
10882
+ return {
10883
+ path: "stage-input.json",
10884
+ contents: JSON.stringify({
10885
+ schema: "framework/package-channel-stage-input/v1",
10886
+ appId: context.common.appId,
10887
+ tag: context.manifest.tag,
10888
+ channel: context.manifest.channel,
10889
+ sourceSha: context.manifest.sourceSha,
10890
+ asset
10891
+ }, null, 2) + `
10892
+ `
10893
+ };
10894
+ }
10895
+ function homebrew(context, row) {
10896
+ keys2(row, "homebrew", ["tap", "token", "bundle", "artifact"]);
10897
+ const tap = text3(row.tap, "Homebrew tap", /^[A-Za-z0-9][A-Za-z0-9-]*\/homebrew-[a-z0-9][a-z0-9-]*$/);
10898
+ const stableToken = text3(row.token, "cask token", /^[a-z0-9]+(?:-[a-z0-9]+)*$/);
10899
+ const bundle = text3(row.bundle, "app bundle", /^[A-Za-z0-9][A-Za-z0-9 ._-]*\.app$/);
10900
+ const asset = exact2(context, row.artifact, "Homebrew", [".dmg"]);
10901
+ const stable = context.manifest.channel === "stable";
10902
+ const token = stable ? stableToken : `${stableToken}@daily`;
10903
+ const [owner, repository] = tap.split("/");
10904
+ const tapName = `${owner}/${repository.slice("homebrew-".length)}`;
10905
+ const { name, description, homepage } = context.common;
10906
+ return {
10907
+ status: "planned",
10908
+ catalogEligible: stable,
10909
+ asset,
10910
+ files: [
10911
+ {
10912
+ path: `Casks/${token}.rb`,
10913
+ contents: `cask ${ruby(token)} do
10914
+ version ${ruby(context.version)}
10915
+ sha256 ${ruby(asset.sha256)}
10916
+
10917
+ url ${ruby(asset.url)}
10918
+ name ${ruby(stable ? name : `${name} Daily`)}
10919
+ desc ${ruby(description)}
10920
+ homepage ${ruby(homepage)}
10921
+
10922
+ depends_on arch: :arm64
10923
+ conflicts_with cask: ${ruby(stable ? `${stableToken}@daily` : stableToken)}
10924
+
10925
+ app ${ruby(bundle)}
10926
+ end
10927
+ `
10928
+ }
10929
+ ],
10930
+ install: `brew install --cask ${tapName}/${token}`
10931
+ };
10932
+ }
10933
+ function winget(context, row) {
10934
+ keys2(row, "winget", ["identifier", "publisher", "artifact"], ["nestedInstaller", "silent", "silentWithProgress"]);
10935
+ const stableId = text3(row.identifier, "WinGet package identifier", /^[A-Za-z0-9][A-Za-z0-9-]*(\.[A-Za-z0-9][A-Za-z0-9-]*)+$/);
10936
+ const publisher = text3(row.publisher, "WinGet publisher");
10937
+ const asset = exact2(context, row.artifact, "WinGet", [".exe", ".zip"]);
10938
+ const direct = asset.name.endsWith(".exe");
10939
+ ensure(direct === (row.nestedInstaller === undefined), direct ? "A direct .exe installer takes no nestedInstaller" : "A .zip installer needs nestedInstaller");
10940
+ const nested = direct ? undefined : text3(row.nestedInstaller, "nested executable", /^[A-Za-z0-9][A-Za-z0-9 ._-]*\.exe$/i);
10941
+ ensure(!direct || row.silent === undefined && row.silentWithProgress === undefined, "A direct .exe installer takes the package-manager switch, not silent flags");
10942
+ const flags = /^[-/][a-zA-Z0-9_-]+(?: [-/][a-zA-Z0-9_-]+)*$/;
10943
+ const silent = direct ? WINDOWS_PACKAGE_MANAGER_SWITCH : text3(row.silent, "silent flags", flags);
10944
+ const progress = direct ? WINDOWS_PACKAGE_MANAGER_SWITCH : text3(row.silentWithProgress, "silent progress flags", flags);
10945
+ const stable = context.manifest.channel === "stable";
10946
+ const id = stable ? stableId : `${stableId}.Daily`;
10947
+ const { name, description, homepage, license } = context.common;
10948
+ const schemaVersion = "1.12.0";
10949
+ const base = `manifests/${id[0].toLowerCase()}/${id.replaceAll(".", "/")}/${context.version}/${id}`;
10950
+ const manifest = (type, body) => `# yaml-language-server: $schema=https://aka.ms/winget-manifest.${type}.${schemaVersion}.schema.json
10951
+ PackageIdentifier: ${quoted(id)}
10952
+ PackageVersion: ${quoted(context.version)}
10953
+ ${body}ManifestType: ${type}
10954
+ ManifestVersion: ${schemaVersion}
10955
+ `;
10956
+ return {
10957
+ status: "planned",
10958
+ catalogEligible: stable,
10959
+ asset,
10960
+ files: [
10961
+ { path: `${base}.yaml`, contents: manifest("version", `DefaultLocale: en-US
10962
+ `) },
10963
+ {
10964
+ path: `${base}.installer.yaml`,
10965
+ contents: manifest("installer", `${direct ? "InstallerType: exe" : `InstallerType: zip
10966
+ NestedInstallerType: exe
10967
+ NestedInstallerFiles:
10968
+ - RelativeFilePath: ${quoted(nested)}`}
10969
+ InstallerSwitches:
10970
+ Silent: ${quoted(silent)}
10971
+ SilentWithProgress: ${quoted(progress)}
10972
+ UpgradeBehavior: install
10973
+ Installers:
10974
+ - Architecture: x64
10975
+ InstallerUrl: ${quoted(asset.url)}
10976
+ InstallerSha256: ${asset.sha256.toUpperCase()}
10977
+ `)
10978
+ },
10979
+ {
10980
+ path: `${base}.locale.en-US.yaml`,
10981
+ contents: manifest("defaultLocale", `PackageLocale: en-US
10982
+ Publisher: ${quoted(publisher)}
10983
+ PublisherUrl: ${quoted(homepage)}
10984
+ PackageName: ${quoted(stable ? name : `${name} Daily`)}
10985
+ PackageUrl: ${quoted(homepage)}
10986
+ License: ${quoted(license)}
10987
+ ShortDescription: ${quoted(description)}
10988
+ `)
10989
+ }
10990
+ ],
10991
+ install: stable ? `winget install --exact --id ${id}` : `winget install --manifest ${base.slice(0, base.lastIndexOf("/")).replaceAll("/", "\\")}`
10992
+ };
10993
+ }
10994
+ function apt(context, row) {
10995
+ keys2(row, "apt", ["packageName", "artifact", "repository", "suite", "keyUrl"], ["component"]);
10996
+ const pkg = text3(row.packageName, "Debian package name", packagePattern);
10997
+ const asset = exact2(context, row.artifact, "APT", [".deb"]);
10998
+ const repository = https(row.repository, "APT repository", true).href;
10999
+ const suite = text3(row.suite, "APT suite", /^(daily|stable)$/);
11000
+ ensure(suite === context.manifest.channel, `APT suite ${suite} does not match the ${context.manifest.channel} manifest`);
11001
+ const component = text3(row.component ?? "main", "APT component", /^main$/);
11002
+ const keyUrl = https(row.keyUrl, "APT key URL", false).href;
11003
+ const keyring = `/usr/share/keyrings/${pkg}-archive-keyring.gpg`;
11004
+ const sources = `${pkg}.sources`;
11005
+ return {
11006
+ status: "planned",
11007
+ catalogEligible: false,
11008
+ asset,
11009
+ files: [
11010
+ {
11011
+ path: sources,
11012
+ contents: `Types: deb
11013
+ URIs: ${repository}
11014
+ Suites: ${suite}
11015
+ Components: ${component}
11016
+ Architectures: amd64
11017
+ Signed-By: ${keyring}
11018
+ `
11019
+ },
11020
+ stageInput(context, asset)
11021
+ ],
11022
+ install: [
11023
+ `curl -fsSL ${shell(keyUrl)} | sudo gpg --dearmor -o ${keyring}`,
11024
+ `curl -fsSL ${shell(repository + sources)} | sudo tee /etc/apt/sources.list.d/${sources} >/dev/null`,
11025
+ `sudo apt update`,
11026
+ `sudo apt install ${pkg}`
11027
+ ].join(" && ")
11028
+ };
11029
+ }
11030
+ function pacman(context, row) {
11031
+ keys2(row, "pacman", ["packageName", "repository", "base", "keyUrl"], ["keyFingerprint"]);
11032
+ const pkg = text3(row.packageName, "Arch package name", /^[a-z0-9@_+][a-z0-9@._+-]{0,62}$/);
11033
+ const repo = text3(row.repository, "pacman repository name", /^[a-z0-9][a-z0-9_-]{0,63}$/);
11034
+ const base = https(row.base, "pacman repository base", true).href;
11035
+ const keyUrl = https(row.keyUrl, "pacman key URL", false).href;
11036
+ ensure(row.keyFingerprint !== undefined, "Needs keyFingerprint: the pacman signing key is not pinned");
11037
+ const fingerprint = text3(row.keyFingerprint, "pacman key fingerprint", /^[A-F0-9]{40}$/);
11038
+ const snippet = `[${repo}]
11039
+ SigLevel = Required TrustedOnly
11040
+ Server = ${base}$arch
11041
+ `;
11042
+ return {
11043
+ status: "planned",
11044
+ catalogEligible: false,
11045
+ asset: null,
11046
+ files: [
11047
+ { path: "pacman.conf.snippet", contents: snippet },
11048
+ {
11049
+ path: "stage-input.json",
11050
+ contents: JSON.stringify({
11051
+ schema: "framework/package-channel-stage-input/v1",
11052
+ appId: context.common.appId,
11053
+ tag: context.manifest.tag,
11054
+ channel: context.manifest.channel,
11055
+ sourceSha: context.manifest.sourceSha,
11056
+ packageName: pkg,
11057
+ repository: repo,
11058
+ keyFingerprint: fingerprint
11059
+ }, null, 2) + `
11060
+ `
11061
+ }
11062
+ ],
11063
+ install: [
11064
+ `curl -fsSL ${shell(keyUrl)} | sudo pacman-key --add -`,
11065
+ `sudo pacman-key --lsign-key ${fingerprint}`,
11066
+ `printf ${shell(snippet.replaceAll(`
11067
+ `, "\\n"))} | sudo tee -a /etc/pacman.conf >/dev/null`,
11068
+ `sudo pacman -Sy ${pkg}`
11069
+ ].join(" && ")
11070
+ };
11071
+ }
11072
+ function linuxPayload(context, row, label) {
11073
+ const asset = exact2(context, row.artifact, label, [".tar.zst", ".tar.gz", ".tar.xz"]);
11074
+ const bundleRoot = text3(row.bundleRoot, `${label} bundle root`, filePattern);
11075
+ const launcher = text3(row.launcher, `${label} launcher`, relativePath2);
11076
+ ensure(!launcher.split("/").includes(".."), `Invalid ${label} launcher`);
11077
+ const formatEnvironment = text3(row.formatEnvironment, `${label} format environment`, /^[A-Z][A-Z0-9_]*_LINUX_PACKAGE_FORMAT$/);
11078
+ return { asset, bundleRoot, launcher, formatEnvironment };
11079
+ }
11080
+ function rpm(context, row) {
11081
+ keys2(row, "rpm", [
11082
+ "packageName",
11083
+ "artifact",
11084
+ "repoId",
11085
+ "repository",
11086
+ "keyUrl",
11087
+ "bundleRoot",
11088
+ "launcher",
11089
+ "executable",
11090
+ "formatEnvironment"
11091
+ ], ["requires"]);
11092
+ const pkg = text3(row.packageName, "RPM package name", /^[a-z0-9][a-z0-9._+-]{0,62}$/);
11093
+ const { asset, bundleRoot, launcher, formatEnvironment } = linuxPayload(context, row, "RPM");
11094
+ const repoId = text3(row.repoId, "RPM repository id", /^[a-z0-9][a-z0-9_-]{0,63}$/);
11095
+ const repository = https(row.repository, "RPM repository", true).href;
11096
+ const keyUrl = https(row.keyUrl, "RPM key URL", false).href;
11097
+ const executable = text3(row.executable, "RPM executable", /^[a-z0-9][a-z0-9._-]{0,63}$/);
11098
+ const requires = row.requires ?? [];
11099
+ ensure(Array.isArray(requires) && requires.length <= 64, "Invalid RPM requires");
11100
+ const requireLines = requires.map((entry) => `Requires: ${text3(entry, "RPM requirement", /^[A-Za-z0-9][A-Za-z0-9._+()-]*( (>=|=|<=) [A-Za-z0-9._+~^-]+)?$/)}
11101
+ `);
11102
+ const { name, description, homepage, license } = context.common;
11103
+ const spec = `# Generated by @adea-ai/app-framework-release-tools from ${asset.name}.
11104
+ # Repackages the verified portable payload; check Source0 against the SHA-256 before building.
11105
+ %global debug_package %{nil}
11106
+ %global __strip /bin/true
11107
+ %global _build_id_links none
11108
+ %global payload_sha256 ${asset.sha256}
11109
+
11110
+ Name: ${pkg}
11111
+ Version: ${context.version}
11112
+ Release: 1
11113
+ Summary: ${description}
11114
+ License: ${license}
11115
+ URL: ${homepage}
11116
+ Source0: ${asset.url}
11117
+ ExclusiveArch: x86_64
11118
+ AutoReqProv: no
11119
+ ${requireLines.join("")}
11120
+ %description
11121
+ ${name}: ${description}
11122
+
11123
+ %prep
11124
+ echo "%{payload_sha256} %{SOURCE0}" | sha256sum --check --strict
11125
+ %setup -q -c -T
11126
+ tar --no-same-owner -xf %{SOURCE0}
11127
+ test -d ${shell(bundleRoot)}
11128
+
11129
+ %install
11130
+ mkdir -p %{buildroot}%{_libdir}/${pkg} %{buildroot}%{_bindir}
11131
+ cp -a ${shell(bundleRoot)}/. %{buildroot}%{_libdir}/${pkg}/
11132
+ printf 'rpm\\n' > %{buildroot}%{_libdir}/${pkg}/Resources/app/.adea-linux-package
11133
+ cat > %{buildroot}%{_bindir}/${executable} <<'LAUNCHER'
11134
+ #!/bin/sh
11135
+ export ${formatEnvironment}=rpm
11136
+ exec %{_libdir}/${pkg}/${launcher} "$@"
11137
+ LAUNCHER
11138
+ chmod 0755 %{buildroot}%{_bindir}/${executable}
11139
+
11140
+ %files
11141
+ %{_libdir}/${pkg}
11142
+ %{_bindir}/${executable}
11143
+ `;
11144
+ const repoFile = `[${repoId}]
11145
+ name=${name} ${context.manifest.channel}
11146
+ baseurl=${repository}${context.manifest.channel}/$basearch/
11147
+ enabled=1
11148
+ gpgcheck=1
11149
+ repo_gpgcheck=1
11150
+ gpgkey=${keyUrl}
11151
+ `;
11152
+ return {
11153
+ status: "planned",
11154
+ catalogEligible: false,
11155
+ asset,
11156
+ files: [
11157
+ { path: `${pkg}.spec`, contents: spec },
11158
+ { path: `${repoId}.repo`, contents: repoFile },
11159
+ stageInput(context, asset)
11160
+ ],
11161
+ install: [
11162
+ `sudo curl -fsSLo /etc/yum.repos.d/${repoId}.repo ${shell(repository + repoId + ".repo")}`,
11163
+ `sudo dnf install ${pkg}`
11164
+ ].join(" && ")
11165
+ };
11166
+ }
11167
+ var yaml = (value) => JSON.stringify(value);
11168
+ var systemTalkDenied = /^(org\.freedesktop\.(Flatpak|DBus|systemd1)|org\.gtk\.GDBus)(\.|$)/;
11169
+ function flatpak(context, row) {
11170
+ keys2(row, "flatpak", [
11171
+ "applicationId",
11172
+ "artifact",
11173
+ "runtime",
11174
+ "runtimeVersion",
11175
+ "sdk",
11176
+ "bundleRoot",
11177
+ "launcher",
11178
+ "command",
11179
+ "formatEnvironment",
11180
+ "remote",
11181
+ "permissions"
11182
+ ]);
11183
+ const id = text3(row.applicationId, "Flatpak application id", reverseDns);
11184
+ const { asset, bundleRoot, launcher, formatEnvironment } = linuxPayload(context, row, "Flatpak");
11185
+ const runtime = text3(row.runtime, "Flatpak runtime", reverseDns);
11186
+ const sdk = text3(row.sdk, "Flatpak SDK", reverseDns);
11187
+ const runtimeVersion = text3(row.runtimeVersion, "Flatpak runtime version", /^[0-9][0-9.]*$/);
11188
+ const command = text3(row.command, "Flatpak command", /^[a-z0-9][a-z0-9._-]{0,63}$/);
11189
+ const remote = object(row.remote, "flatpak.remote");
11190
+ keys2(remote, "flatpak.remote", ["name", "url"]);
11191
+ const remoteName = text3(remote.name, "Flatpak remote name", /^[a-z0-9][a-z0-9_-]{0,63}$/);
11192
+ const remoteUrl = https(remote.url, "Flatpak remote URL", false).href;
11193
+ ensure(remoteUrl.endsWith(".flatpakrepo"), "Expected a .flatpakrepo remote URL");
11194
+ const permissions = object(row.permissions, "flatpak.permissions");
11195
+ keys2(permissions, "flatpak.permissions", ["network", "sockets", "devices", "sessionTalkNames"]);
11196
+ ensure(typeof permissions.network === "boolean", "Invalid Flatpak network permission");
11197
+ const list = (value, label, allowed) => {
11198
+ ensure(Array.isArray(value) && value.length <= 16, `Invalid Flatpak ${label}`);
11199
+ for (const entry of value)
11200
+ ensure(typeof entry === "string" && allowed(entry), `Unsafe Flatpak ${label}: ${String(entry)}`);
11201
+ ensure(new Set(value).size === value.length, `Duplicate Flatpak ${label}`);
11202
+ return value;
11203
+ };
11204
+ const sockets = list(permissions.sockets, "socket", (s) => s === "wayland" || s === "pulseaudio");
11205
+ const devices = list(permissions.devices, "device", (d) => d === "dri");
11206
+ const talk = list(permissions.sessionTalkNames, "session talk name", (n) => /^[A-Za-z_][\w-]*(\.[A-Za-z_][\w-]*)+$/.test(n) && !systemTalkDenied.test(n));
11207
+ const finishArgs = [
11208
+ ...permissions.network ? ["--share=network"] : [],
11209
+ "--share=ipc",
11210
+ ...sockets.map((s) => `--socket=${s}`),
11211
+ ...sockets.includes("wayland") ? ["--socket=fallback-x11"] : [],
11212
+ ...devices.map((d) => `--device=${d}`),
11213
+ ...talk.map((n) => `--talk-name=${n}`),
11214
+ `--env=${formatEnvironment}=flatpak`
11215
+ ];
11216
+ const manifest = `# Generated by @adea-ai/app-framework-release-tools from ${asset.name}.
11217
+ app-id: ${yaml(id)}
11218
+ runtime: ${yaml(runtime)}
11219
+ runtime-version: ${yaml(runtimeVersion)}
11220
+ sdk: ${yaml(sdk)}
11221
+ command: ${yaml(command)}
11222
+ finish-args:
11223
+ ${finishArgs.map((arg) => ` - ${yaml(arg)}`).join(`
11224
+ `)}
11225
+ modules:
11226
+ - name: ${yaml(id)}
11227
+ buildsystem: simple
11228
+ build-commands:
11229
+ - ${yaml(`mkdir -p /app/lib/${command} /app/bin`)}
11230
+ - ${yaml(`cp -a ${bundleRoot}/. /app/lib/${command}/`)}
11231
+ - ${yaml(`printf 'flatpak\\n' > /app/lib/${command}/Resources/app/.adea-linux-package`)}
11232
+ - ${yaml(`printf '#!/bin/sh\\nexport ${formatEnvironment}=flatpak\\nexec /app/lib/${command}/${launcher} "$@"\\n' > /app/bin/${command}`)}
11233
+ - ${yaml(`chmod 0755 /app/bin/${command}`)}
11234
+ sources:
11235
+ - type: archive
11236
+ url: ${yaml(asset.url)}
11237
+ sha256: ${yaml(asset.sha256)}
11238
+ strip-components: 0
11239
+ `;
11240
+ return {
11241
+ status: "planned",
11242
+ catalogEligible: false,
11243
+ asset,
11244
+ files: [
11245
+ { path: `${id}.yml`, contents: manifest },
11246
+ {
11247
+ path: `${id}.flatpakrepo.snippet`,
11248
+ contents: `[Flatpak Repo]
11249
+ Title=${context.common.name}
11250
+ Url=${new URL("./", remoteUrl).href}
11251
+ `
11252
+ }
11253
+ ],
11254
+ install: [
11255
+ `flatpak remote-add --user --if-not-exists ${remoteName} ${shell(remoteUrl)}`,
11256
+ `flatpak install --user ${remoteName} ${id}`
11257
+ ].join(" && ")
11258
+ };
11259
+ }
11260
+ var planners = { homebrew, winget, apt, pacman, rpm, flatpak };
11261
+ function parseCommon(policy) {
11262
+ keys2(policy, "policy", ["schema", "appId", "name", "description", "homepage", "license", "releaseBase", "channels"], ["downloads"]);
11263
+ ensure(policy.schema === "framework/package-channels/v1", "Unsupported package channel policy");
11264
+ return {
11265
+ appId: text3(policy.appId, "appId", /^(?=.{1,128}$)[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/),
11266
+ name: text3(policy.name, "product name"),
11267
+ description: text3(policy.description, "description"),
11268
+ homepage: https(policy.homepage, "homepage", true).href,
11269
+ license: text3(policy.license, "license", /^[A-Za-z0-9][A-Za-z0-9.+-]*( (AND|OR) [A-Za-z0-9][A-Za-z0-9.+-]*)*$/),
11270
+ releaseBase: https(policy.releaseBase, "release base", true)
11271
+ };
11272
+ }
11273
+ function downloads(context, value) {
11274
+ if (value === undefined)
11275
+ return [];
11276
+ ensure(Array.isArray(value) && value.length <= 32, "Invalid downloads");
11277
+ return value.map((entry) => {
11278
+ const row = object(entry, "download");
11279
+ keys2(row, "download", ["platform", "label", "artifact"]);
11280
+ const platform = text3(row.platform, "download platform", /^(macos|windows|linux)-(arm64|x64)$/);
11281
+ return {
11282
+ platform,
11283
+ label: text3(row.label, "download label"),
11284
+ ...exact2(context, row.artifact, "download", [
11285
+ ".dmg",
11286
+ "-Setup.exe",
11287
+ "-Setup.zip",
11288
+ ".deb",
11289
+ ".AppImage",
11290
+ ".rpm",
11291
+ "-Setup.tar.gz"
11292
+ ])
11293
+ };
11294
+ });
11295
+ }
11296
+ function planPackageChannels(input) {
11297
+ const policy = object(input.policy, "policy");
11298
+ const common = parseCommon(policy);
11299
+ const manifest = parsePackageChannelManifest(input.manifest);
11300
+ ensure(manifest.appId === null || manifest.appId === common.appId, "The manifest belongs to a different app");
11301
+ const configured = object(policy.channels, "policy.channels");
11302
+ keys2(configured, "policy.channels", [], packageChannelNames);
11303
+ const requested = input.channels ?? packageChannelNames.filter((n) => Object.hasOwn(configured, n));
11304
+ ensure(requested.length > 0, "No package channels requested");
11305
+ ensure(new Set(requested).size === requested.length, "Duplicate package channel");
11306
+ const context = { common, manifest, version: manifest.tag.slice(1) };
11307
+ const channels = {};
11308
+ for (const name of requested) {
11309
+ ensure(packageChannelNames.includes(name), `Unknown package channel ${String(name)}`);
11310
+ try {
11311
+ ensure(Object.hasOwn(configured, name), `The policy does not configure ${name}`);
11312
+ channels[name] = planners[name](context, object(configured[name], `policy.channels.${name}`));
11313
+ } catch (error) {
11314
+ channels[name] = { status: "failed", reason: error.message };
11315
+ }
11316
+ }
11317
+ return {
11318
+ schema: "framework/package-channel-plan/v1",
11319
+ appId: common.appId,
11320
+ tag: manifest.tag,
11321
+ version: context.version,
11322
+ channel: manifest.channel,
11323
+ sourceSha: manifest.sourceSha,
11324
+ downloads: downloads(context, policy.downloads),
11325
+ channels
11326
+ };
11327
+ }
10650
11328
  // src/framework-loader.ts
10651
11329
  var releaseTools = async () => exports_src;
10652
11330
 
@@ -10831,7 +11509,7 @@ var observeDailyNativeEffect = (options, run) => Effect26.gen(function* () {
10831
11509
  ...previous.kind === "private-from-verified-payload" ? [prior.payload] : []
10832
11510
  ] : undefined;
10833
11511
  const earlier = previous && baseline ? yield* snapshot(previous.directory, baseline, baselineFiles) : undefined;
10834
- const signing = requiresDailyInstallerSigning(matrix.profile, check) ? yield* attempt(() => installerSigningPolicy(config, check)) : undefined;
11512
+ const signing = requiresDailyInstallerSigning(matrix, check) ? yield* attempt(() => installerSigningPolicy(config, check)) : undefined;
10835
11513
  const observeSigning = () => Effect26.gen(function* () {
10836
11514
  if (!signing)
10837
11515
  return;
@@ -10988,6 +11666,46 @@ var stageDailyBatchEffect = (options) => Effect27.gen(function* () {
10988
11666
  }));
10989
11667
  return { directory, ...manifest };
10990
11668
  }).pipe(Effect27.scoped);
11669
+ var stagedDailyBatchManifestEffect = (options) => Effect27.gen(function* () {
11670
+ const fs = yield* ReleaseFs;
11671
+ const directory = resolve21(options.directory);
11672
+ const recordPath = join41(directory, "candidate.json");
11673
+ const info = yield* step(() => fs.lstat(recordPath));
11674
+ if (!info.isFile() || info.size < 1 || info.size > 262144)
11675
+ return yield* fail("Invalid Daily candidate record");
11676
+ const record = yield* attempt(async () => JSON.parse((await fs.readFile(recordPath)).toString("utf8")));
11677
+ if (!isRecord(record) || record.schema !== "framework/daily-staged-batch/v1" || !isRecord(record.identity))
11678
+ return yield* fail("Invalid Daily candidate record");
11679
+ const { tag, sourceSha, workflowSha, runId, runAttempt } = record.identity;
11680
+ if (typeof tag !== "string" || typeof sourceSha !== "string" || typeof workflowSha !== "string" || typeof runId !== "string" || typeof runAttempt !== "number")
11681
+ return yield* fail("Invalid Daily candidate identity");
11682
+ const identity = { tag, sourceSha, workflowSha, runId, runAttempt };
11683
+ const artifacts = join41(directory, "artifacts");
11684
+ const receipts = join41(directory, "receipts");
11685
+ const verified = yield* verifyDailyReleaseMatrixEffect({
11686
+ config: options.config,
11687
+ identity,
11688
+ artifacts,
11689
+ receipts
11690
+ });
11691
+ if (JSON.stringify({ schema: record.schema, ...verified }) !== JSON.stringify({
11692
+ schema: record.schema,
11693
+ profile: record.profile,
11694
+ appId: record.appId,
11695
+ identity: record.identity,
11696
+ assets: record.assets
11697
+ }))
11698
+ return yield* fail("Daily candidate differs from its verified inputs");
11699
+ const feed = yield* attempt(() => parseReleaseConfig(options.config).feed);
11700
+ const plan = yield* attempt(() => planDailyReleaseMatrix(options.config, tag));
11701
+ const receiptFiles = yield* Effect27.forEach(plan.checks, (check) => fileIdentityEffect(join41(receipts, `${check.name}.json`), `${check.name}.json`));
11702
+ return {
11703
+ schema: "framework/daily-batch/v1",
11704
+ identity: { appId: verified.appId, feedApp: feed.app, ...identity },
11705
+ artifacts: verified.assets.map(({ name, size, digest }) => ({ name, size, digest })),
11706
+ receipts: receiptFiles.map(({ name, size, digest }) => ({ name, size, digest }))
11707
+ };
11708
+ });
10991
11709
 
10992
11710
  // src/cli-runner.ts
10993
11711
  import { Cause as Cause3, Effect as Effect28, Exit as Exit5 } from "effect";
@@ -10997,6 +11715,16 @@ function failureError(cause) {
10997
11715
  return new Error(error.message);
10998
11716
  return error instanceof Error ? error : new Error(String(error));
10999
11717
  }
11718
+ function publicFailureCause(cause) {
11719
+ const error = Cause3.squash(cause);
11720
+ if (!(error instanceof ReleaseFailure))
11721
+ return;
11722
+ if (error.reason === "refused")
11723
+ return error.message;
11724
+ if (error.reason !== "step")
11725
+ return;
11726
+ return error.original instanceof PublicReleaseError ? error.original.message : undefined;
11727
+ }
11000
11728
  var runCommand = (failure, program, options = {}) => Effect28.gen(function* () {
11001
11729
  const { env } = yield* ReleaseConfig;
11002
11730
  const output = yield* ReleaseOutput;
@@ -11005,8 +11733,13 @@ var runCommand = (failure, program, options = {}) => Effect28.gen(function* () {
11005
11733
  return 0;
11006
11734
  if (Cause3.hasInterruptsOnly(exit.cause))
11007
11735
  return 130;
11008
- const error = failureError(exit.cause);
11009
- output.stderr(`${typeof failure === "string" ? failure : failure(error)}
11736
+ if (typeof failure !== "string") {
11737
+ output.stderr(`${failure(failureError(exit.cause))}
11738
+ `);
11739
+ return 1;
11740
+ }
11741
+ const cause = publicFailureCause(exit.cause);
11742
+ output.stderr(`${cause && cause !== failure ? `${failure}: ${cause}` : failure}
11010
11743
  `);
11011
11744
  return 1;
11012
11745
  });
@@ -11044,7 +11777,7 @@ import { lstat as lstat23, mkdir as mkdir13, readFile as readFile14, readdir as
11044
11777
  import { basename as basename18, dirname as dirname16, join as join42 } from "path";
11045
11778
 
11046
11779
  // src/library/stable-catalogs.ts
11047
- function object(value) {
11780
+ function object2(value) {
11048
11781
  if (typeof value !== "object" || value === null || Array.isArray(value))
11049
11782
  throw new Error("Expected a JSON object");
11050
11783
  return value;
@@ -11063,20 +11796,20 @@ function requireHttps(value, label) {
11063
11796
  var sha = (value) => requireText(value, "SHA-256", /^[a-f0-9]{64}$/);
11064
11797
  var source = (value) => requireText(value, "source SHA", /^[a-f0-9]{40}$/);
11065
11798
  var file = (value) => requireText(value, "asset name", /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/);
11066
- var quoted = JSON.stringify;
11067
- var ruby = (value) => JSON.stringify(value).replace(/#(?=[{@$])/g, "\\#");
11799
+ var quoted2 = JSON.stringify;
11800
+ var ruby2 = (value) => JSON.stringify(value).replace(/#(?=[{@$])/g, "\\#");
11068
11801
  function asset(value) {
11069
- const row = object(value);
11802
+ const row = object2(value);
11070
11803
  const size = row.size;
11071
11804
  if (typeof size !== "number" || !Number.isSafeInteger(size) || size <= 0)
11072
11805
  throw new Error("Invalid asset size");
11073
11806
  return { name: file(row.name), size, sha256: sha(row.sha256) };
11074
11807
  }
11075
11808
  function select(value, name, tag, stable = false) {
11076
- const doc = object(value);
11809
+ const doc = object2(value);
11077
11810
  if (doc.tag !== tag || !Array.isArray(doc.assets) || stable && doc.channel !== "stable")
11078
11811
  throw new Error(stable ? "Expected matching Stable pointer" : "Expected exact asset manifest");
11079
- const matching = doc.assets.filter((row) => object(row).name === name);
11812
+ const matching = doc.assets.filter((row) => object2(row).name === name);
11080
11813
  if (matching.length !== 1)
11081
11814
  throw new Error("Expected exactly one matching installer asset");
11082
11815
  return asset(matching[0]);
@@ -11092,22 +11825,22 @@ function prepareStableCatalog(input) {
11092
11825
  const { channel, phase, measuredAsset } = input;
11093
11826
  if (channel !== "homebrew" && channel !== "winget" || phase !== "preflight" && phase !== "published-stable")
11094
11827
  throw new Error("Invalid catalog channel or release phase");
11095
- const config = object(input.config);
11828
+ const config = object2(input.config);
11096
11829
  const name = requireText(config.name, "product name");
11097
11830
  const desc = requireText(config.description, "description");
11098
11831
  const homepage = requireHttps(config.homepage, "homepage").href;
11099
11832
  const base = requireHttps(config.releaseBase, "release base");
11100
11833
  if (!base.pathname.endsWith("/"))
11101
11834
  throw new Error("Expected release base directory URL");
11102
- const channelConfig = object(config[channel]);
11835
+ const channelConfig = object2(config[channel]);
11103
11836
  if (channel === "homebrew" && channelConfig.artifacts !== undefined) {
11104
- const proofs = object(input.receipt);
11105
- const templates = object(channelConfig.artifacts);
11837
+ const proofs = object2(input.receipt);
11838
+ const templates = object2(channelConfig.artifacts);
11106
11839
  const targets = ["macos-arm64", "macos-x64"];
11107
11840
  if (proofs.schema !== "stable-homebrew-matrix/v1" || !Array.isArray(proofs.receipts) || proofs.receipts.length !== 2 || Object.keys(templates).length !== 2 || !targets.every((target) => Object.hasOwn(templates, target)) || input.measuredAsset !== undefined || input.measuredAssets?.length !== 2)
11108
11841
  throw new Error("Dual-architecture Homebrew requires exactly two native receipts and DMGs");
11109
11842
  const targetFiles = targets.map((target) => {
11110
- const matches = proofs.receipts.map(object).filter((row) => row.platform === target);
11843
+ const matches = proofs.receipts.map(object2).filter((row) => row.platform === target);
11111
11844
  if (matches.length !== 1)
11112
11845
  throw new Error("Expected one native proof per Homebrew architecture");
11113
11846
  const proof = matches[0];
@@ -11142,24 +11875,24 @@ function prepareStableCatalog(input) {
11142
11875
  return [
11143
11876
  {
11144
11877
  path: `Casks/${token}.rb`,
11145
- contents: `cask ${ruby(token)} do
11146
- version ${ruby(arm.tag.slice(1))}
11878
+ contents: `cask ${ruby2(token)} do
11879
+ version ${ruby2(arm.tag.slice(1))}
11147
11880
 
11148
11881
  on_arm do
11149
- sha256 ${ruby(arm.staged.sha256)}
11150
- url ${ruby(arm.url)}
11882
+ sha256 ${ruby2(arm.staged.sha256)}
11883
+ url ${ruby2(arm.url)}
11151
11884
  end
11152
11885
 
11153
11886
  on_intel do
11154
- sha256 ${ruby(intel.staged.sha256)}
11155
- url ${ruby(intel.url)}
11887
+ sha256 ${ruby2(intel.staged.sha256)}
11888
+ url ${ruby2(intel.url)}
11156
11889
  end
11157
11890
 
11158
- name ${ruby(name)}
11159
- desc ${ruby(desc)}
11160
- homepage ${ruby(homepage)}
11891
+ name ${ruby2(name)}
11892
+ desc ${ruby2(desc)}
11893
+ homepage ${ruby2(homepage)}
11161
11894
 
11162
- app ${ruby(bundle)}
11895
+ app ${ruby2(bundle)}
11163
11896
  end
11164
11897
  `
11165
11898
  }
@@ -11167,7 +11900,7 @@ end
11167
11900
  }
11168
11901
  if (input.measuredAssets !== undefined || measuredAsset === undefined)
11169
11902
  throw new Error("Expected one measured catalog installer");
11170
- const receipt = object(input.receipt);
11903
+ const receipt = object2(input.receipt);
11171
11904
  const tag = requireText(receipt.tag, "release tag", /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/);
11172
11905
  if (receipt.schema !== "stable-catalog.v1" || receipt.channel !== channel)
11173
11906
  throw new Error("Wrong qualification receipt");
@@ -11201,18 +11934,18 @@ end
11201
11934
  return [
11202
11935
  {
11203
11936
  path: `Casks/${token}.rb`,
11204
- contents: `cask ${ruby(token)} do
11205
- version ${ruby(version)}
11206
- sha256 ${ruby(staged.sha256)}
11937
+ contents: `cask ${ruby2(token)} do
11938
+ version ${ruby2(version)}
11939
+ sha256 ${ruby2(staged.sha256)}
11207
11940
 
11208
- url ${ruby(url)}
11209
- name ${ruby(name)}
11210
- desc ${ruby(desc)}
11211
- homepage ${ruby(homepage)}
11941
+ url ${ruby2(url)}
11942
+ name ${ruby2(name)}
11943
+ desc ${ruby2(desc)}
11944
+ homepage ${ruby2(homepage)}
11212
11945
 
11213
11946
  depends_on arch: :arm64
11214
11947
 
11215
- app ${ruby(bundle)}
11948
+ app ${ruby2(bundle)}
11216
11949
  end
11217
11950
  `
11218
11951
  }
@@ -11233,8 +11966,8 @@ end
11233
11966
  const schemaVersion = "1.12.0";
11234
11967
  const path = `manifests/${id[0].toLowerCase()}/${id.replaceAll(".", "/")}/${version}/${id}`;
11235
11968
  const manifest = (type, body) => `# yaml-language-server: $schema=https://aka.ms/winget-manifest.${type}.${schemaVersion}.schema.json
11236
- PackageIdentifier: ${quoted(id)}
11237
- PackageVersion: ${quoted(version)}
11969
+ PackageIdentifier: ${quoted2(id)}
11970
+ PackageVersion: ${quoted2(version)}
11238
11971
  ${body}ManifestType: ${type}
11239
11972
  ManifestVersion: ${schemaVersion}
11240
11973
  `;
@@ -11246,25 +11979,25 @@ ManifestVersion: ${schemaVersion}
11246
11979
  contents: manifest("installer", `${directExe ? "InstallerType: exe" : `InstallerType: zip
11247
11980
  NestedInstallerType: exe
11248
11981
  NestedInstallerFiles:
11249
- - RelativeFilePath: ${quoted(exe)}`}
11982
+ - RelativeFilePath: ${quoted2(exe)}`}
11250
11983
  InstallerSwitches:
11251
- Silent: ${quoted(silent)}
11252
- SilentWithProgress: ${quoted(progress)}
11984
+ Silent: ${quoted2(silent)}
11985
+ SilentWithProgress: ${quoted2(progress)}
11253
11986
  Installers:
11254
11987
  - Architecture: x64
11255
- InstallerUrl: ${quoted(url)}
11988
+ InstallerUrl: ${quoted2(url)}
11256
11989
  InstallerSha256: ${staged.sha256.toUpperCase()}
11257
11990
  `)
11258
11991
  },
11259
11992
  {
11260
11993
  path: `${path}.locale.en-US.yaml`,
11261
11994
  contents: manifest("defaultLocale", `PackageLocale: en-US
11262
- Publisher: ${quoted(publisher)}
11263
- PublisherUrl: ${quoted(homepage)}
11264
- PackageName: ${quoted(name)}
11265
- PackageUrl: ${quoted(homepage)}
11266
- License: ${quoted(license)}
11267
- ShortDescription: ${quoted(desc)}
11995
+ Publisher: ${quoted2(publisher)}
11996
+ PublisherUrl: ${quoted2(homepage)}
11997
+ PackageName: ${quoted2(name)}
11998
+ PackageUrl: ${quoted2(homepage)}
11999
+ License: ${quoted2(license)}
12000
+ ShortDescription: ${quoted2(desc)}
11268
12001
  `)
11269
12002
  }
11270
12003
  ];
@@ -11336,17 +12069,71 @@ async function prepareStableCatalogCommand(args) {
11336
12069
  }
11337
12070
  }
11338
12071
 
12072
+ // src/commands/package-channels.ts
12073
+ import { lstat as lstat24, mkdir as mkdir14, readFile as readFile15, rm as rm15, writeFile as writeFile16 } from "fs/promises";
12074
+ import { dirname as dirname17, isAbsolute as isAbsolute9, join as join43, normalize } from "path";
12075
+ var read3 = async (path) => {
12076
+ const stat = await lstat24(path);
12077
+ if (!stat.isFile() || stat.size > 4 * 1024 * 1024)
12078
+ throw new Error("Expected a bounded ordinary JSON file");
12079
+ return JSON.parse(await readFile15(path, "utf8"));
12080
+ };
12081
+ async function packageChannelsCommand(args) {
12082
+ const [policyPath, manifestPath, out, ...names] = args;
12083
+ if (!policyPath || !manifestPath || !out)
12084
+ throw new Error(`Expected policy, manifest, new output directory [${packageChannelNames.join("|")} ...]`);
12085
+ for (const name of names)
12086
+ if (!packageChannelNames.includes(name))
12087
+ throw new Error(`Unknown package channel ${name}`);
12088
+ const plan = planPackageChannels({
12089
+ policy: await read3(policyPath),
12090
+ manifest: await read3(manifestPath),
12091
+ ...names.length ? { channels: names } : {}
12092
+ });
12093
+ await mkdir14(out);
12094
+ try {
12095
+ const summary = {};
12096
+ for (const [name, result] of Object.entries(plan.channels)) {
12097
+ if (result.status === "failed") {
12098
+ summary[name] = result;
12099
+ continue;
12100
+ }
12101
+ for (const file of result.files) {
12102
+ const relative = normalize(file.path);
12103
+ if (isAbsolute9(relative) || relative.split(/[\\/]/).includes(".."))
12104
+ throw new Error("Refusing a channel file outside the output directory");
12105
+ const target = join43(out, name, relative);
12106
+ await mkdir14(dirname17(target), { recursive: true });
12107
+ await writeFile16(target, file.contents, { flag: "wx" });
12108
+ }
12109
+ summary[name] = { ...result, files: result.files.map((file) => file.path) };
12110
+ }
12111
+ await writeFile16(join43(out, "package-channels.json"), JSON.stringify({ ...plan, channels: summary }, null, 2) + `
12112
+ `, { flag: "wx" });
12113
+ } catch (error) {
12114
+ await rm15(out, { recursive: true, force: true });
12115
+ throw error;
12116
+ }
12117
+ const failed = Object.entries(plan.channels).filter(([, result]) => result.status === "failed").map(([name]) => name);
12118
+ return {
12119
+ tag: plan.tag,
12120
+ channel: plan.channel,
12121
+ planned: Object.keys(plan.channels).filter((name) => !failed.includes(name)),
12122
+ failed
12123
+ };
12124
+ }
12125
+
11339
12126
  // src/commands/build-linux-formats.ts
11340
- import { mkdtemp as mkdtemp14, rename as rename3, rm as rm15 } from "fs/promises";
12127
+ import { mkdtemp as mkdtemp14, rename as rename3, rm as rm16 } from "fs/promises";
11341
12128
  import { tmpdir as tmpdir7 } from "os";
11342
- import { basename as basename19, dirname as dirname17, isAbsolute as isAbsolute9, join as join43, resolve as resolve22 } from "path";
12129
+ import { basename as basename19, dirname as dirname18, isAbsolute as isAbsolute10, join as join44, resolve as resolve22 } from "path";
11343
12130
  import { Effect as Effect29 } from "effect";
11344
12131
 
11345
12132
  // src/library/verified-git-source.ts
11346
12133
  import { createHash as createHash28 } from "crypto";
11347
12134
  var id2 = /^[a-f0-9]{40}$/;
11348
12135
  var pathPart = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
11349
- async function object2(git, type, oid, max) {
12136
+ async function object3(git, type, oid, max) {
11350
12137
  if (!id2.test(oid))
11351
12138
  throw new Error("Invalid source object");
11352
12139
  const bytes = await git(["cat-file", type, oid]);
@@ -11355,7 +12142,7 @@ async function object2(git, type, oid, max) {
11355
12142
  return bytes;
11356
12143
  }
11357
12144
  async function verifiedSourceCommit(git, sha) {
11358
- const bytes = await object2(git, "commit", sha, 1024 * 1024);
12145
+ const bytes = await object3(git, "commit", sha, 1024 * 1024);
11359
12146
  const headers = bytes.toString("utf8").split(`
11360
12147
 
11361
12148
  `, 1)[0];
@@ -11368,10 +12155,10 @@ async function verifiedSourceCommit(git, sha) {
11368
12155
  async function verifiedSourceFile(git, rootTree, path) {
11369
12156
  const parts = path.split("/");
11370
12157
  if (path.length > 512 || !parts.length || parts.some((part) => !pathPart.test(part)))
11371
- throw new Error("Invalid source metadata path");
12158
+ throw new PublicReleaseError("Invalid source metadata path");
11372
12159
  let tree = rootTree;
11373
12160
  for (let index = 0;index < parts.length; index++) {
11374
- const bytes = await object2(git, "tree", tree, 8 * 1024 * 1024);
12161
+ const bytes = await object3(git, "tree", tree, 8 * 1024 * 1024);
11375
12162
  let offset = 0;
11376
12163
  let found;
11377
12164
  while (offset < bytes.length) {
@@ -11389,26 +12176,26 @@ async function verifiedSourceFile(git, rootTree, path) {
11389
12176
  offset = zero + 21;
11390
12177
  }
11391
12178
  if (!found)
11392
- throw new Error("Missing source metadata");
12179
+ throw new PublicReleaseError(`Missing source metadata: ${path}`);
11393
12180
  if (index === parts.length - 1) {
11394
12181
  if (found.mode !== "100644" && found.mode !== "100755")
11395
- throw new Error("Source metadata must be a regular blob");
11396
- return object2(git, "blob", found.oid, 262144);
12182
+ throw new PublicReleaseError(`Source metadata must be a regular blob: ${path}`);
12183
+ return object3(git, "blob", found.oid, 262144);
11397
12184
  }
11398
12185
  if (found.mode !== "40000" && found.mode !== "040000")
11399
- throw new Error("Invalid source metadata directory");
12186
+ throw new PublicReleaseError(`Invalid source metadata directory: ${path}`);
11400
12187
  tree = found.oid;
11401
12188
  }
11402
- throw new Error("Missing source metadata");
12189
+ throw new PublicReleaseError(`Missing source metadata: ${path}`);
11403
12190
  }
11404
12191
 
11405
12192
  // src/commands/build-linux-formats.ts
11406
12193
  var sha2565 = /^[a-f0-9]{64}$/;
11407
12194
  var sourcePath = (path) => path.length <= 512 && path.split("/").every((part) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(part));
11408
- var exact2 = (value, required, optional = []) => required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
12195
+ var exact3 = (value, required, optional = []) => required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
11409
12196
  var strings2 = (value, max) => Array.isArray(value) && value.length <= max && value.every((item) => typeof item === "string" && item.length <= 512);
11410
12197
  function parseLinuxFormatBuildPolicy(value) {
11411
- if (!isRecord(value) || !exact2(value, ["schema", "renderer", "appimagetoolSha256", "runtimeSha256", "policy"]) || value.schema !== "linux-format-build-policy/v1" || value.renderer !== "native" && value.renderer !== "cef" || typeof value.appimagetoolSha256 !== "string" || !sha2565.test(value.appimagetoolSha256) || typeof value.runtimeSha256 !== "string" || !sha2565.test(value.runtimeSha256) || !isRecord(value.policy))
12198
+ if (!isRecord(value) || !exact3(value, ["schema", "renderer", "appimagetoolSha256", "runtimeSha256", "policy"]) || value.schema !== "linux-format-build-policy/v1" || value.renderer !== "native" && value.renderer !== "cef" || typeof value.appimagetoolSha256 !== "string" || !sha2565.test(value.appimagetoolSha256) || typeof value.runtimeSha256 !== "string" || !sha2565.test(value.runtimeSha256) || !isRecord(value.policy))
11412
12199
  throw new Error("Invalid Linux format build policy");
11413
12200
  const p = value.policy;
11414
12201
  const required = [
@@ -11441,10 +12228,10 @@ function parseLinuxFormatBuildPolicy(value) {
11441
12228
  "icon",
11442
12229
  "formatEnvironment"
11443
12230
  ];
11444
- if (!exact2(p, required, ["executable", "links"]) || textFields.some((key) => typeof p[key] !== "string" || p[key].length > 512 || [...p[key]].some((character) => {
12231
+ if (!exact3(p, required, ["executable", "links"]) || textFields.some((key) => typeof p[key] !== "string" || p[key].length > 512 || [...p[key]].some((character) => {
11445
12232
  const code = character.charCodeAt(0);
11446
12233
  return code < 32 || code === 127;
11447
- })) || p.executable !== undefined && (typeof p.executable !== "string" || p.executable.length > 64) || !strings2(p.dependencies, 128) || !strings2(p.categories, 32) || !strings2(p.mimeTypes, 32) || !Array.isArray(p.debSetuid) || p.debSetuid.length > 32 || p.debSetuid.some((pin) => !isRecord(pin) || !exact2(pin, ["path", "sha256"]) || typeof pin.path !== "string" || pin.path.length > 512 || typeof pin.sha256 !== "string" || !sha2565.test(pin.sha256)) || p.links !== undefined && (!Array.isArray(p.links) || p.links.length > 32 || p.links.some((link) => !isRecord(link) || !exact2(link, ["name", "target"]) || typeof link.name !== "string" || link.name.length > 64 || typeof link.target !== "string" || link.target.length > 512)))
12234
+ })) || p.executable !== undefined && (typeof p.executable !== "string" || p.executable.length > 64) || !strings2(p.dependencies, 128) || !strings2(p.categories, 32) || !strings2(p.mimeTypes, 32) || !Array.isArray(p.debSetuid) || p.debSetuid.length > 32 || p.debSetuid.some((pin) => !isRecord(pin) || !exact3(pin, ["path", "sha256"]) || typeof pin.path !== "string" || pin.path.length > 512 || typeof pin.sha256 !== "string" || !sha2565.test(pin.sha256)) || p.links !== undefined && (!Array.isArray(p.links) || p.links.length > 32 || p.links.some((link) => !isRecord(link) || !exact3(link, ["name", "target"]) || typeof link.name !== "string" || link.name.length > 64 || typeof link.target !== "string" || link.target.length > 512)))
11448
12235
  throw new Error("Invalid Linux format build policy");
11449
12236
  return {
11450
12237
  renderer: value.renderer,
@@ -11467,7 +12254,7 @@ var buildLinuxFormatsCommand = (args) => runCommand("Unable to build Linux forma
11467
12254
  output,
11468
12255
  ...extra
11469
12256
  ] = args;
11470
- if (extra.length || !sourceSha || !/^[a-f0-9]{40}$/.test(sourceSha) || !expectedRepository || !isRepositorySlug(expectedRepository) || !expectedRunId || !/^[1-9]\d{0,19}$/.test(expectedRunId) || !expectedAttempt || !/^[1-9]\d{0,8}$/.test(expectedAttempt) || expectedChannel !== "daily" && expectedChannel !== "stable" || !descriptorPath || !archive || !tool || !runtime || !output || ![descriptorPath, archive, tool, runtime, output].every(isAbsolute9))
12257
+ if (extra.length || !sourceSha || !/^[a-f0-9]{40}$/.test(sourceSha) || !expectedRepository || !isRepositorySlug(expectedRepository) || !expectedRunId || !/^[1-9]\d{0,19}$/.test(expectedRunId) || !expectedAttempt || !/^[1-9]\d{0,8}$/.test(expectedAttempt) || expectedChannel !== "daily" && expectedChannel !== "stable" || !descriptorPath || !archive || !tool || !runtime || !output || ![descriptorPath, archive, tool, runtime, output].every(isAbsolute10))
11471
12258
  return yield* fail("Expected trusted source, repository, run, attempt and channel, then descriptor, archive, tools and output");
11472
12259
  const { env, platform, arch, cwd } = yield* ReleaseConfig;
11473
12260
  if (platform !== "linux" || !isLinuxPackageArchitecture(arch) || env.CIRCLECI === "true" && env.CIRCLE_SHA1 !== sourceSha || env.GITLAB_CI === "true" && (env.CI_COMMIT_SHA !== sourceSha || env.CI_PIPELINE_ID !== expectedRunId) || env.GITHUB_ACTIONS === "true" && (env.GITHUB_SHA !== sourceSha || env.GITHUB_RUN_ID !== expectedRunId || env.GITHUB_RUN_ATTEMPT !== expectedAttempt))
@@ -11484,8 +12271,8 @@ var buildLinuxFormatsCommand = (args) => runCommand("Unable to build Linux forma
11484
12271
  const manifest = yield* sourceJson("linux-format-build.json");
11485
12272
  if (!isRecord(manifest) || typeof manifest.releaseConfig !== "string" || !sourcePath(manifest.releaseConfig) || manifest.releaseConfig === "linux-format-build.json")
11486
12273
  return yield* fail("Invalid source Linux format manifest");
11487
- const policies = manifest.schema === "linux-format-build-manifest/v2" && exact2(manifest, ["schema", "releaseConfig", "policies"]) && isRecord(manifest.policies) && exact2(manifest.policies, ["x64", "arm64"]) && manifest.policies.x64 !== manifest.policies.arm64 ? manifest.policies : undefined;
11488
- const policyPath = manifest.schema === "linux-format-build-manifest/v1" && exact2(manifest, ["schema", "releaseConfig", "policy"]) && arch === "x64" ? manifest.policy : policies?.[arch];
12274
+ const policies = manifest.schema === "linux-format-build-manifest/v2" && exact3(manifest, ["schema", "releaseConfig", "policies"]) && isRecord(manifest.policies) && exact3(manifest.policies, ["x64", "arm64"]) && manifest.policies.x64 !== manifest.policies.arm64 ? manifest.policies : undefined;
12275
+ const policyPath = manifest.schema === "linux-format-build-manifest/v1" && exact3(manifest, ["schema", "releaseConfig", "policy"]) && arch === "x64" ? manifest.policy : policies?.[arch];
11489
12276
  if (typeof policyPath !== "string" || !sourcePath(policyPath) || policyPath === manifest.releaseConfig || policyPath === "linux-format-build.json")
11490
12277
  return yield* fail("Invalid source Linux format manifest for the native architecture");
11491
12278
  const config = yield* sourceJson(manifest.releaseConfig);
@@ -11523,7 +12310,7 @@ var buildLinuxFormatsCommand = (args) => runCommand("Unable to build Linux forma
11523
12310
  const receipt = yield* Effect29.callback((resume, signal) => {
11524
12311
  const promise = (async () => {
11525
12312
  signal.throwIfAborted();
11526
- const scratch = await mkdtemp14(join43(tmpdir7(), "adea-linux-formats-"));
12313
+ const scratch = await mkdtemp14(join44(tmpdir7(), "adea-linux-formats-"));
11527
12314
  let scratchCleaned = false;
11528
12315
  try {
11529
12316
  signal.throwIfAborted();
@@ -11548,7 +12335,7 @@ var buildLinuxFormatsCommand = (args) => runCommand("Unable to build Linux forma
11548
12335
  arch,
11549
12336
  signal,
11550
12337
  afterWorkCleanup: async () => {
11551
- await rm15(scratch, { recursive: true, force: true });
12338
+ await rm16(scratch, { recursive: true, force: true });
11552
12339
  scratchCleaned = true;
11553
12340
  },
11554
12341
  inspectAppArchive: async () => {
@@ -11558,7 +12345,7 @@ var buildLinuxFormatsCommand = (args) => runCommand("Unable to build Linux forma
11558
12345
  const extracted = await extractVerifiedUpdate({
11559
12346
  descriptor: verified.descriptor,
11560
12347
  archive: copy,
11561
- directory: dirname17(destination),
12348
+ directory: dirname18(destination),
11562
12349
  platform: target.platform,
11563
12350
  renderer: metadata.renderer,
11564
12351
  appName: config.appName,
@@ -11567,16 +12354,16 @@ var buildLinuxFormatsCommand = (args) => runCommand("Unable to build Linux forma
11567
12354
  maxExpandedBytes: 8 * 1024 ** 3
11568
12355
  });
11569
12356
  try {
11570
- await rename3(extracted.payload, join43(destination, metadata.policy.bundleRoot));
12357
+ await rename3(extracted.payload, join44(destination, metadata.policy.bundleRoot));
11571
12358
  } finally {
11572
- await rm15(extracted.directory, { recursive: true, force: true });
12359
+ await rm16(extracted.directory, { recursive: true, force: true });
11573
12360
  }
11574
12361
  },
11575
12362
  run: async (name, toolArgs, options) => {
11576
12363
  if (name !== "dpkg-deb" && name !== "appimagetool")
11577
12364
  throw new Error("Unexpected Linux build tool");
11578
12365
  const executable = name === "dpkg-deb" ? "/usr/bin/dpkg-deb" : options?.executable;
11579
- if (!executable || !isAbsolute9(executable))
12366
+ if (!executable || !isAbsolute10(executable))
11580
12367
  throw new Error("Invalid Linux build tool");
11581
12368
  await linux.tool(executable, toolArgs, {
11582
12369
  PATH: "/usr/bin:/bin",
@@ -11589,7 +12376,7 @@ var buildLinuxFormatsCommand = (args) => runCommand("Unable to build Linux forma
11589
12376
  return result;
11590
12377
  } finally {
11591
12378
  if (!scratchCleaned)
11592
- await rm15(scratch, { recursive: true, force: true });
12379
+ await rm16(scratch, { recursive: true, force: true });
11593
12380
  }
11594
12381
  })();
11595
12382
  promise.then((value) => resume(Effect29.succeed(value)), (error) => resume(Effect29.fail(new ReleaseFailure({
@@ -11608,6 +12395,206 @@ var buildLinuxFormatsCommand = (args) => runCommand("Unable to build Linux forma
11608
12395
  `);
11609
12396
  }));
11610
12397
 
12398
+ // src/commands/daily-batch.ts
12399
+ import { lstat as lstat26, readFile as readFile17 } from "fs/promises";
12400
+ import { resolve as resolve24 } from "path";
12401
+
12402
+ // src/library/daily-batch-directory.ts
12403
+ import { createHash as createHash29, createPrivateKey as createPrivateKey2, createPublicKey as createPublicKey4, randomBytes as randomBytes5, sign as sign2 } from "crypto";
12404
+ import { createReadStream as createReadStream4 } from "fs";
12405
+ import { link as link2, lstat as lstat25, mkdir as mkdir15, readFile as readFile16, rename as rename4, rm as rm17, rmdir as rmdir2, writeFile as writeFile17 } from "fs/promises";
12406
+ import { dirname as dirname19, isAbsolute as isAbsolute11, join as join45, resolve as resolve23 } from "path";
12407
+ var segment2 = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,199}$/;
12408
+ var hash3 = (bytes) => createHash29("sha256").update(bytes).digest("hex");
12409
+ async function regular3(file) {
12410
+ const stat = await lstat25(file);
12411
+ if (!stat.isFile())
12412
+ throw new Error("Daily batch store object is not a regular file");
12413
+ return stat;
12414
+ }
12415
+ var missing = (error) => error?.code === "ENOENT";
12416
+ function createDailyBatchDirectoryStore(root) {
12417
+ if (!isAbsolute11(root))
12418
+ throw new Error("Daily batch store directory must be absolute");
12419
+ const base = resolve23(root);
12420
+ const path = (key) => {
12421
+ const parts = key.split("/");
12422
+ if (key.length > 1024 || parts.length < 2 || !parts.every((part) => segment2.test(part)))
12423
+ throw new Error("Invalid Daily batch store key");
12424
+ return join45(base, ...parts);
12425
+ };
12426
+ return {
12427
+ async putImmutable(key, bytes, size, sha256) {
12428
+ const target = path(key);
12429
+ if (!Number.isSafeInteger(size) || size < 0 || !/^[a-f0-9]{64}$/.test(sha256))
12430
+ throw new Error("Invalid Daily batch object identity");
12431
+ const chunks = [];
12432
+ let length = 0;
12433
+ for await (const chunk of bytes) {
12434
+ length += chunk.byteLength;
12435
+ if (length > size)
12436
+ throw new Error(`Daily batch object too large: ${key}`);
12437
+ chunks.push(chunk);
12438
+ }
12439
+ const body = Buffer.concat(chunks);
12440
+ if (length !== size || hash3(body) !== sha256)
12441
+ throw new Error(`Daily batch object differs from its identity: ${key}`);
12442
+ await mkdir15(dirname19(target), { recursive: true, mode: 448 });
12443
+ const temporary = `${target}.${randomBytes5(8).toString("hex")}.partial`;
12444
+ await writeFile17(temporary, body, { flag: "wx", mode: 384 });
12445
+ let exists = false;
12446
+ try {
12447
+ await link2(temporary, target);
12448
+ } catch (error) {
12449
+ if (error.code !== "EEXIST")
12450
+ throw error;
12451
+ exists = true;
12452
+ } finally {
12453
+ await rm17(temporary, { force: true });
12454
+ }
12455
+ if (exists) {
12456
+ await regular3(target);
12457
+ if (hash3(await readFile16(target)) !== sha256)
12458
+ throw new Error(`Daily batch object already exists with different bytes: ${key}`);
12459
+ }
12460
+ },
12461
+ async readObject(key) {
12462
+ const target = path(key);
12463
+ await regular3(target);
12464
+ return createReadStream4(target);
12465
+ },
12466
+ async readPointer(key) {
12467
+ const target = path(key);
12468
+ try {
12469
+ await regular3(target);
12470
+ const bytes = await readFile16(target);
12471
+ return { version: hash3(bytes), bytes };
12472
+ } catch (error) {
12473
+ if (missing(error))
12474
+ return null;
12475
+ throw error;
12476
+ }
12477
+ },
12478
+ async compareAndSwap(key, expectedVersion, bytes) {
12479
+ const target = path(key);
12480
+ await mkdir15(dirname19(target), { recursive: true, mode: 448 });
12481
+ const lock = `${target}.lock`;
12482
+ try {
12483
+ await mkdir15(lock);
12484
+ } catch (error) {
12485
+ if (error.code === "EEXIST")
12486
+ return false;
12487
+ throw error;
12488
+ }
12489
+ try {
12490
+ let current = null;
12491
+ try {
12492
+ await regular3(target);
12493
+ current = hash3(await readFile16(target));
12494
+ } catch (error) {
12495
+ if (!missing(error))
12496
+ throw error;
12497
+ }
12498
+ if (current !== expectedVersion)
12499
+ return false;
12500
+ const temporary = `${target}.${randomBytes5(8).toString("hex")}.partial`;
12501
+ await writeFile17(temporary, bytes, { flag: "wx", mode: 384 });
12502
+ await rename4(temporary, target);
12503
+ return true;
12504
+ } finally {
12505
+ await rmdir2(lock);
12506
+ }
12507
+ }
12508
+ };
12509
+ }
12510
+ function dailyPointerSignerFromPem(keyId, pem) {
12511
+ const key = createPrivateKey2(pem);
12512
+ if (key.asymmetricKeyType !== "ed25519")
12513
+ throw new Error("Daily pointer key must be Ed25519");
12514
+ return { keyId, sign: async (message) => new Uint8Array(sign2(null, message, key)) };
12515
+ }
12516
+ function parseDailyPointerTrust(value) {
12517
+ if (!value || typeof value !== "object" || Array.isArray(value))
12518
+ throw new Error("Invalid Daily pointer trust");
12519
+ const entries = Object.entries(value);
12520
+ if (!entries.length || entries.length > 16 || !entries.every(([id, key]) => /^[a-z0-9][a-z0-9._-]{0,63}$/.test(id) && typeof key === "string" && Buffer.from(key, "base64").length === 32))
12521
+ throw new Error("Invalid Daily pointer trust");
12522
+ return new Map(entries);
12523
+ }
12524
+
12525
+ // src/commands/daily-batch.ts
12526
+ var usage = [
12527
+ "daily-batch show --dry-run <store-dir> <app-id> <feed-app> <trust.json>",
12528
+ "daily-batch promote --dry-run <store-dir> <release-config.json> <candidate-dir> <key-id> <signing-key.pem> <trust.json>",
12529
+ "daily-batch rollback --dry-run <store-dir> <app-id> <feed-app> <manifest-digest> <key-id> <signing-key.pem> <trust.json>"
12530
+ ].join("; ");
12531
+ var bounded3 = async (path, max, name) => {
12532
+ const stat = await lstat26(path);
12533
+ if (!stat.isFile() || stat.size < 1 || stat.size > max)
12534
+ throw new Error(`Invalid ${name}`);
12535
+ return readFile17(path);
12536
+ };
12537
+ var json2 = async (path, max, name) => JSON.parse((await bounded3(path, max, name)).toString("utf8"));
12538
+ var summary = (snapshot) => snapshot && {
12539
+ sequence: snapshot.sequence,
12540
+ manifestDigest: snapshot.manifestDigest,
12541
+ tag: snapshot.manifest.identity.tag,
12542
+ sourceSha: snapshot.manifest.identity.sourceSha,
12543
+ artifacts: snapshot.manifest.artifacts.length,
12544
+ receipts: snapshot.manifest.receipts.length
12545
+ };
12546
+ async function dailyBatchCommand(args, cwd) {
12547
+ const [action, flag, storeDir, ...operands] = args;
12548
+ if (!action || !["show", "promote", "rollback"].includes(action))
12549
+ throw new Error(`Expected ${usage}`);
12550
+ if (flag !== "--dry-run")
12551
+ throw new Error("Live Daily batch publication is not enabled; pass --dry-run with a local store directory");
12552
+ if (!storeDir)
12553
+ throw new Error(`Expected ${usage}`);
12554
+ const root = resolve24(cwd, storeDir);
12555
+ const rootStat = await lstat26(root);
12556
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink())
12557
+ throw new Error("The Daily batch store must be an existing real directory");
12558
+ const store = createDailyBatchDirectoryStore(root);
12559
+ const signer = async (keyId, path) => dailyPointerSignerFromPem(keyId, (await bounded3(resolve24(cwd, path), 4096, "Daily pointer signing key")).toString("utf8"));
12560
+ const trust = async (path) => parseDailyPointerTrust(await json2(resolve24(cwd, path), 16384, "Daily pointer trust"));
12561
+ if (action === "show") {
12562
+ const [appId, feedApp, trustPath, ...extra] = operands;
12563
+ if (!appId || !feedApp || !trustPath || extra.length)
12564
+ throw new Error(`Expected ${usage}`);
12565
+ const current = await readDailyBatch(store, { appId, feedApp }, await trust(trustPath));
12566
+ return { action, dryRun: true, store: root, current: summary(current) };
12567
+ }
12568
+ if (action === "promote") {
12569
+ const [configPath, candidateDir, keyId, keyPath, trustPath, ...extra] = operands;
12570
+ if (!configPath || !candidateDir || !keyId || !keyPath || !trustPath || extra.length)
12571
+ throw new Error(`Expected ${usage}`);
12572
+ const config = await json2(resolve24(cwd, configPath), 262144, "release configuration");
12573
+ const directory = resolve24(cwd, candidateDir);
12574
+ const selected = await promoteDailyBatch(store, {
12575
+ verify: () => runReleaseLibrary(provideLibraryPorts()(stagedDailyBatchManifestEffect({ config, directory }))),
12576
+ path: (kind, name) => resolve24(directory, kind, name)
12577
+ }, await signer(keyId, keyPath), await trust(trustPath));
12578
+ return { action, dryRun: true, store: root, current: summary(selected) };
12579
+ }
12580
+ const [appId, feedApp, digest, keyId, keyPath, trustPath, ...extra] = operands;
12581
+ if (!appId || !feedApp || !digest || !keyId || !keyPath || !trustPath || extra.length)
12582
+ throw new Error(`Expected ${usage}`);
12583
+ const keys = await trust(trustPath);
12584
+ const target = { appId, feedApp };
12585
+ const current = await readDailyBatch(store, target, keys);
12586
+ if (!current)
12587
+ throw new Error("No Daily batch is selected; nothing to roll back");
12588
+ await rollbackDailyBatch(store, current, await readDailyBatchByDigest(store, target, digest), await signer(keyId, keyPath), keys);
12589
+ return {
12590
+ action,
12591
+ dryRun: true,
12592
+ store: root,
12593
+ previous: summary(current),
12594
+ current: summary(await readDailyBatch(store, target, keys))
12595
+ };
12596
+ }
12597
+
11611
12598
  // src/commands/build-windows-standalone.ts
11612
12599
  import { basename as basename20 } from "path";
11613
12600
  import { Effect as Effect30 } from "effect";
@@ -11641,8 +12628,8 @@ var buildWindowsStandaloneCommand = (args) => runCommand("Unable to build the st
11641
12628
 
11642
12629
  // src/library/apt/stage-apt-repository.ts
11643
12630
  import { spawnSync as spawnSync3 } from "child_process";
11644
- import { lstat as lstat24, mkdir as mkdir14, readFile as readFile15, readdir as readdir16, rm as rm16, unlink as unlink4, writeFile as writeFile16 } from "fs/promises";
11645
- import { dirname as dirname18, isAbsolute as isAbsolute10, join as join44 } from "path";
12631
+ import { lstat as lstat27, mkdir as mkdir16, readFile as readFile18, readdir as readdir16, rm as rm18, unlink as unlink4, writeFile as writeFile18 } from "fs/promises";
12632
+ import { dirname as dirname20, isAbsolute as isAbsolute12, join as join46 } from "path";
11646
12633
  function cmd(program, options, label) {
11647
12634
  const run = spawnSync3(program, options, { encoding: "utf8", timeout: 60000 });
11648
12635
  if (run.error || run.status !== 0)
@@ -11650,14 +12637,14 @@ function cmd(program, options, label) {
11650
12637
  return run.stdout;
11651
12638
  }
11652
12639
  async function add(path, bytes) {
11653
- await mkdir14(dirname18(path), { recursive: true });
11654
- await writeFile16(path, bytes, { flag: "wx" });
12640
+ await mkdir16(dirname20(path), { recursive: true });
12641
+ await writeFile18(path, bytes, { flag: "wx" });
11655
12642
  }
11656
12643
  async function stageAptRepositoryCommand(args) {
11657
12644
  const [tag, policyPath, inventoryPath, packagePath, output, signingHome, trustedFingerprint] = args;
11658
- if (args.length !== 7 || !tag || !/^v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(tag) || !policyPath || !inventoryPath || !packagePath || !output || !signingHome || !isAbsolute10(signingHome) || !trustedFingerprint || !/^[A-F0-9]{40}$/.test(trustedFingerprint))
12645
+ if (args.length !== 7 || !tag || !/^v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(tag) || !policyPath || !inventoryPath || !packagePath || !output || !signingHome || !isAbsolute12(signingHome) || !trustedFingerprint || !/^[A-F0-9]{40}$/.test(trustedFingerprint))
11659
12646
  throw new Error("Expected TAG POLICY VERIFIED_INVENTORY DEB_OR_DIRECTORY NEW_OUTPUT GPG_HOME PINNED_FINGERPRINT");
11660
- const rawPolicy = JSON.parse(await readFile15(policyPath, "utf8"));
12647
+ const rawPolicy = JSON.parse(await readFile18(policyPath, "utf8"));
11661
12648
  if (typeof rawPolicy !== "object" || rawPolicy === null || Array.isArray(rawPolicy))
11662
12649
  throw new Error("Expected APT repository policy");
11663
12650
  const variant = rawPolicy;
@@ -11665,27 +12652,27 @@ async function stageAptRepositoryCommand(args) {
11665
12652
  const policies = multiarch ? variant.packages : [rawPolicy];
11666
12653
  if (!Array.isArray(policies) || policies.length !== (multiarch ? 2 : 1) || policies.some((policy) => !policy || typeof policy !== "object" || !/^[A-Za-z0-9][A-Za-z0-9_.+-]*\.deb$/.test(policy.assetName)))
11667
12654
  throw new Error("Invalid APT release package selection");
11668
- const inventory = JSON.parse(await readFile15(inventoryPath, "utf8"));
12655
+ const inventory = JSON.parse(await readFile18(inventoryPath, "utf8"));
11669
12656
  if (inventory.tag !== tag || !Array.isArray(inventory.assets))
11670
12657
  throw new Error("Verified inventory does not name requested release");
11671
12658
  if (multiarch) {
11672
- if (!(await lstat24(packagePath)).isDirectory())
12659
+ if (!(await lstat27(packagePath)).isDirectory())
11673
12660
  throw new Error("Multiarch APT requires one directory of two ordinary DEBs");
11674
12661
  const entries = await readdir16(packagePath, { withFileTypes: true });
11675
12662
  if (entries.length !== 2 || entries.some((entry) => !entry.isFile() || !policies.some((policy) => entry.name === policy.assetName)))
11676
12663
  throw new Error("Multiarch APT requires exactly the two selected ordinary DEBs");
11677
12664
  }
11678
- await mkdir14(output, { mode: 448 });
12665
+ await mkdir16(output, { mode: 448 });
11679
12666
  try {
11680
12667
  const now = new Date;
11681
12668
  const stagedInputs = [];
11682
12669
  for (const [index, policy] of policies.entries()) {
11683
- const input = multiarch ? join44(packagePath, policy.assetName) : packagePath;
11684
- if (!(await lstat24(input)).isFile())
12670
+ const input = multiarch ? join46(packagePath, policy.assetName) : packagePath;
12671
+ if (!(await lstat27(input)).isFile())
11685
12672
  throw new Error("Expected ordinary Debian package");
11686
- const deb = await readFile15(input);
11687
- const stagedInput = join44(output, `.input-${index}.deb`);
11688
- await writeFile16(stagedInput, deb, { mode: 384, flag: "wx" });
12673
+ const deb = await readFile18(input);
12674
+ const stagedInput = join46(output, `.input-${index}.deb`);
12675
+ await writeFile18(stagedInput, deb, { mode: 384, flag: "wx" });
11689
12676
  const control = cmd("dpkg-deb", ["--field", stagedInput], "Debian control inspection failed");
11690
12677
  stagedInputs.push({ policy, tag, assets: inventory.assets, deb, control, now, stagedInput });
11691
12678
  }
@@ -11694,12 +12681,12 @@ async function stageAptRepositoryCommand(args) {
11694
12681
  const { packagePath: stagedPackagePath, files, release } = stageAptMetadata(single);
11695
12682
  return { files, release, packages: [{ packagePath: stagedPackagePath, deb: single.deb }] };
11696
12683
  })();
11697
- const base = join44(output, "dists", single.policy.suite);
12684
+ const base = join46(output, "dists", single.policy.suite);
11698
12685
  for (const entry of staged.packages)
11699
- await add(join44(output, entry.packagePath), entry.deb);
12686
+ await add(join46(output, entry.packagePath), entry.deb);
11700
12687
  for (const [path, contents] of staged.files)
11701
- await add(join44(base, path), contents);
11702
- await add(join44(base, "Release"), staged.release);
12688
+ await add(join46(base, path), contents);
12689
+ await add(join46(base, "Release"), staged.release);
11703
12690
  const flags = [
11704
12691
  "--batch",
11705
12692
  "--no-tty",
@@ -11716,15 +12703,15 @@ async function stageAptRepositoryCommand(args) {
11716
12703
  ["InRelease", "--clearsign"],
11717
12704
  ["Release.gpg", "--detach-sign"]
11718
12705
  ]) {
11719
- cmd("gpg", [...flags, "--armor", "--output", join44(base, name), mode, join44(base, "Release")], `Could not produce ${name} with the pinned signing identity`);
12706
+ cmd("gpg", [...flags, "--armor", "--output", join46(base, name), mode, join46(base, "Release")], `Could not produce ${name} with the pinned signing identity`);
11720
12707
  }
11721
12708
  for (const { stagedInput } of stagedInputs)
11722
12709
  await unlink4(stagedInput);
11723
- await add(join44(output, "STAGED"), `${tag}
12710
+ await add(join46(output, "STAGED"), `${tag}
11724
12711
  `);
11725
12712
  return { tag, staged: true };
11726
12713
  } catch (error) {
11727
- await rm16(output, { recursive: true, force: true });
12714
+ await rm18(output, { recursive: true, force: true });
11728
12715
  throw error;
11729
12716
  }
11730
12717
  }
@@ -11732,10 +12719,10 @@ async function stageAptRepositoryCommand(args) {
11732
12719
  // src/library/release-retention-cli.ts
11733
12720
  import { constants as constants9 } from "fs";
11734
12721
  import { open as open16 } from "fs/promises";
11735
- import { isAbsolute as isAbsolute11 } from "path";
12722
+ import { isAbsolute as isAbsolute13 } from "path";
11736
12723
 
11737
12724
  // src/library/release-retention.ts
11738
- import { createHash as createHash29 } from "crypto";
12725
+ import { createHash as createHash30 } from "crypto";
11739
12726
  var day = 86400000;
11740
12727
  var safeTag = /^v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.(?:0|[1-9]\d*))?$/;
11741
12728
  var safeAsset = /^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,254}$/;
@@ -11763,7 +12750,7 @@ function unique(rows, key, caption) {
11763
12750
  var byKey = (a, b) => a.key.localeCompare(b.key);
11764
12751
  var ordered = (rows, key) => rows.toSorted((a, b) => key(a).localeCompare(key(b)));
11765
12752
  var stable = (value) => JSON.stringify(value);
11766
- var fingerprint = (value) => createHash29("sha256").update(stable(value)).digest("hex");
12753
+ var fingerprint = (value) => createHash30("sha256").update(stable(value)).digest("hex");
11767
12754
  var latestFirst = (a, b) => date(b.publishedAt) - date(a.publishedAt) || a.tag.localeCompare(b.tag);
11768
12755
  function planReleaseRetention(snapshot) {
11769
12756
  const { app } = snapshot;
@@ -11907,7 +12894,7 @@ function assertRetirementPreflight(plan, fresh, approvedDigest) {
11907
12894
 
11908
12895
  // src/library/release-retention-cli.ts
11909
12896
  var document = async (path) => {
11910
- if (!path || !isAbsolute11(path))
12897
+ if (!path || !isAbsolute13(path))
11911
12898
  throw new Error("Expected an absolute evidence file path");
11912
12899
  const file = await open16(path, constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
11913
12900
  try {
@@ -11937,22 +12924,22 @@ if (false) {}
11937
12924
 
11938
12925
  // src/linux-channel-proof-cli.ts
11939
12926
  import { spawnSync as spawnSync4 } from "child_process";
11940
- import { createHash as createHash30 } from "crypto";
11941
- import { createReadStream as createReadStream4 } from "fs";
12927
+ import { createHash as createHash31 } from "crypto";
12928
+ import { createReadStream as createReadStream5 } from "fs";
11942
12929
  import { constants as constants10, createWriteStream as createWriteStream2 } from "fs";
11943
- import { lstat as lstat25, mkdtemp as mkdtemp15, open as open17, readFile as readFile16, realpath as realpath13, rm as rm17 } from "fs/promises";
12930
+ import { lstat as lstat28, mkdtemp as mkdtemp15, open as open17, readFile as readFile19, realpath as realpath13, rm as rm19 } from "fs/promises";
11944
12931
  import { tmpdir as tmpdir8 } from "os";
11945
- import { basename as basename21, join as join45 } from "path";
12932
+ import { basename as basename21, join as join47 } from "path";
11946
12933
  import { pipeline as pipeline3 } from "stream/promises";
11947
12934
  import { pathToFileURL } from "url";
11948
12935
  function check4(ok, message) {
11949
12936
  if (!ok)
11950
12937
  throw new Error(message);
11951
12938
  }
11952
- async function hash3(path) {
11953
- check4((await lstat25(path)).isFile(), "artifact must be a regular file");
11954
- const digest = createHash30("sha256");
11955
- for await (const chunk of createReadStream4(path))
12939
+ async function hash4(path) {
12940
+ check4((await lstat28(path)).isFile(), "artifact must be a regular file");
12941
+ const digest = createHash31("sha256");
12942
+ for await (const chunk of createReadStream5(path))
11956
12943
  digest.update(chunk);
11957
12944
  return digest.digest("hex");
11958
12945
  }
@@ -11985,11 +12972,11 @@ async function verifyRpmStage(stage) {
11985
12972
  }
11986
12973
  for (const artifact of [stage.payload, stage.rpm]) {
11987
12974
  check4(/^[0-9a-f]{64}$/.test(artifact.sha256), "expected SHA-256");
11988
- check4(await hash3(artifact.path) === artifact.sha256, "staged artifact digest mismatch");
12975
+ check4(await hash4(artifact.path) === artifact.sha256, "staged artifact digest mismatch");
11989
12976
  }
11990
12977
  const repo = await realpath13(stage.repository);
11991
12978
  const keyUrl = pathToFileURL(await realpath13(stage.publicKey)).href;
11992
- const config = options(await readFile16(stage.repoFile, "utf8"), stage.repoId);
12979
+ const config = options(await readFile19(stage.repoFile, "utf8"), stage.repoId);
11993
12980
  check4(config.get("baseurl") === pathToFileURL(repo).href, "expected the local repository");
11994
12981
  check4(config.get("gpgkey") === keyUrl, "expected the configured QA public key");
11995
12982
  for (const flag of ["pkg_gpgcheck", "repo_gpgcheck"]) {
@@ -11999,10 +12986,10 @@ async function verifyRpmStage(stage) {
11999
12986
  check4([...config.keys()].every((key) => allowed.has(key)), "unexpected repository options");
12000
12987
  for (const path of [
12001
12988
  stage.publicKey,
12002
- join45(repo, "repodata/repomd.xml"),
12003
- join45(repo, "repodata/repomd.xml.asc")
12989
+ join47(repo, "repodata/repomd.xml"),
12990
+ join47(repo, "repodata/repomd.xml.asc")
12004
12991
  ]) {
12005
- check4((await lstat25(path)).isFile(), "expected regular key and signed metadata files");
12992
+ check4((await lstat28(path)).isFile(), "expected regular key and signed metadata files");
12006
12993
  }
12007
12994
  const result = spawnSync4("rpm", ["-qp", "--queryformat", "%{NAME}|%{VERSION}|%{ARCH}", await realpath13(stage.rpm.path)], { encoding: "utf8", timeout: 1e4 });
12008
12995
  check4(result.error?.code !== "ENOENT", "rpm is required for RPM header verification");
@@ -12012,12 +12999,12 @@ async function verifyRpmStage(stage) {
12012
12999
  async function verifySignedRpmStage(stage, fingerprint) {
12013
13000
  check4(/^[A-F0-9]{40}$/.test(fingerprint), "expected an independently trusted full primary fingerprint");
12014
13001
  await verifyRpmStage(stage);
12015
- const root = await mkdtemp15(join45(tmpdir8(), "rpm-signature-proof-"));
12016
- const rpm = join45(root, "package.rpm");
12017
- const key = join45(root, "key.asc");
12018
- const metadata = join45(root, "repomd.xml");
12019
- const signature = join45(root, "repomd.xml.asc");
12020
- const originalMetadata = join45(stage.repository, "repodata/repomd.xml");
13002
+ const root = await mkdtemp15(join47(tmpdir8(), "rpm-signature-proof-"));
13003
+ const rpm = join47(root, "package.rpm");
13004
+ const key = join47(root, "key.asc");
13005
+ const metadata = join47(root, "repomd.xml");
13006
+ const signature = join47(root, "repomd.xml.asc");
13007
+ const originalMetadata = join47(stage.repository, "repodata/repomd.xml");
12021
13008
  const originalSignature = `${originalMetadata}.asc`;
12022
13009
  const snapshot = async (source, target, max) => {
12023
13010
  const file = await open17(source, constants10.O_RDONLY | constants10.O_NOFOLLOW);
@@ -12045,7 +13032,7 @@ async function verifySignedRpmStage(stage, fingerprint) {
12045
13032
  await snapshot(stage.publicKey, key, 1024 * 1024);
12046
13033
  await snapshot(originalMetadata, metadata, 8 * 1024 * 1024);
12047
13034
  await snapshot(originalSignature, signature, 1024 * 1024);
12048
- check4(await hash3(rpm) === stage.rpm.sha256, "RPM changed before signature verification");
13035
+ check4(await hash4(rpm) === stage.rpm.sha256, "RPM changed before signature verification");
12049
13036
  const gpg = ["--no-options", "--batch", "--homedir", root, "--no-auto-key-retrieve"];
12050
13037
  const list = command("gpg", [...gpg, "--with-colons", "--fingerprint", "--show-keys", key]);
12051
13038
  const lines = list.split(`
@@ -12058,7 +13045,7 @@ async function verifySignedRpmStage(stage, fingerprint) {
12058
13045
  const signatures = verified.split(`
12059
13046
  `).filter((line) => line.startsWith("[GNUPG:] VALIDSIG "));
12060
13047
  check4(signatures.length === 1 && signatures[0].split(" ").at(-1) === fingerprint, "metadata signer does not match pinned primary fingerprint");
12061
- const db = join45(root, "rpmdb");
13048
+ const db = join47(root, "rpmdb");
12062
13049
  command("rpm", ["--dbpath", db, "--initdb"]);
12063
13050
  command("rpmkeys", ["--dbpath", db, "--import", key]);
12064
13051
  command("rpmkeys", ["--dbpath", db, "--define", "_pkgverify_level all", "--checksig", rpm]);
@@ -12072,10 +13059,10 @@ async function verifySignedRpmStage(stage, fingerprint) {
12072
13059
  ]);
12073
13060
  const rpmIdentity = identity.split("|");
12074
13061
  check4(rpmIdentity.length === 5 && rpmIdentity[0] === stage.packageName && /^[0-9]+$/.test(rpmIdentity[1]) && rpmIdentity[2] === stage.version && /^[A-Za-z0-9][A-Za-z0-9._+~^]*$/.test(rpmIdentity[3]) && rpmIdentity[4] === stage.architecture, "signed RPM header does not match the requested package");
12075
- const rpmSha256 = await hash3(rpm);
12076
- const metadataSha256 = await hash3(metadata);
12077
- const signatureSha256 = await hash3(signature);
12078
- check4(await hash3(stage.rpm.path) === rpmSha256 && await hash3(originalMetadata) === metadataSha256 && await hash3(originalSignature) === signatureSha256, "signed inputs changed during verification");
13062
+ const rpmSha256 = await hash4(rpm);
13063
+ const metadataSha256 = await hash4(metadata);
13064
+ const signatureSha256 = await hash4(signature);
13065
+ check4(await hash4(stage.rpm.path) === rpmSha256 && await hash4(originalMetadata) === metadataSha256 && await hash4(originalSignature) === signatureSha256, "signed inputs changed during verification");
12079
13066
  return {
12080
13067
  kind: "rpm-signature-proof",
12081
13068
  sourceSha: stage.sourceSha,
@@ -12086,10 +13073,10 @@ async function verifySignedRpmStage(stage, fingerprint) {
12086
13073
  signatureSha256
12087
13074
  };
12088
13075
  } finally {
12089
- await rm17(root, { recursive: true, force: true });
13076
+ await rm19(root, { recursive: true, force: true });
12090
13077
  }
12091
13078
  }
12092
- var systemTalkDenied = /^(org\.freedesktop\.(Flatpak|DBus|systemd1)|org\.gtk\.GDBus)(\.|$)/;
13079
+ var systemTalkDenied2 = /^(org\.freedesktop\.(Flatpak|DBus|systemd1)|org\.gtk\.GDBus)(\.|$)/;
12093
13080
  function verifyFlatpakCapabilities(policy, result) {
12094
13081
  check4(/^[A-Za-z_][A-Za-z0-9_-]*(\.[A-Za-z_][A-Za-z0-9_-]*){2,}$/.test(policy.applicationId) && result.applicationId === policy.applicationId, "unexpected Flatpak app identity");
12095
13082
  check4(/^[0-9a-f]{40}$/.test(policy.sourceSha) && result.sourceSha === policy.sourceSha && /^[0-9a-f]{64}$/.test(policy.artifactSha256) && result.artifactSha256 === policy.artifactSha256, "Flatpak evidence does not match the expected source and artifact");
@@ -12098,7 +13085,7 @@ function verifyFlatpakCapabilities(policy, result) {
12098
13085
  const actual = result.effectivePermissions;
12099
13086
  check4(cap.sockets.every((name) => name === "wayland" || name === "pulseaudio"), "unsafe socket policy");
12100
13087
  check4(cap.devices.every((name) => name === "dri"), "unsafe device policy");
12101
- check4(cap.sessionTalkNames.every((name) => /^[A-Za-z_][\w-]*(\.[A-Za-z_][\w-]*)+$/.test(name) && !systemTalkDenied.test(name)), "unsafe session-bus policy");
13088
+ check4(cap.sessionTalkNames.every((name) => /^[A-Za-z_][\w-]*(\.[A-Za-z_][\w-]*)+$/.test(name) && !systemTalkDenied2.test(name)), "unsafe session-bus policy");
12102
13089
  check4(typeof actual.network === "boolean" && typeof cap.network === "boolean" && (!actual.network || cap.network === true) && actual.sockets.every((name) => cap.sockets.some((allowed) => allowed === name)) && actual.devices.every((name) => cap.devices.some((allowed) => allowed === name)) && actual.sessionTalkNames.every((name) => cap.sessionTalkNames.includes(name)) && actual.filesystems.length === 0 && actual.systemTalkNames.length === 0, "effective Flatpak permissions exceed policy");
12103
13090
  check4([
12104
13091
  result.localRepositoryInstall,
@@ -12115,15 +13102,15 @@ function verifyFlatpakCapabilities(policy, result) {
12115
13102
 
12116
13103
  // src/linux-rpm-metadata-proof.ts
12117
13104
  import { spawnSync as spawnSync5 } from "child_process";
12118
- import { createHash as createHash31 } from "crypto";
13105
+ import { createHash as createHash32 } from "crypto";
12119
13106
  import { constants as constants11 } from "fs";
12120
- import { lstat as lstat26, open as open18, realpath as realpath14 } from "fs/promises";
12121
- import { isAbsolute as isAbsolute12, join as join46, relative as relative7, resolve as resolve23 } from "path";
13107
+ import { lstat as lstat29, open as open18, realpath as realpath14 } from "fs/promises";
13108
+ import { isAbsolute as isAbsolute14, join as join48, relative as relative7, resolve as resolve25 } from "path";
12122
13109
  import { gunzipSync as gunzipSync2 } from "zlib";
12123
13110
  var maxCompressed = 16 * 1024 * 1024;
12124
13111
  var maxOpen = 32 * 1024 * 1024;
12125
- var digest5 = (bytes) => createHash31("sha256").update(bytes).digest("hex");
12126
- function ensure(ok, reason) {
13112
+ var digest5 = (bytes) => createHash32("sha256").update(bytes).digest("hex");
13113
+ function ensure2(ok, reason) {
12127
13114
  if (!ok)
12128
13115
  throw new Error(reason);
12129
13116
  }
@@ -12183,14 +13170,14 @@ function parseXml(kind, bytes, args = []) {
12183
13170
  maxBuffer: 64 * 1024,
12184
13171
  env: { PATH: "/usr/bin:/bin", LANG: "C" }
12185
13172
  });
12186
- ensure(result.status === 0, `Invalid ${kind} XML or package binding`);
13173
+ ensure2(result.status === 0, `Invalid ${kind} XML or package binding`);
12187
13174
  return JSON.parse(result.stdout);
12188
13175
  }
12189
13176
  async function readRegular(path, limit) {
12190
13177
  const file = await open18(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
12191
13178
  try {
12192
13179
  const stat = await file.stat();
12193
- ensure(stat.isFile() && stat.size > 0 && stat.size <= limit, "Invalid repository file");
13180
+ ensure2(stat.isFile() && stat.size > 0 && stat.size <= limit, "Invalid repository file");
12194
13181
  const bytes = Buffer.allocUnsafe(stat.size + 1);
12195
13182
  let total = 0;
12196
13183
  while (total < bytes.length) {
@@ -12199,7 +13186,7 @@ async function readRegular(path, limit) {
12199
13186
  break;
12200
13187
  total += bytesRead;
12201
13188
  }
12202
- ensure(total === stat.size, "Repository file changed while reading");
13189
+ ensure2(total === stat.size, "Repository file changed while reading");
12203
13190
  return bytes.subarray(0, total);
12204
13191
  } finally {
12205
13192
  await file.close();
@@ -12209,47 +13196,47 @@ async function digestRegular(path, expectedSize) {
12209
13196
  const file = await open18(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
12210
13197
  try {
12211
13198
  const stat = await file.stat();
12212
- ensure(stat.isFile() && stat.size === expectedSize && stat.size > 0 && stat.size <= 4 * 1024 * 1024 * 1024, "Invalid RPM file");
12213
- const hash = createHash31("sha256");
13199
+ ensure2(stat.isFile() && stat.size === expectedSize && stat.size > 0 && stat.size <= 4 * 1024 * 1024 * 1024, "Invalid RPM file");
13200
+ const hash = createHash32("sha256");
12214
13201
  let size = 0;
12215
13202
  for await (const chunk of file.createReadStream({ autoClose: false })) {
12216
13203
  size += chunk.length;
12217
- ensure(size <= expectedSize, "RPM changed while reading");
13204
+ ensure2(size <= expectedSize, "RPM changed while reading");
12218
13205
  hash.update(chunk);
12219
13206
  }
12220
- ensure(size === expectedSize, "RPM changed while reading");
13207
+ ensure2(size === expectedSize, "RPM changed while reading");
12221
13208
  return hash.digest("hex");
12222
13209
  } finally {
12223
13210
  await file.close();
12224
13211
  }
12225
13212
  }
12226
13213
  async function contained(repo, href) {
12227
- ensure(!isAbsolute12(href) && href.length <= 1024, "Invalid repository path");
13214
+ ensure2(!isAbsolute14(href) && href.length <= 1024, "Invalid repository path");
12228
13215
  const parts = href.split("/");
12229
- ensure(parts.every((part) => /^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(part)), "Invalid repository path");
13216
+ ensure2(parts.every((part) => /^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(part)), "Invalid repository path");
12230
13217
  let current = repo;
12231
13218
  for (let i = 0;i < parts.length; i++) {
12232
- current = join46(current, parts[i]);
12233
- const info = await lstat26(current);
12234
- ensure(i === parts.length - 1 ? info.isFile() : info.isDirectory(), "Unsafe repository path");
13219
+ current = join48(current, parts[i]);
13220
+ const info = await lstat29(current);
13221
+ ensure2(i === parts.length - 1 ? info.isFile() : info.isDirectory(), "Unsafe repository path");
12235
13222
  }
12236
- ensure(await realpath14(current) === current, "Repository path resolves outside its location");
13223
+ ensure2(await realpath14(current) === current, "Repository path resolves outside its location");
12237
13224
  return current;
12238
13225
  }
12239
13226
  async function verifyRpmRepository(stage, fingerprint) {
12240
13227
  const proof = await verifySignedRpmStage(stage, fingerprint);
12241
13228
  const repo = await realpath14(stage.repository);
12242
13229
  const metadata = await readRegular(await contained(repo, "repodata/repomd.xml"), 8 * 1024 * 1024);
12243
- ensure(digest5(metadata) === proof.metadataSha256, "Signed repomd changed");
13230
+ ensure2(digest5(metadata) === proof.metadataSha256, "Signed repomd changed");
12244
13231
  const record = parseXml("repomd", metadata);
12245
13232
  const href = record.href;
12246
13233
  const packedHash = record.checksum;
12247
13234
  const openHash = record.openChecksum;
12248
- ensure(typeof href === "string" && /^repodata\/[A-Za-z0-9][A-Za-z0-9._+-]*\.xml\.(?:gz|zst)$/.test(href), "Unsupported primary metadata location");
12249
- ensure(typeof packedHash === "string" && /^[a-f0-9]{64}$/.test(packedHash) && typeof openHash === "string" && /^[a-f0-9]{64}$/.test(openHash), "Invalid primary metadata checksum");
12250
- ensure(Number.isSafeInteger(record.size) && record.size > 0 && record.size <= maxCompressed && Number.isSafeInteger(record.openSize) && record.openSize > 0 && record.openSize <= maxOpen, "Primary metadata exceeds bounds");
13235
+ ensure2(typeof href === "string" && /^repodata\/[A-Za-z0-9][A-Za-z0-9._+-]*\.xml\.(?:gz|zst)$/.test(href), "Unsupported primary metadata location");
13236
+ ensure2(typeof packedHash === "string" && /^[a-f0-9]{64}$/.test(packedHash) && typeof openHash === "string" && /^[a-f0-9]{64}$/.test(openHash), "Invalid primary metadata checksum");
13237
+ ensure2(Number.isSafeInteger(record.size) && record.size > 0 && record.size <= maxCompressed && Number.isSafeInteger(record.openSize) && record.openSize > 0 && record.openSize <= maxOpen, "Primary metadata exceeds bounds");
12251
13238
  const packed = await readRegular(await contained(repo, href), maxCompressed);
12252
- ensure(packed.length === record.size && digest5(packed) === packedHash, "Primary metadata checksum mismatch");
13239
+ ensure2(packed.length === record.size && digest5(packed) === packedHash, "Primary metadata checksum mismatch");
12253
13240
  let plain;
12254
13241
  if (href.endsWith(".gz")) {
12255
13242
  try {
@@ -12264,16 +13251,16 @@ async function verifyRpmRepository(stage, fingerprint) {
12264
13251
  maxBuffer: maxOpen,
12265
13252
  env: { PATH: "/usr/bin:/bin", LANG: "C" }
12266
13253
  });
12267
- ensure(zstd.status === 0, "Cannot decompress zstd primary metadata within bounds");
13254
+ ensure2(zstd.status === 0, "Cannot decompress zstd primary metadata within bounds");
12268
13255
  plain = zstd.stdout;
12269
13256
  }
12270
- ensure(plain.length === record.openSize && digest5(plain) === openHash, "Uncompressed primary metadata checksum mismatch");
12271
- const rpmPath = resolve23(stage.rpm.path);
13257
+ ensure2(plain.length === record.openSize && digest5(plain) === openHash, "Uncompressed primary metadata checksum mismatch");
13258
+ const rpmPath = resolve25(stage.rpm.path);
12272
13259
  const rpmHref = relative7(repo, rpmPath);
12273
- ensure(!rpmHref.startsWith("../") && rpmHref !== "" && await contained(repo, rpmHref) === rpmPath, "RPM must be a regular file inside the local repository");
12274
- const rpmStat = await lstat26(rpmPath);
13260
+ ensure2(!rpmHref.startsWith("../") && rpmHref !== "" && await contained(repo, rpmHref) === rpmPath, "RPM must be a regular file inside the local repository");
13261
+ const rpmStat = await lstat29(rpmPath);
12275
13262
  parseXml("primary", plain, [...proof.rpmIdentity, rpmHref, proof.rpmSha256, String(rpmStat.size)]);
12276
- ensure(await digestRegular(rpmPath, rpmStat.size) === proof.rpmSha256, "RPM changed during repository verification");
13263
+ ensure2(await digestRegular(rpmPath, rpmStat.size) === proof.rpmSha256, "RPM changed during repository verification");
12277
13264
  return {
12278
13265
  ...proof,
12279
13266
  kind: "rpm-repository-proof",
@@ -12284,8 +13271,8 @@ async function verifyRpmRepository(stage, fingerprint) {
12284
13271
  }
12285
13272
 
12286
13273
  // src/library/arch-publish.ts
12287
- import { createHash as createHash32 } from "crypto";
12288
- import { join as join47 } from "path";
13274
+ import { createHash as createHash33 } from "crypto";
13275
+ import { join as join49 } from "path";
12289
13276
  import { tmpdir as tmpdir9 } from "os";
12290
13277
  import { Effect as Effect31 } from "effect";
12291
13278
 
@@ -12299,7 +13286,7 @@ function archBundle(appName) {
12299
13286
  assertPortableAppName(appName);
12300
13287
  return appName.replaceAll(" ", "");
12301
13288
  }
12302
- function shell(value) {
13289
+ function shell2(value) {
12303
13290
  if (/[\r\n]/.test(value))
12304
13291
  throw new Error("Arch package value spans lines");
12305
13292
  return `'${value.replaceAll("'", "'\\''")}'`;
@@ -12307,7 +13294,7 @@ function shell(value) {
12307
13294
  function array(name, values) {
12308
13295
  if (!values.length)
12309
13296
  return "";
12310
- const lines = values.map((value) => ` ${shell(value)}`).join(`
13297
+ const lines = values.map((value) => ` ${shell2(value)}`).join(`
12311
13298
  `);
12312
13299
  return `${name}=(
12313
13300
  ${lines}
@@ -12373,9 +13360,9 @@ function renderArchPackage(input) {
12373
13360
  `pkgname=${policy.pkgname}`,
12374
13361
  `pkgver=${pkgver}`,
12375
13362
  `pkgrel=${input.pkgrel}`,
12376
- `pkgdesc=${shell(policy.pkgdesc)}`,
13363
+ `pkgdesc=${shell2(policy.pkgdesc)}`,
12377
13364
  "arch=('x86_64')",
12378
- `url=${shell(policy.url)}`,
13365
+ `url=${shell2(policy.url)}`,
12379
13366
  array("license", policy.license),
12380
13367
  array("depends", policy.depends),
12381
13368
  array("optdepends", policy.optdepends),
@@ -12431,11 +13418,11 @@ function renderPacmanRepository(policy) {
12431
13418
  # sudo ADEA_PACMAN_TRUSTED_FINGERPRINT=<verified fingerprint> sh ./install.sh
12432
13419
  set -eu
12433
13420
 
12434
- repo=${shell(repository.name)}
12435
- package=${shell(policy.pkgname)}
12436
- server=${shell(repository.base)}
12437
- key_url=${shell(repository.publicKey)}
12438
- expected=${shell(repository.keyFingerprint)}
13421
+ repo=${shell2(repository.name)}
13422
+ package=${shell2(policy.pkgname)}
13423
+ server=${shell2(repository.base)}
13424
+ key_url=${shell2(repository.publicKey)}
13425
+ expected=${shell2(repository.keyFingerprint)}
12439
13426
 
12440
13427
  if [ "$(id -u)" -ne 0 ]; then
12441
13428
  echo "Run a trusted local copy as root with a verified repository fingerprint" >&2
@@ -12453,6 +13440,19 @@ if printf '%s\\n' "$repositories" | grep -Fxq -- "$repo"; then
12453
13440
  echo "Existing repository $repo requires manual migration before bootstrap" >&2
12454
13441
  exit 1
12455
13442
  fi
13443
+ # Keep explicit package names, but select them only from the newly verified repository.
13444
+ # The POSIX for list is captured before its body rotates the positional parameters.
13445
+ if [ "$#" -eq 0 ]; then set -- "$package"; fi
13446
+ for target do
13447
+ target=\${target#"$repo/"}
13448
+ case "$target" in
13449
+ ''|[!abcdefghijklmnopqrstuvwxyz0123456789]*|*[!abcdefghijklmnopqrstuvwxyz0123456789@+._-]*)
13450
+ echo "Pass only package names from the $repo repository" >&2
13451
+ exit 1 ;;
13452
+ esac
13453
+ shift
13454
+ set -- "$@" "$repo/$target"
13455
+ done
12456
13456
  tmp=$(mktemp)
12457
13457
  trap 'rm -f "$tmp"' EXIT
12458
13458
  curl -fsSL --proto '=https' --proto-redir '=https' "$key_url" -o "$tmp"
@@ -12469,9 +13469,8 @@ fingerprint=$(printf '%s\\n' "$key_records" | awk -F: '
12469
13469
  pacman-key --add "$tmp" >/dev/null
12470
13470
  pacman-key --lsign-key "$expected" >/dev/null
12471
13471
  printf '\\n[%s]\\nSigLevel = Required TrustedOnly\\nServer = %s$arch\\n' "$repo" "$server" >> /etc/pacman.conf
12472
- pacman -Sy --noconfirm >/dev/null
12473
- if [ "$#" -eq 0 ]; then set -- "$package"; fi
12474
- exec pacman -S --needed --noconfirm "$@"
13472
+ echo 'Pacman will refresh repositories and offer a full system upgrade before installing.'
13473
+ exec pacman -Syu --needed -- "$@"
12475
13474
  `;
12476
13475
  return { "install.sh": bootstrap, "pacman.conf": stanza };
12477
13476
  }
@@ -12515,7 +13514,7 @@ var readLicense = (url) => Effect31.gen(function* () {
12515
13514
  return yield* fail("Release license is unavailable");
12516
13515
  }
12517
13516
  const bytes = yield* step(() => readReleaseBytes(response, MAX_LICENSE_BYTES));
12518
- const sha256 = yield* step(async () => createHash32("sha256").update(bytes).digest("hex"));
13517
+ const sha256 = yield* step(async () => createHash33("sha256").update(bytes).digest("hex"));
12519
13518
  return { url, sha256 };
12520
13519
  });
12521
13520
  var git2 = (args) => Effect31.gen(function* () {
@@ -12557,7 +13556,7 @@ var verifyArchRelease = (options) => Effect31.gen(function* () {
12557
13556
  if (!listed)
12558
13557
  return yield* fail(`Missing signed descriptor: ${descriptorPolicy.name}`);
12559
13558
  const bytes = yield* feedBytes(options.feed, `${options.tag}/${descriptorPolicy.name}`, 65536);
12560
- if (!bytes || bytes.length !== listed.size || createHash32("sha256").update(bytes).digest("hex") !== listed.sha256)
13559
+ if (!bytes || bytes.length !== listed.size || createHash33("sha256").update(bytes).digest("hex") !== listed.sha256)
12561
13560
  return yield* fail(`Signed descriptor differs from its release: ${descriptorPolicy.name}`);
12562
13561
  const json = yield* step(async () => {
12563
13562
  try {
@@ -12629,7 +13628,7 @@ var publishArchPackageEffect = (options) => Effect31.gen(function* () {
12629
13628
  const directory = options.printDirectory;
12630
13629
  yield* step(() => fs.mkdir(directory, { recursive: true }));
12631
13630
  for (const [name, contents] of Object.entries({ ...files, ...repositoryFiles }))
12632
- yield* step(() => fs.writeFile(join47(directory, name), contents, { mode: 420 }));
13631
+ yield* step(() => fs.writeFile(join49(directory, name), contents, { mode: 420 }));
12633
13632
  }
12634
13633
  const base = { pkgname: policy.pkgname, pkgver: rendered.pkgver, pkgrel };
12635
13634
  if (options.dryRun)
@@ -12642,14 +13641,14 @@ var publishArchPackageEffect = (options) => Effect31.gen(function* () {
12642
13641
  if (!key.includes("PRIVATE KEY"))
12643
13642
  return yield* fail("AUR_SSH_PRIVATE_KEY_B64 is not a private key");
12644
13643
  return yield* Effect31.gen(function* () {
12645
- const work = yield* step(() => fs.mkdtemp(join47(tmpdir9(), "arch-package-")));
13644
+ const work = yield* step(() => fs.mkdtemp(join49(tmpdir9(), "arch-package-")));
12646
13645
  yield* Effect31.addFinalizer(() => Effect31.promise(() => fs.rm(work, { recursive: true, force: true }).then(() => {
12647
13646
  return;
12648
13647
  }, () => {
12649
13648
  return;
12650
13649
  })));
12651
- const keyFile = join47(work, "aur_id_ed25519");
12652
- const knownHosts = join47(work, "aur_known_hosts");
13650
+ const keyFile = join49(work, "aur_id_ed25519");
13651
+ const knownHosts = join49(work, "aur_known_hosts");
12653
13652
  yield* step(() => fs.mkdir(work, { recursive: true, mode: 448 }));
12654
13653
  yield* step(() => fs.writeFile(keyFile, key.endsWith(`
12655
13654
  `) ? key : `${key}
@@ -12657,7 +13656,7 @@ var publishArchPackageEffect = (options) => Effect31.gen(function* () {
12657
13656
  yield* step(() => fs.writeFile(knownHosts, `${AUR_HOST_KEY}
12658
13657
  `, { mode: 420 }));
12659
13658
  const ssh = `ssh -i "${keyFile}" -o IdentitiesOnly=yes -o UserKnownHostsFile="${knownHosts}" -o StrictHostKeyChecking=yes`;
12660
- const checkout = join47(work, policy.pkgname);
13659
+ const checkout = join49(work, policy.pkgname);
12661
13660
  yield* git2([
12662
13661
  "-c",
12663
13662
  `core.sshCommand=${ssh}`,
@@ -12670,7 +13669,7 @@ var publishArchPackageEffect = (options) => Effect31.gen(function* () {
12670
13669
  checkout
12671
13670
  ]);
12672
13671
  for (const [name, contents] of Object.entries(files))
12673
- yield* step(() => fs.writeFile(join47(checkout, name), contents, { mode: 420 }));
13672
+ yield* step(() => fs.writeFile(join49(checkout, name), contents, { mode: 420 }));
12674
13673
  yield* git2(["-C", checkout, "add", "--", ...Object.keys(files)]);
12675
13674
  const staged = yield* gitExit(["-C", checkout, "diff", "--cached", "--quiet"]);
12676
13675
  if (staged === 0)
@@ -12748,6 +13747,22 @@ var publish = (argv) => {
12748
13747
  yield* print({ tag: result.tag, runId: result.runId, runAttempt: result.runAttempt });
12749
13748
  }), { requireGitHubActions: !local });
12750
13749
  };
13750
+ var publishPackages = (argv) => {
13751
+ const [local, args] = localFlag(argv);
13752
+ return runCommand((error) => `Unable to stage the Linux packages: ${redactedErrorMessage(error)}`, Effect32.gen(function* () {
13753
+ const [directory, configPath, out, ...extra] = args;
13754
+ if (!local || !directory || !configPath || !out || extra.length)
13755
+ return yield* invalid("Expected --local <packages-dir> <release-config.json> <out>");
13756
+ const config = yield* readReleaseConfig(configPath);
13757
+ const { env } = yield* ReleaseConfig;
13758
+ const { RELEASE_TAG: tag, SOURCE_SHA: sourceSha } = env;
13759
+ if (!tag || !sourceSha)
13760
+ return yield* invalid("Missing local release identity");
13761
+ yield* localTagProvenanceEffect({ config, tag, sourceSha });
13762
+ const plan = yield* Effect32.uninterruptible(stageLocalPackagesEffect({ config, directory, out, tag, sourceSha }));
13763
+ return yield* print({ tag, objects: plan.objects.length });
13764
+ }));
13765
+ };
12751
13766
  var cut = (argv) => {
12752
13767
  const [local, args] = localFlag(argv);
12753
13768
  return runCommand((error) => `Unable to cut the release: ${redactedErrorMessage(error)}. Check the trusted workflow or local checkout and release configuration.`, Effect32.gen(function* () {
@@ -12826,7 +13841,7 @@ var planAssets = (args) => runCommand("Unable to plan release assets; check rele
12826
13841
  const { env } = yield* ReleaseConfig;
12827
13842
  yield* print(yield* planReleaseAssetsEffect({ env, config, tag }));
12828
13843
  }));
12829
- var sign2 = (args) => runCommand("Unable to sign release artifact; check the identity, archive and signing key.", Effect32.gen(function* () {
13844
+ var sign3 = (args) => runCommand("Unable to sign release artifact; check the identity, archive and signing key.", Effect32.gen(function* () {
12830
13845
  const [identityPath, artifactPath, feed, ...extra] = args;
12831
13846
  const { env } = yield* ReleaseConfig;
12832
13847
  if (!identityPath || !artifactPath || !feed || extra.length || !env.ADEA_RELEASE_SIGNING_KEY)
@@ -13030,9 +14045,19 @@ var dailyMatrix = (args) => runCommand("Unable to prepare the Daily matrix; chec
13030
14045
  const result = action === "verify" ? yield* verifyDailyReleaseMatrixEffect(options) : yield* stageDailyBatchEffect({ ...options, parent });
13031
14046
  return yield* print(result);
13032
14047
  }));
14048
+ var dailyBatch = (args) => runCommand((error) => `Unable to run the Daily batch command: ${redactedErrorMessage(error)}`, Effect32.gen(function* () {
14049
+ const { cwd } = yield* ReleaseConfig;
14050
+ yield* print(yield* step(() => dailyBatchCommand(args, cwd)));
14051
+ }));
13033
14052
  var prepareStableCatalog2 = (args) => runCommand((error) => `Unable to prepare Stable catalog: ${redactedErrorMessage(error)}`, Effect32.gen(function* () {
13034
14053
  yield* print(yield* step(() => prepareStableCatalogCommand(args)));
13035
14054
  }));
14055
+ var packageChannels = (args) => runCommand((error) => `Unable to plan package channels: ${redactedErrorMessage(error)}`, Effect32.gen(function* () {
14056
+ const result = yield* step(() => packageChannelsCommand(args));
14057
+ yield* print(result);
14058
+ if (result.failed.length)
14059
+ return yield* refuse("refused", `channels failed: ${result.failed.join(", ")}`);
14060
+ }));
13036
14061
  var stageAptRepository = (args) => runCommand((error) => `Unable to stage Apt repository: ${redactedErrorMessage(error)}`, Effect32.gen(function* () {
13037
14062
  yield* print(yield* step(() => stageAptRepositoryCommand(args)));
13038
14063
  }));
@@ -13071,17 +14096,20 @@ var commands = {
13071
14096
  "build-linux-formats": buildLinuxFormatsCommand,
13072
14097
  "build-windows-standalone": buildWindowsStandaloneCommand,
13073
14098
  cut,
14099
+ "daily-batch": dailyBatch,
13074
14100
  "daily-matrix": dailyMatrix,
13075
14101
  finalize,
13076
14102
  "linux-channel-proof": linuxChannelProof,
14103
+ "package-channels": packageChannels,
13077
14104
  "plan-assets": planAssets,
13078
14105
  "prepare-stable-catalog": prepareStableCatalog2,
13079
14106
  "release-retention": releaseRetention,
13080
14107
  promote,
13081
14108
  publish,
13082
14109
  "publish-arch": publishArch,
14110
+ "publish-packages": publishPackages,
13083
14111
  "publish-framework-package": publishFramework,
13084
- sign: sign2,
14112
+ sign: sign3,
13085
14113
  "sign-descriptors": signDescriptors,
13086
14114
  "stage-apt-repository": stageAptRepository,
13087
14115
  step: releaseStep,