From 0c9da45981bb78cda04b8a0ef7f2617d71d2ab70 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 17 Sep 2026 22:26:20 +0000 Subject: [PATCH 1/8] install: block a version whose publish time is not a date under minimum-release-age A `time` entry that is present but that `Date.parse` cannot read left `publish_timestamp_ms` at 0, so the version counted as old enough. - Read `time` with the parser behind `Date.parse` (the V8 date parser in JSC) and not the ISO-only `WTF::parseES5Date`. RFC 2822 and `Date.toString()` dates now gate like ISO dates. - A string that is not a date, and a truthy value that is not a string, is stored as infinity and never passes the gate. A falsy entry (null, "", 0, false) and a missing entry still pass. This follows npm's `!time[v] || Date.parse(time[v]) <= before`, except that npm also reads a non-string that stringifies into a date (2020, ["2020-01-01"]). - The age-gate error says that the publish time is not a valid date. An exact version from an expired cached manifest now reports through the same error arm as a fresh manifest. - `--minimum-release-age=0` stays the off switch. - Bump the manifest cache version so cached manifests are parsed again. --- docs/pm/cli/install.mdx | 1 + src/bun_core/wtf.rs | 32 +-- .../PackageManager/PackageManagerEnqueue.rs | 73 ++++-- src/install/error.rs | 3 + src/install/npm.rs | 68 ++++- src/jsc/bindings/wtf-bindings.cpp | 9 +- test/cli/install/minimum-release-age.test.ts | 239 ++++++++++++++++-- 7 files changed, 358 insertions(+), 67 deletions(-) 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..8da7856a16a3 100644 --- a/src/bun_core/wtf.rs +++ b/src/bun_core/wtf.rs @@ -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`. //! -//! 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. 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. #[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)] @@ -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 { +pub fn parse_date(buf: &[u8]) -> Result { 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 { diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index ea9ec05aa566..028323062bf1 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, ); } } @@ -1200,19 +1207,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 +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)] @@ -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 }, 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..50f3e3b374bb 100644 --- a/src/install/npm.rs +++ b/src/install/npm.rs @@ -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`). pub(crate) publish_timestamp_ms: f64, } @@ -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 { @@ -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. @@ -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 @@ -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. + TooRecent { + unreadable_publish_time: bool, + }, + AllVersionsTooRecent { + unreadable_publish_time: bool, + }, } pub enum FindVersionResult<'a> { @@ -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, } @@ -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( @@ -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); } @@ -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) @@ -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. +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>, @@ -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); } } diff --git a/src/jsc/bindings/wtf-bindings.cpp b/src/jsc/bindings/wtf-bindings.cpp index 4c6344fe0050..c3a26cc080f0 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,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. +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..569e4a8d4e7f 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 { bunEnv, bunExe, isDebug, normalizeBunSnapshot, tempDir } from "harness"; +import { readdirSync } from "fs"; +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,48 @@ 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)], + }; + // 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(), + }; + // 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(), + }; + // 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, + ...unsetPublishTimes, + // Only the expired cached manifest test asks for these two, so it can count their manifest requests. + "odd-time-cached-unreadable": "yesterday", + "odd-time-cached-recent": new Date(currentTime).toISOString(), + }; + const oddTimeManifestRequests = new Map(); + // Helper to create a minimal valid tarball const createTarball = (name: string, version: string) => { const packageJson = JSON.stringify({ @@ -706,6 +750,31 @@ 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 11: exact-threshold-package (exactly at age boundary) if (url.pathname === "/exact-threshold-package") { const packageData = { @@ -2211,29 +2280,169 @@ 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); + }, + ); - // Should succeed - invalid timestamps should be skipped gracefully + 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); + }, + ); + + 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, with no request. Only a debug + // build reads BUN_CONFIG_MANIFEST_CACHE_CONTROL_TIMESTAMP, which makes the cached manifest count as expired. + test.skipIf(!isDebug).concurrent.each([ + ["odd-time-cached-unreadable", "the publish time in the registry is not a valid date"], + ["odd-time-cached-recent", `${5 * SECONDS_PER_DAY} seconds`], + ])("%s: an exact version from an expired cached manifest is blocked with the same error", async (name, reason) => { + using cache = tempDir("odd-publish-time-cache", {}); + const cacheDir = String(cache); + // bun saves the manifest from a thread pool task and does not wait for it at exit. + do { + await install({ [name]: "1.0.0" }, fiveDayGate, {}, { cacheDir }); + } while (!readdirSync(cacheDir).some(file => file.endsWith(".npm"))); + const requests = oddTimeManifestRequests.get(name); + + const { stderr, exitCode } = await install( + { [name]: "2.0.0" }, + fiveDayGate, + {}, + { + cacheDir, + env: { BUN_CONFIG_MANIFEST_CACHE_CONTROL_TIMESTAMP: "4294967295" }, + }, + ); + + 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); + expect(exitCode).toBe(1); + }); + + 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); }); }); From 11dc74cfe62456045bad790d9515eeb88ccbbaec Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:18:44 +0000 Subject: [PATCH 2/8] [autofix.ci] apply automated fixes --- test/cli/install/minimum-release-age.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/cli/install/minimum-release-age.test.ts b/test/cli/install/minimum-release-age.test.ts index 569e4a8d4e7f..65ae8ae0f90a 100644 --- a/test/cli/install/minimum-release-age.test.ts +++ b/test/cli/install/minimum-release-age.test.ts @@ -1,7 +1,7 @@ import type { Server } from "bun"; import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { bunEnv, bunExe, isDebug, 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 From 126fc2cff85b111383a25172aba782f8b81c193d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:25:10 +0000 Subject: [PATCH 3/8] install: name the publish time sentinels and shorten comments `PackageVersion::NO_PUBLISH_TIME` and `UNREADABLE_PUBLISH_TIME` replace the bare 0 and infinity, so the code says what the long comments said. `parse_date` calls the C++ shim directly. --- src/bun_core/wtf.rs | 26 ++++----------------- src/install/npm.rs | 38 +++++++++++++++---------------- src/jsc/bindings/wtf-bindings.cpp | 3 +-- 3 files changed, 24 insertions(+), 43 deletions(-) diff --git a/src/bun_core/wtf.rs b/src/bun_core/wtf.rs index 8da7856a16a3..441bc1a76c4a 100644 --- a/src/bun_core/wtf.rs +++ b/src/bun_core/wtf.rs @@ -4,30 +4,12 @@ //! 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` (`Bun__parseDateTimeString`), -//! which forwards to `v8::ParseDateTimeString` in -//! vendor/WebKit `Source/JavaScriptCore/runtime/JSDateMath-v8.{h,cpp}`, the -//! parser behind JS `Date.parse`. -//! -//! 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. unsafe extern "C" { - // src/jsc/bindings/wtf-bindings.cpp: - // extern "C" double Bun__parseDateTimeString(const Latin1Character* string, size_t length) + // src/jsc/bindings/wtf-bindings.cpp fn Bun__parseDateTimeString(bytes: *const u8, length: usize) -> f64; } -/// Direct call to the parser. Returns NaN for any input `Date.parse` rejects. -/// `s` is treated as Latin-1. -#[inline] -pub(crate) fn parse_date_raw(s: &[u8]) -> f64 { - // SAFETY: s.as_ptr() is valid for s.len() bytes. - unsafe { Bun__parseDateTimeString(s.as_ptr(), s.len()) } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct InvalidDate; @@ -38,13 +20,13 @@ impl core::fmt::Display for InvalidDate { } impl core::error::Error for InvalidDate {} -/// 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)`. +/// 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_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/npm.rs b/src/install/npm.rs index 50f3e3b374bb..4ba9cf2f34bc 100644 --- a/src/install/npm.rs +++ b/src/install/npm.rs @@ -739,8 +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 when the registry gives none, - /// infinity when it gives one that is not a date (see `publish_timestamp_ms_from_json`). + /// Unix timestamp when this version was published, or `NO_PUBLISH_TIME` / `UNREADABLE_PUBLISH_TIME` pub(crate) publish_timestamp_ms: f64, } @@ -767,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, } } } @@ -777,9 +776,13 @@ 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. + /// 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.is_infinite() + self.publish_timestamp_ms == Self::UNREADABLE_PUBLISH_TIME } /// Used by `Package.fromNPM` to walk dependency groups by name. @@ -1666,8 +1669,7 @@ impl PackageManifest { #[derive(Clone, Copy, PartialEq, Eq)] pub enum FindVersionError { NotFound, - /// `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. + /// `unreadable_publish_time`: the newest blocked candidate has `UNREADABLE_PUBLISH_TIME`, it is not new. TooRecent { unreadable_publish_time: bool, }, @@ -1999,19 +2001,17 @@ 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. -fn publish_timestamp_ms_from_json(entry: &JSON::E::JsonValue) -> f64 { +/// 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 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, + 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, } } diff --git a/src/jsc/bindings/wtf-bindings.cpp b/src/jsc/bindings/wtf-bindings.cpp index c3a26cc080f0..4d6b42454708 100644 --- a/src/jsc/bindings/wtf-bindings.cpp +++ b/src/jsc/bindings/wtf-bindings.cpp @@ -238,8 +238,7 @@ extern "C" size_t WTF__base64URLEncode(const char* __restrict inputDataBuffer, s return simdutf::binary_to_base64(inputDataBuffer, inputDataBufferSize, destinationDataBuffer, simdutf::base64_url); } -// `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. +// 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 = false; From 00309d1bc2b13b2cbb0d54fe3f78bec6ea94c2ae Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:39:20 +0000 Subject: [PATCH 4/8] test: bound the manifest cache priming loop in minimum-release-age.test.ts --- test/cli/install/minimum-release-age.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/cli/install/minimum-release-age.test.ts b/test/cli/install/minimum-release-age.test.ts index 65ae8ae0f90a..5d1bb42bbbac 100644 --- a/test/cli/install/minimum-release-age.test.ts +++ b/test/cli/install/minimum-release-age.test.ts @@ -2390,9 +2390,12 @@ describe("minimum-release-age", () => { using cache = tempDir("odd-publish-time-cache", {}); const cacheDir = String(cache); // bun saves the manifest from a thread pool task and does not wait for it at exit. - do { + let cached = false; + for (let attempt = 0; attempt < 5 && !cached; attempt++) { await install({ [name]: "1.0.0" }, fiveDayGate, {}, { cacheDir }); - } while (!readdirSync(cacheDir).some(file => file.endsWith(".npm"))); + 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}`); const requests = oddTimeManifestRequests.get(name); const { stderr, exitCode } = await install( From 3d3984be67a647235bd9ebac1e9d63672b49e98b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 17:01:31 +0000 Subject: [PATCH 5/8] install: keep an unreadable publish time out of the stability check and out of a stale cache - The stability check measures a candidate against the newer blocked version. A blocked version with an unreadable publish time no longer replaces a readable one there, so it cannot make every gap look large. - An exact version whose cached publish time is unreadable is not resolved from an expired cached manifest. Bun fetches the manifest again, so a registry that corrects the time is read. --- .../PackageManager/PackageManagerEnqueue.rs | 14 +- src/install/npm.rs | 17 ++- test/cli/install/minimum-release-age.test.ts | 123 ++++++++++++++---- 3 files changed, 125 insertions(+), 29 deletions(-) diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index 028323062bf1..098ca7a847d9 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.rs +++ b/src/install/PackageManager/PackageManagerEnqueue.rs @@ -1182,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 @@ -1193,6 +1195,14 @@ 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 + && needs_extended_manifest + && found + .package + .has_unreadable_publish_time()) + }) { if let Some(min_age_ms) = this.options.minimum_release_age_ms diff --git a/src/install/npm.rs b/src/install/npm.rs index 4ba9cf2f34bc..66609a3957a3 100644 --- a/src/install/npm.rs +++ b/src/install/npm.rs @@ -1592,6 +1592,17 @@ impl PackageManifest { 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], @@ -1619,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 { @@ -1791,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; } diff --git a/test/cli/install/minimum-release-age.test.ts b/test/cli/install/minimum-release-age.test.ts index 5d1bb42bbbac..9ce95174d3c0 100644 --- a/test/cli/install/minimum-release-age.test.ts +++ b/test/cli/install/minimum-release-age.test.ts @@ -61,9 +61,10 @@ describe("minimum-release-age", () => { ...recentLegacyPublishTimes, ...oldLegacyPublishTimes, ...unsetPublishTimes, - // Only the expired cached manifest test asks for these two, so it can count their manifest requests. + // 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", }; const oddTimeManifestRequests = new Map(); @@ -775,6 +776,33 @@ describe("minimum-release-age", () => { }); } + // 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 = { @@ -2381,14 +2409,10 @@ describe("minimum-release-age", () => { expect(exitCode).toBe(1); }); - // An exact version resolves from a manifest that is on disk but expired, with no request. Only a debug - // build reads BUN_CONFIG_MANIFEST_CACHE_CONTROL_TIMESTAMP, which makes the cached manifest count as expired. - test.skipIf(!isDebug).concurrent.each([ - ["odd-time-cached-unreadable", "the publish time in the registry is not a valid date"], - ["odd-time-cached-recent", `${5 * SECONDS_PER_DAY} seconds`], - ])("%s: an exact version from an expired cached manifest is blocked with the same error", async (name, reason) => { - using cache = tempDir("odd-publish-time-cache", {}); - const cacheDir = String(cache); + // 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++) { @@ -2396,24 +2420,73 @@ describe("minimum-release-age", () => { 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}`); - const requests = oddTimeManifestRequests.get(name); + } - const { stderr, exitCode } = await install( - { [name]: "2.0.0" }, - fiveDayGate, - {}, - { - cacheDir, - env: { BUN_CONFIG_MANIFEST_CACHE_CONTROL_TIMESTAMP: "4294967295" }, - }, - ); + // 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); - expect(exitCode).toBe(1); - }); + 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); + }); + + // 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( From 374ffe02d12a0711731040f1ed1c324348c6bc8b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 17:33:08 +0000 Subject: [PATCH 6/8] ci: retrigger From 0222917f88502b87111225d979e7d5a49a148bfa Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 17:44:23 +0000 Subject: [PATCH 7/8] install: refetch a cached unreadable publish time only when the age gate is on `--minimum-release-age=0` is `Some(0.0)`, so the check on the extended manifest flag also skipped the cached exact version with the gate off. --- .../PackageManager/PackageManagerEnqueue.rs | 5 +++- test/cli/install/minimum-release-age.test.ts | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index 098ca7a847d9..d9e4c6193932 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.rs +++ b/src/install/PackageManager/PackageManagerEnqueue.rs @@ -1198,7 +1198,10 @@ pub fn enqueue_dependency_with_main_and_success_fn( // A cached "not a date" cannot become a date: fetch an expired manifest again. .filter(|found| { !(expired - && needs_extended_manifest + && this + .options + .minimum_release_age_ms + .is_some_and(|age| age > 0.0) && found .package .has_unreadable_publish_time()) diff --git a/test/cli/install/minimum-release-age.test.ts b/test/cli/install/minimum-release-age.test.ts index 9ce95174d3c0..701d565024f3 100644 --- a/test/cli/install/minimum-release-age.test.ts +++ b/test/cli/install/minimum-release-age.test.ts @@ -65,6 +65,7 @@ describe("minimum-release-age", () => { "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(); @@ -2475,6 +2476,30 @@ describe("minimum-release-age", () => { 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", From 8ee0b59fae0d5d67feed57df0d6e8e11a3beed5c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 19:12:04 +0000 Subject: [PATCH 8/8] test: cover a V8-only date form and a publish time with no time zone under minimum-release-age Two date forms join the publish time tables. "YYYY-MM-DD HH:mm:ss +00:00" is a form that only the V8 date parser reads. A date-time with no time zone must read as UTC when TZ is UTC+14. --- test/cli/install/minimum-release-age.test.ts | 30 ++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/cli/install/minimum-release-age.test.ts b/test/cli/install/minimum-release-age.test.ts index 701d565024f3..07e40ff3ea9e 100644 --- a/test/cli/install/minimum-release-age.test.ts +++ b/test/cli/install/minimum-release-age.test.ts @@ -39,15 +39,26 @@ describe("minimum-release-age", () => { "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 = { @@ -60,6 +71,7 @@ describe("minimum-release-age", () => { ...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", @@ -2360,6 +2372,24 @@ describe("minimum-release-age", () => { }, ); + // 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 => {