"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../_virtual/_rolldown/runtime.js');
const require_primordials_buffer = require('../primordials/buffer.js');
const require_primordials_string = require('../primordials/string.js');
const require_abort_signal = require('../abort/signal.js');
const require_primordials_array = require('../primordials/array.js');
const require_primordials_object = require('../primordials/object.js');
const require_primordials_json = require('../primordials/json.js');
const require_objects_predicates = require('../objects/predicates.js');
const require_constants_agents = require('../constants/agents.js');
const require_constants_packages = require('../constants/packages.js');
const require_url_parse = require('../url/parse.js');
let src_external_make_fetch_happen = require("../external/make-fetch-happen");
src_external_make_fetch_happen = require_runtime.__toESM(src_external_make_fetch_happen);

//#region src/packages/provenance.ts
/**
* @file Package provenance and attestation verification utilities.
*/
const SLSA_PROVENANCE_V0_2 = "https://slsa.dev/provenance/v0.2";
const SLSA_PROVENANCE_V1_0 = "https://slsa.dev/provenance/v1";
let _fetcher;
/**
* Comparator ordering two trust statuses by ascending trust level. Sorts an
* array of statuses lowest-trust-first; negate for highest-first.
*/
function compareTrust(a, b) {
	const levelA = getTrustLevel(a);
	const levelB = getTrustLevel(b);
	if (levelA < levelB) return -1;
	if (levelA > levelB) return 1;
	return 0;
}
/**
* Whether `next` sits at a lower trust level than `prev` — i.e. a release
* regressed its supply-chain posture. Drives the post-publish provenance
* reminder: a version that drops from trustedPublisher back to bare provenance
* is a red flag worth surfacing.
*/
function didTrustDecrease(prev, next) {
	return getTrustLevel(next) < getTrustLevel(prev);
}
/**
* Fetch package provenance information from npm registry.
*
* @example
*   ;```typescript
*   const provenance = await fetchPackageProvenance('lodash', '4.17.21')
*   ```
*/
/*@__NO_SIDE_EFFECTS__*/
async function fetchPackageProvenance(pkgName, pkgVersion, options) {
	const { signal, timeout = 1e4 } = {
		__proto__: null,
		...options
	};
	if (signal?.aborted) return;
	const compositeSignal = require_abort_signal.createCompositeAbortSignal(signal, require_abort_signal.createTimeoutSignal(timeout));
	const fetcher = /* @__PURE__ */ getFetcher();
	try {
		const response = await fetcher(`${require_constants_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 {}
}
/**
* Find the first attestation with valid provenance data.
*/
function findProvenance(attestations) {
	for (const attestation of attestations) {
		const att = attestation;
		try {
			let predicate = att.predicate;
			if (!predicate && att.bundle?.dsseEnvelope?.payload) try {
				predicate = require_primordials_json.JSONParse(require_primordials_buffer.BufferFrom(att.bundle.dsseEnvelope.payload, "base64").toString("utf8")).predicate;
			} catch {
				continue;
			}
			const predicateData = predicate;
			if (predicateData?.buildDefinition?.externalParameters) return {
				predicate,
				externalParameters: predicateData.buildDefinition.externalParameters
			};
		} catch {}
	}
}
/**
* Extract and filter SLSA provenance attestations from attestation data.
*/
function getAttestations(attestationData) {
	const data = attestationData;
	if (!data.attestations || !require_primordials_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 = src_external_make_fetch_happen.default.defaults({
		cachePath: /* @__PURE__ */ require_constants_packages.getPacoteCachePath(),
		cache: "force-cache"
	});
	return _fetcher;
}
/**
* Convert raw attestation data to user-friendly provenance details.
*
* @example
*   ;```typescript
*   const details = getProvenanceDetails(attestationData)
*   // { level: 'trusted', repository: '...', commitSha: '...' }
*   ```
*/
function getProvenanceDetails(attestationData) {
	const attestations = getAttestations(attestationData);
	if (!attestations.length) return;
	const provenance = findProvenance(attestations);
	if (!provenance) return { level: "attested" };
	const { externalParameters, predicate } = provenance;
	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;
	return {
		commitSha,
		gitRef,
		level: isTrustedPublisher(workflowRef) || isTrustedPublisher(workflowUrl) || isTrustedPublisher(workflowPlatform) || isTrustedPublisher(repository) ? "trusted" : "attested",
		repository,
		workflowRef,
		workflowUrl,
		workflowPlatform,
		workflowRunId
	};
}
/**
* Map a trust status to its 0..3 ladder level.
*/
function getTrustLevel(status) {
	if (status.stagedPublish) return 3;
	if (status.trustedPublisher && status.provenance) return 2;
	if (status.provenance) return 1;
	return 0;
}
/**
* Map a trust status to its human-readable level name.
*/
function getTrustLevelName(status) {
	return TRUST_LEVELS[getTrustLevel(status)];
}
/**
* Extract provenance / trusted-publisher / staged-publish flags from a registry
* version document.
*
* Staged-publish detection follows pnpm/pnpm#12056: `_npmUser.approver` is set
* by the registry when a package version was promoted out of staging via a
* 2FA-gated approve step. That signal ranks ABOVE both `trustedPublisher` and
* `provenance` in pnpm's trust-evidence ladder, because it adds a human
* approval gate on top of the OIDC publisher identity.
*/
function getTrustStatus(meta) {
	const status = {
		provenance: false,
		trustedPublisher: false,
		stagedPublish: false
	};
	if (!/* @__PURE__ */ require_objects_predicates.isObject(meta)) return status;
	const npmUser = require_primordials_object.ObjectHasOwn(meta, "_npmUser") ? meta["_npmUser"] : void 0;
	if (/* @__PURE__ */ require_objects_predicates.isObject(npmUser)) {
		if (require_primordials_object.ObjectHasOwn(npmUser, "approver") && npmUser["approver"]) status.stagedPublish = true;
		if (require_primordials_object.ObjectHasOwn(npmUser, "trustedPublisher") && npmUser["trustedPublisher"]) status.trustedPublisher = true;
	}
	const dist = require_primordials_object.ObjectHasOwn(meta, "dist") ? meta["dist"] : void 0;
	const attestations = /* @__PURE__ */ require_objects_predicates.isObject(dist) && require_primordials_object.ObjectHasOwn(dist, "attestations") ? dist["attestations"] : void 0;
	if (/* @__PURE__ */ require_objects_predicates.isObject(attestations) && require_primordials_object.ObjectHasOwn(attestations, "provenance") && attestations["provenance"]) status.provenance = true;
	return status;
}
/**
* Check if a value indicates a trusted publisher (GitHub or GitLab).
*/
function isTrustedPublisher(value) {
	if (typeof value !== "string" || !value) return false;
	let url = /* @__PURE__ */ require_url_parse.parseUrl(value);
	let hostname = url?.hostname;
	if (!url && require_primordials_string.StringPrototypeIncludes(value, "@")) {
		const firstPart = require_primordials_string.StringPrototypeSplit(value, "@")[0];
		if (firstPart) url = /* @__PURE__ */ require_url_parse.parseUrl(firstPart);
		if (url) hostname = url.hostname;
	}
	if (!url) {
		const httpsUrl = /* @__PURE__ */ require_url_parse.parseUrl(`https://${value}`);
		if (httpsUrl) hostname = httpsUrl.hostname;
	}
	if (hostname) return hostname === "github.com" || require_primordials_string.StringPrototypeEndsWith(hostname, ".github.com") || hostname === "gitlab.com" || require_primordials_string.StringPrototypeEndsWith(hostname, ".gitlab.com");
	return require_primordials_string.StringPrototypeIncludes(value, "github") || require_primordials_string.StringPrototypeIncludes(value, "gitlab");
}
/**
* Trust ladder, low → high. The index IS the level (0..3), so a single array
* maps both directions: `TRUST_LEVELS[level]` → name, and
* `TRUST_LEVELS.indexOf(name)` → level. One source of truth, no parallel Record
* to keep in sync.
*/
const TRUST_LEVELS = [
	"none",
	"provenance",
	"trustedPublisher",
	"stagedPublish"
];

//#endregion
exports.TRUST_LEVELS = TRUST_LEVELS;
exports.compareTrust = compareTrust;
exports.didTrustDecrease = didTrustDecrease;
exports.fetchPackageProvenance = fetchPackageProvenance;
exports.findProvenance = findProvenance;
exports.getAttestations = getAttestations;
exports.getFetcher = getFetcher;
exports.getProvenanceDetails = getProvenanceDetails;
exports.getTrustLevel = getTrustLevel;
exports.getTrustLevelName = getTrustLevelName;
exports.getTrustStatus = getTrustStatus;
exports.isTrustedPublisher = isTrustedPublisher;