#!/usr/bin/env node

/*
 * Standalone MarketingOS release acquisition bootstrap.
 *
 * Trust begins before this file is executed. Its SHA256 must be compared over
 * an independent channel. This file imports Node.js built-ins only. It never
 * executes downloaded product code and never chooses an asset from an index.
 */
import {
  createHash,
  createPublicKey,
  randomBytes,
  verify as verifyEd25519,
} from "node:crypto";
import { spawnSync } from "node:child_process";
import {
  closeSync,
  constants as fsConstants,
  existsSync,
  fchmodSync,
  fstatSync,
  fsyncSync,
  lstatSync,
  mkdirSync,
  openSync,
  readdirSync,
  readSync,
  realpathSync,
  renameSync,
  rmdirSync,
  statSync,
  unlinkSync,
  writeSync,
} from "node:fs";
import http from "node:http";
import https from "node:https";
import path from "node:path";
import { Readable } from "node:stream";
import { createGunzip, createInflateRaw } from "node:zlib";

const BOOTSTRAP_NAME = "marketingos-release-acquire.mjs";
const VERIFIER_NAME = "marketingos-release-verify.mjs";
const PIN_NAME = "marketingos-trust-pins.v1.json";
const MINIMUM_NODE_VERSION = "22.19.0";
const CHANNEL_SCHEMA = "marketingos.releaseChannel.v1";
const RELEASE_SET_SCHEMA = "marketingos.releaseSet.v1";
const RELEASE_SET_SIGNATURE_SCHEMA = "marketingos.releaseSetSignature.v1";
const RELEASE_SET_LATEST_SCHEMA = "marketingos.releaseSetLatest.v1";
const RELEASE_SET_LATEST_ENVELOPE_SCHEMA = "marketingos.releaseSetLatestEnvelope.v1";
const RELEASE_SET_TRUSTED_STATE_SCHEMA = "marketingos.releaseSetTrustedState.v1";
const ACQUIRED_RELEASE_SET_BINDING_SCHEMA = "marketingos.acquiredReleaseSetBinding.v1";
const RELEASE_SET_FILE = "RELEASE-SET.json";
const RELEASE_SET_SIGNATURE_FILE = "RELEASE-SET.signature.json";
const RELEASE_SET_LATEST_FILE = "LATEST.json";
const RELEASE_SET_VALIDITY_MS = 45 * 24 * 60 * 60 * 1000;
const RELEASE_SET_MINIMUM_REMAINING_MS = 30 * 24 * 60 * 60 * 1000;
const RELEASE_SET_CLOCK_SKEW_MS = 5 * 60 * 1000;
const EXTERNAL_RECEIPT_SCHEMA = "marketingos.externalBootstrapReceipt.v1";
const ACQUISITION_RECEIPT_SCHEMA = "marketingos.acquisitionReceipt.v1";
const ACQUISITION_VERIFICATION_SCHEMA =
  "marketingos.acquisitionReceiptVerification.v1";
const RESULT_SCHEMA = "marketingos.releaseAcquisitionResult.v1";
const PRODUCTION_REPOSITORY = "SGforcefs/marketingos";
const PRODUCTION_ORIGIN = "https://releases.scilipoti.de";
const PUBLICATION_TARGETS = Object.freeze([
  "linux-x64",
  "linux-arm64",
  "macos-x64",
  "macos-arm64",
  "windows-x64",
  "audit-witness-linux-x64",
  "audit-witness-linux-arm64",
]);
const TEST_ENVIRONMENT = "fixture-test";
const MAX_REDIRECTS = 2;
const MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
const MAX_JSON_BYTES = 4 * 1024 * 1024;
const MAX_MANIFEST_BYTES = 128 * 1024 * 1024;
const MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;
const MAX_UNPACKED_BYTES = 8 * 1024 * 1024 * 1024;
const MAX_ARCHIVE_ENTRIES = 200_000;
const MAX_PATH_BYTES = 4_096;
const MAX_TAR_STRUCTURAL_BYTES =
  MAX_ARCHIVE_ENTRIES * 1_024 + 64 * 1024 * 1024;
const MAX_TAR_DECOMPRESSED_BYTES =
  MAX_UNPACKED_BYTES + MAX_TAR_STRUCTURAL_BYTES;
const MAX_TAR_ZERO_TAIL_BYTES = 16 * 1024 * 1024;
const DOWNLOAD_IDLE_TIMEOUT_MS = 30_000;
const DOWNLOAD_SMALL_TOTAL_TIMEOUT_MS = 2 * 60_000;
const DOWNLOAD_ARCHIVE_TOTAL_TIMEOUT_MS = 30 * 60_000;
const VERIFIER_TIMEOUT_MS = 2 * 60_000;
const TRUST_BOUNDARY =
  "This receipt is a statement made by the independently hash-checked MarketingOS acquisition bootstrap. It is not a publisher signature.";
const SIDECAR_KINDS = Object.freeze([
  "checksum",
  "release-evidence",
  "sbom",
  "provenance",
  "release-signature",
]);
let activeAcquisitionMode = null;

async function acquire(args) {
  if (args.help) return helpResult();
  const initialPolicy = validateLatestUrl(args.latestUrl, args.testMode, args.target);
  if (activeAcquisitionMode !== null) throw new Error("Acquisition bootstrap is single use");
  activeAcquisitionMode = initialPolicy.mode;
  const inputs = validateLocalInputs(args, initialPolicy);
  const destination = validateNewDestination(args.destination, inputs);
  const lock = acquireDestinationLock(destination);
  let catalogStateLock = null;
  let destinationCreated = false;
  try {
    catalogStateLock = acquireCatalogStateLock(inputs.catalogState);
    if (existsSync(destination))
      throw new Error("Acquisition destination already exists");
    mkdirSync(destination, { mode: 0o700 });
    protectNewDestination(destination);
    destinationCreated = true;
    const downloadDirectory = path.join(destination, "download");
    const verificationDirectory = path.join(destination, "verification");
    mkdirSync(downloadDirectory, { mode: 0o700 });
    mkdirSync(verificationDirectory, { mode: 0o700 });
    const stagedTrust = stageVerifiedTrustInputs(inputs, verificationDirectory);
    const catalog = await downloadAndVerifyReleaseSetCatalog({
      destination,
      initialPolicy,
      stagedTrust,
      catalogStatePath: inputs.catalogState,
    });
    const policy = catalog.routingPolicy;

    const names = canonicalReleaseNames(policy.channelName);
    assertCatalogTargetNames(catalog.target, names, policy);
    const downloaded = new Map();
    const channelRecord = names.ordered.find(
      (record) => record.kind === "release-channel",
    );
    const acquisitionOrder = [
      channelRecord,
      ...names.ordered.filter((record) => record !== channelRecord),
    ];
    for (const record of acquisitionOrder) {
      const target = path.join(downloadDirectory, record.name);
      const source = releaseAssetUrl(policy, record.name);
      const observed = await downloadReleaseFile({
        source,
        target,
        maximumBytes: maximumBytesFor(record.kind),
        expectedName: record.name,
        policy,
      });
      downloaded.set(record.kind, observed);
    }
    assertExactDownloadSet(downloadDirectory, names);
    assertCatalogTargetDownloads(catalog.target, names, downloaded);

    const channelPath = path.join(downloadDirectory, names.channel);
    const channel = readStrictJson(channelPath, "downloaded channel manifest");
    validateRoutingManifest(channel, names, downloaded, policy);
    assertChannelMatchesReleaseSetTarget(channel, catalog.target, catalog.manifest);

    const externalReceiptPath = path.join(
      verificationDirectory,
      "external-bootstrap-receipt.json",
    );
    const verifierResult = runExternalVerifier({
      verifierPath: stagedTrust.verifier.path,
      artifactPath: path.join(downloadDirectory, names.artifact),
      pinPath: stagedTrust.pin.path,
      statePath: inputs.state,
      receiptPath: externalReceiptPath,
      requirePublished: policy.mode === "production",
    });
    const externalReceipt = validateExternalReceipt({
      receiptPath: externalReceiptPath,
      verifierResult,
      verifier: stagedTrust.verifier,
      pin: stagedTrust.pin,
      statePath: inputs.state,
      channel,
      names,
      downloaded,
      downloadDirectory,
    });
    assertDigestUnchanged(
      stagedTrust.verifier.path,
      stagedTrust.verifier,
      "staged external verifier",
    );
    assertDigestUnchanged(
      stagedTrust.pin.path,
      stagedTrust.pin,
      "staged trust pin publication",
    );
    assertDownloadedBundleUnchanged(downloaded);

    const artifactPath = path.join(downloadDirectory, names.artifact);
    applyFixtureExtractionEnvironment(policy);
    assertDigestUnchanged(artifactPath, downloaded.get("artifact"), "artifact");
    const openArtifact = openBoundArchive(
      artifactPath,
      downloaded.get("artifact"),
    );
    let archiveInventory;
    const stagingDirectory = path.join(destination, "staging");
    try {
      await runAcquisitionTestBarrier(
        policy,
        verificationDirectory,
        "before-archive-inspection",
      );
      archiveInventory = names.archiveType === "zip"
        ? inspectZipArchive(openArtifact, names.root, channel.platform)
        : await inspectTarGzArchive(
            openArtifact,
            names.root,
            channel.platform,
          );
      await runAcquisitionTestBarrier(
        policy,
        verificationDirectory,
        "after-archive-inspection-before-extraction",
      );
      assertOpenArchiveContentUnchanged(openArtifact, "artifact");
      mkdirSync(stagingDirectory, { mode: 0o700 });
      await extractVerifiedArchive({
        openArtifact,
        stagingDirectory,
        archiveInventory,
        archiveType: names.archiveType,
        expectedRoot: names.root,
        platform: channel.platform,
      });
      await runAcquisitionTestBarrier(
        policy,
        verificationDirectory,
        "after-extraction-before-artifact-recheck",
      );
      assertOpenArchiveUnchanged(openArtifact, artifactPath, "artifact");
      assertDigestUnchanged(artifactPath, downloaded.get("artifact"), "artifact");
    } finally {
      closeSync(openArtifact.descriptor);
    }
    const extracted = inventoryExtractedPayload({
      stagingDirectory,
      expectedRootName: names.root,
      archiveInventory,
      platform: channel.platform,
    });
    const innerBuildIntegrity = verifyExtractedInnerBuildIntegrity({
      extracted,
      channel,
      artifactKind: names.artifactKind,
      evidencePath: path.join(downloadDirectory, names.evidence),
      evidenceDigest: downloaded.get("release-evidence"),
      artifact: downloaded.get("artifact"),
    });
    assertDownloadedBundleUnchanged(downloaded);
    const finalizedExtracted = inventoryExtractedPayload({
      stagingDirectory,
      expectedRootName: names.root,
      archiveInventory,
      platform: channel.platform,
    });
    if (
      finalizedExtracted.root !== extracted.root ||
      finalizedExtracted.payloadInventorySha256 !== extracted.payloadInventorySha256 ||
      canonicalJson(finalizedExtracted.files) !== canonicalJson(extracted.files)
    ) {
      throw new Error("Extracted payload changed after inner build verification");
    }

    const releaseSet = persistVerifiedCatalogState({
      statePath: inputs.catalogState,
      observedState: catalog.observedState,
      catalog,
    });

    const acquisitionReceiptPath = path.join(
      verificationDirectory,
      "marketingos-acquisition-receipt.v1.json",
    );
    const acquisitionReceipt = writeAcquisitionReceipt({
      receiptPath: acquisitionReceiptPath,
      bootstrap: inputs.bootstrap,
      policy,
      externalReceipt,
      artifactPath,
      artifact: downloaded.get("artifact"),
      channel,
      channelDigest: downloaded.get("release-channel"),
      extracted: finalizedExtracted,
      stagingDirectory,
      innerBuildIntegrity,
      artifactKind: names.artifactKind,
      canonicalRootName: names.root,
      releaseSet,
    });
    const acquisitionReceiptDigest = secureDigestFile(
      acquisitionReceiptPath,
      "acquisition receipt",
      128 * 1024 * 1024,
    );
    const verification = {
      schemaVersion: ACQUISITION_VERIFICATION_SCHEMA,
      ok: true,
      product: "MarketingOS",
      acquisitionMode: policy.mode === "production" ? "production" : "fixture-test",
      canonicalOrigin: policy.origin,
      canonicalRepository: policy.repository,
      releaseTag: `v${channel.version}`,
      channelUrl: policy.channelUrl,
      acquisitionReceiptPath: realpathSync.native(acquisitionReceiptPath),
      acquisitionReceiptSha256: acquisitionReceiptDigest.sha256,
      acquisitionReceiptHash: acquisitionReceipt.receiptHash,
      externalBootstrapReceiptPath: externalReceipt.path,
      externalBootstrapReceiptSha256: externalReceipt.sha256,
      artifactPath: realpathSync.native(artifactPath),
      artifactName: names.artifact,
      artifactKind: names.artifactKind,
      artifactSha256: downloaded.get("artifact").sha256,
      artifactBytes: downloaded.get("artifact").bytes,
      productVersion: channel.version,
      platform: channel.platform,
      architecture: channel.architecture,
      channel: channel.channel,
      sequence: channel.sequence,
      expiresAt: channel.expiresAt,
      releaseSet,
      extractedRoot: finalizedExtracted.root,
      canonicalRootName: names.root,
      files: finalizedExtracted.files,
      payloadInventorySha256: finalizedExtracted.payloadInventorySha256,
      innerBuildIntegrity,
      productCodeExecuted: false,
    };
    const acquisitionVerificationPath = path.join(
      verificationDirectory,
      "marketingos-acquisition-verification.v1.json",
    );
    atomicJson(acquisitionVerificationPath, verification);
    const acquisitionVerificationDigest = secureDigestFile(
      acquisitionVerificationPath,
      "persisted acquisition verification",
      128 * 1024 * 1024,
    );
    return {
      schemaVersion: RESULT_SCHEMA,
      ok: true,
      destination: realpathSync.native(destination),
      downloadDirectory: realpathSync.native(downloadDirectory),
      stagingDirectory: realpathSync.native(stagingDirectory),
      artifactPath: verification.artifactPath,
      artifactName: verification.artifactName,
      artifactKind: verification.artifactKind,
      artifactSha256: verification.artifactSha256,
      acquisitionMode: verification.acquisitionMode,
      canonicalOrigin: verification.canonicalOrigin,
      canonicalRepository: verification.canonicalRepository,
      releaseTag: verification.releaseTag,
      channelUrl: verification.channelUrl,
      productVersion: verification.productVersion,
      platform: verification.platform,
      architecture: verification.architecture,
      channel: verification.channel,
      sequence: verification.sequence,
      expiresAt: verification.expiresAt,
      releaseSet: verification.releaseSet,
      extractedRoot: verification.extractedRoot,
      canonicalRootName: verification.canonicalRootName,
      acquisitionReceiptPath: verification.acquisitionReceiptPath,
      acquisitionReceiptSha256: verification.acquisitionReceiptSha256,
      acquisitionReceiptHash: verification.acquisitionReceiptHash,
      acquisitionVerificationPath: realpathSync.native(acquisitionVerificationPath),
      acquisitionVerificationSha256: acquisitionVerificationDigest.sha256,
      externalBootstrapReceiptPath: verification.externalBootstrapReceiptPath,
      externalBootstrapReceiptSha256:
        verification.externalBootstrapReceiptSha256,
      productCodeExecuted: false,
      verification,
    };
  } catch (error) {
    if (destinationCreated) writeFailureMarker(destination, error);
    throw error;
  } finally {
    releaseCatalogStateLock(catalogStateLock);
    releaseDestinationLock(lock);
  }
}

function parseArguments(values) {
  const result = Object.create(null);
  const allowed = new Set([
    "--latest-url",
    "--target",
    "--verifier",
    "--verifier-sha256",
    "--pin",
    "--pin-sha256",
    "--state",
    "--catalog-state",
    "--release-key",
    "--destination",
  ]);
  for (let index = 0; index < values.length; index += 1) {
    const value = values[index];
    if (value === "--help" || value === "-h") {
      result.help = true;
      continue;
    }
    if (value === "--test-mode") {
      if (result.testMode) throw new Error("--test-mode may only be supplied once");
      result.testMode = true;
      continue;
    }
    if (!allowed.has(value)) throw new Error(`Unknown argument: ${value}`);
    const next = values[index + 1];
    if (!next || next.startsWith("--"))
      throw new Error(`${value} requires a value`);
    const key = value
      .slice(2)
      .replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
    if (result[key]) throw new Error(`${value} may only be supplied once`);
    result[key] = next;
    index += 1;
  }
  if (result.help) return result;
  for (const key of [
    "latestUrl",
    "verifier",
    "verifierSha256",
    "pin",
    "pinSha256",
    "state",
    "catalogState",
    "releaseKey",
    "destination",
  ]) {
    if (!result[key]) throw new Error(`--${toKebab(key)} is required`);
  }
  for (const key of ["verifierSha256", "pinSha256"])
    if (!isSha256(result[key]))
      throw new Error(`--${toKebab(key)} must be a lowercase SHA256 digest`);
  result.testMode = result.testMode === true;
  return result;
}

function helpResult() {
  process.stdout.write(helpText());
  process.exit(0);
}

function helpText() {
  return `MarketingOS standalone release acquisition bootstrap\n\nUsage:\n  node ${BOOTSTRAP_NAME} --latest-url <signed-latest-url> --verifier <external-verifier> --verifier-sha256 <independently-obtained-sha256> --pin <trust-pin-json> --pin-sha256 <independently-obtained-sha256> --release-key <reviewed-public-key-pem> --state <persistent-channel-state-json> --catalog-state <persistent-release-set-state-json> --destination <new-empty-path>\n\nThe destination must not exist. Production accepts only the signed global pointer below https://releases.scilipoti.de/v1/latest/. The bootstrap verifies LATEST.json, the immutable release set, all seven target records and all 56 customer file bindings before it derives the current runtime channel URL. It then downloads exactly the selected eight release files, runs only the separately checked external verifier, persists downgrade-resistant release set state, extracts only after successful verification, and never starts product code.\n`;
}

function validateLocalInputs(args, policy) {
  const bootstrap = secureExpectedInput(
    path.resolve(process.argv[1]),
    BOOTSTRAP_NAME,
    sha256File(path.resolve(process.argv[1])),
    "acquisition bootstrap",
    4 * 1024 * 1024,
  );
  const verifier = secureExpectedInput(
    args.verifier,
    VERIFIER_NAME,
    args.verifierSha256,
    "external verifier",
    4 * 1024 * 1024,
  );
  const pin = secureExpectedInput(
    args.pin,
    PIN_NAME,
    args.pinSha256,
    "trust pin publication",
    4 * 1024 * 1024,
  );
  const releaseKey = secureNamedInput(
    args.releaseKey,
    "release-signing-public.pem",
    "release set public key",
    64 * 1024,
  );
  const parsedPin = readStrictJson(pin.path, "trust pin publication");
  const releaseKeyIdentity = validateCatalogPublicKey(releaseKey.path, parsedPin);
  if (policy.mode === "production") {
    if (parsedPin.publicationStatus !== "published") {
      throw new Error(
        "Production acquisition requires a published trust pin publication",
      );
    }
  }
  const state = path.resolve(args.state);
  if (existsSync(state)) assertRegularUnlinkedFile(state, "channel state");
  assertSafeExistingParent(state, "channel state");
  const catalogState = path.resolve(args.catalogState);
  if (existsSync(catalogState)) assertRegularUnlinkedFile(catalogState, "release set catalog state");
  assertSafeExistingParent(catalogState, "release set catalog state");
  if (samePath(state, catalogState)) throw new Error("Channel state and release set catalog state must be separate files");
  return { bootstrap, verifier, pin, releaseKey, releaseKeyIdentity, state, catalogState };
}

function secureExpectedInput(filePath, expectedName, expectedSha256, label, limit) {
  const absolute = path.resolve(filePath);
  if (path.basename(absolute) !== expectedName)
    throw new Error(`${label} must be named ${expectedName}`);
  const digest = secureDigestFile(absolute, label, limit);
  if (digest.sha256 !== expectedSha256)
    throw new Error(`${label} does not match the independently supplied SHA256`);
  return Object.freeze({ path: realpathSync.native(absolute), ...digest });
}

