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
32 changes: 16 additions & 16 deletions src/bun_core/wtf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,27 @@
//! 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}`.
//! Source of truth: `src/jsc/bindings/wtf-bindings.cpp` (`Bun__parseDateTimeString`),
//! which forwards to `v8::ParseDateTimeString` in
//! vendor/WebKit `Source/JavaScriptCore/runtime/JSDateMath-v8.{h,cpp}`, the
//! parser behind JS `Date.parse`.
Comment thread
robobun marked this conversation as resolved.
Resolved
//!
//! 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.
//! Note: the parser sets a `local` 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.
Comment thread
robobun marked this conversation as resolved.
Resolved

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;
// extern "C" double Bun__parseDateTimeString(const Latin1Character* string, size_t length)
fn Bun__parseDateTimeString(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.
/// Direct call to the parser. Returns NaN for any input `Date.parse` rejects.
/// `s` is treated as Latin-1.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[inline]
pub(crate) fn parse_es5_date_raw(s: &[u8]) -> f64 {
pub(crate) fn parse_date_raw(s: &[u8]) -> f64 {
// SAFETY: s.as_ptr() is valid for s.len() bytes.
unsafe { WTF__parseES5Date(s.as_ptr(), s.len()) }
unsafe { Bun__parseDateTimeString(s.as_ptr(), s.len()) }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand All @@ -38,13 +38,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.
/// What JS `Date.parse` returns for `buf`, without a VM. `Err` where `Date.parse` returns NaN.
/// `2000-01-01T00:00:00.000Z` → `Ok(946684800000.0)`.
pub fn parse_es5_date(buf: &[u8]) -> Result<f64, InvalidDate> {
pub fn parse_date(buf: &[u8]) -> Result<f64, InvalidDate> {
if buf.is_empty() {
return Err(InvalidDate);
}
let ms = parse_es5_date_raw(buf);
let ms = parse_date_raw(buf);
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
68 changes: 55 additions & 13 deletions src/install/npm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,8 @@ 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. 0 when the registry gives none,
/// infinity when it gives one that is not a date (see `publish_timestamp_ms_from_json`).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) publish_timestamp_ms: f64,
}

Expand Down Expand Up @@ -776,6 +777,11 @@ impl PackageVersion {
self.bundled_dependencies.is_invalid()
}

/// The registry gave a publish time that is not a date, so minimum-release-age cannot tell the age.
pub(crate) fn has_unreadable_publish_time(&self) -> bool {
self.publish_timestamp_ms.is_infinite()
}

/// 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 +939,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 +1580,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 +1666,14 @@ impl PackageManifest {
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum FindVersionError {
NotFound,
TooRecent,
AllVersionsTooRecent,
/// `unreadable_publish_time`: minimum-release-age blocked the newest candidate because the
/// registry's publish time for it is not a date, and not because the version is new.
Comment thread
robobun marked this conversation as resolved.
Resolved
TooRecent {
unreadable_publish_time: bool,
},
AllVersionsTooRecent {
unreadable_publish_time: bool,
},
}

pub enum FindVersionResult<'a> {
Expand All @@ -1682,7 +1699,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 +1832,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 +1866,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 +1920,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 +1999,22 @@ impl PackageManifest {
}
}

/// A version's entry in the packument's `time` object, as `PackageVersion::publish_timestamp_ms`.
/// Follows npm's `!time[v] || Date.parse(time[v]) <= before`: a falsy entry is no publish time
/// (0, passes minimum-release-age like a missing entry), and what is not a date never passes
/// (infinity). Stricter than npm in one place: only a string is read as a date, so `2020` or
/// `["2020-01-01"]`, which `Date.parse` stringifies into dates, do not pass.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn publish_timestamp_ms_from_json(entry: &JSON::E::JsonValue) -> f64 {
use JSON::E::JsonValue;
match entry {
JsonValue::Null | JsonValue::Boolean(false) => 0.0,
JsonValue::Number(n) if n.value() == 0.0 => 0.0,
JsonValue::String(s) if s.slice().is_empty() => 0.0,
JsonValue::String(s) => bun_core::wtf::parse_date(s.slice()).unwrap_or(f64::INFINITY),
_ => f64::INFINITY,
}
}

/// 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
9 changes: 6 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,12 @@ 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)
// `Date.parse` without a VM: the V8 date parser that JSC runs for Bun (JSC::Options::useV8DateParser).
// A date-time with no time zone reads as UTC.
Comment thread
robobun marked this conversation as resolved.
Resolved
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