Merge current main and fix the CI formatting failures

This commit is contained in:
skylartaylor committed 2026-10-22 19:59:21 +02:00
commit 20715c1eed
11 files changed
+257 -46

No files matched your search

+6
View File
@@ -113,6 +113,12 @@ only; English where there is none): never bundle a CJK font, they are 10 MB and
GitHub release JSON fixtures (small, committed under `crates/core/tests/fixtures/`).
5. When fetching anything, use a generic `ArtCraft-Launcher/<version>` User-Agent and never put
a person's name, email or other personal details in requests.
6. **Time goes through `jiff`** (workspace dependency). Never hand-roll UTC/calendar conversion
(days-to-date algorithms, leap-year math); a module owns only its output format string. The one
exception is range extension: past the years jiff can represent, shift the date by whole 400-year
Gregorian cycles (146,097 days, after which the calendar repeats), let jiff compute the month and
day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is
plain arithmetic).
## 3. Before you finish a task
Generated
+4
View File
@@ -303,6 +303,7 @@ dependencies = [
name = "artcraft-launcher-core"
version = "0.6.1"
dependencies = [
"jiff",
"semver",
"serde",
"serde_json",
@@ -5893,6 +5894,9 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xtask"
version = "0.6.1"
dependencies = [
"jiff",
]
[[package]]
name = "yoke"
+2
View File
@@ -28,6 +28,8 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
semver = { version = "1", features = ["serde"] }
log = "0.4"
# All date/time conversion goes through jiff (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
jiff = "0.2"
[profile.dev.package."*"]
opt-level = 2
+2
View File
@@ -14,3 +14,5 @@ workspace = true
serde = { workspace = true }
serde_json = { workspace = true }
semver = { workspace = true }
# Calendar conversion (jiff); see AGENTS.md. Only civil-date math is used, no time zone.
jiff = { workspace = true }
+27 -8
View File
@@ -186,13 +186,14 @@ impl FeedRelease {
/// when it doesn't hold up (no tag, or not a version).
fn to_release(&self, repo: &str, mirror: Option<&str>) -> Option<Release> {
let version = version::parse(&self.tag)?;
let prefix = release::download_prefix(repo);
let allowed = |url: &str| url.starts_with(&prefix) || mirror.is_some_and(|m| url.starts_with(m) && !url.contains(".."));
let allowed = |url: &str| {
release::download_url_under(url, &release::download_prefix(repo)) || mirror.is_some_and(|m| release::download_url_under_mirror(url, m))
};
let releases_page = format!("https://github.com/{repo}/releases/");
let assets = self
.assets
.iter()
.filter(|(name, _, url, _)| release::valid_file_name(name) && allowed(url) && !url.contains(['?', '#', '\\']))
.filter(|(name, _, url, _)| release::valid_file_name(name) && allowed(url))
.map(|(name, size, url, sha)| Asset {
name: name.clone(),
size: *size,
@@ -407,9 +408,13 @@ impl RawNotice {
if self.title.trim().is_empty() && self.body.trim().is_empty() {
return None;
}
let link = self
.maybe_web_link
.filter(|l| (l.starts_with("https://") || l.starts_with("http://")) && l.len() <= 2000 && !l.chars().any(char::is_whitespace));
// The link may reach the system opener (whose WSL fallback shells out), so refuse any
// shell/cmd metacharacter or control character in it as well as whitespace (CWE-78).
let link = self.maybe_web_link.filter(|l| {
(l.starts_with("https://") || l.starts_with("http://"))
&& l.len() <= 2000
&& !l.chars().any(|c| c.is_whitespace() || c.is_control() || release::is_shell_meta(c))
});
Some(Notice {
id: format!("{kind}:{}:{}", self.created_at.as_deref().unwrap_or(""), self.title.trim()),
title: truncate(self.title.trim(), 200),
@@ -564,6 +569,18 @@ mod tests {
assert_eq!(feed.answer(app("photocraft"), NOW), FeedAnswer::AskGitHub);
}
#[test]
fn a_feed_url_cannot_traverse_out_of_the_repository() {
// The feed advertises a legitimate tag but points the asset at another repository by
// climbing out with `../` after the approved prefix (CWE-180).
let escaped = sample().replace(
"https://github.com/storytold/photocraft/releases/download/v0.6.0/photocraft-0.6.0-macos-universal.dmg",
"https://github.com/storytold/photocraft/releases/download/../../../../attacker/repo/releases/download/v99/photocraft-0.6.0-macos-universal.dmg",
);
let FeedAnswer::Fresh(Some(r)) = Feed::parse(&escaped).unwrap().answer(app("photocraft"), NOW) else { panic!() };
assert!(r.assets.is_empty(), "the traversing download must be rejected");
}
#[test]
fn a_local_mirror_is_trusted_only_when_asked_for_and_never_goes_stale() {
const MIRROR: &str = "http://127.0.0.1:8787/";
@@ -612,7 +629,8 @@ mod tests {
"\"alerts\": []",
r#""alerts": [
{"title": "Security update", "body": "Update PdfCraft now.", "maybe_web_link": "https://getartcraft.com/security", "created_at": null},
{"title": "Bad link", "body": "x", "maybe_web_link": "javascript:alert(1)"}]"#,
{"title": "Bad link", "body": "x", "maybe_web_link": "javascript:alert(1)"},
{"title": "Shell link", "body": "x", "maybe_web_link": "https://getartcraft.com/a|calc.exe"}]"#,
)
.replace(
"\"app_renames\": []",
@@ -620,9 +638,10 @@ mod tests {
"new_name_lower": "docucraft", "description": "Same app, new name.", "renamed_at": "2026-10-09T08:00:00Z"}]"#,
);
let feed = Feed::parse(&with_notices).unwrap();
assert_eq!(feed.alerts.len(), 2);
assert_eq!(feed.alerts.len(), 3);
assert_eq!(feed.alerts[0].link.as_deref(), Some("https://getartcraft.com/security"));
assert_eq!(feed.alerts[1].link, None, "only web links are kept");
assert_eq!(feed.alerts[2].link, None, "a link with shell metacharacters is dropped");
let titles: Vec<&str> = feed.announcements.iter().map(|n| n.title.as_str()).collect();
assert_eq!(titles, ["New: CADCraft 1.0", "PdfCraft is now DocuCraft"]);
// Ids are stable across parses, so dismissals stick.
+94 -3
View File
@@ -61,11 +61,28 @@ fn is_hex64(s: &str) -> bool {
}
/// Whether `url` is safe to hand to the system browser from untrusted text (release notes):
/// `https` only, a host, no user-info, no spaces or control characters.
/// `https` only, a host, no user-info, no spaces or control characters, and no shell metacharacters.
///
/// The system opener is not always a direct `open`: the pinned `webbrowser` crate's WSL fallback
/// passes the URL to `cmd.exe /c start` while escaping only `^` and `&`, so a character like `|`
/// in an otherwise valid URL becomes a command separator (CWE-78). Because a legitimate
/// `https://` web link never needs these characters unescaped, we refuse any URL that contains a
/// shell/cmd metacharacter rather than rely on the opener to neutralise it.
pub fn safe_web_link(url: &str) -> bool {
let Some(rest) = url.strip_prefix("https://") else { return false };
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
url.len() <= 2000 && !authority.is_empty() && !authority.contains(['@', '\\']) && !url.chars().any(|c| c.is_control() || c.is_whitespace())
url.len() <= 2000
&& !authority.is_empty()
&& !authority.contains(['@', '\\'])
&& !url.chars().any(|c| c.is_control() || c.is_whitespace())
&& !url.chars().any(is_shell_meta)
}
/// Characters a command interpreter (POSIX shells or `cmd.exe`) may treat specially. A real
/// `https` URL never needs any of them unescaped in a browser-opened link. `%` matters because
/// `cmd.exe` expands `%NAME%` references, and an expanded value could itself carry metacharacters.
pub fn is_shell_meta(c: char) -> bool {
matches!(c, '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '"' | '\'' | '^' | '!' | '*' | '%' | '{' | '}' | '[' | ']')
}
/// The prefix every download of `repo` must start with.
@@ -73,6 +90,49 @@ pub fn download_prefix(repo: &str) -> String {
format!("https://github.com/{repo}/releases/download/")
}
/// Whether `url` is a download that truly belongs to `repo`.
///
/// A raw `starts_with(prefix)` check is not enough: a value such as
/// `https://github.com/storytold/craft-launcher/releases/download/../../../ATTACKER/REPO/releases/download/v1/x`
/// shares the prefix textually, yet its interpreted path escapes the repository. The link is
/// accepted only when the text after the prefix is exactly `<tag>/<name>` — two non-empty path
/// segments with no traversal (`.`/`..`), no additional slashes, no query or fragment, and no
/// backslash or percent-encoded separators that a client could later re-interpret.
pub fn download_url_under(url: &str, prefix: &str) -> bool {
let Some(rest) = url.strip_prefix(prefix) else { return false };
download_suffix_ok(rest)
}
/// Whether `url` sits under a developer mirror `base` (ending in `/`) without escaping it.
pub fn download_url_under_mirror(url: &str, base: &str) -> bool {
let Some(rest) = url.strip_prefix(base) else { return false };
// A mirror serves `<tag>/<name>` just like GitHub, but we only require that it can't climb out
// of its own folder; its layout is otherwise the developer's business.
!rest.is_empty() && !url.contains(['?', '#', '\\']) && !contains_traversal(rest) && !contains_encoded_separator(rest)
}
/// `<tag>/<name>`: exactly two non-empty segments, no traversal, no re-interpretable separators.
fn download_suffix_ok(rest: &str) -> bool {
if rest.contains(['?', '#', '\\']) || contains_encoded_separator(rest) {
return false;
}
let mut parts = rest.split('/');
let (Some(tag), Some(name), None) = (parts.next(), parts.next(), parts.next()) else { return false };
!tag.is_empty() && tag != "." && tag != ".." && tag.len() <= 64 && !tag.contains('\\') && valid_file_name(name)
}
/// Any `.` or `..` path segment that could climb out of the repository.
fn contains_traversal(rest: &str) -> bool {
rest.split('/').any(|seg| seg == "." || seg == "..")
}
/// Percent-encoded slash or backslash (`%2f`, `%5c`): a client could decode these back into
/// separators after the check, so a confined URL must not contain them.
fn contains_encoded_separator(rest: &str) -> bool {
let bytes = rest.as_bytes();
bytes.windows(3).any(|w| w[0] == b'%' && matches!(&w[1..].to_ascii_lowercase()[..], b"2f" | b"5c"))
}
/// Reads `GET /repos/<repo>/releases/latest` (or one element of `/releases`).
pub fn parse_github_release(json: &str, repo: &str) -> Result<Release, String> {
let v: serde_json::Value = serde_json::from_str(json).map_err(|e| format!("unreadable answer from GitHub ({e})"))?;
@@ -119,7 +179,7 @@ fn release_from_value(v: &serde_json::Value, repo: &str) -> Result<Release, Stri
list.iter()
.filter_map(|a| {
let name = a["name"].as_str().filter(|n| valid_file_name(n))?.to_string();
let url = a["browser_download_url"].as_str().filter(|u| u.starts_with(&prefix) && !u.contains(['?', '#', '\\']))?.to_string();
let url = a["browser_download_url"].as_str().filter(|u| download_url_under(u, &prefix))?.to_string();
let sha256 = a["digest"].as_str().and_then(|d| d.strip_prefix("sha256:")).filter(|h| is_hex64(h)).map(str::to_ascii_lowercase);
Some(Asset { name, size: a["size"].as_u64().unwrap_or(0), url, sha256 })
})
@@ -216,6 +276,16 @@ mod tests {
"https://example.com/a b",
"https://example.com/\nx",
"https:///path",
// Shell/cmd metacharacters: the WSL opener fallback shells out, so these must be
// refused even inside an otherwise valid https URL (CWE-78).
"https://example.com/a|calc",
"https://example.com/p?x=1&y=2",
"https://example.com/`id`",
"https://example.com/$(whoami)",
"https://example.com/a;b",
"https://example.com/a>b",
"https://example.com/%COMSPEC%",
"https://example.com/%PATH%",
] {
assert!(!safe_web_link(bad), "{bad:?}");
}
@@ -255,6 +325,27 @@ mod tests {
assert!(parse_github_release("<html>", REPO).is_err());
}
#[test]
fn traversal_cannot_escape_the_repository() {
// Raw-prefix matches but the interpreted path climbs into another repository (CWE-180).
for url in [
"https://github.com/storytold/photocraft/releases/download/../../../../attacker/repo/releases/download/v99/photocraft-99.0.0-linux-x86_64.AppImage",
"https://github.com/storytold/photocraft/releases/download/v1/../../../attacker/repo/x.dmg",
"https://github.com/storytold/photocraft/releases/download/./v1/x.dmg",
"https://github.com/storytold/photocraft/releases/download/v1/sub/x.dmg",
"https://github.com/storytold/photocraft/releases/download/v1%2f..%2f..%2fx.dmg",
"https://github.com/storytold/photocraft/releases/download/v1/x%2fy.dmg",
] {
let prefix = download_prefix(REPO);
assert!(!download_url_under(url, &prefix), "{url}");
let r = parse_github_release(&api_json(url), REPO).unwrap();
assert!(r.assets.is_empty(), "{url}");
}
// A plain, confined download still passes.
let prefix = download_prefix(REPO);
assert!(download_url_under("https://github.com/storytold/photocraft/releases/download/v0.5.0/photocraft-0.5.0-macos-universal.dmg", &prefix));
}
#[test]
fn list_picks_the_newest_stable_release() {
let json = r#"[
+34 -22
View File
@@ -1,4 +1,5 @@
//! Just enough calendar to read GitHub's timestamps and show them, without a date crate.
//! Just enough calendar to read GitHub's timestamps and show them (the conversion goes through
//! jiff; this module owns only the parsing and the output format strings).
//!
//! # Internationalisation
//! [`format_ago`] and [`format_date`] are English-only fallbacks. Translatable UI must use
@@ -64,32 +65,35 @@ pub fn parse_rfc3339(text: &str) -> Option<i64> {
}
_ => return None,
};
Some(days_from_civil(y, mo, d) * 86_400 + h * 3600 + mi * 60 + s - offset)
Some(days_from_civil(y, mo, d)? * 86_400 + h * 3600 + mi * 60 + s - offset)
}
/// Days since 1970-01-01 (Howard Hinnant's algorithm).
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (m + 9) % 12;
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
/// Days since 1970-01-01 (through jiff's civil calendar). A day past the month's length rolls over
/// the way the old Hinnant arithmetic did (e.g. `2026-02-30` → `2026-03-02`). `None` for a year
/// outside jiff's range.
fn days_from_civil(y: i64, m: i64, d: i64) -> Option<i64> {
let first = jiff::civil::Date::new(i16::try_from(y).ok()?, i8::try_from(m).ok()?, 1).ok()?;
let date = first.checked_add(jiff::SignedDuration::from_hours(d.checked_sub(1)?.checked_mul(24)?)).ok()?;
Some(date.duration_since(jiff::civil::Date::constant(1970, 1, 1)).as_secs() / 86_400)
}
/// (year, month, day) for a Unix time.
/// (year, month, day) for a Unix time (UTC). jiff's civil calendar only spans years -9999..=9999,
/// far narrower than the whole `i64` the old hand-rolled Hinnant code converted, so the instant is
/// first moved into range by whole 400-year Gregorian cycles (the calendar repeats every 400 years
/// = 146_097 days) and the real year restored afterwards. jiff still does the month/day; the cycle
/// count only shifts the year, keeping every `i64` exact (e.g. `i64::MAX` → year 292277026596,
/// `i64::MIN` → year -292277022657), with no epoch fallback for a value the old code converted.
pub fn civil_from_unix(secs: i64) -> (i64, u32, u32) {
let z = secs.div_euclid(86_400) + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
(y, u32::try_from(m).unwrap_or(1), u32::try_from(d).unwrap_or(1))
let epoch = jiff::civil::Date::constant(1970, 1, 1);
let days = secs.div_euclid(86_400);
let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
// `rest` is in `0..146_097` (under one 400-year cycle), so `epoch + rest days` always lands in
// 1970..=2369 — comfortably inside jiff's range — and `rest * 86_400` never overflows.
let date = epoch.checked_add(jiff::SignedDuration::from_secs(rest * 86_400)).unwrap_or(epoch);
// Restore the real year through `i128` so `cycles * 400` can't overflow at the `i64` extremes.
let y = i128::from(date.year()) + i128::from(cycles) * 400;
let year = i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX });
(year, u32::try_from(date.month()).unwrap_or(1), u32::try_from(date.day()).unwrap_or(1))
}
const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
@@ -161,6 +165,14 @@ mod tests {
fn shows_dates_people_read() {
assert_eq!(format_date(1_791_471_170), "Oct 8, 2026");
assert_eq!(civil_from_unix(951_782_400), (2000, 2, 29));
// Year 10000 is past jiff's own calendar range, but the 400-year cycle reduction keeps the
// old conversion (jiff spans only -9999..=9999).
assert_eq!(civil_from_unix(253_402_300_800), (10000, 1, 1));
// The `i64` extremes stay the dates the old Hinnant code produced, not the epoch.
assert_eq!(civil_from_unix(i64::MAX), (292_277_026_596, 12, 4));
assert_eq!(civil_from_unix(i64::MIN), (-292_277_022_657, 1, 27));
assert_eq!(format_date(i64::MAX), "Dec 4, 292277026596");
assert_eq!(format_date(i64::MIN), "Jan 27, -292277022657");
let now = 1_791_471_170;
assert_eq!(format_ago(now - 5, now), "just now");
assert_eq!(format_ago(now - 600, now), "10 min ago");
+64
View File
@@ -81,6 +81,7 @@ pub fn install_at(
{
return Err(format!("{} is running. Quit it, then try again.", app.name));
}
bind_artifact_version(app, release, asset)?;
if !job.replace
&& let Some(inst) = existing
&& let (Some(rel_v), Some(inst_v)) = (release.version.as_ref(), inst.version.as_ref())
@@ -147,6 +148,38 @@ pub fn install_at(
result.map_err(|e| if e == CANCELLED { INSTALL_CANCELLED.to_string() } else { e })
}
/// Rejects an artifact whose own identity disagrees with the release that authorized it.
///
/// A feed or GitHub converter supplies the release version, the asset filename, and the download
/// URL independently. The downgrade guard and the persisted record both trust `release.version`,
/// so a controller could advertise a new version while pointing at an older official artifact —
/// bypassing the guard and recording a false installed version (finding: version not bound to the
/// release). We require the version encoded in the asset filename and the release tag embedded in
/// the download URL to agree with the release version before any bytes are fetched.
fn bind_artifact_version(app: &CraftApp, release: &Release, asset: &Asset) -> Result<(), String> {
let Some(release_version) = release.version.as_ref() else { return Ok(()) };
let mismatch = || format!("{}'s download does not match the advertised version {}.", app.name, release.version_label());
// The version in the asset filename (`<stem>-<version>-<os>-<arch>.<ext>`), when it carries one.
let stems: Vec<&str> = app.stems().collect();
if let Some(parsed) = artcraft_launcher_core::platform::parse_asset_name(&asset.name, &stems)
&& version::parse(&parsed.version).as_ref() != Some(release_version)
{
return Err(mismatch());
}
// The release tag embedded in a GitHub download URL (`.../releases/download/<tag>/<name>`).
if let Some(tag) = asset.url.split("/releases/download/").nth(1).and_then(|rest| rest.split('/').next())
&& !tag.is_empty()
&& version::parse(tag).is_some()
&& version::parse(tag).as_ref() != Some(release_version)
&& tag != release.tag
{
return Err(mismatch());
}
Ok(())
}
/// What a new install would write over: something already at its destination that the launcher
/// didn't put there.
pub fn occupied(
@@ -2262,6 +2295,37 @@ mod tests {
assert!(result.unwrap_err().contains("installed version 0.5.0 is newer"));
}
#[test]
fn install_rejects_an_artifact_whose_version_is_not_the_advertised_one() {
// The release advertises 99.0.0, but the selected artifact is an older official build
// (filename and URL tag say 0.4.0). The guard must refuse before any download.
let dir = tempfile::tempdir().unwrap();
let paths = Paths::under(dir.path());
let http = Http::new().unwrap();
let phase = &mut |_| ();
let locations = InstallLocations::default();
let app = CraftApp::by_id("photocraft").unwrap();
let release = Release { version: version::parse("99.0.0"), tag: "v99.0.0".into(), ..Release::default() };
let asset = Asset {
name: "photocraft-0.4.0-linux-x86_64.AppImage".into(),
url: "https://github.com/storytold/photocraft/releases/download/v0.4.0/photocraft-0.4.0-linux-x86_64.AppImage".into(),
..Asset::default()
};
let stop = Stop::default();
let mut job = Job { http: &http, paths: &paths, stop: &stop, phase, install_locations: &locations, replace: false };
let result = install_at(app, &release, &asset, PackageKind::AppImage, None, None, &mut job, None);
assert!(result.is_err(), "mismatched artifact version must be rejected");
assert!(result.unwrap_err().contains("does not match the advertised version"));
// A matching artifact passes the guard (it fails later for unrelated reasons, not the bind).
let good = Asset {
name: "photocraft-99.0.0-linux-x86_64.AppImage".into(),
url: "https://github.com/storytold/photocraft/releases/download/v99.0.0/photocraft-99.0.0-linux-x86_64.AppImage".into(),
..Asset::default()
};
assert!(bind_artifact_version(app, &release, &good).is_ok());
}
#[cfg(target_os = "linux")]
#[test]
fn package_kinds_order_matches_launcher_format() {
+1 -1
View File
@@ -24,7 +24,7 @@ sys-locale = "0.3"
# Finding the Simplified Chinese face in a system font collection; egui already uses it.
skrifa = { version = "0.44", default-features = false, features = ["std"] }
# The system time zone, so dates read as this computer's calendar; already in the desktop build.
jiff = "0.2"
jiff = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# The browser's time zone, for the same dates.
+3
View File
@@ -7,3 +7,6 @@ publish = false
[lints]
workspace = true
[dependencies]
jiff = { workspace = true }
+20 -12
View File
@@ -493,20 +493,23 @@ fn unix_now() -> i64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0))
}
/// `2026-10-10T12:00:00Z` (civil-from-days, Howard Hinnant's algorithm).
/// `2026-10-10T12:00:00Z` (through jiff's civil calendar). jiff spans only years -9999..=9999, far
/// narrower than the whole `i64` the old hand-rolled Hinnant code converted, so the instant is
/// moved into range by whole 400-year Gregorian cycles (146_097 days) and the real year restored
/// afterwards. jiff still does the month/day; the cycle count only shifts the year, keeping every
/// `i64` exact (e.g. `i64::MAX` → year 292277026596) with no epoch fallback.
fn rfc3339(secs: i64) -> String {
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
let epoch = jiff::civil::Date::constant(1970, 1, 1);
let days = secs.div_euclid(86_400);
let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
// `rest` is in `0..146_097` (under one 400-year cycle), so `epoch + rest days` lands in
// 1970..=2369 (inside jiff's range) and `rest * 86_400` never overflows.
let date = epoch.checked_add(jiff::SignedDuration::from_secs(rest * 86_400)).unwrap_or(epoch);
// Restore the real year through `i128` so `cycles * 400` can't overflow at the `i64` extremes.
let y = i128::from(date.year()) + i128::from(cycles) * 400;
let y = i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX });
format!("{y:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", date.month(), date.day(), rem / 3600, rem % 3600 / 60, rem % 60)
}
// ---- versions -----------------------------------------------------------------------------------
@@ -692,6 +695,11 @@ mod tests {
fn dates_and_versions() {
assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");
assert_eq!(rfc3339(1_791_500_000), "2026-10-08T22:53:20Z");
// Year 10000 and the `i64` extremes are past jiff's own calendar range (-9999..=9999), but
// the 400-year cycle reduction keeps the dates the old Hinnant code produced, not the epoch.
assert_eq!(rfc3339(253_402_300_800), "10000-01-01T00:00:00Z");
assert_eq!(rfc3339(i64::MAX), "292277026596-12-04T15:30:07Z");
assert_eq!(rfc3339(i64::MIN), "-292277022657-01-27T08:29:52Z");
assert_eq!(compare_versions("0.10.0", "0.9.0"), std::cmp::Ordering::Greater);
assert_eq!(compare_versions("1.0.0", "1.0.0-rc.1"), std::cmp::Ordering::Greater);
assert!(parse_version("1.2").is_none() && parse_version(".building-1.2.3").is_none());