function secureNamedInput(filePath, expectedName, label, limit) {
  const absolute = path.resolve(filePath);
  if (path.basename(absolute) !== expectedName) throw new Error(`${label} must be named ${expectedName}`);
  const digest = secureDigestFile(absolute, label, limit);
  return Object.freeze({ path: realpathSync.native(absolute), ...digest });
}

function stageVerifiedTrustInputs(inputs, verificationDirectory) {
  const trustDirectory = path.join(verificationDirectory, "trust");
  mkdirSync(trustDirectory, { mode: 0o700 });
  const copyOne = (source, label, maximumBytes) => {
    const bytes = secureReadFile(source.path, label, maximumBytes);
    if (bytes.length !== source.bytes || sha256(bytes) !== source.sha256)
      throw new Error(`${label} changed before isolated staging`);
    const target = path.join(trustDirectory, source.name);
    writeNewFile(target, bytes, 0o600);
    const staged = secureDigestFile(target, `staged ${label}`, maximumBytes);
    if (staged.bytes !== source.bytes || staged.sha256 !== source.sha256)
      throw new Error(`Staged ${label} differs from its independently checked source`);
    return staged;
  };
  return Object.freeze({
    verifier: copyOne(inputs.verifier, "external verifier", 4 * 1024 * 1024),
    pin: copyOne(inputs.pin, "trust pin publication", 4 * 1024 * 1024),
    releaseKey: copyOne(inputs.releaseKey, "release set public key", 64 * 1024),
    releaseKeyIdentity: inputs.releaseKeyIdentity,
  });
}

function validateNewDestination(value, inputs) {
  const destination = path.resolve(value);
  if (destination === path.parse(destination).root)
    throw new Error("Acquisition destination cannot be a filesystem root");
  assertSafeExistingParent(destination, "acquisition destination");
  for (const input of [
    inputs.bootstrap.path,
    inputs.verifier.path,
    inputs.pin.path,
    inputs.releaseKey.path,
    inputs.state,
    inputs.catalogState,
  ]) {
    if (pathInside(destination, input) || pathInside(input, destination))
      throw new Error("Acquisition destination must be isolated from trust inputs and state");
  }
  return destination;
}

function validateLatestUrl(value, testMode, requestedTarget) {
  let url;
  try { url = new URL(value); }
  catch { throw new Error("Release set latest URL is invalid"); }
  if (url.username || url.password || url.hash || url.search) throw new Error("Release set latest URL contains forbidden URL components");
  const match = /^\/v1\/latest\/(alpha|beta|stable)\/LATEST\.json$/.exec(url.pathname);
  if (!match) throw new Error("Release set latest URL is not canonical");
  const channel = match[1];
  const automaticTarget = productTargetForRuntime(process.platform, process.arch);
  const target = String(requestedTarget || automaticTarget || "");
  if (!PUBLICATION_TARGETS.includes(target)) throw new Error("Release set acquisition target is invalid");
  if (testMode) {
    if (process.env.MARKETINGOS_ACQUISITION_ENV !== TEST_ENVIRONMENT || process.env.NODE_ENV === "production") {
      throw new Error("Test mode requires MARKETINGOS_ACQUISITION_ENV=fixture-test and a non-production NODE_ENV");
    }
    if (url.protocol !== "http:" || !isLiteralLoopback(url.hostname)) throw new Error("Test mode accepts only a literal loopback HTTP origin");
    return Object.freeze({ mode: "test", origin: url.origin, repository: "fixture-test/marketingos", channel, target, latestUrl: url.toString() });
  }
  if (url.origin !== PRODUCTION_ORIGIN || url.protocol !== "https:" || url.hostname !== "releases.scilipoti.de" || url.port) {
    throw new Error("Production accepts only the canonical releases.scilipoti.de latest pointer");
  }
  if (target !== automaticTarget && target !== `audit-witness-${automaticTarget}`) {
    throw new Error("Production release set target does not match this runtime");
  }
  return Object.freeze({ mode: "production", origin: PRODUCTION_ORIGIN, repository: PRODUCTION_REPOSITORY, channel, target, latestUrl: url.toString() });
}

function productTargetForRuntime(platform, architecture) {
  if (!new Set(["x64", "arm64"]).has(architecture)) return "";
  const label = platform === "win32" ? "windows" : platform === "darwin" ? "macos" : platform === "linux" ? "linux" : "";
  return label ? `${label}-${architecture}` : "";
}

function validateChannelUrl(value, testMode) {
  let url;
  try {
    url = new URL(value);
  } catch {
    throw new Error("Release channel URL is invalid");
  }
  if (url.username || url.password || url.hash)
    throw new Error("Release channel URL cannot contain credentials or a fragment");
  const match = /^\/v1\/channels\/(alpha|beta|stable)\/(linux-x64|linux-arm64|macos-x64|macos-arm64|windows-x64|audit-witness-linux-x64|audit-witness-linux-arm64)\/([1-9][0-9]{0,15})\/([^/]+)$/.exec(
    url.pathname,
  );
  if (!match)
    throw new Error("Release channel URL does not use the immutable publication path");
  const channel = match[1];
  const target = match[2];
  const sequence = Number(match[3]);
  if (!Number.isSafeInteger(sequence) || sequence < 1)
    throw new Error("Release channel URL sequence is invalid");
  if (!PUBLICATION_TARGETS.includes(target))
    throw new Error("Release channel URL target is invalid");
  const channelName = match[4];
  assertSafeBasename(channelName, "release channel filename");
  const names = canonicalReleaseNames(channelName);
  if (publicationTarget(names) !== target)
    throw new Error("Release channel URL target does not match its filename");
  if (url.search)
    throw new Error("Release channel URL cannot contain a query string");

  if (testMode) {
    if (
      process.env.MARKETINGOS_ACQUISITION_ENV !== TEST_ENVIRONMENT ||
      process.env.NODE_ENV === "production"
    ) {
      throw new Error(
        "Test mode requires MARKETINGOS_ACQUISITION_ENV=fixture-test and a non-production NODE_ENV",
      );
    }
    if (url.protocol !== "http:" || !isLiteralLoopback(url.hostname))
      throw new Error("Test mode accepts only a literal loopback HTTP origin");
    return Object.freeze({
      mode: "test",
      origin: url.origin,
      repository: "fixture-test/marketingos",
      channel,
      target,
      sequence,
      channelName,
      channelUrl: url.toString(),
    });
  }

  if (
    url.origin !== PRODUCTION_ORIGIN ||
    url.port ||
    url.hostname !== "releases.scilipoti.de"
  ) {
    throw new Error(
      "Production accepts only https://releases.scilipoti.de release URLs",
    );
  }
  return Object.freeze({
    mode: "production",
    origin: PRODUCTION_ORIGIN,
    repository: PRODUCTION_REPOSITORY,
    channel,
    target,
    sequence,
    channelName,
    channelUrl: url.toString(),
  });
}

function validateCatalogPublicKey(publicKeyPath, pin) {
  const publicPem = decodeUtf8(secureReadFile(publicKeyPath, "release set public key", 64 * 1024), "release set public key");
  const publicKey = createPublicKey(publicPem);
  if (publicKey.asymmetricKeyType !== "ed25519") throw new Error("Release set public key must be Ed25519");
  const der = publicKey.export({ type: "spki", format: "der" });
  const spkiSha256 = sha256(der);
  const keyId = `marketingos-release-ed25519:${spkiSha256.slice(0, 32)}`;
  exactKeys(pin.releaseKey, ["algorithm", "changePolicy", "keyId", "spkiSha256"], "trust pin release key");
  if (
    pin.releaseKey.algorithm !== "Ed25519" || pin.releaseKey.keyId !== keyId ||
    pin.releaseKey.spkiSha256 !== spkiSha256
  ) throw new Error("Release set public key does not match the independently checked trust pin");
  return Object.freeze({ publicPem, publicKey, keyId, spkiSha256 });
}

async function downloadAndVerifyReleaseSetCatalog({ destination, initialPolicy, stagedTrust, catalogStatePath }) {
  const catalogDirectory = path.join(destination, "catalog");
  mkdirSync(catalogDirectory, { mode: 0o700 });
  const key = validateCatalogPublicKey(
    stagedTrust.releaseKey.path,
    readStrictJson(stagedTrust.pin.path, "staged trust pin publication"),
  );
  const latestPath = path.join(catalogDirectory, RELEASE_SET_LATEST_FILE);
  const latestObserved = await downloadReleaseFile({
    source: new URL(initialPolicy.latestUrl),
    target: latestPath,
    maximumBytes: MAX_JSON_BYTES,
    expectedName: RELEASE_SET_LATEST_FILE,
    policy: initialPolicy,
    exactProductionUrl: initialPolicy.latestUrl,
  });
  const latestEnvelope = readStrictJson(latestPath, "signed latest release set pointer");
  const pointer = verifyLatestCatalogEnvelope({ envelope: latestEnvelope, bytes: secureReadFile(latestPath, "signed latest release set pointer", MAX_JSON_BYTES), key, policy: initialPolicy });
  const setUrl = validateCatalogObjectUrl(pointer.releaseSet.url, initialPolicy, pointer.setSequence, RELEASE_SET_FILE);
  const signatureUrl = validateCatalogObjectUrl(pointer.releaseSet.signatureUrl, initialPolicy, pointer.setSequence, RELEASE_SET_SIGNATURE_FILE);
  const setPath = path.join(catalogDirectory, RELEASE_SET_FILE);
  const signaturePath = path.join(catalogDirectory, RELEASE_SET_SIGNATURE_FILE);
  const setObserved = await downloadReleaseFile({
    source: setUrl,
    target: setPath,
    maximumBytes: MAX_JSON_BYTES,
    expectedName: RELEASE_SET_FILE,
    policy: initialPolicy,
    exactProductionUrl: setUrl.toString(),
  });
  const signatureObserved = await downloadReleaseFile({
    source: signatureUrl,
    target: signaturePath,
    maximumBytes: MAX_JSON_BYTES,
    expectedName: RELEASE_SET_SIGNATURE_FILE,
    policy: initialPolicy,
    exactProductionUrl: signatureUrl.toString(),
  });
  const setBytes = secureReadFile(setPath, "immutable release set", MAX_JSON_BYTES);
  const manifest = readStrictJson(setPath, "immutable release set");
  const signature = readStrictJson(signaturePath, "immutable release set signature");
  verifyCatalogManifest({ manifest, signature, setBytes, key, policy: initialPolicy });
  if (
    pointer.releaseSet.bytes !== setObserved.bytes || pointer.releaseSet.sha256 !== setObserved.sha256 ||
    pointer.releaseSet.setHash !== manifest.setHash || pointer.setSequence !== manifest.setSequence ||
    pointer.sourceCommit !== manifest.source.commit || pointer.channel !== manifest.channel ||
    pointer.version !== manifest.version || canonicalJson(pointer.releaseKey) !== canonicalJson(manifest.releaseKey)
  ) throw new Error("Signed latest pointer does not bind the immutable release set");
  const target = manifest.targets.find((item) => item.target === initialPolicy.target);
  if (!target) throw new Error("Release set does not contain the requested runtime target");
  const channelUrl = new URL(target.channelUrlPath, initialPolicy.origin).toString();
  const routingPolicy = validateChannelUrl(channelUrl, initialPolicy.mode === "test");
  if (
    routingPolicy.origin !== initialPolicy.origin || routingPolicy.repository !== initialPolicy.repository ||
    routingPolicy.channel !== initialPolicy.channel || routingPolicy.target !== initialPolicy.target ||
    routingPolicy.sequence !== target.sequence
  ) throw new Error("Release set target routing differs from the signed latest pointer");
  const observedState = readCatalogTrustedState(catalogStatePath, {
    setSequence: pointer.setSequence,
    pointerSha256: latestObserved.sha256,
    releaseSetSha256: setObserved.sha256,
    sourceCommit: pointer.sourceCommit,
  });
  return Object.freeze({
    latestEnvelope,
    pointer,
    manifest,
    signature,
    target,
    routingPolicy,
    observedState,
    latestObserved,
    setObserved,
    signatureObserved,
    latestUrl: initialPolicy.latestUrl,
    setUrl: setUrl.toString(),
    signatureUrl: signatureUrl.toString(),
  });
}

function verifyLatestCatalogEnvelope({ envelope, bytes, key, policy }) {
  exactKeys(envelope, ["algorithm", "keyId", "pointer", "schemaVersion", "signature", "signedAt"], "latest pointer envelope");
  if (envelope.schemaVersion !== RELEASE_SET_LATEST_ENVELOPE_SCHEMA || envelope.algorithm !== "Ed25519" || envelope.keyId !== key.keyId) {
    throw new Error("Latest pointer envelope identity is invalid");
  }
  const pointer = envelope.pointer;
  exactKeys(pointer, [
    "channel", "expiresAt", "issuedAt", "origin", "pointerHash", "pointerLocation", "product",
    "releaseKey", "releaseSet", "schemaVersion", "setSequence", "sourceCommit", "version",
  ], "latest pointer");
  if (
    pointer.schemaVersion !== RELEASE_SET_LATEST_SCHEMA || pointer.product !== "MarketingOS" ||
    pointer.origin !== policy.origin || pointer.channel !== policy.channel ||
    !Number.isSafeInteger(pointer.setSequence) || pointer.setSequence < 1 ||
    !isRuntimeVersion(pointer.version) || !/^[a-f0-9]{40}$/.test(String(pointer.sourceCommit || ""))
  ) throw new Error("Latest pointer release identity is invalid");
  assertCatalogReleaseKey(pointer.releaseKey, key, "latest pointer");
  exactKeys(pointer.pointerLocation, ["policy", "url"], "latest pointer location");
  if (pointer.pointerLocation.policy !== "atomic-replace-single-signed-file" || pointer.pointerLocation.url !== policy.latestUrl) {
    throw new Error("Latest pointer location is invalid");
  }
  exactKeys(pointer.releaseSet, ["bytes", "name", "policy", "setHash", "sha256", "signatureUrl", "url"], "latest pointer release set");
  validateCatalogDigest(pointer.releaseSet, RELEASE_SET_FILE, "latest pointer release set");
  if (pointer.releaseSet.policy !== "immutable-no-overwrite" || !isSha256(pointer.releaseSet.setHash)) throw new Error("Latest pointer release set policy is invalid");
  validateCatalogTimeWindow(pointer.issuedAt, pointer.expiresAt, "latest pointer");
  if (envelope.signedAt !== pointer.issuedAt) throw new Error("Latest pointer signature time is invalid");
  const pointerUnsigned = { ...pointer };
  delete pointerUnsigned.pointerHash;
  if (!isSha256(pointer.pointerHash) || pointer.pointerHash !== sha256Text(canonicalJson(pointerUnsigned))) throw new Error("Latest pointer canonical hash is invalid");
  const unsigned = { ...envelope };
  delete unsigned.signature;
  if (!verifyEd25519(null, Buffer.from(canonicalJson(unsigned), "utf8"), key.publicKey, decodeCatalogSignature(envelope.signature, "latest pointer signature"))) {
    throw new Error("Latest pointer Ed25519 signature is invalid");
  }
  if (sha256(bytes) === "") throw new Error("Latest pointer byte digest is unavailable");
  return pointer;
}

function validateCatalogObjectUrl(value, policy, setSequence, filename) {
  let url;
  try { url = new URL(value); }
  catch { throw new Error("Release set immutable URL is invalid"); }
  const expected = `${policy.origin}/v1/sets/${setSequence}/${filename}`;
  if (url.toString() !== expected || url.username || url.password || url.hash || url.search) throw new Error("Release set immutable URL is not canonical");
  return url;
}

function verifyCatalogManifest({ manifest, signature, setBytes, key, policy }) {
  exactKeys(manifest, [
    "channel", "counts", "createdAt", "immutableLocation", "origin", "product", "releaseKey",
    "schemaVersion", "setHash", "setSequence", "source", "targets", "version", "workflow",
  ], "release set manifest");
  if (
    manifest.schemaVersion !== RELEASE_SET_SCHEMA || manifest.product !== "MarketingOS" ||
    manifest.origin !== policy.origin || manifest.channel !== policy.channel ||
    !Number.isSafeInteger(manifest.setSequence) || manifest.setSequence < 1 || !isRuntimeVersion(manifest.version)
  ) throw new Error("Release set manifest identity is invalid");
  assertCatalogReleaseKey(manifest.releaseKey, key, "release set manifest");
  exactKeys(manifest.source, ["commit", "repository"], "release set source");
  if (manifest.source.repository !== policy.repository || !/^[a-f0-9]{40}$/.test(String(manifest.source.commit || ""))) throw new Error("Release set source identity is invalid");
  exactKeys(manifest.workflow, ["name", "runAttempt", "runId", "runNumber"], "release set workflow");
  if (manifest.workflow.name !== "Official release staging" || ["runId", "runNumber", "runAttempt"].some((keyName) => !/^[1-9]\d*$/.test(String(manifest.workflow[keyName] || "")))) {
    throw new Error("Release set workflow identity is invalid");
  }
  if (!isExactIso(manifest.createdAt) || Date.parse(manifest.createdAt) > Date.now() + RELEASE_SET_CLOCK_SKEW_MS) throw new Error("Release set creation time is invalid");
  exactKeys(manifest.immutableLocation, ["directoryPath", "manifestUrl", "policy", "signatureUrl"], "release set immutable location");
  const setPath = `/v1/sets/${manifest.setSequence}`;
  if (
    manifest.immutableLocation.policy !== "immutable-no-overwrite" || manifest.immutableLocation.directoryPath !== setPath ||
    manifest.immutableLocation.manifestUrl !== `${policy.origin}${setPath}/${RELEASE_SET_FILE}` ||
    manifest.immutableLocation.signatureUrl !== `${policy.origin}${setPath}/${RELEASE_SET_SIGNATURE_FILE}`
  ) throw new Error("Release set immutable location is invalid");
  if (!Array.isArray(manifest.targets) || manifest.targets.length !== 7 || canonicalJson(manifest.targets.map((item) => item.target)) !== canonicalJson(PUBLICATION_TARGETS)) {
    throw new Error("Release set must contain the seven canonical targets");
  }
  for (let index = 0; index < manifest.targets.length; index += 1) validateCatalogTarget(manifest.targets[index], manifest, PUBLICATION_TARGETS[index]);
  exactKeys(manifest.counts, ["customerFiles", "filesPerTarget", "targets"], "release set counts");
  if (manifest.counts.targets !== 7 || manifest.counts.customerFiles !== 56 || manifest.counts.filesPerTarget !== 8) throw new Error("Release set counts are invalid");
  const unsignedManifest = { ...manifest };
  delete unsignedManifest.setHash;
  if (!isSha256(manifest.setHash) || manifest.setHash !== sha256Text(canonicalJson(unsignedManifest))) throw new Error("Release set canonical hash is invalid");
  exactKeys(signature, ["algorithm", "keyId", "schemaVersion", "signature", "signedAt", "subject"], "release set signature");
  if (signature.schemaVersion !== RELEASE_SET_SIGNATURE_SCHEMA || signature.algorithm !== "Ed25519" || signature.keyId !== key.keyId || signature.signedAt !== manifest.createdAt) {
    throw new Error("Release set signature identity is invalid");
  }
  exactKeys(signature.subject, ["bytes", "kind", "name", "sha256"], "release set signature subject");
  validateCatalogDigest(signature.subject, RELEASE_SET_FILE, "release set signature subject");
  if (signature.subject.kind !== "release-set" || signature.subject.bytes !== setBytes.length || signature.subject.sha256 !== sha256(setBytes)) {
    throw new Error("Release set signature subject does not bind the manifest bytes");
  }
  const unsignedSignature = { ...signature };
  delete unsignedSignature.signature;
  if (!verifyEd25519(null, Buffer.from(canonicalJson(unsignedSignature), "utf8"), key.publicKey, decodeCatalogSignature(signature.signature, "release set signature"))) {
    throw new Error("Release set Ed25519 signature is invalid");
  }
}

