"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var provenance_exports = {};
__export(provenance_exports, {
  fetchPackageProvenance: () => fetchPackageProvenance,
  findProvenance: () => findProvenance,
  getAttestations: () => getAttestations,
  getFetcher: () => getFetcher,
  getProvenanceDetails: () => getProvenanceDetails,
  isTrustedPublisher: () => isTrustedPublisher
});
module.exports = __toCommonJS(provenance_exports);
var import_agents = require("../constants/agents");
var import_packages = require("../constants/packages");
var import_make_fetch_happen = __toESM(require("../external/make-fetch-happen"));
var import_signal = require("../abort/signal");
var import_parse = require("../url/parse");
var import_array = require("../primordials/array");
var import_buffer = require("../primordials/buffer");
var import_json = require("../primordials/json");
var import_string = require("../primordials/string");
const SLSA_PROVENANCE_V0_2 = "https://slsa.dev/provenance/v0.2";
const SLSA_PROVENANCE_V1_0 = "https://slsa.dev/provenance/v1";
let _fetcher;
// @__NO_SIDE_EFFECTS__
async function fetchPackageProvenance(pkgName, pkgVersion, options) {
  const { signal, timeout = 1e4 } = {
    __proto__: null,
    ...options
  };
  if (signal?.aborted) {
    return void 0;
  }
  const timeoutSignal = (0, import_signal.createTimeoutSignal)(timeout);
  const compositeSignal = (0, import_signal.createCompositeAbortSignal)(signal, timeoutSignal);
  const fetcher = /* @__PURE__ */ getFetcher();
  try {
    const response = await fetcher(
      // The npm registry attestations API endpoint.
      `${import_agents.NPM_REGISTRY_URL}/-/npm/v1/attestations/${encodeURIComponent(pkgName)}@${encodeURIComponent(pkgVersion)}`,
      {
        method: "GET",
        signal: compositeSignal,
        headers: {
          "User-Agent": "socket-registry"
        }
      }
    );
    if (response.ok) {
      return getProvenanceDetails(await response.json());
    }
  } catch {
  }
  return void 0;
}
function findProvenance(attestations) {
  for (const attestation of attestations) {
    const att = attestation;
    try {
      let predicate = att.predicate;
      if (!predicate && att.bundle?.dsseEnvelope?.payload) {
        try {
          const decodedPayload = (0, import_buffer.BufferFrom)(
            att.bundle.dsseEnvelope.payload,
            "base64"
          ).toString("utf8");
          const statement = (0, import_json.JSONParse)(decodedPayload);
          predicate = statement.predicate;
        } catch {
          continue;
        }
      }
      const predicateData = predicate;
      if (predicateData?.buildDefinition?.externalParameters) {
        return {
          predicate,
          externalParameters: predicateData.buildDefinition.externalParameters
        };
      }
    } catch {
    }
  }
  return void 0;
}
function getAttestations(attestationData) {
  const data = attestationData;
  if (!data.attestations || !(0, import_array.ArrayIsArray)(data.attestations)) {
    return [];
  }
  return data.attestations.filter((attestation) => {
    const att = attestation;
    return att.predicateType === SLSA_PROVENANCE_V0_2 || att.predicateType === SLSA_PROVENANCE_V1_0;
  });
}
// @__NO_SIDE_EFFECTS__
function getFetcher() {
  if (_fetcher === void 0) {
    _fetcher = import_make_fetch_happen.default.defaults({
      cachePath: (0, import_packages.getPacoteCachePath)(),
      // Prefer-offline: Staleness checks for cached data will be bypassed, but
      // missing data will be requested from the server.
      // https://github.com/npm/make-fetch-happen?tab=readme-ov-file#--optscache
      cache: "force-cache"
    });
  }
  return _fetcher;
}
function getProvenanceDetails(attestationData) {
  const attestations = getAttestations(attestationData);
  if (!attestations.length) {
    return void 0;
  }
  const provenance = findProvenance(attestations);
  if (!provenance) {
    return { level: "attested" };
  }
  const provenanceData = provenance;
  const { externalParameters, predicate } = provenanceData;
  const def = predicate?.buildDefinition;
  const workflow = externalParameters?.workflow;
  const workflowRef = workflow?.ref || externalParameters?.workflow_ref;
  const workflowUrl = externalParameters?.context;
  const workflowPlatform = def?.buildType;
  const repository = workflow?.repository || externalParameters?.repository;
  const gitRef = externalParameters?.ref || workflow?.ref;
  const commitSha = externalParameters?.sha;
  const workflowRunId = externalParameters?.run_id;
  const trusted = isTrustedPublisher(workflowRef) || isTrustedPublisher(workflowUrl) || isTrustedPublisher(workflowPlatform) || isTrustedPublisher(repository);
  return {
    commitSha,
    gitRef,
    level: trusted ? "trusted" : "attested",
    repository,
    workflowRef,
    workflowUrl,
    workflowPlatform,
    workflowRunId
  };
}
function isTrustedPublisher(value) {
  if (typeof value !== "string" || !value) {
    return false;
  }
  let url = (0, import_parse.parseUrl)(value);
  let hostname = url?.hostname;
  if (!url && (0, import_string.StringPrototypeIncludes)(value, "@")) {
    const firstPart = (0, import_string.StringPrototypeSplit)(value, "@")[0];
    if (firstPart) {
      url = (0, import_parse.parseUrl)(firstPart);
    }
    if (url) {
      hostname = url.hostname;
    }
  }
  if (!url) {
    const httpsUrl = (0, import_parse.parseUrl)(`https://${value}`);
    if (httpsUrl) {
      hostname = httpsUrl.hostname;
    }
  }
  if (hostname) {
    return hostname === "github.com" || (0, import_string.StringPrototypeEndsWith)(hostname, ".github.com") || hostname === "gitlab.com" || (0, import_string.StringPrototypeEndsWith)(hostname, ".gitlab.com");
  }
  return (0, import_string.StringPrototypeIncludes)(value, "github") || (0, import_string.StringPrototypeIncludes)(value, "gitlab");
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  fetchPackageProvenance,
  findProvenance,
  getAttestations,
  getFetcher,
  getProvenanceDetails,
  isTrustedPublisher
});
