~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
243 lines · 8.1 KB Raw History
//! npm source: full version history, deprecation state, and tarball metadata.
//!
//! The packument at `https://registry.npmjs.org/{name}` lists every published
//! version, including pre-releases. Scoped names are percent-encoded for the
//! path lookup while the display name reported by the payload is preserved in
//! project metadata. npm publishes only SHA-1 (`dist.shasum`) and SHA-512
//! (`dist.integrity`) digests, so the artifact SHA-256 stays unknown until the
//! resolver downloads the tarball; neither digest is ever relabeled. The
//! packument does not report tarball bytes, so `dist.unpackedSize` is carried
//! as the size fallback and the resolver records the real size after download.

use std::sync::Arc;

use anyhow::{Result, anyhow};
use async_trait::async_trait;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
use serde_json::{Map, Value};

use crate::release::http::RegistryHttp;
use crate::release::source::{
    ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, VersionInfo,
};
use crate::release::versioning::{VersionScheme, compare, normalize_version};

pub const REGISTRY_BASE: &str = "https://registry.npmjs.org";

/// npm path encoding: `@` stays literal (the registry's scoped-name
/// convention) and the `/` between scope and name becomes `%2F`.
const NPM_PATH: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~')
    .remove(b'@');

pub struct NpmSource {
    http: Arc<dyn RegistryHttp>,
}

impl NpmSource {
    pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
        Self { http }
    }

    /// Registry lookup URL; scoped names become `@scope%2Fname`.
    pub fn registry_url(name: &str) -> String {
        format!("{REGISTRY_BASE}/{}", utf8_percent_encode(name, NPM_PATH))
    }

    async fn packument(&self, project: &ProjectRef) -> Result<Value> {
        self.http.get_json(&Self::registry_url(&project.name)).await
    }
}

#[async_trait]
impl ReleaseSource for NpmSource {
    fn name(&self) -> &'static str {
        "npm"
    }

    fn capabilities(&self) -> SourceCapabilities {
        SourceCapabilities {
            versions: true,
            artifacts: true,
            statuses: true,
            project_meta: true,
        }
    }

    async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
        version_infos(&self.packument(project).await?)
    }

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        Ok(artifacts_for(&self.packument(project).await?, &version.raw))
    }

    async fn statuses(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        Ok(statuses_for(&self.packument(project).await?, &version.raw))
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        Ok(project_meta_value(
            &self.packument(project).await?,
            &project.name,
        ))
    }
}

fn version_entry<'a>(payload: &'a Value, raw: &str) -> Option<&'a Value> {
    payload.get("versions")?.as_object()?.get(raw)
}

fn version_infos(payload: &Value) -> Result<Vec<VersionInfo>> {
    let versions = payload
        .get("versions")
        .and_then(Value::as_object)
        .ok_or_else(|| anyhow!("npm packument missing versions"))?;
    let mut infos = versions
        .iter()
        .map(|(raw, entry)| {
            let reason = deprecation_message(entry);
            VersionInfo {
                raw: raw.clone(),
                version: normalize_version(raw).unwrap_or_else(|| raw.clone()),
                deprecated: reason.is_some(),
                reason: reason.unwrap_or_default(),
            }
        })
        .collect::<Vec<_>>();
    infos.sort_by(|left, right| {
        compare(VersionScheme::Semver, &right.raw, &left.raw).then_with(|| right.raw.cmp(&left.raw))
    });
    Ok(infos)
}