function validateCatalogTarget(target, manifest, expectedTarget) {
  exactKeys(target, [
    "architecture", "channel", "channelUrlPath", "expiresAt", "files", "issuedAt", "platform",
    "relativeDirectory", "sequence", "source", "target", "version", "workflow",
  ], `release set target ${expectedTarget}`);
  const identity = catalogTargetIdentity(expectedTarget);
  if (
    target.target !== expectedTarget || target.platform !== identity.platform || target.architecture !== identity.architecture ||
    target.channel !== manifest.channel || target.version !== manifest.version || !Number.isSafeInteger(target.sequence) || target.sequence < 1 ||
    canonicalJson(target.source) !== canonicalJson(manifest.source) || canonicalJson(target.workflow) !== canonicalJson(manifest.workflow)
  ) throw new Error(`Release set target identity is invalid for ${expectedTarget}`);
  validateCatalogTimeWindow(target.issuedAt, target.expiresAt, `release set target ${expectedTarget}`);
  if (Date.parse(target.issuedAt) > Date.parse(manifest.createdAt)) throw new Error("Release set predates a target channel");
  const relativeDirectory = `v1/channels/${manifest.channel}/${expectedTarget}/${target.sequence}`;
  if (target.relativeDirectory !== relativeDirectory) throw new Error(`Release set target directory is invalid for ${expectedTarget}`);
  const artifact = expectedCatalogArtifact(expectedTarget, manifest.version);
  const expectedFiles = canonicalCatalogFiles(artifact);
  if (!Array.isArray(target.files) || target.files.length !== 8 || canonicalJson(target.files.map(({ kind, name }) => ({ kind, name }))) !== canonicalJson(expectedFiles)) {
    throw new Error(`Release set target files are invalid for ${expectedTarget}`);
  }
  const names = new Set();
  for (const file of target.files) {
    exactKeys(file, ["bytes", "kind", "name", "sha256", "urlPath"], `release set ${expectedTarget} file`);
    validateCatalogDigest(file, file.name, `release set ${expectedTarget} file`);
    if (names.has(file.name) || file.urlPath !== `/${relativeDirectory}/${file.name}`) throw new Error(`Release set target file path is invalid for ${expectedTarget}`);
    names.add(file.name);
  }
  const channel = target.files.find((file) => file.kind === "release-channel");
  if (!channel || target.channelUrlPath !== channel.urlPath) throw new Error(`Release set target channel URL is invalid for ${expectedTarget}`);
}

function catalogTargetIdentity(target) {
  const architecture = target.endsWith("arm64") ? "arm64" : "x64";
  const platform = target.startsWith("windows") ? "win32" : target.startsWith("macos") ? "darwin" : "linux";
  return { platform, architecture };
}

function expectedCatalogArtifact(target, version) {
  const identity = catalogTargetIdentity(target);
  if (target.startsWith("audit-witness-")) return `MarketingOS-Audit-Witness-${version}-linux-${identity.architecture}.tar.gz`;
  if (target === "windows-x64") return `MarketingOS-Alpha-${version}-windows-x64.zip`;
  const platform = identity.platform === "darwin" ? "macos" : "linux";
  return `MarketingOS-Alpha-${version}-${platform}-${identity.architecture}.tar.gz`;
}

function canonicalCatalogFiles(artifact) {
  const stem = artifact.endsWith(".zip") ? artifact.slice(0, -4) : artifact;
  return [
    { kind: "artifact", name: artifact },
    { kind: "checksum", name: `${artifact}.sha256` },
    { kind: "release-evidence", name: `${stem}.release-evidence.json` },
    { kind: "sbom", name: `${stem}.sbom.cdx.json` },
    { kind: "provenance", name: `${stem}.intoto.json` },
    { kind: "release-signature", name: `${stem}.signature.json` },
    { kind: "release-channel", name: `${stem}.channel.json` },
    { kind: "release-channel-signature", name: `${stem}.channel.signature.json` },
  ];
}

function assertCatalogTargetNames(target, names, policy) {
  const actual = names.ordered.map(({ kind, name }) => ({ kind, name }));
  const expected = target.files.map(({ kind, name }) => ({ kind, name }));
  if (
    canonicalJson(actual) !== canonicalJson(expected) || names.channel !== path.basename(target.channelUrlPath) ||
    policy.channelUrl !== `${policy.origin}${target.channelUrlPath}`
  ) throw new Error("Selected release filenames differ from the signed release set target");
}

function assertCatalogTargetDownloads(target, names, downloaded) {
  for (const expected of target.files) {
    const observed = downloaded.get(expected.kind);
    if (!observed || observed.name !== expected.name || observed.bytes !== expected.bytes || observed.sha256 !== expected.sha256) {
      throw new Error(`Downloaded ${expected.kind} differs from the signed release set`);
    }
  }
  if (downloaded.size !== names.ordered.length) throw new Error("Downloaded target file count differs from the release set");
}

function assertChannelMatchesReleaseSetTarget(channel, target, manifest) {
  if (
    channel.channel !== target.channel || channel.version !== target.version || channel.sequence !== target.sequence ||
    channel.platform !== target.platform || channel.architecture !== target.architecture ||
    canonicalJson(channel.releaseKey) !== canonicalJson(manifest.releaseKey)
  ) throw new Error("Downloaded channel identity differs from the signed release set target");
}

function assertCatalogReleaseKey(value, key, label) {
  exactKeys(value, ["algorithm", "keyId", "spkiSha256"], `${label} release key`);
  if (value.algorithm !== "Ed25519" || value.keyId !== key.keyId || value.spkiSha256 !== key.spkiSha256) throw new Error(`${label} release key identity is invalid`);
}

function validateCatalogDigest(value, expectedName, label) {
  if (
    value.name !== expectedName || path.basename(String(value.name || "")) !== value.name ||
    !Number.isSafeInteger(value.bytes) || value.bytes < 1 || !isSha256(value.sha256)
  ) throw new Error(`${label} digest record is invalid`);
}

function validateCatalogTimeWindow(issuedAt, expiresAt, label) {
  if (!isExactIso(issuedAt) || !isExactIso(expiresAt)) throw new Error(`${label} time encoding is invalid`);
  const issued = Date.parse(issuedAt);
  const expires = Date.parse(expiresAt);
  if (expires - issued !== RELEASE_SET_VALIDITY_MS) throw new Error(`${label} validity must be exactly 45 days`);
  if (issued > Date.now() + RELEASE_SET_CLOCK_SKEW_MS) throw new Error(`${label} is issued too far in the future`);
  if (expires < Date.now() + RELEASE_SET_MINIMUM_REMAINING_MS) throw new Error(`${label} has insufficient remaining validity`);
}

function decodeCatalogSignature(value, label) {
  if (!/^[A-Za-z0-9_-]{86}$/.test(String(value || ""))) throw new Error(`${label} encoding is invalid`);
  const bytes = Buffer.from(value, "base64url");
  if (bytes.length !== 64) throw new Error(`${label} length is invalid`);
  return bytes;
}

function readCatalogTrustedState(statePath, candidate) {
  if (!existsSync(statePath)) return Object.freeze({ exists: false, digest: null, value: null });
  assertRegularUnlinkedFile(statePath, "release set catalog state");
  const digest = secureDigestFile(statePath, "release set catalog state", MAX_JSON_BYTES);
  const value = readStrictJson(statePath, "release set catalog state");
  exactKeys(value, ["pointerSha256", "releaseSetSha256", "schemaVersion", "setSequence", "sourceCommit"], "release set catalog state");
  if (
    value.schemaVersion !== RELEASE_SET_TRUSTED_STATE_SCHEMA || !Number.isSafeInteger(value.setSequence) || value.setSequence < 1 ||
    !isSha256(value.pointerSha256) || !isSha256(value.releaseSetSha256) || !/^[a-f0-9]{40}$/.test(String(value.sourceCommit || ""))
  ) throw new Error("Release set catalog state is invalid");
  if (candidate.setSequence < value.setSequence) throw new Error("Release set latest pointer is a downgrade");
  if (candidate.setSequence === value.setSequence && (
    candidate.pointerSha256 !== value.pointerSha256 || candidate.releaseSetSha256 !== value.releaseSetSha256 || candidate.sourceCommit !== value.sourceCommit
  )) throw new Error("Release set pointer substitution was detected at a trusted sequence");
  return Object.freeze({ exists: true, digest, value });
}

function persistVerifiedCatalogState({ statePath, observedState, catalog }) {
  const state = {
    schemaVersion: RELEASE_SET_TRUSTED_STATE_SCHEMA,
    setSequence: catalog.pointer.setSequence,
    pointerSha256: catalog.latestObserved.sha256,
    releaseSetSha256: catalog.setObserved.sha256,
    sourceCommit: catalog.pointer.sourceCommit,
  };
  let digest;
  if (observedState.exists && canonicalJson(observedState.value) === canonicalJson(state)) {
    const current = secureDigestFile(statePath, "release set catalog state", MAX_JSON_BYTES);
    if (current.sha256 !== observedState.digest.sha256 || current.bytes !== observedState.digest.bytes) throw new Error("Release set catalog state changed during acquisition");
    digest = current;
  } else {
    replaceCatalogStateAtomically(statePath, state, observedState);
    digest = secureDigestFile(statePath, "persisted release set catalog state", MAX_JSON_BYTES);
  }
  return Object.freeze({
    schemaVersion: ACQUIRED_RELEASE_SET_BINDING_SCHEMA,
    setSequence: catalog.pointer.setSequence,
    setHash: catalog.manifest.setHash,
    sourceCommit: catalog.manifest.source.commit,
    sourceRepository: catalog.manifest.source.repository,
    version: catalog.manifest.version,
    channel: catalog.manifest.channel,
    target: catalog.target.target,
    latestUrl: catalog.latestUrl,
    pointerSha256: catalog.latestObserved.sha256,
    releaseSetUrl: catalog.setUrl,
    releaseSetSha256: catalog.setObserved.sha256,
    releaseSetSignatureUrl: catalog.signatureUrl,
    releaseSetSignatureSha256: catalog.signatureObserved.sha256,
    channelUrl: catalog.routingPolicy.channelUrl,
    catalogStatePath: realpathSync.native(statePath),
    catalogStateSha256: digest.sha256,
  });
}

function replaceCatalogStateAtomically(statePath, value, observedState) {
  const temporary = path.join(path.dirname(statePath), `.${path.basename(statePath)}.${process.pid}.${randomBytes(12).toString("hex")}.tmp`);
  try {
    writeNewFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 0o600);
    if (observedState.exists) {
      const current = secureDigestFile(statePath, "release set catalog state before replacement", MAX_JSON_BYTES);
      if (current.sha256 !== observedState.digest.sha256 || current.bytes !== observedState.digest.bytes) throw new Error("Release set catalog state changed before atomic replacement");
    } else if (existsSync(statePath)) {
      throw new Error("Release set catalog state appeared during acquisition");
    }
    renameSync(temporary, statePath);
    fsyncDirectory(path.dirname(statePath));
    assertRegularUnlinkedFile(statePath, "atomically persisted release set catalog state");
  } catch (error) {
    try { unlinkSync(temporary); } catch {}
    throw error;
  }
}

function publicationTarget(names) {
  if (names.artifactKind === "audit-witness") {
    return `audit-witness-linux-${names.root.endsWith("-arm64") ? "arm64" : "x64"}`;
  }
  const platform = names.root.includes("-windows-")
    ? "windows"
    : names.root.includes("-macos-")
      ? "macos"
      : "linux";
  const architecture = names.root.endsWith("-arm64") ? "arm64" : "x64";
  return `${platform}-${architecture}`;
}

function canonicalReleaseNames(channelName) {
  const windows = /^(MarketingOS-Alpha-[A-Za-z0-9][A-Za-z0-9._-]*-windows-x64)\.channel\.json$/.exec(
    channelName,
  );
  const portable = /^(MarketingOS-Alpha-[A-Za-z0-9][A-Za-z0-9._-]*-(?:linux|macos)-(?:x64|arm64)\.tar\.gz)\.channel\.json$/.exec(
    channelName,
  );
  const witness = /^(MarketingOS-Audit-Witness-[A-Za-z0-9][A-Za-z0-9._-]*-linux-(?:x64|arm64)\.tar\.gz)\.channel\.json$/.exec(
    channelName,
  );
  const match = windows || portable || witness;
  if (!match)
    throw new Error("Release channel filename is not canonical");
  const artifact = windows ? `${match[1]}.zip` : match[1];
  const root = windows ? match[1] : artifact.slice(0, -7);
  const sidecarStem = windows ? root : artifact;
  const records = [
    { kind: "artifact", name: artifact },
    { kind: "checksum", name: `${artifact}.sha256` },
    { kind: "release-evidence", name: `${sidecarStem}.release-evidence.json` },
    { kind: "sbom", name: `${sidecarStem}.sbom.cdx.json` },
    { kind: "provenance", name: `${sidecarStem}.intoto.json` },
    { kind: "release-signature", name: `${sidecarStem}.signature.json` },
    { kind: "release-channel", name: channelName },
    {
      kind: "release-channel-signature",
      name: `${sidecarStem}.channel.signature.json`,
    },
  ];
  return Object.freeze({
    root,
    artifactKind: witness ? "audit-witness" : "product",
    artifact,
    archiveType: windows ? "zip" : "tar.gz",
    checksum: records[1].name,
    evidence: records[2].name,
    sbom: records[3].name,
    provenance: records[4].name,
    signature: records[5].name,
    channel: records[6].name,
    channelSignature: records[7].name,
    ordered: Object.freeze(records),
  });
}

function releaseAssetUrl(policy, name) {
  assertSafeBasename(name, "release asset filename");
  return new URL(
    `/v1/channels/${policy.channel}/${policy.target}/${policy.sequence}/${name}`,
    policy.origin,
  );
}

function maximumBytesFor(kind) {
  return {
    artifact: MAX_ARCHIVE_BYTES,
    checksum: 4 * 1024,
    "release-evidence": 128 * 1024 * 1024,
    sbom: 128 * 1024 * 1024,
    provenance: 32 * 1024 * 1024,
    "release-signature": 4 * 1024 * 1024,
    "release-channel": MAX_JSON_BYTES,
    "release-channel-signature": MAX_JSON_BYTES,
  }[kind];
}

async function downloadReleaseFile({
  source,
  target,
  maximumBytes,
  expectedName,
  policy,
  exactProductionUrl = "",
}) {
  let current = source;
  const totalTimeout = maximumBytes === MAX_ARCHIVE_BYTES
    ? DOWNLOAD_ARCHIVE_TOTAL_TIMEOUT_MS
    : DOWNLOAD_SMALL_TOTAL_TIMEOUT_MS;
  const deadline = Date.now() + totalTimeout;
  for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects += 1) {
    validateRequestUrl(current, policy, redirects, exactProductionUrl);
    const response = await requestOnce(current, deadline);
    if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
      response.destroy();
      if (redirects === MAX_REDIRECTS)
        throw new Error(`Too many redirects for ${expectedName}`);
      if (!response.headers.location)
        throw new Error(`Redirect has no Location for ${expectedName}`);
      const next = new URL(response.headers.location, current);
      validateRedirect(next, policy);
      current = next;
      continue;
    }
    if (response.statusCode !== 200) {
      response.destroy();
      throw new Error(
        `Release asset ${expectedName} returned HTTP ${response.statusCode}`,
      );
    }
    return writeDownloadResponse({
      response,
      target,
      maximumBytes,
      expectedName,
      deadline,
    });
  }
  throw new Error(`Redirect handling failed for ${expectedName}`);
}

function requestOnce(url, deadline) {
  return new Promise((resolve, reject) => {
    const client = url.protocol === "https:" ? https : http;
    const remaining = deadline - Date.now();
    if (remaining <= 0) return reject(new Error("Release download total timeout exceeded"));
    const request = client.get(
      url,
      {
        headers: {
          Accept: "application/octet-stream",
          "User-Agent": "MarketingOS-Release-Acquisition/1",
        },
        agent: false,
      },
      (response) => {
        clearTimeout(totalTimer);
        response.setTimeout(DOWNLOAD_IDLE_TIMEOUT_MS, () => {
          response.destroy(new Error("Release download idle timeout exceeded"));
        });
        resolve(response);
      },
    );
    const totalTimer = setTimeout(() => {
      request.destroy(new Error("Release download total timeout exceeded"));
    }, remaining);
    request.setTimeout(DOWNLOAD_IDLE_TIMEOUT_MS, () => {
      request.destroy(new Error("Release download connection timeout exceeded"));
    });
    request.once("error", (error) => {
      clearTimeout(totalTimer);
      reject(error);
    });
  });
}

function validateRequestUrl(url, policy, redirects, exactProductionUrl = "") {
  if (url.username || url.password || url.hash)
    throw new Error("Release download URL contains forbidden URL components");
  if (policy.mode === "test") {
    if (
      url.protocol !== "http:" ||
      !isLiteralLoopback(url.hostname) ||
      url.origin !== policy.origin
    ) {
      throw new Error("Test release redirect left the exact loopback origin");
    }
    return;
  }
  if (
    redirects !== 0 ||
    url.origin !== PRODUCTION_ORIGIN ||
    url.protocol !== "https:" ||
    url.hostname !== "releases.scilipoti.de" ||
    url.port ||
    (exactProductionUrl
      ? url.toString() !== exactProductionUrl
      : !url.pathname.startsWith(`/v1/channels/${policy.channel}/${policy.target}/${policy.sequence}/`)) ||
    url.search
  ) {
    throw new Error("Release asset request is outside the immutable publication path");
  }
}

function validateRedirect(next, policy) {
  if (next.username || next.password || next.hash)
    throw new Error("Release redirect contains forbidden URL components");
  if (policy.mode === "test") {
    if (
      next.protocol !== "http:" ||
      !isLiteralLoopback(next.hostname) ||
      next.origin !== policy.origin
    ) {
      throw new Error("Test release redirect left the exact loopback origin");
    }
    return;
  }
  throw new Error("Production release assets must not redirect");
}

function writeDownloadResponse({ response, target, maximumBytes, expectedName, deadline }) {
  return new Promise((resolve, reject) => {
    const remaining = deadline - Date.now();
    if (remaining <= 0) {
      response.destroy(new Error(`Release asset ${expectedName} total timeout exceeded`));
      return reject(new Error(`Release asset ${expectedName} total timeout exceeded`));
    }
    const totalTimer = setTimeout(() => {
      response.destroy(new Error(`Release asset ${expectedName} total timeout exceeded`));
    }, remaining);
    const rejectHeaders = (error) => {
      clearTimeout(totalTimer);
      response.destroy();
      reject(error);
    };
    const rawContentLengths = [];
    const rawTransferEncodings = [];
    for (let index = 0; index < response.rawHeaders.length; index += 2) {
      const key = response.rawHeaders[index].toLowerCase();
      if (key === "content-length") rawContentLengths.push(response.rawHeaders[index + 1]);
      if (key === "transfer-encoding")
        rawTransferEncodings.push(response.rawHeaders[index + 1]);
    }
    if (rawContentLengths.length !== 1)
      return rejectHeaders(
        new Error(`Release asset ${expectedName} needs one exact Content-Length`),
      );
    if (rawTransferEncodings.length)
      return rejectHeaders(
        new Error(`Chunked transfer encoding is forbidden for ${expectedName}`),
      );
    if (response.headers["content-encoding"])
      return rejectHeaders(
        new Error(`Content encoding is forbidden for ${expectedName}`),
      );
    const declared = Number(rawContentLengths[0]);
    if (
      !/^(?:0|[1-9][0-9]*)$/.test(rawContentLengths[0]) ||
      !Number.isSafeInteger(declared) ||
      declared < 1 ||
      declared > maximumBytes
    ) {
      return rejectHeaders(
        new Error(`Release asset ${expectedName} Content-Length is outside its limit`),
      );
    }
    assertSafeExistingParent(target, `download ${expectedName}`);
    const flags =
      fsConstants.O_CREAT |
      fsConstants.O_EXCL |
      fsConstants.O_WRONLY |
      (fsConstants.O_NOFOLLOW || 0);
    let descriptor;
    try {
      descriptor = openSync(target, flags, 0o600);
    } catch (error) {
      return rejectHeaders(error);
    }
    const hash = createHash("sha256");
    let observed = 0;
    let settled = false;
    const fail = (error) => {
      if (settled) return;
      settled = true;
      clearTimeout(totalTimer);
      try {
        closeSync(descriptor);
      } catch {}
      try {
        unlinkSync(target);
      } catch {}
      reject(error);
    };
    response.on("data", (chunk) => {
      try {
        observed += chunk.length;
        if (observed > declared || observed > maximumBytes)
          throw new Error(`Release asset ${expectedName} exceeded its declared size`);
        hash.update(chunk);
        writeAll(descriptor, chunk);
      } catch (error) {
        response.destroy();
        fail(error);
      }
    });
    response.once("aborted", () =>
      fail(new Error(`Release asset ${expectedName} download was partial`)),
    );
    response.once("error", fail);
    response.once("end", () => {
      if (settled) return;
      try {
        if (observed !== declared)
          throw new Error(`Release asset ${expectedName} download was partial`);
        fsyncSync(descriptor);
        closeSync(descriptor);
        descriptor = undefined;
        assertRegularUnlinkedFile(target, `downloaded ${expectedName}`);
        settled = true;
        clearTimeout(totalTimer);
        resolve(
          Object.freeze({
            name: expectedName,
            path: realpathSync.native(target),
            bytes: observed,
            sha256: hash.digest("hex"),
          }),
        );
      } catch (error) {
        fail(error);
      }
    });
  });
}

