Skip to content
1 change: 1 addition & 0 deletions docs/pm/cli/install.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ When the minimum age filter is active:
- The check searches up to 7 days past the age gate; if releases are still rapid beyond that, Bun ignores the stability check
- Exact version requests (like `package@1.1.1`) still respect the age gate but bypass the stability check
- Bun treats versions without a `time` field as passing the age check (the npm registry should always provide timestamps)
- Bun blocks a version whose `time` value is not a date string that `Date.parse` can read, because its age is unknown

For more advanced security scanning, including integration with services and custom filtering, see the [Security Scanner API](/pm/security-scanner-api).

Expand Down
30 changes: 6 additions & 24 deletions src/bun_core/wtf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,10 @@
//! library code in Rust. WTF is statically linked into the binary, so
//! tier-0 callers declare the C symbol directly — no `bun_jsc` crate
//! dependency is required to reference it.
//!
//! Source of truth: `src/jsc/bindings/wtf-bindings.cpp` (`WTF__parseES5Date`),
//! which forwards to `WTF::parseES5Date` in
//! vendor/WebKit `Source/WTF/wtf/DateMath.{h,cpp}`.
//!
//! Note: WTF's `parseES5Date` sets an `isLocalTime` out-param so the JS
//! `Date` constructor can later apply the VM's tz offset. The C shim discards
//! it, so local-time inputs return their naive
//! UTC value here too.

unsafe extern "C" {
// src/jsc/bindings/wtf-bindings.cpp:
// extern "C" double WTF__parseES5Date(const Latin1Character* string, size_t length)
fn WTF__parseES5Date(bytes: *const u8, length: usize) -> f64;
}

