Installation counter after review: strict input, limits, country only, GitHub outages
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

- /api/update takes a 32-hex id, an x.y.z version and a known platform; at most 5 new
  installations a day per address are counted (made-up ids do not flood the bot).
- A download's notice: once a day per file and visitor; notices name the country only,
  as the texts promise; Android's text also says the system is sent.
- The release cache is not locked while GitHub is asked (one request asks, the others
  get what is known); after a failure GitHub is asked again in a minute, not on every
  request.
- An unrecognised desktop installation counts as 'other'; the bot logs a wrong token or a
  second listener; .env.example lists the bot's settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-24 14:08:05 +03:00
parent d15989bff1
commit df2ee6f528
15 changed files with 106 additions and 35 deletions

View file

@ -44,8 +44,20 @@ pub const PLATFORMS: &[(&str, &str)] = &[
("checksums", "SHA256SUMS.txt"),
];
/// What a program's update check may give as its platform (desktop installations,
/// Android builds).
const LAUNCH_PLATFORMS: &[&str] = &[
"windows", "macos", "deb", "rpm", "arch", "aur", "appimage", "flatpak", "tarball", "other",
"android", "android-noengine",
];
/// New installations counted per address and day.
const NEW_INSTALLS_PER_ADDRESS: u32 = 5;
/// The latest release is asked from GitHub at most this often.
const RELEASE_TTL: Duration = Duration::from_secs(600);
/// GitHub did not answer: what is known serves on, and GitHub is asked again after this.
const RELEASE_RETRY: Duration = Duration::from_secs(60);
struct Config {
port: u16,
@ -113,7 +125,12 @@ struct AppState {
http: reqwest::Client,
/// The same without following redirects: to learn where GitHub sends a file.
direct: reqwest::Client,
/// The latest release and until when it is fresh.
release: tokio::sync::Mutex<Option<(Instant, Release)>>,
/// Held by the one request that asks GitHub; the others meanwhile get what is known.
asking: tokio::sync::Mutex<()>,
/// New installations counted today per address (a hash of it): a few per address.
new_installs: Mutex<(String, HashMap<String, u32>)>,
/// The owner's Telegram bot (notices and `/stat`), when configured.
bot: Option<Arc<telegram::Bot>>,
/// The visitor-key salt and the local day it belongs to.
@ -214,6 +231,8 @@ async fn main() {
.build()
.expect("http client"),
release: tokio::sync::Mutex::new(None),
asking: tokio::sync::Mutex::new(()),
new_installs: Mutex::new((String::new(), HashMap::new())),
bot: telegram::Bot::from_env(),
salt: Mutex::new((String::new(), 0)),
});
@ -490,12 +509,16 @@ async fn sitemap(State(state): State<Shared>) -> Response {
/// The latest release, from the cache or GitHub; the last good answer is kept when
/// GitHub fails.
async fn latest(state: &Shared) -> Option<Release> {
let mut cache = state.release.lock().await;
if let Some((at, r)) = cache.as_ref()
&& at.elapsed() < RELEASE_TTL
let known = || async { state.release.lock().await.as_ref().map(|(_, r)| r.clone()) };
if let Some((until, r)) = state.release.lock().await.as_ref()
&& Instant::now() < *until
{
return Some(r.clone());
}
// One request asks GitHub (up to 15 s); the others do not wait for it.
let Ok(_asking) = state.asking.try_lock() else {
return known().await;
};
let url = format!(
"https://api.github.com/repos/{}/releases/latest",
state.config.repo
@ -536,12 +559,18 @@ async fn latest(state: &Shared) -> Option<Release> {
})
}
.await;
let mut cache = state.release.lock().await;
match fetched {
Some(r) => {
*cache = Some((Instant::now(), r.clone()));
*cache = Some((Instant::now() + RELEASE_TTL, r.clone()));
Some(r)
}
None => cache.as_ref().map(|(_, r)| r.clone()),
None => {
if let Some((until, _)) = cache.as_mut() {
*until = Instant::now() + RELEASE_RETRY;
}
cache.as_ref().map(|(_, r)| r.clone())
}
}
}
@ -581,15 +610,36 @@ async fn api_update(
.filter(|v| !v.is_empty() && v.len() <= max && v.chars().all(ok))
.map(str::to_owned)
};
let install = token(&q.install, 64, |c| c.is_ascii_hexdigit() || c == '-');
let version = token(&q.version, 20, |c| c.is_ascii_digit() || c == '.');
let platform = token(&q.platform, 24, |c| c.is_ascii_lowercase() || c == '-');
// An id is 32 lowercase hex digits, a version "1.0.1", a platform one of the builds.
let install = token(&q.install, 32, |c| c.is_ascii_digit() || ('a'..='f').contains(&c))
.filter(|i| i.len() == 32);
let version = token(&q.version, 20, |c| c.is_ascii_digit() || c == '.')
.filter(|v| v.split('.').count() == 3 && v.split('.').all(|p| !p.is_empty()));
let platform = token(&q.platform, 24, |c| c.is_ascii_lowercase() || c == '-')
.filter(|p| LAUNCH_PLATFORMS.contains(&p.as_str()));
if let (Some(install), Some(version), Some(platform)) = (install, version, platform) {
let ip = client_ip(&state.config, peer, &headers);
if !is_local(ip) {
let (country, region, city) = locate(&state, ip);
let (country, _, _) = locate(&state, ip);
let day = chrono::Local::now().format("%Y-%m-%d").to_string();
// A few new installations a day per address (a family, a classroom); more is
// someone making ids up, and is not counted.
let address = visitor_key(&state, ip, "");
let notice = state.db.lock().ok().and_then(|db| {
let known: Option<i64> = db
.query_row("SELECT n FROM installs WHERE install = ?1", [&install], |r| r.get(0))
.ok();
if known.is_none() {
let mut seen = state.new_installs.lock().unwrap_or_else(|e| e.into_inner());
if seen.0 != day {
*seen = (day.clone(), HashMap::new());
}
let count = seen.1.entry(address).or_default();
if *count >= NEW_INSTALLS_PER_ADDRESS {
return None;
}
*count += 1;
}
// What this installation was before: its last version, and whether it
// already ran today.
let before: Option<String> = db
@ -611,9 +661,6 @@ async fn api_update(
VALUES (?1, ?2, ?3, ?4, ?5)",
rusqlite::params![day, install, version, platform, country],
);
let known: Option<i64> = db
.query_row("SELECT n FROM installs WHERE install = ?1", [&install], |r| r.get(0))
.ok();
let n = match known {
Some(n) => n,
None => {
@ -626,7 +673,8 @@ async fn api_update(
}
};
let label = platform_label(&platform);
let place = telegram::place(country.as_deref(), region.as_deref(), city.as_deref());
// The country only: what the texts about the update check promise.
let place = telegram::place(country.as_deref(), None, None);
let place = if place.is_empty() { String::new() } else { format!("\n{place}") };
match before {
_ if known.is_none() => {
@ -723,9 +771,18 @@ async fn download(
c.ua
],
);
// People only: not crawlers, not the owner, not the local network.
if kind == "human" && asset.platform != "checksums" {
let place = telegram::place(c.country.as_deref(), c.region.as_deref(), c.city.as_deref());
// People only: not crawlers, not the owner, not the local network; one notice a
// day per file and visitor (a download started again is not another person).
let again: bool = db
.query_row(
"SELECT COUNT(*) > 1 FROM downloads WHERE visitor = ?1 AND platform = ?2
AND date(ts, 'localtime') = date('now', 'localtime')",
rusqlite::params![c.visitor, asset.platform],
|r| r.get(0),
)
.unwrap_or(false);
if kind == "human" && asset.platform != "checksums" && !again {
let place = telegram::place(c.country.as_deref(), None, None);
let from = referrer.as_deref().map(|r| format!(" · с {r}")).unwrap_or_default();
let line = [place, from.trim_start_matches(" · ").to_owned()]
.into_iter()
@ -861,7 +918,7 @@ fn platform_label(platform: &str) -> &str {
"rpm" => "Linux · .rpm",
"arch" => "Linux · Arch",
"aur" => "Linux · AUR",
"source" => "Собрано из исходников",
"other" => "Другая установка",
"appimage" => "Linux · AppImage",
"flatpak" => "Linux · Flatpak",
"tarball" => "Linux · .tar.gz",