function assertExactDownloadSet(directory, names) {
  const expected = names.ordered.map((record) => record.name).sort();
  const actual = readdirSync(directory).sort();
  if (
    actual.length !== 8 ||
    actual.some((name, index) => name !== expected[index])
  ) {
    throw new Error("Downloaded release directory is not the exact eight-file set");
  }
  for (const name of actual)
    assertRegularUnlinkedFile(path.join(directory, name), `release file ${name}`);
}

function validateRoutingManifest(manifest, names, downloaded, policy) {
  exactKeys(
    manifest,
    [
      "architecture",
      "artifact",
      "channel",
      "expiresAt",
      "issuedAt",
      "minimumVersions",
      "platform",
      "product",
      "releaseKey",
      "schemaVersion",
      "sequence",
      "sidecars",
      "version",
    ],
    "release channel manifest",
  );
  if (
    manifest.schemaVersion !== CHANNEL_SCHEMA ||
    manifest.product !== "MarketingOS" ||
    !Number.isSafeInteger(manifest.sequence) ||
    manifest.sequence < 1 ||
    !/^[a-z][a-z0-9-]{0,31}$/.test(String(manifest.channel || "")) ||
    !isSafeVersion(manifest.version) ||
    !isExactIso(manifest.issuedAt) ||
    !isExactIso(manifest.expiresAt)
  ) {
    throw new Error("Release channel routing identity is invalid");
  }
  if (
    manifest.channel !== policy.channel ||
    manifest.sequence !== policy.sequence ||
    publicationTarget(names) !== policy.target
  ) {
    throw new Error(
      "Release channel identity does not match the immutable publication URL",
    );
  }
  exactKeys(
    manifest.minimumVersions,
    ["hermes", "node", "openclaw"],
    "release channel minimum versions",
  );
  for (const [runtime, version] of Object.entries(manifest.minimumVersions)) {
    if (!isRuntimeVersion(version))
      throw new Error(`Release channel minimum ${runtime} version is invalid`);
  }
  if (compareVersions(manifest.minimumVersions.node, MINIMUM_NODE_VERSION) < 0)
    throw new Error("Release channel weakens the acquisition Node.js floor");
  assertVersionAtLeast(
    process.versions.node,
    manifest.minimumVersions.node,
    "Release acquisition Node.js",
  );
  exactKeys(
    manifest.releaseKey,
    ["algorithm", "keyId", "spkiSha256"],
    "release channel publisher key",
  );
  if (
    manifest.releaseKey.algorithm !== "Ed25519" ||
    !/^[A-Za-z0-9][A-Za-z0-9:._-]{0,255}$/.test(
      String(manifest.releaseKey.keyId || ""),
    ) ||
    !isSha256(manifest.releaseKey.spkiSha256)
  ) {
    throw new Error("Release channel publisher key identity is invalid");
  }
  const platformLabel = manifest.platform === "win32"
    ? "windows"
    : manifest.platform === "darwin"
      ? "macos"
      : manifest.platform === "linux"
        ? "linux"
        : null;
  if (!platformLabel) throw new Error("Release channel platform is unsupported");
  const expectedStem = names.artifactKind === "audit-witness"
    ? `MarketingOS-Audit-Witness-${manifest.version}-${platformLabel}-${manifest.architecture}`
    : `MarketingOS-Alpha-${manifest.version}-${platformLabel}-${manifest.architecture}`;
  const expectedArtifact = manifest.platform === "win32" ? `${expectedStem}.zip` : `${expectedStem}.tar.gz`;
  const expectedRoot = expectedStem;
  const expectedChannel = `${manifest.platform === "win32" ? expectedStem : expectedArtifact}.channel.json`;
  if (names.artifact !== expectedArtifact || names.root !== expectedRoot || names.channel !== expectedChannel) {
    throw new Error("Release filename identity does not match the signed channel identity");
  }
  const expectedPlatform = names.root.includes("-windows-")
    ? "win32"
    : names.root.includes("-macos-")
      ? "darwin"
      : "linux";
  const expectedArchitecture = names.root.endsWith("-arm64") ? "arm64" : "x64";
  if (
    manifest.platform !== expectedPlatform ||
    manifest.architecture !== expectedArchitecture
  ) {
    throw new Error("Release channel platform does not match its canonical filename");
  }
  if (
    policy.mode === "production" &&
    (manifest.platform !== process.platform || manifest.architecture !== process.arch)
  ) {
    throw new Error("Production release target does not match this runtime platform and architecture");
  }
  validateRoutingRecord(manifest.artifact, "artifact", names.artifact, downloaded);
  if (!Array.isArray(manifest.sidecars) || manifest.sidecars.length !== 5)
    throw new Error("Release channel must contain exactly five signed sidecars");
  const seenNames = new Set([manifest.artifact.name]);
  for (let index = 0; index < SIDECAR_KINDS.length; index += 1) {
    const kind = SIDECAR_KINDS[index];
    const expectedName = names.ordered.find((record) => record.kind === kind).name;
    const record = manifest.sidecars[index];
    validateRoutingRecord(record, kind, expectedName, downloaded);
    if (seenNames.has(record.name))
      throw new Error("Release channel contains a duplicate filename");
    seenNames.add(record.name);
  }
}

function validateRoutingRecord(record, kind, expectedName, downloaded) {
  exactKeys(record, ["bytes", "kind", "name", "sha256"], `release ${kind}`);
  if (
    record.kind !== kind ||
    record.name !== expectedName ||
    !Number.isSafeInteger(record.bytes) ||
    record.bytes < 1 ||
    !isSha256(record.sha256)
  ) {
    throw new Error(`Release channel ${kind} record is invalid`);
  }
  const observed = downloaded.get(kind);
  if (
    !observed ||
    observed.name !== record.name ||
    observed.bytes !== record.bytes ||
    observed.sha256 !== record.sha256
  ) {
    throw new Error(`Downloaded ${kind} does not match the channel record`);
  }
}

function runExternalVerifier({
  verifierPath,
  artifactPath,
  pinPath,
  statePath,
  receiptPath,
  requirePublished,
}) {
  const verifierArguments = [
    verifierPath,
    "--artifact",
    artifactPath,
    "--pin",
    pinPath,
    "--state",
    statePath,
    "--receipt",
    receiptPath,
  ];
  if (requirePublished) verifierArguments.push("--require-published");
  const result = spawnSync(
    process.execPath,
    verifierArguments,
    {
      shell: false,
      windowsHide: true,
      encoding: "utf8",
      timeout: VERIFIER_TIMEOUT_MS,
      maxBuffer: MAX_OUTPUT_BYTES,
      env: minimalVerifierEnvironment(),
    },
  );
  if (result.error)
    throw new Error(`External verifier could not run: ${result.error.message}`);
  if (result.status !== 0)
    throw new Error(
      `External verifier rejected the release with exit ${result.status}: ${String(result.stderr || "").trim().slice(0, 1_024)}`,
    );
  if (String(result.stderr || "").trim())
    throw new Error("External verifier wrote unexpected stderr output");
  const parsed = parseStrictJsonText(
    String(result.stdout || ""),
    "external verifier output",
  );
  exactKeys(
    parsed,
    [
      "architecture",
      "artifact",
      "artifactSha256",
      "channel",
      "expiresAt",
      "externalBootstrapReceipt",
      "externalBootstrapReceiptSha256",
      "minimumVersions",
      "ok",
      "platform",
      "product",
      "releaseKeyId",
      "sequence",
      "sequenceState",
      "version",
    ],
    "external verifier output",
  );
  if (parsed.ok !== true || parsed.product !== "MarketingOS")
    throw new Error("External verifier output is not a successful MarketingOS result");
  return parsed;
}

function minimalVerifierEnvironment() {
  const result = Object.create(null);
  for (const key of [
    "SystemRoot",
    "WINDIR",
    "HOME",
    "USERPROFILE",
    "TMP",
    "TEMP",
    "TMPDIR",
    "LANG",
    "LC_ALL",
  ]) {
    if (process.env[key] !== undefined) result[key] = process.env[key];
  }
  if (process.env.MARKETINGOS_ACQUISITION_ENV === TEST_ENVIRONMENT)
    result.MARKETINGOS_ACQUISITION_ENV = TEST_ENVIRONMENT;
  return result;
}

function validateExternalReceipt({
  receiptPath,
  verifierResult,
  verifier,
  pin,
  statePath,
  channel,
  names,
  downloaded,
  downloadDirectory,
}) {
  assertRegularUnlinkedFile(receiptPath, "external bootstrap receipt");
  const receiptDigest = secureDigestFile(
    receiptPath,
    "external bootstrap receipt",
    16 * 1024 * 1024,
  );
  if (
    verifierResult.externalBootstrapReceipt !== path.resolve(receiptPath) ||
    verifierResult.externalBootstrapReceiptSha256 !== receiptDigest.sha256 ||
    verifierResult.artifact !== names.artifact ||
    verifierResult.artifactSha256 !== downloaded.get("artifact").sha256 ||
    verifierResult.channel !== channel.channel ||
    verifierResult.sequence !== channel.sequence ||
    verifierResult.version !== channel.version ||
    verifierResult.platform !== channel.platform ||
    verifierResult.architecture !== channel.architecture ||
    verifierResult.expiresAt !== channel.expiresAt ||
    verifierResult.sequenceState !== path.resolve(statePath) ||
    verifierResult.releaseKeyId !== channel.releaseKey.keyId ||
    canonicalJson(verifierResult.minimumVersions) !==
      canonicalJson(channel.minimumVersions)
  ) {
    throw new Error("External verifier output does not bind the downloaded release");
  }
  const receipt = readStrictJson(receiptPath, "external bootstrap receipt");
  exactKeys(
    receipt,
    [
      "artifact",
      "bundleDirectory",
      "channel",
      "files",
      "generatedAt",
      "pin",
      "product",
      "publisherKey",
      "receiptHash",
      "relocationPolicy",
      "schemaVersion",
      "verificationBoundary",
      "verifier",
    ],
    "external bootstrap receipt",
  );
  const unsigned = { ...receipt };
  delete unsigned.receiptHash;
  if (
    receipt.schemaVersion !== EXTERNAL_RECEIPT_SCHEMA ||
    receipt.product !== "MarketingOS" ||
    receipt.receiptHash !== sha256Text(canonicalJson(unsigned)) ||
    !isExactIso(receipt.generatedAt) ||
    Date.parse(receipt.generatedAt) < Date.parse(channel.issuedAt) - 300_000 ||
    Date.parse(receipt.generatedAt) > Date.parse(channel.expiresAt) ||
    Date.parse(receipt.generatedAt) > Date.now() + 300_000
  ) {
    throw new Error("External bootstrap receipt hash or schema is invalid");
  }
  exactKeys(receipt.bundleDirectory, ["path", "pathSha256"], "receipt bundle directory");
  const bundlePath = realpathSync.native(downloadDirectory);
  if (
    receipt.bundleDirectory.path !== bundlePath ||
    receipt.bundleDirectory.pathSha256 !==
      sha256Text(normalizedPathIdentity(bundlePath))
  ) {
    throw new Error("External bootstrap receipt is bound to another bundle directory");
  }
  validateReceiptDigest(receipt.artifact, downloaded.get("artifact"), false, "receipt artifact");
  if (!Array.isArray(receipt.files) || receipt.files.length !== 8)
    throw new Error("External bootstrap receipt must bind exactly eight files");
  const expectedReceiptRecords = new Map();
  for (const item of names.ordered) {
    const observed = downloaded.get(item.kind);
    expectedReceiptRecords.set(item.kind, { kind: item.kind, ...observed });
  }
  const seenKinds = new Set();
  for (const record of receipt.files) {
    exactKeys(record, ["bytes", "kind", "name", "sha256"], "receipt file");
    if (seenKinds.has(record.kind) || !expectedReceiptRecords.has(record.kind))
      throw new Error("External bootstrap receipt contains a duplicate or unknown kind");
    seenKinds.add(record.kind);
    validateReceiptDigest(
      record,
      expectedReceiptRecords.get(record.kind),
      true,
      `receipt ${record.kind}`,
    );
  }
  exactKeys(
    receipt.channel,
    [
      "expiresAt",
      "issuedAt",
      "manifestSha256",
      "name",
      "sequence",
      "signatureKeyId",
      "signatureSha256",
    ],
    "receipt channel",
  );
  if (
    receipt.channel.name !== channel.channel ||
    receipt.channel.sequence !== channel.sequence ||
    receipt.channel.issuedAt !== channel.issuedAt ||
    receipt.channel.expiresAt !== channel.expiresAt ||
    receipt.channel.manifestSha256 !== downloaded.get("release-channel").sha256 ||
    receipt.channel.signatureSha256 !==
      downloaded.get("release-channel-signature").sha256 ||
    receipt.channel.signatureKeyId !== channel.releaseKey.keyId
  ) {
    throw new Error("External bootstrap receipt channel binding is invalid");
  }
  exactKeys(
    receipt.publisherKey,
    ["algorithm", "keyId", "spkiSha256"],
    "receipt publisher key",
  );
  if (
    receipt.publisherKey.algorithm !== channel.releaseKey.algorithm ||
    receipt.publisherKey.keyId !== channel.releaseKey.keyId ||
    receipt.publisherKey.spkiSha256 !== channel.releaseKey.spkiSha256
  ) {
    throw new Error("External bootstrap receipt publisher key binding is invalid");
  }
  exactKeys(receipt.pin, ["bytes", "path", "sha256"], "receipt pin");
  if (
    receipt.pin.path !== pin.path ||
    receipt.pin.bytes !== pin.bytes ||
    receipt.pin.sha256 !== pin.sha256
  ) {
    throw new Error("External bootstrap receipt pin binding is invalid");
  }
  exactKeys(
    receipt.verifier,
    ["bytes", "name", "path", "sha256"],
    "receipt verifier",
  );
  if (
    receipt.verifier.path !== verifier.path ||
    receipt.verifier.name !== VERIFIER_NAME ||
    receipt.verifier.bytes !== verifier.bytes ||
    receipt.verifier.sha256 !== verifier.sha256
  ) {
    throw new Error("External bootstrap receipt verifier binding is invalid");
  }
  return Object.freeze({
    path: realpathSync.native(receiptPath),
    bytes: receiptDigest.bytes,
    sha256: receiptDigest.sha256,
    receipt,
  });
}

function validateReceiptDigest(actual, expected, withKind, label) {
  exactKeys(
    actual,
    withKind
      ? ["bytes", "kind", "name", "sha256"]
      : ["bytes", "name", "sha256"],
    label,
  );
  const observedBinding = withKind
    ? {
        kind: String(actual.kind),
        name: String(actual.name),
        bytes: Number(actual.bytes),
        sha256: String(actual.sha256),
      }
    : {
        name: String(actual.name),
        bytes: Number(actual.bytes),
        sha256: String(actual.sha256),
      };
  const expectedBinding = withKind
    ? {
        kind: String(expected.kind),
        name: String(expected.name),
        bytes: Number(expected.bytes),
        sha256: String(expected.sha256),
      }
    : {
        name: String(expected.name),
        bytes: Number(expected.bytes),
        sha256: String(expected.sha256),
      };
  if (canonicalJson(observedBinding) !== canonicalJson(expectedBinding)) {
    throw new Error(
      `${label} digest is invalid: observed ${canonicalJson(observedBinding)}, expected ${canonicalJson(expectedBinding)}`,
    );
  }
}

function openBoundArchive(archivePath, expected) {
  const absolute = path.resolve(archivePath);
  assertRegularUnlinkedFile(absolute, "artifact archive");
  const descriptor = openSync(
    absolute,
    fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0),
  );
  try {
    const identity = fstatIdentity(descriptor);
    const observed = digestOpenDescriptor(descriptor, Number(identity.size));
    if (observed.bytes !== expected.bytes || observed.sha256 !== expected.sha256)
      throw new Error("Artifact archive descriptor differs from the verified download");
    assertPathMatchesIdentity(absolute, identity, "artifact archive");
    return Object.freeze({
      descriptor,
      identity,
      path: realpathSync.native(absolute),
      bytes: observed.bytes,
      sha256: observed.sha256,
    });
  } catch (error) {
    closeSync(descriptor);
    throw error;
  }
}

function assertOpenArchiveUnchanged(openArtifact, archivePath, label) {
  const identity = fstatIdentity(openArtifact.descriptor);
  if (canonicalJson(identity) !== canonicalJson(openArtifact.identity))
    throw new Error(`${label} descriptor identity changed after inspection`);
  const observed = digestOpenDescriptor(openArtifact.descriptor, openArtifact.bytes);
  if (
    observed.bytes !== openArtifact.bytes ||
    observed.sha256 !== openArtifact.sha256
  ) {
    throw new Error(`${label} descriptor content changed after inspection`);
  }
  assertPathMatchesIdentity(archivePath, openArtifact.identity, label);
}

function assertOpenArchiveContentUnchanged(openArtifact, label) {
  const stats = fstatSync(openArtifact.descriptor, { bigint: true });
  if (
    !stats.isFile() ||
    stats.nlink !== 1n ||
    stats.size !== BigInt(openArtifact.bytes)
  ) {
    throw new Error(`${label} descriptor changed after archive inspection`);
  }
  const observed = digestOpenDescriptor(openArtifact.descriptor, openArtifact.bytes);
  if (observed.sha256 !== openArtifact.sha256)
    throw new Error(`${label} descriptor content changed after archive inspection`);
}

function digestOpenDescriptor(descriptor, maximumBytes) {
  const hash = createHash("sha256");
  const buffer = Buffer.allocUnsafe(1024 * 1024);
  let total = 0;
  while (total < maximumBytes) {
    const count = readSync(
      descriptor,
      buffer,
      0,
      Math.min(buffer.length, maximumBytes - total),
      total,
    );
    if (!count) break;
    total += count;
    hash.update(buffer.subarray(0, count));
  }
  if (total !== maximumBytes)
    throw new Error("Artifact archive descriptor ended during hashing");
  return { bytes: total, sha256: hash.digest("hex") };
}

