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

@ -6,8 +6,8 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
- The update check goes through the ChessPenguin site (GitHub when the site does not
answer), which counts installations that run: once a day, only a random number of the
installation, the version and the platform. With the check turned off, nothing is
sent. The site's statistics show installations by day, platform and version.
installation, the version and the platform. With the check at start turned off,
nothing is sent unless one checks by hand. The site's statistics show installations by day, platform and version.
## [1.0.0] — 2026-10-24

View file

@ -376,7 +376,7 @@
<string name="upd_copy">Kopieren</string>
<string name="upd_group">Updates</string>
<string name="upd_auto">Beim Start nach Updates suchen</string>
<string name="upd_auto_sub">Einmal am Tag fragt ChessPenguin seine Website nach der neuesten Version; die Website zählt laufende Installationen. Gesendet werden nur eine Zufallsnummer dieser Installation und die Version.</string>
<string name="upd_auto_sub">Einmal am Tag fragt ChessPenguin seine Website nach der neuesten Version; die Website zählt laufende Installationen. Gesendet werden nur eine Zufallsnummer dieser Installation, die Version und das System.</string>
<string name="upd_check_now">Jetzt prüfen</string>
<string name="upd_checking">Wird geprüft…</string>
<string name="upd_latest">Sie haben die neueste Version</string>

View file

@ -382,7 +382,7 @@
<string name="upd_copy">Copiar</string>
<string name="upd_group">Actualizaciones</string>
<string name="upd_auto">Buscar actualizaciones al iniciar</string>
<string name="upd_auto_sub">Una vez al día ChessPenguin pregunta a su sitio cuál es la última versión; el sitio cuenta las instalaciones en uso. Solo se envían un número aleatorio de esta instalación y la versión.</string>
<string name="upd_auto_sub">Una vez al día ChessPenguin pregunta a su sitio cuál es la última versión; el sitio cuenta las instalaciones en uso. Solo se envían un número aleatorio de esta instalación, la versión y el sistema.</string>
<string name="upd_check_now">Comprobar ahora</string>
<string name="upd_checking">Comprobando…</string>
<string name="upd_latest">Tienes la última versión</string>

View file

@ -382,7 +382,7 @@
<string name="upd_copy">Copier</string>
<string name="upd_group">Mises à jour</string>
<string name="upd_auto">Rechercher les mises à jour au démarrage</string>
<string name="upd_auto_sub">Une fois par jour, ChessPenguin demande à son site quelle est la dernière version ; le site compte les installations actives. Seuls un numéro aléatoire de cette installation et la version sont envoyés.</string>
<string name="upd_auto_sub">Une fois par jour, ChessPenguin demande à son site quelle est la dernière version ; le site compte les installations actives. Seuls un numéro aléatoire de cette installation, la version et le système sont envoyés.</string>
<string name="upd_check_now">Vérifier maintenant</string>
<string name="upd_checking">Vérification…</string>
<string name="upd_latest">Vous avez la dernière version</string>

View file

@ -382,7 +382,7 @@
<string name="upd_copy">Copia</string>
<string name="upd_group">Aggiornamenti</string>
<string name="upd_auto">Cerca aggiornamenti all’avvio</string>
<string name="upd_auto_sub">Una volta al giorno ChessPenguin chiede al suo sito qual è l’ultima versione; il sito conta le installazioni in uso. Vengono inviati solo un numero casuale di questa installazione e la versione.</string>
<string name="upd_auto_sub">Una volta al giorno ChessPenguin chiede al suo sito qual è l’ultima versione; il sito conta le installazioni in uso. Vengono inviati solo un numero casuale di questa installazione, la versione e il sistema.</string>
<string name="upd_check_now">Controlla ora</string>
<string name="upd_checking">Controllo in corso…</string>
<string name="upd_latest">Hai l’ultima versione</string>

View file

@ -375,7 +375,7 @@
<string name="upd_copy">Көшіру</string>
<string name="upd_group">Жаңартулар</string>
<string name="upd_auto">Іске қосқанда жаңартуларды тексеру</string>
<string name="upd_auto_sub">Күніне бір рет ChessPenguin өз сайтынан соңғы нұсқаны сұрайды; сайт жұмыс істеп тұрған орнатуларды санайды. Тек осы орнатудың кездейсоқ нөмірі мен нұсқа жіберіледі.</string>
<string name="upd_auto_sub">Күніне бір рет ChessPenguin өз сайтынан соңғы нұсқаны сұрайды; сайт жұмыс істеп тұрған орнатуларды санайды. Тек осы орнатудың кездейсоқ нөмірі, нұсқа және жүйе жіберіледі.</string>
<string name="upd_check_now">Қазір тексеру</string>
<string name="upd_checking">Тексерілуде…</string>
<string name="upd_latest">Сізде соңғы нұсқа</string>

View file

@ -381,7 +381,7 @@
<string name="upd_copy">Copiar</string>
<string name="upd_group">Atualizações</string>
<string name="upd_auto">Verificar atualizações ao iniciar</string>
<string name="upd_auto_sub">Uma vez por dia o ChessPenguin pergunta ao seu site qual é a versão mais recente; o site conta as instalações em uso. São enviados apenas um número aleatório desta instalação e a versão.</string>
<string name="upd_auto_sub">Uma vez por dia o ChessPenguin pergunta ao seu site qual é a versão mais recente; o site conta as instalações em uso. São enviados apenas um número aleatório desta instalação, a versão e o sistema.</string>
<string name="upd_check_now">Verificar agora</string>
<string name="upd_checking">Verificando…</string>
<string name="upd_latest">Você tem a versão mais recente</string>