fn artifacts_for(payload: &Value, raw: &str) -> Vec<ArtifactInfo> {
    let Some(dist) = version_entry(payload, raw).and_then(|entry| entry.get("dist")) else {
        return Vec::new();
    };
    let Some(url) = text_field(dist, "tarball") else {
        return Vec::new();
    };
    let path = url.split(['?', '#']).next().unwrap_or(url);
    let file_name = path.rsplit('/').next().unwrap_or(path);
    let size = dist
        .get("unpackedSize")
        .and_then(Value::as_u64)
        .filter(|size| *size > 0);
    vec![ArtifactInfo {
        file_name: file_name.to_owned(),
        url: url.to_owned(),
        // npm publishes SHA-1 (`shasum`) and SHA-512 (`integrity`) only;
        // neither is ever relabeled as SHA-256.
        sha256: None,
        size,
        mime_type: Some("application/gzip".to_owned()),
    }]
}

fn statuses_for(payload: &Value, raw: &str) -> Vec<StatusInfo> {
    let Some(version) = version_entry(payload, raw) else {
        return Vec::new();
    };
    let Some(reason) = deprecation_message(version) else {
        return Vec::new();
    };
    // Registry deprecations are not security verdicts, even when the message
    // mentions a vulnerability; the kind is always `registry`.
    vec![StatusInfo {
        status: "deprecated".to_owned(),
        kind: Some("registry".to_owned()),
        reason,
    }]
}

/// `Some(reason)` when the version is deprecated. npm stores the message as a
/// string; a bare `true` is accepted as a reasonless deprecation.
fn deprecation_message(version: &Value) -> Option<String> {
    match version.get("deprecated")? {
        Value::String(reason) => (!reason.is_empty()).then(|| reason.clone()),
        value if truthy(Some(value)) => Some(String::new()),
        _ => None,
    }
}

fn project_meta_value(payload: &Value, requested: &str) -> Value {
    let mut meta = Map::new();
    insert_text(
        &mut meta,
        "name",
        Some(text_field(payload, "name").unwrap_or(requested)),
    );
    insert_text(&mut meta, "description", text_field(payload, "description"));
    insert_text(&mut meta, "homepage", text_field(payload, "homepage"));
    insert_text(&mut meta, "repository", repository_url(payload));
    insert_text(&mut meta, "license", license_text(payload));
    if let Some(channels) = channel_map(payload) {
        meta.insert("channels".to_owned(), Value::Object(channels));
    }
    Value::Object(meta)
}

fn repository_url(payload: &Value) -> Option<&str> {
    match payload.get("repository")? {
        Value::String(url) => Some(url.as_str()).filter(|url| !url.is_empty()),
        repository => text_field(repository, "url"),
    }
}

fn license_text(payload: &Value) -> Option<&str> {
    match payload.get("license")? {
        Value::String(license) => Some(license.as_str()).filter(|license| !license.is_empty()),
        license => text_field(license, "type"),
    }
}

/// `dist-tags` (`latest`, `next`, `beta`, ...) become version channels.
fn channel_map(payload: &Value) -> Option<Map<String, Value>> {
    let tags = payload.get("dist-tags")?.as_object()?;
    let channels = tags
        .iter()
        .filter_map(|(channel, version)| {
            version
                .as_str()
                .filter(|version| !version.is_empty())
                .map(|version| (channel.clone(), Value::String(version.to_owned())))
        })
        .collect::<Map<String, Value>>();
    (!channels.is_empty()).then_some(channels)
}

fn truthy(value: Option<&Value>) -> bool {
    match value {
        Some(Value::Bool(value)) => *value,
        Some(Value::String(value)) => !value.is_empty(),
        Some(Value::Number(number)) => number.as_f64().is_some_and(|value| value != 0.0),
        Some(Value::Array(values)) => !values.is_empty(),
        Some(Value::Object(values)) => !values.is_empty(),
        Some(Value::Null) | None => false,
    }
}

fn text_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
    value
        .get(key)
        .and_then(Value::as_str)
        .filter(|text| !text.is_empty())
}

fn insert_text(meta: &mut Map<String, Value>, key: &str, value: Option<&str>) {
    if let Some(value) = value.filter(|value| !value.is_empty()) {
        meta.insert(key.to_owned(), Value::String(value.to_owned()));
    }
}