function inspectZipArchive(openArtifact, expectedRoot, platform) {
  const descriptor = openArtifact.descriptor;
  const stats = fstatSync(descriptor);
  if (stats.size !== openArtifact.bytes)
    throw new Error("ZIP descriptor size changed before inspection");
  if (stats.size < 22) throw new Error("ZIP archive is truncated");
  const tailBytes = Math.min(stats.size, 65_557);
  const tail = readExactly(descriptor, tailBytes, stats.size - tailBytes);
    let endOffset = -1;
    for (let index = tail.length - 22; index >= 0; index -= 1) {
      if (tail.readUInt32LE(index) !== 0x06054b50) continue;
      const commentLength = tail.readUInt16LE(index + 20);
      if (index + 22 + commentLength === tail.length) {
        if (endOffset !== -1) throw new Error("ZIP archive has ambiguous end records");
        endOffset = stats.size - tailBytes + index;
      }
    }
    if (endOffset < 0) throw new Error("ZIP archive end record is missing");
    const end = readExactly(descriptor, 22, endOffset);
    if (
      end.readUInt16LE(4) !== 0 ||
      end.readUInt16LE(6) !== 0 ||
      end.readUInt16LE(8) !== end.readUInt16LE(10) ||
      end.readUInt16LE(20) !== 0
    ) {
      throw new Error("ZIP archive must be one non-ZIP64 disk with no comment");
    }
    const entryCount = end.readUInt16LE(10);
    const centralSize = end.readUInt32LE(12);
    const centralOffset = end.readUInt32LE(16);
    if (
      entryCount < 1 ||
      entryCount > MAX_ARCHIVE_ENTRIES ||
      centralOffset + centralSize !== endOffset
    ) {
      throw new Error("ZIP central directory bounds are invalid");
    }
    const files = [];
    const records = [];
    const seenNames = new Set();
    const seenOffsets = new Set();
    const pathRegistry = new ArchivePathRegistry(platform);
    const dataRanges = [];
    let cursor = centralOffset;
    let totalBytes = 0;
    for (let index = 0; index < entryCount; index += 1) {
      const header = readExactly(descriptor, 46, cursor);
      if (header.readUInt32LE(0) !== 0x02014b50)
        throw new Error("ZIP central directory entry is malformed");
      const versionMadeBy = header.readUInt16LE(4);
      const requiredVersion = header.readUInt16LE(6);
      const flags = header.readUInt16LE(8);
      const method = header.readUInt16LE(10);
      const modifiedTime = header.readUInt16LE(12);
      const modifiedDate = header.readUInt16LE(14);
      const crc = header.readUInt32LE(16);
      const compressedBytes = header.readUInt32LE(20);
      const uncompressedBytes = header.readUInt32LE(24);
      const nameLength = header.readUInt16LE(28);
      const extraLength = header.readUInt16LE(30);
      const commentLength = header.readUInt16LE(32);
      const disk = header.readUInt16LE(34);
      const externalAttributes = header.readUInt32LE(38);
      const localOffset = header.readUInt32LE(42);
      if (
        requiredVersion > 20 ||
        flags !== 0x0800 ||
        ![0, 8].includes(method) ||
        nameLength < 1 ||
        extraLength !== 0 ||
        commentLength !== 0 ||
        disk !== 0 ||
        [compressedBytes, uncompressedBytes, localOffset].includes(0xffff_ffff)
      ) {
        throw new Error("ZIP entry uses an unsupported or ambiguous feature");
      }
      const nameBuffer = readExactly(descriptor, nameLength, cursor + 46);
      const archiveName = decodeUtf8(nameBuffer, "ZIP entry name");
      const creator = versionMadeBy >>> 8;
      const unixMode = externalAttributes >>> 16;
      if (creator === 3) {
        const type = unixMode & 0xf000;
        if (type && type !== 0x8000)
          throw new Error("ZIP links and special filesystem entries are forbidden");
      }
      if (archiveName.endsWith("/"))
        throw new Error("Canonical MarketingOS ZIP contains regular files only");
      const relativePath = validateArchivePath(
        archiveName,
        expectedRoot,
        false,
        platform,
      );
      pathRegistry.register(relativePath, false);
      if (seenNames.has(archiveName) || seenOffsets.has(localOffset))
        throw new Error("ZIP archive contains a duplicate or hardlink-like entry");
      seenNames.add(archiveName);
      seenOffsets.add(localOffset);

      const local = readExactly(descriptor, 30, localOffset);
      if (
        local.readUInt32LE(0) !== 0x04034b50 ||
        local.readUInt16LE(4) !== requiredVersion ||
        local.readUInt16LE(6) !== flags ||
        local.readUInt16LE(8) !== method ||
        local.readUInt16LE(10) !== modifiedTime ||
        local.readUInt16LE(12) !== modifiedDate ||
        local.readUInt32LE(14) !== crc ||
        local.readUInt32LE(18) !== compressedBytes ||
        local.readUInt32LE(22) !== uncompressedBytes ||
        local.readUInt16LE(26) !== nameLength ||
        local.readUInt16LE(28) !== 0
      ) {
        throw new Error("ZIP local header differs from the central directory");
      }
      const localName = readExactly(descriptor, nameLength, localOffset + 30);
      if (!localName.equals(nameBuffer))
        throw new Error("ZIP local filename differs from the central directory");
      const dataStart = localOffset + 30 + nameLength;
      const dataEnd = dataStart + compressedBytes;
      if (dataEnd > centralOffset)
        throw new Error("ZIP entry data overlaps the central directory");
      if (method === 0 && compressedBytes !== uncompressedBytes)
        throw new Error("Stored ZIP entry has unequal compressed and uncompressed sizes");
      if (method === 8 && compressedBytes < 1)
        throw new Error("Deflated ZIP entry has no compressed stream");
      dataRanges.push([localOffset, dataEnd]);
      totalBytes += uncompressedBytes;
      if (totalBytes > MAX_UNPACKED_BYTES)
        throw new Error("ZIP expanded size exceeds the acquisition limit");
      files.push({ path: relativePath, bytes: uncompressedBytes, mode: "neutral" });
      records.push({
        path: relativePath,
        bytes: uncompressedBytes,
        mode: "neutral",
        method,
        crc32: crc,
        compressedBytes,
        localOffset,
        dataStart,
        dataEnd,
      });
      cursor += 46 + nameLength;
    }
    if (cursor !== endOffset)
      throw new Error("ZIP central directory size is not canonical");
    dataRanges.sort((left, right) => left[0] - right[0]);
    if (dataRanges[0][0] !== 0)
      throw new Error("ZIP archive has a preamble before its first local record");
    for (let index = 1; index < dataRanges.length; index += 1) {
      if (dataRanges[index][0] !== dataRanges[index - 1][1])
        throw new Error("ZIP archive has a gap or overlap between local records");
    }
    if (dataRanges.at(-1)[1] !== centralOffset)
      throw new Error("ZIP archive has a gap before its central directory");
    files.sort((left, right) => left.path.localeCompare(right.path, "en"));
    records.sort((left, right) => left.localOffset - right.localOffset);
    return Object.freeze({
      archiveType: "zip",
      files,
      records,
      fileCount: files.length,
      totalBytes,
      archiveRecordSha256: sha256Text(
        canonicalJson(records.map(zipRecordBinding)),
      ),
    });
}

function zipRecordBinding(record) {
  return {
    path: record.path,
    bytes: record.bytes,
    mode: record.mode,
    method: record.method,
    crc32: record.crc32.toString(16).padStart(8, "0"),
    compressedBytes: record.compressedBytes,
  };
}

async function inspectTarGzArchive(openArtifact, expectedRoot, platform) {
  return processTarGzArchive({ openArtifact, expectedRoot, platform });
}

async function processTarGzArchive({
  openArtifact,
  expectedRoot,
  platform,
  extractionRoot = null,
}) {
  const processor = new TarInspector(expectedRoot, platform, extractionRoot);
  const source = descriptorReadStream(
    openArtifact.descriptor,
    0,
    openArtifact.bytes,
  );
  const gunzip = createGunzip();
  let compressedBytes = 0;
  source.on("data", (chunk) => {
    compressedBytes += chunk.length;
    if (compressedBytes > openArtifact.bytes)
      source.destroy(new Error("TAR.GZ compressed input exceeded its descriptor size"));
  });
  source.once("error", (error) => gunzip.destroy(error));
  source.pipe(gunzip);
  try {
    for await (const chunk of gunzip) processor.consume(chunk);
    if (compressedBytes !== openArtifact.bytes)
      throw new Error("TAR.GZ compressed stream ended before the descriptor boundary");
    if (
      Number.isSafeInteger(gunzip.bytesWritten) &&
      gunzip.bytesWritten !== openArtifact.bytes
    ) {
      throw new Error("TAR.GZ decoder did not consume the exact compressed stream");
    }
    return processor.finish();
  } catch (error) {
    processor.abort();
    source.destroy();
    gunzip.destroy();
    throw error;
  }
}

class TarInspector {
  constructor(expectedRoot, platform, extractionRoot = null) {
    this.expectedRoot = expectedRoot;
    this.platform = platform;
    this.pathRegistry = new ArchivePathRegistry(platform);
    this.buffer = Buffer.alloc(0);
    this.current = null;
    this.zeroBlocks = 0;
    this.ended = false;
    this.pendingLongName = null;
    this.pendingPax = null;
    this.seen = new Set();
    this.files = [];
    this.records = [];
    this.totalBytes = 0;
    this.entryCount = 0;
    this.decompressedBytes = 0;
    this.zeroTailBytes = 0;
    this.streamHash = createHash("sha256");
    this.extractionRoot = extractionRoot;
  }

  consume(chunk) {
    if (!Buffer.isBuffer(chunk)) chunk = Buffer.from(chunk);
    this.decompressedBytes += chunk.length;
    if (this.decompressedBytes > MAX_TAR_DECOMPRESSED_BYTES)
      throw new Error("TAR decompressed stream exceeds its hard structural limit");
    this.streamHash.update(chunk);
    this.buffer = this.buffer.length
      ? Buffer.concat([this.buffer, chunk])
      : chunk;
    while (this.buffer.length) {
      if (this.ended) {
        if (this.buffer.some((byte) => byte !== 0))
          throw new Error("TAR archive has data after its end markers");
        this.zeroTailBytes += this.buffer.length;
        if (this.zeroTailBytes > MAX_TAR_ZERO_TAIL_BYTES)
          throw new Error("TAR zero tail exceeds its hard limit");
        this.buffer = Buffer.alloc(0);
        return;
      }
      if (this.current) {
        if (this.current.dataRemaining > 0) {
          const count = Math.min(this.buffer.length, this.current.dataRemaining);
          const data = this.buffer.subarray(0, count);
          if (this.current.capture) {
            if (this.current.capturedBytes + count > 64 * 1024)
              throw new Error("TAR metadata extension is too large");
            this.current.chunks.push(data);
            this.current.capturedBytes += count;
          }
          if (this.current.hash) this.current.hash.update(data);
          if (this.current.writer) {
            writeAll(this.current.writer.descriptor, data);
            this.current.writer.bytes += count;
          }
          this.buffer = this.buffer.subarray(count);
          this.current.dataRemaining -= count;
          if (!this.buffer.length) return;
          continue;
        }
        if (this.current.paddingRemaining > 0) {
          const count = Math.min(this.buffer.length, this.current.paddingRemaining);
          if (this.buffer.subarray(0, count).some((byte) => byte !== 0))
            throw new Error("TAR entry padding is not zeroed");
          this.buffer = this.buffer.subarray(count);
          this.current.paddingRemaining -= count;
          if (!this.buffer.length) return;
          continue;
        }
        const completed = this.current;
        this.current = null;
        if (completed.capture)
          this.completeMetadata(completed.type, Buffer.concat(completed.chunks));
        if (completed.record?.kind === "file") {
          completed.record.dataSha256 = completed.hash.digest("hex");
          if (completed.writer)
            finalizeExtractionFile(
              completed.writer,
              completed.record.bytes,
              completed.record.mode,
            );
        }
        continue;
      }
      if (this.buffer.length < 512) return;
      const header = this.buffer.subarray(0, 512);
      this.buffer = this.buffer.subarray(512);
      if (header.every((byte) => byte === 0)) {
        this.zeroBlocks += 1;
        if (this.zeroBlocks === 2) this.ended = true;
        continue;
      }
      if (this.zeroBlocks)
        throw new Error("TAR archive has a nonzero block after an end marker");
      const parsed = parseTarHeader(header);
      this.entryCount += 1;
      if (this.entryCount > MAX_ARCHIVE_ENTRIES)
        throw new Error("TAR archive has too many entries");
      const metadata = ["L", "x", "g"].includes(parsed.type);
      if (metadata && parsed.size > 64 * 1024)
        throw new Error("TAR metadata extension is too large");
      const record = metadata ? null : this.registerEntry(parsed);
      this.current = {
        type: parsed.type,
        capture: metadata,
        chunks: [],
        capturedBytes: 0,
        dataRemaining: parsed.size,
        paddingRemaining: (512 - (parsed.size % 512)) % 512,
        record,
        hash: record?.kind === "file" ? createHash("sha256") : null,
        writer:
          record?.kind === "file" && this.extractionRoot
            ? openExtractionFile(
                this.extractionRoot,
                record.path,
                record.mode,
              )
            : null,
      };
    }
  }

  completeMetadata(type, data) {
    if (type === "L") {
      if (this.pendingLongName)
        throw new Error("TAR archive has duplicate long-name metadata");
      const zero = data.indexOf(0);
      const value = zero >= 0 ? data.subarray(0, zero) : data;
      if (zero >= 0 && data.subarray(zero).some((byte) => byte !== 0))
        throw new Error("TAR long-name metadata has trailing data");
      this.pendingLongName = decodeUtf8(value, "TAR long entry name").replace(/\n$/, "");
      return;
    }
    const pax = parsePax(data);
    if (Object.hasOwn(pax, "linkpath") || Object.hasOwn(pax, "size"))
      throw new Error("TAR PAX linkpath and size overrides are forbidden");
    const allowed = new Set([
      "atime",
      "charset",
      "comment",
      "ctime",
      "gid",
      "gname",
      "mtime",
      "path",
      "uid",
      "uname",
    ]);
    for (const key of Object.keys(pax))
      if (!allowed.has(key))
        throw new Error(`TAR PAX key is not allowed: ${key}`);
    if (type === "g") {
      if (Object.hasOwn(pax, "path"))
        throw new Error("Global TAR PAX path overrides are forbidden");
      return;
    }
    if (this.pendingPax)
      throw new Error("TAR archive has duplicate per-entry PAX metadata");
    this.pendingPax = pax;
  }

  registerEntry(parsed) {
    if (!["0", "\0", "5"].includes(parsed.type))
      throw new Error("TAR links and special filesystem entries are forbidden");
    const paxName = this.pendingPax?.path || null;
    if (this.pendingLongName && paxName && this.pendingLongName !== paxName)
      throw new Error("TAR entry has ambiguous path metadata");
    const archiveName = this.pendingLongName || paxName || parsed.name;
    this.pendingLongName = null;
    this.pendingPax = null;
    const directory = parsed.type === "5";
    validateTarMode(parsed.mode, directory);
    const relativePath = validateArchivePath(
      archiveName,
      this.expectedRoot,
      directory,
      this.platform,
    );
    this.pathRegistry.register(relativePath, directory);
    const identity = directory ? `${relativePath}/` : relativePath;
    if (this.seen.has(identity))
      throw new Error("TAR archive contains a duplicate entry");
    this.seen.add(identity);
    const record = {
      kind: directory ? "directory" : "file",
      path: relativePath,
      bytes: parsed.size,
      mode: normalizedPosixMode(parsed.mode),
    };
    this.records.push(record);
    if (directory) {
      if (parsed.size !== 0) throw new Error("TAR directory has file data");
      return record;
    }
    this.totalBytes += parsed.size;
    if (this.totalBytes > MAX_UNPACKED_BYTES)
      throw new Error("TAR expanded size exceeds the acquisition limit");
    this.files.push(record);
    return record;
  }

  finish() {
    if (this.current || this.buffer.length)
      throw new Error("TAR archive ended inside an entry");
    if (!this.ended || this.zeroBlocks < 2)
      throw new Error("TAR archive does not have two end markers");
    if (this.pendingLongName || this.pendingPax)
      throw new Error("TAR archive ended after orphan metadata");
    if (!this.files.length) throw new Error("TAR archive contains no regular files");
    if (this.records.some((record) => record.kind === "file" && !record.dataSha256))
      throw new Error("TAR file content digest was not finalized");
    const files = this.files
      .map((record) => ({
        path: record.path,
        bytes: record.bytes,
        mode: record.mode,
        dataSha256: record.dataSha256,
      }))
      .sort((left, right) => left.path.localeCompare(right.path, "en"));
    const records = this.records.map((record) => ({ ...record }));
    return Object.freeze({
      archiveType: "tar.gz",
      files,
      records,
      fileCount: files.length,
      totalBytes: this.totalBytes,
      decompressedBytes: this.decompressedBytes,
      zeroTailBytes: this.zeroTailBytes,
      tarStreamSha256: this.streamHash.digest("hex"),
      archiveRecordSha256: sha256Text(canonicalJson(records)),
    });
  }

  abort() {
    if (this.current?.writer) abortExtractionFile(this.current.writer);
    this.current = null;
  }
}

function parseTarHeader(header) {
  const expectedChecksum = parseTarOctal(header.subarray(148, 156), "checksum");
  let actualChecksum = 0;
  for (let index = 0; index < header.length; index += 1)
    actualChecksum += index >= 148 && index < 156 ? 0x20 : header[index];
  if (actualChecksum !== expectedChecksum)
    throw new Error("TAR header checksum is invalid");
  if (header.subarray(257, 263).toString("binary") !== "ustar\0"
    || header.subarray(263, 265).toString("ascii") !== "00") {
    throw new Error("TAR header is not canonical USTAR version 00");
  }
  const name = tarText(header.subarray(0, 100), "TAR entry name");
  const prefix = tarText(header.subarray(345, 500), "TAR entry prefix");
  const combined = prefix ? `${prefix}/${name}` : name;
  if (!combined) throw new Error("TAR entry name is empty");
  return {
    name: combined,
    mode: parseTarOctal(header.subarray(100, 108), "entry mode"),
    size: parseTarOctal(header.subarray(124, 136), "entry size"),
    type: String.fromCharCode(header[156] || 0),
  };
}

function validateTarMode(mode, directory) {
  if (!Number.isSafeInteger(mode) || mode < 0 || mode > 0o7777)
    throw new Error("TAR entry mode is invalid");
  if ((mode & 0o7000) !== 0 || (mode & 0o002) !== 0)
    throw new Error("TAR setuid, setgid, sticky, and world-writable modes are forbidden");
  if (directory && ![0o755, 0o555, 0o750, 0o700].includes(mode & 0o777))
    throw new Error("TAR directory mode is not safe and canonical");
}

function normalizedPosixMode(mode) {
  return `0${(mode & 0o7777).toString(8).padStart(3, "0")}`;
}

function parseTarOctal(buffer, label) {
  if (buffer[0] & 0x80)
    throw new Error(`TAR ${label} uses an unsupported base-256 number`);
  const text = buffer.toString("ascii").replace(/\0.*$/, "").trim();
  if (!/^[0-7]+$/.test(text)) throw new Error(`TAR ${label} is not canonical octal`);
  const value = Number.parseInt(text, 8);
  if (!Number.isSafeInteger(value) || value < 0)
    throw new Error(`TAR ${label} is outside the safe integer range`);
  return value;
}

function tarText(buffer, label) {
  const zero = buffer.indexOf(0);
  const value = zero >= 0 ? buffer.subarray(0, zero) : buffer;
  if (zero >= 0 && buffer.subarray(zero).some((byte) => byte !== 0))
    throw new Error(`${label} has nonzero bytes after its terminator`);
  return decodeUtf8(value, label);
}

function parsePax(buffer) {
  const result = Object.create(null);
  let offset = 0;
  while (offset < buffer.length) {
    const space = buffer.indexOf(0x20, offset);
    if (space < 0) throw new Error("TAR PAX record has no length separator");
    const lengthText = buffer.subarray(offset, space).toString("ascii");
    if (!/^[1-9][0-9]*$/.test(lengthText))
      throw new Error("TAR PAX record length is invalid");
    const length = Number(lengthText);
    if (!Number.isSafeInteger(length) || length < 5 || offset + length > buffer.length)
      throw new Error("TAR PAX record exceeds its metadata block");
    const record = buffer.subarray(space + 1, offset + length);
    if (record.at(-1) !== 0x0a) throw new Error("TAR PAX record has no newline");
    const content = decodeUtf8(record.subarray(0, -1), "TAR PAX record");
    const equals = content.indexOf("=");
    if (equals < 1) throw new Error("TAR PAX record has no key/value separator");
    const key = content.slice(0, equals);
    if (!/^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(key) || Object.hasOwn(result, key))
      throw new Error("TAR PAX record key is invalid or duplicated");
    result[key] = content.slice(equals + 1);
    offset += length;
  }
  return result;
}

function validateArchivePath(value, expectedRoot, directory, platform) {
  if (
    typeof value !== "string" ||
    !value ||
    Buffer.byteLength(value, "utf8") > MAX_PATH_BYTES ||
    /[\0-\x1f\x7f]/.test(value) ||
    value.includes("\\") ||
    value.startsWith("/") ||
    /^[A-Za-z]:/.test(value) ||
    value.startsWith("//")
  ) {
    throw new Error("Archive entry path is unsafe");
  }
  let normalized = value;
  if (directory && normalized.endsWith("/")) normalized = normalized.slice(0, -1);
  const segments = normalized.split("/");
  if (
    segments.some((segment) => !segment || segment === "." || segment === "..") ||
    segments[0] !== expectedRoot
  ) {
    throw new Error("Archive entry escapes or differs from the canonical single root");
  }
  validateTargetPathSegments(segments.slice(1), platform);
  if (segments.length === 1) {
    if (!directory)
      throw new Error("Archive root must be a directory, not a regular file");
    return ".";
  }
  return segments.slice(1).join("/");
}