View file

@ -388,7 +388,7 @@
<string name="upd_copy">Копировать</string>
<string name="upd_group">Обновления</string>
<string name="upd_auto">Проверять обновления при запуске</string>
<string name="upd_auto_sub">Раз в день ChessPenguin спрашивает у своего сайта, какая версия последняя; сайт считает работающие установки. Передаются только случайный номер этой установки и версия.</string>
<string name="upd_auto_sub">Раз в день ChessPenguin спрашивает у своего сайта, какая версия последняя; сайт считает работающие установки. Передаются только случайный номер этой установки, версия и система.</string>
<string name="upd_check_now">Проверить сейчас</string>
<string name="upd_checking">Проверяю…</string>
<string name="upd_latest">У вас последняя версия</string>

View file

@ -374,7 +374,7 @@
<string name="upd_copy">Nusxalash</string>
<string name="upd_group">Yangilanishlar</string>
<string name="upd_auto">Ishga tushganda yangilanishlarni tekshirish</string>
<string name="upd_auto_sub">ChessPenguin kuniga bir marta oʻz saytidan eng soʻnggi versiyani soʻraydi; sayt ishlayotgan oʻrnatmalarni sanaydi. Faqat shu oʻrnatmaning tasodifiy raqami va versiya yuboriladi.</string>
<string name="upd_auto_sub">ChessPenguin kuniga bir marta oʻz saytidan eng soʻnggi versiyani soʻraydi; sayt ishlayotgan oʻrnatmalarni sanaydi. Faqat shu oʻrnatmaning tasodifiy raqami, versiya va tizim yuboriladi.</string>
<string name="upd_check_now">Hozir tekshirish</string>
<string name="upd_checking">Tekshirilmoqda…</string>
<string name="upd_latest">Sizda eng soʻnggi versiya</string>

View file

@ -378,7 +378,7 @@
<string name="upd_copy">Copy</string>
<string name="upd_group">Updates</string>
<string name="upd_auto">Check for updates at start</string>
<string name="upd_auto_sub">Once a day ChessPenguin asks its site which version is the latest; the site counts installations that run. Only a random number of this installation and the version are sent.</string>
<string name="upd_auto_sub">Once a day ChessPenguin asks its site which version is the latest; the site counts installations that run. Only a random number of this installation, the version and the system are sent.</string>
<string name="upd_check_now">Check now</string>
<string name="upd_checking">Checking…</string>
<string name="upd_latest">You have the latest version</string>

View file

@ -242,7 +242,7 @@ impl Install {
Install::Arch => "arch",
Install::Aur => "aur",
Install::Flatpak => "flatpak",
Install::Other => "source",
Install::Other => "other",
}
}
}

View file

@ -15,3 +15,8 @@ STATS_PASSWORD=
GITHUB_REPO=vrubelroman/chessPenguin
# Take the visitor address from X-Forwarded-For / X-Real-IP (set by nginx).
TRUST_PROXY=1
# The owner's Telegram bot (downloads, installations, /stat): its token from @BotFather
# and the owner's chat id. Empty: no notices. One server per bot.
TELEGRAM_TOKEN=
TELEGRAM_CHAT=

View file

@ -73,18 +73,21 @@ The programs (desktop and Android, from 1.0.1) check for updates through `GET /a
instead of GitHub: the answer is GitHub's latest release (the fields the programs read:
`tag_name`, `html_url`, `assets[].name/browser_download_url/size`), and the call is counted
in the `launches` table — one row per installation and local day: the random id the
program made up, its version, platform (`windows`, `macos`, `deb`, `rpm`, `arch`, `aur`,
`appimage`, `flatpak`, `tarball`, `source`, `android`, `android-noengine`) and the country
of the address (the address is not kept). The local network is not counted. `/stats`
program made up (32 hex digits), its version, platform (`windows`, `macos`, `deb`, `rpm`,
`arch`, `aur`, `appimage`, `flatpak`, `tarball`, `other`, `android`, `android-noengine`) and
the country of the address (the address is not kept). The local network is not counted,
nor more than 5 new installations a day from one address. `/stats`
shows installations that ran today, in 7 and 30 days, in all, and new ones in 7 days, by
platform, and the versions of the last 7 days. A program that cannot reach the site asks
GitHub (uncounted); one with the update check turned off is not counted.
GitHub (uncounted); one with the update check at start turned off is counted only when
the user checks by hand.
## Telegram
With `TELEGRAM_TOKEN` (the owner's bot) and `TELEGRAM_CHAT` (the owner's chat id) in
`.env`, the site writes to the owner: «⬇️ Скачали …» for a person's download (not
crawlers, the owner or the local network), «🆕 Новая установка №N» for an installation's
`.env`, the site writes to the owner (with the country only): «⬇️ Скачали …» for a
person's download (not crawlers, the owner or the local network; once a day per file and
visitor), «🆕 Новая установка №N» for an installation's
first run, «⬆️ Обновилась …» when it runs a new version, «▶️ Запуск …» when it runs on a
new day (once a day at most). `/stat` answers with today and all time: downloads,
installations that ran and new ones, active in 7 and 30 days, by platform. Only the

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",

View file

@ -60,6 +60,12 @@ impl Bot {
.send()
.await;
let updates: Value = match got {
// 401: a wrong token; 409: another server listens to this bot.
Ok(r) if !r.status().is_success() => {
eprintln!("telegram: getUpdates {}", r.status());
tokio::time::sleep(Duration::from_secs(60)).await;
continue;
}
Ok(r) => r.json().await.unwrap_or(Value::Null),
Err(e) => {
eprintln!("telegram: {}", e.without_url());