/// Direct call to `WTF::parseES5Date`. Returns NaN for any input the WTF
/// parser rejects. `s` is treated as Latin-1.
#[inline]
pub(crate) fn parse_es5_date_raw(s: &[u8]) -> f64 {
// SAFETY: s.as_ptr() is valid for s.len() bytes.
unsafe { WTF__parseES5Date(s.as_ptr(), s.len()) }
// src/jsc/bindings/wtf-bindings.cpp
fn Bun__parseDateTimeString(bytes: *const u8, length: usize) -> f64;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand All @@ -38,13 +20,13 @@ impl core::fmt::Display for InvalidDate {
}
impl core::error::Error for InvalidDate {}

/// `bun.jsc.wtf.parseES5Date` shape — `Err` on empty input or non-finite result.
/// `2000-01-01T00:00:00.000Z` → `Ok(946684800000.0)`.
pub fn parse_es5_date(buf: &[u8]) -> Result<f64, InvalidDate> {
/// JS `Date.parse(buf)` with no VM, except that a date-time with no time zone reads as UTC.
pub fn parse_date(buf: &[u8]) -> Result<f64, InvalidDate> {
if buf.is_empty() {
return Err(InvalidDate);
}
let ms = parse_es5_date_raw(buf);
// SAFETY: `buf.as_ptr()` is valid for `buf.len()` bytes.
let ms = unsafe { Bun__parseDateTimeString(buf.as_ptr(), buf.len()) };
if ms.is_finite() {
Ok(ms)
} else {
Expand Down
73 changes: 53 additions & 20 deletions src/install/PackageManager/PackageManagerEnqueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -958,36 +958,43 @@ pub fn enqueue_dependency_with_main_and_success_fn(
}
}
return Ok(());
} else if err == crate::Error::TooRecentVersion {
} else if err == crate::Error::TooRecentVersion
|| err == crate::Error::UnreadablePublishTime
{
if dependency.behavior.is_required() {
if let Some(fail) = fail_fn {
fail(this, dependency, id, err);
} else {
let age_gate_ms =
this.options.minimum_release_age_ms.unwrap_or(0.0);
let blocked_by = AgeGateBlock {
unreadable_publish_time: err
== crate::Error::UnreadablePublishTime,
age_gate_ms,
};
if version.tag == dependency::version::Tag::DistTag {
bun_ast::add_error_pretty!(
this.log_mut(),
None,
bun_ast::Loc::EMPTY,
"Package \"{}\" with tag \"{}\" not found<r> <d>(all versions blocked by minimum-release-age: {} seconds)<r>",
"Package \"{}\" with tag \"{}\" not found<r> <d>(all versions blocked by minimum-release-age: {})<r>",
bstr::BStr::new(this.lockfile.str(&name)),
bstr::BStr::new(
this.lockfile.str(&version.dist_tag().tag)
),
age_gate_ms / MS_PER_S,
blocked_by,
);
} else {
bun_ast::add_error_pretty!(
this.log_mut(),
None,
bun_ast::Loc::EMPTY,
"No version matching \"{}\" found for specifier \"{}\"<r> <d>(blocked by minimum-release-age: {} seconds)<r>",
"No version matching \"{}\" found for specifier \"{}\"<r> <d>(blocked by minimum-release-age: {})<r>",
bstr::BStr::new(this.lockfile.str(&name)),
bstr::BStr::new(
this.lockfile.str(&version.literal)
),
age_gate_ms / MS_PER_S,
blocked_by,
);
}
}
Expand Down Expand Up @@ -1200,19 +1207,21 @@ pub fn enqueue_dependency_with_main_and_success_fn(
find_result.package, min_age_ms,
)
{
Comment thread
robobun marked this conversation as resolved.
Resolved
let package_name = this.lockfile.str(&name);
let min_age_seconds = min_age_ms / MS_PER_S;
let _ = this.log_mut().add_error_fmt(
None,
bun_ast::Loc::EMPTY,
format_args!(
"Version \"{}@{}\" was published within minimum release age of {} seconds",
bstr::BStr::new(package_name),
find_result.version.fmt(this.lockfile.buffers.string_bytes.as_slice()),
min_age_seconds,
),
// Reported by the error arm above, like a fresh manifest would be.
resolve_result_ = Err(
if find_result
.package
.has_unreadable_publish_time()
{
crate::Error::UnreadablePublishTime
} else {
crate::Error::TooRecentVersion
},
);
return Ok(());
let _ = this
.network_dedupe_map
.remove(&task_id);
continue 'retry_with_new_resolve_result;
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
// reshaped for borrowck — `find_result`
Expand Down Expand Up @@ -1834,6 +1843,22 @@ pub fn enqueue_dependency_with_main_and_success_fn(
}
}

/// Why minimum-release-age blocked a version: the text after "minimum-release-age:" in the errors.
struct AgeGateBlock {
unreadable_publish_time: bool,
age_gate_ms: f64,
}

impl core::fmt::Display for AgeGateBlock {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if self.unreadable_publish_time {
f.write_str("the publish time in the registry is not a valid date")
} else {
write!(f, "{} seconds", self.age_gate_ms / MS_PER_S)
}
}
}

/// Unmet peers stay unresolved instead of failing the install; see `may_stay_unresolved`.
#[cold]
#[inline(never)]
Expand Down Expand Up @@ -2799,9 +2824,17 @@ fn get_or_put_resolved_package(
break 'blk Some(result);
}
Npm::FindVersionResult::Err(err_type) => match err_type {
Npm::FindVersionError::TooRecent
| Npm::FindVersionError::AllVersionsTooRecent => {
return Err(crate::Error::TooRecentVersion);
Npm::FindVersionError::TooRecent {
unreadable_publish_time,
}
| Npm::FindVersionError::AllVersionsTooRecent {
unreadable_publish_time,
} => {
return Err(if unreadable_publish_time {
crate::Error::UnreadablePublishTime
} else {
crate::Error::TooRecentVersion
});
}
Npm::FindVersionError::NotFound => None, // Handle below with existing logic
},
Expand Down
3 changes: 3 additions & 0 deletions src/install/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ pub enum Error {
NoMatchingVersion,
#[error("TooRecentVersion")]
TooRecentVersion,
#[error("UnreadablePublishTime")]
UnreadablePublishTime,
#[error("MissingPackageJSON")]
MissingPackageJSON,
#[error("InstallFailed")]
Expand Down Expand Up @@ -270,6 +272,7 @@ impl Error {
Self::DistTagNotFound => "DistTagNotFound",
Self::NoMatchingVersion => "NoMatchingVersion",
Self::TooRecentVersion => "TooRecentVersion",
Self::UnreadablePublishTime => "UnreadablePublishTime",
Self::MissingPackageJSON => "MissingPackageJSON",
Self::InstallFailed => "InstallFailed",
Self::HTTPError => "HTTPError",
Expand Down
70 changes: 56 additions & 14 deletions src/install/npm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,7 @@ pub struct PackageVersion {
pub(crate) has_install_script: bool,
pub(crate) _padding_tail: [u8; 2],

/// Unix timestamp when this version was published (0 if unknown)
/// Unix timestamp when this version was published, or `NO_PUBLISH_TIME` / `UNREADABLE_PUBLISH_TIME`
pub(crate) publish_timestamp_ms: f64,
}

Expand All @@ -766,7 +766,7 @@ impl Default for PackageVersion {
libc: Libc::NONE,
has_install_script: false,
_padding_tail: [0; 2],
publish_timestamp_ms: 0.0,
publish_timestamp_ms: Self::NO_PUBLISH_TIME,
}
}
}
Expand All @@ -776,6 +776,15 @@ impl PackageVersion {
self.bundled_dependencies.is_invalid()
}

/// The registry gives no publish time. The version passes minimum-release-age.
pub(crate) const NO_PUBLISH_TIME: f64 = 0.0;
/// The registry gives a publish time that is not a date. The version never passes minimum-release-age.
pub(crate) const UNREADABLE_PUBLISH_TIME: f64 = f64::INFINITY;

pub(crate) fn has_unreadable_publish_time(&self) -> bool {
self.publish_timestamp_ms == Self::UNREADABLE_PUBLISH_TIME
}

/// Used by `Package.fromNPM` to walk dependency groups by name.
pub(crate) fn dep_group(&self, field: &[u8]) -> ExternalStringMap {
match field {
Expand Down Expand Up @@ -933,8 +942,9 @@ pub mod package_manifest {
// - v0.0.5: added bundled dependencies
// - v0.0.6: changed semver major/minor/patch to each use u64 instead of u32
// - v0.0.7: added version publish times and extended manifest flag for minimum release age
// - v0.0.8: publish times are read like `Date.parse`; one that is not a date is infinity, not 0
const HEADER_BYTES: &'static str =
concat!("#!/usr/bin/env bun\n", "bun-npm-manifest-cache-v0.0.7\n");
concat!("#!/usr/bin/env bun\n", "bun-npm-manifest-cache-v0.0.8\n");

// Field order is hardcoded (descending alignment). Re-verify if the
// layout changes.
Expand Down Expand Up @@ -1573,6 +1583,10 @@ impl PackageManifest {
package_version: &PackageVersion,
minimum_release_age_ms: f64,
) -> bool {
// `--minimum-release-age=0` turns the gate off, also for a version whose age is unknown.
if minimum_release_age_ms <= 0.0 {
return false;
}
let current_timestamp_ms: f64 =
(bun_core::start_time() / bun_core::time::NS_PER_MS as i128) as f64;
package_version.publish_timestamp_ms > current_timestamp_ms - minimum_release_age_ms
Expand Down Expand Up @@ -1655,8 +1669,13 @@ impl PackageManifest {
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum FindVersionError {
NotFound,
TooRecent,
AllVersionsTooRecent,
/// `unreadable_publish_time`: the newest blocked candidate has `UNREADABLE_PUBLISH_TIME`, it is not new.
TooRecent {
unreadable_publish_time: bool,
},
AllVersionsTooRecent {
unreadable_publish_time: bool,
},
}

pub enum FindVersionResult<'a> {
Expand All @@ -1682,7 +1701,9 @@ impl<'a> FindVersionResult<'a> {
FindVersionResult::FoundWithFilter {
newest_filtered, ..
} => newest_filtered.is_some(),
FindVersionResult::Err(err) => *err == FindVersionError::AllVersionsTooRecent,
FindVersionResult::Err(err) => {
matches!(err, FindVersionError::AllVersionsTooRecent { .. })
}
// .err.too_recent is only for direct version checks which doesn't prove there was a later version that could have been chosen
_ => false,
}
Expand Down Expand Up @@ -1813,7 +1834,9 @@ impl PackageManifest {
};
}

FindVersionResult::Err(FindVersionError::AllVersionsTooRecent)
FindVersionResult::Err(FindVersionError::AllVersionsTooRecent {
unreadable_publish_time: dist_result.package.has_unreadable_publish_time(),
})
}

pub fn find_best_version_with_filter(
Expand Down Expand Up @@ -1845,7 +1868,9 @@ impl PackageManifest {
let result = self.find_by_version(left.version);
if let Some(r) = result {
if Self::is_package_version_too_recent(r.package, min_age_ms) {
return FindVersionResult::Err(FindVersionError::TooRecent);
return FindVersionResult::Err(FindVersionError::TooRecent {
unreadable_publish_time: r.package.has_unreadable_publish_time(),
});
}
return FindVersionResult::Found(r);
}
Expand Down Expand Up @@ -1897,8 +1922,12 @@ impl PackageManifest {
}
}

if newest_filtered.is_some() {
return FindVersionResult::Err(FindVersionError::AllVersionsTooRecent);
if let Some(newest) = newest_filtered {
return FindVersionResult::Err(FindVersionError::AllVersionsTooRecent {
unreadable_publish_time: self
.find_by_version(newest)
.is_some_and(|r| r.package.has_unreadable_publish_time()),
});
}

FindVersionResult::Err(FindVersionError::NotFound)
Expand Down Expand Up @@ -1972,6 +2001,20 @@ impl PackageManifest {
}
}

/// npm's `!time[v] || Date.parse(time[v]) <= before`, except that only a string is read as a date.
fn publish_timestamp_ms_from_json(time_entry: &JSON::E::JsonValue) -> f64 {
use JSON::E::JsonValue;
match time_entry {
JsonValue::Null | JsonValue::Boolean(false) => PackageVersion::NO_PUBLISH_TIME,
JsonValue::Number(n) if n.value() == 0.0 => PackageVersion::NO_PUBLISH_TIME,
JsonValue::String(s) if s.slice().is_empty() => PackageVersion::NO_PUBLISH_TIME,
JsonValue::String(s) => {
bun_core::wtf::parse_date(s.slice()).unwrap_or(PackageVersion::UNREADABLE_PUBLISH_TIME)
}
_ => PackageVersion::UNREADABLE_PUBLISH_TIME,
}
}

/// Fills `set` with the names listed in `bundle(d)Dependencies`; returns whether it was `true` (bundle everything).
fn collect_bundled_deps(
version_obj: Option<&JSON::E::ObjectJSON>,
Expand Down Expand Up @@ -2951,10 +2994,9 @@ impl PackageManifest {
// result matches the previous `ObjectJSON::get` exactly.
time_props.iter().find(|p| p.key.slice() == version_name)
};
if let Some(publish_time_str) = entry.and_then(|p| p.value.as_str()) {
if let Ok(ms) = bun_core::wtf::parse_es5_date(publish_time_str) {
package_version.publish_timestamp_ms = ms;
}
if let Some(entry) = entry {
package_version.publish_timestamp_ms =
publish_timestamp_ms_from_json(&entry.value);
}
}

Expand Down
8 changes: 5 additions & 3 deletions src/jsc/bindings/wtf-bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <wtf/dtoa.h>
#include <wtf/DateMath.h>
#include <wtf/NumberOfCores.h>
#include <JavaScriptCore/JSDateMath-v8.h>
#include <atomic>
#include <cassert>

Expand Down Expand Up @@ -237,10 +238,11 @@ extern "C" size_t WTF__base64URLEncode(const char* __restrict inputDataBuffer, s
return simdutf::binary_to_base64(inputDataBuffer, inputDataBufferSize, destinationDataBuffer, simdutf::base64_url);
}

extern "C" double WTF__parseES5Date(const Latin1Character* string, size_t length)
// JS `Date.parse` with no VM, except that a date-time with no time zone reads as UTC.
extern "C" double Bun__parseDateTimeString(const Latin1Character* string, size_t length)
{
bool isLocalTime;
return WTF::parseES5Date({ string, length }, isLocalTime);
bool isLocalTime = false;
return v8::TimeClip(v8::ParseDateTimeString(string, length, isLocalTime));
Comment thread
robobun marked this conversation as resolved.
Resolved
}

namespace Bun {
Expand Down
Loading
Loading