class ArchivePathRegistry {
  constructor(platform) {
    this.platform = platform;
    this.nodes = new Map();
    this.explicit = new Set();
  }

  identity(relativePath) {
    const segments = relativePath === "." ? [] : relativePath.split("/");
    const normalized = segments.map((segment) =>
      this.platform === "win32" || this.platform === "darwin"
        ? segment.normalize("NFC").toLowerCase()
        : segment,
    );
    return normalized.join("/");
  }

  register(relativePath, directory) {
    const identity = this.identity(relativePath);
    if (!identity) {
      if (!directory) throw new Error("Archive root cannot be a regular file");
      if (this.explicit.has(identity))
        throw new Error("Archive contains a duplicate root directory entry");
      this.nodes.set(identity, "directory");
      this.explicit.add(identity);
      return;
    }
    const segments = identity.split("/");
    for (let index = 1; index < segments.length; index += 1) {
      const parent = segments.slice(0, index).join("/");
      if (this.nodes.get(parent) === "file")
        throw new Error("Archive contains a file versus directory prefix conflict");
      if (!this.nodes.has(parent)) this.nodes.set(parent, "directory");
    }
    const expectedType = directory ? "directory" : "file";
    const existing = this.nodes.get(identity);
    if (existing && existing !== expectedType)
      throw new Error("Archive contains a file versus directory path conflict");
    if (this.explicit.has(identity))
      throw new Error("Archive contains a target-platform path collision");
    this.nodes.set(identity, expectedType);
    this.explicit.add(identity);
  }
}

function validateTargetPathSegments(segments, platform) {
  if (!segments.length) return;
  if (segments.some((segment) => Buffer.byteLength(segment, "utf8") > 255))
    throw new Error("Archive path segment is too long for safe extraction");
  const relative = segments.join("/");
  if (platform === "win32") {
    if (Buffer.byteLength(relative, "utf8") > 1_024)
      throw new Error("Windows archive path is too long for safe extraction");
    for (const segment of segments) {
      if (
        /[^\x20-\x7e]/.test(segment) ||
        /[:<>"|?*]/.test(segment) ||
        /[. ]$/.test(segment) ||
        /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(segment)
      ) {
        throw new Error("Windows archive path uses ADS, reserved, or noncanonical names");
      }
    }
  }
  if (platform === "darwin") {
    if (Buffer.byteLength(relative, "utf8") > 2_048)
      throw new Error("macOS archive path is too long for safe extraction");
    if (segments.some((segment) => /[^\x20-\x7e]/.test(segment)))
      throw new Error("macOS archive path uses a noncanonical name");
  }
}

async function extractVerifiedArchive({
  openArtifact,
  stagingDirectory,
  archiveInventory,
  archiveType,
  expectedRoot,
  platform,
}) {
  const extractionRoot = prepareExtractionDirectories({
    stagingDirectory,
    expectedRoot,
    archiveInventory,
  });
  if (archiveType === "zip") {
    await extractZipArchive({ openArtifact, extractionRoot, archiveInventory });
  } else {
    const replay = await processTarGzArchive({
      openArtifact,
      expectedRoot,
      platform,
      extractionRoot,
    });
    if (
      replay.tarStreamSha256 !== archiveInventory.tarStreamSha256 ||
      replay.archiveRecordSha256 !== archiveInventory.archiveRecordSha256 ||
      replay.decompressedBytes !== archiveInventory.decompressedBytes ||
      canonicalJson(replay.files) !== canonicalJson(archiveInventory.files)
    ) {
      throw new Error("TAR extraction did not replay the exact inspected archive records");
    }
  }
  applyInspectedDirectoryModes(extractionRoot, archiveInventory, platform);
}

function prepareExtractionDirectories({
  stagingDirectory,
  expectedRoot,
  archiveInventory,
}) {
  assertDirectoryUnlinked(stagingDirectory, "archive staging directory");
  if (readdirSync(stagingDirectory).length)
    throw new Error("Archive staging directory must be empty before extraction");
  const stagingRoot = realpathSync.native(stagingDirectory);
  const directories = new Set(["."]);
  for (const record of archiveInventory.records || [])
    if (record.kind === "directory") directories.add(record.path);
  for (const record of archiveInventory.files) {
    const segments = record.path.split("/");
    for (let index = 1; index < segments.length; index += 1)
      directories.add(segments.slice(0, index).join("/"));
  }
  const ordered = [...directories].sort((left, right) => {
    const depth = (value) => (value === "." ? 0 : value.split("/").length);
    return depth(left) - depth(right) || left.localeCompare(right, "en");
  });
  let extractionRoot;
  for (const relative of ordered) {
    const target = relative === "."
      ? path.join(stagingRoot, expectedRoot)
      : path.join(extractionRoot, ...relative.split("/"));
    const parent = path.dirname(target);
    assertSecureDirectoryChain(stagingRoot, parent);
    if (existsSync(target))
      throw new Error("Extraction directory appeared before its exclusive creation");
    mkdirSync(target, { mode: 0o700 });
    assertDirectoryUnlinked(target, "new archive extraction directory");
    const actual = realpathSync.native(target);
    if (!pathInside(stagingRoot, actual))
      throw new Error("New archive extraction directory escaped staging");
    if (relative === ".") extractionRoot = actual;
  }
  return extractionRoot;
}

async function extractZipArchive({ openArtifact, extractionRoot, archiveInventory }) {
  for (const record of archiveInventory.records) {
    const writer = openExtractionFile(extractionRoot, record.path, "0600");
    let checksum = 0xffff_ffff;
    let outputBytes = 0;
    const accept = (chunk) => {
      outputBytes += chunk.length;
      if (
        outputBytes > record.bytes ||
        outputBytes > MAX_UNPACKED_BYTES
      ) {
        throw new Error(`ZIP entry expanded beyond its inspected size: ${record.path}`);
      }
      checksum = updateCrc32(checksum, chunk);
      writeAll(writer.descriptor, chunk);
      writer.bytes += chunk.length;
    };
    try {
      if (record.method === 0) {
        let offset = record.dataStart;
        while (offset < record.dataEnd) {
          const length = Math.min(1024 * 1024, record.dataEnd - offset);
          const chunk = readExactly(openArtifact.descriptor, length, offset);
          accept(chunk);
          offset += length;
        }
      } else {
        await inflateZipRecord(openArtifact, record, accept);
      }
      const observedCrc = (checksum ^ 0xffff_ffff) >>> 0;
      if (outputBytes !== record.bytes)
        throw new Error(`ZIP entry size differs from inspection: ${record.path}`);
      if (observedCrc !== record.crc32)
        throw new Error(`ZIP entry CRC32 differs from inspection: ${record.path}`);
      finalizeExtractionFile(writer, record.bytes, "0600");
    } catch (error) {
      abortExtractionFile(writer);
      throw error;
    }
  }
}

async function inflateZipRecord(openArtifact, record, accept) {
  const source = descriptorReadStream(
    openArtifact.descriptor,
    record.dataStart,
    record.dataEnd,
  );
  const inflater = createInflateRaw();
  let compressedBytes = 0;
  source.on("data", (chunk) => {
    compressedBytes += chunk.length;
    if (compressedBytes > record.compressedBytes)
      source.destroy(new Error("ZIP compressed stream exceeded its inspected range"));
  });
  source.once("error", (error) => inflater.destroy(error));
  source.pipe(inflater);
  try {
    for await (const chunk of inflater) accept(chunk);
    if (compressedBytes !== record.compressedBytes)
      throw new Error(`ZIP entry compressed stream was partial: ${record.path}`);
    if (
      Number.isSafeInteger(inflater.bytesWritten) &&
      inflater.bytesWritten !== record.compressedBytes
    ) {
      throw new Error(`ZIP deflate stream has unconsumed trailing bytes: ${record.path}`);
    }
  } catch (error) {
    source.destroy();
    inflater.destroy();
    throw error;
  }
}

const crc32Table = Array.from({ length: 256 }, (_unused, value) => {
  let current = value;
  for (let bit = 0; bit < 8; bit += 1)
    current = current & 1 ? 0xedb88320 ^ (current >>> 1) : current >>> 1;
  return current >>> 0;
});

function updateCrc32(checksum, buffer) {
  let current = checksum >>> 0;
  for (const byte of buffer)
    current = crc32Table[(current ^ byte) & 0xff] ^ (current >>> 8);
  return current >>> 0;
}

function descriptorReadStream(descriptor, start, endExclusive) {
  if (
    !Number.isSafeInteger(start) ||
    !Number.isSafeInteger(endExclusive) ||
    start < 0 ||
    endExclusive < start
  ) {
    throw new Error("Archive descriptor stream bounds are invalid");
  }
  return Readable.from((async function* readDescriptorRange() {
    let position = start;
    while (position < endExclusive) {
      const length = Math.min(1024 * 1024, endExclusive - position);
      const chunk = readExactly(descriptor, length, position);
      position += chunk.length;
      yield chunk;
    }
  })());
}

function openExtractionFile(extractionRoot, relativePath, mode) {
  const target = path.resolve(extractionRoot, ...relativePath.split("/"));
  if (!pathInside(extractionRoot, target) || target === extractionRoot)
    throw new Error("Extraction file path escaped its canonical root");
  assertSecureDirectoryChain(extractionRoot, path.dirname(target));
  const descriptor = openSync(
    target,
    fsConstants.O_CREAT |
      fsConstants.O_EXCL |
      fsConstants.O_WRONLY |
      (fsConstants.O_NOFOLLOW || 0),
    Number.parseInt(mode, 8) & 0o777,
  );
  try {
    const stats = fstatSync(descriptor, { bigint: true });
    if (!stats.isFile() || stats.nlink !== 1n)
      throw new Error("Exclusive extraction target is not one regular file");
    return { descriptor, target, bytes: 0, closed: false };
  } catch (error) {
    closeSync(descriptor);
    try { unlinkSync(target); } catch {}
    throw error;
  }
}

function finalizeExtractionFile(writer, expectedBytes, mode) {
  if (writer.closed) throw new Error("Extraction file was already finalized");
  try {
    if (writer.bytes !== expectedBytes)
      throw new Error("Extraction file byte count differs from its inspected record");
    fchmodSync(writer.descriptor, Number.parseInt(mode, 8) & 0o777);
    fsyncSync(writer.descriptor);
    const stats = fstatSync(writer.descriptor, { bigint: true });
    if (
      !stats.isFile() ||
      stats.nlink !== 1n ||
      stats.size !== BigInt(expectedBytes)
    ) {
      throw new Error("Extraction file descriptor differs from its inspected record");
    }
    const identity = {
      dev: stats.dev.toString(),
      ino: stats.ino.toString(),
      size: stats.size,
      mtimeNs: stats.mtimeNs.toString(),
      ctimeNs: stats.ctimeNs.toString(),
    };
    closeSync(writer.descriptor);
    writer.closed = true;
    assertPathMatchesIdentity(writer.target, identity, "extracted archive file");
  } catch (error) {
    abortExtractionFile(writer);
    throw error;
  }
}

function abortExtractionFile(writer) {
  if (!writer || writer.closed) return;
  try { closeSync(writer.descriptor); } catch {}
  writer.closed = true;
  try { unlinkSync(writer.target); } catch {}
}

function assertSecureDirectoryChain(root, directory) {
  const rootReal = realpathSync.native(root);
  const target = path.resolve(directory);
  if (!pathInside(rootReal, target))
    throw new Error("Extraction directory chain escaped its staging root");
  const relative = path.relative(rootReal, target);
  let current = rootReal;
  assertDirectoryUnlinked(current, "archive extraction root");
  for (const segment of relative ? relative.split(path.sep) : []) {
    current = path.join(current, segment);
    assertDirectoryUnlinked(current, "archive extraction parent");
    if (!pathInside(rootReal, realpathSync.native(current)))
      throw new Error("Archive extraction parent resolves outside staging");
  }
}

function applyInspectedDirectoryModes(extractionRoot, archiveInventory, platform) {
  if (platform === "win32" || platform !== process.platform) return;
  const directories = (archiveInventory.records || [])
    .filter((record) => record.kind === "directory")
    .sort((left, right) => right.path.split("/").length - left.path.split("/").length);
  for (const record of directories) {
    const target = record.path === "."
      ? extractionRoot
      : path.resolve(extractionRoot, ...record.path.split("/"));
    assertSecureDirectoryChain(extractionRoot, target);
    const descriptor = openSync(
      target,
      fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0),
    );
    try {
      const stats = fstatSync(descriptor, { bigint: true });
      if (!stats.isDirectory())
        throw new Error("Inspected TAR directory became a non-directory");
      fchmodSync(descriptor, Number.parseInt(record.mode, 8) & 0o777);
      fsyncSync(descriptor);
    } finally {
      closeSync(descriptor);
    }
  }
}

function inventoryExtractedPayload({
  stagingDirectory,
  expectedRootName,
  archiveInventory,
  platform,
}) {
  const stagingEntries = readdirSync(stagingDirectory, { withFileTypes: true });
  if (
    stagingEntries.length !== 1 ||
    stagingEntries[0].name !== expectedRootName ||
    !stagingEntries[0].isDirectory() ||
    stagingEntries[0].isSymbolicLink()
  ) {
    throw new Error("Extracted archive does not contain the exact canonical single root");
  }
  const root = path.join(stagingDirectory, expectedRootName);
  assertDirectoryUnlinked(root, "extracted canonical root");
  const realRoot = realpathSync.native(root);
  const files = [];
  const observedModes = new Map();
  const walk = (directory, relativeDirectory = "") => {
    const entries = readdirSync(directory, { withFileTypes: true }).sort((left, right) =>
      left.name.localeCompare(right.name, "en"),
    );
    for (const entry of entries) {
      if (entry.name === "." || entry.name === ".." || /[\0-\x1f\x7f]/.test(entry.name))
        throw new Error("Extracted entry name is unsafe");
      const absolute = path.join(directory, entry.name);
      const relative = relativeDirectory
        ? `${relativeDirectory}/${entry.name}`
        : entry.name;
      const stats = lstatSync(absolute, { bigint: true });
      if (stats.isSymbolicLink())
        throw new Error("Extracted symbolic links are forbidden");
      const actual = realpathSync.native(absolute);
      if (!pathInside(realRoot, actual))
        throw new Error("Extracted entry resolves outside the canonical root");
      if (stats.isDirectory()) {
        walk(absolute, relative);
        continue;
      }
      if (!stats.isFile() || stats.nlink !== 1n)
        throw new Error("Extracted hardlinks and special filesystem entries are forbidden");
      const bytes = Number(stats.size);
      if (!Number.isSafeInteger(bytes))
        throw new Error("Extracted file size exceeds the safe integer range");
      files.push({ path: relative, bytes, sha256: sha256File(absolute) });
      observedModes.set(relative, Number(stats.mode & 0o7777n));
    }
  };
  walk(root);
  files.sort((left, right) => left.path.localeCompare(right.path, "en"));
  if (files.length !== archiveInventory.files.length)
    throw new Error("Extracted file count differs from the inspected archive");
  for (let index = 0; index < files.length; index += 1) {
    const expected = archiveInventory.files[index];
    const actual = files[index];
    if (
      actual.path !== expected.path ||
      actual.bytes !== expected.bytes ||
      (expected.dataSha256 && actual.sha256 !== expected.dataSha256)
    )
      throw new Error("Extracted file inventory differs from the inspected archive");
  }
  const totalBytes = files.reduce((sum, record) => sum + record.bytes, 0);
  if (totalBytes !== archiveInventory.totalBytes)
    throw new Error("Extracted byte count differs from the inspected archive");
  const modeBoundFiles = files.map((record, index) => {
    const expectedMode = archiveInventory.files[index].mode;
    if (platform !== "win32" && !/^0[0-7]{3}$/.test(expectedMode))
      throw new Error("Inspected POSIX archive mode is not canonical");
    if (
      platform === process.platform &&
      platform !== "win32" &&
      normalizedPosixMode(observedModes.get(record.path)) !== expectedMode
    ) {
      throw new Error(`Extracted POSIX mode differs from the inspected archive: ${record.path}`);
    }
    return { ...record, mode: platform === "win32" ? "neutral" : expectedMode };
  });
  return Object.freeze({
    root: realRoot,
    rootName: expectedRootName,
    files: modeBoundFiles,
    fileCount: modeBoundFiles.length,
    totalBytes,
    payloadInventorySha256: sha256Text(canonicalJson(modeBoundFiles)),
  });
}

