diff --git a/docs/pm/cli/install.mdx b/docs/pm/cli/install.mdx index 8a6f330d0fe1..76248d868d23 100644 --- a/docs/pm/cli/install.mdx +++ b/docs/pm/cli/install.mdx @@ -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). diff --git a/src/bun_core/wtf.rs b/src/bun_core/wtf.rs index 506fc908632b..441bc1a76c4a 100644 --- a/src/bun_core/wtf.rs +++ b/src/bun_core/wtf.rs @@ -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)] @@ -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 { +/// 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 { 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 { diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index ea9ec05aa566..d9e4c6193932 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.rs +++ b/src/install/PackageManager/PackageManagerEnqueue.rs @@ -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 (all versions blocked by minimum-release-age: {} seconds)", + "Package \"{}\" with tag \"{}\" not found (all versions blocked by minimum-release-age: {})", 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 \"{}\" (blocked by minimum-release-age: {} seconds)", + "No version matching \"{}\" found for specifier \"{}\" (blocked by minimum-release-age: {})", bstr::BStr::new(this.lockfile.str(&name)), bstr::BStr::new( this.lockfile.str(&version.literal) ), - age_gate_ms / MS_PER_S, + blocked_by, ); } } @@ -1175,8 +1182,10 @@ pub fn enqueue_dependency_with_main_and_success_fn( if version.tag == dependency::version::Tag::Npm && version.npm().version.is_exact() { - if let Some(find_result) = - loaded_manifest.as_ref().unwrap().find_by_version( + if let Some(find_result) = loaded_manifest + .as_ref() + .unwrap() + .find_by_version( version .npm() .version @@ -1186,6 +1195,17 @@ pub fn enqueue_dependency_with_main_and_success_fn( .left .version, ) + // A cached "not a date" cannot become a date: fetch an expired manifest again. + .filter(|found| { + !(expired + && this + .options + .minimum_release_age_ms + .is_some_and(|age| age > 0.0) + && found + .package + .has_unreadable_publish_time()) + }) { if let Some(min_age_ms) = this.options.minimum_release_age_ms @@ -1200,19 +1220,21 @@ pub fn enqueue_dependency_with_main_and_success_fn( find_result.package, min_age_ms, ) { - 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; } } // reshaped for borrowck — `find_result` @@ -1834,6 +1856,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)] @@ -2799,9 +2837,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 }, diff --git a/src/install/error.rs b/src/install/error.rs index 1b2e2e464587..afd4f5217889 100644 --- a/src/install/error.rs +++ b/src/install/error.rs @@ -58,6 +58,8 @@ pub enum Error { NoMatchingVersion, #[error("TooRecentVersion")] TooRecentVersion, + #[error("UnreadablePublishTime")] + UnreadablePublishTime, #[error("MissingPackageJSON")] MissingPackageJSON, #[error("InstallFailed")] @@ -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", diff --git a/src/install/npm.rs b/src/install/npm.rs index e9fb7d848ec4..66609a3957a3 100644 --- a/src/install/npm.rs +++ b/src/install/npm.rs @@ -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, } @@ -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, } } } @@ -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 { @@ -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. @@ -1573,11 +1583,26 @@ 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 } + /// The stability check measures the next candidate against this. An unreadable time replaces no readable one. + fn newer_blocked<'a>( + prev: Option<&'a PackageVersion>, + blocked: &'a PackageVersion, + ) -> Option<&'a PackageVersion> { + match prev { + Some(prev) if blocked.has_unreadable_publish_time() => Some(prev), + _ => Some(blocked), + } + } + fn search_version_list<'a>( &'a self, versions: &'a [Semver::Version], @@ -1605,7 +1630,8 @@ impl PackageManifest { if newest_filtered.is_none() { *newest_filtered = Some(version); } - prev_package_blocked_from_age = Some(package); + prev_package_blocked_from_age = + Self::newer_blocked(prev_package_blocked_from_age, package); } // stability check - if the previous package is blocked from age, we need to check if the current package wasn't the cause else if let Some(prev_package) = prev_package_blocked_from_age { @@ -1655,8 +1681,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> { @@ -1682,7 +1713,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, } @@ -1770,7 +1803,8 @@ impl PackageManifest { } if Self::is_package_version_too_recent(package, min_age_ms) { - prev_package_blocked_from_age = Some(package); + prev_package_blocked_from_age = + Self::newer_blocked(prev_package_blocked_from_age, package); continue; } @@ -1813,7 +1847,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( @@ -1845,7 +1881,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); } @@ -1897,8 +1935,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) @@ -1972,6 +2014,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>, @@ -2951,10 +3007,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); } } diff --git a/src/jsc/bindings/wtf-bindings.cpp b/src/jsc/bindings/wtf-bindings.cpp index 4c6344fe0050..4d6b42454708 100644 --- a/src/jsc/bindings/wtf-bindings.cpp +++ b/src/jsc/bindings/wtf-bindings.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -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)); } namespace Bun { diff --git a/test/cli/install/minimum-release-age.test.ts b/test/cli/install/minimum-release-age.test.ts index 1f7a0f934640..07e40ff3ea9e 100644 --- a/test/cli/install/minimum-release-age.test.ts +++ b/test/cli/install/minimum-release-age.test.ts @@ -1,6 +1,8 @@ import type { Server } from "bun"; import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { bunEnv, bunExe, normalizeBunSnapshot, tempDir } from "harness"; +import { readdirSync } from "fs"; +import { bunEnv, bunExe, isDebug, normalizeBunSnapshot, tempDir } from "harness"; +import { join } from "path"; // These tests drive real `bun install` runs against a mock registry, which is // slow under the debug/ASAN build — give them the same generous timeout the @@ -23,6 +25,62 @@ describe("minimum-release-age", () => { // Helper to create ISO timestamp for a given number of days ago const daysAgo = (days: number) => new Date(currentTime - days * DAY_MS).toISOString(); + // `time` entries that are not an ISO 8601 string, keyed by the name of the mock package that + // serves them for its newest version. bun follows npm's `!time[v] || Date.parse(time[v]) <= before`, + // but reads only a string as a date. + // + // Not a date: the age is unknown, so the version never passes the gate. + const unreadablePublishTimes: Record = { + "odd-time-text": "yesterday", + "odd-time-epoch-ms": currentTime, + "odd-time-boolean": true, + "odd-time-object": {}, + // npm passes these two, because `Date.parse` stringifies them into dates. bun does not. + "odd-time-year-number": 2020, + "odd-time-array": [daysAgo(30)], + }; + // "YYYY-MM-DD HH:mm:ss +00:00". JavaScriptCore's own date parsers reject it. The V8 parser behind `Date.parse` reads it. + const spaceAndOffset = (ms: number) => new Date(ms).toISOString().slice(0, 19).replace("T", " ") + " +00:00"; + // Dates that `Date.parse` reads, for a version published just now: too recent. + const recentLegacyPublishTimes: Record = { + "odd-time-rfc2822": new Date(currentTime).toUTCString(), + "odd-time-date-to-string": new Date(currentTime).toString(), + "odd-time-space-and-offset": spaceAndOffset(currentTime), + }; + // The same forms for a version published 30 days ago: old enough. + const oldLegacyPublishTimes: Record = { + "odd-time-old-rfc2822": new Date(currentTime - 30 * DAY_MS).toUTCString(), + "odd-time-old-date-to-string": new Date(currentTime - 30 * DAY_MS).toString(), + "odd-time-old-space-and-offset": spaceAndOffset(currentTime - 30 * DAY_MS), + }; + // No time zone, for a version published 4 days 23 hours ago. bun reads the value as UTC on every + // machine. `Date.parse` reads it in the zone of the host. + const almostFiveDaysAgo = new Date(currentTime - 5 * DAY_MS + 60 * 60 * MS_PER_SECOND); + const zonelessPublishTimes: Record = { + "odd-time-zoneless-rfc2822": almostFiveDaysAgo.toUTCString().replace(" GMT", ""), + "odd-time-zoneless-iso": almostFiveDaysAgo.toISOString().slice(0, 19), + }; + // Falsy: no publish time on record. Passes like a missing entry. + const unsetPublishTimes: Record = { + "odd-time-null": null, + "odd-time-empty-string": "", + "odd-time-zero": 0, + "odd-time-false": false, + }; + const oddPublishTimes: Record = { + ...unreadablePublishTimes, + ...recentLegacyPublishTimes, + ...oldLegacyPublishTimes, + ...zonelessPublishTimes, + ...unsetPublishTimes, + // Only the expired cached manifest tests ask for these, so they can count and change what the registry serves. + "odd-time-cached-unreadable": "yesterday", + "odd-time-cached-recent": new Date(currentTime).toISOString(), + "odd-time-cached-then-fixed": "yesterday", + "odd-time-cached-gate-off": "yesterday", + }; + const oddTimeManifestRequests = new Map(); + // Helper to create a minimal valid tarball const createTarball = (name: string, version: string) => { const packageJson = JSON.stringify({ @@ -706,6 +764,58 @@ describe("minimum-release-age", () => { return Response.json(packageData); } + // TEST PACKAGES: odd-time-* (1.0.0 is 30 days old, the `time` entry of the newest + // version is not an ISO 8601 date string) + const oddTimeName = url.pathname.slice(1); + if (oddTimeName in oddPublishTimes) { + oddTimeManifestRequests.set(oddTimeName, (oddTimeManifestRequests.get(oddTimeName) ?? 0) + 1); + return Response.json({ + name: oddTimeName, + "dist-tags": { latest: "2.0.0" }, + versions: Object.fromEntries( + ["1.0.0", "2.0.0"].map(version => [ + version, + { + name: oddTimeName, + version, + dist: { + tarball: `${mockRegistryUrl}/${oddTimeName}/-/${oddTimeName}-${version}.tgz`, + integrity: "sha512-fake==", + }, + }, + ]), + ), + time: { "1.0.0": daysAgo(30), "2.0.0": oddPublishTimes[oddTimeName] }, + }); + } + + // TEST PACKAGE: unreadable-between-rapid-releases. 1.3.0 is too recent, 1.2.0 has no readable time, + // and 1.1.0 came out 4 days before 1.3.0, inside the 5 day stability window. + if (url.pathname === "/unreadable-between-rapid-releases") { + const name = "unreadable-between-rapid-releases"; + const time: Record = { + "1.0.0": daysAgo(11.5), + "1.1.0": daysAgo(6), + "1.2.0": "yesterday", + "1.3.0": daysAgo(2), + }; + return Response.json({ + name, + "dist-tags": { latest: "1.3.0" }, + versions: Object.fromEntries( + Object.keys(time).map(version => [ + version, + { + name, + version, + dist: { tarball: `${mockRegistryUrl}/${name}/-/${name}-${version}.tgz`, integrity: "sha512-fake==" }, + }, + ]), + ), + time, + }); + } + // TEST PACKAGE 11: exact-threshold-package (exactly at age boundary) if (url.pathname === "/exact-threshold-package") { const packageData = { @@ -2211,29 +2321,259 @@ describe("minimum-release-age", () => { expect(lockfile).toContain("no-time-package@1.0.0"); }); - test("handles invalid timestamp formats", async () => { - using dir = tempDir("bad-timestamp", { - "package.json": JSON.stringify({ - dependencies: { "bad-timestamp-package": "*" }, - }), - ".npmrc": `registry=${mockRegistryUrl}`, + // Installs `dependencies` from the mock registry and returns what the tests below assert on. + // These tests run concurrently, so every install has its own cache unless `cacheDir` is set. + async function install( + dependencies: Record, + args: string[], + bunfig: object = {}, + { cacheDir, env = {} }: { cacheDir?: string; env?: Record } = {}, + ) { + using dir = tempDir("odd-publish-time", { + "package.json": JSON.stringify({ dependencies }), + "bunfig.toml": Bun.TOML.stringify({ install: { registry: mockRegistryUrl, ...bunfig } }), }); - const proc = Bun.spawn({ - cmd: [bunExe(), "install", "--minimum-release-age", `${5 * SECONDS_PER_DAY}`, "--no-verify"], + await using proc = Bun.spawn({ + cmd: [bunExe(), "install", "--no-verify", ...args], cwd: String(dir), - env: bunEnv, - stdout: "pipe", + env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: cacheDir ?? join(String(dir), ".bun-cache"), ...env }, + stdout: "ignore", stderr: "pipe", }); + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); - const exitCode = await proc.exited; + const lockfile = Bun.file(`${dir}/bun.lock`); + return { stderr, exitCode, lockfile: (await lockfile.exists()) ? await lockfile.text() : "" }; + } + const fiveDayGate = ["--minimum-release-age", `${5 * SECONDS_PER_DAY}`]; + + // The version could be minutes old: it must not pass the gate. npm never picks it either. + test.concurrent.each(Object.keys({ ...unreadablePublishTimes, ...recentLegacyPublishTimes }))( + "%s: a range skips a version whose publish time is unreadable or recent", + async name => { + const { stderr, exitCode, lockfile } = await install({ [name]: "*" }, fiveDayGate); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain(`${name}@1.0.0`); + expect(lockfile).not.toContain(`${name}@2.0.0`); + expect(exitCode).toBe(0); + }, + ); + + test.concurrent.each(Object.keys(oldLegacyPublishTimes))( + "%s: an old publish time in a legacy date format passes", + async name => { + const { stderr, exitCode, lockfile } = await install({ [name]: "2.0.0" }, fiveDayGate); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain(`${name}@2.0.0`); + expect(exitCode).toBe(0); + }, + ); + + // The host is in UTC+14. Read as local time, 2.0.0 would be 5 days 13 hours old and pass the gate. + test.concurrent.each(Object.keys(zonelessPublishTimes))( + "%s: a publish time with no time zone reads as UTC, not in the zone of the host", + async name => { + const { stderr, exitCode, lockfile } = await install( + { [name]: "*" }, + fiveDayGate, + {}, + { env: { TZ: "Etc/GMT-14" } }, + ); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain(`${name}@1.0.0`); + expect(lockfile).not.toContain(`${name}@2.0.0`); + expect(exitCode).toBe(0); + }, + ); + + test.concurrent.each(Object.keys(unsetPublishTimes))( + "%s: a falsy publish time passes like a missing entry", + async name => { + const { stderr, exitCode, lockfile } = await install({ [name]: "*" }, fiveDayGate); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain(`${name}@2.0.0`); + expect(exitCode).toBe(0); + }, + ); - // Should succeed - invalid timestamps should be skipped gracefully + test.concurrent("the latest dist-tag skips a version with an unreadable publish time", async () => { + const { stderr, exitCode, lockfile } = await install({ "odd-time-text": "latest" }, fiveDayGate); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain("odd-time-text@1.0.0"); expect(exitCode).toBe(0); + }); - const lockfile = await Bun.file(`${dir}/bun.lock`).text(); - expect(lockfile).toContain("bad-timestamp-package@1.0.0"); + // The errors say why a version from years ago is blocked. + test.concurrent("an exact version with an unreadable publish time is blocked", async () => { + const { stderr, exitCode, lockfile } = await install({ "odd-time-text": "2.0.0" }, fiveDayGate); + + expect(stderr).toContain( + 'error: No version matching "odd-time-text" found for specifier "2.0.0" (blocked by minimum-release-age: the publish time in the registry is not a valid date)', + ); + expect(lockfile).not.toContain("odd-time-text@2.0.0"); + expect(exitCode).toBe(1); + }); + + test.concurrent("a range with only unreadable publish times is blocked", async () => { + const { stderr, exitCode, lockfile } = await install({ "bad-timestamp-package": "*" }, fiveDayGate); + + expect(stderr).toContain( + 'error: No version matching "bad-timestamp-package" found for specifier "*" (blocked by minimum-release-age: the publish time in the registry is not a valid date)', + ); + expect(lockfile).not.toContain("bad-timestamp-package@1.0.0"); + expect(exitCode).toBe(1); + }); + + test.concurrent("a dist-tag with only unreadable publish times is blocked", async () => { + const { stderr, exitCode, lockfile } = await install({ "bad-timestamp-package": "latest" }, fiveDayGate); + + expect(stderr).toContain( + 'error: Package "bad-timestamp-package" with tag "latest" not found (all versions blocked by minimum-release-age: the publish time in the registry is not a valid date)', + ); + expect(lockfile).not.toContain("bad-timestamp-package@1.0.0"); + expect(exitCode).toBe(1); + }); + + // An exact version resolves from a manifest that is on disk but expired. Only a debug build reads + // BUN_CONFIG_MANIFEST_CACHE_CONTROL_TIMESTAMP, which makes the cached manifest count as expired. + const expiredCache = { BUN_CONFIG_MANIFEST_CACHE_CONTROL_TIMESTAMP: "4294967295" }; + async function cacheManifest(name: string, cacheDir: string) { + // bun saves the manifest from a thread pool task and does not wait for it at exit. + let cached = false; + for (let attempt = 0; attempt < 5 && !cached; attempt++) { + await install({ [name]: "1.0.0" }, fiveDayGate, {}, { cacheDir }); + cached = readdirSync(cacheDir).some(file => file.endsWith(".npm")); + } + if (!cached) throw new Error(`5 installs of ${name}@1.0.0 left no .npm manifest in ${cacheDir}`); + } + + // A too-recent version ages, so the cached manifest is enough. A time that is not a date cannot + // change in the cache, so bun asks the registry again. + test.skipIf(!isDebug).concurrent.each([ + ["odd-time-cached-recent", `${5 * SECONDS_PER_DAY} seconds`, 0], + ["odd-time-cached-unreadable", "the publish time in the registry is not a valid date", 1], + ])( + "%s: an exact version from an expired cached manifest is blocked with the same error", + async (name, reason, manifestRequests) => { + using cache = tempDir("odd-publish-time-cache", {}); + await cacheManifest(name, String(cache)); + const requests = oddTimeManifestRequests.get(name)!; + + const { stderr, exitCode } = await install( + { [name]: "2.0.0" }, + fiveDayGate, + {}, + { + cacheDir: String(cache), + env: expiredCache, + }, + ); + + expect(stderr).toContain( + `error: No version matching "${name}" found for specifier "2.0.0" (blocked by minimum-release-age: ${reason})`, + ); + expect(oddTimeManifestRequests.get(name)).toBe(requests + manifestRequests); + expect(exitCode).toBe(1); + }, + ); + + test + .skipIf(!isDebug) + .concurrent("an exact version installs after the registry corrects its publish time", async () => { + const name = "odd-time-cached-then-fixed"; + using cache = tempDir("odd-publish-time-cache", {}); + await cacheManifest(name, String(cache)); + oddPublishTimes[name] = daysAgo(30); + + const { stderr, exitCode, lockfile } = await install( + { [name]: "2.0.0" }, + fiveDayGate, + {}, + { + cacheDir: String(cache), + env: expiredCache, + }, + ); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain(`${name}@2.0.0`); + expect(exitCode).toBe(0); + }); + + test + .skipIf(!isDebug) + .concurrent("--minimum-release-age 0 resolves the exact version from the expired cached manifest", async () => { + const name = "odd-time-cached-gate-off"; + using cache = tempDir("odd-publish-time-cache", {}); + await cacheManifest(name, String(cache)); + const requests = oddTimeManifestRequests.get(name); + + const { stderr, exitCode, lockfile } = await install( + { [name]: "2.0.0" }, + ["--minimum-release-age", "0"], + {}, + { + cacheDir: String(cache), + env: expiredCache, + }, + ); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain(`${name}@2.0.0`); + expect(oddTimeManifestRequests.get(name)).toBe(requests); + expect(exitCode).toBe(0); + }); + + // The stability check compares 1.1.0 with the blocked 1.3.0, not with the unreadable 1.2.0 between them. + test.concurrent.each(["*", "latest"])( + "%s: an unreadable publish time between rapid releases does not end the stability check", + async specifier => { + const name = "unreadable-between-rapid-releases"; + const { stderr, exitCode, lockfile } = await install({ [name]: specifier }, fiveDayGate); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain(`${name}@1.0.0`); + expect(exitCode).toBe(0); + }, + ); + + test.concurrent("--minimum-release-age 0 installs a version with an unreadable publish time", async () => { + const { stderr, exitCode, lockfile } = await install( + { "odd-time-text": "2.0.0" }, + ["--minimum-release-age", "0"], + { + minimumReleaseAge: 5 * SECONDS_PER_DAY, + }, + ); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain("odd-time-text@2.0.0"); + expect(exitCode).toBe(0); + }); + + test.concurrent("minimumReleaseAgeExcludes bypasses an unreadable publish time", async () => { + const { stderr, exitCode, lockfile } = await install({ "odd-time-text": "*" }, [], { + minimumReleaseAge: 5 * SECONDS_PER_DAY, + minimumReleaseAgeExcludes: ["odd-time-text"], + }); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain("odd-time-text@2.0.0"); + expect(exitCode).toBe(0); + }); + + test.concurrent("an unreadable publish time changes nothing without the age gate", async () => { + const { stderr, exitCode, lockfile } = await install({ "odd-time-text": "*" }, []); + + expect(stderr).not.toContain("error:"); + expect(lockfile).toContain("odd-time-text@2.0.0"); + expect(exitCode).toBe(0); }); });