function verifyExtractedInnerBuildIntegrity({
  extracted,
  channel,
  artifactKind,
  evidencePath,
  evidenceDigest,
  artifact,
}) {
  const manifestName = "BUILD-MANIFEST.json";
  const attestationName = "BUILD-MANIFEST.signature.json";
  const publicKeyName = "trust/release-signing-public.pem";
  const keyMetadataName = "trust/release-signing-key.json";
  const byPath = new Map(extracted.files.map((record) => [record.path, record]));
  for (const required of [
    manifestName,
    attestationName,
    publicKeyName,
    keyMetadataName,
  ]) {
    if (!byPath.has(required))
      throw new Error(`Extracted inner build integrity file is missing: ${required}`);
  }
  const manifestPath = payloadPath(extracted.root, manifestName);
  const attestationPath = payloadPath(extracted.root, attestationName);
  const publicKeyPath = payloadPath(extracted.root, publicKeyName);
  const keyMetadataPath = payloadPath(extracted.root, keyMetadataName);
  const manifest = readStrictJson(
    manifestPath,
    "extracted BUILD-MANIFEST",
    MAX_MANIFEST_BYTES,
  );
  const expectedProduct = artifactKind === "audit-witness"
    ? "MarketingOS Audit Witness"
    : artifactKind === "product"
      ? "MarketingOS"
      : null;
  if (
    manifest.schemaVersion !== "marketingos.buildManifest.v2" ||
    expectedProduct === null ||
    manifest.product !== expectedProduct ||
    manifest.version !== channel.version ||
    manifest.channel !== channel.channel ||
    manifest.channelSequence !== channel.sequence ||
    manifest.platform !== channel.platform ||
    manifest.architecture !== channel.architecture ||
    manifest.signingAuthority !== "ci-ephemeral-contract-only" ||
    !Array.isArray(manifest.files) ||
    manifest.files.length < 1 ||
    manifest.files.length > MAX_ARCHIVE_ENTRIES
  ) {
    throw new Error("Extracted BUILD-MANIFEST identity is invalid");
  }
  const seen = new Set();
  const portableSeen = new Set();
  let previous = "";
  for (const record of manifest.files) {
    exactKeys(record, ["bytes", "path", "sha256"], "BUILD-MANIFEST file");
    const portableIdentity = String(record.path || "").normalize("NFC").toLowerCase();
    if (
      !safePayloadRelativePath(record.path) ||
      [manifestName, attestationName].includes(record.path) ||
      !Number.isSafeInteger(record.bytes) ||
      record.bytes < 0 ||
      !isSha256(record.sha256) ||
      seen.has(record.path) ||
      portableSeen.has(portableIdentity) ||
      (previous && previous.localeCompare(record.path, "en") >= 0)
    ) {
      throw new Error(`Extracted BUILD-MANIFEST file record is invalid: ${String(record.path)}`);
    }
    seen.add(record.path);
    portableSeen.add(portableIdentity);
    previous = record.path;
  }
  const actualPayload = extracted.files
    .filter((record) => ![manifestName, attestationName].includes(record.path))
    .map(({ path: filePath, bytes, sha256: fileSha256 }) => ({
      path: filePath,
      bytes,
      sha256: fileSha256,
    }));
  if (canonicalJson(actualPayload) !== canonicalJson(manifest.files))
    throw new Error("Extracted payload has unknown, missing, or changed BUILD-MANIFEST files");
  const inventorySha256 = sha256Text(canonicalJson(manifest.files));
  const modePolicy = verifyAcquiredModePolicy({ manifest, extracted, channel });

  const publicPem = secureReadFile(
    publicKeyPath,
    "inner build public key",
    64 * 1024,
  ).toString("utf8");
  const publicKey = createPublicKey(publicPem);
  if (publicKey.asymmetricKeyType !== "ed25519")
    throw new Error("Inner build public key is not Ed25519");
  const spkiSha256 = sha256(publicKey.export({ type: "spki", format: "der" }));
  const keyId = `marketingos-release-ed25519:${spkiSha256.slice(0, 32)}`;
  if (spkiSha256 === channel.releaseKey?.spkiSha256)
    throw new Error("Inner build and outer publisher identities must be distinct");
  const metadata = readStrictJson(
    keyMetadataPath,
    "inner build key metadata",
  );
  exactKeys(
    metadata,
    ["algorithm", "keyId", "publicKeyFile", "schemaVersion", "spkiSha256"],
    "inner build key metadata",
  );
  if (
    metadata.schemaVersion !== "marketingos.releaseSigningKey.v1" ||
    metadata.algorithm !== "Ed25519" ||
    metadata.keyId !== keyId ||
    metadata.spkiSha256 !== spkiSha256 ||
    metadata.publicKeyFile !== "release-signing-public.pem"
  ) {
    throw new Error("Inner build key metadata does not match its public key");
  }
  const envelope = readStrictJson(
    attestationPath,
    "extracted BUILD-MANIFEST attestation",
    4 * 1024 * 1024,
  );
  exactKeys(
    envelope,
    ["algorithm", "keyId", "payload", "schemaVersion", "signature", "signedAt", "subject"],
    "BUILD-MANIFEST attestation",
  );
  exactKeys(envelope.subject, ["bytes", "name", "sha256"], "BUILD-MANIFEST subject");
  exactKeys(envelope.payload, ["fileCount", "inventorySha256"], "BUILD-MANIFEST payload");
  const manifestDigest = byPath.get(manifestName);
  if (
    envelope.schemaVersion !== "marketingos.buildManifestAttestation.v1" ||
    envelope.algorithm !== "Ed25519" ||
    envelope.keyId !== keyId ||
    !isExactIso(envelope.signedAt) ||
    envelope.subject.name !== manifestName ||
    envelope.subject.bytes !== manifestDigest.bytes ||
    envelope.subject.sha256 !== manifestDigest.sha256 ||
    envelope.payload.fileCount !== manifest.files.length ||
    envelope.payload.inventorySha256 !== inventorySha256 ||
    !/^[A-Za-z0-9_-]{86}$/.test(String(envelope.signature || ""))
  ) {
    throw new Error("BUILD-MANIFEST attestation binding is invalid");
  }
  const signature = Buffer.from(envelope.signature, "base64url");
  if (
    signature.length !== 64 ||
    signature.toString("base64url") !== envelope.signature
  ) {
    throw new Error("BUILD-MANIFEST signature encoding is not canonical");
  }
  const unsignedEnvelope = { ...envelope };
  delete unsignedEnvelope.signature;
  if (
    !verifyEd25519(
      null,
      Buffer.from(canonicalJson(unsignedEnvelope), "utf8"),
      publicKey,
      signature,
    )
  ) {
    throw new Error("BUILD-MANIFEST Ed25519 signature is invalid");
  }

  assertDigestUnchanged(
    evidencePath,
    evidenceDigest,
    "outer signed release evidence",
  );
  const evidence = readStrictJson(
    evidencePath,
    "outer signed release evidence",
    128 * 1024 * 1024,
  );
  const binding = evidence.officialPublisher;
  const inner = binding?.innerBuildIntegrity;
  if (
    binding?.schemaVersion !== "marketingos.officialPublisherBinding.v1" ||
    binding.artifactSha256 !== artifact.sha256 ||
    binding.artifactUnchangedAfterBuild !== true ||
    !inner ||
    inner.keyId !== keyId ||
    inner.spkiSha256 !== spkiSha256 ||
    inner.inventorySha256 !== inventorySha256 ||
    inner.signingAuthority !== "ci-ephemeral-contract-only"
  ) {
    throw new Error(
      "Outer signed release evidence does not bind the exact extracted inner build identity",
    );
  }
  return Object.freeze({
    schemaVersion: "marketingos.acquiredInnerBuildIntegrity.v1",
    verified: true,
    algorithm: "Ed25519",
    keyId,
    spkiSha256,
    inventorySha256,
    fileCount: manifest.files.length,
    signingAuthority: "ci-ephemeral-contract-only",
    manifestPath: realpathSync.native(manifestPath),
    manifestSha256: manifestDigest.sha256,
    attestationPath: realpathSync.native(attestationPath),
    evidencePath: realpathSync.native(evidencePath),
    evidenceSha256: evidenceDigest.sha256,
    outerEvidenceBindingVerified: true,
    everyDeclaredFileVerified: true,
    unknownFilesBlocked: true,
    modePolicyVerified: true,
    executableFileCount: modePolicy.executableFileCount,
    normalizedModePolicy: modePolicy.normalizedModePolicy,
  });
}

function verifyAcquiredModePolicy({ manifest, extracted, channel }) {
  if (channel.platform === "win32") {
    if (extracted.files.some((record) => record.mode !== "neutral"))
      throw new Error("Windows acquisition inventory must use neutral mode values");
    if (manifest.executableModes !== undefined)
      throw new Error("Windows BUILD-MANIFEST must not declare POSIX executable modes");
    return {
      executableFileCount: 0,
      normalizedModePolicy: "windows-neutral",
    };
  }
  const productExecutables = [
    "Install-MarketingOS-Agent-Pack.sh",
    "Install-MarketingOS-Hermes.sh",
    "Install-MarketingOS-OpenClaw.sh",
    "MarketingOS-Autostart.sh",
    "MarketingOS-Maintenance.sh",
    "MarketingOS-Secure.sh",
    "Start-MarketingOS.sh",
    "Status-MarketingOS.sh",
    "Stop-MarketingOS.sh",
    "agent-pack/bin/install-marketingos.mjs",
    "agent-pack/bin/manage-autostart.mjs",
    "agent-pack/bin/portable-service.mjs",
    "runtime/node",
  ];
  const witnessExecutables = [
    "Register-Audit-Service.sh",
    "Setup-Witness.sh",
    "Start-Witness.sh",
    "Verify-Witness-Release.sh",
    "Verify-Witness.sh",
    "bin/audit-witness-ingress-relay.mjs",
    "bin/audit-witness-release-entrypoint.mjs",
    "bin/check-audit-witness-tailscale-serve.mjs",
    "runtime/node",
  ];
  const allowed = manifest.product === "MarketingOS Audit Witness"
    ? witnessExecutables
    : productExecutables;
  if (!Array.isArray(manifest.executableModes))
    throw new Error("POSIX BUILD-MANIFEST executable mode contract is missing");
  const declared = [];
  for (const record of manifest.executableModes) {
    exactKeys(record, ["mode", "path"], "BUILD-MANIFEST executable mode");
    if (!safePayloadRelativePath(record.path) || record.mode !== "0755")
      throw new Error("BUILD-MANIFEST executable mode record is invalid");
    declared.push(record.path);
  }
  const sortedDeclared = [...declared].sort((left, right) =>
    left.localeCompare(right, "en"),
  );
  const sortedAllowed = [...allowed].sort((left, right) =>
    left.localeCompare(right, "en"),
  );
  if (canonicalJson(sortedDeclared) !== canonicalJson(sortedAllowed))
    throw new Error("BUILD-MANIFEST executable paths differ from the fixed release allowlist");
  const byPath = new Map(extracted.files.map((record) => [record.path, record]));
  for (const executable of allowed) {
    const record = byPath.get(executable);
    if (!record || record.mode !== "0755")
      throw new Error(`Required release executable mode is missing: ${executable}`);
  }
  const executableSet = new Set(allowed);
  for (const record of extracted.files) {
    if (executableSet.has(record.path)) continue;
    if (!new Set(["0444", "0644"]).has(record.mode))
      throw new Error(`Unexpected executable or writable payload mode: ${record.path}`);
  }
  return {
    executableFileCount: allowed.length,
    normalizedModePolicy: "posix-fixed-executable-allowlist-v1",
  };
}

function payloadPath(root, relativePath) {
  if (!safePayloadRelativePath(relativePath))
    throw new Error("Payload path is unsafe");
  const target = path.resolve(root, ...relativePath.split("/"));
  if (!pathInside(root, target)) throw new Error("Payload path escapes its root");
  return target;
}

function safePayloadRelativePath(value) {
  return (
    typeof value === "string" &&
    value.length > 0 &&
    !value.includes("\\") &&
    !value.startsWith("/") &&
    !value.split("/").some((segment) => !segment || segment === "." || segment === "..") &&
    !/[\0-\x1f\x7f]/.test(value)
  );
}

async function runAcquisitionTestBarrier(policy, directory, name) {
  if (
    policy.mode !== "test" ||
    process.env.MARKETINGOS_ACQUISITION_ENV !== TEST_ENVIRONMENT ||
    process.env.MARKETINGOS_ACQUISITION_TEST_BARRIERS !== "1"
  ) return;
  const marker = path.join(directory, `.fixture-barrier-${name}`);
  writeNewFile(marker, `${name}\n`, 0o600);
  const deadline = Date.now() + 15_000;
  while (existsSync(marker)) {
    if (Date.now() >= deadline)
      throw new Error(`Fixture barrier timed out: ${name}`);
    await new Promise((resolve) => setTimeout(resolve, 20));
  }
}

function applyFixtureExtractionEnvironment(policy) {
  const fakeSystemRoot =
    process.env.MARKETINGOS_ACQUISITION_TEST_SYSTEM_ROOT || "";
  if (!fakeSystemRoot) return;
  if (
    policy.mode !== "test" ||
    process.env.MARKETINGOS_ACQUISITION_ENV !== TEST_ENVIRONMENT ||
    process.env.NODE_ENV === "production"
  ) {
    throw new Error("Fixture extraction environment is forbidden in production");
  }
  process.env.SystemRoot = fakeSystemRoot;
  process.env.WINDIR = fakeSystemRoot;
}

function writeAcquisitionReceipt({
  receiptPath,
  bootstrap,
  policy,
  externalReceipt,
  artifactPath,
  artifact,
  channel,
  channelDigest,
  extracted,
  stagingDirectory,
  innerBuildIntegrity,
  artifactKind,
  canonicalRootName,
  releaseSet,
}) {
  const unsigned = {
    schemaVersion: ACQUISITION_RECEIPT_SCHEMA,
    generatedAt: new Date().toISOString(),
    product: "MarketingOS",
    acquisitionMode: policy.mode === "production" ? "production" : "fixture-test",
    canonicalOrigin: policy.origin,
    canonicalRepository: policy.repository,
    releaseTag: `v${channel.version}`,
    channelUrl: policy.channelUrl,
    productVersion: channel.version,
    artifactName: artifact.name,
    artifactKind,
    platform: channel.platform,
    architecture: channel.architecture,
    canonicalRootName,
    releaseSet,
    trustBoundary: TRUST_BOUNDARY,
    productCodeExecuted: false,
    bootstrap: {
      name: BOOTSTRAP_NAME,
      path: bootstrap.path,
      bytes: bootstrap.bytes,
      sha256: bootstrap.sha256,
    },
    externalBootstrapReceipt: {
      path: externalReceipt.path,
      bytes: externalReceipt.bytes,
      sha256: externalReceipt.sha256,
    },
    artifact: {
      name: artifact.name,
      path: realpathSync.native(artifactPath),
      bytes: artifact.bytes,
      sha256: artifact.sha256,
    },
    channel: {
      name: channel.channel,
      sequence: channel.sequence,
      issuedAt: channel.issuedAt,
      expiresAt: channel.expiresAt,
      manifestName: path.basename(channelDigest.path),
      manifestSha256: channelDigest.sha256,
    },
    extraction: {
      stagingDirectory: realpathSync.native(stagingDirectory),
      extractedRoot: extracted.root,
      canonicalRootName: extracted.rootName,
      fileCount: extracted.fileCount,
      totalBytes: extracted.totalBytes,
    },
    files: extracted.files,
    payloadInventorySha256: extracted.payloadInventorySha256,
    innerBuildIntegrity,
  };
  const receipt = {
    ...unsigned,
    receiptHash: sha256Text(canonicalJson(unsigned)),
  };
  atomicJson(receiptPath, receipt);
  const readBack = readStrictJson(receiptPath, "acquisition receipt");
  if (canonicalJson(readBack) !== canonicalJson(receipt))
    throw new Error("Acquisition receipt atomic readback differs from its source");
  return Object.freeze(receipt);
}

function acquireDestinationLock(destination) {
  const lockPath = `${destination}.acquire.lock`;
  assertSafeExistingParent(lockPath, "acquisition lock");
  try {
    mkdirSync(lockPath, { mode: 0o700 });
  } catch (error) {
    if (error?.code === "EEXIST")
      throw new Error("Acquisition destination is locked by another process");
    throw error;
  }
  const token = randomBytes(24).toString("hex");
  const ownerPath = path.join(lockPath, "owner.json");
  const owner = {
    schemaVersion: "marketingos.acquisitionLock.v1",
    pid: process.pid,
    startedAt: new Date().toISOString(),
    destination,
    token,
  };
  try {
    writeNewFile(ownerPath, `${JSON.stringify(owner, null, 2)}\n`, 0o600);
    fsyncDirectory(lockPath);
    return Object.freeze({ path: lockPath, ownerPath, token });
  } catch (error) {
    try {
      rmdirSync(lockPath);
    } catch {}
    throw error;
  }
}

function acquireCatalogStateLock(statePath) {
  const lockPath = `${statePath}.lock`;
  assertSafeExistingParent(lockPath, "release set catalog state lock");
  try { mkdirSync(lockPath, { mode: 0o700 }); }
  catch (error) {
    if (error?.code === "EEXIST") throw new Error("Release set catalog state is locked by another acquisition");
    throw error;
  }
  const token = randomBytes(24).toString("hex");
  const ownerPath = path.join(lockPath, "owner.json");
  try {
    writeNewFile(ownerPath, `${JSON.stringify({
      schemaVersion: "marketingos.releaseSetCatalogStateLock.v1",
      pid: process.pid,
      startedAt: new Date().toISOString(),
      statePath: path.resolve(statePath),
      token,
    }, null, 2)}\n`, 0o600);
    fsyncDirectory(lockPath);
    return Object.freeze({ path: lockPath, ownerPath, token });
  } catch (error) {
    try { rmdirSync(lockPath); } catch {}
    throw error;
  }
}

function releaseCatalogStateLock(lock) {
  if (!lock) return;
  try {
    assertDirectoryUnlinked(lock.path, "release set catalog state lock");
    const owner = readStrictJson(lock.ownerPath, "release set catalog state lock owner");
    if (owner.token !== lock.token) throw new Error("Release set catalog state lock ownership changed");
    const entries = readdirSync(lock.path);
    if (entries.length !== 1 || entries[0] !== "owner.json") throw new Error("Release set catalog state lock contains unknown files");
    unlinkSync(lock.ownerPath);
    rmdirSync(lock.path);
    fsyncDirectory(path.dirname(lock.path));
  } catch {
    // An ambiguous catalog state lock is retained for manual review.
  }
}

function releaseDestinationLock(lock) {
  if (!lock) return;
  try {
    assertDirectoryUnlinked(lock.path, "acquisition lock");
    const owner = readStrictJson(lock.ownerPath, "acquisition lock owner");
    if (owner.token !== lock.token)
      throw new Error("Acquisition lock ownership changed");
    const entries = readdirSync(lock.path);
    if (entries.length !== 1 || entries[0] !== "owner.json")
      throw new Error("Acquisition lock directory contains unknown files");
    unlinkSync(lock.ownerPath);
    rmdirSync(lock.path);
    fsyncDirectory(path.dirname(lock.path));
  } catch {
    // Fail closed. An ambiguous lock is deliberately left for manual review.
  }
}

function writeFailureMarker(destination, error) {
  try {
    const marker = path.join(destination, "ACQUISITION-FAILED.json");
    if (existsSync(marker)) return;
    atomicJson(marker, {
      schemaVersion: "marketingos.releaseAcquisitionFailure.v1",
      failedAt: new Date().toISOString(),
      productCodeExecuted: false,
      recovery:
        "Inspect and remove this isolated destination manually before retrying. A failed destination is never reused automatically.",
      error: String(error?.message || error).slice(0, 2_048),
    });
  } catch {}
}

function atomicJson(target, value) {
  const absolute = path.resolve(target);
  if (existsSync(absolute)) throw new Error(`Atomic target already exists: ${path.basename(absolute)}`);
  assertSafeExistingParent(absolute, "atomic JSON target");
  const temporary = path.join(
    path.dirname(absolute),
    `.${path.basename(absolute)}.${process.pid}.${randomBytes(12).toString("hex")}.tmp`,
  );
  const text = `${JSON.stringify(value, null, 2)}\n`;
  try {
    writeNewFile(temporary, text, 0o600);
    if (existsSync(absolute))
      throw new Error("Atomic target appeared before publication");
    renameSync(temporary, absolute);
    fsyncDirectory(path.dirname(absolute));
  } catch (error) {
    try {
      unlinkSync(temporary);
    } catch {}
    throw error;
  }
}

function writeNewFile(target, text, mode) {
  const buffer = Buffer.from(text, "utf8");
  const descriptor = openSync(
    target,
    fsConstants.O_CREAT |
      fsConstants.O_EXCL |
      fsConstants.O_WRONLY |
      (fsConstants.O_NOFOLLOW || 0),
    mode,
  );
  try {
    writeAll(descriptor, buffer);
    fsyncSync(descriptor);
  } finally {
    closeSync(descriptor);
  }
}

function fsyncDirectory(directory) {
  if (process.platform === "win32") return;
  let descriptor;
  try {
    descriptor = openSync(directory, fsConstants.O_RDONLY);
    fsyncSync(descriptor);
  } catch (error) {
    if (!["EISDIR", "EPERM", "EACCES", "EINVAL", "EBADF"].includes(error?.code))
      throw error;
  } finally {
    if (descriptor !== undefined) closeSync(descriptor);
  }
}

function assertDigestUnchanged(filePath, expected, label) {
  const observed = secureDigestFile(filePath, label, MAX_ARCHIVE_BYTES);
  if (observed.bytes !== expected.bytes || observed.sha256 !== expected.sha256)
    throw new Error(`${label} changed after external verification`);
}

function assertDownloadedBundleUnchanged(downloaded) {
  if (!(downloaded instanceof Map) || downloaded.size !== 8)
    throw new Error("Downloaded release bundle is not the exact eight-file set");
  for (const [kind, record] of downloaded)
    assertDigestUnchanged(
      record.path,
      record,
      `downloaded release ${kind}`,
    );
}

function secureDigestFile(filePath, label, maximumBytes, minimumBytes = 1) {
  const absolute = path.resolve(filePath);
  assertRegularUnlinkedFile(absolute, label);
  const descriptor = openSync(
    absolute,
    fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0),
  );
  try {
    const before = fstatIdentity(descriptor);
    if (before.size < BigInt(minimumBytes) || before.size > BigInt(maximumBytes))
      throw new Error(`${label} size is outside its limit`);
    const hash = createHash("sha256");
    const buffer = Buffer.allocUnsafe(1024 * 1024);
    let total = 0;
    while (true) {
      const count = readSync(descriptor, buffer, 0, buffer.length, null);
      if (!count) break;
      total += count;
      if (total > maximumBytes) throw new Error(`${label} exceeded its read limit`);
      hash.update(buffer.subarray(0, count));
    }
    const after = fstatIdentity(descriptor);
    if (canonicalJson(before) !== canonicalJson(after) || BigInt(total) !== before.size)
      throw new Error(`${label} changed while it was being read`);
    assertPathMatchesIdentity(absolute, before, label);
    return Object.freeze({
      name: path.basename(absolute),
      path: realpathSync.native(absolute),
      bytes: total,
      sha256: hash.digest("hex"),
    });
  } finally {
    closeSync(descriptor);
  }
}

function fstatIdentity(descriptor) {
  const stats = statDescriptor(descriptor);
  if (!stats.isFile() || stats.nlink !== 1n)
    throw new Error("Secure file is not one unlinked regular file");
  return {
    dev: stats.dev.toString(),
    ino: stats.ino.toString(),
    size: stats.size,
    mtimeNs: stats.mtimeNs.toString(),
    ctimeNs: stats.ctimeNs.toString(),
  };
}

function statDescriptor(descriptor) {
  return fstatSync(descriptor, { bigint: true });
}

function sha256File(filePath) {
  const stats = statSync(filePath);
  const maximum = Math.max(1, stats.size);
  return secureDigestFile(filePath, path.basename(filePath), maximum, 0).sha256;
}

function assertRegularUnlinkedFile(filePath, label) {
  const absolute = path.resolve(filePath);
  if (!existsSync(absolute)) throw new Error(`${label} does not exist`);
  const stats = lstatSync(absolute, { bigint: true });
  if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1n)
    throw new Error(`${label} must be one regular file without links`);
  const real = realpathSync.native(absolute);
  if (normalizedPathIdentity(real) !== normalizedPathIdentity(absolute))
    throw new Error(`${label} resolves through a linked path`);
}

function assertPathMatchesIdentity(filePath, expected, label) {
  assertRegularUnlinkedFile(filePath, label);
  const stats = lstatSync(path.resolve(filePath), { bigint: true });
  if (
    stats.dev.toString() !== expected.dev ||
    stats.ino.toString() !== expected.ino ||
    stats.size !== expected.size ||
    stats.mtimeNs.toString() !== expected.mtimeNs ||
    stats.ctimeNs.toString() !== expected.ctimeNs
  ) {
    throw new Error(`${label} path identity changed while it was being read`);
  }
}

function assertDirectoryUnlinked(directory, label) {
  const absolute = path.resolve(directory);
  const stats = lstatSync(absolute, { bigint: true });
  if (!stats.isDirectory() || stats.isSymbolicLink())
    throw new Error(`${label} must be a real directory`);
  const real = realpathSync.native(absolute);
  if (normalizedPathIdentity(real) !== normalizedPathIdentity(absolute))
    throw new Error(`${label} resolves through a linked path`);
}

function assertSafeExistingParent(target, label) {
  const parent = path.dirname(path.resolve(target));
  if (!existsSync(parent)) throw new Error(`${label} parent directory does not exist`);
  assertDirectoryUnlinked(parent, `${label} parent`);
  assertPrivateCreationParent(parent, label);
}

function assertPrivateCreationParent(parent, label) {
  if (process.platform === "win32") {
    if (fixtureWindowsAclBypass()) return;
    assertWindowsDirectoryBoundary(parent, label, false);
    return;
  }
  if (typeof process.getuid !== "function")
    throw new Error(`${label} cannot establish the current POSIX user identity`);
  const currentUid = BigInt(process.getuid());
  const parsed = path.parse(parent);
  let current = parsed.root;
  const components = parent.slice(parsed.root.length).split(path.sep).filter(Boolean);
  for (const component of components) {
    current = path.join(current, component);
    const info = lstatSync(current, { bigint: true });
    if (!info.isDirectory() || info.isSymbolicLink())
      throw new Error(`${label} parent path is not a real directory`);
    const mode = Number(info.mode & 0o7777n);
    const sharedWritable = (mode & 0o022) !== 0;
    const sticky = (mode & 0o1000) !== 0;
    if (info.uid !== currentUid && info.uid !== 0n)
      throw new Error(`${label} parent path is owned by another POSIX principal`);
    if (sharedWritable && !sticky)
      throw new Error(`${label} parent path is writable by another POSIX principal`);
    if (sharedWritable && sticky && info.uid !== currentUid && info.uid !== 0n)
      throw new Error(`${label} sticky parent is controlled by another POSIX principal`);
  }
  const direct = lstatSync(parent, { bigint: true });
  if (direct.uid !== currentUid && direct.uid !== 0n)
    throw new Error(`${label} direct parent is not owned by the current POSIX user`);
}

function protectNewDestination(destination) {
  assertDirectoryUnlinked(destination, "new acquisition destination");
  if (process.platform === "win32") {
    if (fixtureWindowsAclBypass()) return;
    assertWindowsDirectoryBoundary(destination, "new acquisition destination", true);
    return;
  }
  const info = lstatSync(destination, { bigint: true });
  if (typeof process.getuid !== "function" || info.uid !== BigInt(process.getuid())
    || Number(info.mode & 0o077n) !== 0) {
    throw new Error("New acquisition destination is not private to the current POSIX user");
  }
}

function fixtureWindowsAclBypass() {
  return process.platform === "win32"
    && activeAcquisitionMode === "test"
    && process.env.MARKETINGOS_ACQUISITION_ENV === TEST_ENVIRONMENT
    && process.env.NODE_ENV !== "production"
    && process.env.MARKETINGOS_ACQUISITION_TEST_SKIP_WINDOWS_ACL === "1";
}

function assertWindowsDirectoryBoundary(directory, label, harden) {
  const script = [
    "$ErrorActionPreference='Stop'",
    "$target=[IO.Path]::GetFullPath($env:MARKETINGOS_ACQUISITION_ACL_PATH)",
    "$current=[Security.Principal.WindowsIdentity]::GetCurrent().User",
    "$system=New-Object Security.Principal.SecurityIdentifier('S-1-5-18')",
    "$admins=New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')",
    "$creator=New-Object Security.Principal.SecurityIdentifier('S-1-3-0')",
    "$trustedInstaller=New-Object Security.Principal.SecurityIdentifier('S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464')",
    "if ($env:MARKETINGOS_ACQUISITION_ACL_HARDEN -eq '1') {",
    "  $next=New-Object Security.AccessControl.DirectorySecurity",
    "  $next.SetOwner($current)",
    "  $next.SetAccessRuleProtection($true,$false)",
    "  $inherit=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'",
    "  $prop=[Security.AccessControl.PropagationFlags]::None",
    "  foreach($sid in @($current,$system,$admins)) { $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,[Security.AccessControl.FileSystemRights]::FullControl,$inherit,$prop,[Security.AccessControl.AccessControlType]::Allow); [void]$next.AddAccessRule($rule) }",
    "  Set-Acl -LiteralPath $target -AclObject $next",
    "}",
    "$allowed=@($current.Value,$system.Value,$admins.Value,$creator.Value,$trustedInstaller.Value)",
    "$danger=[int]([Security.AccessControl.FileSystemRights]::Delete -bor [Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership)",
    "$chain=New-Object Collections.Generic.List[string]",
    "$cursor=[IO.Path]::GetPathRoot($target)",
    "[void]$chain.Add($cursor)",
    "$remainder=$target.Substring($cursor.Length).Split([IO.Path]::DirectorySeparatorChar,[StringSplitOptions]::RemoveEmptyEntries)",
    "foreach($part in $remainder) { $cursor=Join-Path $cursor $part; [void]$chain.Add($cursor) }",
    "$unsafeCount=0",
    "$targetProtected=$false",
    "foreach($probe in $chain) {",
    "  $item=Get-Item -LiteralPath $probe -Force",
    "  if (-not $item.PSIsContainer -or (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) { throw 'unsafe directory chain' }",
    "  $acl=Get-Acl -LiteralPath $probe",
    "  $owner=(New-Object Security.Principal.NTAccount($acl.Owner)).Translate([Security.Principal.SecurityIdentifier]).Value",
    "  if ($allowed -notcontains $owner) { $unsafeCount++ }",
    "  $unsafeCount += @($acl.Access | Where-Object { $_.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and (($_.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0) } | Where-Object { $sid=$_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value; (([int]$_.FileSystemRights -band $danger) -ne 0) -and ($allowed -notcontains $sid) }).Count",
    "  if ($probe -eq $target) { $targetProtected=$acl.AreAccessRulesProtected }",
    "}",
    "[pscustomobject]@{Protected=$targetProtected;Owner=$current.Value;Current=$current.Value;Unsafe=$unsafeCount}|ConvertTo-Json -Compress",
  ].join("; ");
  const encoded = Buffer.from(script, "utf16le").toString("base64");
  const environment = Object.create(null);
  for (const key of ["SystemRoot", "WINDIR", "TEMP", "TMP", "USERPROFILE"]) {
    if (process.env[key] !== undefined) environment[key] = process.env[key];
  }
  environment.MARKETINGOS_ACQUISITION_ACL_PATH = directory;
  environment.MARKETINGOS_ACQUISITION_ACL_HARDEN = harden ? "1" : "0";
  const result = spawnSync(trustedWindowsPowerShell(), ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
    encoding: "utf8",
    env: environment,
    shell: false,
    windowsHide: true,
    timeout: 15_000,
    maxBuffer: 64 * 1024,
  });
  if (result.status !== 0) throw new Error(`${label} Windows ACL inspection failed`);
  let posture;
  try { posture = JSON.parse(String(result.stdout || "").trim()); }
  catch { throw new Error(`${label} Windows ACL inspection returned invalid output`); }
  const allowedOwners = new Set([posture.Current, "S-1-5-18", "S-1-5-32-544"]);
  if (!allowedOwners.has(posture.Owner) || posture.Unsafe !== 0 || (harden && posture.Protected !== true)) {
    throw new Error(`${label} Windows ACL permits another local principal to replace acquisition files`);
  }
}

let acquisitionWindowsPowerShell = null;
function trustedWindowsPowerShell() {
  if (acquisitionWindowsPowerShell) return acquisitionWindowsPowerShell;
  const systemRoot = path.win32.resolve("C:\\Windows");
  if (process.env.SystemRoot && normalizedPathIdentity(process.env.SystemRoot) !== normalizedPathIdentity(systemRoot))
    throw new Error("Windows system root is not the supported canonical C:\\Windows directory");
  if (process.env.WINDIR && normalizedPathIdentity(process.env.WINDIR) !== normalizedPathIdentity(systemRoot))
    throw new Error("Windows system directory environment is inconsistent");
  const executable = path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
  const parsed = path.parse(executable);
  let current = parsed.root;
  for (const component of executable.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
    current = path.join(current, component);
    if (!existsSync(current)) throw new Error("Trusted Windows PowerShell path is unavailable");
    const info = lstatSync(current, { bigint: true });
    if (info.isSymbolicLink() || normalizedPathIdentity(realpathSync.native(current)) !== normalizedPathIdentity(current))
      throw new Error("Trusted Windows PowerShell path contains a link or junction");
  }
  const info = lstatSync(executable, { bigint: true });
  if (!info.isFile() || info.isSymbolicLink() || info.nlink < 1n)
    throw new Error("Trusted Windows PowerShell is not a regular system file");
  acquisitionWindowsPowerShell = executable;
  return executable;
}

function readExactly(descriptor, bytes, position) {
  if (!Number.isSafeInteger(bytes) || bytes < 0 || !Number.isSafeInteger(position) || position < 0)
    throw new Error("Archive read bounds are invalid");
  const buffer = Buffer.allocUnsafe(bytes);
  let offset = 0;
  while (offset < bytes) {
    const count = readSync(descriptor, buffer, offset, bytes - offset, position + offset);
    if (!count) throw new Error("Archive ended before the declared structure");
    offset += count;
  }
  return buffer;
}

function readStrictJson(filePath, label, maximumBytes = MAX_JSON_BYTES) {
  const data = secureReadFile(filePath, label, maximumBytes);
  return parseStrictJsonText(data.toString("utf8"), label, maximumBytes);
}

function secureReadFile(filePath, label, maximumBytes) {
  const absolute = path.resolve(filePath);
  assertRegularUnlinkedFile(absolute, label);
  const descriptor = openSync(
    absolute,
    fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0),
  );
  try {
    const before = fstatIdentity(descriptor);
    if (before.size < 1n || before.size > BigInt(maximumBytes))
      throw new Error(`${label} size is outside its read limit`);
    const chunks = [];
    let total = 0;
    while (true) {
      const buffer = Buffer.allocUnsafe(
        Math.min(1024 * 1024, maximumBytes - total),
      );
      const count = readSync(descriptor, buffer, 0, buffer.length, null);
      if (!count) break;
      total += count;
      if (total > maximumBytes) throw new Error(`${label} exceeded its read limit`);
      chunks.push(buffer.subarray(0, count));
    }
    const after = fstatIdentity(descriptor);
    if (canonicalJson(before) !== canonicalJson(after) || BigInt(total) !== before.size)
      throw new Error(`${label} changed while it was being read`);
    assertPathMatchesIdentity(absolute, before, label);
    return Buffer.concat(chunks, total);
  } finally {
    closeSync(descriptor);
  }
}

function parseStrictJsonText(text, label, maximumBytes = MAX_JSON_BYTES) {
  if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > maximumBytes)
    throw new Error(`${label} exceeds the JSON limit`);
  return new StrictJsonParser(text, label).parse();
}

class StrictJsonParser {
  constructor(text, label) {
    this.text = text;
    this.label = label;
    this.index = 0;
    this.depth = 0;
  }

  parse() {
    this.skipWhitespace();
    const value = this.parseValue();
    this.skipWhitespace();
    if (this.index !== this.text.length) this.fail("has trailing data");
    return value;
  }

  parseValue() {
    const char = this.text[this.index];
    if (char === "{") return this.parseObject();
    if (char === "[") return this.parseArray();
    if (char === '"') return this.parseString();
    if (char === "t") return this.parseLiteral("true", true);
    if (char === "f") return this.parseLiteral("false", false);
    if (char === "n") return this.parseLiteral("null", null);
    if (char === "-" || /[0-9]/.test(char || "")) return this.parseNumber();
    this.fail("contains an invalid value");
  }

  parseObject() {
    this.enter();
    const result = Object.create(null);
    this.index += 1;
    this.skipWhitespace();
    if (this.text[this.index] === "}") {
      this.index += 1;
      this.leave();
      return result;
    }
    let count = 0;
    while (true) {
      this.skipWhitespace();
      if (this.text[this.index] !== '"') this.fail("has a non-string object key");
      const key = this.parseString();
      if (Object.hasOwn(result, key)) this.fail(`contains duplicate key ${key}`);
      this.skipWhitespace();
      if (this.text[this.index] !== ":") this.fail("is missing an object colon");
      this.index += 1;
      this.skipWhitespace();
      result[key] = this.parseValue();
      count += 1;
      if (count > 4_096) this.fail("contains too many object keys");
      this.skipWhitespace();
      const char = this.text[this.index];
      if (char === "}") {
        this.index += 1;
        this.leave();
        return result;
      }
      if (char !== ",") this.fail("is missing an object comma");
      this.index += 1;
    }
  }

  parseArray() {
    this.enter();
    const result = [];
    this.index += 1;
    this.skipWhitespace();
    if (this.text[this.index] === "]") {
      this.index += 1;
      this.leave();
      return result;
    }
    while (true) {
      this.skipWhitespace();
      result.push(this.parseValue());
      if (result.length > MAX_ARCHIVE_ENTRIES)
        this.fail("contains too many array entries");
      this.skipWhitespace();
      const char = this.text[this.index];
      if (char === "]") {
        this.index += 1;
        this.leave();
        return result;
      }
      if (char !== ",") this.fail("is missing an array comma");
      this.index += 1;
    }
  }

  parseString() {
    const start = this.index;
    this.index += 1;
    while (this.index < this.text.length) {
      const code = this.text.charCodeAt(this.index);
      if (code === 0x22) {
        this.index += 1;
        try {
          return JSON.parse(this.text.slice(start, this.index));
        } catch {
          this.fail("contains an invalid JSON string");
        }
      }
      if (code < 0x20) this.fail("contains a control character in a string");
      if (code === 0x5c) {
        this.index += 1;
        const escape = this.text[this.index];
        if (escape === "u") {
          const hex = this.text.slice(this.index + 1, this.index + 5);
          if (!/^[a-fA-F0-9]{4}$/.test(hex))
            this.fail("contains an invalid Unicode escape");
          this.index += 5;
          continue;
        }
        if (!["\"", "\\", "/", "b", "f", "n", "r", "t"].includes(escape))
          this.fail("contains an invalid string escape");
      }
      this.index += 1;
    }
    this.fail("contains an unterminated string");
  }

  parseNumber() {
    const match = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(
      this.text.slice(this.index),
    );
    if (!match) this.fail("contains an invalid number");
    this.index += match[0].length;
    const value = Number(match[0]);
    if (!Number.isFinite(value)) this.fail("contains a non-finite number");
    return value;
  }

  parseLiteral(source, value) {
    if (this.text.slice(this.index, this.index + source.length) !== source)
      this.fail("contains an invalid literal");
    this.index += source.length;
    return value;
  }

  skipWhitespace() {
    while ([" ", "\t", "\r", "\n"].includes(this.text[this.index]))
      this.index += 1;
  }

  enter() {
    this.depth += 1;
    if (this.depth > 64) this.fail("exceeds maximum nesting depth");
  }

  leave() {
    this.depth -= 1;
  }

  fail(message) {
    throw new Error(
      `${this.label} ${message} at byte ${Buffer.byteLength(this.text.slice(0, this.index), "utf8")}`,
    );
  }
}

function exactKeys(value, expected, label) {
  if (!value || typeof value !== "object" || Array.isArray(value))
    throw new Error(`${label} must be an object`);
  const actual = Object.keys(value).sort();
  const wanted = [...expected].sort();
  if (
    actual.length !== wanted.length ||
    actual.some((key, index) => key !== wanted[index])
  ) {
    throw new Error(`${label} schema is not closed`);
  }
}

function canonicalJson(value) {
  if (value === null || typeof value === "string" || typeof value === "boolean")
    return JSON.stringify(value);
  if (typeof value === "number") {
    if (!Number.isFinite(value)) throw new Error("Canonical JSON rejects non-finite numbers");
    return JSON.stringify(value);
  }
  if (typeof value === "bigint") return JSON.stringify(value.toString());
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
  if (value && typeof value === "object") {
    return `{${Object.keys(value)
      .sort()
      .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
      .join(",")}}`;
  }
  throw new Error("Canonical JSON received an unsupported value");
}

function writeAll(descriptor, buffer) {
  let offset = 0;
  while (offset < buffer.length)
    offset += writeSync(descriptor, buffer, offset, buffer.length - offset);
}

function sha256(value) {
  return createHash("sha256").update(value).digest("hex");
}

function sha256Text(value) {
  return sha256(Buffer.from(value, "utf8"));
}

function normalizedPathIdentity(value) {
  const resolved = path.resolve(value);
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
}

function samePath(left, right) {
  return normalizedPathIdentity(left) === normalizedPathIdentity(right);
}

function pathInside(parent, candidate) {
  const root = normalizedPathIdentity(parent);
  const target = normalizedPathIdentity(candidate);
  return target === root || target.startsWith(`${root}${path.sep}`);
}

function assertSafeBasename(value, label) {
  if (
    typeof value !== "string" ||
    !value ||
    path.basename(value) !== value ||
    value === "." ||
    value === ".." ||
    /[\0-\x1f\x7f]/.test(value) ||
    value.includes("/") ||
    value.includes("\\")
  ) {
    throw new Error(`${label} is unsafe`);
  }
}

function isLiteralLoopback(hostname) {
  return hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
}

function isSha256(value) {
  return /^[a-f0-9]{64}$/.test(String(value || ""));
}

function isSafeVersion(value) {
  return /^[0-9A-Za-z][0-9A-Za-z._+-]{0,127}$/.test(String(value || ""));
}

function isRuntimeVersion(value) {
  return /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/.test(
    String(value || ""),
  );
}

function isExactIso(value) {
  if (typeof value !== "string") return false;
  const timestamp = Date.parse(value);
  return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;
}

function decodeUtf8(buffer, label) {
  try {
    return new TextDecoder("utf-8", { fatal: true }).decode(buffer);
  } catch {
    throw new Error(`${label} is not valid UTF-8`);
  }
}

function toKebab(value) {
  return value.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
}

function assertVersionAtLeast(actual, required, label) {
  if (compareVersions(actual, required) < 0)
    throw new Error(`${label} ${required} or newer is required`);
}

function compareVersions(left, right) {
  const parse = (value) =>
    String(value)
      .split(".")
      .slice(0, 3)
      .map((part) => Number.parseInt(part, 10) || 0);
  const a = parse(left);
  const b = parse(right);
  for (let index = 0; index < 3; index += 1) {
    if (a[index] !== b[index]) return a[index] > b[index] ? 1 : -1;
  }
  return 0;
}

try {
  assertVersionAtLeast(process.versions.node, MINIMUM_NODE_VERSION, "Node.js");
  const result = await acquire(parseArguments(process.argv.slice(2)));
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
} catch (error) {
  process.stderr.write(
    `MarketingOS release acquisition failed: ${String(error?.message || error)}\n`,
  );
  process.exitCode = 1;
}
