From e99719a2dd8720edda1ac0b993536b0823e7fbad Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 19:09:38 +0300 Subject: [PATCH 01/65] feat(homepage): show installed services from a server-side services.json MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The World Map, Kolibri and the Library/Maps/Admin links in the top menu always showed as "Installed", even when the device did not have them. - scripts/services.sh runs the scripts/services.d/.sh modules and writes /library/www/html/home/services.json: for each service whether it is installed, its URL and its Turkish/English label. A new service is a new module file. - Modules: kiwix, maps (IIAB osm-vector-maps), kolibri, iiab-admin. - install-homepage.sh calls it at the end. - Homepage: a missing item shows "Not installed yet"; a top menu link goes to the first installed service and is hidden when there is none. Without the file (older installs) nothing changes. Dünya Haritası, Kolibri ve üst menüdeki Kütüphane/Haritalar/Yönetim, cihazda olmasa da hep "Kurulu" görünüyordu. - scripts/services.sh, scripts/services.d/.sh modüllerini çalıştırıp /library/www/html/home/services.json yazar: her servis için kurulu mu, adresi, Türkçe/İngilizce adı. Yeni servis = yeni modül dosyası. - Modüller: kiwix, maps (IIAB osm-vector-maps), kolibri, iiab-admin. - install-homepage.sh sonunda çağırır. - Ana sayfa: kurulu olmayan öğe "Henüz yüklenmedi"; üst menü bağlantısı ilk kurulu servise gider, hiçbiri yoksa gizlenir. Dosya yoksa (eski kurulum) davranış aynı. --- scripts/install-homepage.sh | 2 ++ scripts/services.d/iiab-admin.sh | 4 +++ scripts/services.d/kiwix.sh | 5 ++++ scripts/services.d/kolibri.sh | 4 +++ scripts/services.d/maps.sh | 5 ++++ scripts/services.sh | 47 ++++++++++++++++++++++++++++++++ www/home/index.html | 38 ++++++++++++++++++++++---- 7 files changed, 99 insertions(+), 6 deletions(-) create mode 100644 scripts/services.d/iiab-admin.sh create mode 100644 scripts/services.d/kiwix.sh create mode 100644 scripts/services.d/kolibri.sh create mode 100644 scripts/services.d/maps.sh create mode 100755 scripts/services.sh diff --git a/scripts/install-homepage.sh b/scripts/install-homepage.sh index 3fbb2e9..993196e 100755 --- a/scripts/install-homepage.sh +++ b/scripts/install-homepage.sh @@ -13,5 +13,7 @@ if [ -f "$DST/index.html" ] && [ ! -f "$DST/index.html.iiab-original" ]; then cp "$DST/index.html" "$DST/index.html.iiab-original" fi cp "$SRC/index.html" "$SRC/acil.html" "$DST/" +# Ana sayfa yalnız kurulu servisleri (harita, Kolibri, yönetim) gösterir / the homepage only lists installed services +"$(dirname "$0")/services.sh" echo "Ana sayfa kuruldu / homepage installed: http://box.lan/home" echo "Geri almak için / to restore: sudo cp $DST/index.html.iiab-original $DST/index.html" diff --git a/scripts/services.d/iiab-admin.sh b/scripts/services.d/iiab-admin.sh new file mode 100644 index 0000000..bac8fa9 --- /dev/null +++ b/scripts/services.d/iiab-admin.sh @@ -0,0 +1,4 @@ +# shellcheck shell=bash disable=SC2034 # services.sh içine alınır / sourced by services.sh +# IIAB yönetim paneli (iiab-cmdsrv) / IIAB admin console (iiab-cmdsrv) +label_tr="IIAB yönetim paneli"; label_en="IIAB admin console"; url="/admin" +check(){ active iiab-cmdsrv; } diff --git a/scripts/services.d/kiwix.sh b/scripts/services.d/kiwix.sh new file mode 100644 index 0000000..487745e --- /dev/null +++ b/scripts/services.d/kiwix.sh @@ -0,0 +1,5 @@ +# shellcheck shell=bash disable=SC2034 # services.sh içine alınır / sourced by services.sh +# Kiwix kütüphanesi (Vikipedi ve diğer ZIM'ler) / Kiwix library (Wikipedia and other ZIMs) +# Pi: IIAB'nin kiwix-serve servisi; Docker: imajdaki kiwix-serve. / Pi: IIAB's kiwix-serve service; Docker: kiwix-serve in the image. +label_tr="Kütüphane"; label_en="Library"; url="/kiwix/" +check(){ active kiwix-serve || command -v kiwix-serve; } diff --git a/scripts/services.d/kolibri.sh b/scripts/services.d/kolibri.sh new file mode 100644 index 0000000..63da434 --- /dev/null +++ b/scripts/services.d/kolibri.sh @@ -0,0 +1,4 @@ +# shellcheck shell=bash disable=SC2034 # services.sh içine alınır / sourced by services.sh +# IIAB Kolibri (çevrimdışı dersler) / IIAB Kolibri (offline lessons) +label_tr="Kolibri"; label_en="Kolibri"; url="/kolibri" +check(){ active kolibri; } diff --git a/scripts/services.d/maps.sh b/scripts/services.d/maps.sh new file mode 100644 index 0000000..bbf3814 --- /dev/null +++ b/scripts/services.d/maps.sh @@ -0,0 +1,5 @@ +# shellcheck shell=bash disable=SC2034 # services.sh içine alınır / sourced by services.sh +# IIAB haritası (osm-vector-maps): /maps → /library/www/osm-vector-maps/viewer +# IIAB map (osm-vector-maps): /maps → /library/www/osm-vector-maps/viewer +label_tr="Harita"; label_en="Map"; url="/maps" +check(){ [ -d /library/www/osm-vector-maps/viewer ]; } diff --git a/scripts/services.sh b/scripts/services.sh new file mode 100755 index 0000000..285824d --- /dev/null +++ b/scripts/services.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Cihazdaki servisleri ana sayfanın ve yönetim panelinin okuduğu services.json'a yazar. +# Writes the services on this device to services.json, read by the homepage and the admin panel. +# +# Modüler: her servis scripts/services.d/.sh dosyasıdır. Yeni servis = yeni dosya. +# Modular: each service is a file scripts/services.d/.sh. A new service is a new file. +# Modül şunları tanımlar / a module defines: +# label_tr, label_en görünen ad / display name +# url servisin adresi / the service's address +# check() kuruluysa 0 döner / returns 0 when installed +# install-homepage.sh çağırır; Pi'de ve Docker'da aynı betik. / Called by install-homepage.sh; same script on the Pi and in Docker. +# +# Ortam / environment: WEB=/library/www/html +set -uo pipefail + +WEB="${WEB:-/library/www/html}" +OUT="$WEB/home/services.json" +DIR="$(cd "$(dirname "$0")" && pwd)/services.d" + +# Modüllerin kullanabileceği yardımcı / helper for modules +active(){ command -v systemctl >/dev/null && systemctl is-active --quiet "$1"; } +json(){ local s=${1//\/\\}; printf '"%s"' "${s//\"/\\\"}"; } + +items="" +summary="" +for mod in "$DIR"/*.sh; do + [ -f "$mod" ] || continue + name=$(basename "$mod" .sh) + # Her modül kendi alt kabuğunda; biri bozuksa diğerleri etkilenmez. + # Each module runs in its own subshell; a broken one does not affect the others. + line=$( + label_tr="$name"; label_en="$name"; url="" + check(){ return 1; } + # shellcheck source=/dev/null + . "$mod" + if check >/dev/null 2>&1; then installed=true; else installed=false; fi + printf '%s:{"installed":%s,"url":%s,"label":{"tr":%s,"en":%s}}' \ + "$(json "$name")" "$installed" "$(json "$url")" "$(json "$label_tr")" "$(json "$label_en")" + ) || continue + items+="${items:+,}$line" + case "$line" in *'"installed":true'*) summary+=" $name=var/yes";; *) summary+=" $name=yok/no";; esac +done + +mkdir -p "$WEB/home" +printf '{"checked":"%s","services":{%s}}\n' "$(date -Is)" "$items" > "$OUT.tmp" +chmod 644 "$OUT.tmp" && mv "$OUT.tmp" "$OUT" +echo "Servisler / services:$summary" diff --git a/www/home/index.html b/www/home/index.html index 1b079f0..a70ed1a 100644 --- a/www/home/index.html +++ b/www/home/index.html @@ -96,7 +96,7 @@
Çevrimdışı bilgi arşivi — internet olmasa da açık
@@ -146,6 +146,7 @@ zim: Kiwix dosya adının tarihsiz başı. Sayfa, cihazda hangi sürümün yüklü olduğunu Kiwix kataloğundan kendisi bulur. url: zim olmayan servisler için sabit adres. + service: services.json'daki ad (scripts/services.d/.sh modülü); kurulu değilse "henüz yüklenmedi". Cihazda bulunamayan ZIM'ler gri klasörle "henüz yüklenmedi" görünür. */ const CATS = [ { title:"Ansiklopedi", items:[ @@ -161,7 +162,7 @@ { name:"PhET Simülasyonları", desc:"Fizik, kimya ve matematik etkileşimli deneyleri.", lang:"TR", size:"~107 MB", zim:"phet_tr_all" }, ]}, { title:"Haritalar ve Navigasyon", items:[ - { name:"Dünya Haritası", desc:"Avrupa ve Orta Doğu sokak seviyesinde, dünyanın geri kalanı şehir seviyesinde.", lang:"—", size:"~40 GB", url:"/maps" }, + { name:"Dünya Haritası", desc:"Avrupa ve Orta Doğu sokak seviyesinde, dünyanın geri kalanı şehir seviyesinde.", lang:"—", size:"~40 GB", url:"/maps", service:"maps" }, ]}, { title:"Hayatta Kalma ve Hazırlık", items:[ { name:"Afet Sonrası Kitaplığı", desc:"Barınak, enerji, tarım ve yeniden yapılanma üzerine kitaplar.", lang:"EN", size:"~615 MB", zim:"zimgit-post-disaster_en", search:true }, @@ -191,7 +192,7 @@ { name:"Sürdürülebilirlik", desc:"Enerji, su ve kaynak tasarrufu.", lang:"EN", size:"—", zim:"sustainability.stackexchange.com_en_all" }, ]}, { title:"Eğitim", items:[ - { name:"Kolibri", desc:"Çevrimdışı dersler ve eğitim videoları.", lang:"—", size:"—", url:"/kolibri" }, + { name:"Kolibri", desc:"Çevrimdışı dersler ve eğitim videoları.", lang:"—", size:"—", url:"/kolibri", service:"kolibri" }, ]}, ]; @@ -214,7 +215,32 @@ }catch(e){ return null; } } -function render(books){ +/* Kurulu servisler: scripts/services.sh sunucuda yazar. Dosya yoksa (eski kurulum) hepsi var sayılır. + Installed services, written on the server by scripts/services.sh. Without the file (older installs) all are assumed present. */ +async function loadServices(){ + try{ + const r = await fetch("/home/services.json", {cache:"no-store"}); + return r.ok ? (await r.json()).services || null : null; + }catch(e){ return null; } +} +/* Servis kurulu mu: dosya ya da kayıt yoksa var sayılır (eski kurulum). / installed? assumed yes without the file or entry. */ +const svc = (services, name) => services && services[name]; +const has = (services, name) => { + if (!services || !name) return true; + const s = svc(services, name); + return s === undefined ? true : (typeof s === "object" ? s.installed !== false : s !== false); +}; + +function render(books, services){ + // Üst menü: data-service'teki ilk kurulu servise bağlanır, hiçbiri yoksa gizlenir (ör. Yönetim: HAS paneli, yoksa IIAB paneli). + // Top menu: links to the first installed service in data-service, hidden if none (e.g. Admin: HAS panel, else IIAB console). + for (const a of document.querySelectorAll("a[data-service]")) { + const name = a.dataset.service.split(" ").find(n => has(services, n) && (!services || svc(services, n) !== undefined)) + || (services ? null : a.dataset.service.split(" ")[0]); + if (!name) { a.hidden = true; continue; } + const s = svc(services, name); + if (s && typeof s === "object" && s.url) a.href = s.url; + } let html = "", ready = 0, total = 0; const used = new Set(); const sel = document.getElementById("book"); @@ -223,7 +249,7 @@ html += `${esc(c.title)}`; for (const i of c.items) { total++; - let url = i.url || null, status = i.url ? "Kurulu" : "Henüz yüklenmedi"; + let url = i.url && has(services, i.service) ? i.url : null, status = url ? "Kurulu" : "Henüz yüklenmedi"; if (i.zim) { if (books === null) { url = "/kiwix/"; status = "Kütüphaneden açın"; } else { @@ -292,7 +318,7 @@ box.hidden = false; }).catch(() => {}); -loadBooks().then(render); +Promise.all([loadBooks(), loadServices()]).then(([books, services]) => render(books, services)); From f0f24923c38b430b0e0e416d332741036b63c29e Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 19:08:48 +0300 Subject: [PATCH 02/65] feat(docker): add a multi-arch image with the homepage and Kiwix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One container for people without a Pi. Same layout as the Pi/IIAB install (/library/zims, /library/www/html), so install-homepage.sh, download-content.sh and verify-content.sh run unchanged. - Alpine 3.24.4, official static kiwix-tools 3.8.2 binaries (pinned version + SHA-256) - kiwix-serve and nginx run as a non-root user, read-only root filesystem - download-content.sh: the library rebuild command can be set with KIWIX_LIB_CMD (default iiab-make-kiwix-lib, same behaviour) - GitHub Actions: amd64 smoke test, then amd64/arm64/arm-v7/arm-v6/386 images to ghcr.io; weekly rebuild Pi'si olmayanlar için tek konteyner. Dizin düzeni Pi/IIAB kurulumuyla aynı (/library/zims, /library/www/html); install-homepage.sh, download-content.sh ve verify-content.sh değişmeden çalışır. - Alpine 3.24.4, kiwix-tools 3.8.2 resmî statik ikilileri (sürüm + SHA-256) - kiwix-serve ve nginx root olmayan kullanıcıyla, salt okunur kök dosya sistemi - download-content.sh: kütüphaneyi yenileyen komut KIWIX_LIB_CMD ile seçilebilir (varsayılan iiab-make-kiwix-lib, davranış aynı) - GitHub Actions: amd64 duman testi, ardından amd64/arm64/arm-v7/arm-v6/386 imajı ghcr.io'ya; haftalık yeniden derleme --- .dockerignore | 9 +++ .gitattributes | 3 +- .github/workflows/docker.yml | 117 +++++++++++++++++++++++++++++++++++ .gitignore | 3 + compose.yaml | 34 ++++++++++ docker/Dockerfile | 66 ++++++++++++++++++++ docker/README.md | 67 ++++++++++++++++++++ docker/entrypoint.sh | 32 ++++++++++ docker/kiwix-library.sh | 29 +++++++++ docker/nginx.conf | 54 ++++++++++++++++ scripts/download-content.sh | 9 ++- 11 files changed, 419 insertions(+), 4 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/docker.yml create mode 100644 compose.yaml create mode 100644 docker/Dockerfile create mode 100644 docker/README.md create mode 100644 docker/entrypoint.sh create mode 100644 docker/kiwix-library.sh create mode 100644 docker/nginx.conf diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c7082d2 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +# Docker derleme bağlamına girmesin: indirilen içerik (library/) GB'larca olabilir. +# Keep out of the Docker build context: downloaded content (library/) can be many GB. +.git +.github +library +assets +saglik +*.md +*.zip diff --git a/.gitattributes b/.gitattributes index b6639ec..1c9a020 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,4 +9,5 @@ *.css text eol=lf *.js text eol=lf *.json text eol=lf -*.md text eol=lf \ No newline at end of file +*.md text eol=lf +Dockerfile text eol=lf diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..3158732 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,117 @@ +name: Docker + +# Çok mimarili imajı derler, dener ve GitHub Container Registry'ye (ghcr.io) gönderir. +# Builds, tests and pushes the multi-architecture image to GitHub Container Registry (ghcr.io). +# PR'larda yalnız derlenir ve denenir, gönderilmez. / On pull requests it is only built and tested. +# Haftalık derleme Alpine güvenlik düzeltmelerini imaja alır. / The weekly build picks up Alpine security fixes. + +on: + push: + branches: [main] + tags: ['v*'] + paths: + - 'docker/**' + - 'compose.yaml' + - '.dockerignore' + - 'config/**' + - 'scripts/download-content.sh' + - 'scripts/verify-content.sh' + - 'www/**' + - '.github/workflows/docker.yml' + pull_request: + paths: + - 'docker/**' + - 'compose.yaml' + - '.dockerignore' + - 'config/**' + - 'scripts/download-content.sh' + - 'scripts/verify-content.sh' + - 'www/**' + - '.github/workflows/docker.yml' + schedule: + - cron: '23 4 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: docker-${{ github.ref }} + cancel-in-progress: true + +env: + PLATFORMS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6,linux/386 + +jobs: + image: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Imaj adı / image name + id: name + run: echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/has-disk" >> "$GITHUB_OUTPUT" + + - name: Dene (amd64) / test (amd64) + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + load: true + tags: has-disk:ci + no-cache: ${{ github.event_name == 'schedule' }} + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Duman testi / smoke test + run: | + mkdir -p "$RUNNER_TEMP/library" + docker run -d --name has -p 8080:8080 -v "$RUNNER_TEMP/library:/library" \ + --read-only --tmpfs /tmp --cap-drop ALL --cap-add SETUID --cap-add SETGID \ + --cap-add DAC_OVERRIDE --security-opt no-new-privileges:true has-disk:ci + for i in $(seq 1 30); do curl -fsS -o /dev/null http://127.0.0.1:8080/home/ && break; sleep 1; done + curl -fsS -o /dev/null http://127.0.0.1:8080/home/ + curl -fsS -o /dev/null http://127.0.0.1:8080/home/acil.html + curl -fsS -o /dev/null http://127.0.0.1:8080/kiwix/ + curl -fsS -o /dev/null 'http://127.0.0.1:8080/kiwix/catalog/v2/entries?count=-1' + test "$(docker exec has stat -c %U /proc/$(docker exec has pgrep -o kiwix-serve))" = has + docker logs has + docker rm -f has + + - uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 + id: meta + with: + images: ${{ steps.name.outputs.image }} + tags: | + type=raw,value=latest,enable={{is_default_branch}} + type=semver,pattern={{version}} + type=sha,format=short + + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + if: github.event_name != 'pull_request' + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Tüm mimariler / all platforms + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + platforms: ${{ env.PLATFORMS }} + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + sbom: true + provenance: mode=max + no-cache: ${{ github.event_name == 'schedule' }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.gitignore b/.gitignore index 7eb99cd..ec39107 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,6 @@ __MACOSX/ *.zip Claude outputs/ + +# Docker ile indirilen içerik / content downloaded with Docker +library/ diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..3b93dbe --- /dev/null +++ b/compose.yaml @@ -0,0 +1,34 @@ +# HAS_PrepperDisk: Docker ile çalıştırma (Raspberry Pi olmayan cihazlar). Ayrıntı: docker/README.md +# HAS_PrepperDisk: run with Docker (devices without a Raspberry Pi). Details: docker/README.md +# +# docker compose up -d # başlat / start +# docker compose exec has /opt/has/scripts/download-content.sh # içerik indir / download content +# +# Ana sayfa / homepage: http://:8080/home/ + +services: + has: + image: ghcr.io/schematrix/has-disk:latest + build: + context: . + dockerfile: docker/Dockerfile + ports: + - "${HAS_PORT:-8080}:8080" + volumes: + # ZIM dosyaları burada tutulur; harici disk için tam yol yazın (ör. /mnt/ssd/library). + # ZIM files are kept here; use a full path for an external disk (e.g. /mnt/ssd/library). + - "${HAS_LIBRARY:-./library}:/library" + restart: unless-stopped + read_only: true + tmpfs: + - /tmp + cap_drop: + - ALL + cap_add: + # su-exec ile root olmayan kullanıcıya geçiş + indirme betiğinin /library'ye yazması için. + # Switching to the non-root user with su-exec + the download script writing to /library. + - SETUID + - SETGID + - DAC_OVERRIDE + security_opt: + - no-new-privileges:true diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..4c463e7 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,66 @@ +# syntax=docker/dockerfile:1 +# HAS_PrepperDisk Docker imajı: ana sayfa + Kiwix (kiwix-serve), Raspberry Pi olmayan cihazlar için. +# HAS_PrepperDisk Docker image: homepage + Kiwix (kiwix-serve), for devices without a Raspberry Pi. +# +# Platformlar / platforms: linux/amd64, linux/arm64, linux/arm/v7, linux/arm/v6, linux/386 +# Taban imaj sürüme, Kiwix ikili dosyaları sürüm + SHA-256 ile sabit. +# The base image is pinned by version, the Kiwix binaries by version + SHA-256. + +# ---------------------------------------------------------------- kiwix-tools (resmî, statik / official, static) +FROM alpine:3.24.4 AS kiwix +ARG TARGETARCH +ARG TARGETVARIANT +ARG KIWIX_VERSION=3.8.2 +# hadolint ignore=DL3018 +RUN apk add --no-cache curl tar +# SHA-256 değerleri download.kiwix.org'daki arşivlerden hesaplandı (yayımlanan .md5 ile de eşleşiyor). +# SHA-256 values computed from the archives on download.kiwix.org (they also match the published .md5). +RUN set -eu; \ + case "${TARGETARCH}${TARGETVARIANT:+/${TARGETVARIANT}}" in \ + amd64) a=x86_64; s=b0ae98dd344aa0469a15ab42feff6d5aafb79541a82fb4e2647c74b073123815 ;; \ + arm64|arm64/v8) a=aarch64; s=a9898fc5363437327350db669bbc03dcc7ecfd498dae727d7184bebe77019514 ;; \ + arm/v7|arm/v6) a=armv6; s=a5f24ea7ae1e9f7bee1b1e73d14639f3b77dc9583922ab902c84856d8d567c61 ;; \ + 386) a=i586; s=1083134a4b81364508f60babaeee1d359ebf8597a6e6a6ed128fd75055b9f3cc ;; \ + *) echo "desteklenmeyen mimari / unsupported platform: ${TARGETARCH} ${TARGETVARIANT}" >&2; exit 1 ;; \ + esac; \ + d="kiwix-tools_linux-${a}-${KIWIX_VERSION}"; \ + curl -fsSL -o /tmp/kiwix.tar.gz "https://download.kiwix.org/release/kiwix-tools/${d}.tar.gz"; \ + printf '%s %s\n' "${s}" /tmp/kiwix.tar.gz > /tmp/kiwix.sha256; \ + sha256sum -c /tmp/kiwix.sha256; \ + mkdir /out; \ + tar -xzf /tmp/kiwix.tar.gz -C /out --strip-components=1 "${d}/kiwix-serve" "${d}/kiwix-manage" + +# ---------------------------------------------------------------- imaj / image +FROM alpine:3.24.4 +# apk upgrade: taban imajdan sonra çıkan güvenlik düzeltmeleri her derlemede gelir. +# apk upgrade: security fixes released after the base image are picked up on every build. +# apk paketleri bilerek sabitlenmedi: sabit sürüm Alpine deposundan kalkınca derleme bozulur, güvenlik düzeltmesi gelmez. +# apk packages are deliberately not pinned: a pinned version breaks the build once Alpine drops it and blocks security fixes. +# hadolint ignore=DL3018 +RUN apk upgrade --no-cache \ + && apk add --no-cache bash coreutils curl findmnt nginx su-exec tini util-linux-misc wget \ + && adduser -D -H -u 1000 -s /sbin/nologin has + +COPY --from=kiwix --chmod=0755 /out/kiwix-serve /out/kiwix-manage /usr/local/bin/ +COPY config/ /opt/has/config/ +COPY scripts/ /opt/has/scripts/ +COPY www/ /opt/has/www/ +COPY docker/nginx.conf /etc/nginx/nginx.conf +COPY --chmod=0755 docker/entrypoint.sh /usr/local/bin/has-entrypoint +COPY --chmod=0755 docker/kiwix-library.sh /usr/local/bin/kiwix-library +# Windows'ta CRLF ile çıkarılmış bir kopyadan derlenirse betikler "bash\r" hatası verir; satır sonları LF'ye çevrilir. +# When built from a Windows checkout with CRLF line endings the scripts fail with "bash\r"; line endings are normalized to LF. +RUN find /opt/has /etc/nginx/nginx.conf /usr/local/bin/has-entrypoint /usr/local/bin/kiwix-library -type f \ + \( -name '*.sh' -o -name '*.conf' -o -name '*.html' -o -name 'has-entrypoint' -o -name 'kiwix-library' \) \ + -exec sed -i 's/\r$//' {} + \ + && chmod 0755 /opt/has/scripts/*.sh + +# download-content.sh indirme sonunda Kiwix kütüphanesini bu komutla yeniler (IIAB'de iiab-make-kiwix-lib). +# download-content.sh rebuilds the Kiwix library with this command at the end (iiab-make-kiwix-lib on IIAB). +ENV KIWIX_LIB_CMD=kiwix-library +WORKDIR /opt/has +VOLUME /library +EXPOSE 8080 +HEALTHCHECK --interval=60s --timeout=5s --start-period=20s \ + CMD curl -fsS -o /dev/null http://127.0.0.1:8080/home/ || exit 1 +ENTRYPOINT ["/sbin/tini", "-g", "--", "has-entrypoint"] diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 0000000..246734f --- /dev/null +++ b/docker/README.md @@ -0,0 +1,67 @@ +# Docker + +## Türkçe + +Raspberry Pi'si olmayanlar için: HAS ana sayfası, acil durum sayfası ve Kiwix (Vikipedi ve diğer ZIM arşivleri) tek bir konteynerde. Dizüstü, masaüstü, NAS, eski bilgisayar ya da Pi'de çalışır. + +**Platformlar:** `linux/amd64`, `linux/arm64` (Pi 3/4/5 64 bit), `linux/arm/v7` ve `linux/arm/v6` (32 bit Pi, Pi Zero), `linux/386`. + +**İmajda olanlar:** ana sayfa (`www/home`), Kiwix (`kiwix-serve` 3.8.2), içerik indirme (`scripts/download-content.sh`, aynı `config/content.conf` listesi) ve çevrimdışı doğrulama (`scripts/verify-content.sh`). +**Olmayanlar:** Wi-Fi hotspot, captive portal, Kolibri, harita, IIAB yönetim paneli. Bunlar Pi kurulumunda (`install.sh`) var. Docker'da cihazınızın kendi ağı kullanılır. + +### Kullanım + +```sh +git clone https://github.com/schematrix/HAS_Disk.git && cd HAS_Disk +docker compose up -d +docker compose exec has /opt/has/scripts/download-content.sh # içerik indir (yarıda kalırsa tekrar çalıştır) +``` + +Ana sayfa: `http://:8080/home/`. İndirme bitince Kiwix yeni içeriği yeniden başlatmadan görür. + +- **Harici disk:** `HAS_LIBRARY=/mnt/ssd/library docker compose up -d` (ya da `.env` dosyasına `HAS_LIBRARY=...`). +- **Port:** `HAS_PORT=80 docker compose up -d`. +- **Kendi listeniz:** listeyi `library/` içine koyup `docker compose exec has /opt/has/scripts/download-content.sh /library/benim-listem.conf`. +- **Doğrulama:** `docker compose exec has /opt/has/scripts/verify-content.sh`. +- **Güncelleme:** `docker compose pull && docker compose up -d`. +- **Kendiniz derlemek için:** `docker compose up -d --build`. + +### Güvenlik + +- Taban imaj Alpine 3.24.4 (sürüme sabit); Kiwix resmî statik ikili dosyaları sürüm + SHA-256 ile doğrulanıyor. +- Her derlemede `apk upgrade` çalışır; GitHub Actions imajı her hafta yeniden derler, güvenlik düzeltmeleri böyle gelir. +- `kiwix-serve` ve `nginx` root olmayan `has` kullanıcısıyla çalışır; kök dosya sistemi salt okunur, yetkilerin hepsi düşürülür (yalnız kullanıcı değişimi ve `/library`'ye yazma için üç yetki kalır), erişim kaydı tutulmaz. +- Kiwix yalnız konteyner içinde (127.0.0.1) dinler, dışarıya nginx üzerinden açılır. + +## English + +For people without a Raspberry Pi: the HAS homepage, the emergency page and Kiwix (Wikipedia and other ZIM archives) in one container. Runs on a laptop, desktop, NAS, old PC or a Pi. + +**Platforms:** `linux/amd64`, `linux/arm64` (64-bit Pi 3/4/5), `linux/arm/v7` and `linux/arm/v6` (32-bit Pi, Pi Zero), `linux/386`. + +**Included:** homepage (`www/home`), Kiwix (`kiwix-serve` 3.8.2), content download (`scripts/download-content.sh`, same `config/content.conf` list) and offline verification (`scripts/verify-content.sh`). +**Not included:** Wi-Fi hotspot, captive portal, Kolibri, maps, IIAB admin console. These come with the Pi install (`install.sh`). With Docker the device's own network is used. + +### Usage + +```sh +git clone https://github.com/schematrix/HAS_Disk.git && cd HAS_Disk +docker compose up -d +docker compose exec has /opt/has/scripts/download-content.sh # download content (re-run to resume) +``` + +Homepage: `http://:8080/home/`. Kiwix picks up new content without a restart. + +- **External disk:** `HAS_LIBRARY=/mnt/ssd/library docker compose up -d` (or put `HAS_LIBRARY=...` in `.env`). +- **Port:** `HAS_PORT=80 docker compose up -d`. +- **Your own list:** put it in `library/` and run `docker compose exec has /opt/has/scripts/download-content.sh /library/my-list.conf`. +- **Verify:** `docker compose exec has /opt/has/scripts/verify-content.sh`. +- **Update:** `docker compose pull && docker compose up -d`. +- **Build it yourself:** `docker compose up -d --build`. + +### Security + +- Base image Alpine 3.24.4 (pinned by version); the official static Kiwix binaries are checked against a pinned SHA-256. +- `apk upgrade` runs on every build and GitHub Actions rebuilds the image weekly, so security fixes get in. +- `kiwix-serve` and `nginx` run as the non-root `has` user; the root filesystem is read-only, all capabilities are dropped except three (switching user and writing to `/library`), no access log. +- Kiwix only listens inside the container (127.0.0.1) and is exposed through nginx. diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh new file mode 100644 index 0000000..524860b --- /dev/null +++ b/docker/entrypoint.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Konteyner başlangıcı: Kiwix kütüphanesini hazırlar, kiwix-serve ve nginx'i root olmayan "has" kullanıcısıyla başlatır. +# Container start: prepares the Kiwix library, starts kiwix-serve and nginx as the non-root "has" user. +set -euo pipefail + +# Dizin düzeni Pi/IIAB kurulumuyla aynı: içerik /library/zims, web /library/www/html. +# Aynı betikler (install-homepage.sh, download-content.sh, ...) iki kurulumda da değişmeden çalışır. +# Same layout as the Pi/IIAB install: content in /library/zims, web root /library/www/html. +# The same scripts (install-homepage.sh, download-content.sh, ...) run unchanged on both. +LIB=/library/zims/library.xml +mkdir -p /library/zims/content /library/www/html/home +# Ana sayfa her açılışta imajdaki sürümle güncellenir (Pi'de install-homepage.sh'yi elle çalıştırmakla aynı). +# The homepage is refreshed from the image on every start (same as running install-homepage.sh on the Pi). +/opt/has/scripts/install-homepage.sh >/dev/null +# Kütüphane yoksa var olan ZIM'lerden oluştur (ilk açılış ya da elle kopyalanmış ZIM'ler). +# Build the library from existing ZIMs if it is missing (first start or ZIMs copied by hand). +[ -s "$LIB" ] || kiwix-library + +# --monitorLibrary: download-content.sh kütüphaneyi yenileyince kiwix-serve yeniden başlatmadan görür. +# --monitorLibrary: kiwix-serve picks up the library rebuilt by download-content.sh without a restart. +su-exec has kiwix-serve --library --monitorLibrary --address=127.0.0.1 --port=8081 \ + --urlRootLocation=/kiwix "$LIB" & +su-exec has nginx -e stderr -g 'daemon off;' & + +# Biri durursa konteyner de durur, Docker yeniden başlatır (restart: unless-stopped). +# If either process stops, the container stops and Docker restarts it (restart: unless-stopped). +set +e +wait -n +status=$? +mapfile -t pids < <(jobs -p) +kill "${pids[@]}" 2>/dev/null +exit "$status" diff --git a/docker/kiwix-library.sh b/docker/kiwix-library.sh new file mode 100644 index 0000000..8d53997 --- /dev/null +++ b/docker/kiwix-library.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# /library/zims/content altındaki ZIM'lerden Kiwix kütüphanesini (library.xml) yeniden oluşturur. +# Rebuilds the Kiwix library (library.xml) from the ZIMs under /library/zims/content. +# Dosya aynı klasörde hazırlanıp tek adımda değiştirilir; kiwix-serve yarım dosya görmez. +# The file is built in the same directory and swapped in one step, so kiwix-serve never sees a partial file. +set -euo pipefail +shopt -s nullglob + +ZIM_DIR="${ZIM_DIR:-/library/zims/content}" +LIB="${KIWIX_LIBRARY:-/library/zims/library.xml}" + +mkdir -p -- "$ZIM_DIR" "$(dirname -- "$LIB")" +tmp=$(mktemp "$LIB.XXXXXX") +trap 'rm -f -- "$tmp"' EXIT +printf '\n\n\n' > "$tmp" + +count=0 +for zim in "$ZIM_DIR"/*.zim; do + if kiwix-manage "$tmp" add "$zim"; then + count=$((count + 1)) + else + echo "!! kütüphaneye eklenemedi / could not add: $zim" >&2 + fi +done + +chmod 0644 "$tmp" +mv -f -- "$tmp" "$LIB" +trap - EXIT +echo "Kiwix kütüphanesi / library: $count ZIM ($LIB)" diff --git a/docker/nginx.conf b/docker/nginx.conf new file mode 100644 index 0000000..8aa3584 --- /dev/null +++ b/docker/nginx.conf @@ -0,0 +1,54 @@ +# HAS_PrepperDisk Docker: ana sayfa + /kiwix/ (kiwix-serve 127.0.0.1:8081). +# HAS_PrepperDisk Docker: homepage + /kiwix/ (kiwix-serve on 127.0.0.1:8081). +# nginx root olmayan kullanıcıyla çalışır; yazdığı her şey /tmp altında (salt okunur kök dosya sistemi). +# nginx runs as a non-root user; everything it writes goes under /tmp (read-only root filesystem). + +worker_processes 1; +pid /tmp/nginx.pid; +error_log stderr warn; + +events { + worker_connections 512; +} + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + charset utf-8; + sendfile on; + server_tokens off; + # Yönlendirmeler göreli: konteyner başka bir porta (ör. 18080) eşlense de doğru adrese gider. + # Relative redirects: they stay correct when the container is published on another port (e.g. 18080). + absolute_redirect off; + # Erişim kaydı tutulmaz / no access log + access_log off; + + client_body_temp_path /tmp/nginx-client; + proxy_temp_path /tmp/nginx-proxy; + fastcgi_temp_path /tmp/nginx-fastcgi; + uwsgi_temp_path /tmp/nginx-uwsgi; + scgi_temp_path /tmp/nginx-scgi; + + server { + listen 8080; + # IIAB ile aynı web kökü / same web root as IIAB + root /library/www/html; + + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy no-referrer always; + + location = / { + return 302 /home/; + } + + location / { + try_files $uri $uri/ =404; + } + + location /kiwix/ { + proxy_pass http://127.0.0.1:8081; + proxy_set_header Host $host; + proxy_http_version 1.1; + } + } +} diff --git a/scripts/download-content.sh b/scripts/download-content.sh index d9670ea..5803fe3 100755 --- a/scripts/download-content.sh +++ b/scripts/download-content.sh @@ -13,6 +13,8 @@ # # Kullanım / usage: sudo ./scripts/download-content.sh [config-dosyası] # Ortam / environment: DEST=/library/zims/content RESERVE_GB=5 (boş bırakılacak pay / headroom to keep free) +# KIWIX_LIB_CMD=iiab-make-kiwix-lib (Kiwix kütüphanesini yenileyen komut; Docker imajında kiwix-library) +# KIWIX_LIB_CMD=iiab-make-kiwix-lib (command that rebuilds the Kiwix library; kiwix-library in the Docker image) set -uo pipefail [ "$EUID" -eq 0 ] || { echo "sudo ile çalıştır / run with sudo" >&2; exit 1; } @@ -136,13 +138,14 @@ while read -r folder prefix _; do done < "$CONF" echo ">> Kiwix kütüphanesi güncelleniyor / rebuilding Kiwix library" -if command -v iiab-make-kiwix-lib >/dev/null; then - iiab-make-kiwix-lib || { +KIWIX_LIB_CMD="${KIWIX_LIB_CMD:-iiab-make-kiwix-lib}" +if command -v "$KIWIX_LIB_CMD" >/dev/null; then + "$KIWIX_LIB_CMD" || { printf '!! Kiwix kütüphanesi güncellenemedi / Kiwix library rebuild failed (exit %s)\n' "$?" >&2 failed=1 } else - echo "!! iiab-make-kiwix-lib yok / not found. Internet-in-a-Box kurulu mu? / is Internet-in-a-Box installed?"; failed=1 + echo "!! $KIWIX_LIB_CMD yok / not found. Internet-in-a-Box kurulu mu? / is Internet-in-a-Box installed?"; failed=1 fi exit $failed From 608b68e0d6a2422d8b3fed1aa31d7bb825880c40 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 20:32:40 +0300 Subject: [PATCH 03/65] feat(admin): add the Go admin panel with first-run setup, login and downloads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A single static Go binary under admin/ (has-admin), standard library only. Shared by the Pi and Docker installs; it runs the scripts in the repo. - First run: the admin account is created with a setup code written to the logs; no default password in the repo - has-admin reset-password : reset a password from the command line - PBKDF2-SHA256 (600,000 iterations), login with a POST body, HttpOnly + SameSite=Strict session cookie, growing wait after 5 failed attempts, JSON + same-origin check (CSRF) - Status (disk, ZIMs), pick and download from content.conf, verify, delete; one job at a time, output shown on the page - Errors as error_code + English message; the page is Turkish/English - Docker: cross-compile stage (tests run during the build), nginx /admin, CI smoke test admin/ altında tek statik Go dosyası (has-admin), yalnız standart kütüphane. Pi ve Docker için ortak; repodaki betikleri çağırır. - İlk kurulum: kayıtlara yazılan kurulum koduyla yönetici hesabı; repoda varsayılan şifre yok - has-admin reset-password : komut satırından şifre sıfırlama - PBKDF2-SHA256 (600.000 yineleme), giriş POST gövdesiyle, oturum çerezi HttpOnly + SameSite=Strict, 5 hatalı denemeden sonra artan bekleme, JSON + aynı kaynak kontrolü (CSRF) - Durum (disk, ZIM), content.conf'tan seçip indirme, doğrulama, silme; tek iş, çıktı sayfada - Hatalar error_code + İngilizce message; sayfa Türkçe/İngilizce - Docker: çapraz derleme aşaması (testler derlemede), nginx /admin, CI duman testi --- .gitattributes | 2 + .github/workflows/docker.yml | 8 + admin/auth.go | 261 +++++++++++++++++++ admin/auth_test.go | 61 +++++ admin/errors_test.go | 29 +++ admin/go.mod | 3 + admin/handlers.go | 444 ++++++++++++++++++++++++++++++++ admin/jobs.go | 141 ++++++++++ admin/main.go | 114 ++++++++ admin/web/index.html | 250 ++++++++++++++++++ docker/Dockerfile | 14 + docker/README.md | 20 +- docker/entrypoint.sh | 3 + docker/nginx.conf | 9 + scripts/services.d/has-admin.sh | 4 + 15 files changed, 1361 insertions(+), 2 deletions(-) create mode 100644 admin/auth.go create mode 100644 admin/auth_test.go create mode 100644 admin/errors_test.go create mode 100644 admin/go.mod create mode 100644 admin/handlers.go create mode 100644 admin/jobs.go create mode 100644 admin/main.go create mode 100644 admin/web/index.html create mode 100644 scripts/services.d/has-admin.sh diff --git a/.gitattributes b/.gitattributes index 1c9a020..275b4ea 100644 --- a/.gitattributes +++ b/.gitattributes @@ -11,3 +11,5 @@ *.json text eol=lf *.md text eol=lf Dockerfile text eol=lf +*.go text eol=lf +go.mod text eol=lf diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 3158732..655704c 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -11,6 +11,9 @@ on: tags: ['v*'] paths: - 'docker/**' + - 'admin/**' + - 'scripts/services.sh' + - 'scripts/install-homepage.sh' - 'compose.yaml' - '.dockerignore' - 'config/**' @@ -21,6 +24,9 @@ on: pull_request: paths: - 'docker/**' + - 'admin/**' + - 'scripts/services.sh' + - 'scripts/install-homepage.sh' - 'compose.yaml' - '.dockerignore' - 'config/**' @@ -81,6 +87,8 @@ jobs: curl -fsS -o /dev/null http://127.0.0.1:8080/home/acil.html curl -fsS -o /dev/null http://127.0.0.1:8080/kiwix/ curl -fsS -o /dev/null 'http://127.0.0.1:8080/kiwix/catalog/v2/entries?count=-1' + curl -fsS http://127.0.0.1:8080/admin/api/session | grep -q '"setup":true' + docker logs has 2>&1 | grep -q 'first-run setup code' test "$(docker exec has stat -c %U /proc/$(docker exec has pgrep -o kiwix-serve))" = has docker logs has docker rm -f has diff --git a/admin/auth.go b/admin/auth.go new file mode 100644 index 0000000..db25060 --- /dev/null +++ b/admin/auth.go @@ -0,0 +1,261 @@ +package main + +// Kullanıcılar, şifreler, oturumlar ve giriş denemesi sınırı. +// Users, passwords, sessions and login attempt limits. + +import ( + "crypto/pbkdf2" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base32" + "encoding/base64" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +// PBKDF2-SHA256; yineleme sayısı OWASP önerisine göre. / iteration count per the OWASP recommendation. +const pbkdf2Iter = 600_000 + +type user struct { + Name string `json:"name"` + Salt string `json:"salt"` + Hash string `json:"hash"` + Iter int `json:"iter"` +} + +type store struct { + mu sync.Mutex + path string + Users []user `json:"users"` +} + +func (s *store) load() error { + b, err := os.ReadFile(s.path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + return json.Unmarshal(b, s) +} + +func (s *store) saveLocked() error { + b, err := json.MarshalIndent(s, "", " ") + if err != nil { + return err + } + tmp := s.path + ".tmp" + if err := os.WriteFile(tmp, b, 0o600); err != nil { + return err + } + return os.Rename(tmp, s.path) +} + +func (s *store) hasUsers() bool { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.Users) > 0 +} + +func hashPassword(pw string, salt []byte, iter int) ([]byte, error) { + return pbkdf2.Key(sha256.New, pw, salt, iter, 32) +} + +func validName(n string) bool { + if len(n) < 2 || len(n) > 32 { + return false + } + for _, r := range n { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.') { + return false + } + } + return true +} + +var ( + errInvalidName = errors.New("invalid user name: 2-32 characters, letters, digits, . _ -") + errShortPassword = errors.New("password must be at least 10 characters") +) + +// setPassword kullanıcıyı ekler ya da şifresini değiştirir. / adds the user or changes its password. +func (s *store) setPassword(name, pw string) error { + if !validName(name) { + return errInvalidName + } + if len(pw) < 10 { + return errShortPassword + } + salt := make([]byte, 16) + if _, err := rand.Read(salt); err != nil { + return err + } + h, err := hashPassword(pw, salt, pbkdf2Iter) + if err != nil { + return err + } + u := user{Name: name, Salt: base64.StdEncoding.EncodeToString(salt), Hash: base64.StdEncoding.EncodeToString(h), Iter: pbkdf2Iter} + s.mu.Lock() + defer s.mu.Unlock() + for i := range s.Users { + if s.Users[i].Name == name { + s.Users[i] = u + return s.saveLocked() + } + } + s.Users = append(s.Users, u) + return s.saveLocked() +} + +func (s *store) check(name, pw string) bool { + s.mu.Lock() + var u *user + for i := range s.Users { + if s.Users[i].Name == name { + c := s.Users[i] + u = &c + } + } + s.mu.Unlock() + if u == nil { + // Var olmayan kullanıcıda da aynı süre harcansın / spend the same time for unknown users + hashPassword(pw, make([]byte, 16), pbkdf2Iter) + return false + } + salt, err1 := base64.StdEncoding.DecodeString(u.Salt) + want, err2 := base64.StdEncoding.DecodeString(u.Hash) + if err1 != nil || err2 != nil { + return false + } + got, err := hashPassword(pw, salt, u.Iter) + return err == nil && subtle.ConstantTimeCompare(got, want) == 1 +} + +func randomToken(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return base64.RawURLEncoding.EncodeToString(b) +} + +// randomPassword okunması kolay, 20 karakterlik şifre. / easy to read, 20-character password. +func randomPassword() string { + b := make([]byte, 15) + if _, err := rand.Read(b); err != nil { + panic(err) + } + s := strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b)) + return s[0:5] + "-" + s[5:10] + "-" + s[10:15] + "-" + s[15:20] +} + +// setupCode ilk kurulum kodunu dosyadan okur, yoksa üretir. Kodu bilen kişi ilk kullanıcıyı oluşturur; +// Wi-Fi'a bağlanan herkes değil. / reads the first-run setup code, creating it if missing. Whoever knows +// the code creates the first user, not just anyone on the Wi-Fi. +func setupCode(dir string) (string, error) { + p := filepath.Join(dir, "setup-code") + if b, err := os.ReadFile(p); err == nil && len(strings.TrimSpace(string(b))) > 0 { + return strings.TrimSpace(string(b)), nil + } + code := randomPassword()[:11] + return code, os.WriteFile(p, []byte(code+"\n"), 0o600) +} + +// ---------------------------------------------------------------- oturumlar / sessions + +type sessions struct { + mu sync.Mutex + m map[string]session +} + +type session struct { + user string + expires time.Time +} + +const sessionTTL = 12 * time.Hour + +func (s *sessions) create(user string) string { + t := randomToken(32) + s.mu.Lock() + defer s.mu.Unlock() + now := time.Now() + for k, v := range s.m { + if now.After(v.expires) { + delete(s.m, k) + } + } + s.m[t] = session{user: user, expires: now.Add(sessionTTL)} + return t +} + +func (s *sessions) get(t string) (string, bool) { + s.mu.Lock() + defer s.mu.Unlock() + v, ok := s.m[t] + if !ok || time.Now().After(v.expires) { + delete(s.m, t) + return "", false + } + return v.user, true +} + +func (s *sessions) drop(t string) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.m, t) +} + +// ---------------------------------------------------------------- giriş sınırı / login limit + +// Aynı adresten 5 hatalı denemeden sonra bekleme süresi her seferinde iki katına çıkar (en çok 15 dk). +// After 5 failed attempts from one address the wait doubles each time (at most 15 min). +type limiter struct { + mu sync.Mutex + m map[string]*attempts +} + +type attempts struct { + fails int + until time.Time +} + +func (l *limiter) blocked(ip string) time.Duration { + l.mu.Lock() + defer l.mu.Unlock() + if a, ok := l.m[ip]; ok && time.Now().Before(a.until) { + return time.Until(a.until).Round(time.Second) + } + return 0 +} + +func (l *limiter) fail(ip string) { + l.mu.Lock() + defer l.mu.Unlock() + a, ok := l.m[ip] + if !ok { + a = &attempts{} + l.m[ip] = a + } + a.fails++ + if a.fails >= 5 { + d := time.Minute << min(a.fails-5, 4) + if d > 15*time.Minute { + d = 15 * time.Minute + } + a.until = time.Now().Add(d) + } +} + +func (l *limiter) ok(ip string) { + l.mu.Lock() + defer l.mu.Unlock() + delete(l.m, ip) +} diff --git a/admin/auth_test.go b/admin/auth_test.go new file mode 100644 index 0000000..1b360e4 --- /dev/null +++ b/admin/auth_test.go @@ -0,0 +1,61 @@ +package main + +import ( + "path/filepath" + "testing" +) + +func TestPasswordRoundTrip(t *testing.T) { + st := &store{path: filepath.Join(t.TempDir(), "users.json")} + if err := st.setPassword("burak", "kisa"); err == nil { + t.Fatal("kısa şifre kabul edildi / short password accepted") + } + if err := st.setPassword("bad name!", "uzun-bir-sifre-123"); err == nil { + t.Fatal("geçersiz ad kabul edildi / invalid name accepted") + } + if err := st.setPassword("burak", "uzun-bir-sifre-123"); err != nil { + t.Fatal(err) + } + if !st.check("burak", "uzun-bir-sifre-123") { + t.Fatal("doğru şifre reddedildi / correct password rejected") + } + if st.check("burak", "yanlis-sifre-12345") || st.check("yok", "uzun-bir-sifre-123") { + t.Fatal("yanlış giriş kabul edildi / wrong login accepted") + } + // Dosyadan yeniden yükleme / reload from file + st2 := &store{path: st.path} + if err := st2.load(); err != nil || !st2.check("burak", "uzun-bir-sifre-123") { + t.Fatal("yeniden yüklenen kayıt çalışmıyor / reloaded store fails", err) + } +} + +func TestZimName(t *testing.T) { + for _, ok := range []string{"wikipedia_tr_all_maxi_2026-09.zim", "a.zim"} { + if !zimName.MatchString(ok) { + t.Errorf("reddedildi / rejected: %s", ok) + } + } + for _, bad := range []string{"../x.zim", "a/b.zim", "x.zim.sha256", "x.txt", ".zim/../../etc"} { + if zimName.MatchString(bad) { + t.Errorf("kabul edildi / accepted: %s", bad) + } + } +} + +func TestLimiter(t *testing.T) { + l := &limiter{m: map[string]*attempts{}} + for i := 0; i < 4; i++ { + l.fail("1.2.3.4") + } + if l.blocked("1.2.3.4") != 0 { + t.Fatal("4 hatada engellendi / blocked after 4 failures") + } + l.fail("1.2.3.4") + if l.blocked("1.2.3.4") == 0 { + t.Fatal("5 hatada engellenmedi / not blocked after 5 failures") + } + l.ok("1.2.3.4") + if l.blocked("1.2.3.4") != 0 { + t.Fatal("başarılı girişten sonra engel sürüyor / still blocked after success") + } +} diff --git a/admin/errors_test.go b/admin/errors_test.go new file mode 100644 index 0000000..32085ba --- /dev/null +++ b/admin/errors_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "os" + "regexp" + "testing" +) + +// Koddaki her hata kodunun İngilizce mesajı ve sayfada iki dilde karşılığı olmalı. +// Every error code used in the code needs an English message and an entry in both page languages. +func TestErrorCodesComplete(t *testing.T) { + src, _ := os.ReadFile("handlers.go") + page, _ := os.ReadFile("web/index.html") + used := map[string]bool{} + for _, m := range regexp.MustCompile(`fail\(w, [^,]+, "([a-z_]+)"\)`).FindAllStringSubmatch(string(src), -1) { + used[m[1]] = true + } + for _, c := range []string{"busy", "invalid_name", "short_password", "server_error", "too_many_attempts"} { + used[c] = true + } + for c := range used { + if errorMessages[c] == "" { + t.Errorf("message yok / missing message: %s", c) + } + if n := len(regexp.MustCompile(`\b`+c+`:"`).FindAll(page, -1)); n < 2 { + t.Errorf("sayfada iki dilde yok / not in both page languages: %s (%d)", c, n) + } + } +} diff --git a/admin/go.mod b/admin/go.mod new file mode 100644 index 0000000..786796e --- /dev/null +++ b/admin/go.mod @@ -0,0 +1,3 @@ +module github.com/schematrix/HAS_Disk/admin + +go 1.26 diff --git a/admin/handlers.go b/admin/handlers.go new file mode 100644 index 0000000..bf5a8f0 --- /dev/null +++ b/admin/handlers.go @@ -0,0 +1,444 @@ +package main + +// HTTP uçları. Sayfa tek HTML (web/index.html); veri JSON uçlarından gelir. +// HTTP endpoints. The page is one HTML file (web/index.html); data comes from the JSON endpoints. + +import ( + "bufio" + "crypto/subtle" + "embed" + "encoding/json" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "regexp" + "sort" + "strings" + "syscall" + "time" +) + +//go:embed web/index.html +var webFS embed.FS + +const cookieName = "has_admin" + +type app struct { + cfg config + st *store + ses *sessions + lim *limiter + work *job +} + +func newApp(cfg config, st *store) *app { + return &app{cfg: cfg, st: st, + ses: &sessions{m: map[string]session{}}, + lim: &limiter{m: map[string]*attempts{}}, + work: newJob(cfg.data)} +} + +func (a *app) routes() http.Handler { + p := a.cfg.prefix + mux := http.NewServeMux() + mux.HandleFunc("GET "+p+"/{$}", a.page) + mux.HandleFunc("GET "+p, func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, p+"/", http.StatusFound) }) + mux.HandleFunc("GET "+p+"/api/session", a.sessionInfo) + mux.HandleFunc("POST "+p+"/api/setup", a.post(a.setup)) + mux.HandleFunc("POST "+p+"/api/login", a.post(a.login)) + mux.HandleFunc("POST "+p+"/api/logout", a.post(a.logout)) + mux.HandleFunc("GET "+p+"/api/status", a.auth(a.status)) + mux.HandleFunc("GET "+p+"/api/job", a.auth(a.jobStatus)) + mux.HandleFunc("POST "+p+"/api/download", a.post(a.auth(a.download))) + mux.HandleFunc("POST "+p+"/api/verify", a.post(a.auth(a.verify))) + mux.HandleFunc("POST "+p+"/api/delete", a.post(a.auth(a.remove))) + mux.HandleFunc("POST "+p+"/api/job/stop", a.post(a.auth(a.stopJob))) + return headers(mux) +} + +func headers(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("Referrer-Policy", "no-referrer") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'") + h.ServeHTTP(w, r) + }) +} + +func writeJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(code) + json.NewEncoder(w).Encode(v) +} + +// Hata yanıtı: {"error_code": "...", "message": "..."}. Sayfa error_code'a göre seçili dilde metin gösterir +// (web/index.html, T.*.errors); message İngilizce açıklamadır (curl, kayıt, yeni istemciler için). +// Error response: {"error_code": "...", "message": "..."}. The page localizes by error_code +// (web/index.html, T.*.errors); message is a plain English explanation (for curl, logs, other clients). +var errorMessages = map[string]string{ + "json_required": "The request body must be JSON.", + "cross_origin": "Requests from another origin are not allowed.", + "login_required": "Log in first.", + "setup_done": "Setup is already done.", + "bad_request": "Bad request.", + "wrong_setup_code": "Wrong setup code.", + "wrong_login": "Wrong user name or password.", + "too_many_attempts": "Too many attempts; try again later.", + "content_unreadable": "Could not read config/content.conf.", + "choose_content": "Choose content to download.", + "not_in_list": "This item is not in config/content.conf.", + "invalid_file": "Invalid file name.", + "file_not_found": "File not found.", + "busy": "Another job is running.", + "invalid_name": "User name must be 2-32 characters: letters, digits, . _ -", + "short_password": "Password must be at least 10 characters.", + "server_error": "Server error.", +} + +func fail(w http.ResponseWriter, status int, code string) { + writeJSON(w, status, map[string]string{"error_code": code, "message": errorMessages[code]}) +} + +func failWait(w http.ResponseWriter, d time.Duration) { + writeJSON(w, http.StatusTooManyRequests, map[string]any{ + "error_code": "too_many_attempts", "message": errorMessages["too_many_attempts"], "wait": int(d.Seconds())}) +} + +// clientIP: nginx arkasındayken (bağlantı 127.0.0.1'den) X-Real-IP'ye güvenilir. +// clientIP: X-Real-IP is trusted only when the connection comes from nginx on 127.0.0.1. +func clientIP(r *http.Request) string { + host, _, _ := net.SplitHostPort(r.RemoteAddr) + if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { + if x := r.Header.Get("X-Real-IP"); x != "" { + return x + } + } + return host +} + +// post: veri değiştiren her istek JSON gövdeli ve aynı kaynaktan olmalı (CSRF'e karşı). +// post: every data-changing request must carry a JSON body and come from the same origin (against CSRF). +func (a *app) post(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { + fail(w, http.StatusUnsupportedMediaType, "json_required") + return + } + if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" { + fail(w, http.StatusForbidden, "cross_origin") + return + } + if o := r.Header.Get("Origin"); o != "" { + if u, err := url.Parse(o); err != nil || u.Host != r.Host { + fail(w, http.StatusForbidden, "cross_origin") + return + } + } + r.Body = http.MaxBytesReader(w, r.Body, 64<<10) + next(w, r) + } +} + +func (a *app) currentUser(r *http.Request) (string, bool) { + c, err := r.Cookie(cookieName) + if err != nil { + return "", false + } + return a.ses.get(c.Value) +} + +func (a *app) auth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if _, ok := a.currentUser(r); !ok { + fail(w, http.StatusUnauthorized, "login_required") + return + } + next(w, r) + } +} + +func (a *app) page(w http.ResponseWriter, r *http.Request) { + b, _ := webFS.ReadFile("web/index.html") + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write(b) +} + +// ---------------------------------------------------------------- oturum / session + +func (a *app) sessionInfo(w http.ResponseWriter, r *http.Request) { + u, _ := a.currentUser(r) + writeJSON(w, 200, map[string]any{"setup": !a.st.hasUsers(), "user": u}) +} + +type credentials struct { + User string `json:"user"` + Password string `json:"password"` + Code string `json:"code"` +} + +func (a *app) setCookie(w http.ResponseWriter, r *http.Request, user string) { + http.SetCookie(w, &http.Cookie{ + Name: cookieName, Value: a.ses.create(user), Path: a.cfg.prefix, + HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil, + MaxAge: int(sessionTTL.Seconds()), + }) +} + +func (a *app) setup(w http.ResponseWriter, r *http.Request) { + ip := clientIP(r) + if d := a.lim.blocked(ip); d > 0 { + failWait(w, d) + return + } + if a.st.hasUsers() { + fail(w, http.StatusConflict, "setup_done") + return + } + var c credentials + if err := json.NewDecoder(r.Body).Decode(&c); err != nil { + fail(w, http.StatusBadRequest, "bad_request") + return + } + code, err := setupCode(a.cfg.data) + if err != nil || subtle.ConstantTimeCompare([]byte(strings.TrimSpace(c.Code)), []byte(code)) != 1 { + a.lim.fail(ip) + fail(w, http.StatusForbidden, "wrong_setup_code") + return + } + if err := a.st.setPassword(c.User, c.Password); err != nil { + fail(w, http.StatusBadRequest, errCode(err)) + return + } + os.Remove(filepath.Join(a.cfg.data, "setup-code")) + a.lim.ok(ip) + a.setCookie(w, r, c.User) + writeJSON(w, 200, map[string]string{"user": c.User}) +} + +func (a *app) login(w http.ResponseWriter, r *http.Request) { + ip := clientIP(r) + if d := a.lim.blocked(ip); d > 0 { + failWait(w, d) + return + } + var c credentials + if err := json.NewDecoder(r.Body).Decode(&c); err != nil { + fail(w, http.StatusBadRequest, "bad_request") + return + } + if !a.st.check(c.User, c.Password) { + a.lim.fail(ip) + fail(w, http.StatusUnauthorized, "wrong_login") + return + } + a.lim.ok(ip) + a.setCookie(w, r, c.User) + writeJSON(w, 200, map[string]string{"user": c.User}) +} + +func (a *app) logout(w http.ResponseWriter, r *http.Request) { + if c, err := r.Cookie(cookieName); err == nil { + a.ses.drop(c.Value) + } + http.SetCookie(w, &http.Cookie{Name: cookieName, Value: "", Path: a.cfg.prefix, MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteStrictMode}) + writeJSON(w, 200, map[string]bool{"ok": true}) +} + +// ---------------------------------------------------------------- içerik / content + +type contentItem struct { + Folder string `json:"folder"` + Prefix string `json:"prefix"` + Note string `json:"note"` + Installed string `json:"installed,omitempty"` + Size int64 `json:"size,omitempty"` + line string +} + +var zimName = regexp.MustCompile(`^[A-Za-z0-9._-]+\.zim$`) + +// readContent config/content.conf'u okur (betikle aynı biçim: klasör, ön ek, # not). +// readContent reads config/content.conf (same format as the script: folder, prefix, # note). +func (a *app) readContent() ([]contentItem, error) { + f, err := os.Open(filepath.Join(a.cfg.repo, "config", "content.conf")) + if err != nil { + return nil, err + } + defer f.Close() + var items []contentItem + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimRight(sc.Text(), "\r") + body, note, _ := strings.Cut(line, "#") + fields := strings.Fields(body) + if len(fields) < 2 { + continue + } + items = append(items, contentItem{Folder: fields[0], Prefix: fields[1], Note: strings.TrimSpace(note), line: line}) + } + return items, sc.Err() +} + +type zimFile struct { + Name string `json:"name"` + Size int64 `json:"size"` + Sha256 bool `json:"sha256"` +} + +func (a *app) zims() []zimFile { + entries, _ := os.ReadDir(a.cfg.zimDir()) + var out []zimFile + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".zim") { + continue + } + fi, err := e.Info() + if err != nil { + continue + } + _, err = os.Stat(filepath.Join(a.cfg.zimDir(), e.Name()+".sha256")) + out = append(out, zimFile{Name: e.Name(), Size: fi.Size(), Sha256: err == nil}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} + +func (a *app) status(w http.ResponseWriter, r *http.Request) { + var st syscall.Statfs_t + disk := map[string]uint64{} + if syscall.Statfs(a.cfg.library, &st) == nil { + disk["total"] = st.Blocks * uint64(st.Bsize) + disk["free"] = st.Bavail * uint64(st.Bsize) + } + zims := a.zims() + items, err := a.readContent() + if err != nil { + fail(w, 500, "content_unreadable") + return + } + for i := range items { + for _, z := range zims { + if strings.HasPrefix(z.Name, items[i].Prefix+"_") { + items[i].Installed, items[i].Size = z.Name, z.Size + } + } + } + var services map[string]any + if b, err := os.ReadFile(filepath.Join(a.cfg.library, "www", "html", "home", "services.json")); err == nil { + json.Unmarshal(b, &services) + } + writeJSON(w, 200, map[string]any{ + "checked": time.Now().Format(time.RFC3339), + "disk": disk, + "zims": zims, + "content": items, + "services": services, + }) +} + +func (a *app) jobStatus(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, a.work.state()) } + +func (a *app) script(name string) string { return filepath.Join(a.cfg.repo, "scripts", name) } + +// download yalnız content.conf'taki satırları seçtirir; kullanıcıdan gelen metin betiğe gitmez. +// download only lets you pick lines from content.conf; no user-supplied text reaches the script. +func (a *app) download(w http.ResponseWriter, r *http.Request) { + var req struct { + Prefixes []string `json:"prefixes"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || len(req.Prefixes) == 0 { + fail(w, http.StatusBadRequest, "choose_content") + return + } + items, err := a.readContent() + if err != nil { + fail(w, 500, "content_unreadable") + return + } + want := map[string]bool{} + for _, p := range req.Prefixes { + want[p] = true + } + var lines []string + for _, it := range items { + if want[it.Prefix] { + lines = append(lines, it.line) + } + } + if len(lines) != len(want) { + fail(w, http.StatusBadRequest, "not_in_list") + return + } + tmp, err := os.CreateTemp(a.cfg.data, "secim-*.conf") + if err != nil { + fail(w, 500, "server_error") + return + } + tmp.WriteString(strings.Join(lines, "\n") + "\n") + tmp.Close() + if err := a.work.start("download", func() { os.Remove(tmp.Name()) }, "bash", a.script("download-content.sh"), tmp.Name()); err != nil { + os.Remove(tmp.Name()) + fail(w, http.StatusConflict, errCode(err)) + return + } + writeJSON(w, 202, map[string]bool{"started": true}) +} + +func (a *app) verify(w http.ResponseWriter, r *http.Request) { + if err := a.work.start("verify", nil, "bash", a.script("verify-content.sh"), a.cfg.zimDir()); err != nil { + fail(w, http.StatusConflict, errCode(err)) + return + } + writeJSON(w, 202, map[string]bool{"started": true}) +} + +func (a *app) remove(w http.ResponseWriter, r *http.Request) { + var req struct { + File string `json:"file"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || !zimName.MatchString(req.File) { + fail(w, http.StatusBadRequest, "invalid_file") + return + } + if a.work.state().Running { + fail(w, http.StatusConflict, "busy") + return + } + p := filepath.Join(a.cfg.zimDir(), req.File) + if _, err := os.Stat(p); err != nil { + fail(w, http.StatusNotFound, "file_not_found") + return + } + if err := os.Remove(p); err != nil { + fail(w, 500, "server_error") + return + } + os.Remove(p + ".sha256") + lib := env("KIWIX_LIB_CMD", "iiab-make-kiwix-lib") + if path, err := exec.LookPath(lib); err == nil { + a.work.start("library", nil, path) + } + writeJSON(w, 200, map[string]string{"removed": req.File}) +} + +func (a *app) stopJob(w http.ResponseWriter, r *http.Request) { + writeJSON(w, 200, map[string]bool{"stopped": a.work.stop()}) +} + +// errCode bilinen hataları sabit koda çevirir. / maps known errors to fixed codes. +func errCode(err error) string { + switch err { + case errBusy: + return "busy" + case errInvalidName: + return "invalid_name" + case errShortPassword: + return "short_password" + } + return "server_error" +} diff --git a/admin/jobs.go b/admin/jobs.go new file mode 100644 index 0000000..c96d430 --- /dev/null +++ b/admin/jobs.go @@ -0,0 +1,141 @@ +package main + +// Betik çalıştırma: aynı anda tek iş, çıktının son satırları bellekte ve son-is.log dosyasında. +// Running scripts: one job at a time, the last output lines in memory and in last-job.log. + +import ( + "bufio" + "context" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "sync" + "syscall" + "time" +) + +const keepLines = 400 + +type job struct { + mu sync.Mutex + name string + running bool + started time.Time + finished time.Time + exitCode int + lines []string + cancel context.CancelFunc + logPath string +} + +type jobState struct { + Name string `json:"name"` + Running bool `json:"running"` + Started string `json:"started,omitempty"` + Finished string `json:"finished,omitempty"` + ExitCode int `json:"exitCode"` + Lines []string `json:"lines"` +} + +var errBusy = errors.New("another job is running") + +func (j *job) state() jobState { + j.mu.Lock() + defer j.mu.Unlock() + s := jobState{Name: j.name, Running: j.running, ExitCode: j.exitCode, Lines: append([]string(nil), j.lines...)} + if !j.started.IsZero() { + s.Started = j.started.Format(time.RFC3339) + } + if !j.finished.IsZero() { + s.Finished = j.finished.Format(time.RFC3339) + } + return s +} + +func (j *job) add(line string) { + j.mu.Lock() + defer j.mu.Unlock() + j.lines = append(j.lines, line) + if len(j.lines) > keepLines { + j.lines = j.lines[len(j.lines)-keepLines:] + } +} + +// start betiği arka planda çalıştırır; cleanup iş bitince çağrılır (geçici dosyaları silmek için). +// start runs the script in the background; cleanup runs when the job ends (to remove temp files). +func (j *job) start(name string, cleanup func(), argv ...string) error { + j.mu.Lock() + if j.running { + j.mu.Unlock() + return errBusy + } + ctx, cancel := context.WithCancel(context.Background()) + cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) + // Kendi süreç grubu: durdurunca alt süreçler (curl) de durur. / own process group so children (curl) stop too. + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) } + cmd.WaitDelay = 10 * time.Second + pr, pw := io.Pipe() + cmd.Stdout, cmd.Stderr = pw, pw + cmd.Stdin = nil + if err := cmd.Start(); err != nil { + cancel() + j.mu.Unlock() + return err + } + j.name, j.running, j.started, j.finished, j.exitCode, j.lines, j.cancel = name, true, time.Now(), time.Time{}, 0, nil, cancel + j.mu.Unlock() + + logf, _ := os.OpenFile(j.logPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + go func() { + sc := bufio.NewScanner(pr) + sc.Buffer(make([]byte, 64<<10), 1<<20) + for sc.Scan() { + line := sc.Text() + j.add(line) + if logf != nil { + logf.WriteString(line + "\n") + } + } + }() + go func() { + err := cmd.Wait() + pw.Close() + code := 0 + if err != nil { + code = -1 + var ee *exec.ExitError + if errors.As(err, &ee) { + code = ee.ExitCode() + } + } + if cleanup != nil { + cleanup() + } + time.Sleep(100 * time.Millisecond) // okuyucu son satırları alsın / let the reader take the last lines + if logf != nil { + logf.Close() + } + j.mu.Lock() + j.running, j.finished, j.exitCode = false, time.Now(), code + j.mu.Unlock() + cancel() + }() + return nil +} + +func (j *job) stop() bool { + j.mu.Lock() + defer j.mu.Unlock() + if !j.running || j.cancel == nil { + return false + } + j.cancel() + return true +} + +func newJob(dataDir string) *job { + return &job{logPath: filepath.Join(dataDir, "last-job.log")} +} diff --git a/admin/main.go b/admin/main.go new file mode 100644 index 0000000..a39b1d4 --- /dev/null +++ b/admin/main.go @@ -0,0 +1,114 @@ +// has-admin: HAS_PrepperDisk yönetim paneli (Pi ve Docker için ortak). +// has-admin: HAS_PrepperDisk admin panel (shared by the Pi and Docker installs). +// +// Panel kendi başına iş yapmaz; repodaki betikleri çağırır (download-content.sh, verify-content.sh). +// The panel does no work by itself; it runs the scripts in the repo (download-content.sh, verify-content.sh). +// +// Kullanım / usage: +// +// has-admin sunucuyu başlat / start the server +// has-admin reset-password şifreyi sıfırla, yeni şifreyi yaz / reset the password, print the new one +// has-admin setup-code ilk kurulum kodunu göster / show the first-run setup code +// +// Ayarlar ortam değişkenleriyle / settings via environment variables: +// +// HAS_ADMIN_ADDR 127.0.0.1:8090 yalnız nginx arkasından / only behind nginx +// HAS_ADMIN_PREFIX /admin adres öneki / URL prefix +// HAS_ADMIN_DATA /library/has-admin kullanıcılar, kurulum kodu, son iş kaydı / users, setup code, last job log +// HAS_REPO /opt/has scripts/ ve config/ klasörlerinin olduğu yer / where scripts/ and config/ live +// HAS_LIBRARY /library +package main + +import ( + "fmt" + "log" + "net/http" + "os" + "path/filepath" + "time" +) + +type config struct { + addr, prefix, data, repo, library string +} + +func env(k, def string) string { + if v := os.Getenv(k); v != "" { + return v + } + return def +} + +func loadConfig() config { + return config{ + addr: env("HAS_ADMIN_ADDR", "127.0.0.1:8090"), + prefix: env("HAS_ADMIN_PREFIX", "/admin"), + data: env("HAS_ADMIN_DATA", "/library/has-admin"), + repo: env("HAS_REPO", "/opt/has"), + library: env("HAS_LIBRARY", "/library"), + } +} + +func (c config) zimDir() string { return filepath.Join(c.library, "zims", "content") } + +func main() { + log.SetFlags(0) + cfg := loadConfig() + if err := os.MkdirAll(cfg.data, 0o700); err != nil { + log.Fatalf("HATA / ERROR: %s oluşturulamadı / could not be created: %v", cfg.data, err) + } + st := &store{path: filepath.Join(cfg.data, "users.json")} + if err := st.load(); err != nil { + log.Fatalf("HATA / ERROR: %v", err) + } + + args := os.Args[1:] + if len(args) > 0 { + switch args[0] { + case "reset-password": + if len(args) != 2 { + log.Fatal("kullanım / usage: has-admin reset-password ") + } + pw := randomPassword() + if err := st.setPassword(args[1], pw); err != nil { + log.Fatalf("HATA / ERROR: %v", err) + } + fmt.Printf("Yeni şifre / new password (%s): %s\n", args[1], pw) + fmt.Println("Açık oturumlar panel yeniden başlayınca kapanır / open sessions end when the panel restarts") + return + case "setup-code": + if st.hasUsers() { + fmt.Println("Kullanıcı zaten var; kurulum kodu gerekmiyor / a user already exists; no setup code needed") + return + } + code, err := setupCode(cfg.data) + if err != nil { + log.Fatalf("HATA / ERROR: %v", err) + } + fmt.Println(code) + return + default: + log.Fatalf("bilinmeyen komut / unknown command: %s", args[0]) + } + } + + if !st.hasUsers() { + code, err := setupCode(cfg.data) + if err != nil { + log.Fatalf("HATA / ERROR: %v", err) + } + log.Printf("İlk kurulum: %s/ adresinde kullanıcı oluşturun. Kurulum kodu / first-run setup code: %s", cfg.prefix, code) + } + + app := newApp(cfg, st) + srv := &http.Server{ + Addr: cfg.addr, + Handler: app.routes(), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 60 * time.Second, + MaxHeaderBytes: 16 << 10, + } + log.Printf("has-admin %s üzerinde / listening on %s (önek / prefix %s)", cfg.addr, cfg.addr, cfg.prefix) + log.Fatal(srv.ListenAndServe()) +} diff --git a/admin/web/index.html b/admin/web/index.html new file mode 100644 index 0000000..9a06f14 --- /dev/null +++ b/admin/web/index.html @@ -0,0 +1,250 @@ + + + + + +HAS_PrepperDisk · Yönetim / Admin + + + +
+
+

HAS_PrepperDisk ·

+
+ +
+
+
+ + + + + + + +
+ + + + diff --git a/docker/Dockerfile b/docker/Dockerfile index 4c463e7..56c572a 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -30,6 +30,19 @@ RUN set -eu; \ mkdir /out; \ tar -xzf /tmp/kiwix.tar.gz -C /out --strip-components=1 "${d}/kiwix-serve" "${d}/kiwix-manage" +# ---------------------------------------------------------------- yönetim paneli (Go) / admin panel (Go) +# Derleyicinin kendi mimarisinde çalışır, hedef mimariye çapraz derler (QEMU gerekmez). +# Runs on the build machine's architecture and cross-compiles for the target (no QEMU needed). +FROM --platform=$BUILDPLATFORM golang:1.27.3-alpine3.24 AS admin +ARG TARGETARCH +ARG TARGETVARIANT +WORKDIR /src +COPY admin/ ./ +# Derlemeden önce testler / tests before the build +RUN go vet ./... && go test ./... +RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} GOARM=${TARGETVARIANT#v} \ + go build -trimpath -ldflags "-s -w" -o /out/has-admin . + # ---------------------------------------------------------------- imaj / image FROM alpine:3.24.4 # apk upgrade: taban imajdan sonra çıkan güvenlik düzeltmeleri her derlemede gelir. @@ -42,6 +55,7 @@ RUN apk upgrade --no-cache \ && adduser -D -H -u 1000 -s /sbin/nologin has COPY --from=kiwix --chmod=0755 /out/kiwix-serve /out/kiwix-manage /usr/local/bin/ +COPY --from=admin --chmod=0755 /out/has-admin /usr/local/bin/has-admin COPY config/ /opt/has/config/ COPY scripts/ /opt/has/scripts/ COPY www/ /opt/has/www/ diff --git a/docker/README.md b/docker/README.md index 246734f..9a23722 100644 --- a/docker/README.md +++ b/docker/README.md @@ -7,7 +7,7 @@ Raspberry Pi'si olmayanlar için: HAS ana sayfası, acil durum sayfası ve Kiwix **Platformlar:** `linux/amd64`, `linux/arm64` (Pi 3/4/5 64 bit), `linux/arm/v7` ve `linux/arm/v6` (32 bit Pi, Pi Zero), `linux/386`. **İmajda olanlar:** ana sayfa (`www/home`), Kiwix (`kiwix-serve` 3.8.2), içerik indirme (`scripts/download-content.sh`, aynı `config/content.conf` listesi) ve çevrimdışı doğrulama (`scripts/verify-content.sh`). -**Olmayanlar:** Wi-Fi hotspot, captive portal, Kolibri, harita, IIAB yönetim paneli. Bunlar Pi kurulumunda (`install.sh`) var. Docker'da cihazınızın kendi ağı kullanılır. +**Olmayanlar:** Wi-Fi hotspot, captive portal, Kolibri, harita, IIAB yönetim paneli (yerine HAS yönetim paneli var). Bunlar Pi kurulumunda (`install.sh`) var. Docker'da cihazınızın kendi ağı kullanılır. ### Kullanım @@ -26,6 +26,14 @@ Ana sayfa: `http://:8080/home/`. İndirme bitince Kiwix yeni içeriği - **Güncelleme:** `docker compose pull && docker compose up -d`. - **Kendiniz derlemek için:** `docker compose up -d --build`. +### Yönetim paneli + +`http://:8080/admin/`: disk ve ZIM durumu, `config/content.conf` listesinden seçip indirme (ilerleme sayfada görünür), doğrulama, silme. Türkçe ve İngilizce. + +- **İlk kurulum:** ilk açılışta kurulum kodu kayıtlara yazılır (`docker compose logs has`); kodu bilen kişi yönetici hesabını oluşturur. Repoda varsayılan şifre yok. +- **Şifre sıfırlama:** `docker compose exec has has-admin reset-password ` yeni şifreyi yazar. +- Giriş POST gövdesiyle yapılır, oturum çerezi `HttpOnly` + `SameSite=Strict`; 5 hatalı denemeden sonra bekleme süresi uzar. Panel betikleri çağırır, kendisi indirme yapmaz. + ### Güvenlik - Taban imaj Alpine 3.24.4 (sürüme sabit); Kiwix resmî statik ikili dosyaları sürüm + SHA-256 ile doğrulanıyor. @@ -40,7 +48,7 @@ For people without a Raspberry Pi: the HAS homepage, the emergency page and Kiwi **Platforms:** `linux/amd64`, `linux/arm64` (64-bit Pi 3/4/5), `linux/arm/v7` and `linux/arm/v6` (32-bit Pi, Pi Zero), `linux/386`. **Included:** homepage (`www/home`), Kiwix (`kiwix-serve` 3.8.2), content download (`scripts/download-content.sh`, same `config/content.conf` list) and offline verification (`scripts/verify-content.sh`). -**Not included:** Wi-Fi hotspot, captive portal, Kolibri, maps, IIAB admin console. These come with the Pi install (`install.sh`). With Docker the device's own network is used. +**Not included:** Wi-Fi hotspot, captive portal, Kolibri, maps, IIAB admin console (the HAS admin panel replaces it). These come with the Pi install (`install.sh`). With Docker the device's own network is used. ### Usage @@ -59,6 +67,14 @@ Homepage: `http://:8080/home/`. Kiwix picks up new content without a - **Update:** `docker compose pull && docker compose up -d`. - **Build it yourself:** `docker compose up -d --build`. +### Admin panel + +`http://:8080/admin/`: disk and ZIM status, pick items from `config/content.conf` and download them (progress shown on the page), verify, delete. Turkish and English. + +- **First run:** a setup code is written to the logs on first start (`docker compose logs has`); whoever has the code creates the admin account. No default password in the repo. +- **Password reset:** `docker compose exec has has-admin reset-password ` prints a new password. +- Login uses a POST body, the session cookie is `HttpOnly` + `SameSite=Strict`, and the wait grows after 5 failed attempts. The panel runs the scripts; it does not download anything itself. + ### Security - Base image Alpine 3.24.4 (pinned by version); the official static Kiwix binaries are checked against a pinned SHA-256. diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 524860b..f605b99 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -21,6 +21,9 @@ mkdir -p /library/zims/content /library/www/html/home su-exec has kiwix-serve --library --monitorLibrary --address=127.0.0.1 --port=8081 \ --urlRootLocation=/kiwix "$LIB" & su-exec has nginx -e stderr -g 'daemon off;' & +# Yönetim paneli root çalışır, çünkü indirme betiği root ister; yalnız 127.0.0.1'de, nginx arkasında dinler. +# The admin panel runs as root because the download script requires it; it only listens on 127.0.0.1 behind nginx. +HAS_REPO=/opt/has has-admin & # Biri durursa konteyner de durur, Docker yeniden başlatır (restart: unless-stopped). # If either process stops, the container stops and Docker restarts it (restart: unless-stopped). diff --git a/docker/nginx.conf b/docker/nginx.conf index 8aa3584..876aa47 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -45,6 +45,15 @@ http { try_files $uri $uri/ =404; } + # Yönetim paneli (admin/, has-admin) / admin panel + location /admin { + proxy_pass http://127.0.0.1:8090; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_http_version 1.1; + client_max_body_size 64k; + } + location /kiwix/ { proxy_pass http://127.0.0.1:8081; proxy_set_header Host $host; diff --git a/scripts/services.d/has-admin.sh b/scripts/services.d/has-admin.sh new file mode 100644 index 0000000..35a35db --- /dev/null +++ b/scripts/services.d/has-admin.sh @@ -0,0 +1,4 @@ +# shellcheck shell=bash disable=SC2034 # services.sh içine alınır / sourced by services.sh +# HAS yönetim paneli (admin/, has-admin) / HAS admin panel (admin/, has-admin) +label_tr="Yönetim paneli"; label_en="Admin panel"; url="/admin/" +check(){ command -v has-admin; } From c1285e5827bde2ea0c1ee1e08fd3f9bfda5edaf5 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 19:30:35 +0300 Subject: [PATCH 04/65] refactor(scripts): download content with curl instead of wget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The script already uses curl for the catalog and SHA-256; the large download now uses curl -C - too (resume, 5 retries). A complete partial file is not re-downloaded. Drops the wget dependency. Betik katalog ve SHA-256 için zaten curl kullanıyor; büyük dosya indirmesi de curl -C - ile (kaldığı yerden devam, 5 yeniden deneme). Yarım dosya zaten tamsa indirme atlanır. wget bağımlılığı kalkar (Alpine'de wget 1.25.0'da düzeltmesi olmayan iki yüksek düzeyli CVE var; Docker imajı için de gerekli değil). --- scripts/download-content.sh | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/download-content.sh b/scripts/download-content.sh index 5803fe3..c4f0d49 100755 --- a/scripts/download-content.sh +++ b/scripts/download-content.sh @@ -88,8 +88,12 @@ while read -r folder prefix _; do sizetxt="boyut bilinmiyor / size unknown"; [ -n "$size" ] && sizetxt="$((size / 1024 / 1024)) MB" echo ">> $latest indiriliyor / downloading ($sizetxt)" df -h "$DEST" | tail -1 - if ! wget -c --progress=dot:giga -O "$DEST/$latest.part" "$url" < /dev/null; then - echo "!! $latest indirilemedi / download failed (tekrar çalıştır / re-run to resume)"; failed=1; continue + # curl -C -: yarım dosyadan devam eder; dosya zaten tamsa indirme atlanır. + # curl -C -: resumes the partial file; skipped when the file is already complete. + if [ -z "$size" ] || [ "$have" != "$size" ]; then + if ! curl -fL -C - --retry 5 --retry-delay 10 --progress-bar -o "$DEST/$latest.part" "$url" < /dev/null; then + echo "!! $latest indirilemedi / download failed (tekrar çalıştır / re-run to resume)"; failed=1; continue + fi fi # SHA-256 doğrulama / verification From fee24eb921452dde3ef072eeddf2ff813a7d1e06 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 20:43:39 +0300 Subject: [PATCH 05/65] fix(admin): keep curl progress on one line and drop wget from the image MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit curl redraws its progress bar with carriage returns. The job reader now replaces the last line on a \r instead of adding a new one, so the panel shows one live progress line; only full lines go to last-job.log. Test added. wget is no longer installed in the image, since download-content.sh uses curl only. curl ilerleme çubuğunu satır başı (\r) ile yeniliyor. İş okuyucusu artık \r gelince son satırı değiştiriyor, yeni satır eklemiyor; panelde tek, canlı bir ilerleme satırı görünüyor, last-job.log'a yalnız tam satırlar yazılıyor. Test eklendi. download-content.sh yalnız curl kullandığı için imaja wget kurulmuyor. --- admin/auth_test.go | 22 ++++++++++++++++++++++ admin/jobs.go | 38 ++++++++++++++++++++++++++++++-------- docker/Dockerfile | 2 +- 3 files changed, 53 insertions(+), 9 deletions(-) diff --git a/admin/auth_test.go b/admin/auth_test.go index 1b360e4..0e3c892 100644 --- a/admin/auth_test.go +++ b/admin/auth_test.go @@ -3,6 +3,7 @@ package main import ( "path/filepath" "testing" + "time" ) func TestPasswordRoundTrip(t *testing.T) { @@ -59,3 +60,24 @@ func TestLimiter(t *testing.T) { t.Fatal("başarılı girişten sonra engel sürüyor / still blocked after success") } } + +func TestJobProgressLines(t *testing.T) { + j := newJob(t.TempDir()) + if err := j.start("test", nil, "sh", "-c", `printf 'a\nbar 10%%\rbar 50%%\rbar 100%%\nson\n'`); err != nil { + t.Fatal(err) + } + for i := 0; i < 50 && j.state().Running; i++ { + time.Sleep(20 * time.Millisecond) + } + time.Sleep(200 * time.Millisecond) + got := j.state().Lines + want := []string{"a", "bar 100%", "son"} + if len(got) != len(want) { + t.Fatalf("satırlar / lines: %q", got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("satırlar / lines: %q", got) + } + } +} diff --git a/admin/jobs.go b/admin/jobs.go index c96d430..9cf7def 100644 --- a/admin/jobs.go +++ b/admin/jobs.go @@ -54,9 +54,13 @@ func (j *job) state() jobState { return s } -func (j *job) add(line string) { +func (j *job) add(line string, replaceLast bool) { j.mu.Lock() defer j.mu.Unlock() + if replaceLast && len(j.lines) > 0 { + j.lines[len(j.lines)-1] = line + return + } j.lines = append(j.lines, line) if len(j.lines) > keepLines { j.lines = j.lines[len(j.lines)-keepLines:] @@ -90,14 +94,32 @@ func (j *job) start(name string, cleanup func(), argv ...string) error { logf, _ := os.OpenFile(j.logPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) go func() { - sc := bufio.NewScanner(pr) - sc.Buffer(make([]byte, 64<<10), 1<<20) - for sc.Scan() { - line := sc.Text() - j.add(line) - if logf != nil { - logf.WriteString(line + "\n") + // curl'ün ilerleme çubuğu satırı \r ile yeniler; \r'den sonraki metin önceki satırın yerine yazılır. + // curl's progress bar redraws the line with \r; the text after a \r replaces the previous line. + rd := bufio.NewReaderSize(pr, 64<<10) + var buf []byte + replace := false + for { + c, err := rd.ReadByte() + if err != nil { + if len(buf) > 0 { + j.add(string(buf), replace) + } + break + } + if c != '\n' && c != '\r' { + if len(buf) < 4096 { + buf = append(buf, c) + } + continue + } + if len(buf) > 0 || c == '\n' { + j.add(string(buf), replace) + if logf != nil && c == '\n' { + logf.WriteString(string(buf) + "\n") + } } + buf, replace = buf[:0], c == '\r' } }() go func() { diff --git a/docker/Dockerfile b/docker/Dockerfile index 56c572a..9786631 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -51,7 +51,7 @@ FROM alpine:3.24.4 # apk packages are deliberately not pinned: a pinned version breaks the build once Alpine drops it and blocks security fixes. # hadolint ignore=DL3018 RUN apk upgrade --no-cache \ - && apk add --no-cache bash coreutils curl findmnt nginx su-exec tini util-linux-misc wget \ + && apk add --no-cache bash coreutils curl findmnt nginx su-exec tini util-linux-misc \ && adduser -D -H -u 1000 -s /sbin/nologin has COPY --from=kiwix --chmod=0755 /out/kiwix-serve /out/kiwix-manage /usr/local/bin/ From 5675af7cee8d6b452bf32262c60fa4271da50fa1 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 21:10:34 +0300 Subject: [PATCH 06/65] fix(admin): accept logins whatever address the box is reached by MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Origin vs Host comparison rejected browser logins because nginx passed Host without the port. Protection is now address-independent: JSON body (cross-site JSON needs a CORS preflight the panel never grants), Sec-Fetch-Site "cross-site" refused, SameSite=Strict cookie. Tests cover other addresses, ports and old browsers. Origin ile Host karşılaştırması, nginx Host'u portsuz geçirdiği için tarayıcıdan yapılan girişi "cross_origin" diye reddediyordu (127.0.0.1:18081). Afette kutuya hangi adresle (IP, port, box.lan, captive portal) ulaşılacağı belli değil; adres karşılaştırması meşru isteği reddedebilir. Koruma artık adresten bağımsız: JSON gövde zorunlu (başka site CORS ön isteği olmadan JSON gönderemez, panel CORS izni vermez), Sec-Fetch-Site yalnız "cross-site" ise ret, oturum çerezi SameSite=Strict. nginx Host'u portuyla geçirir. Farklı adres/port/eski tarayıcı/başka site durumları için test eklendi. --- admin/csrf_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ admin/handlers.go | 22 ++++++++++++---------- docker/nginx.conf | 4 ++-- 3 files changed, 60 insertions(+), 12 deletions(-) create mode 100644 admin/csrf_test.go diff --git a/admin/csrf_test.go b/admin/csrf_test.go new file mode 100644 index 0000000..b67552c --- /dev/null +++ b/admin/csrf_test.go @@ -0,0 +1,46 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// Kutuya hangi adresle ulaşılırsa ulaşılsın (IP, port, box.lan) aynı sayfadan gelen istek kabul edilmeli; +// yalnız başka siteden gelen ya da JSON olmayan istek reddedilmeli. +// Whatever address the box is reached at (IP, port, box.lan), a same-page request must pass; +// only cross-site or non-JSON requests are refused. +func TestPostGuard(t *testing.T) { + a := &app{} + ok := a.post(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }) + cases := []struct { + name, host, origin, site, ctype string + want int + }{ + {"port farkı (nginx Host'u portsuz geçirir)", "127.0.0.1", "http://127.0.0.1:18081", "same-origin", "application/json", 204}, + {"box.lan", "box.lan", "http://box.lan", "same-origin", "application/json", 204}, + {"IP değişmiş / changed IP", "10.10.10.10", "http://192.168.4.1", "same-origin", "application/json", 204}, + {"eski tarayıcı, başlık yok / no fetch metadata", "10.10.10.10", "", "", "application/json", 204}, + {"aynı site alt alan / same-site", "box.lan", "http://harita.box.lan", "same-site", "application/json", 204}, + {"başka site / cross-site", "box.lan", "http://evil.example", "cross-site", "application/json", 403}, + {"form gönderimi / form post", "box.lan", "http://evil.example", "", "application/x-www-form-urlencoded", 415}, + {"text/plain", "box.lan", "", "", "text/plain", 415}, + } + for _, c := range cases { + r := httptest.NewRequest("POST", "http://"+c.host+"/admin/api/login", strings.NewReader("{}")) + r.Host = c.host + r.Header.Set("Content-Type", c.ctype) + if c.origin != "" { + r.Header.Set("Origin", c.origin) + } + if c.site != "" { + r.Header.Set("Sec-Fetch-Site", c.site) + } + w := httptest.NewRecorder() + ok(w, r) + if w.Code != c.want { + t.Errorf("%s: %d, beklenen / want %d", c.name, w.Code, c.want) + } + } +} diff --git a/admin/handlers.go b/admin/handlers.go index bf5a8f0..b27ed3e 100644 --- a/admin/handlers.go +++ b/admin/handlers.go @@ -10,7 +10,6 @@ import ( "encoding/json" "net" "net/http" - "net/url" "os" "os/exec" "path/filepath" @@ -121,24 +120,27 @@ func clientIP(r *http.Request) string { return host } -// post: veri değiştiren her istek JSON gövdeli ve aynı kaynaktan olmalı (CSRF'e karşı). -// post: every data-changing request must carry a JSON body and come from the same origin (against CSRF). +// post: veri değiştiren isteklere CSRF koruması. Kutunun adresine (IP, port, box.lan, captive portal) +// hiç bakılmaz: afette kutuya hangi adresle ulaşıldığı belli olmaz, adres karşılaştırması meşru isteği +// reddedebilir. Koruma üç katman: (1) gövde JSON olmalı; başka bir site JSON gönderirse tarayıcı önce +// OPTIONS sorar, panel CORS izni vermediği için istek hiç gitmez. (2) Tarayıcının kendi bildirdiği +// Sec-Fetch-Site: yalnız "cross-site" reddedilir. (3) Oturum çerezi SameSite=Strict. +// +// post: CSRF protection for data-changing requests. The box's address (IP, port, box.lan, captive portal) +// is never compared: in a disaster you cannot know which address people use, and comparing it could +// reject a legitimate request. Three layers instead: (1) JSON body; a cross-site JSON request needs a +// CORS preflight the panel never grants. (2) The browser's own Sec-Fetch-Site: only "cross-site" is +// refused. (3) SameSite=Strict session cookie. func (a *app) post(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { fail(w, http.StatusUnsupportedMediaType, "json_required") return } - if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" { + if r.Header.Get("Sec-Fetch-Site") == "cross-site" { fail(w, http.StatusForbidden, "cross_origin") return } - if o := r.Header.Get("Origin"); o != "" { - if u, err := url.Parse(o); err != nil || u.Host != r.Host { - fail(w, http.StatusForbidden, "cross_origin") - return - } - } r.Body = http.MaxBytesReader(w, r.Body, 64<<10) next(w, r) } diff --git a/docker/nginx.conf b/docker/nginx.conf index 876aa47..d8b594d 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -48,7 +48,7 @@ http { # Yönetim paneli (admin/, has-admin) / admin panel location /admin { proxy_pass http://127.0.0.1:8090; - proxy_set_header Host $host; + proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_http_version 1.1; client_max_body_size 64k; @@ -56,7 +56,7 @@ http { location /kiwix/ { proxy_pass http://127.0.0.1:8081; - proxy_set_header Host $host; + proxy_set_header Host $http_host; proxy_http_version 1.1; } } From 85d9cb788cf5c5102d0524b6a90139bfdc836abb Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 21:14:45 +0300 Subject: [PATCH 07/65] feat(admin): confirm deletes with the password in an in-page dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Delete now asks in an in-page dialog for the logged-in user's password; it is checked on the server and wrong attempts count towards the login limit. Silme, tarayıcının confirm() kutusu yerine sayfa içi bir pencereyle soruluyor ve oturumdaki kullanıcının şifresini istiyor. Şifre sunucuda doğrulanıyor, yanlış denemeler giriş ile aynı sınıra takılıyor; şifre alanı her açılışta ve işten sonra temizleniyor. Test: şifresiz ve yanlış şifreyle dosya silinmiyor. --- admin/delete_test.go | 53 +++++++++++++++++++++++++++++++++++++++ admin/handlers.go | 20 ++++++++++++++- admin/web/index.html | 59 ++++++++++++++++++++++++++++++++++++++------ 3 files changed, 124 insertions(+), 8 deletions(-) create mode 100644 admin/delete_test.go diff --git a/admin/delete_test.go b/admin/delete_test.go new file mode 100644 index 0000000..f2559c5 --- /dev/null +++ b/admin/delete_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +// Silme, oturumdaki kullanıcının şifresi doğru değilse yapılmamalı. +// Delete must not happen unless the logged-in user's password is correct. +func TestDeleteNeedsPassword(t *testing.T) { + lib := t.TempDir() + zdir := filepath.Join(lib, "zims", "content") + os.MkdirAll(zdir, 0o755) + zim := filepath.Join(zdir, "test_2026-01.zim") + os.WriteFile(zim, []byte("x"), 0o644) + t.Setenv("KIWIX_LIB_CMD", "true") + + st := &store{path: filepath.Join(t.TempDir(), "users.json")} + if err := st.setPassword("deneme", "deneme-sifre-123"); err != nil { + t.Fatal(err) + } + a := newApp(config{prefix: "/admin", data: t.TempDir(), library: lib}, st) + h := a.routes() + tok := a.ses.create("deneme") + + del := func(body string) int { + r := httptest.NewRequest("POST", "/admin/api/delete", strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + r.AddCookie(&http.Cookie{Name: cookieName, Value: tok}) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code + } + if c := del(`{"file":"test_2026-01.zim"}`); c != http.StatusForbidden { + t.Fatalf("şifresiz / no password: %d", c) + } + if c := del(`{"file":"test_2026-01.zim","password":"yanlis-sifre-12"}`); c != http.StatusForbidden { + t.Fatalf("yanlış şifre / wrong password: %d", c) + } + if _, err := os.Stat(zim); err != nil { + t.Fatal("dosya şifre doğrulanmadan silindi / file deleted without a valid password") + } + if c := del(`{"file":"test_2026-01.zim","password":"deneme-sifre-123"}`); c != http.StatusOK { + t.Fatalf("doğru şifre / correct password: %d", c) + } + if _, err := os.Stat(zim); !os.IsNotExist(err) { + t.Fatal("doğru şifreyle silinmedi / not deleted with the correct password") + } +} diff --git a/admin/handlers.go b/admin/handlers.go index b27ed3e..ad125c7 100644 --- a/admin/handlers.go +++ b/admin/handlers.go @@ -87,6 +87,7 @@ var errorMessages = map[string]string{ "bad_request": "Bad request.", "wrong_setup_code": "Wrong setup code.", "wrong_login": "Wrong user name or password.", + "wrong_password": "Wrong password.", "too_many_attempts": "Too many attempts; try again later.", "content_unreadable": "Could not read config/content.conf.", "choose_content": "Choose content to download.", @@ -399,14 +400,31 @@ func (a *app) verify(w http.ResponseWriter, r *http.Request) { writeJSON(w, 202, map[string]bool{"started": true}) } +// remove silmeden önce oturumdaki kullanıcının şifresini yeniden ister; şifre sunucuda doğrulanır, +// yanlış denemeler giriş ile aynı sınıra takılır. +// remove asks for the logged-in user's password again before deleting; it is checked on the server +// and wrong attempts count towards the same limit as logins. func (a *app) remove(w http.ResponseWriter, r *http.Request) { var req struct { - File string `json:"file"` + File string `json:"file"` + Password string `json:"password"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil || !zimName.MatchString(req.File) { fail(w, http.StatusBadRequest, "invalid_file") return } + ip := clientIP(r) + if d := a.lim.blocked(ip); d > 0 { + failWait(w, d) + return + } + user, _ := a.currentUser(r) + if req.Password == "" || !a.st.check(user, req.Password) { + a.lim.fail(ip) + fail(w, http.StatusForbidden, "wrong_password") + return + } + a.lim.ok(ip) if a.work.state().Running { fail(w, http.StatusConflict, "busy") return diff --git a/admin/web/index.html b/admin/web/index.html index 9a06f14..830e767 100644 --- a/admin/web/index.html +++ b/admin/web/index.html @@ -25,6 +25,12 @@ .bar{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:8px 0} .err{color:#B00000;margin:6px 0} a{color:#006699} + dialog{border:1px solid #A9B8C2;padding:0;max-width:360px;width:90%} + dialog::backdrop{background:rgba(0,0,0,.45)} + dialog h2{margin:0} + dialog .in{padding:10px 12px} + dialog .btns{display:flex;gap:8px;justify-content:flex-end} + button.danger{background:#B00000;color:#fff;border:1px solid #B00000} @media (max-width:600px){.hide-s{display:none}} @@ -81,6 +87,19 @@

+ +
+

+
+

+

+ + +
+
+
+
+ + + From d0f046020ecee73ab384af7de797b0b0b919f0ba Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 21:39:23 +0300 Subject: [PATCH 11/65] fix(ui): fit the reader bar and admin panel on phone screens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reader bar collapses to SVG icons on narrow screens and fits two rows; panel gets larger touch targets and wraps long names. Checked at 320/390/768/1280 px, light and dark. - Okuyucu çubuğu dar ekranda simgelere iner (SVG, yazı tipine bağlı değil; tam ad title/aria-label'da) ve iki satıra sığar: üstte ana sayfa, kütüphane, kaynağın başı, kaynak listesi; altta arama, rastgele, dil. - Panel: dar ekranda kenar boşluğu, büyük dokunma hedefleri, uzun adlar satır kırıyor, Sil düğmesi bölünmüyor. 320, 390, 768, 1280 px genişlikte, açık ve karanlık temada ekran görüntüsüyle denendi. --- admin/web/index.html | 10 +++++++++- www/home/oku.html | 28 ++++++++++++++++++++++------ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/admin/web/index.html b/admin/web/index.html index a832dbe..cce8427 100644 --- a/admin/web/index.html +++ b/admin/web/index.html @@ -47,7 +47,15 @@ pre{background:#0f1215} code{color:#ffc078} } - @media (max-width:600px){.hide-s{display:none}} + td{overflow-wrap:anywhere} + td button{white-space:nowrap;overflow-wrap:normal} + @media (max-width:600px){ + .hide-s{display:none} + .wrap{margin:0;border:0;padding:8px 10px} + button{min-height:38px;padding:8px 12px} + td,th{padding:8px 4px} + pre{max-height:240px} + } diff --git a/www/home/oku.html b/www/home/oku.html index ae74aaa..752bcd7 100644 --- a/www/home/oku.html +++ b/www/home/oku.html @@ -20,6 +20,20 @@ .bar input{flex:1;min-width:6em} .lang button{padding:3px 6px} .lang button[aria-pressed="true"]{background:#fff;color:#006699} + .lang{display:flex} + .i{display:none;vertical-align:-3px} + .br{display:none} + /* Dar ekran: düğmeler simgeye iner (tam adı title'da), çubuk iki satıra sığar. + Narrow screens: buttons shrink to icons (full name in title), the bar fits in two rows. */ + @media (max-width:560px){ + .bar{gap:4px;padding:4px 6px} + .i{display:inline-block} .l{display:none} + .br{display:block;flex-basis:100%;height:0} + .bar a,.bar button{padding:6px 9px} + .bar select{flex:1 1 6em;min-width:0} + .bar form{flex:1 1 6em;min-width:0} + .bar input{min-width:0} + } iframe{flex:1;border:0;width:100%;background:#fff} .msg{padding:20px;background:#fff;flex:1} @media (prefers-color-scheme: dark){ @@ -35,12 +49,13 @@
- - - + + + + - +
@@ -51,10 +66,10 @@ Address: oku.html#/ or oku.html#search?books.name=..&pattern=.. */ const K = "/kiwix"; const T = { - tr:{home:"⌂ Ana sayfa", library:"Kütüphane", book:"Kaynağın başı", all:"Tüm kaynaklar", search:"Ara", random:"Rastgele", + tr:{home:"Ana sayfa", library:"Kütüphane", book:"Kaynağın başı", all:"Tüm kaynaklar", search:"Ara", random:"Rastgele", ph:"Bu kaynakta ara…", phAll:"Tüm kaynaklarda ara…", none:"Cihazda henüz kaynak yok. İçerik yönetim panelinden indirilebilir.", noKiwix:"Kütüphaneye ulaşılamadı."}, - en:{home:"⌂ Home", library:"Library", book:"Source start", all:"All sources", search:"Search", random:"Random", + en:{home:"Home", library:"Library", book:"Source start", all:"All sources", search:"Search", random:"Random", ph:"Search this source…", phAll:"Search all sources…", none:"No sources on this device yet. Content can be downloaded from the admin panel.", noKiwix:"Could not reach the library."} }; @@ -68,6 +83,7 @@ function applyLang(){ document.documentElement.lang = lang; for (const el of document.querySelectorAll("[data-t]")) el.textContent = t(el.dataset.t); + for (const el of document.querySelectorAll("[data-title]")) { el.title = t(el.dataset.title); el.setAttribute("aria-label", t(el.dataset.title)); } for (const b of document.querySelectorAll("[data-lang]")) b.setAttribute("aria-pressed", String(b.dataset.lang === lang)); if (sel.options[0]) sel.options[0].textContent = t("all"); $("q").placeholder = current ? t("ph") : t("phAll"); From 5b85e0503d67d26de17c9f594da4a3baead8dfc7 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 21:43:17 +0300 Subject: [PATCH 12/65] feat(reader): show the Kiwix library under the HAS bar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reader #library shows Kiwix's library page under the HAS bar (books open in the reader, dark theme applied); Docker redirects a direct /kiwix/ there. - Okuyucuda #library: Kiwix'in kitaplık sayfası HAS çubuğunun altında; bir kitaba tıklanınca okuyucuda açılır. Karanlık temada kitaplık sayfası da koyulaşır (Kiwix'in kendi karanlık teması yok). - Ana sayfa ve okuyucudaki Kütüphane bağlantısı buraya gider (services.d/kiwix). - Docker: /kiwix/ doğrudan açılırsa okuyucunun kitaplığına yönlenir; çerçeve ?has=1 ile döngüye girmez. --- docker/nginx.conf | 11 +++++++++++ scripts/services.d/kiwix.sh | 2 +- www/home/index.html | 2 +- www/home/oku.html | 33 +++++++++++++++++++++++++++++++-- 4 files changed, 44 insertions(+), 4 deletions(-) diff --git a/docker/nginx.conf b/docker/nginx.conf index d8b594d..d1ab681 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -54,6 +54,17 @@ http { client_max_body_size 64k; } + # Kiwix kitaplığı doğrudan açılınca HAS çubuklu okuyucuya git; okuyucu çerçevesi ?has=1 ile gelir. + # Opening the Kiwix library directly goes to the reader with the HAS bar; the reader's frame uses ?has=1. + location = /kiwix/ { + if ($arg_has = "") { + return 302 /home/oku.html#library; + } + proxy_pass http://127.0.0.1:8081; + proxy_set_header Host $http_host; + proxy_http_version 1.1; + } + location /kiwix/ { proxy_pass http://127.0.0.1:8081; proxy_set_header Host $http_host; diff --git a/scripts/services.d/kiwix.sh b/scripts/services.d/kiwix.sh index 487745e..f7a31cf 100644 --- a/scripts/services.d/kiwix.sh +++ b/scripts/services.d/kiwix.sh @@ -1,5 +1,5 @@ # shellcheck shell=bash disable=SC2034 # services.sh içine alınır / sourced by services.sh # Kiwix kütüphanesi (Vikipedi ve diğer ZIM'ler) / Kiwix library (Wikipedia and other ZIMs) # Pi: IIAB'nin kiwix-serve servisi; Docker: imajdaki kiwix-serve. / Pi: IIAB's kiwix-serve service; Docker: kiwix-serve in the image. -label_tr="Kütüphane"; label_en="Library"; url="/kiwix/" +label_tr="Kütüphane"; label_en="Library"; url="/home/oku.html#library" check(){ active kiwix-serve || command -v kiwix-serve; } diff --git a/www/home/index.html b/www/home/index.html index be45a65..11ce26b 100644 --- a/www/home/index.html +++ b/www/home/index.html @@ -121,7 +121,7 @@
Çevrimdışı bilgi arşivi — internet olmasa da açık
diff --git a/www/home/oku.html b/www/home/oku.html index 752bcd7..6af7ccf 100644 --- a/www/home/oku.html +++ b/www/home/oku.html @@ -50,7 +50,7 @@
- + @@ -119,7 +119,11 @@ } /* Adres çubuğundaki # → çerçevedeki Kiwix adresi / hash → Kiwix address in the frame */ +/* #library: Kiwix'in kitaplık sayfası, HAS çubuğuyla. ?has=1, Docker'daki nginx'in /kiwix/ → okuyucu + yönlendirmesini atlatır (çerçeve içinde döngü olmasın). / #library: Kiwix's library page with the HAS bar. + ?has=1 skips the Docker nginx /kiwix/ → reader redirect (no loop inside the frame). */ function hashToSrc(h){ + if (h === "library" || h.startsWith("library?")) return K + "/?has=1" + (h.length > 8 ? "#" + h.slice(8) : ""); if (h.startsWith("search?")) return K + "/search?" + h.slice(7); return K + "/content/" + h; } @@ -127,7 +131,8 @@ if (!h) return; frame.hidden = false; $("msg").hidden = true; if (frame.dataset.h !== h) { frame.dataset.h = h; frame.src = hashToSrc(h); } - if (h.startsWith("search?")) setCurrent(new URLSearchParams(h.slice(7)).get("books.name") || ""); + if (h === "library" || h.startsWith("library?")) setCurrent(""); + else if (h.startsWith("search?")) setCurrent(new URLSearchParams(h.slice(7)).get("books.name") || ""); else setCurrent(h.split("/")[0]); } @@ -136,6 +141,30 @@ frame.addEventListener("load", () => { let loc; try { loc = frame.contentWindow.location; } catch(e) { return; } + // Kitaplıkta bir kitaba tıklanınca (Kiwix /viewer#kitap bağlantısı) okuyucuda aç; sayfa içeriği + // sonradan yüklendiği için tıklama belge düzeyinde yakalanır. + // A click on a book in the library (Kiwix's /viewer#book link) opens it in the reader; the list is + // built later by script, so the click is caught at document level. + if (loc.pathname === K + "/" || loc.pathname === K) { + frame.contentDocument.addEventListener("click", ev => { + const a = ev.target.closest && ev.target.closest("a[href]"); + if (!a) return; + const m = a.getAttribute("href").match(/\/viewer#(.+)$/); + if (m) { ev.preventDefault(); location.hash = decodeURIComponent(m[1]); } + }, true); + // Kiwix kitaplık sayfasının karanlık teması yok; karanlık temada renkleri ters çevir (resimler korunur). + // Kiwix's library page has no dark theme; in dark mode invert its colours (images kept as they are). + if (matchMedia("(prefers-color-scheme: dark)").matches && !frame.contentDocument.getElementById("has-dark")) { + const st = frame.contentDocument.createElement("style"); + st.id = "has-dark"; + st.textContent = "html{filter:invert(.9) hue-rotate(180deg);background:#fff}img,svg,picture,video{filter:invert(1) hue-rotate(180deg)}"; + frame.contentDocument.head.appendChild(st); + } + if (!location.hash.slice(1).startsWith("library")) history.replaceState(null, "", "#library"); + setCurrent(""); + try { document.title = (frame.contentDocument.title || "Kiwix") + " · HAS_PrepperDisk"; } catch(e) {} + return; + } let h = ""; if (loc.pathname.startsWith(K + "/content/")) h = decodeURI(loc.pathname.slice(K.length + 9)) + loc.hash; else if (loc.pathname === K + "/search") h = "search" + loc.search; From c1aa7391f99fd6bed2bb47843a6a044dc5c02adc Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sat, 28 Nov 2026 21:59:51 +0300 Subject: [PATCH 13/65] feat(ui): add a system, dark and light theme choice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Theme selector (system default, dark, light) on all HAS pages, shared and stored in the browser, applied before first paint. Ana sayfa, acil sayfası, okuyucu ve yönetim panelinde tema seçimi. Seçim tarayıcıda saklanıyor ve tüm HAS sayfalarında ortak; "sistem" cihaz ayarını izliyor ve ayar değişince anında uyuyor. Tema sayfa çizilmeden önce uygulandığı için açılışta yanıp sönme yok. Okuyucudaki Kiwix kitaplığı da seçime uyuyor. Dar ekranda okuyucudaki seçim simgeye iniyor. --- admin/web/index.html | 58 +++++++++++++++++++++++----------- www/home/acil.html | 73 +++++++++++++++++++++++++++++-------------- www/home/index.html | 74 ++++++++++++++++++++++++++++++-------------- www/home/oku.html | 66 ++++++++++++++++++++++++++++----------- 4 files changed, 189 insertions(+), 82 deletions(-) diff --git a/admin/web/index.html b/admin/web/index.html index cce8427..a20ae27 100644 --- a/admin/web/index.html +++ b/admin/web/index.html @@ -2,9 +2,24 @@ - HAS_PrepperDisk · Yönetim / Admin +
- +
HAS_PrepperDisk Ana Sayfa » Acil Durum
Hayati tehlike varsa ve telefon çalışıyorsa: 112
@@ -160,5 +181,11 @@
HAS_PrepperDisk · Bu sayfa çevrimdışı çalışır, yazdırılabilir.
+ diff --git a/www/home/index.html b/www/home/index.html index 11ce26b..1c963b4 100644 --- a/www/home/index.html +++ b/www/home/index.html @@ -2,9 +2,24 @@ - HAS_PrepperDisk :: Ana Sayfa + @@ -121,7 +143,7 @@
Çevrimdışı bilgi arşivi — internet olmasa da açık
@@ -357,5 +379,11 @@ Promise.all([loadBooks(), loadServices()]).then(([books, services]) => render(books, services)); + diff --git a/www/home/oku.html b/www/home/oku.html index 6af7ccf..ae63597 100644 --- a/www/home/oku.html +++ b/www/home/oku.html @@ -2,9 +2,24 @@ - HAS_PrepperDisk · Okuyucu + @@ -56,6 +73,7 @@ + @@ -66,10 +84,10 @@ Address: oku.html#/ or oku.html#search?books.name=..&pattern=.. */ const K = "/kiwix"; const T = { - tr:{home:"Ana sayfa", library:"Kütüphane", book:"Kaynağın başı", all:"Tüm kaynaklar", search:"Ara", random:"Rastgele", + tr:{tSystem:"◐ Sistem", tDark:"● Koyu", tLight:"○ Açık", home:"Ana sayfa", library:"Kütüphane", book:"Kaynağın başı", all:"Tüm kaynaklar", search:"Ara", random:"Rastgele", ph:"Bu kaynakta ara…", phAll:"Tüm kaynaklarda ara…", none:"Cihazda henüz kaynak yok. İçerik yönetim panelinden indirilebilir.", noKiwix:"Kütüphaneye ulaşılamadı."}, - en:{home:"Home", library:"Library", book:"Source start", all:"All sources", search:"Search", random:"Random", + en:{tSystem:"◐ System", tDark:"● Dark", tLight:"○ Light", home:"Home", library:"Library", book:"Source start", all:"All sources", search:"Search", random:"Random", ph:"Search this source…", phAll:"Search all sources…", none:"No sources on this device yet. Content can be downloaded from the admin panel.", noKiwix:"Could not reach the library."} }; @@ -154,12 +172,7 @@ }, true); // Kiwix kitaplık sayfasının karanlık teması yok; karanlık temada renkleri ters çevir (resimler korunur). // Kiwix's library page has no dark theme; in dark mode invert its colours (images kept as they are). - if (matchMedia("(prefers-color-scheme: dark)").matches && !frame.contentDocument.getElementById("has-dark")) { - const st = frame.contentDocument.createElement("style"); - st.id = "has-dark"; - st.textContent = "html{filter:invert(.9) hue-rotate(180deg);background:#fff}img,svg,picture,video{filter:invert(1) hue-rotate(180deg)}"; - frame.contentDocument.head.appendChild(st); - } + libraryTheme(); if (!location.hash.slice(1).startsWith("library")) history.replaceState(null, "", "#library"); setCurrent(""); try { document.title = (frame.contentDocument.title || "Kiwix") + " · HAS_PrepperDisk"; } catch(e) {} @@ -175,6 +188,23 @@ try { document.title = (frame.contentDocument.title || "") + " · HAS_PrepperDisk"; } catch(e) {} }); +/* Kitaplık sayfasına koyu tema (Kiwix'in kendi koyu teması yok) / dark theme for the library page */ +function libraryTheme(){ + let d; + try { d = frame.contentDocument; if (!d || !(d.location.pathname === K + "/" || d.location.pathname === K)) return; } catch(e) { return; } + const old = d.getElementById("has-dark"); + if (document.documentElement.dataset.theme === "dark") { + if (old) return; + const st = d.createElement("style"); + st.id = "has-dark"; + st.textContent = "html{filter:invert(.9) hue-rotate(180deg);background:#fff}img,svg,picture,video{filter:invert(1) hue-rotate(180deg)}"; + d.head.appendChild(st); + } else if (old) old.remove(); +} +document.addEventListener("has-theme", libraryTheme); +$("theme").value = document.documentElement.dataset.themeChoice || "system"; +$("theme").onchange = () => hasTheme($("theme").value); + window.addEventListener("hashchange", () => open(decodeURI(location.hash.slice(1)))); sel.onchange = () => { location.hash = sel.value ? sel.value : ""; if (!sel.value) setCurrent(""); }; From a96d61a103980e10d79e4b311e8f2913b218301b Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 02:18:09 +0300 Subject: [PATCH 14/65] ci(docker): test the image on every platform before publishing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docker/test.sh starts the image with the hardening from compose.yaml and checks the homepage and relative redirects, services.json, Kiwix, first-run setup, login, CSRF (including a browser using another host name/port), bad input, sessions and users across a restart, CLI password reset, non-root processes, only port 8080 exposed, read-only root and the wait after failed attempts. --download fetches a small ZIM via the panel, verifies and deletes it. Workflow: hadolint + docker compose config; each of the five platforms is built in its own job and tested with test.sh (arm64 on an ARM runner, arm/v7 and arm/v6 under QEMU); amd64 also runs the download and a compose start. The publish job depends on the tests and reuses their cache. HEALTHCHECK in JSON form (hadolint 2.15 DL3025). docker/test.sh imajı compose.yaml'daki güvenlik ayarlarıyla açıp dener: ana sayfa ve göreli yönlendirmeler, services.json, Kiwix, ilk kurulum, giriş, CSRF (başka ad/portla gelen tarayıcı dahil), hatalı girdiler, yeniden başlatmada oturum ve kullanıcı, CLI ile şifre sıfırlama, root olmayan süreçler, yalnız 8080'in dışa açık olması, salt okunur kök, hatalı denemede bekleme. --download panelden küçük bir ZIM indirir, doğrular, siler. Workflow: hadolint + docker compose config; beş mimari ayrı işte derlenip test.sh ile deneniyor (arm64 ARM makinede, arm/v7 ve arm/v6 QEMU ile); amd64'te ayrıca indirme ve compose ile açılış. Yayın işi testlere bağlı ve onların önbelleğini kullanıyor. HEALTHCHECK JSON biçiminde (hadolint 2.15 DL3025). --- .github/workflows/docker.yml | 125 +++++++++++++----- docker/Dockerfile | 2 +- docker/README.md | 24 ++++ docker/test.sh | 238 +++++++++++++++++++++++++++++++++++ 4 files changed, 354 insertions(+), 35 deletions(-) create mode 100755 docker/test.sh diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 655704c..1779dac 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,8 +1,9 @@ name: Docker -# Çok mimarili imajı derler, dener ve GitHub Container Registry'ye (ghcr.io) gönderir. -# Builds, tests and pushes the multi-architecture image to GitHub Container Registry (ghcr.io). -# PR'larda yalnız derlenir ve denenir, gönderilmez. / On pull requests it is only built and tested. +# Çok mimarili imajı derler, her mimaride dener (docker/test.sh) ve GitHub Container Registry'ye (ghcr.io) gönderir. +# Builds the multi-architecture image, tests it on every platform (docker/test.sh) and pushes it to ghcr.io. +# Gönderim yalnız tüm testler geçince. PR'larda yalnız derlenir ve denenir. +# Pushing happens only after every test passes. On pull requests it is only built and tested. # Haftalık derleme Alpine güvenlik düzeltmelerini imaja alır. / The weekly build picks up Alpine security fixes. on: @@ -13,6 +14,7 @@ on: - 'docker/**' - 'admin/**' - 'scripts/services.sh' + - 'scripts/services.d/**' - 'scripts/install-homepage.sh' - 'compose.yaml' - '.dockerignore' @@ -26,6 +28,7 @@ on: - 'docker/**' - 'admin/**' - 'scripts/services.sh' + - 'scripts/services.d/**' - 'scripts/install-homepage.sh' - 'compose.yaml' - '.dockerignore' @@ -49,49 +52,99 @@ env: PLATFORMS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6,linux/386 jobs: - image: + lint: + name: Dockerfile + compose runs-on: ubuntu-latest - permissions: - contents: read - packages: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: hadolint + run: docker run --rm -i hadolint/hadolint:v2.15.1 < docker/Dockerfile + + - name: compose.yaml + run: docker compose -f compose.yaml config --quiet + + test: + name: Test ${{ matrix.platform }} + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + # amd64: ayrıca gerçek indirme (~15 MB) ve compose ile açılış / also a real download (~15 MB) and a compose start + - { platform: linux/amd64, scope: amd64, runner: ubuntu-latest, qemu: false, full: true } + # arm64 GitHub'ın ARM makinesinde, emülasyonsuz / on GitHub's ARM runner, no emulation + - { platform: linux/arm64, scope: arm64, runner: ubuntu-24.04-arm, qemu: false, full: false } + - { platform: linux/arm/v7, scope: armv7, runner: ubuntu-latest, qemu: true, full: false } + - { platform: linux/arm/v6, scope: armv6, runner: ubuntu-latest, qemu: true, full: false } + - { platform: linux/386, scope: '386', runner: ubuntu-latest, qemu: false, full: false } steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + if: matrix.qemu - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - name: Imaj adı / image name - id: name - run: echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/has-disk" >> "$GITHUB_OUTPUT" - - - name: Dene (amd64) / test (amd64) + - name: Derle / build uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . file: docker/Dockerfile + platforms: ${{ matrix.platform }} load: true tags: has-disk:ci no-cache: ${{ github.event_name == 'schedule' }} - cache-from: type=gha - cache-to: type=gha,mode=max + cache-from: type=gha,scope=${{ matrix.scope }} + cache-to: type=gha,scope=${{ matrix.scope }},mode=max - - name: Duman testi / smoke test + - name: İmaj testi / image test + env: + HAS_TEST_TIMEOUT: '600' + HAS_TEST_LOGS: ${{ runner.temp }}/container.log + PLATFORM: ${{ matrix.platform }} + DOWNLOAD: ${{ matrix.full && '1' || '' }} + run: bash docker/test.sh has-disk:ci --platform "$PLATFORM" ${DOWNLOAD:+--download} + + - name: compose ile açılış / start with compose + if: matrix.full run: | - mkdir -p "$RUNNER_TEMP/library" - docker run -d --name has -p 8080:8080 -v "$RUNNER_TEMP/library:/library" \ - --read-only --tmpfs /tmp --cap-drop ALL --cap-add SETUID --cap-add SETGID \ - --cap-add DAC_OVERRIDE --security-opt no-new-privileges:true has-disk:ci - for i in $(seq 1 30); do curl -fsS -o /dev/null http://127.0.0.1:8080/home/ && break; sleep 1; done - curl -fsS -o /dev/null http://127.0.0.1:8080/home/ - curl -fsS -o /dev/null http://127.0.0.1:8080/home/acil.html - curl -fsS -o /dev/null http://127.0.0.1:8080/kiwix/ - curl -fsS -o /dev/null 'http://127.0.0.1:8080/kiwix/catalog/v2/entries?count=-1' - curl -fsS http://127.0.0.1:8080/admin/api/session | grep -q '"setup":true' - docker logs has 2>&1 | grep -q 'first-run setup code' - test "$(docker exec has stat -c %U /proc/$(docker exec has pgrep -o kiwix-serve))" = has - docker logs has - docker rm -f has + docker tag has-disk:ci ghcr.io/schematrix/has-disk:latest + mkdir -p "$RUNNER_TEMP/compose-library" + export HAS_PORT=18091 HAS_LIBRARY="$RUNNER_TEMP/compose-library" + docker compose -p has-ci up -d --no-build --pull never --wait --wait-timeout 240 + curl -fsS -o /dev/null http://127.0.0.1:18091/home/ + curl -fsS http://127.0.0.1:18091/admin/api/session | grep -q '"setup":true' + test -s "$HAS_LIBRARY/www/html/home/services.json" + docker compose -p has-ci logs + docker compose -p has-ci down + + - name: Kayıtlar / logs + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: container-log-${{ matrix.scope }} + path: ${{ runner.temp }}/container.log + if-no-files-found: ignore + + publish: + name: Yayımla / publish + needs: [lint, test] + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Imaj adı / image name + id: name + run: echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/has-disk" >> "$GITHUB_OUTPUT" - uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 id: meta @@ -103,23 +156,27 @@ jobs: type=sha,format=short - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 - if: github.event_name != 'pull_request' with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + # Test işlerinin önbelleği kullanılır: denenen katmanlar yayımlanır. + # Uses the test jobs' cache: the layers that were tested are the ones published. - name: Tüm mimariler / all platforms uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . file: docker/Dockerfile platforms: ${{ env.PLATFORMS }} - push: ${{ github.event_name != 'pull_request' }} + push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} sbom: true provenance: mode=max - no-cache: ${{ github.event_name == 'schedule' }} - cache-from: type=gha - cache-to: type=gha,mode=max + cache-from: | + type=gha,scope=amd64 + type=gha,scope=arm64 + type=gha,scope=armv7 + type=gha,scope=armv6 + type=gha,scope=386 diff --git a/docker/Dockerfile b/docker/Dockerfile index 9786631..7c7287d 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -76,5 +76,5 @@ WORKDIR /opt/has VOLUME /library EXPOSE 8080 HEALTHCHECK --interval=60s --timeout=5s --start-period=20s \ - CMD curl -fsS -o /dev/null http://127.0.0.1:8080/home/ || exit 1 + CMD ["/bin/sh", "-c", "curl -fsS -o /dev/null http://127.0.0.1:8080/home/ || exit 1"] ENTRYPOINT ["/sbin/tini", "-g", "--", "has-entrypoint"] diff --git a/docker/README.md b/docker/README.md index 160a1f6..9e5894f 100644 --- a/docker/README.md +++ b/docker/README.md @@ -42,6 +42,18 @@ Ana sayfa: `http://:8080/home/`. İndirme bitince Kiwix yeni içeriği - `kiwix-serve` ve `nginx` root olmayan `has` kullanıcısıyla çalışır; kök dosya sistemi salt okunur, yetkilerin hepsi düşürülür (yalnız kullanıcı değişimi ve `/library`'ye yazma için üç yetki kalır), erişim kaydı tutulmaz. - Kiwix yalnız konteyner içinde (127.0.0.1) dinler, dışarıya nginx üzerinden açılır. +### Test + +`docker/test.sh` imajı `compose.yaml`'daki güvenlik ayarlarıyla açıp dener: ana sayfa ve yönlendirmeler, `services.json`, Kiwix, ilk kurulum, giriş, CSRF, hatalı girdiler, yeniden başlatmada oturum ve kullanıcının kalması, komut satırından şifre sıfırlama, süreçlerin root olmaması, yalnız 8080'in dışa açık olması, salt okunur kök, hatalı denemede bekleme. `--download` panelden küçük bir ZIM indirip doğrular ve siler (internet ister). + +```sh +docker build -f docker/Dockerfile -t has-disk:test . +docker/test.sh has-disk:test --download +docker/test.sh has-disk:arm --platform linux/arm/v7 # QEMU ile / with QEMU +``` + +GitHub Actions her PR'da beş mimarinin hepsini ayrı ayrı derleyip bu betikle dener (arm64 ARM makinede, arm/v7 ve arm/v6 QEMU ile); amd64'te ayrıca indirme ve `compose.yaml` ile açılış denenir; hadolint ve `docker compose config` çalışır. İmaj yalnız bütün testler geçince yayımlanır. + ## English For people without a Raspberry Pi: the HAS homepage, the emergency page and Kiwix (Wikipedia and other ZIM archives) in one container. Runs on a laptop, desktop, NAS, old PC or a Pi. @@ -83,3 +95,15 @@ Homepage: `http://:8080/home/`. Kiwix picks up new content without a - `apk upgrade` runs on every build and GitHub Actions rebuilds the image weekly, so security fixes get in. - `kiwix-serve` and `nginx` run as the non-root `has` user; the root filesystem is read-only, all capabilities are dropped except three (switching user and writing to `/library`), no access log. - Kiwix only listens inside the container (127.0.0.1) and is exposed through nginx. + +### Tests + +`docker/test.sh` starts the image with the hardening from `compose.yaml` and checks: homepage and redirects, `services.json`, Kiwix, first-run setup, login, CSRF, bad input, sessions and users surviving a restart, CLI password reset, no process running as root, only port 8080 exposed, read-only root, the wait after failed attempts. `--download` downloads a small ZIM through the panel, verifies and deletes it (needs internet). + +```sh +docker build -f docker/Dockerfile -t has-disk:test . +docker/test.sh has-disk:test --download +docker/test.sh has-disk:arm --platform linux/arm/v7 # with QEMU +``` + +On every PR, GitHub Actions builds each of the five platforms separately and runs this script (arm64 on an ARM runner, arm/v7 and arm/v6 under QEMU); amd64 also runs the download and a start with `compose.yaml`; hadolint and `docker compose config` run too. The image is published only after all tests pass. diff --git a/docker/test.sh b/docker/test.sh new file mode 100755 index 0000000..4b622b6 --- /dev/null +++ b/docker/test.sh @@ -0,0 +1,238 @@ +#!/usr/bin/env bash +# İmaj testi: konteyneri compose.yaml'daki güvenlik ayarlarıyla açar; ana sayfa, Kiwix, yönetim paneli, +# kalıcılık ve güvenlik ayarlarını dener. CI'da ve yerelde aynı betik. +# Image test: starts the container with the same hardening as compose.yaml and checks the homepage, Kiwix, +# the admin panel, persistence and the security settings. The same script runs in CI and locally. +# +# Kullanım / usage: +# docker/test.sh IMAGE [--platform linux/arm64] [--download] +# --platform imajın mimarisi (QEMU ile) / image platform (via QEMU) +# --download panelden gerçek bir ZIM indirir (~15 MB, internet ister) / downloads a real ZIM via the panel (~15 MB, needs internet) +# +# Ortam / environment: HAS_TEST_PORT (18090), HAS_TEST_TIMEOUT (240 sn / s, QEMU için uzun / long for QEMU), +# HAS_TEST_LOGS (konteyner kayıtlarının kopyası / copy of the container log) +set -uo pipefail +# Windows Git Bash: docker komutlarında konteyner içi yolları çevirme (curl'ün yerel yolları çevrilmeye devam eder). +# Windows Git Bash: do not rewrite container paths for docker (curl's local paths are still converted). +docker() { MSYS_NO_PATHCONV=1 command docker "$@"; } + +IMAGE=${1:?kullanım / usage: docker/test.sh IMAGE [--platform P] [--download]} +shift +PLATFORM="" DOWNLOAD=0 +while [ $# -gt 0 ]; do + case "$1" in + --platform) PLATFORM=$2; shift 2 ;; + --download) DOWNLOAD=1; shift ;; + *) echo "bilinmeyen seçenek / unknown option: $1" >&2; exit 2 ;; + esac +done + +PORT=${HAS_TEST_PORT:-18090} +TIMEOUT=${HAS_TEST_TIMEOUT:-240} +NAME=has-test-$$ +VOL=has-test-$$ +BASE=http://127.0.0.1:$PORT +API=$BASE/admin/api +WORK=$(mktemp -d) +JAR=$WORK/cookies +ADMIN=ci-admin +PASS=ci-password-0001 +PASS2=ci-password-0002 +ZIM=nhs.uk_en_medicines # content.conf'taki en küçük kayıtlardan / one of the smallest entries in content.conf + +passed=0 failed=0 +ok() { echo "ok - $*"; passed=$((passed + 1)); } +bad() { echo "FAIL - $*"; failed=$((failed + 1)); } +check() { local d=$1; shift; if "$@" >/dev/null 2>&1; then ok "$d"; else bad "$d"; fi; } + +cleanup() { + docker logs "$NAME" >"$WORK/container.log" 2>&1 || true + if [ "$failed" -gt 0 ]; then + echo "--- konteyner kayıtları / container logs"; tail -n 80 "$WORK/container.log" + fi + if [ -n "${HAS_TEST_LOGS:-}" ]; then cp "$WORK/container.log" "$HAS_TEST_LOGS"; fi + docker rm -f "$NAME" >/dev/null 2>&1 + docker volume rm "$VOL" >/dev/null 2>&1 + rm -rf "$WORK" +} +trap cleanup EXIT + +# req YÖNTEM YOL [JSON] [curl seçenekleri] → STATUS, BODY / req METHOD PATH [JSON] [curl options] → STATUS, BODY +# NOJAR=1 req ...: çerezsiz, başka bir tarayıcı gibi / without cookies, like another browser +# CT=text/plain req ...: gövde türü / body content type +req() { + local m=$1 p=$2 d=${3-} out + local jar=(-b "$JAR" -c "$JAR") + shift $(($# < 3 ? $# : 3)) + if [ "${NOJAR:-0}" = 1 ]; then jar=(); fi + if [ -n "$d" ]; then + out=$(curl -s -m 120 -X "$m" "${jar[@]}" -H "Content-Type: ${CT:-application/json}" --data "$d" "$@" -w '\n%{http_code}' "$API$p") + else + out=$(curl -s -m 120 -X "$m" "${jar[@]}" "$@" -w '\n%{http_code}' "$API$p") + fi + STATUS=${out##*$'\n'} BODY=${out%$'\n'*} +} +# expect AÇIKLAMA DURUM [METİN] / expect DESCRIPTION STATUS [TEXT] +expect() { + if [ "$STATUS" = "$2" ] && { [ -z "${3-}" ] || [[ $BODY == *"$3"* ]]; }; then ok "$1" + else bad "$1 (beklenen / expected $2 ${3-}; gelen / got $STATUS $BODY)"; fi +} +code() { curl -s -m 30 -o /dev/null -w '%{http_code}' "$@"; } +location() { curl -s -m 30 -o /dev/null -w '%header{location}' "$1"; } + +wait_healthy() { + local s + for _ in $(seq 1 "$TIMEOUT"); do + s=$(docker inspect -f '{{.State.Health.Status}}' "$NAME" 2>/dev/null) + [ "$s" = healthy ] && return 0 + [ "$(docker inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = true ] || return 1 + sleep 1 + done + return 1 +} +# wait_job AD: iş bitene kadar bekler, çıkış kodu JOB_EXIT'te / waits for the job, exit code in JOB_EXIT +wait_job() { + JOB_EXIT="" + for _ in $(seq 1 900); do + req GET /job + [ "$STATUS" = 200 ] || return 1 + if [[ $BODY == *'"running":false'* ]]; then + if [[ $BODY == *"\"name\":\"$1\""* ]]; then + JOB_EXIT=$(sed -n 's/.*"exitCode":\(-\{0,1\}[0-9]*\).*/\1/p' <<<"$BODY") + fi + return 0 + fi + sleep 2 + done + return 1 +} + +setup_code_logged() { docker logs "$NAME" 2>&1 | grep -q 'first-run setup code: '; } +nosniff() { curl -sI "$BASE/home/" | grep -qi '^x-content-type-options: nosniff'; } +cookie_flags() { grep -i '^set-cookie:' "$WORK/h" | grep -i httponly | grep -qi 'samesite=strict'; } +cli_reset() { printf '%s\n' "$PASS2" | docker exec -i "$NAME" has-admin reset-password "$ADMIN" --stdin | grep -q 'password changed'; } + +echo "# imaj / image: $IMAGE ${PLATFORM:+($PLATFORM)}" +docker volume create "$VOL" >/dev/null +run_args=(-d --name "$NAME" -p "127.0.0.1:$PORT:8080" -v "$VOL:/library" + --read-only --tmpfs /tmp --cap-drop ALL --cap-add SETUID --cap-add SETGID --cap-add DAC_OVERRIDE + --security-opt no-new-privileges:true --health-interval 3s --health-start-period 3s) +if [ -n "$PLATFORM" ]; then run_args+=(--platform "$PLATFORM"); fi +if ! docker run "${run_args[@]}" "$IMAGE" >/dev/null; then + bad "konteyner açılmadı / container did not start"; exit 1 +fi + +# ---------------------------------------------------------------- açılış / start-up +if wait_healthy; then ok "sağlık kontrolü / healthcheck: healthy"; else bad "sağlık kontrolü / healthcheck"; exit 1; fi +ok "mimari / architecture: $(docker exec "$NAME" uname -m)" +check "ilk kurulum kodu kayıtta / setup code in the log" setup_code_logged + +# ---------------------------------------------------------------- ana sayfa ve Kiwix / homepage and Kiwix +for p in /home/ /home/acil.html /home/oku.html /home/services.json "/kiwix/?has=1" "/kiwix/catalog/v2/entries?count=-1" /admin/; do + c=$(code "$BASE$p") + if [ "$c" = 200 ]; then ok "GET $p"; else bad "GET $p → $c"; fi +done +check "/ → /home/" test "$(location "$BASE/")" = /home/ +# Yönlendirme göreli olmalı: dışarıdaki port içerdekinden farklı olabilir (11-28 hatası). +# Redirects must be relative: the outside port can differ from the inside one (11-28 bug). +check "/home → /home/ (göreli / relative)" test "$(location "$BASE/home")" = /home/ +check "/kiwix/ → HAS okuyucusu / reader" test "$(location "$BASE/kiwix/")" = "/home/oku.html#library" +s=$(curl -s "$BASE/home/services.json") +check "services.json: kiwix kurulu / installed" grep -q '"kiwix":{"installed":true' <<<"$s" +check "services.json: has-admin kurulu / installed" grep -q '"has-admin":{"installed":true' <<<"$s" +check "services.json: maps kurulu değil / not installed" grep -q '"maps":{"installed":false' <<<"$s" +check "nosniff başlığı / header" nosniff + +# ---------------------------------------------------------------- ilk kurulum / first-run setup +req GET /session; expect "oturum: kurulum bekleniyor / session: setup pending" 200 '"setup":true' +req GET /status; expect "girişsiz durum reddedilir / status needs login" 401 login_required +CODE=$(docker logs "$NAME" 2>&1 | sed -n 's/.*first-run setup code: //p' | tail -1 | tr -d '\r') +check "setup-code komutu kayıttakiyle aynı / CLI matches the log" test "$(docker exec "$NAME" has-admin setup-code | tr -d '\r')" = "$CODE" +req POST /setup "{\"code\":\"yanlis\",\"user\":\"$ADMIN\",\"password\":\"$PASS\"}"; expect "yanlış kurulum kodu / wrong setup code" 403 wrong_setup_code +req POST /setup "{\"code\":\"$CODE\",\"user\":\"$ADMIN\",\"password\":\"kisa\"}"; expect "kısa şifre / short password" 400 short_password +req POST /setup "{\"code\":\"$CODE\",\"user\":\"$ADMIN\",\"password\":\"$PASS\"}" -D "$WORK/h"; expect "ilk kullanıcı / first user" 200 "\"user\":\"$ADMIN\"" +check "çerez HttpOnly + SameSite=Strict / cookie flags" cookie_flags +req POST /setup "{\"code\":\"$CODE\",\"user\":\"x2\",\"password\":\"$PASS\"}"; expect "ikinci kurulum reddedilir / setup only once" 409 setup_done +req GET /session; expect "oturum açık / logged in" 200 "\"user\":\"$ADMIN\"" +req GET /status; expect "durum / status" 200 '"content":[' +check "users.json izni 600 / mode 600" test "$(docker exec "$NAME" stat -c %a /library/has-admin/users.json)" = 600 + +# ---------------------------------------------------------------- CSRF ve girdi / CSRF and input +CT=text/plain req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}"; expect "JSON olmayan istek / non-JSON body" 415 json_required +req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}" -H 'Sec-Fetch-Site: cross-site' -H 'Origin: http://evil.example'; expect "başka siteden istek / cross-site request" 403 cross_origin +# Tarayıcı kutuya başka ad/portla gelir (box.lan, yönlendirilmiş port): kabul edilmeli (11-28 hatası). +# The browser reaches the box by another name/port (box.lan, forwarded port): must be accepted (11-28 bug). +req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}" -H 'Sec-Fetch-Site: same-origin' -H 'Origin: http://box.lan:8888'; expect "aynı site, başka ad/port / same-origin via another name and port" 200 "\"user\":\"$ADMIN\"" +NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"yanlis-sifre-00\"}"; expect "yanlış şifre / wrong password" 401 wrong_login +req POST /download '{"prefixes":[]}'; expect "boş seçim / empty selection" 400 choose_content +req POST /download '{"prefixes":["../../etc/passwd"]}'; expect "listede olmayan içerik / not in content.conf" 400 not_in_list +req POST /delete "{\"file\":\"../users.json\",\"password\":\"$PASS\"}"; expect "geçersiz dosya adı / invalid file name" 400 invalid_file +req POST /delete '{"file":"yok.zim","password":"yanlis-sifre-00"}'; expect "silmede yanlış şifre / wrong password on delete" 403 wrong_password +req POST /delete "{\"file\":\"yok.zim\",\"password\":\"$PASS\"}"; expect "olmayan dosya / missing file" 404 file_not_found + +# ---------------------------------------------------------------- indirme / download +if [ "$DOWNLOAD" = 1 ]; then + req POST /download "{\"prefixes\":[\"$ZIM\"]}"; expect "indirme başladı / download started" 202 started + wait_job download; check "indirme bitti / download finished (exit $JOB_EXIT)" test "$JOB_EXIT" = 0 + req GET /status; expect "ZIM ve .sha256 diskte / ZIM and .sha256 on disk" 200 '"sha256":true' + F=$(grep -o "\"name\":\"${ZIM}_[^\"]*\.zim\"" <<<"$BODY" | head -1 | cut -d'"' -f4) + found=0 + for _ in $(seq 1 30); do + if curl -s "$BASE/kiwix/catalog/v2/entries?count=-1" | grep -q "$ZIM"; then found=1; break; fi + sleep 1 + done + check "Kiwix kataloğunda / in the Kiwix catalog: $F" test "$found" = 1 + req POST /verify '{}'; expect "doğrulama başladı / verify started" 202 started + wait_job verify; check "doğrulama / verify (exit $JOB_EXIT)" test "$JOB_EXIT" = 0 + req POST /delete "{\"file\":\"$F\",\"password\":\"$PASS\"}"; expect "şifreyle silme / delete with password" 200 removed + wait_job library + req GET /status + if [ -n "$F" ] && [[ $BODY != *"$F"* ]]; then ok "silinen dosya listede yok / deleted file gone"; else bad "silinen dosya / deleted file: '$F'"; fi +fi + +# ---------------------------------------------------------------- yeniden başlatma / restart +docker restart "$NAME" >/dev/null +if wait_healthy; then ok "yeniden başlatma / restart: healthy"; else bad "yeniden başlatma / restart"; exit 1; fi +req GET /session; expect "oturum yeniden başlatmada kalır / session survives restart" 200 "\"user\":\"$ADMIN\"" +NOJAR=1 req GET /session; expect "kullanıcı kalıcı / user persists" 200 '"setup":false' + +# ---------------------------------------------------------------- komut satırından şifre / CLI password reset +check "reset-password --stdin" cli_reset +req GET /session; expect "şifre değişince eski oturum kapanır / old session ends" 200 '"user":""' +NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}"; expect "eski şifre geçmez / old password rejected" 401 wrong_login +req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS2\"}"; expect "yeni şifreyle giriş / login with new password" 200 "\"user\":\"$ADMIN\"" +req POST /logout '{}'; expect "çıkış / logout" 200 '"ok":true' +req GET /status; expect "çıkıştan sonra durum kapalı / status closed after logout" 401 login_required + +# ---------------------------------------------------------------- güvenlik / security +ps_out=$(docker exec "$NAME" ps -o user,args) +listen=$(docker exec "$NAME" netstat -ltn 2>/dev/null | awk 'NR>2 {print $4}') +kiwix_not_root() { grep kiwix-serve <<<"$ps_out" | grep -v grep | grep -qv '^root'; } +nginx_not_root() { grep -q nginx <<<"$ps_out" && ! grep nginx <<<"$ps_out" | grep -v grep | grep -q '^root'; } +only_8080_outside() { + grep -q ':8080$' <<<"$listen" && + ! grep -vE '^(127\.0\.0\.1:[0-9]+|0\.0\.0\.0:8080|:::8080|\[::\]:8080)$' <<<"$listen" | grep -q . +} +root_fs_read_only() { ! docker exec "$NAME" touch /opt/has/yazilabilir 2>/dev/null; } +check "kiwix-serve root değil / not root" kiwix_not_root +check "nginx süreçleri root değil / nginx not root" nginx_not_root +check "yalnız 8080 dışa açık / only 8080 listens outside ($(echo $listen))" only_8080_outside +check "kök dosya sistemi salt okunur / read-only root fs" root_fs_read_only + +# Hatalı denemede bekleme (en sonda: bu adresi bir dakika kilitler). +# Growing wait after failed attempts (last: it locks this address for a minute). +for _ in 1 2 3 4 5; do NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"yanlis-sifre-00\"}"; done +NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS2\"}"; expect "5 hatadan sonra bekleme / wait after 5 failures" 429 too_many_attempts + +# ---------------------------------------------------------------- özet / summary +size=$(docker image inspect "$IMAGE" -f '{{.Size}}' 2>/dev/null || echo 0) +versions=$(docker exec "$NAME" sh -c 'kiwix-serve --version 2>&1 | head -1; nginx -v 2>&1; echo "alpine $(cat /etc/alpine-release)"' | tr '\n' ' ') +echo "# boyut / size: $((size / 1000000)) MB · $versions" +echo "# sonuç / result: $passed ok, $failed hata / failed" +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + { + echo "### ${PLATFORM:-local}: $passed ok, $failed failed" + echo "Image size $((size / 1000000)) MB · $versions" + } >>"$GITHUB_STEP_SUMMARY" +fi +[ "$failed" = 0 ] From f65b2985dff301f9d16a85a274a9e97ac9b49a88 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 02:39:20 +0300 Subject: [PATCH 15/65] ci(docker): run the tests on every branch, publish only from main and tags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The push trigger used to cover only main, so pushing a side branch or a fork did not run the workflow at all. Tests now run on every push (with the paths filter); the publish job is limited to main, v* tags and the weekly build. Önceden push tetikleyicisi yalnız main'deydi; fork'ta ya da yan dalda push edilince workflow hiç çalışmıyordu. Testler artık her push'ta (paths süzgeciyle) çalışıyor; yayın işi main, v* etiketi ve haftalık derlemeyle sınırlı. --- .github/workflows/docker.yml | 13 +++++++++---- docker/README.md | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 1779dac..98ea079 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -2,13 +2,15 @@ name: Docker # Çok mimarili imajı derler, her mimaride dener (docker/test.sh) ve GitHub Container Registry'ye (ghcr.io) gönderir. # Builds the multi-architecture image, tests it on every platform (docker/test.sh) and pushes it to ghcr.io. -# Gönderim yalnız tüm testler geçince. PR'larda yalnız derlenir ve denenir. -# Pushing happens only after every test passes. On pull requests it is only built and tested. +# Gönderim yalnız tüm testler geçince ve yalnız ana daldan / sürüm etiketinden. Diğer dallarda ve PR'larda +# yalnız derlenir ve denenir (fork'ta çalışırken de). +# Pushing happens only after every test passes, and only from the default branch or a version tag. +# Other branches and pull requests are only built and tested (also while working in a fork). # Haftalık derleme Alpine güvenlik düzeltmelerini imaja alır. / The weekly build picks up Alpine security fixes. on: push: - branches: [main] + branches: ['**'] tags: ['v*'] paths: - 'docker/**' @@ -130,7 +132,10 @@ jobs: publish: name: Yayımla / publish needs: [lint, test] - if: github.event_name != 'pull_request' + if: >- + github.event_name != 'pull_request' && + (github.ref == 'refs/heads/main' || + startsWith(github.ref, 'refs/tags/v')) runs-on: ubuntu-latest permissions: contents: read diff --git a/docker/README.md b/docker/README.md index 9e5894f..67755ba 100644 --- a/docker/README.md +++ b/docker/README.md @@ -52,7 +52,7 @@ docker/test.sh has-disk:test --download docker/test.sh has-disk:arm --platform linux/arm/v7 # QEMU ile / with QEMU ``` -GitHub Actions her PR'da beş mimarinin hepsini ayrı ayrı derleyip bu betikle dener (arm64 ARM makinede, arm/v7 ve arm/v6 QEMU ile); amd64'te ayrıca indirme ve `compose.yaml` ile açılış denenir; hadolint ve `docker compose config` çalışır. İmaj yalnız bütün testler geçince yayımlanır. +GitHub Actions her push'ta ve PR'da beş mimarinin hepsini ayrı ayrı derleyip bu betikle dener (arm64 ARM makinede, arm/v7 ve arm/v6 QEMU ile); amd64'te ayrıca indirme ve `compose.yaml` ile açılış denenir; hadolint ve `docker compose config` çalışır. İmaj yalnız bütün testler geçince ve yalnız `main`'den ya da `v*` etiketinden yayımlanır. ## English @@ -106,4 +106,4 @@ docker/test.sh has-disk:test --download docker/test.sh has-disk:arm --platform linux/arm/v7 # with QEMU ``` -On every PR, GitHub Actions builds each of the five platforms separately and runs this script (arm64 on an ARM runner, arm/v7 and arm/v6 under QEMU); amd64 also runs the download and a start with `compose.yaml`; hadolint and `docker compose config` run too. The image is published only after all tests pass. +On every push and PR, GitHub Actions builds each of the five platforms separately and runs this script (arm64 on an ARM runner, arm/v7 and arm/v6 under QEMU); amd64 also runs the download and a start with `compose.yaml`; hadolint and `docker compose config` run too. The image is published only after all tests pass, and only from `main` or a `v*` tag. From 9e7265940989305e51d154a3d0ea6b6a59682820 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 02:39:46 +0300 Subject: [PATCH 16/65] fix(services): detect the newer IIAB Maps install path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The maintainer's has-disk-setup branch uses IIAB Maps (maps_install, /library/www/maps); the module only looked for the older osm-vector-maps folder, so an installed map would show as not installed. Both paths are accepted now. Bakımcının has-disk-setup dalı IIAB Maps'i (maps_install, /library/www/maps) kullanıyor; modül yalnız eski osm-vector-maps klasörüne bakıyordu, harita kurulu olsa da 'Henüz yüklenmedi' görünecekti. İki yol da kabul ediliyor. --- scripts/services.d/maps.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/services.d/maps.sh b/scripts/services.d/maps.sh index bbf3814..6b0c660 100644 --- a/scripts/services.d/maps.sh +++ b/scripts/services.d/maps.sh @@ -1,5 +1,5 @@ # shellcheck shell=bash disable=SC2034 # services.sh içine alınır / sourced by services.sh -# IIAB haritası (osm-vector-maps): /maps → /library/www/osm-vector-maps/viewer -# IIAB map (osm-vector-maps): /maps → /library/www/osm-vector-maps/viewer +# IIAB haritası /maps: yeni IIAB Maps (/library/www/maps) ya da eski osm-vector-maps. +# IIAB map at /maps: the newer IIAB Maps (/library/www/maps) or the older osm-vector-maps. label_tr="Harita"; label_en="Map"; url="/maps" -check(){ [ -d /library/www/osm-vector-maps/viewer ]; } +check(){ [ -f /library/www/maps/index.html ] || [ -d /library/www/osm-vector-maps/viewer ]; } From 2c29c674ca68f4a9622217f4e4b3e844cbff5b14 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 03:26:17 +0300 Subject: [PATCH 17/65] fix(docker): restart only the admin panel when it stops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before, the container stopped when the panel (has-admin) exited, so with restart: unless-stopped a crashing panel took the homepage and Kiwix down with it (seen on 386 in CI). The panel now runs in its own loop and restarts after 10 s; the container stops only when kiwix-serve or nginx stops. Önceden panel (has-admin) çıkınca wait -n bütün konteyneri kapatıyordu; restart: unless-stopped ile sürekli çöken bir panel ana sayfayı ve Kiwix'i de kapatıp açardı (CI'da 386'da görüldü). Panel artık kendi döngüsünde 10 sn arayla yeniden başlıyor; konteyner yalnız kiwix-serve ya da nginx durunca duruyor. --- docker/entrypoint.sh | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index f605b99..32aa40b 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -23,10 +23,19 @@ su-exec has kiwix-serve --library --monitorLibrary --address=127.0.0.1 --port=80 su-exec has nginx -e stderr -g 'daemon off;' & # Yönetim paneli root çalışır, çünkü indirme betiği root ister; yalnız 127.0.0.1'de, nginx arkasında dinler. # The admin panel runs as root because the download script requires it; it only listens on 127.0.0.1 behind nginx. -HAS_REPO=/opt/has has-admin & +# Panel durursa yalnız panel yeniden başlatılır; ana sayfa ve Kiwix açık kalır (afette içerik paneldan önemli). +# If the panel stops only the panel is restarted; the homepage and Kiwix stay up (content matters more than the panel). +( + while :; do + rc=0 + HAS_REPO=/opt/has has-admin || rc=$? + echo "has-admin durdu (çıkış $rc), 10 sn sonra yeniden / has-admin stopped (exit $rc), restarting in 10 s" >&2 + sleep 10 + done +) & -# Biri durursa konteyner de durur, Docker yeniden başlatır (restart: unless-stopped). -# If either process stops, the container stops and Docker restarts it (restart: unless-stopped). +# kiwix-serve ya da nginx durursa konteyner de durur, Docker yeniden başlatır (restart: unless-stopped). +# If kiwix-serve or nginx stops, the container stops and Docker restarts it (restart: unless-stopped). set +e wait -n status=$? From c1b88a3927f799e4115f404e723b238c991b9b43 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 03:26:17 +0300 Subject: [PATCH 18/65] ci(docker): run the 386 test on ubuntu-24.04 and fix false failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ubuntu-latest (26.04) ships Docker 29.4.2, whose seccomp profile blocks socketcall (moby/profiles#21, reverted in 29.4.3; actions/runner-images#14790), so Go and kiwix-serve have no network on 32-bit x86. The 386 job moves to ubuntu-24.04 (Docker 28.0.4); on that version + 386 test.sh states the cause and stops instead of weakening the hardening. README note added. test.sh: the reset-password check uses the exit code (pipefail + grep -q gave a false failure on arm/v6); new checks that the homepage and Kiwix stay up while the panel is stopped and that the panel comes back. ubuntu-latest (26.04) Docker 29.4.2 ile geliyor; o sürümün seccomp profili socketcall'u kapatıyor (moby/profiles#21, 29.4.3'te geri alındı; actions/runner-images#14790) ve 32 bit x86'da Go ile kiwix-serve ağa çıkamıyor. 386 işi Docker 28.0.4'lü ubuntu-24.04'e alındı; test.sh bu sürüm + 386'da güvenliği gevşetmeden nedeni yazıp duruyor. README'ye not. test.sh: reset-password kontrolü çıkış koduna bakıyor (pipefail + grep -q yüzünden arm/v6'da yanlış hata veriyordu); panel kapatılınca ana sayfa ve Kiwix açık kalıyor mu, panel geri geliyor mu kontrolü eklendi. --- .github/workflows/docker.yml | 6 +++++- docker/README.md | 6 ++++-- docker/test.sh | 26 ++++++++++++++++++++++++-- 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 98ea079..3e55311 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -79,7 +79,11 @@ jobs: - { platform: linux/arm64, scope: arm64, runner: ubuntu-24.04-arm, qemu: false, full: false } - { platform: linux/arm/v7, scope: armv7, runner: ubuntu-latest, qemu: true, full: false } - { platform: linux/arm/v6, scope: armv6, runner: ubuntu-latest, qemu: true, full: false } - - { platform: linux/386, scope: '386', runner: ubuntu-latest, qemu: false, full: false } + # 386 ubuntu-24.04'te: ubuntu-latest (26.04) Docker 29.4.2 ile geliyor, o sürüm 32 bit x86'da socketcall'u + # kapatıyor (actions/runner-images#14790, moby/profiles#21; 29.4.3'te düzeldi). 24.04'te Docker 28.0.4. + # 386 on ubuntu-24.04: ubuntu-latest (26.04) ships Docker 29.4.2, which blocks socketcall on 32-bit x86 + # (actions/runner-images#14790, moby/profiles#21; fixed in 29.4.3). 24.04 has Docker 28.0.4. + - { platform: linux/386, scope: '386', runner: ubuntu-24.04, qemu: false, full: false } steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/docker/README.md b/docker/README.md index 67755ba..4a1daa7 100644 --- a/docker/README.md +++ b/docker/README.md @@ -4,7 +4,7 @@ Raspberry Pi'si olmayanlar için: HAS ana sayfası, acil durum sayfası ve Kiwix (Vikipedi ve diğer ZIM arşivleri) tek bir konteynerde. Dizüstü, masaüstü, NAS, eski bilgisayar ya da Pi'de çalışır. -**Platformlar:** `linux/amd64`, `linux/arm64` (Pi 3/4/5 64 bit), `linux/arm/v7` ve `linux/arm/v6` (32 bit Pi, Pi Zero), `linux/386`. +**Platformlar:** `linux/amd64`, `linux/arm64` (Pi 3/4/5 64 bit), `linux/arm/v7` ve `linux/arm/v6` (32 bit Pi, Pi Zero), `linux/386`. Not: yalnız Docker 29.4.2'de 386 imajı ağa çıkamaz; o sürümün güvenlik profili 32 bit x86'nın ağ çağrısını (`socketcall`) kapatıyordu ([moby/profiles#21](https://github.com/moby/profiles/pull/21)), 29.4.3'te geri alındı. Docker'ı güncellemek yeterli. **İmajda olanlar:** ana sayfa (`www/home`), Kiwix (`kiwix-serve` 3.8.2), içerik indirme (`scripts/download-content.sh`, aynı `config/content.conf` listesi) ve çevrimdışı doğrulama (`scripts/verify-content.sh`). **Olmayanlar:** Wi-Fi hotspot, captive portal, Kolibri, harita, IIAB yönetim paneli (yerine HAS yönetim paneli var). Bunlar Pi kurulumunda (`install.sh`) var. Docker'da cihazınızın kendi ağı kullanılır. @@ -40,6 +40,7 @@ Ana sayfa: `http://:8080/home/`. İndirme bitince Kiwix yeni içeriği - Taban imaj Alpine 3.24.4 (sürüme sabit); Kiwix resmî statik ikili dosyaları sürüm + SHA-256 ile doğrulanıyor. - Her derlemede `apk upgrade` çalışır; GitHub Actions imajı her hafta yeniden derler, güvenlik düzeltmeleri böyle gelir. - `kiwix-serve` ve `nginx` root olmayan `has` kullanıcısıyla çalışır; kök dosya sistemi salt okunur, yetkilerin hepsi düşürülür (yalnız kullanıcı değişimi ve `/library`'ye yazma için üç yetki kalır), erişim kaydı tutulmaz. +- Yönetim paneli durursa yalnız panel 10 sn sonra yeniden başlar; ana sayfa ve Kiwix açık kalır. - Kiwix yalnız konteyner içinde (127.0.0.1) dinler, dışarıya nginx üzerinden açılır. ### Test @@ -58,7 +59,7 @@ GitHub Actions her push'ta ve PR'da beş mimarinin hepsini ayrı ayrı derleyip For people without a Raspberry Pi: the HAS homepage, the emergency page and Kiwix (Wikipedia and other ZIM archives) in one container. Runs on a laptop, desktop, NAS, old PC or a Pi. -**Platforms:** `linux/amd64`, `linux/arm64` (64-bit Pi 3/4/5), `linux/arm/v7` and `linux/arm/v6` (32-bit Pi, Pi Zero), `linux/386`. +**Platforms:** `linux/amd64`, `linux/arm64` (64-bit Pi 3/4/5), `linux/arm/v7` and `linux/arm/v6` (32-bit Pi, Pi Zero), `linux/386`. Note: only on Docker 29.4.2 the 386 image has no network; that version's security profile blocked the 32-bit x86 network call (`socketcall`) ([moby/profiles#21](https://github.com/moby/profiles/pull/21)), reverted in 29.4.3. Updating Docker is enough. **Included:** homepage (`www/home`), Kiwix (`kiwix-serve` 3.8.2), content download (`scripts/download-content.sh`, same `config/content.conf` list) and offline verification (`scripts/verify-content.sh`). **Not included:** Wi-Fi hotspot, captive portal, Kolibri, maps, IIAB admin console (the HAS admin panel replaces it). These come with the Pi install (`install.sh`). With Docker the device's own network is used. @@ -94,6 +95,7 @@ Homepage: `http://:8080/home/`. Kiwix picks up new content without a - Base image Alpine 3.24.4 (pinned by version); the official static Kiwix binaries are checked against a pinned SHA-256. - `apk upgrade` runs on every build and GitHub Actions rebuilds the image weekly, so security fixes get in. - `kiwix-serve` and `nginx` run as the non-root `has` user; the root filesystem is read-only, all capabilities are dropped except three (switching user and writing to `/library`), no access log. +- If the admin panel stops, only the panel restarts after 10 s; the homepage and Kiwix stay up. - Kiwix only listens inside the container (127.0.0.1) and is exposed through nginx. ### Tests diff --git a/docker/test.sh b/docker/test.sh index 4b622b6..f48341d 100755 --- a/docker/test.sh +++ b/docker/test.sh @@ -110,7 +110,6 @@ wait_job() { setup_code_logged() { docker logs "$NAME" 2>&1 | grep -q 'first-run setup code: '; } nosniff() { curl -sI "$BASE/home/" | grep -qi '^x-content-type-options: nosniff'; } cookie_flags() { grep -i '^set-cookie:' "$WORK/h" | grep -i httponly | grep -qi 'samesite=strict'; } -cli_reset() { printf '%s\n' "$PASS2" | docker exec -i "$NAME" has-admin reset-password "$ADMIN" --stdin | grep -q 'password changed'; } echo "# imaj / image: $IMAGE ${PLATFORM:+($PLATFORM)}" docker volume create "$VOL" >/dev/null @@ -118,6 +117,14 @@ run_args=(-d --name "$NAME" -p "127.0.0.1:$PORT:8080" -v "$VOL:/library" --read-only --tmpfs /tmp --cap-drop ALL --cap-add SETUID --cap-add SETGID --cap-add DAC_OVERRIDE --security-opt no-new-privileges:true --health-interval 3s --health-start-period 3s) if [ -n "$PLATFORM" ]; then run_args+=(--platform "$PLATFORM"); fi +# Docker 29.4.2'nin varsayılan seccomp profili socketcall'u kapatıyor (moby/profiles#21, 29.4.3'te geri alındı); +# 32 bit x86'da Go ve kiwix-serve ağ çağrılarını onunla yapar. Güvenliği gevşetmek yerine nedeni söyleyip dur. +# Docker 29.4.2's default seccomp profile blocks socketcall (moby/profiles#21, reverted in 29.4.3); on 32-bit x86 +# Go and kiwix-serve make their network calls through it. Say why and stop instead of weakening the hardening. +if [ "$PLATFORM" = linux/386 ] && [ "$(docker version -f '{{.Server.Version}}' 2>/dev/null)" = 29.4.2 ]; then + bad "Docker 29.4.2 linux/386 çalıştıramaz, 29.4.3+ gerekir / cannot run linux/386, needs 29.4.3+ (moby/profiles#21)" + exit 1 +fi if ! docker run "${run_args[@]}" "$IMAGE" >/dev/null; then bad "konteyner açılmadı / container did not start"; exit 1 fi @@ -197,7 +204,9 @@ req GET /session; expect "oturum yeniden başlatmada kalır / session survives r NOJAR=1 req GET /session; expect "kullanıcı kalıcı / user persists" 200 '"setup":false' # ---------------------------------------------------------------- komut satırından şifre / CLI password reset -check "reset-password --stdin" cli_reset +reset_out=$(printf '%s\n' "$PASS2" | docker exec -i "$NAME" has-admin reset-password "$ADMIN" --stdin 2>&1) +reset_rc=$? +if [ "$reset_rc" = 0 ]; then ok "reset-password --stdin"; else bad "reset-password --stdin (çıkış / exit $reset_rc: $reset_out)"; fi req GET /session; expect "şifre değişince eski oturum kapanır / old session ends" 200 '"user":""' NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}"; expect "eski şifre geçmez / old password rejected" 401 wrong_login req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS2\"}"; expect "yeni şifreyle giriş / login with new password" 200 "\"user\":\"$ADMIN\"" @@ -219,6 +228,19 @@ check "nginx süreçleri root değil / nginx not root" nginx_not_root check "yalnız 8080 dışa açık / only 8080 listens outside ($(echo $listen))" only_8080_outside check "kök dosya sistemi salt okunur / read-only root fs" root_fs_read_only +# Panel durursa ana sayfa ve Kiwix açık kalmalı, panel kendiliğinden geri gelmeli. +# If the panel stops, the homepage and Kiwix must stay up and the panel must come back by itself. +docker exec "$NAME" pkill -x has-admin +sleep 2 +check "panel durunca ana sayfa açık / homepage up while the panel is down" test "$(code "$BASE/home/")" = 200 +check "panel durunca Kiwix açık / Kiwix up while the panel is down" test "$(code "$BASE/kiwix/?has=1")" = 200 +back=0 +for _ in $(seq 1 60); do + if [ "$(code "$API/session")" = 200 ]; then back=1; break; fi + sleep 1 +done +check "panel kendiliğinden geri geldi / panel restarted by itself" test "$back" = 1 + # Hatalı denemede bekleme (en sonda: bu adresi bir dakika kilitler). # Growing wait after failed attempts (last: it locks this address for a minute). for _ in 1 2 3 4 5; do NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"yanlis-sifre-00\"}"; done From 5a43eab56ed525319e68049cc593389df047ebc7 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 03:28:50 +0300 Subject: [PATCH 19/65] test(docker): check reset-password by exit code and message MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The output is captured first and then searched for 'password changed'; piping straight into 'grep -q' with pipefail could hit SIGPIPE and fail falsely on slow machines. Çıktı önce değişkene alınıyor, sonra 'password changed' aranıyor; doğrudan '| grep -q' pipefail ile SIGPIPE'a takılıp yavaş makinede yanlış hata veriyordu. --- docker/test.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docker/test.sh b/docker/test.sh index f48341d..c9dcb4e 100755 --- a/docker/test.sh +++ b/docker/test.sh @@ -204,9 +204,14 @@ req GET /session; expect "oturum yeniden başlatmada kalır / session survives r NOJAR=1 req GET /session; expect "kullanıcı kalıcı / user persists" 200 '"setup":false' # ---------------------------------------------------------------- komut satırından şifre / CLI password reset +# Çıktı önce değişkene alınır: doğrudan `| grep -q` ile pipefail, grep erken çıkınca docker exec'i SIGPIPE ile +# düşürüp yanlış hata verebiliyor (yavaş QEMU'da, arm/v6'da görüldü). +# The output is captured first: piping into `grep -q` with pipefail can kill docker exec with SIGPIPE when grep +# exits early, a false failure (seen under slow QEMU on arm/v6). reset_out=$(printf '%s\n' "$PASS2" | docker exec -i "$NAME" has-admin reset-password "$ADMIN" --stdin 2>&1) reset_rc=$? -if [ "$reset_rc" = 0 ]; then ok "reset-password --stdin"; else bad "reset-password --stdin (çıkış / exit $reset_rc: $reset_out)"; fi +if [ "$reset_rc" = 0 ] && [[ $reset_out == *'password changed'* ]]; then ok "reset-password --stdin" +else bad "reset-password --stdin (çıkış / exit $reset_rc: $reset_out)"; fi req GET /session; expect "şifre değişince eski oturum kapanır / old session ends" 200 '"user":""' NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}"; expect "eski şifre geçmez / old password rejected" 401 wrong_login req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS2\"}"; expect "yeni şifreyle giriş / login with new password" 200 "\"user\":\"$ADMIN\"" From 099c08f31e1191e224fb4c489536c366edc9a263 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 03:35:12 +0300 Subject: [PATCH 20/65] test(docker): wait for the setup code and stop piping into grep -q MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The healthcheck only covers nginx, so on arm/v7 (QEMU) the check ran before the panel had logged the setup code; it now waits up to the timeout. '| grep -q' chains can fail falsely with SIGPIPE under pipefail, so outputs are captured first and the process and port checks use a single awk step. Under QEMU ps shows {nginx} in the second column, so the pattern is not anchored. Sağlık kontrolü yalnız nginx'e baktığı için arm/v7'de (QEMU) panel kurulum kodunu yazmadan kontrol yapılıyordu; artık zaman aşımına kadar bekleniyor. '| grep -q' zincirleri pipefail altında SIGPIPE ile yanlış hata verebildiği için çıktılar önce değişkene alınıyor, süreç ve port kontrolleri tek adımda awk ile. QEMU'da ps ikinci sütunu {nginx} gösterdiği için desen başa sabitlenmiyor. --- docker/test.sh | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/docker/test.sh b/docker/test.sh index c9dcb4e..d5c66bd 100755 --- a/docker/test.sh +++ b/docker/test.sh @@ -107,9 +107,21 @@ wait_job() { return 1 } -setup_code_logged() { docker logs "$NAME" 2>&1 | grep -q 'first-run setup code: '; } -nosniff() { curl -sI "$BASE/home/" | grep -qi '^x-content-type-options: nosniff'; } -cookie_flags() { grep -i '^set-cookie:' "$WORK/h" | grep -i httponly | grep -qi 'samesite=strict'; } +# Sağlık kontrolü yalnız nginx'e bakar; panel QEMU'da birkaç saniye sonra açılabilir, kurulum kodunu bekle. +# Kayıt önce değişkene alınır (| grep -q + pipefail SIGPIPE'a takılabilir). +# The healthcheck only covers nginx; under QEMU the panel can start a few seconds later, so wait for the code. +# The log is captured first (| grep -q with pipefail can hit SIGPIPE). +setup_code_logged() { + local logs + for _ in $(seq 1 "$TIMEOUT"); do + logs=$(docker logs "$NAME" 2>&1) + [[ $logs == *'first-run setup code: '* ]] && return 0 + sleep 1 + done + return 1 +} +nosniff() { local h; h=$(curl -sI "$BASE/home/"); grep -qi '^x-content-type-options: nosniff' <<<"$h"; } +cookie_flags() { local c; c=$(grep -i '^set-cookie:' "$WORK/h"); [[ ${c,,} == *httponly* && ${c,,} == *samesite=strict* ]]; } echo "# imaj / image: $IMAGE ${PLATFORM:+($PLATFORM)}" docker volume create "$VOL" >/dev/null @@ -185,7 +197,8 @@ if [ "$DOWNLOAD" = 1 ]; then F=$(grep -o "\"name\":\"${ZIM}_[^\"]*\.zim\"" <<<"$BODY" | head -1 | cut -d'"' -f4) found=0 for _ in $(seq 1 30); do - if curl -s "$BASE/kiwix/catalog/v2/entries?count=-1" | grep -q "$ZIM"; then found=1; break; fi + catalog=$(curl -s "$BASE/kiwix/catalog/v2/entries?count=-1") + if [[ $catalog == *"$ZIM"* ]]; then found=1; break; fi sleep 1 done check "Kiwix kataloğunda / in the Kiwix catalog: $F" test "$found" = 1 @@ -221,11 +234,14 @@ req GET /status; expect "çıkıştan sonra durum kapalı / status closed after # ---------------------------------------------------------------- güvenlik / security ps_out=$(docker exec "$NAME" ps -o user,args) listen=$(docker exec "$NAME" netstat -ltn 2>/dev/null | awk 'NR>2 {print $4}') -kiwix_not_root() { grep kiwix-serve <<<"$ps_out" | grep -v grep | grep -qv '^root'; } -nginx_not_root() { grep -q nginx <<<"$ps_out" && ! grep nginx <<<"$ps_out" | grep -v grep | grep -q '^root'; } +# Süzme awk ile tek adımda: | grep -q zincirleri pipefail altında SIGPIPE'a takılabilir. +# QEMU altında ps ikinci sütunu {nginx} gösterir; desen bu yüzden başa sabitlenmez. +# Filtering in one awk step: | grep -q chains can hit SIGPIPE under pipefail. +# Under QEMU ps shows {nginx} in the second column, so the pattern is not anchored. +kiwix_not_root() { awk '$2 ~ /kiwix-serve/ {n++; if ($1 == "root") r++} END {exit !(n > 0 && r == 0)}' <<<"$ps_out"; } +nginx_not_root() { awk '$2 ~ /nginx/ {n++; if ($1 == "root") r++} END {exit !(n > 0 && r == 0)}' <<<"$ps_out"; } only_8080_outside() { - grep -q ':8080$' <<<"$listen" && - ! grep -vE '^(127\.0\.0\.1:[0-9]+|0\.0\.0\.0:8080|:::8080|\[::\]:8080)$' <<<"$listen" | grep -q . + awk '/:8080$/ {p++; next} !/^127\.0\.0\.1:[0-9]+$/ {o++} END {exit !(p > 0 && o == 0)}' <<<"$listen" } root_fs_read_only() { ! docker exec "$NAME" touch /opt/has/yazilabilir 2>/dev/null; } check "kiwix-serve root değil / not root" kiwix_not_root From 584b10fa0e382d72406b3814498548117e8901e8 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 03:42:07 +0300 Subject: [PATCH 21/65] test(docker): cover far more of the image in test.sh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The image test grows from 54 to 134 checks (156 with --download): - image metadata: HEALTHCHECK, port 8080, /library volume, tini entrypoint - start-up: kiwix-serve version matches the Dockerfile, data dir 700, setup code file 600 - web: missing pages 404, ZIMs and panel data not served, no ../ traversal, Referrer-Policy, hidden nginx version, panel X-Frame-Options / Cache-Control / CSP, no outside resources on any page (offline), theme choice on every page, reader bar elements, TR + EN text for every API error code - panel: every endpoint needs login, invalid user name, broken JSON, cookie path and 12 h lifetime, setup code file removed, status fields, password and cookie never stored in plain text, form bodies rejected, no CORS, no GET login, forged cookie, mixed valid and unknown download entries, empty delete password - download: second job rejected while busy, stop and resume, SHA-256 matches, book opens, search and random work, content survives a restart, library.xml rebuilt from the ZIMs, delete also removes .sha256 and the catalog entry - CLI: --stdin does not echo the password, short password and unknown command rejected, random password works, the old cookie is invalid on the server after logout - security: no capabilities for the has user, no-new-privileges; memory use and a clean stop under 15 s are reported No '| grep -q' is left in the script: under pipefail it can fail falsely with SIGPIPE. İmaj testi 54'ten 134 kontrole çıktı (--download ile 156): - imaj bilgisi: HEALTHCHECK, 8080 portu, /library volume, tini giriş noktası - açılış: kiwix-serve sürümü Dockerfile'daki ile aynı, veri klasörü 700, kurulum kodu dosyası 600 - web: olmayan sayfa 404, ZIM'ler ve panel verisi dışarıdan okunamıyor, ../ ile yol aşımı yok, Referrer-Policy, nginx sürümü gizli, panelde X-Frame-Options / Cache-Control / CSP, hiçbir sayfa dışarıdan kaynak yüklemiyor (çevrimdışı), her sayfada tema seçimi, okuyucu çubuğunun öğeleri, API'nin her hata kodu için TR + EN metin - panel: her uç giriş istiyor, geçersiz kullanıcı adı, bozuk JSON, çerez yolu ve 12 saatlik ömrü, kurulum kodu dosyasının silinmesi, durum alanları, şifre ve çerez düz metin saklanmıyor, form gövdesi reddediliyor, CORS yok, GET ile giriş yok, uydurma çerez, geçerli ve bilinmeyen öğe karışık indirme, silmede boş şifre - indirme: iş sürerken ikinci iş reddediliyor, durdurup kaldığı yerden sürdürme, SHA-256 eşleşiyor, kitap açılıyor, arama ve rastgele sayfa çalışıyor, içerik yeniden başlatmada kalıyor, library.xml ZIM'lerden yeniden kuruluyor, silme .sha256'yı ve katalog kaydını da kaldırıyor - komut satırı: --stdin şifreyi ekrana yazmıyor, kısa şifre ve bilinmeyen komut reddediliyor, rastgele şifre çalışıyor, çıkıştan sonra eski çerez sunucuda da geçersiz - güvenlik: has kullanıcısında yetki yok, no-new-privileges; bellek kullanımı ve 15 sn'den kısa düzgün kapanış raporlanıyor Betikte '| grep -q' kalmadı: pipefail altında SIGPIPE ile yanlış hata verebiliyor. --- docker/test.sh | 241 +++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 205 insertions(+), 36 deletions(-) diff --git a/docker/test.sh b/docker/test.sh index d5c66bd..0766d25 100755 --- a/docker/test.sh +++ b/docker/test.sh @@ -11,6 +11,11 @@ # # Ortam / environment: HAS_TEST_PORT (18090), HAS_TEST_TIMEOUT (240 sn / s, QEMU için uzun / long for QEMU), # HAS_TEST_LOGS (konteyner kayıtlarının kopyası / copy of the container log) +# +# Not: '| grep -q' kullanılmaz. pipefail altında grep erken çıkınca soldaki komut SIGPIPE alır ve kontrol yanlış +# düşer (yavaş QEMU'da görüldü); çıktı önce değişkene alınır. +# Note: no '| grep -q'. Under pipefail, grep exiting early sends SIGPIPE to the left-hand command and the check +# fails falsely (seen under slow QEMU); output is captured into a variable first. set -uo pipefail # Windows Git Bash: docker komutlarında konteyner içi yolları çevirme (curl'ün yerel yolları çevrilmeye devam eder). # Windows Git Bash: do not rewrite container paths for docker (curl's local paths are still converted). @@ -27,6 +32,7 @@ while [ $# -gt 0 ]; do esac done +REPO=$(cd "$(dirname "$0")/.." && pwd) PORT=${HAS_TEST_PORT:-18090} TIMEOUT=${HAS_TEST_TIMEOUT:-240} NAME=has-test-$$ @@ -44,6 +50,7 @@ passed=0 failed=0 ok() { echo "ok - $*"; passed=$((passed + 1)); } bad() { echo "FAIL - $*"; failed=$((failed + 1)); } check() { local d=$1; shift; if "$@" >/dev/null 2>&1; then ok "$d"; else bad "$d"; fi; } +section() { echo; echo "## $*"; } cleanup() { docker logs "$NAME" >"$WORK/container.log" 2>&1 || true @@ -79,6 +86,10 @@ expect() { } code() { curl -s -m 30 -o /dev/null -w '%{http_code}' "$@"; } location() { curl -s -m 30 -o /dev/null -w '%header{location}' "$1"; } +# has METİN DESEN: grep -E, borusuz / has TEXT PATTERN: grep -E without a pipe +has() { grep -qiE -- "$2" <<<"$1"; } +mode() { docker exec "$NAME" stat -c %a "$1" 2>/dev/null; } +exists() { docker exec "$NAME" test -e "$1"; } wait_healthy() { local s @@ -106,11 +117,8 @@ wait_job() { done return 1 } - # Sağlık kontrolü yalnız nginx'e bakar; panel QEMU'da birkaç saniye sonra açılabilir, kurulum kodunu bekle. -# Kayıt önce değişkene alınır (| grep -q + pipefail SIGPIPE'a takılabilir). # The healthcheck only covers nginx; under QEMU the panel can start a few seconds later, so wait for the code. -# The log is captured first (| grep -q with pipefail can hit SIGPIPE). setup_code_logged() { local logs for _ in $(seq 1 "$TIMEOUT"); do @@ -120,10 +128,27 @@ setup_code_logged() { done return 1 } -nosniff() { local h; h=$(curl -sI "$BASE/home/"); grep -qi '^x-content-type-options: nosniff' <<<"$h"; } -cookie_flags() { local c; c=$(grep -i '^set-cookie:' "$WORK/h"); [[ ${c,,} == *httponly* && ${c,,} == *samesite=strict* ]]; } +# Katalogda ZIM görünene / kaybolana kadar bekle / wait until the ZIM appears in / leaves the catalog +catalog_has() { + local c + for _ in $(seq 1 30); do + c=$(curl -s "$BASE/kiwix/catalog/v2/entries?count=-1") + if [ "$1" = yes ]; then [[ $c == *"$ZIM"* ]] && return 0; else [[ $c != *"$ZIM"* ]] && return 0; fi + sleep 1 + done + return 1 +} echo "# imaj / image: $IMAGE ${PLATFORM:+($PLATFORM)}" + +# ---------------------------------------------------------------- imaj bilgisi / image metadata +section "imaj / image" +meta=$(docker image inspect "$IMAGE" -f '{{json .Config.Healthcheck}} {{json .Config.ExposedPorts}} {{json .Config.Volumes}} {{json .Config.Entrypoint}}' 2>/dev/null) +check "HEALTHCHECK tanımlı / defined" has "$meta" '^\{"Test":\[' +check "8080 portu bildirilmiş / port 8080 exposed" has "$meta" '"8080/tcp"' +check "/library volume" has "$meta" '"/library"' +check "giriş noktası tini / tini entrypoint" has "$meta" 'tini' + docker volume create "$VOL" >/dev/null run_args=(-d --name "$NAME" -p "127.0.0.1:$PORT:8080" -v "$VOL:/library" --read-only --tmpfs /tmp --cap-drop ALL --cap-add SETUID --cap-add SETGID --cap-add DAC_OVERRIDE @@ -137,16 +162,25 @@ if [ "$PLATFORM" = linux/386 ] && [ "$(docker version -f '{{.Server.Version}}' 2 bad "Docker 29.4.2 linux/386 çalıştıramaz, 29.4.3+ gerekir / cannot run linux/386, needs 29.4.3+ (moby/profiles#21)" exit 1 fi +started=$(date +%s) if ! docker run "${run_args[@]}" "$IMAGE" >/dev/null; then bad "konteyner açılmadı / container did not start"; exit 1 fi # ---------------------------------------------------------------- açılış / start-up -if wait_healthy; then ok "sağlık kontrolü / healthcheck: healthy"; else bad "sağlık kontrolü / healthcheck"; exit 1; fi +section "açılış / start-up" +if wait_healthy; then ok "sağlık kontrolü / healthcheck: healthy ($(($(date +%s) - started)) sn / s)"; else bad "sağlık kontrolü / healthcheck"; exit 1; fi ok "mimari / architecture: $(docker exec "$NAME" uname -m)" check "ilk kurulum kodu kayıtta / setup code in the log" setup_code_logged +kv=$(sed -n 's/^ARG KIWIX_VERSION=//p' "$REPO/docker/Dockerfile" | tr -d '\r') +kiwix_version() { local v; v=$(docker exec "$NAME" kiwix-serve --version 2>&1); [[ -n $kv && $v == *"$kv"* ]]; } +check "kiwix-serve sürümü Dockerfile'daki / version matches the Dockerfile ($kv)" kiwix_version +check "panel verisi klasörü 700 / data directory mode 700" test "$(mode /library/has-admin)" = 700 +check "kurulum kodu dosyası 600 / setup code file mode 600" test "$(mode /library/has-admin/setup-code)" = 600 +check "kütüphane dosyası var / library.xml exists" exists /library/zims/library.xml # ---------------------------------------------------------------- ana sayfa ve Kiwix / homepage and Kiwix +section "web" for p in /home/ /home/acil.html /home/oku.html /home/services.json "/kiwix/?has=1" "/kiwix/catalog/v2/entries?count=-1" /admin/; do c=$(code "$BASE$p") if [ "$c" = 200 ]; then ok "GET $p"; else bad "GET $p → $c"; fi @@ -155,88 +189,208 @@ check "/ → /home/" test "$(location "$BASE/")" = /home/ # Yönlendirme göreli olmalı: dışarıdaki port içerdekinden farklı olabilir (11-28 hatası). # Redirects must be relative: the outside port can differ from the inside one (11-28 bug). check "/home → /home/ (göreli / relative)" test "$(location "$BASE/home")" = /home/ +check "/admin → /admin/" test "$(location "$BASE/admin")" = /admin/ check "/kiwix/ → HAS okuyucusu / reader" test "$(location "$BASE/kiwix/")" = "/home/oku.html#library" +check "olmayan sayfa 404 / missing page 404" test "$(code "$BASE/home/yok-boyle-sayfa.html")" = 404 +# Web kökü /library/www/html: ZIM'ler ve panel verisi dışarıdan okunamamalı. +# The web root is /library/www/html: ZIMs and panel data must not be readable from outside. +for p in /zims/library.xml /has-admin/users.json /library/has-admin/users.json; do + check "dışarıdan okunamaz / not served: $p" test "$(code "$BASE$p")" = 404 +done +no_traversal() { local b; b=$(curl -s --path-as-is -m 30 "$BASE/home/../../has-admin/users.json"); [[ $b != *'"salt"'* && $b != *'"hash"'* ]]; } +check "yol aşımı yok / no path traversal (../)" no_traversal + s=$(curl -s "$BASE/home/services.json") -check "services.json: kiwix kurulu / installed" grep -q '"kiwix":{"installed":true' <<<"$s" -check "services.json: has-admin kurulu / installed" grep -q '"has-admin":{"installed":true' <<<"$s" -check "services.json: maps kurulu değil / not installed" grep -q '"maps":{"installed":false' <<<"$s" -check "nosniff başlığı / header" nosniff +check "services.json: kiwix kurulu / installed" has "$s" '"kiwix":\{"installed":true' +check "services.json: has-admin kurulu / installed" has "$s" '"has-admin":\{"installed":true' +check "services.json: maps kurulu değil / not installed" has "$s" '"maps":\{"installed":false' +check "services.json: kolibri kurulu değil / not installed" has "$s" '"kolibri":\{"installed":false' +check "services.json: Türkçe ve İngilizce adlar / TR and EN labels" has "$s" '"label":\{"tr":"[^"]+","en":"[^"]+"\}' +hdr=$(curl -sI "$BASE/home/") +check "nosniff başlığı / header" has "$hdr" '^x-content-type-options: nosniff' +check "Referrer-Policy: no-referrer" has "$hdr" '^referrer-policy: no-referrer' +check "nginx sürümü gizli / version hidden" has "$hdr" '^server: nginx[[:space:]]*$' +check "services.json JSON türünde / served as JSON" has "$(curl -sI "$BASE/home/services.json")" '^content-type: application/json' +ahdr=$(curl -sI "$BASE/admin/") +check "panel: X-Frame-Options DENY" has "$ahdr" '^x-frame-options: deny' +check "panel: Cache-Control no-store" has "$ahdr" '^cache-control: no-store' +check "panel: CSP frame-ancestors 'none'" has "$ahdr" "^content-security-policy: .*frame-ancestors 'none'" + +# Sayfalar dışarıdan kaynak (betik, stil, yazı tipi) yüklememeli: afette internet yok. +# Pages must not load outside resources (scripts, styles, fonts): there is no internet in a disaster. +for p in /home/ /home/acil.html /home/oku.html /admin/; do + html=$(curl -s "$BASE$p") + ext=$(grep -oiE "(src|]*href)=[\"']https?://[^\"']*|url\\([\"']?https?://[^)]*|@import" <<<"$html" | head -3) + if [ -z "$ext" ]; then ok "çevrimdışı, dış kaynak yok / offline, no outside resources: $p"; else bad "dış kaynak / outside resource in $p: $ext"; fi + if [[ $html == *has-theme* ]]; then ok "tema seçimi / theme choice: $p"; else bad "tema seçimi yok / no theme choice: $p"; fi +done +oku=$(curl -s "$BASE/home/oku.html") +for id in lib book books q random theme frame; do + if [[ $oku == *"id=\"$id\""* ]]; then ok "okuyucu çubuğu / reader bar: #$id"; else bad "okuyucuda #$id yok / reader lacks #$id"; fi +done +check "ana sayfa servis listesini okur / homepage reads services.json" has "$(curl -s "$BASE/home/")" 'services\.json' +check "acil sayfasında 112 / emergency page lists 112" has "$(curl -s "$BASE/home/acil.html")" '112' +# Panelin her hata kodu için Türkçe ve İngilizce metni olmalı (API error_code döner, sayfa çevirir). +# The panel needs Turkish and English text for every error code (the API returns error_code, the page translates). +page=$(curl -s "$BASE/admin/") +missing="" +for c in $(sed -n '/errorMessages = map/,/^}/p' "$REPO/admin/handlers.go" | grep -o '"[a-z_]*":' | tr -d '":'); do + n=$(grep -o "$c" <<<"$page" | wc -l) + [ "$n" -ge 2 ] || missing+=" $c" +done +if [ -z "$missing" ]; then ok "her hata kodunun TR + EN metni var / every error code has TR + EN text"; else bad "çevirisi eksik / untranslated:$missing"; fi # ---------------------------------------------------------------- ilk kurulum / first-run setup +section "ilk kurulum / first-run setup" req GET /session; expect "oturum: kurulum bekleniyor / session: setup pending" 200 '"setup":true' req GET /status; expect "girişsiz durum reddedilir / status needs login" 401 login_required +expect "hata biçimi error_code + message / error format" 401 '"message":"' +req GET /job; expect "girişsiz iş durumu reddedilir / job needs login" 401 login_required +req POST /verify '{}'; expect "girişsiz doğrulama reddedilir / verify needs login" 401 login_required +req POST /download "{\"prefixes\":[\"$ZIM\"]}"; expect "girişsiz indirme reddedilir / download needs login" 401 login_required +req POST /delete '{"file":"x.zim","password":"x"}'; expect "girişsiz silme reddedilir / delete needs login" 401 login_required CODE=$(docker logs "$NAME" 2>&1 | sed -n 's/.*first-run setup code: //p' | tail -1 | tr -d '\r') check "setup-code komutu kayıttakiyle aynı / CLI matches the log" test "$(docker exec "$NAME" has-admin setup-code | tr -d '\r')" = "$CODE" req POST /setup "{\"code\":\"yanlis\",\"user\":\"$ADMIN\",\"password\":\"$PASS\"}"; expect "yanlış kurulum kodu / wrong setup code" 403 wrong_setup_code req POST /setup "{\"code\":\"$CODE\",\"user\":\"$ADMIN\",\"password\":\"kisa\"}"; expect "kısa şifre / short password" 400 short_password +req POST /setup "{\"code\":\"$CODE\",\"user\":\"a b/../x\",\"password\":\"$PASS\"}"; expect "geçersiz kullanıcı adı / invalid user name" 400 invalid_name +req POST /setup '{bozuk'; expect "bozuk JSON / broken JSON" 400 bad_request req POST /setup "{\"code\":\"$CODE\",\"user\":\"$ADMIN\",\"password\":\"$PASS\"}" -D "$WORK/h"; expect "ilk kullanıcı / first user" 200 "\"user\":\"$ADMIN\"" -check "çerez HttpOnly + SameSite=Strict / cookie flags" cookie_flags +setcookie=$(grep -i '^set-cookie:' "$WORK/h") +check "çerez HttpOnly / cookie HttpOnly" has "$setcookie" 'httponly' +check "çerez SameSite=Strict / cookie SameSite=Strict" has "$setcookie" 'samesite=strict' +check "çerez yolu /admin, 12 sa / cookie path /admin, 12 h" has "$setcookie" 'path=/admin.*max-age=43200|max-age=43200.*path=/admin' +check "kurulum kodu dosyası silindi / setup code file removed" test "$(docker exec "$NAME" sh -c 'test -e /library/has-admin/setup-code && echo var || echo yok')" = yok req POST /setup "{\"code\":\"$CODE\",\"user\":\"x2\",\"password\":\"$PASS\"}"; expect "ikinci kurulum reddedilir / setup only once" 409 setup_done req GET /session; expect "oturum açık / logged in" 200 "\"user\":\"$ADMIN\"" req GET /status; expect "durum / status" 200 '"content":[' -check "users.json izni 600 / mode 600" test "$(docker exec "$NAME" stat -c %a /library/has-admin/users.json)" = 600 +st=$BODY +check "durum: disk boyutu / status: disk size" has "$st" '"disk":\{"free":[1-9][0-9]*,"total":[1-9]' +check "durum: servisler / status: services" has "$st" '"services":\{"checked"' +nconf=$(grep -cvE '^[[:space:]]*(#|$)' "$REPO/config/content.conf") +check "durum: content.conf'un tüm satırları / every content.conf entry ($nconf)" test "$(grep -o '"prefix":' <<<"$st" | wc -l)" = "$nconf" +check "users.json izni 600 / mode 600" test "$(mode /library/has-admin/users.json)" = 600 +check "sessions.json izni 600 / mode 600" test "$(mode /library/has-admin/sessions.json)" = 600 +no_plain_password() { local u; u=$(docker exec "$NAME" cat /library/has-admin/users.json); [[ $u != *"$PASS"* ]]; } +check "şifre düz metin saklanmaz / password not stored in plain text" no_plain_password +cookie_value=$(awk '$6 == "has_admin" {print $7}' "$JAR" | tail -1) +no_plain_cookie() { local s; s=$(docker exec "$NAME" cat /library/has-admin/sessions.json); [[ -n $cookie_value && $s != *"$cookie_value"* ]]; } +check "oturum dosyasında çerez değil özeti var / sessions.json holds a hash, not the cookie" no_plain_cookie # ---------------------------------------------------------------- CSRF ve girdi / CSRF and input +section "CSRF ve girdi / CSRF and input" CT=text/plain req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}"; expect "JSON olmayan istek / non-JSON body" 415 json_required +CT=application/x-www-form-urlencoded req POST /login "user=$ADMIN&password=$PASS"; expect "form gövdesi / form body" 415 json_required req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}" -H 'Sec-Fetch-Site: cross-site' -H 'Origin: http://evil.example'; expect "başka siteden istek / cross-site request" 403 cross_origin # Tarayıcı kutuya başka ad/portla gelir (box.lan, yönlendirilmiş port): kabul edilmeli (11-28 hatası). # The browser reaches the box by another name/port (box.lan, forwarded port): must be accepted (11-28 bug). req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}" -H 'Sec-Fetch-Site: same-origin' -H 'Origin: http://box.lan:8888'; expect "aynı site, başka ad/port / same-origin via another name and port" 200 "\"user\":\"$ADMIN\"" +no_cors() { local h; h=$(curl -s -m 30 -D - -o /dev/null -X OPTIONS -H 'Origin: http://evil.example' -H 'Access-Control-Request-Method: POST' "$API/login"); ! has "$h" '^access-control-allow-origin'; } +check "CORS izni yok / no CORS allowance" no_cors +req GET /login; expect "GET ile giriş yok / no login via GET" 405 NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"yanlis-sifre-00\"}"; expect "yanlış şifre / wrong password" 401 wrong_login +NOJAR=1 req POST /login "{\"user\":\"olmayan\",\"password\":\"$PASS\"}"; expect "olmayan kullanıcıda aynı hata / unknown user, same error" 401 wrong_login +NOJAR=1 req GET /session -H 'Cookie: has_admin=uydurma'; expect "uydurma çerez geçmez / forged cookie rejected" 200 '"user":""' req POST /download '{"prefixes":[]}'; expect "boş seçim / empty selection" 400 choose_content req POST /download '{"prefixes":["../../etc/passwd"]}'; expect "listede olmayan içerik / not in content.conf" 400 not_in_list +req POST /download "{\"prefixes\":[\"$ZIM\",\"uydurma\"]}"; expect "bir yanlış öğe hepsini reddeder / one unknown entry rejects all" 400 not_in_list req POST /delete "{\"file\":\"../users.json\",\"password\":\"$PASS\"}"; expect "geçersiz dosya adı / invalid file name" 400 invalid_file +req POST /delete "{\"file\":\"../../has-admin/x.zim\",\"password\":\"$PASS\"}"; expect "yol içeren .zim / .zim with a path" 400 invalid_file req POST /delete '{"file":"yok.zim","password":"yanlis-sifre-00"}'; expect "silmede yanlış şifre / wrong password on delete" 403 wrong_password +req POST /delete '{"file":"yok.zim","password":""}'; expect "silmede boş şifre / empty password on delete" 403 wrong_password req POST /delete "{\"file\":\"yok.zim\",\"password\":\"$PASS\"}"; expect "olmayan dosya / missing file" 404 file_not_found +# Boş kütüphanede doğrulama işi çalışır, iş kaydı yalnız root okur. +# A verify job runs on an empty library; the job log is root-only. +req POST /verify '{}'; expect "doğrulama başladı / verify started" 202 started +wait_job verify; check "doğrulama işi bitti / verify job ended" test -n "$JOB_EXIT" +check "iş kaydı 600 / job log mode 600" test "$(mode /library/has-admin/last-job.log)" = 600 +req GET /job; expect "iş durumu / job status" 200 '"name":"verify"' + # ---------------------------------------------------------------- indirme / download +F="" if [ "$DOWNLOAD" = 1 ]; then + section "indirme / download" req POST /download "{\"prefixes\":[\"$ZIM\"]}"; expect "indirme başladı / download started" 202 started + req POST /verify '{}'; busy_status=$STATUS busy_body=$BODY + req GET /job + if [[ $BODY == *'"running":true'* ]]; then + STATUS=$busy_status BODY=$busy_body; expect "iş sürerken ikinci iş reddedilir / second job rejected while busy" 409 busy + # Durdur ve kaldığı yerden sürdür (indirme çok hızlı biterse bu adım atlanır). + # Stop and resume (skipped when the download finishes too fast). + req POST /job/stop '{}'; expect "durdur / stop" 200 '"stopped":' + wait_job download; check "durdurulan iş hata koduyla biter / stopped job ends non-zero (exit $JOB_EXIT)" test "${JOB_EXIT:-0}" != 0 + req POST /download "{\"prefixes\":[\"$ZIM\"]}"; expect "kaldığı yerden / resume" 202 started + else + ok "indirme çok hızlı bitti, durdur/sürdür atlandı / download too fast, stop/resume skipped" + fi wait_job download; check "indirme bitti / download finished (exit $JOB_EXIT)" test "$JOB_EXIT" = 0 + req GET /job; expect "iş çıktısı / job output lines" 200 '"lines":["' req GET /status; expect "ZIM ve .sha256 diskte / ZIM and .sha256 on disk" 200 '"sha256":true' F=$(grep -o "\"name\":\"${ZIM}_[^\"]*\.zim\"" <<<"$BODY" | head -1 | cut -d'"' -f4) - found=0 - for _ in $(seq 1 30); do - catalog=$(curl -s "$BASE/kiwix/catalog/v2/entries?count=-1") - if [[ $catalog == *"$ZIM"* ]]; then found=1; break; fi - sleep 1 - done - check "Kiwix kataloğunda / in the Kiwix catalog: $F" test "$found" = 1 + check "durumda kurulu görünür / shown as installed: $F" has "$BODY" "\"prefix\":\"$ZIM\",\"note\":\"[^\"]*\",\"installed\":\"$F\"" + sha_ok() { docker exec "$NAME" sh -c "cd /library/zims/content && echo \"\$(cat '$F.sha256') $F\" | sha256sum -c --status"; } + check "SHA-256 eşleşiyor / SHA-256 matches" sha_ok + check "Kiwix kataloğunda / in the Kiwix catalog" catalog_has yes + B=${F%.zim} + check "kitap açılıyor / book opens: /kiwix/content/$B/" test "$(code -L "$BASE/kiwix/content/$B/")" = 200 + check "Kiwix araması / Kiwix search" test "$(code "$BASE/kiwix/search?content=$B&pattern=pain")" = 200 + check "rastgele sayfa / random page" test "$(code "$BASE/kiwix/random?content=$B")" = 302 req POST /verify '{}'; expect "doğrulama başladı / verify started" 202 started wait_job verify; check "doğrulama / verify (exit $JOB_EXIT)" test "$JOB_EXIT" = 0 - req POST /delete "{\"file\":\"$F\",\"password\":\"$PASS\"}"; expect "şifreyle silme / delete with password" 200 removed - wait_job library - req GET /status - if [ -n "$F" ] && [[ $BODY != *"$F"* ]]; then ok "silinen dosya listede yok / deleted file gone"; else bad "silinen dosya / deleted file: '$F'"; fi fi # ---------------------------------------------------------------- yeniden başlatma / restart +section "yeniden başlatma / restart" docker restart "$NAME" >/dev/null if wait_healthy; then ok "yeniden başlatma / restart: healthy"; else bad "yeniden başlatma / restart"; exit 1; fi req GET /session; expect "oturum yeniden başlatmada kalır / session survives restart" 200 "\"user\":\"$ADMIN\"" NOJAR=1 req GET /session; expect "kullanıcı kalıcı / user persists" 200 '"setup":false' +check "yeniden başlatmada kurulum kodu yok / no setup code after restart" test "$(docker exec "$NAME" sh -c 'test -e /library/has-admin/setup-code && echo var || echo yok')" = yok +if [ -n "$F" ]; then + check "içerik yeniden başlatmada kalır / content survives restart" catalog_has yes + # library.xml silinirse açılışta ZIM'lerden yeniden kurulur (elle kopyalanan ZIM'ler için). + # If library.xml is gone it is rebuilt from the ZIMs at start (for ZIMs copied by hand). + docker exec "$NAME" rm -f /library/zims/library.xml + docker restart "$NAME" >/dev/null + wait_healthy + check "kütüphane ZIM'lerden yeniden kuruldu / library rebuilt from the ZIMs" catalog_has yes + req POST /delete "{\"file\":\"$F\",\"password\":\"$PASS\"}"; expect "şifreyle silme / delete with password" 200 removed + wait_job library + req GET /status + if [[ $BODY != *"$F"* ]]; then ok "silinen dosya listede yok / deleted file gone"; else bad "silinen dosya hâlâ listede / still listed: $F"; fi + check ".sha256 de silindi / .sha256 removed too" test "$(docker exec "$NAME" sh -c 'ls /library/zims/content | grep -c sha256 || true')" = 0 + check "Kiwix kataloğundan çıktı / removed from the Kiwix catalog" catalog_has no +fi # ---------------------------------------------------------------- komut satırından şifre / CLI password reset -# Çıktı önce değişkene alınır: doğrudan `| grep -q` ile pipefail, grep erken çıkınca docker exec'i SIGPIPE ile -# düşürüp yanlış hata verebiliyor (yavaş QEMU'da, arm/v6'da görüldü). -# The output is captured first: piping into `grep -q` with pipefail can kill docker exec with SIGPIPE when grep -# exits early, a false failure (seen under slow QEMU on arm/v6). +section "komut satırı / CLI" reset_out=$(printf '%s\n' "$PASS2" | docker exec -i "$NAME" has-admin reset-password "$ADMIN" --stdin 2>&1) reset_rc=$? if [ "$reset_rc" = 0 ] && [[ $reset_out == *'password changed'* ]]; then ok "reset-password --stdin" else bad "reset-password --stdin (çıkış / exit $reset_rc: $reset_out)"; fi +check "--stdin şifreyi ekrana yazmaz / --stdin does not print the password" test "${reset_out/$PASS2/}" = "$reset_out" +printf 'kisa\n' | docker exec -i "$NAME" has-admin reset-password "$ADMIN" --stdin >/dev/null 2>&1 +short_rc=$? +check "CLI kısa şifreyi reddeder / CLI rejects a short password" test "$short_rc" != 0 +check "CLI bilinmeyen komutu reddeder / CLI rejects an unknown command" test "$(docker exec "$NAME" has-admin yok-boyle >/dev/null 2>&1; echo $?)" != 0 req GET /session; expect "şifre değişince eski oturum kapanır / old session ends" 200 '"user":""' NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS\"}"; expect "eski şifre geçmez / old password rejected" 401 wrong_login -req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS2\"}"; expect "yeni şifreyle giriş / login with new password" 200 "\"user\":\"$ADMIN\"" +rand_out=$(docker exec "$NAME" has-admin reset-password "$ADMIN" 2>&1) +RANDPW=$(sed -n 's/.*): \([a-z0-9-]*\)[[:space:]]*$/\1/p' <<<"$rand_out" | head -1) +check "rastgele şifre üretildi / random password printed (${#RANDPW} karakter / chars)" test "${#RANDPW}" -ge 20 +NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS2\"}"; expect "--stdin şifresi de geçersiz oldu / the --stdin password is replaced" 401 wrong_login +req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$RANDPW\"}"; expect "rastgele şifreyle giriş / login with the random password" 200 "\"user\":\"$ADMIN\"" +saved=$(awk '$6 == "has_admin" {print $7}' "$JAR" | tail -1) req POST /logout '{}'; expect "çıkış / logout" 200 '"ok":true' req GET /status; expect "çıkıştan sonra durum kapalı / status closed after logout" 401 login_required +NOJAR=1 req GET /status -H "Cookie: has_admin=$saved"; expect "eski çerez sunucuda da geçersiz / old cookie invalid on the server" 401 login_required # ---------------------------------------------------------------- güvenlik / security +section "güvenlik / security" ps_out=$(docker exec "$NAME" ps -o user,args) listen=$(docker exec "$NAME" netstat -ltn 2>/dev/null | awk 'NR>2 {print $4}') -# Süzme awk ile tek adımda: | grep -q zincirleri pipefail altında SIGPIPE'a takılabilir. # QEMU altında ps ikinci sütunu {nginx} gösterir; desen bu yüzden başa sabitlenmez. -# Filtering in one awk step: | grep -q chains can hit SIGPIPE under pipefail. # Under QEMU ps shows {nginx} in the second column, so the pattern is not anchored. kiwix_not_root() { awk '$2 ~ /kiwix-serve/ {n++; if ($1 == "root") r++} END {exit !(n > 0 && r == 0)}' <<<"$ps_out"; } nginx_not_root() { awk '$2 ~ /nginx/ {n++; if ($1 == "root") r++} END {exit !(n > 0 && r == 0)}' <<<"$ps_out"; } @@ -244,10 +398,14 @@ only_8080_outside() { awk '/:8080$/ {p++; next} !/^127\.0\.0\.1:[0-9]+$/ {o++} END {exit !(p > 0 && o == 0)}' <<<"$listen" } root_fs_read_only() { ! docker exec "$NAME" touch /opt/has/yazilabilir 2>/dev/null; } +no_caps() { local c; c=$(docker exec -u has "$NAME" sh -c 'grep CapEff /proc/self/status'); has "$c" 'CapEff:[[:space:]]+0+$'; } +no_new_privs() { local c; c=$(docker exec "$NAME" sh -c 'grep NoNewPrivs /proc/1/status'); has "$c" 'NoNewPrivs:[[:space:]]+1'; } check "kiwix-serve root değil / not root" kiwix_not_root check "nginx süreçleri root değil / nginx not root" nginx_not_root check "yalnız 8080 dışa açık / only 8080 listens outside ($(echo $listen))" only_8080_outside check "kök dosya sistemi salt okunur / read-only root fs" root_fs_read_only +check "has kullanıcısında yetki yok / no capabilities for has" no_caps +check "no-new-privileges" no_new_privs # Panel durursa ana sayfa ve Kiwix açık kalmalı, panel kendiliğinden geri gelmeli. # If the panel stops, the homepage and Kiwix must stay up and the panel must come back by itself. @@ -262,20 +420,31 @@ for _ in $(seq 1 60); do done check "panel kendiliğinden geri geldi / panel restarted by itself" test "$back" = 1 -# Hatalı denemede bekleme (en sonda: bu adresi bir dakika kilitler). -# Growing wait after failed attempts (last: it locks this address for a minute). +# Hatalı denemede bekleme (bu adresi bir dakika kilitler, girişli kontrollerden sonra). +# Growing wait after failed attempts (locks this address for a minute, so after the logged-in checks). for _ in 1 2 3 4 5; do NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"yanlis-sifre-00\"}"; done -NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$PASS2\"}"; expect "5 hatadan sonra bekleme / wait after 5 failures" 429 too_many_attempts +NOJAR=1 req POST /login "{\"user\":\"$ADMIN\",\"password\":\"$RANDPW\"}"; expect "5 hatadan sonra doğru şifre de bekler / even the right password waits after 5 failures" 429 too_many_attempts +expect "bekleme süresi yanıtta / wait time in the response" 429 '"wait":' + +# ---------------------------------------------------------------- kaynak ve kapanış / resources and shutdown +section "kaynak ve kapanış / resources and shutdown" +mem=$(docker stats --no-stream --format '{{.MemUsage}}' "$NAME" 2>/dev/null | cut -d/ -f1 | tr -d ' ') +ok "bellek / memory: ${mem:-?}" +t0=$(date +%s) +docker stop -t 20 "$NAME" >/dev/null +took=$(($(date +%s) - t0)) +check "düzgün kapanış, 15 sn'den kısa / clean stop under 15 s (${took} sn / s)" test "$took" -lt 15 # ---------------------------------------------------------------- özet / summary size=$(docker image inspect "$IMAGE" -f '{{.Size}}' 2>/dev/null || echo 0) -versions=$(docker exec "$NAME" sh -c 'kiwix-serve --version 2>&1 | head -1; nginx -v 2>&1; echo "alpine $(cat /etc/alpine-release)"' | tr '\n' ' ') -echo "# boyut / size: $((size / 1000000)) MB · $versions" +versions=$(docker run --rm --entrypoint sh ${PLATFORM:+--platform "$PLATFORM"} "$IMAGE" -c 'kiwix-serve --version 2>&1 | head -1; nginx -v 2>&1; echo "alpine $(cat /etc/alpine-release)"' 2>/dev/null | tr '\n' ' ') +echo +echo "# boyut / size: $((size / 1000000)) MB · bellek / memory: ${mem:-?} · $versions" echo "# sonuç / result: $passed ok, $failed hata / failed" if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then { echo "### ${PLATFORM:-local}: $passed ok, $failed failed" - echo "Image size $((size / 1000000)) MB · $versions" + echo "Image size $((size / 1000000)) MB · memory ${mem:-?} · $versions" } >>"$GITHUB_STEP_SUMMARY" fi [ "$failed" = 0 ] From d4f12aabfbd423c5ca77e1a81d399c6ab95e2d8d Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 03:46:28 +0300 Subject: [PATCH 22/65] ci(docker): name test reports after the platform, OS and Docker version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every test job now uploads a report, also when it passes, named like has-disk-armv7-ubuntu26.04-docker29.4.2. It holds environment.txt (runner OS, kernel, runner image, Docker and containerd, buildx, Go build image, commit, run link, and the Alpine, Kiwix, nginx and musl versions inside the image), packages.txt (apk list), test.txt (test output) and container.log; the amd64 job adds compose.log. The opaque .dockerbuild build records are no longer uploaded; the build summary stays. The compose step no longer pipes curl into grep -q. Her test işi artık geçse de bir rapor yüklüyor; adı has-disk-armv7-ubuntu26.04-docker29.4.2 gibi. İçinde environment.txt (makinenin işletim sistemi, çekirdek, runner imajı, Docker ve containerd, buildx, Go derleme imajı, commit, koşu bağlantısı ve imajdaki Alpine, Kiwix, nginx, musl sürümleri), packages.txt (apk listesi), test.txt (test çıktısı) ve container.log var; amd64 işi compose.log da ekliyor. Adı okunmayan .dockerbuild derleme kayıtları artık yüklenmiyor, derleme özeti kalıyor. compose adımında curl çıktısı artık grep -q'ya boruyla verilmiyor. --- .github/workflows/docker.yml | 70 +++++++++++++++++++++++++++++++----- docker/README.md | 4 +-- 2 files changed, 64 insertions(+), 10 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 3e55311..7846efb 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -92,8 +92,37 @@ jobs: - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + # Raporun adı ve environment.txt: hangi işletim sistemi, Docker ve mimaride denendiği. + # Report name and environment.txt: which OS, Docker and platform the test ran on. + - name: Ortam / environment + id: env + env: + SCOPE: ${{ matrix.scope }} + PLATFORM: ${{ matrix.platform }} + QEMU: ${{ matrix.qemu }} + run: | + . /etc/os-release + docker_v=$(docker version -f '{{.Server.Version}}') + containerd_v=$(docker version -f '{{range .Server.Components}}{{if eq .Name "containerd"}}{{.Version}}{{end}}{{end}}') + mkdir -p "$RUNNER_TEMP/report" + { + echo "platform: $PLATFORM (QEMU: $QEMU)" + echo "runner: $PRETTY_NAME, $(uname -m), kernel $(uname -r), image ${ImageOS:-?} ${ImageVersion:-?}" + echo "docker: $docker_v, containerd $containerd_v" + echo "buildx: $(docker buildx version)" + echo "go (build): $(sed -n 's/^FROM .*golang:\([^ ]*\).*/\1/p' docker/Dockerfile)" + echo "commit: $GITHUB_SHA ($GITHUB_REF_NAME, $GITHUB_EVENT_NAME)" + echo "run: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + } | tee "$RUNNER_TEMP/report/environment.txt" + echo "artifact=has-disk-${SCOPE}-${ID}${VERSION_ID}-docker${docker_v}" >> "$GITHUB_OUTPUT" + - name: Derle / build + id: build uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + env: + # Adı okunmayan .dockerbuild kayıtları yüklenmesin; özet yine yazılır. + # Do not upload the opaque .dockerbuild records; the summary is still written. + DOCKER_BUILD_RECORD_UPLOAD: 'false' with: context: . file: docker/Dockerfile @@ -104,13 +133,30 @@ jobs: cache-from: type=gha,scope=${{ matrix.scope }} cache-to: type=gha,scope=${{ matrix.scope }},mode=max + # İmajın içindeki sürümler ve paket listesi rapora / versions and package list inside the image + - name: İmaj bilgisi / image details + if: steps.build.outcome == 'success' + env: + PLATFORM: ${{ matrix.platform }} + run: | + r="$RUNNER_TEMP/report" + { + docker image inspect has-disk:ci -f 'image: {{.Id}}, {{.Size}} bytes, {{.Os}}/{{.Architecture}}' + docker run --rm --platform "$PLATFORM" --entrypoint sh has-disk:ci -c ' + echo "alpine: $(cat /etc/alpine-release)" + echo "kiwix: $(kiwix-serve --version 2>&1 | head -1)" + echo "nginx: $(nginx -v 2>&1 | sed "s/^nginx version: //")" + echo "musl: $(apk info -v 2>/dev/null | grep "^musl-[0-9]")"' + } | tee -a "$r/environment.txt" + docker run --rm --platform "$PLATFORM" --entrypoint apk has-disk:ci info -v | sort > "$r/packages.txt" + - name: İmaj testi / image test env: HAS_TEST_TIMEOUT: '600' - HAS_TEST_LOGS: ${{ runner.temp }}/container.log + HAS_TEST_LOGS: ${{ runner.temp }}/report/container.log PLATFORM: ${{ matrix.platform }} DOWNLOAD: ${{ matrix.full && '1' || '' }} - run: bash docker/test.sh has-disk:ci --platform "$PLATFORM" ${DOWNLOAD:+--download} + run: bash docker/test.sh has-disk:ci --platform "$PLATFORM" ${DOWNLOAD:+--download} 2>&1 | tee "$RUNNER_TEMP/report/test.txt" - name: compose ile açılış / start with compose if: matrix.full @@ -120,17 +166,23 @@ jobs: export HAS_PORT=18091 HAS_LIBRARY="$RUNNER_TEMP/compose-library" docker compose -p has-ci up -d --no-build --pull never --wait --wait-timeout 240 curl -fsS -o /dev/null http://127.0.0.1:18091/home/ - curl -fsS http://127.0.0.1:18091/admin/api/session | grep -q '"setup":true' + session=$(curl -fsS http://127.0.0.1:18091/admin/api/session) + [[ $session == *'"setup":true'* ]] test -s "$HAS_LIBRARY/www/html/home/services.json" - docker compose -p has-ci logs + docker compose -p has-ci logs > "$RUNNER_TEMP/report/compose.log" 2>&1 docker compose -p has-ci down - - name: Kayıtlar / logs - if: failure() + # Her işte rapor: environment.txt (işletim sistemi, Docker, imaj sürümleri), packages.txt, test.txt, + # container.log. Adında mimari, işletim sistemi ve Docker sürümü var. + # A report from every job: environment.txt (OS, Docker, image versions), packages.txt, test.txt, + # container.log. Its name carries the platform, OS and Docker version. + - name: Rapor / report + if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: container-log-${{ matrix.scope }} - path: ${{ runner.temp }}/container.log + name: ${{ steps.env.outputs.artifact || format('has-disk-{0}', matrix.scope) }} + path: ${{ runner.temp }}/report/ + retention-days: 14 if-no-files-found: ignore publish: @@ -174,6 +226,8 @@ jobs: # Uses the test jobs' cache: the layers that were tested are the ones published. - name: Tüm mimariler / all platforms uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' with: context: . file: docker/Dockerfile diff --git a/docker/README.md b/docker/README.md index 4a1daa7..8d45ee4 100644 --- a/docker/README.md +++ b/docker/README.md @@ -53,7 +53,7 @@ docker/test.sh has-disk:test --download docker/test.sh has-disk:arm --platform linux/arm/v7 # QEMU ile / with QEMU ``` -GitHub Actions her push'ta ve PR'da beş mimarinin hepsini ayrı ayrı derleyip bu betikle dener (arm64 ARM makinede, arm/v7 ve arm/v6 QEMU ile); amd64'te ayrıca indirme ve `compose.yaml` ile açılış denenir; hadolint ve `docker compose config` çalışır. İmaj yalnız bütün testler geçince ve yalnız `main`'den ya da `v*` etiketinden yayımlanır. +GitHub Actions her push'ta ve PR'da beş mimarinin hepsini ayrı ayrı derleyip bu betikle dener (arm64 ARM makinede, arm/v7 ve arm/v6 QEMU ile); amd64'te ayrıca indirme ve `compose.yaml` ile açılış denenir; hadolint ve `docker compose config` çalışır. İmaj yalnız bütün testler geçince ve yalnız `main`'den ya da `v*` etiketinden yayımlanır. Her iş, adında mimari, işletim sistemi ve Docker sürümü olan bir rapor bırakır (ör. `has-disk-armv7-ubuntu26.04-docker29.4.2`): `environment.txt` (makine, Docker, imajdaki Alpine/Kiwix/nginx sürümleri), `packages.txt`, `test.txt`, `container.log`. ## English @@ -108,4 +108,4 @@ docker/test.sh has-disk:test --download docker/test.sh has-disk:arm --platform linux/arm/v7 # with QEMU ``` -On every push and PR, GitHub Actions builds each of the five platforms separately and runs this script (arm64 on an ARM runner, arm/v7 and arm/v6 under QEMU); amd64 also runs the download and a start with `compose.yaml`; hadolint and `docker compose config` run too. The image is published only after all tests pass, and only from `main` or a `v*` tag. +On every push and PR, GitHub Actions builds each of the five platforms separately and runs this script (arm64 on an ARM runner, arm/v7 and arm/v6 under QEMU); amd64 also runs the download and a start with `compose.yaml`; hadolint and `docker compose config` run too. The image is published only after all tests pass, and only from `main` or a `v*` tag. Every job leaves a report named after the platform, OS and Docker version (e.g. `has-disk-armv7-ubuntu26.04-docker29.4.2`): `environment.txt` (runner, Docker, Alpine/Kiwix/nginx versions in the image), `packages.txt`, `test.txt`, `container.log`. From a6b2c6a953455c84893f6a61dfe679e1acecfc66 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 03:56:29 +0300 Subject: [PATCH 23/65] feat(admin): group content by language and verify selected items MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The content list is now one table per language (Turkish, English, multilingual, then other codes), taken from the second part of the ZIM name (wikipedia_tr_all_maxi → tr). Each group header has a select-all checkbox and an "x/y on device" count; items can be selected across groups at the same time and the selection survives a refresh. "Verify selected" checks only the selected items that are on the device, next to "Download selected" and "Verify all". Group tables share column widths, and long ZIM names wrap after _ and . on narrow screens. API: /api/status gives each content item a "lang" field; /api/verify accepts {"files": [...]} to check only those files. Names must match the ZIM name rule and exist (invalid_file, file_not_found, choose_content for an empty list); each file is verified in turn and the job fails if any of them is bad. Go tests and test.sh cover the language field and the selective verify. İçerik listesi artık dile göre ayrı tablolar (Türkçe, İngilizce, çok dilli, sonra diğer kodlar); dil ZIM adının ikinci parçasından alınıyor (wikipedia_tr_all_maxi → tr). Her grup başlığında hepsini seçen bir kutu ve "x/y cihazda" sayısı var; gruplar arası birlikte seçilebiliyor, seçim yenilemede korunuyor. "Seçilenleri doğrula" yalnız seçilenlerden cihazda olanları doğruluyor; "Seçilenleri indir" ve "Hepsini doğrula" yanında. Grup tabloları aynı sütun genişliğinde, uzun ZIM adları dar ekranda _ ve . sonrasında satır kırıyor. API: /api/status her içeriğe "lang" alanı ekliyor; /api/verify {"files": [...]} ile yalnız o dosyaları doğruluyor. Adlar ZIM adı kuralına uymalı ve klasörde olmalı (invalid_file, file_not_found, boş listede choose_content); dosyalar tek tek doğrulanıyor, biri bozuksa iş hata koduyla bitiyor. Go testleri ve test.sh dil alanını ve seçili doğrulamayı deniyor. --- admin/content_test.go | 66 ++++++++++++++++++++++++++++++++++++++ admin/handlers.go | 61 ++++++++++++++++++++++++++++++++++-- admin/web/index.html | 73 +++++++++++++++++++++++++++++++++++-------- docker/README.md | 4 +-- docker/test.sh | 8 +++++ 5 files changed, 195 insertions(+), 17 deletions(-) create mode 100644 admin/content_test.go diff --git a/admin/content_test.go b/admin/content_test.go new file mode 100644 index 0000000..a7d87be --- /dev/null +++ b/admin/content_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +// Dil kodu ZIM adının ikinci parçasından / the language code comes from the second part of the ZIM name. +func TestLangOf(t *testing.T) { + cases := map[string]string{ + "wikipedia_tr_all_maxi": "tr", + "zimgit-water_en": "en", + "solar.lowtechmagazine.com_mul_all": "mul", + "irp.fas.org_en_military-medicine": "en", + "ifixit_tr_all": "tr", + "tekparca": "", + "x_TR_all": "", + "x_toolong_all": "", + } + for in, want := range cases { + if got := langOf(in); got != want { + t.Errorf("langOf(%q) = %q, beklenen / want %q", in, got, want) + } + } +} + +// Seçili doğrulama: geçersiz ya da olmayan dosya betiğe gitmeden reddedilir. +// Selective verify: invalid or missing files are rejected before the script runs. +func TestVerifyFilesValidated(t *testing.T) { + lib := t.TempDir() + zdir := filepath.Join(lib, "zims", "content") + os.MkdirAll(zdir, 0o755) + os.WriteFile(filepath.Join(zdir, "var_2026-01.zim"), []byte("x"), 0o644) + + st := &store{path: filepath.Join(t.TempDir(), "users.json")} + if err := st.setPassword("deneme", "deneme-sifre-123"); err != nil { + t.Fatal(err) + } + a := newApp(config{prefix: "/admin", data: t.TempDir(), library: lib}, st) + h := a.routes() + tok := a.ses.create("deneme") + + verify := func(body string) (int, string) { + r := httptest.NewRequest("POST", "/admin/api/verify", strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + r.AddCookie(&http.Cookie{Name: cookieName, Value: tok}) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Body.String() + } + for body, want := range map[string]string{ + `{"files":[]}`: "choose_content", + `{"files":["../users.json"]}`: "invalid_file", + `{"files":["../../has-admin/x.zim"]}`: "invalid_file", + `{"files":["var_2026-01.zim","yok.zim"]}`: "file_not_found", + `{bozuk`: "bad_request", + } { + if _, b := verify(body); !strings.Contains(b, `"error_code":"`+want+`"`) { + t.Errorf("%s → %s, beklenen / want %s", body, b, want) + } + } +} diff --git a/admin/handlers.go b/admin/handlers.go index d3d3770..6f2a3b2 100644 --- a/admin/handlers.go +++ b/admin/handlers.go @@ -8,6 +8,7 @@ import ( "crypto/subtle" "embed" "encoding/json" + "io" "net" "net/http" "os" @@ -271,9 +272,27 @@ type contentItem struct { Note string `json:"note"` Installed string `json:"installed,omitempty"` Size int64 `json:"size,omitempty"` + Lang string `json:"lang"` line string } +// langOf ZIM adının ikinci parçasını dil kodu sayar (wikipedia_tr_all_maxi → tr, zimgit-water_en → en, +// solar.lowtechmagazine.com_mul_all → mul); yoksa boş. Panel içeriği buna göre gruplar. +// langOf takes the second part of the ZIM name as the language code (wikipedia_tr_all_maxi → tr, +// zimgit-water_en → en, solar.lowtechmagazine.com_mul_all → mul); empty otherwise. The panel groups by it. +func langOf(prefix string) string { + parts := strings.Split(prefix, "_") + if len(parts) < 2 || len(parts[1]) < 2 || len(parts[1]) > 3 { + return "" + } + for _, c := range parts[1] { + if c < 'a' || c > 'z' { + return "" + } + } + return parts[1] +} + var zimName = regexp.MustCompile(`^[A-Za-z0-9._-]+\.zim$`) // readContent config/content.conf'u okur (betikle aynı biçim: klasör, ön ek, # not). @@ -293,7 +312,7 @@ func (a *app) readContent() ([]contentItem, error) { if len(fields) < 2 { continue } - items = append(items, contentItem{Folder: fields[0], Prefix: fields[1], Note: strings.TrimSpace(note), line: line}) + items = append(items, contentItem{Folder: fields[0], Prefix: fields[1], Note: strings.TrimSpace(note), Lang: langOf(fields[1]), line: line}) } return items, sc.Err() } @@ -403,8 +422,46 @@ func (a *app) download(w http.ResponseWriter, r *http.Request) { writeJSON(w, 202, map[string]bool{"started": true}) } +// verify gövdesiz ya da {} ile tüm ZIM'leri, {"files": [...]} ile yalnız seçilenleri doğrular. +// Dosya adları ZIM adı kuralına uymalı ve klasörde olmalı; betiğe yalnız tam yollar gider. +// verify checks every ZIM with an empty body or {}, only the chosen ones with {"files": [...]}. +// File names must match the ZIM name rule and exist; only full paths reach the script. func (a *app) verify(w http.ResponseWriter, r *http.Request) { - if err := a.work.start("verify", nil, "bash", a.script("verify-content.sh"), a.cfg.zimDir()); err != nil { + var req struct { + Files *[]string `json:"files"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF { + fail(w, http.StatusBadRequest, "bad_request") + return + } + argv := []string{"bash", a.script("verify-content.sh"), a.cfg.zimDir()} + if req.Files != nil { + if len(*req.Files) == 0 { + fail(w, http.StatusBadRequest, "choose_content") + return + } + seen := map[string]bool{} + var paths []string + for _, f := range *req.Files { + if !zimName.MatchString(f) { + fail(w, http.StatusBadRequest, "invalid_file") + return + } + p := filepath.Join(a.cfg.zimDir(), f) + if _, err := os.Stat(p); err != nil { + fail(w, http.StatusNotFound, "file_not_found") + return + } + if !seen[p] { + seen[p] = true + paths = append(paths, p) + } + } + // Betik tek dosya ya da klasör alır; seçilenler tek tek doğrulanır, biri bozuksa iş hata koduyla biter. + // The script takes one file or a directory; each chosen file is checked, the job fails if any is bad. + argv = append([]string{"bash", "-c", `rc=0; for f; do bash "$0" "$f" || rc=1; done; exit $rc`, a.script("verify-content.sh")}, paths...) + } + if err := a.work.start("verify", nil, argv...); err != nil { fail(w, http.StatusConflict, errCode(err)) return } diff --git a/admin/web/index.html b/admin/web/index.html index a20ae27..dc1cd30 100644 --- a/admin/web/index.html +++ b/admin/web/index.html @@ -49,6 +49,12 @@ dialog .in{padding:10px 12px} dialog .btns{display:flex;gap:8px;justify-content:flex-end} button.danger{background:#B00000;color:#fff;border:1px solid #B00000} + h3.grp{font-size:13px;margin:14px 0 0;padding:6px 8px;background:#EEF2F5;border-left:4px solid #006699;display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap} + h3.grp label{display:flex;gap:6px;align-items:center;cursor:pointer} + h3.grp input{margin:0} + /* Grup tabloları aynı sütun genişliğinde / group tables share column widths */ + table.ct{table-layout:fixed} + .ct .c-chk{width:32px} .ct .c-item{width:32%} .ct .c-dev{width:26%} .ct .c-act{width:84px} /* Koyu tema (data-theme="dark", başta seçilir) / dark theme */ html[data-theme="dark"] body{background:#1b1f23;color:#e6e6e6} html[data-theme="dark"] .wrap,html[data-theme="dark"] dialog{background:#23292f;border-color:#3a444d;color:#e6e6e6} @@ -65,11 +71,14 @@ html[data-theme="dark"] .lang button[aria-pressed="true"]{background:#7cc4ee;color:#151a1e;border-color:#7cc4ee} html[data-theme="dark"] pre{background:#0f1215} html[data-theme="dark"] code{color:#ffc078} + html[data-theme="dark"] h3.grp{background:#2a323a;border-left-color:#7cc4ee} td{overflow-wrap:anywhere} td button{white-space:nowrap;overflow-wrap:normal} @media (max-width:600px){ .hide-s{display:none} + .ct .c-chk{width:22px} .ct .c-item{width:auto} .ct .c-dev{width:36%} .ct .c-act{width:64px} + .ct td:first-child,.ct th:first-child{padding-left:2px;padding-right:2px} .wrap{margin:0;border:0;padding:8px 10px} button{min-height:38px;padding:8px 12px} td,th{padding:8px 4px} @@ -117,13 +126,12 @@

+
- - - -
+ +

—
@@ -154,7 +162,9 @@

code:"Kurulum kodu", user:"Kullanıcı adı", password:"Şifre", newPassword:"Şifre (en az 10 karakter)", repeat:"Şifre (tekrar)", create:"Hesabı oluştur", login:"Giriş", forgot:"Şifreyi unuttuysanız: Docker'da docker compose exec has has-admin reset-password <ad>, kutuda sudo has-admin reset-password <ad>.", - status:"Durum", content:"İçerik", download:"Seçilenleri indir", verify:"Hepsini doğrula", + status:"Durum", content:"İçerik", download:"Seçilenleri indir", verify:"Hepsini doğrula", verifySel:"Seçilenleri doğrula", + chooseVerify:"Doğrulamak için cihazda olan içerik seçin.", onDeviceCount:"cihazda", selectGroup:"Bu gruptakilerin hepsini seç", + langs:{tr:"Türkçe", en:"İngilizce", mul:"Çok dilli"}, otherLang:"Diğer", contentHelp:"Liste: config/content.conf. İndirme yarıda kalırsa tekrar başlatın, kaldığı yerden sürer.", item:"İçerik", note:"Not", onDevice:"Cihazda", job:"İş", stop:"Durdur", noJob:"Henüz iş çalışmadı.", disk:"Disk", used:"dolu", free:"boş", total:"toplam", files:"dosya", services:"Servisler", service:"Servis", state:"Durum", installed:"Kurulu", notInstalled:"Kurulu değil", checked:"Son kontrol", @@ -177,7 +187,9 @@

code:"Setup code", user:"User name", password:"Password", newPassword:"Password (at least 10 characters)", repeat:"Password (again)", create:"Create account", login:"Log in", forgot:"Forgot the password: docker compose exec has has-admin reset-password <name> with Docker, sudo has-admin reset-password <name> on the box.", - status:"Status", content:"Content", download:"Download selected", verify:"Verify all", + status:"Status", content:"Content", download:"Download selected", verify:"Verify all", verifySel:"Verify selected", + chooseVerify:"Choose content that is on the device to verify.", onDeviceCount:"on device", selectGroup:"Select everything in this group", + langs:{tr:"Turkish", en:"English", mul:"Multilingual"}, otherLang:"Other", contentHelp:"List: config/content.conf. If a download stops, start it again; it resumes.", item:"Item", note:"Note", onDevice:"On device", job:"Job", stop:"Stop", noJob:"No job has run yet.", disk:"Disk", used:"used", free:"free", total:"total", files:"files", services:"Services", service:"Service", state:"State", installed:"Installed", notInstalled:"Not installed", checked:"Last check", @@ -222,6 +234,20 @@

function showErr(msg){ const e = $("err"); e.textContent = msg || ""; e.hidden = !msg; } +/* İçerik dile göre gruplanır: önce Türkçe, İngilizce, çok dilli; sonra diğer kodlar; dil kodu olmayanlar en sonda. + Content is grouped by language: Turkish, English, multilingual first; then other codes; no code last. */ +const LANG_ORDER = ["tr", "en", "mul"]; +function groups(items){ + const m = new Map(); + for (const c of items) { const k = c.lang || ""; if (!m.has(k)) m.set(k, []); m.get(k).push(c); } + const rank = k => { const i = LANG_ORDER.indexOf(k); return i >= 0 ? i : (k ? 10 : 99); }; + return [...m.entries()].sort((a, b) => rank(a[0]) - rank(b[0]) || a[0].localeCompare(b[0])); +} +const langName = k => ((T[lang].langs || {})[k]) || (k ? k.toUpperCase() : t("otherLang")); +/* Uzun ZIM adları _ ve . sonrasında satır kırar / long ZIM names wrap after _ and . */ +const brk = s => esc(s).replace(/([_.])/g, "$1"); +const selected = () => [...document.querySelectorAll("#content input[data-prefix]:checked")]; + async function api(path, body){ const opt = body === undefined ? {} : {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(body)}; const r = await fetch(P + "/api/" + path, {credentials:"same-origin", ...opt}); @@ -271,12 +297,27 @@

ZIM${d.zims.length} ${t("files")}, ${mb(d.zims.reduce((a,z) => a + z.size, 0))} ${t("checked")}${esc(new Date(d.checked).toLocaleString(LOCALE[lang]))}`; $("svc").innerHTML = svcRows; - $("content").innerHTML = d.content.map(c => ` - - ${esc(c.prefix)}
${esc(c.folder)}
- ${esc(c.note)} - ${c.installed ? `${esc(c.installed)}
${mb(c.size)}
` : `${t("no")}`} - ${c.installed ? `` : ""}`).join(""); + // Dile göre gruplu tablolar; seçimler yenilemede korunur, gruplar arası birlikte seçilebilir. + // Tables grouped by language; selections survive a refresh and can span groups. + const keep = new Set(selected().map(i => i.dataset.prefix)); + $("content").innerHTML = groups(d.content).map(([k, items]) => ` +

+ ${items.filter(c => c.installed).length}/${items.length} ${t("onDeviceCount")}

+ + ${items.map(c => ` + + + + + `).join("")} +
${t("item")}${t("note")}${t("onDevice")}
${brk(c.prefix)}
${esc(c.folder)}
${esc(c.note)}${c.installed ? `${brk(c.installed)}
${mb(c.size)}
` : `${t("no")}`}
${c.installed ? `` : ""}
`).join(""); + for (const g of document.querySelectorAll("#content input[data-group]")) { + const boxes = [...g.closest("h3").nextElementSibling.querySelectorAll("input[data-prefix]")]; + const sync = () => { g.checked = boxes.every(x => x.checked); g.indeterminate = !g.checked && boxes.some(x => x.checked); }; + g.onchange = () => { for (const x of boxes) x.checked = g.checked; g.indeterminate = false; }; + for (const x of boxes) x.addEventListener("change", sync); + sync(); + } for (const b of document.querySelectorAll("button[data-del]")) b.onclick = () => remove(b.dataset.del); } catch(x){ showErr(x.message); } job(); @@ -297,10 +338,16 @@

} $("dl").onclick = async () => { - const sel = [...document.querySelectorAll("#content input:checked")].map(i => i.value); + const sel = selected().map(i => i.dataset.prefix); if (!sel.length) return showErr(t("choose")); try { showErr(""); await api("download", {prefixes: sel}); job(); } catch(x){ showErr(x.message); } }; +/* Seçilenlerden yalnız cihazda olanlar doğrulanır / only the selected items on the device are verified */ +$("verifySel").onclick = async () => { + const files = selected().map(i => i.dataset.file).filter(Boolean); + if (!files.length) return showErr(t("chooseVerify")); + try { showErr(""); await api("verify", {files}); job(); } catch(x){ showErr(x.message); } +}; $("verify").onclick = async () => { try { showErr(""); await api("verify", {}); job(); } catch(x){ showErr(x.message); } }; $("stop").onclick = async () => { try { await api("job/stop", {}); job(); } catch(x){ showErr(x.message); } }; /* Silme: sayfa içi pencere, şifre sunucuda doğrulanır; şifre alanı her açılışta ve işten sonra temizlenir. diff --git a/docker/README.md b/docker/README.md index 8d45ee4..8fde905 100644 --- a/docker/README.md +++ b/docker/README.md @@ -28,7 +28,7 @@ Ana sayfa: `http://:8080/home/`. İndirme bitince Kiwix yeni içeriği ### Yönetim paneli -`http://:8080/admin/`: disk ve ZIM durumu, `config/content.conf` listesinden seçip indirme (ilerleme sayfada görünür), doğrulama, silme. Türkçe ve İngilizce. +`http://:8080/admin/`: disk ve ZIM durumu, `config/content.conf` listesinden seçip indirme (ilerleme sayfada görünür), doğrulama, silme. İçerik dile göre ayrı tablolarda (Türkçe, İngilizce, çok dilli); gruplar arası birlikte seçilebilir, grubun hepsi tek tıkla seçilir; seçilenler indirilir ya da doğrulanır. Türkçe ve İngilizce. - **İlk kurulum:** ilk açılışta kurulum kodu kayıtlara yazılır (`docker compose logs has`); kodu bilen kişi yönetici hesabını oluşturur. Repoda varsayılan şifre yok. - **Şifre sıfırlama:** `docker compose exec has has-admin reset-password ` rastgele yeni şifre üretip yazar; kendi şifreniz için `echo 'yeni-sifre' | docker compose exec -T has has-admin reset-password --stdin`. Şifre değişince o kullanıcının açık oturumları kapanır. @@ -83,7 +83,7 @@ Homepage: `http://:8080/home/`. Kiwix picks up new content without a ### Admin panel -`http://:8080/admin/`: disk and ZIM status, pick items from `config/content.conf` and download them (progress shown on the page), verify, delete. Turkish and English. +`http://:8080/admin/`: disk and ZIM status, pick items from `config/content.conf` and download them (progress shown on the page), verify, delete. Content is shown in one table per language (Turkish, English, multilingual); items can be selected across groups, a whole group with one click, and the selection downloaded or verified. Turkish and English. - **First run:** a setup code is written to the logs on first start (`docker compose logs has`); whoever has the code creates the admin account. No default password in the repo. - **Password reset:** `docker compose exec has has-admin reset-password ` prints a new random password; to set your own: `echo 'new-password' | docker compose exec -T has has-admin reset-password --stdin`. Changing a password ends that user's open sessions. diff --git a/docker/test.sh b/docker/test.sh index 0766d25..11dcfcc 100755 --- a/docker/test.sh +++ b/docker/test.sh @@ -269,6 +269,8 @@ check "durum: disk boyutu / status: disk size" has "$st" '"disk":\{"free":[1-9][ check "durum: servisler / status: services" has "$st" '"services":\{"checked"' nconf=$(grep -cvE '^[[:space:]]*(#|$)' "$REPO/config/content.conf") check "durum: content.conf'un tüm satırları / every content.conf entry ($nconf)" test "$(grep -o '"prefix":' <<<"$st" | wc -l)" = "$nconf" +check "durum: içerikte dil kodu / status: language per item (tr)" has "$st" '"prefix":"wikipedia_tr_all_maxi"[^}]*"lang":"tr"' +check "durum: içerikte dil kodu / status: language per item (en)" has "$st" '"prefix":"zimgit-water_en"[^}]*"lang":"en"' check "users.json izni 600 / mode 600" test "$(mode /library/has-admin/users.json)" = 600 check "sessions.json izni 600 / mode 600" test "$(mode /library/has-admin/sessions.json)" = 600 no_plain_password() { local u; u=$(docker exec "$NAME" cat /library/has-admin/users.json); [[ $u != *"$PASS"* ]]; } @@ -299,6 +301,9 @@ req POST /delete "{\"file\":\"../../has-admin/x.zim\",\"password\":\"$PASS\"}"; req POST /delete '{"file":"yok.zim","password":"yanlis-sifre-00"}'; expect "silmede yanlış şifre / wrong password on delete" 403 wrong_password req POST /delete '{"file":"yok.zim","password":""}'; expect "silmede boş şifre / empty password on delete" 403 wrong_password req POST /delete "{\"file\":\"yok.zim\",\"password\":\"$PASS\"}"; expect "olmayan dosya / missing file" 404 file_not_found +req POST /verify '{"files":[]}'; expect "seçili doğrulamada boş liste / empty list for selective verify" 400 choose_content +req POST /verify '{"files":["../users.json"]}'; expect "seçili doğrulamada geçersiz ad / invalid name for selective verify" 400 invalid_file +req POST /verify '{"files":["yok.zim"]}'; expect "seçili doğrulamada olmayan dosya / missing file for selective verify" 404 file_not_found # Boş kütüphanede doğrulama işi çalışır, iş kaydı yalnız root okur. # A verify job runs on an empty library; the job log is root-only. @@ -338,6 +343,9 @@ if [ "$DOWNLOAD" = 1 ]; then check "rastgele sayfa / random page" test "$(code "$BASE/kiwix/random?content=$B")" = 302 req POST /verify '{}'; expect "doğrulama başladı / verify started" 202 started wait_job verify; check "doğrulama / verify (exit $JOB_EXIT)" test "$JOB_EXIT" = 0 + req POST /verify "{\"files\":[\"$F\"]}"; expect "seçili doğrulama başladı / selective verify started" 202 started + wait_job verify; check "seçili doğrulama / selective verify (exit $JOB_EXIT)" test "$JOB_EXIT" = 0 + req GET /job; expect "seçili doğrulama yalnız o dosyaya bakar / selective verify checks that file" 200 "$F" fi # ---------------------------------------------------------------- yeniden başlatma / restart From f20d64e7924493a8ddb0e9a8d689af81c5c88865 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 04:44:09 +0300 Subject: [PATCH 24/65] feat(home): add a Turkish/English choice to the homepage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The homepage gets TR/EN buttons in the menu, like the admin panel and the reader. The choice is stored in the browser under has-lang and shared by every HAS page, so a language picked on the homepage also applies to the reader and the panel. Section titles, item names and descriptions, table headers, status words, the search box, the system information line and the footer are translated; sizes use a decimal point in English and the server time follows the language. Switching language redraws the table and keeps the source selected for search. Not translated yet: the disk warnings, which come in Turkish from disk-health.sh, and the emergency page, whose life-safety text needs a translation checked against its sources. Ana sayfaya, panel ve okuyucudaki gibi menüde TR/EN düğmeleri eklendi. Seçim tarayıcıda has-lang olarak saklanıyor ve tüm HAS sayfalarında ortak; ana sayfada seçilen dil okuyucuda ve panelde de geçerli. Bölüm başlıkları, içerik adları ve açıklamaları, tablo başlıkları, durum metinleri, arama kutusu, sistem bilgisi ve alt bilgi çevrildi; İngilizcede boyutlar ondalık noktayla, sunucu saati seçili dile göre. Dil değişince tablo yeniden çiziliyor, aramada seçili kaynak korunuyor. Henüz çevrilmeyenler: disk-health.sh'den Türkçe gelen disk uyarıları ve hayati bilgi içeren acil sayfası (çevirisi kaynaklarla karşılaştırılarak yapılmalı). --- www/home/index.html | 220 +++++++++++++++++++++++++++++--------------- 1 file changed, 144 insertions(+), 76 deletions(-) diff --git a/www/home/index.html b/www/home/index.html index 1c963b4..247aae9 100644 --- a/www/home/index.html +++ b/www/home/index.html @@ -38,6 +38,9 @@ .navlinks a::before{content:"» ";color:#999;font-weight:normal} .navlinks a.acil{color:#B00000} select.theme{font:11px Verdana,sans-serif;margin-left:10px;vertical-align:middle} + .lang{display:inline-flex;gap:4px;margin-left:8px;vertical-align:middle} + .lang button{font:bold 11px Verdana,sans-serif;padding:1px 6px;border:1px solid #7F9DB9;background:#FAFAFA;cursor:pointer} + .lang button[aria-pressed="true"]{background:#006699;color:#fff;border-color:#006699} .crumb{font-weight:bold;font-size:12px;margin:8px 2px} .small{font-size:10px;color:#444} @@ -131,6 +134,8 @@ html[data-theme="dark"] .btn{background:#2f3841;color:#e6e6e6;border-color:#6b7780} html[data-theme="dark"] .btn:hover{background:#3a4652} html[data-theme="dark"] #disk td{color:#ff7b7b} + html[data-theme="dark"] .lang button{background:#2f3841;color:#e6e6e6;border-color:#6b7780} + html[data-theme="dark"] .lang button[aria-pressed="true"]{background:#7cc4ee;color:#151a1e;border-color:#7cc4ee} @@ -140,50 +145,50 @@
-
Çevrimdışı bilgi arşivi — internet olmasa da açık
+
Çevrimdışı bilgi arşivi — internet olmasa da açık
- +
- +
- - - - + + + +
BölümDilBoyutDurumBölümDilBoyutDurum
- Hazır - Henüz yüklenmedi + Hazır + Henüz yüklenmedi
- +
Sistem bilgisi
Sistem bilgisi
- HAS_PrepperDisk © 2026 · Raspberry Pi 5 üzerinde çalışır
- İçerikler: Wikipedia, OpenStreetMap, Kolibri — ilgili lisanslar altında + HAS_PrepperDisk © 2026 · Raspberry Pi 5 üzerinde çalışır
+ İçerikler: Wikipedia, OpenStreetMap, Kolibri — ilgili lisanslar altında
@@ -196,53 +201,106 @@ service: services.json'daki ad (scripts/services.d/.sh modülü); kurulu değilse "henüz yüklenmedi". Cihazda bulunamayan ZIM'ler gri klasörle "henüz yüklenmedi" görünür. */ const CATS = [ - { title:"Ansiklopedi", items:[ - { name:"Vikipedi (Türkçe)", desc:"Türkçe Vikipedi'nin resimli tam kopyası.", lang:"TR", size:"~9 GB", zim:"wikipedia_tr_all_maxi", search:true }, - { name:"Wikipedia (English)", desc:"Tüm İngilizce Wikipedia, resimleriyle birlikte.", lang:"EN", size:"~120 GB", zim:"wikipedia_en_all_maxi", search:true }, + { title:{tr:"Ansiklopedi", en:"Encyclopedia"}, items:[ + { name:{tr:"Vikipedi (Türkçe)", en:"Wikipedia (Turkish)"}, desc:{tr:"Türkçe Vikipedi'nin resimli tam kopyası.", en:"The full Turkish Wikipedia with images."}, lang:"TR", size:"~9 GB", zim:"wikipedia_tr_all_maxi", search:true }, + { name:"Wikipedia (English)", desc:{tr:"Tüm İngilizce Wikipedia, resimleriyle birlikte.", en:"All of the English Wikipedia, with images."}, lang:"EN", size:"~120 GB", zim:"wikipedia_en_all_maxi", search:true }, ]}, - { title:"Türkçe Kitaplık", items:[ - { name:"Vikisözlük", desc:"Türkçe sözlük, köken bilgisi ve çeviriler.", lang:"TR", size:"~810 MB", zim:"wiktionary_tr_all", search:true }, - { name:"Vikikitap", desc:"Açık ders kitapları ve el kitapları.", lang:"TR", size:"~27 MB", zim:"wikibooks_tr_all" }, - { name:"Vikikaynak", desc:"Telifsiz metinler, kanunlar, klasikler.", lang:"TR", size:"~68 MB", zim:"wikisource_tr_all" }, - { name:"Vikisöz", desc:"Özlü sözler ve alıntılar.", lang:"TR", size:"~59 MB", zim:"wikiquote_tr_all" }, - { name:"iFixit (Türkçe)", desc:"Cihaz ve araç tamiri için Türkçe adım adım rehberler.", lang:"TR", size:"~3,6 GB", zim:"ifixit_tr_all", search:true }, - { name:"PhET Simülasyonları", desc:"Fizik, kimya ve matematik etkileşimli deneyleri.", lang:"TR", size:"~107 MB", zim:"phet_tr_all" }, + { title:{tr:"Türkçe Kitaplık", en:"Turkish Library"}, items:[ + { name:{tr:"Vikisözlük", en:"Wiktionary (Turkish)"}, desc:{tr:"Türkçe sözlük, köken bilgisi ve çeviriler.", en:"Turkish dictionary, word origins and translations."}, lang:"TR", size:"~810 MB", zim:"wiktionary_tr_all", search:true }, + { name:{tr:"Vikikitap", en:"Wikibooks (Turkish)"}, desc:{tr:"Açık ders kitapları ve el kitapları.", en:"Open textbooks and handbooks."}, lang:"TR", size:"~27 MB", zim:"wikibooks_tr_all" }, + { name:{tr:"Vikikaynak", en:"Wikisource (Turkish)"}, desc:{tr:"Telifsiz metinler, kanunlar, klasikler.", en:"Public-domain texts, laws, classics."}, lang:"TR", size:"~68 MB", zim:"wikisource_tr_all" }, + { name:{tr:"Vikisöz", en:"Wikiquote (Turkish)"}, desc:{tr:"Özlü sözler ve alıntılar.", en:"Sayings and quotations."}, lang:"TR", size:"~59 MB", zim:"wikiquote_tr_all" }, + { name:{tr:"iFixit (Türkçe)", en:"iFixit (Turkish)"}, desc:{tr:"Cihaz ve araç tamiri için Türkçe adım adım rehberler.", en:"Step-by-step repair guides for devices and vehicles, in Turkish."}, lang:"TR", size:"~3,6 GB", zim:"ifixit_tr_all", search:true }, + { name:{tr:"PhET Simülasyonları", en:"PhET Simulations"}, desc:{tr:"Fizik, kimya ve matematik etkileşimli deneyleri.", en:"Interactive physics, chemistry and maths experiments."}, lang:"TR", size:"~107 MB", zim:"phet_tr_all" }, ]}, - { title:"Haritalar ve Navigasyon", items:[ - { name:"Dünya Haritası", desc:"Avrupa ve Orta Doğu sokak seviyesinde, dünyanın geri kalanı şehir seviyesinde.", lang:"—", size:"~40 GB", url:"/maps", service:"maps" }, + { title:{tr:"Haritalar ve Navigasyon", en:"Maps and Navigation"}, items:[ + { name:{tr:"Dünya Haritası", en:"World Map"}, desc:{tr:"Avrupa ve Orta Doğu sokak seviyesinde, dünyanın geri kalanı şehir seviyesinde.", en:"Street level for Europe and the Middle East, city level for the rest of the world."}, lang:"—", size:"~40 GB", url:"/maps", service:"maps" }, ]}, - { title:"Hayatta Kalma ve Hazırlık", items:[ - { name:"Afet Sonrası Kitaplığı", desc:"Barınak, enerji, tarım ve yeniden yapılanma üzerine kitaplar.", lang:"EN", size:"~615 MB", zim:"zimgit-post-disaster_en", search:true }, - { name:"Su Arıtma", desc:"İçme suyu bulma, arıtma ve saklama.", lang:"EN", size:"~20 MB", zim:"zimgit-water_en" }, - { name:"Gıda Hazırlama ve Saklama", desc:"Konserve, kurutma ve uzun süreli gıda saklama.", lang:"EN", size:"~93 MB", zim:"zimgit-food-preparation_en" }, - { name:"Düğümler Kitaplığı", desc:"Düğüm çeşitleri ve kullanım alanları.", lang:"EN", size:"~27 MB", zim:"zimgit-knots_en" }, - { name:"Ready.gov", desc:"ABD resmi afet hazırlık rehberleri: deprem, sel, yangın.", lang:"EN", size:"~1,9 GB", zim:"ready.gov_en_all", search:true }, - { name:"Low-tech Magazine", desc:"Elektriksiz ve düşük teknolojili pratik çözümler.", lang:"EN", size:"~670 MB", zim:"solar.lowtechmagazine.com_mul_all" }, - { name:"Appropedia", desc:"Uygun teknoloji wiki'si: su, güneş enerjisi, tarım, barınak.", lang:"EN", size:"~580 MB", zim:"appropedia_en_all", search:true }, + { title:{tr:"Hayatta Kalma ve Hazırlık", en:"Survival and Preparedness"}, items:[ + { name:{tr:"Afet Sonrası Kitaplığı", en:"Post-Disaster Library"}, desc:{tr:"Barınak, enerji, tarım ve yeniden yapılanma üzerine kitaplar.", en:"Books on shelter, energy, farming and rebuilding."}, lang:"EN", size:"~615 MB", zim:"zimgit-post-disaster_en", search:true }, + { name:{tr:"Su Arıtma", en:"Water Treatment"}, desc:{tr:"İçme suyu bulma, arıtma ve saklama.", en:"Finding, treating and storing drinking water."}, lang:"EN", size:"~20 MB", zim:"zimgit-water_en" }, + { name:{tr:"Gıda Hazırlama ve Saklama", en:"Food Preparation and Storage"}, desc:{tr:"Konserve, kurutma ve uzun süreli gıda saklama.", en:"Canning, drying and long-term food storage."}, lang:"EN", size:"~93 MB", zim:"zimgit-food-preparation_en" }, + { name:{tr:"Düğümler Kitaplığı", en:"Knots Library"}, desc:{tr:"Düğüm çeşitleri ve kullanım alanları.", en:"Kinds of knots and what they are used for."}, lang:"EN", size:"~27 MB", zim:"zimgit-knots_en" }, + { name:"Ready.gov", desc:{tr:"ABD resmi afet hazırlık rehberleri: deprem, sel, yangın.", en:"Official US disaster preparedness guides: earthquake, flood, fire."}, lang:"EN", size:"~1,9 GB", zim:"ready.gov_en_all", search:true }, + { name:"Low-tech Magazine", desc:{tr:"Elektriksiz ve düşük teknolojili pratik çözümler.", en:"Practical low-tech solutions, many without electricity."}, lang:"EN", size:"~670 MB", zim:"solar.lowtechmagazine.com_mul_all" }, + { name:"Appropedia", desc:{tr:"Uygun teknoloji wiki'si: su, güneş enerjisi, tarım, barınak.", en:"Appropriate technology wiki: water, solar energy, farming, shelter."}, lang:"EN", size:"~580 MB", zim:"appropedia_en_all", search:true }, ]}, - { title:"Sağlık ve İlk Yardım", items:[ - { name:"WikiMed", desc:"Wikipedia'nın tıp maddeleri: hastalıklar, ilaçlar, anatomi.", lang:"EN", size:"~2 GB", zim:"wikipedia_en_medicine_maxi", search:true }, - { name:"MDWiki", desc:"Doktorlar tarafından düzenlenen tıp ansiklopedisi.", lang:"EN", size:"~2 GB", zim:"mdwiki_en_all_maxi", search:true }, - { name:"MedlinePlus", desc:"ABD Ulusal Tıp Kütüphanesi hasta bilgilendirme sayfaları.", lang:"EN", size:"~1,9 GB", zim:"medlineplus.gov_en_all", search:true }, - { name:"Tıp Kitaplığı", desc:"Temel tıp ve sağlık kitapları.", lang:"EN", size:"~67 MB", zim:"zimgit-medicine_en" }, - { name:"Askeri Sahra Tıbbı", desc:"Sahada travma ve yaralı bakımı (FAS).", lang:"EN", size:"~65 MB", zim:"irp.fas.org_en_military-medicine" }, - { name:"NHS İlaç Rehberi", desc:"İlaçların kullanımı, dozları ve yan etkileri.", lang:"EN", size:"~15 MB", zim:"nhs.uk_en_medicines" }, + { title:{tr:"Sağlık ve İlk Yardım", en:"Health and First Aid"}, items:[ + { name:"WikiMed", desc:{tr:"Wikipedia'nın tıp maddeleri: hastalıklar, ilaçlar, anatomi.", en:"Wikipedia's medical articles: diseases, medicines, anatomy."}, lang:"EN", size:"~2 GB", zim:"wikipedia_en_medicine_maxi", search:true }, + { name:"MDWiki", desc:{tr:"Doktorlar tarafından düzenlenen tıp ansiklopedisi.", en:"A medical encyclopedia edited by doctors."}, lang:"EN", size:"~2 GB", zim:"mdwiki_en_all_maxi", search:true }, + { name:"MedlinePlus", desc:{tr:"ABD Ulusal Tıp Kütüphanesi hasta bilgilendirme sayfaları.", en:"Patient information pages of the US National Library of Medicine."}, lang:"EN", size:"~1,9 GB", zim:"medlineplus.gov_en_all", search:true }, + { name:{tr:"Tıp Kitaplığı", en:"Medical Library"}, desc:{tr:"Temel tıp ve sağlık kitapları.", en:"Basic medical and health books."}, lang:"EN", size:"~67 MB", zim:"zimgit-medicine_en" }, + { name:{tr:"Askeri Sahra Tıbbı", en:"Military Field Medicine"}, desc:{tr:"Sahada travma ve yaralı bakımı (FAS).", en:"Trauma and casualty care in the field (FAS)."}, lang:"EN", size:"~65 MB", zim:"irp.fas.org_en_military-medicine" }, + { name:{tr:"NHS İlaç Rehberi", en:"NHS Medicines A to Z"}, desc:{tr:"İlaçların kullanımı, dozları ve yan etkileri.", en:"How medicines are used, their doses and side effects."}, lang:"EN", size:"~15 MB", zim:"nhs.uk_en_medicines" }, ]}, - { title:"Tamir ve Beceriler", items:[ - { name:"iFixit", desc:"Cihaz ve araç tamiri için adım adım rehberler.", lang:"EN", size:"~3 GB", zim:"ifixit_en_all", search:true }, - { name:"Ev Tamiri (DIY)", desc:"Elektrik, tesisat ve yapı soruları.", lang:"EN", size:"—", zim:"diy.stackexchange.com_en_all" }, - { name:"Bahçecilik", desc:"Sebze yetiştirme, toprak ve bitki hastalıkları.", lang:"EN", size:"—", zim:"gardening.stackexchange.com_en_all" }, - { name:"Yemek Pişirme", desc:"Pişirme teknikleri ve gıda güvenliği.", lang:"EN", size:"—", zim:"cooking.stackexchange.com_en_all" }, - { name:"Amatör Telsiz", desc:"Telsiz kurulumu, anten ve haberleşme.", lang:"EN", size:"—", zim:"ham.stackexchange.com_en_all" }, - { name:"Araç Bakımı", desc:"Motor, fren ve araç arızaları.", lang:"EN", size:"—", zim:"mechanics.stackexchange.com_en_all" }, - { name:"Doğa ve Kamp", desc:"Kamp, yürüyüş ve doğada hayatta kalma.", lang:"EN", size:"—", zim:"outdoors.stackexchange.com_en_all" }, - { name:"Sürdürülebilirlik", desc:"Enerji, su ve kaynak tasarrufu.", lang:"EN", size:"—", zim:"sustainability.stackexchange.com_en_all" }, + { title:{tr:"Tamir ve Beceriler", en:"Repair and Skills"}, items:[ + { name:"iFixit", desc:{tr:"Cihaz ve araç tamiri için adım adım rehberler.", en:"Step-by-step repair guides for devices and vehicles."}, lang:"EN", size:"~3 GB", zim:"ifixit_en_all", search:true }, + { name:{tr:"Ev Tamiri (DIY)", en:"Home Improvement (DIY)"}, desc:{tr:"Elektrik, tesisat ve yapı soruları.", en:"Electrical, plumbing and building questions."}, lang:"EN", size:"—", zim:"diy.stackexchange.com_en_all" }, + { name:{tr:"Bahçecilik", en:"Gardening"}, desc:{tr:"Sebze yetiştirme, toprak ve bitki hastalıkları.", en:"Growing vegetables, soil and plant diseases."}, lang:"EN", size:"—", zim:"gardening.stackexchange.com_en_all" }, + { name:{tr:"Yemek Pişirme", en:"Cooking"}, desc:{tr:"Pişirme teknikleri ve gıda güvenliği.", en:"Cooking techniques and food safety."}, lang:"EN", size:"—", zim:"cooking.stackexchange.com_en_all" }, + { name:{tr:"Amatör Telsiz", en:"Amateur Radio"}, desc:{tr:"Telsiz kurulumu, anten ve haberleşme.", en:"Radio setup, antennas and communication."}, lang:"EN", size:"—", zim:"ham.stackexchange.com_en_all" }, + { name:{tr:"Araç Bakımı", en:"Vehicle Maintenance"}, desc:{tr:"Motor, fren ve araç arızaları.", en:"Engine, brake and vehicle faults."}, lang:"EN", size:"—", zim:"mechanics.stackexchange.com_en_all" }, + { name:{tr:"Doğa ve Kamp", en:"Outdoors and Camping"}, desc:{tr:"Kamp, yürüyüş ve doğada hayatta kalma.", en:"Camping, hiking and survival in nature."}, lang:"EN", size:"—", zim:"outdoors.stackexchange.com_en_all" }, + { name:{tr:"Sürdürülebilirlik", en:"Sustainability"}, desc:{tr:"Enerji, su ve kaynak tasarrufu.", en:"Saving energy, water and resources."}, lang:"EN", size:"—", zim:"sustainability.stackexchange.com_en_all" }, ]}, - { title:"Eğitim", items:[ - { name:"Kolibri", desc:"Çevrimdışı dersler ve eğitim videoları.", lang:"—", size:"—", url:"/kolibri", service:"kolibri" }, + { title:{tr:"Eğitim", en:"Education"}, items:[ + { name:"Kolibri", desc:{tr:"Çevrimdışı dersler ve eğitim videoları.", en:"Offline lessons and educational videos."}, lang:"—", size:"—", url:"/kolibri", service:"kolibri" }, ]}, ]; +/* Sayfa metinleri: Türkçe ve İngilizce; dil seçimi tüm HAS sayfalarında ortak (has-lang). + Page texts in Turkish and English; the language choice is shared by all HAS pages (has-lang). */ +const T = { + tr: { + title:"HAS_PrepperDisk :: Ana Sayfa", slogan:"Çevrimdışı bilgi arşivi — internet olmasa da açık", + emergency:"Acil Durum", library:"Kütüphane", maps:"Haritalar", admin:"Yönetim", + tSystem:"Tema: Sistem", tDark:"Tema: Koyu", tLight:"Tema: Açık", + search:"Ara:", ph:"ilk yardım, su arıtma...", go:"Git", all:"Tüm kütüphane", + crumb:"HAS_PrepperDisk Ana Sayfa", diskWarn:"Disk ve güç uyarısı", + section:"Bölüm", lang:"Dil", size:"Boyut", status:"Durum", ready:"Hazır", notYet:"Henüz yüklenmedi", + installed:"Kurulu", openLib:"Kütüphaneden açın", edition:(m, y) => `${m}/${y} sürümü`, others:"Diğer Kaynaklar", + sysInfo:"Sistem bilgisi", serverTime:"Sunucu saati", + stats:(t, r) => `Toplam ${t} kaynak var, bunlardan ${r} tanesi kullanıma hazır.
Bu sayfa internet bağlantısı olmadan çalışır.`, + runsOn:"Raspberry Pi 5 üzerinde çalışır", contents:"İçerikler: Wikipedia, OpenStreetMap, Kolibri — ilgili lisanslar altında" + }, + en: { + title:"HAS_PrepperDisk :: Home", slogan:"Offline knowledge archive — open even without the internet", + emergency:"Emergency", library:"Library", maps:"Maps", admin:"Admin", + tSystem:"Theme: System", tDark:"Theme: Dark", tLight:"Theme: Light", + search:"Search:", ph:"first aid, water treatment...", go:"Go", all:"Whole library", + crumb:"HAS_PrepperDisk Home", diskWarn:"Disk and power warning", + section:"Section", lang:"Language", size:"Size", status:"Status", ready:"Ready", notYet:"Not installed yet", + installed:"Installed", openLib:"Open from the library", edition:(m, y) => `${m}/${y} edition`, others:"Other Sources", + sysInfo:"System information", serverTime:"Server time", + stats:(t, r) => `There are ${t} sources, ${r} of them ready to use.
This page works without an internet connection.`, + runsOn:"Runs on a Raspberry Pi 5", contents:"Contents: Wikipedia, OpenStreetMap, Kolibri — under their own licences" + } +}; +const LOCALE = {tr:"tr-TR", en:"en-GB"}; +let lang = (() => { try { return localStorage.getItem("has-lang"); } catch(e) { return null; } })() + || ((navigator.language || "tr").toLowerCase().startsWith("tr") ? "tr" : "en"); +if (!T[lang]) lang = "tr"; +const t = k => (T[lang] && T[lang][k] !== undefined ? T[lang][k] : T.tr[k]); +/* Dile göre alan: {tr, en} ya da düz metin / a field per language: {tr, en} or plain text */ +const L = v => v && typeof v === "object" ? (v[lang] || v.tr) : v; +const sizeText = s => lang === "en" ? s.replace(",", ".") : s; + +function applyLang(){ + document.documentElement.lang = lang; + document.title = t("title"); + for (const el of document.querySelectorAll("[data-t]")) el.textContent = t(el.dataset.t); + for (const el of document.querySelectorAll("[data-tp]")) el.placeholder = t(el.dataset.tp); + for (const el of document.querySelectorAll("[data-tv]")) el.value = t(el.dataset.tv); + for (const b of document.querySelectorAll("[data-lang]")) b.setAttribute("aria-pressed", String(b.dataset.lang === lang)); +} +let loaded = null; +for (const b of document.querySelectorAll("[data-lang]")) b.onclick = () => { + lang = b.dataset.lang; + try { localStorage.setItem("has-lang", lang); } catch(e) {} + applyLang(); showTime(); + if (loaded) render(loaded[0], loaded[1]); +}; + const esc = s => String(s).replace(/[&<>"]/g, c => ({"&":"&","<":"<",">":">",'"':"""}[c])); /* Kiwix kataloğundan cihazdaki ZIM'leri oku: { "wikipedia_tr_all_maxi_2026-09": "/kiwix/content/..." } */ @@ -287,6 +345,10 @@ }; function render(books, services){ + // Dil değişince yeniden çizilir: önceki satırlar ve seçenekler silinir, seçim korunur. + // Redrawn when the language changes: old rows and options are removed, the selection is kept. + const table = document.getElementById("forums"); + while (table.rows.length > 1) table.deleteRow(1); // Üst menü: data-service'teki ilk kurulu servise bağlanır, hiçbiri yoksa gizlenir (ör. Yönetim: HAS paneli, yoksa IIAB paneli). // Top menu: links to the first installed service in data-service, hidden if none (e.g. Admin: HAS panel, else IIAB console). for (const a of document.querySelectorAll("a[data-service]")) { @@ -298,41 +360,42 @@ } let html = "", ready = 0, total = 0; const used = new Set(); - const sel = document.getElementById("book"); - sel.add(new Option("Tüm kütüphane", "")); + const sel = document.getElementById("book"), keep = sel.value; + sel.length = 0; + sel.add(new Option(t("all"), "")); for (const c of CATS) { - html += `${esc(c.title)}`; + html += `${esc(L(c.title))}`; for (const i of c.items) { total++; - let url = i.url && has(services, i.service) ? i.url : null, status = url ? "Kurulu" : "Henüz yüklenmedi"; + let url = i.url && has(services, i.service) ? i.url : null, status = url ? t("installed") : t("notYet"); if (i.zim) { - if (books === null) { url = "/kiwix/"; status = "Kütüphaneden açın"; } + if (books === null) { url = "/kiwix/"; status = t("openLib"); } else { const b = books.filter(b => b.id.startsWith(i.zim + "_")).sort((a,z) => a.id < z.id ? 1 : -1)[0]; if (b) { used.add(b.id); url = b.href; const v = b.id.match(/(\d{4})-(\d{2})[a-z]?$/); - status = v ? `${v[2]}/${v[1]} sürümü` : "Kurulu"; - sel.add(new Option(i.name, b.id)); + status = v ? t("edition")(v[2], v[1]) : t("installed"); + sel.add(new Option(L(i.name), b.id)); } } } if (url) ready++; const icon = !url ? "fold gray" : "fold"; - const name = url ? `${esc(i.name)}` : `${esc(i.name)}`; + const name = url ? `${esc(L(i.name))}` : `${esc(L(i.name))}`; html += ` - ${name}
${esc(i.desc)}
+ ${name}
${esc(L(i.desc))}
${esc(i.lang)} - ${esc(i.size)} + ${esc(sizeText(i.size))} ${esc(status)}`; } } // Listede olmayan ama cihazda yüklü ZIM'ler / installed ZIMs not listed above const others = (books || []).filter(b => !used.has(b.id)); if (others.length) { - html += `Diğer Kaynaklar`; + html += `${esc(t("others"))}`; for (const b of others) { total++; ready++; // Listede olmayan kurulu kaynaklar da aramada seçilebilsin / installed sources not in the list are searchable too @@ -341,21 +404,25 @@ ${esc(b.title || b.id)}
${esc(b.id)}
—— - Kurulu`; + ${esc(t("installed"))}`; } } - document.getElementById("forums").insertAdjacentHTML("beforeend", html); - document.getElementById("stats").innerHTML = - `Toplam ${total} kaynak var, bunlardan ${ready} tanesi kullanıma hazır.
- Bu sayfa internet bağlantısı olmadan çalışır.`; + table.insertAdjacentHTML("beforeend", html); + if ([...sel.options].some(o => o.value === keep)) sel.value = keep; + document.getElementById("stats").innerHTML = t("stats")(total, ready); } -/* Saat, telefonun değil Pi'nin saatidir: HTTP yanıtının Date başlığından okunur. */ +/* Saat, telefonun değil Pi'nin saatidir: HTTP yanıtının Date başlığından okunur. + The clock is the Pi's, not the phone's: read from the Date header of the HTTP response. */ +let serverDate = null; +function showTime(){ + if (!serverDate) return; + const loc = LOCALE[lang]; + document.getElementById("now").textContent = `${t("serverTime")}: ${serverDate.toLocaleDateString(loc)} ${serverDate.toLocaleTimeString(loc, {hour:"2-digit", minute:"2-digit"})}`; +} fetch(location.href, {method:"HEAD", cache:"no-store"}).then(r => { const d = new Date(r.headers.get("Date")); - if (isNaN(d)) return; - document.getElementById("now").textContent = - "Sunucu saati: " + d.toLocaleDateString("tr-TR") + " " + d.toLocaleTimeString("tr-TR",{hour:"2-digit",minute:"2-digit"}); + if (!isNaN(d)) { serverDate = d; showTime(); } }).catch(() => {}); document.getElementById("search").addEventListener("submit", e => { @@ -377,7 +444,8 @@ box.hidden = false; }).catch(() => {}); -Promise.all([loadBooks(), loadServices()]).then(([books, services]) => render(books, services)); +applyLang(); +Promise.all([loadBooks(), loadServices()]).then(([books, services]) => { loaded = [books, services]; render(books, services); }); + +
-
+

HAS_PrepperDisk ·

-
+
- +
+
+ - + -

+

- +
@@ -236,7 +247,7 @@

${items.map(c => ` - + diff --git a/e2e/package-lock.json b/e2e/package-lock.json index 6d3bdb7..a0d2766 100644 --- a/e2e/package-lock.json +++ b/e2e/package-lock.json @@ -7,6 +7,7 @@ "name": "has-e2e", "devDependencies": { "@playwright/test": "1.65.1", + "axe-core": "4.14.0", "playwright-1.22.2": "npm:@playwright/test@1.22.2", "playwright-1.29.2": "npm:@playwright/test@1.29.2", "playwright-1.37.1": "npm:@playwright/test@1.37.1", @@ -41,6 +42,16 @@ "undici-types": "~8.9.0" } }, + "node_modules/axe-core": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.0.tgz", + "integrity": "sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", diff --git a/e2e/package.json b/e2e/package.json index dab4917..170efda 100644 --- a/e2e/package.json +++ b/e2e/package.json @@ -12,6 +12,7 @@ "playwright-1.46.1": "npm:@playwright/test@1.46.1", "playwright-1.37.1": "npm:@playwright/test@1.37.1", "playwright-1.29.2": "npm:@playwright/test@1.29.2", - "playwright-1.22.2": "npm:@playwright/test@1.22.2" + "playwright-1.22.2": "npm:@playwright/test@1.22.2", + "axe-core": "4.14.0" } } diff --git a/e2e/tests/a11y.spec.js b/e2e/tests/a11y.spec.js new file mode 100644 index 0000000..663ad46 --- /dev/null +++ b/e2e/tests/a11y.spec.js @@ -0,0 +1,76 @@ +// Erişilebilirlik: axe-core ile WCAG 2.2 A/AA kuralları, her sayfa açık ve koyu temada. +// Accessibility: WCAG 2.2 A/AA rules with axe-core, every page in the light and dark theme. +// +// Kiwix'in içeriği (okuyucudaki çerçeve) HAS'ın değil, denetim dışında tutulur. +// Kiwix's content (the frame in the reader) is not HAS's own and is left out. +const path = require('path'); +const { test, expect } = require('@playwright/test'); +const { BOOKS, login } = require('./common'); + +const AXE = path.join(__dirname, '..', 'node_modules', 'axe-core', 'axe.min.js'); +const TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']; + +async function audit(page, theme) { + await page.evaluate((t) => window.hasTheme && window.hasTheme(t), theme); + await page.addScriptTag({ path: AXE }); + const result = await page.evaluate( + (tags) => + window.axe.run( + { exclude: [['#frame']] }, + { runOnly: { type: 'tag', values: tags }, resultTypes: ['violations'] }, + ), + TAGS, + ); + return result.violations.map( + (v) => + `${v.id} (${v.impact}): ${v.help} → ${v.nodes + .slice(0, 3) + .map((n) => n.target.join(' ')) + .join(' | ')}`, + ); +} + +const pages = [ + { name: 'ana sayfa / homepage', url: '/home/', ready: '#forums td.cat' }, + { name: 'acil / emergency', url: '/home/acil.html', ready: 'body' }, + { name: 'okuyucu / reader', url: () => `/home/oku.html#${BOOKS[0] || 'library'}`, ready: '.bar' }, + { name: 'panel girişi / panel login', url: '/admin/', ready: '#login:not([hidden])' }, + { name: 'panel', url: '/admin/', ready: 'h3.grp', login: true }, +]; + +for (const p of pages) { + for (const theme of ['light', 'dark']) { + test(`erişilebilirlik / accessibility: ${p.name}, ${theme}`, async ({ page }) => { + if (p.login) await login(page); + await page.goto(typeof p.url === 'function' ? p.url() : p.url); + await page.waitForSelector(p.ready); + const violations = await audit(page, theme); + expect(violations, violations.join('\n')).toEqual([]); + }); + } +} + +test('klavye: içeriğe atla bağlantısı ve görünür odak / keyboard: skip link and visible focus', async ({ + page, + browserName, +}) => { + test.skip( + browserName === 'webkit', + 'WebKit Tab ile bağlantılara odaklanmaz (Safari varsayılanı) / WebKit does not tab to links by default', + ); + for (const url of ['/home/', '/home/acil.html', '/admin/']) { + await page.goto(url); + await page.keyboard.press('Tab'); + const focused = await page.evaluate(() => { + const el = document.activeElement; + const s = getComputedStyle(el); + return { + cls: el.className, + href: el.getAttribute('href'), + outline: s.outlineStyle !== 'none' && parseFloat(s.outlineWidth) > 0, + }; + }); + expect(focused.href, `${url}: ilk Tab içeriğe atlar / first Tab is the skip link`).toBe('#main'); + expect(focused.outline, `${url}: odak görünür / focus visible`).toBe(true); + } +}); diff --git a/www/home/acil.html b/www/home/acil.html index 7d79f5d..676149d 100644 --- a/www/home/acil.html +++ b/www/home/acil.html @@ -55,14 +55,26 @@ html[data-theme="dark"] .btn:hover{background:#3a4652} html[data-theme="dark"] #disk td{color:#ff7b7b} + + /* Erişilebilirlik: içeriğe atla bağlantısı ve klavye odağı / accessibility: skip link and keyboard focus */ + .skip{position:absolute;left:-9999px;top:0;z-index:1000;background:#000;color:#fff;padding:10px 14px;font-weight:bold} + .skip:focus{left:8px;top:8px} + :focus-visible{outline:3px solid #E8A200;outline-offset:2px} + main:focus{outline:none} + /* Metin içindeki bağlantılar renkle değil alt çizgiyle de ayrılır / links in text are underlined, not only coloured */ + td.row1 a,td.src a,.toc a{text-decoration:underline} +
+
HAS_PrepperDisk Ana Sayfa » Acil Durum
+
+
-
${t("item")}${t("note")}${t("onDevice")}
${brk(c.prefix)}
${esc(c.folder)}
${c.note ? `
${esc(c.note)}
` : ""}
${esc(c.note)} ${c.installed ? `${brk(c.installed)}
${mb(c.size)}
` : `${t("no")}`}
Hayati tehlike varsa ve telefon çalışıyorsa: 112
+
Hayati tehlike varsa ve telefon çalışıyorsa: 112
Deprem anında · Enkaz altında · @@ -164,7 +176,8 @@ talimatları her zaman önceliklidir. -
HAS_PrepperDisk · Bu sayfa çevrimdışı çalışır, yazdırılabilir.
+ +
HAS_PrepperDisk · Bu sayfa çevrimdışı çalışır, yazdırılabilir.
From b62e8bccaeff66aafc748eb45e21f56252501ffb Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 05:28:35 +0300 Subject: [PATCH 41/65] feat: show sizes for content that is not installed, also offline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A box that never had internet had no sizes.json, so items not yet downloaded showed only the old estimates. config/sizes.json is a starter list generated from the Kiwix catalog (SIZES_OUT=config/sizes.json scripts/catalog-sizes.sh, 29 items); install-homepage.sh copies it when the box has none, and catalog-sizes.sh replaces it with current values whenever there is internet. For services that are not installed, a module can give a typical size from its docs: the map module uses the IIAB Maps default (~170 MB, vector nat-z8 plus satellite z7), shown with a ~ on the homepage; once installed, the measured size replaces it. Hiç internet görmemiş kutuda sizes.json yoktu; henüz indirilmemiş içerikte yalnız eski tahminler görünüyordu. config/sizes.json Kiwix kataloğundan üretilen başlangıç listesi (SIZES_OUT=config/sizes.json scripts/catalog-sizes.sh, 29 içerik); install-homepage.sh kutuda yoksa kopyalıyor, internet olduğunda catalog-sizes.sh güncel değerleri yazıyor. Kurulu olmayan servisler için modül belgesinden yaklaşık bir boyut verebiliyor: harita modülü IIAB Maps varsayılanını (~170 MB, vektör nat-z8 + uydu z7) kullanıyor, ana sayfada ~ ile; kurulunca ölçülen boyut yerini alıyor. --- .prettierignore | 2 ++ config/sizes.json | 1 + scripts/catalog-sizes.sh | 6 ++++-- scripts/install-homepage.sh | 5 +++++ scripts/services.d/maps.sh | 3 +++ scripts/services.sh | 8 ++++++-- www/home/index.html | 4 +++- 7 files changed, 24 insertions(+), 5 deletions(-) create mode 100644 config/sizes.json diff --git a/.prettierignore b/.prettierignore index 4ebc417..faed3a2 100644 --- a/.prettierignore +++ b/.prettierignore @@ -7,3 +7,5 @@ library/ e2e/test-results/ e2e/playwright-report/ **/package-lock.json +# Betikle üretilir / generated by a script (scripts/catalog-sizes.sh) +config/sizes.json diff --git a/config/sizes.json b/config/sizes.json new file mode 100644 index 0000000..0098638 --- /dev/null +++ b/config/sizes.json @@ -0,0 +1 @@ +{"checked":"2026-11-29T05:28:00+03:00","items":{"wikipedia_tr_all_maxi":{"file":"wikipedia_tr_all_maxi_2026-09.zim","bytes":8907256832},"wikipedia_en_all_maxi":{"file":"wikipedia_en_all_maxi_2026-08.zim","bytes":127418088448},"wiktionary_tr_all_nopic":{"file":"wiktionary_tr_all_nopic_2026-10.zim","bytes":812545024},"wikibooks_tr_all_maxi":{"file":"wikibooks_tr_all_maxi_2026-09.zim","bytes":26889216},"wikisource_tr_all_maxi":{"file":"wikisource_tr_all_maxi_2026-10.zim","bytes":68264960},"wikiquote_tr_all_maxi":{"file":"wikiquote_tr_all_maxi_2026-07.zim","bytes":59491328},"ifixit_tr_all":{"file":"ifixit_tr_all_2026-03.zim","bytes":3633666048},"phet_tr_all":{"file":"phet_tr_all_2026-11.zim","bytes":106995712},"appropedia_en_all_maxi":{"file":"appropedia_en_all_maxi_2026-02.zim","bytes":581642240},"zimgit-post-disaster_en":{"file":"zimgit-post-disaster_en_2024-05.zim","bytes":644666368},"zimgit-water_en":{"file":"zimgit-water_en_2024-08.zim","bytes":20925440},"zimgit-food-preparation_en":{"file":"zimgit-food-preparation_en_2025-04.zim","bytes":97822720},"zimgit-knots_en":{"file":"zimgit-knots_en_2024-08.zim","bytes":27945984},"ready.gov_en_all":{"file":"ready.gov_en_all_2026-10.zim","bytes":2063895552},"solar.lowtechmagazine.com_mul_all":{"file":"solar.lowtechmagazine.com_mul_all_2025-01.zim","bytes":700556288},"wikipedia_en_medicine_maxi":{"file":"wikipedia_en_medicine_maxi_2026-10.zim","bytes":1864210432},"mdwiki_en_all_maxi":{"file":"mdwiki_en_all_maxi_2025-11.zim","bytes":2302838784},"medlineplus.gov_en_all":{"file":"medlineplus.gov_en_all_2025-01.zim","bytes":1944841216},"zimgit-medicine_en":{"file":"zimgit-medicine_en_2024-08.zim","bytes":70179840},"irp.fas.org_en_military-medicine":{"file":"irp.fas.org_en_military-medicine_2026-10.zim","bytes":64986112},"nhs.uk_en_medicines":{"file":"nhs.uk_en_medicines_2026-09b.zim","bytes":15323136},"ifixit_en_all":{"file":"ifixit_en_all_2025-12.zim","bytes":3570696192},"diy.stackexchange.com_en_all":{"file":"diy.stackexchange.com_en_all_2026-10.zim","bytes":2086025216},"gardening.stackexchange.com_en_all":{"file":"gardening.stackexchange.com_en_all_2026-10.zim","bytes":933097472},"cooking.stackexchange.com_en_all":{"file":"cooking.stackexchange.com_en_all_2026-10.zim","bytes":238098432},"ham.stackexchange.com_en_all":{"file":"ham.stackexchange.com_en_all_2026-10.zim","bytes":77109248},"mechanics.stackexchange.com_en_all":{"file":"mechanics.stackexchange.com_en_all_2026-10.zim","bytes":341672960},"outdoors.stackexchange.com_en_all":{"file":"outdoors.stackexchange.com_en_all_2026-10.zim","bytes":141820928},"sustainability.stackexchange.com_en_all":{"file":"sustainability.stackexchange.com_en_all_2026-10.zim","bytes":27687936}}} diff --git a/scripts/catalog-sizes.sh b/scripts/catalog-sizes.sh index 1d7ea6a..d05011a 100644 --- a/scripts/catalog-sizes.sh +++ b/scripts/catalog-sizes.sh @@ -7,11 +7,13 @@ # Kullanım / usage: ./scripts/catalog-sizes.sh [config-dosyası / config file] # Ortam / environment: WEB=/library/www/html CATALOG_URL=https://library.kiwix.org/catalog/v2/entries?count=-1 # CATALOG_FILE= önceden indirilmiş katalog (download-content.sh verir) / an already downloaded catalog +# SIZES_OUT= çıktı dosyası; repodaki ilk liste için: SIZES_OUT=config/sizes.json +# output file; for the starter list in the repo: SIZES_OUT=config/sizes.json set -uo pipefail CONF="${1:-$(cd "$(dirname "$0")/.." && pwd)/config/content.conf}" WEB="${WEB:-/library/www/html}" -OUT="$WEB/home/sizes.json" +OUT="${SIZES_OUT:-$WEB/home/sizes.json}" CATALOG_URL="${CATALOG_URL:-https://library.kiwix.org/catalog/v2/entries?count=-1}" CAT="${CATALOG_FILE:-}" @@ -39,7 +41,7 @@ while read -r folder prefix _; do done <"$CONF" [ "$n" -gt 0 ] || { echo "!! Katalogda eşleşen içerik yok / no matching content in the catalog" >&2; exit 0; } -mkdir -p "$WEB/home" +mkdir -p "$(dirname "$OUT")" printf '{"checked":"%s","items":{%s}}\n' "$(date -Is)" "$items" >"$OUT.tmp" chmod 644 "$OUT.tmp" && mv "$OUT.tmp" "$OUT" echo "Boyutlar / sizes: $n içerik / items → $OUT" diff --git a/scripts/install-homepage.sh b/scripts/install-homepage.sh index 5ebb128..ce5312e 100755 --- a/scripts/install-homepage.sh +++ b/scripts/install-homepage.sh @@ -17,6 +17,11 @@ fi cp "$SRC"/*.html "$SRC"/*.js "$DST/" # Ana sayfa yalnız kurulu servisleri (harita, Kolibri, yönetim) gösterir / the homepage only lists installed services "$(dirname "$0")/services.sh" +# Boyutlar: hiç internet görmemiş kutuda da görünsün diye repodaki liste (config/sizes.json) başlangıç olarak +# kopyalanır; internet varsa catalog-sizes.sh güncelini yazar. / Sizes: the list in the repo (config/sizes.json) +# is copied as a starting point so a box that never had internet still shows them; online, catalog-sizes.sh +# writes the current ones. +[ -s "$DST/sizes.json" ] || cp "$(dirname "$0")/../config/sizes.json" "$DST/sizes.json" 2>/dev/null || true # Kesin ZIM boyutları (internet yoksa atlanır) / exact ZIM sizes (skipped without internet) [ "${HAS_SIZES:-1}" = 1 ] && { "$(dirname "$0")/catalog-sizes.sh" || true; } echo "Ana sayfa kuruldu / homepage installed: http://box.lan/home" diff --git a/scripts/services.d/maps.sh b/scripts/services.d/maps.sh index 9e65ef6..ce76aa3 100644 --- a/scripts/services.d/maps.sh +++ b/scripts/services.d/maps.sh @@ -5,3 +5,6 @@ label_tr="Harita"; label_en="Map"; url="/maps" check(){ [ -f /library/www/maps/index.html ] || [ -d /library/www/osm-vector-maps/viewer ]; } # Diskteki gerçek boyut, internetsiz de bilinir / real size on disk, known without internet size(){ for d in /library/www/maps /library/www/osm-vector-maps; do [ -d "$d" ] && { du -sbL "$d" | cut -f1; return; }; done; } +# Kurulu değilken: IIAB Maps varsayılanı ~170 MB (vektör nat-z8 85 MB + uydu z7 85 MB; iiab/iiab roles/maps/README.md) +# When not installed: the IIAB Maps default, ~170 MB (vector nat-z8 85 MB + satellite z7 85 MB; iiab/iiab roles/maps/README.md) +typical=178257920 diff --git a/scripts/services.sh b/scripts/services.sh index d382eb1..cd0ad16 100755 --- a/scripts/services.sh +++ b/scripts/services.sh @@ -9,6 +9,7 @@ # url servisin adresi / the service's address # check() kuruluysa 0 döner / returns 0 when installed # size() isteğe bağlı: kuruluysa diskteki bayt / optional: bytes on disk when installed +# typical isteğe bağlı: kurulu değilken gösterilen yaklaşık bayt / optional: approximate bytes shown when not installed # install-homepage.sh çağırır; Pi'de ve Docker'da aynı betik. / Called by install-homepage.sh; same script on the Pi and in Docker. # # Ortam / environment: WEB=/library/www/html @@ -30,7 +31,7 @@ for mod in "$DIR"/*.sh; do # Her modül kendi alt kabuğunda; biri bozuksa diğerleri etkilenmez. # Each module runs in its own subshell; a broken one does not affect the others. line=$( - label_tr="$name"; label_en="$name"; url="" + label_tr="$name"; label_en="$name"; url=""; typical="" check(){ return 1; } size(){ :; } # shellcheck source=/dev/null @@ -39,8 +40,11 @@ for mod in "$DIR"/*.sh; do # İsteğe bağlı size(): kuruluysa diskteki bayt / optional size(): bytes on disk when installed bytes="" if [ "$installed" = true ]; then bytes=$(size 2>/dev/null | tr -dc '0-9'); fi + # typical: kurulu değilken gösterilecek, belgeden alınmış yaklaşık boyut / approximate size from the docs, shown when not installed + extra="${bytes:+,\"bytes\":$bytes}" + if [ "$installed" = false ] && [ -n "${typical:-}" ]; then extra=",\"typical\":${typical//[!0-9]/}"; fi printf '%s:{"installed":%s,"url":%s,"label":{"tr":%s,"en":%s}%s}' \ - "$(json "$name")" "$installed" "$(json "$url")" "$(json "$label_tr")" "$(json "$label_en")" "${bytes:+,\"bytes\":$bytes}" + "$(json "$name")" "$installed" "$(json "$url")" "$(json "$label_tr")" "$(json "$label_en")" "$extra" ) || continue items+="${items:+,}$line" case "$line" in *'"installed":true'*) summary+=" $name=var/yes";; *) summary+=" $name=yok/no";; esac diff --git a/www/home/index.html b/www/home/index.html index 415974f..dc3e5a4 100644 --- a/www/home/index.html +++ b/www/home/index.html @@ -413,7 +413,9 @@ /* Servisin diskteki boyutu (services.json, ör. harita) / a service's size on disk (services.json, e.g. the map) */ function serviceSize(services, name){ const s = name && services && services[name]; - return s && typeof s === "object" && s.bytes ? formatBytes(s.bytes) : ""; + if (!s || typeof s !== "object") return ""; + // Kuruluysa ölçülen boyut, değilse belgeden yaklaşık boyut / measured when installed, else approximate from the docs + return s.bytes ? formatBytes(s.bytes) : s.typical ? "~" + formatBytes(s.typical) : ""; } const loadSizes = () => fetch("/home/sizes.json", {cache:"no-store"}).then(r => r.ok ? r.json() : {}).then(d => { sizes = d.items || {}; }).catch(() => {}); Promise.all([loadBooks(), loadServices(), loadSizes()]).then(([books, services]) => { loaded = [books, services]; render(books, services); }); From a4b4e9efe2cbec4e0ca646de1005a136d83e4f55 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 05:32:30 +0300 Subject: [PATCH 42/65] build(docker): refresh sizes at build time and download kiwix-tools natively MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new "sizes" stage runs scripts/catalog-sizes.sh on the build machine's architecture and puts the current Kiwix catalog sizes into the image instead of the repo's starter list; it does not depend on the target, so the 4.4 MB catalog is fetched once for all five platforms and cached, and the weekly build keeps it fresh. The kiwix stage only downloads and unpacks the archive for the target, so it now also runs natively instead of under QEMU. catalog-sizes.sh no longer spoils the file when the catalog is bad: unreachable or not a catalog leaves it untouched (as before), and items missing from a cut catalog keep their previous values. Tested with a cut catalog, an HTML error page and an unreachable host; an arm64 build picks the aarch64 kiwix-serve and carries fresh sizes. Yeni "sizes" aşaması scripts/catalog-sizes.sh'yi derleyen makinenin mimarisinde çalıştırıp repodaki başlangıç listesi yerine güncel Kiwix katalog boyutlarını imaja koyuyor; hedeften bağımsız olduğu için 4,4 MB katalog beş mimari için bir kez inip önbellekte kalıyor, haftalık derleme tazeliyor. kiwix aşaması hedef için arşivi yalnız indirip açtığından artık o da QEMU yerine yerel çalışıyor. catalog-sizes.sh katalog bozuksa artık dosyayı bozmuyor: erişilemez ya da katalog değilse dokunmuyor (önceki gibi), kesik katalogda bulunamayan içerikler eski değerini koruyor. Kesik katalog, HTML hata sayfası ve erişilemeyen adresle denendi; arm64 derlemesi aarch64 kiwix-serve'ü seçiyor ve güncel boyutları taşıyor. --- docker/Dockerfile | 19 ++++++++++++++++++- scripts/catalog-sizes.sh | 14 ++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index aafc95e..7df0267 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -7,7 +7,9 @@ # The base image is pinned by version, the Kiwix binaries by version + SHA-256. # ---------------------------------------------------------------- kiwix-tools (resmî, statik / official, static) -FROM alpine:3.24.4 AS kiwix +# Yalnız indirip açar, hedef ikiliyi çalıştırmaz: derleyicinin mimarisinde (QEMU'suz) çalışır. +# Only downloads and unpacks, never runs the target binaries: runs on the build machine's arch (no QEMU). +FROM --platform=$BUILDPLATFORM alpine:3.24.4 AS kiwix ARG TARGETARCH ARG TARGETVARIANT ARG KIWIX_VERSION=3.8.2 @@ -46,6 +48,20 @@ RUN go vet ./... && go test ./... RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} GOARM=${TARGETVARIANT#v} \ go build -trimpath -ldflags "-s -w" -o /out/has-admin . +# ---------------------------------------------------------------- boyutlar / sizes +# İmaj derlenirken Kiwix kataloğundan güncel kesin boyutlar (config/sizes.json'un yerine); haftalık derleme +# tazeler. Katalog erişilemezse repodaki liste kalır. Derleyicinin mimarisinde bir kez çalışır. +# Current exact sizes from the Kiwix catalog at build time (replacing config/sizes.json); the weekly build keeps +# them fresh. If the catalog is unreachable, the list in the repo stays. Runs once, on the build machine's arch. +# Ayrı aşama: hedef mimariden bağımsız olduğu için beş mimari için tek kez (4,4 MB katalog) indirilir ve önbellekte kalır. +# Separate stage: it does not depend on the target, so the 4.4 MB catalog is fetched once for all five platforms and cached. +FROM --platform=$BUILDPLATFORM alpine:3.24.4 AS sizes +# hadolint ignore=DL3018 +RUN apk add --no-cache bash curl +COPY config/ /src/config/ +COPY scripts/catalog-sizes.sh /src/scripts/ +RUN SIZES_OUT=/src/config/sizes.json bash /src/scripts/catalog-sizes.sh || true + # ---------------------------------------------------------------- imaj / image FROM alpine:3.24.4 # apk upgrade: taban imajdan sonra çıkan güvenlik düzeltmeleri her derlemede gelir. @@ -60,6 +76,7 @@ RUN apk upgrade --no-cache \ COPY --from=kiwix --chmod=0755 /out/kiwix-serve /out/kiwix-manage /usr/local/bin/ COPY --from=admin --chmod=0755 /out/has-admin /usr/local/bin/has-admin COPY config/ /opt/has/config/ +COPY --from=sizes /src/config/sizes.json /opt/has/config/sizes.json COPY scripts/ /opt/has/scripts/ COPY www/ /opt/has/www/ COPY docker/nginx.conf /etc/nginx/nginx.conf diff --git a/scripts/catalog-sizes.sh b/scripts/catalog-sizes.sh index d05011a..cc8b5f1 100644 --- a/scripts/catalog-sizes.sh +++ b/scripts/catalog-sizes.sh @@ -29,11 +29,21 @@ fi json() { local s=${1//\\/\\\\}; printf '"%s"' "${s//\"/\\\"}"; } items="" n=0 + +# Önceki dosya: katalogda bulunamayan içeriğin eski değeri korunur (kesik ya da eksik katalog dosyayı bozmaz). +# Previous file: an item missing from the catalog keeps its old value (a cut or partial catalog cannot spoil the file). +old="" +[ -s "$OUT" ] && old=$(cat "$OUT") +kept=0 while read -r folder prefix _; do case "$folder" in '' | \#*) continue ;; esac # Katalog satırı / catalog line: href="https://.../_YYYY-MM.zim.meta4" ... length="" entry=$(grep -oE "href=\"https://[^\"]*/${prefix}_[0-9]{4}-[0-9]{2}[a-z]?\.zim\.meta4\"[^>]*length=\"[0-9]+\"" "$CAT" | sort -u | tail -1) - [ -n "$entry" ] || continue + if [ -z "$entry" ]; then + prev=$(grep -oE "\"${prefix//./\.}\":\{\"file\":\"[^\"]*\",\"bytes\":[0-9]+\}" <<<"$old" | head -1) + if [ -n "$prev" ]; then items+="${items:+,}$prev"; kept=$((kept + 1)); fi + continue + fi file=$(sed -E 's#^href="[^"]*/([^/"]*)\.meta4".*#\1#' <<<"$entry") bytes=$(sed -E 's/.*length="([0-9]+)".*/\1/' <<<"$entry") items+="${items:+,}$(json "$prefix"):{\"file\":$(json "$file"),\"bytes\":$bytes}" @@ -44,4 +54,4 @@ done <"$CONF" mkdir -p "$(dirname "$OUT")" printf '{"checked":"%s","items":{%s}}\n' "$(date -Is)" "$items" >"$OUT.tmp" chmod 644 "$OUT.tmp" && mv "$OUT.tmp" "$OUT" -echo "Boyutlar / sizes: $n içerik / items → $OUT" +echo "Boyutlar / sizes: $n içerik / items (+$kept eski / kept) → $OUT" From 97bb9edf55ac42fc69dbccc9aa632fc3a3b6b64c Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 05:44:05 +0300 Subject: [PATCH 43/65] perf(docker): cache the Kiwix catalog, use every core, cache has.js in the browser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measured with ab -k -c 50 in Docker (4 cores, not a Pi), before → after: Kiwix catalog 8,440 → 35,569 req/s (p99 21 → 7 ms), has.js 28,072 → 51,553, Kiwix article 5,313 → 6,820. - worker_processes auto (was 1), worker_connections 1024 (was 512). - /kiwix/catalog/ is cached for 10 s with proxy_cache_lock, so a burst of clients costs Kiwix one catalog build. Kiwix sends "max-age=0, must-revalidate", which has to be ignored (proxy_ignore_headers); without it every request waited 5 s on the lock (catalog fell to 544 req/s in the first try). - has.js stays 10 minutes in the browser; pages and json files are sent with Cache-Control: no-cache, so they are revalidated with ETag (304 without a body). - The panel upstream keeps connections open. For Kiwix it is left off: kiwix-serve runs with few threads and idle kept-open connections made articles slower (4,469 req/s with, 6,820 without). - On one core static pages got slightly slower (several workers competing). test.sh: the "deleted file gone" check now looks at the ZIM list only, since the new "latest" field can carry the same file name from the catalog. Docker'da ab -k -c 50 ile ölçüldü (4 çekirdek, Pi değil), önce → sonra: Kiwix kataloğu 8.440 → 35.569 istek/sn (p99 21 → 7 ms), has.js 28.072 → 51.553, Kiwix makalesi 5.313 → 6.820. - worker_processes auto (önce 1), worker_connections 1024 (önce 512). - /kiwix/catalog/ 10 sn proxy_cache_lock ile önbellekte; aynı anda gelen çok istemci Kiwix'e tek katalog üretimine mal oluyor. Kiwix "max-age=0, must-revalidate" gönderiyor, yok sayılması gerekiyor (proxy_ignore_headers); yoksa her istek kilitte 5 sn bekliyordu (ilk denemede katalog 544 istek/sn'ye düştü). - has.js tarayıcıda 10 dk kalıyor; sayfalar ve json dosyaları Cache-Control: no-cache ile gidiyor, ETag ile denetleniyor (değişmediyse gövdesiz 304). - Panel upstream'inde bağlantılar açık tutuluyor. Kiwix'te kapalı: kiwix-serve az iş parçacığıyla çalışıyor, açık tutulan boştaki bağlantılar makaleleri yavaşlattı (açıkken 4.469, kapalıyken 6.820 istek/sn). - Tek çekirdekte sabit sayfalar biraz yavaşladı (birden çok işçi yarışıyor). test.sh: "silinen dosya listede yok" kontrolü artık yalnız ZIM listesine bakıyor; yeni "latest" alanı katalogdaki aynı dosya adını taşıyabiliyor. --- docker/nginx.conf | 80 ++++++++++++++++++++++++++++++++++++++++++----- docker/test.sh | 4 ++- 2 files changed, 76 insertions(+), 8 deletions(-) diff --git a/docker/nginx.conf b/docker/nginx.conf index e818fb1..c3043e5 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -3,12 +3,13 @@ # nginx root olmayan kullanıcıyla çalışır; yazdığı her şey /tmp altında (salt okunur kök dosya sistemi). # nginx runs as a non-root user; everything it writes goes under /tmp (read-only root filesystem). -worker_processes 1; +# Her çekirdeğe bir işçi (Pi'de 4 çekirdek) / one worker per core (4 core on a Pi) +worker_processes auto; pid /tmp/nginx.pid; error_log stderr warn; events { - worker_connections 512; + worker_connections 1024; } http { @@ -29,8 +30,15 @@ http { gzip_min_length 1024; gzip_vary on; gzip_proxied any; - gzip_types text/css text/plain text/xml application/javascript application/json application/xml - application/atom+xml image/svg+xml; + gzip_types + text/css + text/plain + text/xml + application/javascript + application/json + application/xml + application/atom+xml + image/svg+xml; client_body_temp_path /tmp/nginx-client; proxy_temp_path /tmp/nginx-proxy; @@ -38,6 +46,26 @@ http { uwsgi_temp_path /tmp/nginx-uwsgi; scgi_temp_path /tmp/nginx-scgi; + # Kiwix'e açık bağlantı tutulmaz: kiwix-serve az sayıda iş parçacığıyla çalışıyor, boştaki bağlantılar onları + # meşgul edip makale isteklerini bekletiyordu (ölçüm: 4 çekirdekte keepalive ile 4.469, onsuz 6.820 istek/sn). + # Panelde bağlantı açık tutulup yeniden kullanılır. + # No kept-open connections to Kiwix: kiwix-serve runs with few threads and idle connections kept them busy, + # making article requests wait (measured on 4 cores: 4,469 req/s with keepalive, 6,820 without). + # For the panel, connections are kept open and reused. + upstream kiwix { + server 127.0.0.1:8081; + } + upstream admin { + server 127.0.0.1:8090; + keepalive 4; + } + + # Kiwix kataloğu her istekte yeniden üretiliyor; 10 sn önbellek, aynı anda gelenler tek istekle karşılanır. + # Yeni indirilen kitap en geç 10 sn sonra görünür. Önbellek /tmp'de (tmpfs), diske yazılmaz. + # Kiwix builds its catalog on every request; a 10 s cache, simultaneous requests are served by one upstream call. + # A newly downloaded book shows up within 10 s. The cache is in /tmp (tmpfs), nothing is written to disk. + proxy_cache_path /tmp/nginx-cache levels=1 keys_zone=catalog:1m max_size=16m inactive=5m use_temp_path=off; + server { listen 8080; # IIAB ile aynı web kökü / same web root as IIAB @@ -54,11 +82,33 @@ http { try_files $uri $uri/ =404; } + # Ortak betik 10 dk tarayıcıda kalır (zayıf Wi-Fi'de her sayfada yeniden indirilmez); sayfalar ve + # durum dosyaları her seferinde ETag ile denetlenir (değişmediyse 304, gövde gitmez). + # The shared script stays in the browser for 10 min (not fetched again on every page over weak Wi-Fi); + # pages and status files are revalidated each time with ETag (304 without a body when unchanged). + location = /home/has.js { + expires 10m; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy no-referrer always; + } + location ~ ^/home/.*\.(html|json)$ { + add_header Cache-Control "no-cache" always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy no-referrer always; + } + location = /home/ { + add_header Cache-Control "no-cache" always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy no-referrer always; + try_files /home/index.html =404; + } + # Yönetim paneli (admin/, has-admin) / admin panel location /admin { - proxy_pass http://127.0.0.1:8090; + proxy_pass http://admin; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; + proxy_set_header Connection ""; proxy_http_version 1.1; client_max_body_size 64k; } @@ -69,14 +119,30 @@ http { if ($arg_has = "") { return 302 /home/oku.html#library; } - proxy_pass http://127.0.0.1:8081; + proxy_pass http://kiwix; + proxy_set_header Host $http_host; + proxy_set_header Connection ""; + proxy_http_version 1.1; + } + + location /kiwix/catalog/ { + proxy_pass http://kiwix; proxy_set_header Host $http_host; + proxy_set_header Connection ""; proxy_http_version 1.1; + proxy_cache catalog; + # Kiwix "max-age=0, must-revalidate" gönderiyor; önbellek bunu yok sayar (yoksa her istek 5 sn kilitte bekler). + # Kiwix sends "max-age=0, must-revalidate"; the cache ignores it (otherwise every request waits 5 s on the lock). + proxy_ignore_headers Cache-Control Expires; + proxy_cache_valid 200 10s; + proxy_cache_lock on; + proxy_cache_use_stale updating error timeout; } location /kiwix/ { - proxy_pass http://127.0.0.1:8081; + proxy_pass http://kiwix; proxy_set_header Host $http_host; + proxy_set_header Connection ""; proxy_http_version 1.1; } } diff --git a/docker/test.sh b/docker/test.sh index 7024acd..d1f9b05 100755 --- a/docker/test.sh +++ b/docker/test.sh @@ -374,7 +374,9 @@ if [ -n "$F" ]; then req POST /delete "{\"file\":\"$F\",\"password\":\"$PASS\"}"; expect "şifreyle silme / delete with password" 200 removed wait_job library req GET /status - if [[ $BODY != *"$F"* ]]; then ok "silinen dosya listede yok / deleted file gone"; else bad "silinen dosya hâlâ listede / still listed: $F"; fi + # Yalnız diskteki ZIM listesine bakılır; "latest" alanı katalogdaki aynı adı taşıyabilir. + # Only the ZIM list on disk is checked; the "latest" field may carry the same name from the catalog. + if [[ $BODY != *"\"name\":\"$F\""* && $BODY != *"\"installed\":\"$F\""* ]]; then ok "silinen dosya listede yok / deleted file gone"; else bad "silinen dosya hâlâ listede / still listed: $F"; fi check ".sha256 de silindi / .sha256 removed too" test "$(docker exec "$NAME" sh -c 'ls /library/zims/content | grep -c sha256 || true')" = 0 check "Kiwix kataloğundan çıktı / removed from the Kiwix catalog" catalog_has no fi From 0139c03dd2888947653cad41b7766579527c41f2 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 05:52:25 +0300 Subject: [PATCH 44/65] ci: run the browser tests in the Docker workflow and reuse the image MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Docker and E2E workflows each built the amd64 image. The E2E jobs now live in the Docker workflow: the amd64 test job saves its image as a short-lived artifact (has-disk-image-amd64, one day) and the seven E2E jobs load it instead of building again. Publishing waits for lint, the image tests and the browser tests. e2e/** is added to the workflow paths; the separate e2e.yml is removed. Docker ve E2E iş akışları amd64 imajını ayrı ayrı derliyordu. E2E işleri artık Docker iş akışında: amd64 test işi imajını kısa ömürlü bir artifact olarak saklıyor (has-disk-image-amd64, bir gün), yedi E2E işi yeniden derlemek yerine onu yüklüyor. Yayın lint, imaj testleri ve tarayıcı testlerini bekliyor. e2e/** iş akışı yollarına eklendi; ayrı e2e.yml kaldırıldı. --- .github/workflows/docker.yml | 109 +++++++++++++++++++++++++++++- .github/workflows/e2e.yml | 126 ----------------------------------- e2e/README.md | 4 +- 3 files changed, 108 insertions(+), 131 deletions(-) delete mode 100644 .github/workflows/e2e.yml diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 1442fc2..8c4a0eb 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,7 +1,9 @@ name: Docker -# Çok mimarili imajı derler, her mimaride dener (docker/test.sh) ve GitHub Container Registry'ye (ghcr.io) gönderir. -# Builds the multi-architecture image, tests it on every platform (docker/test.sh) and pushes it to ghcr.io. +# Çok mimarili imajı derler, her mimaride dener (docker/test.sh), amd64 imajıyla tarayıcı testlerini çalıştırır +# (e2e/) ve GitHub Container Registry'ye (ghcr.io) gönderir. İmaj bir kez derlenir, tarayıcı testleri onu kullanır. +# Builds the multi-architecture image, tests it on every platform (docker/test.sh), runs the browser tests with +# the amd64 image (e2e/) and pushes it to ghcr.io. The image is built once; the browser tests reuse it. # Gönderim yalnız tüm testler geçince ve yalnız ana daldan / sürüm etiketinden. Diğer dallarda ve PR'larda # yalnız derlenir ve denenir (fork'ta çalışırken de). # Pushing happens only after every test passes, and only from the default branch or a version tag. @@ -24,6 +26,7 @@ on: - 'scripts/download-content.sh' - 'scripts/verify-content.sh' - 'www/**' + - 'e2e/**' - '.github/workflows/docker.yml' pull_request: paths: @@ -38,6 +41,7 @@ on: - 'scripts/download-content.sh' - 'scripts/verify-content.sh' - 'www/**' + - 'e2e/**' - '.github/workflows/docker.yml' schedule: - cron: '23 4 * * 1' @@ -133,6 +137,20 @@ jobs: cache-from: type=gha,scope=${{ matrix.scope }} cache-to: type=gha,scope=${{ matrix.scope }},mode=max + # amd64 imajı tarayıcı testlerine artifact olarak geçer; orada yeniden derlenmez. + # The amd64 image is handed to the browser tests as an artifact; it is not built again there. + - name: İmajı sakla / save the image + if: matrix.full && steps.build.outcome == 'success' + run: docker save has-disk:ci | gzip -1 > "$RUNNER_TEMP/has-disk-amd64.tar.gz" + + - name: İmaj artifact'ı / image artifact + if: matrix.full && steps.build.outcome == 'success' + uses: actions/upload-artifact@v7.0.2 + with: + name: has-disk-image-amd64 + path: ${{ runner.temp }}/has-disk-amd64.tar.gz + retention-days: 1 + # İmajın içindeki sürümler ve paket listesi rapora / versions and package list inside the image - name: İmaj bilgisi / image details if: steps.build.outcome == 'success' @@ -185,9 +203,94 @@ jobs: retention-days: 14 if-no-files-found: ignore + # Tarayıcı testleri (Playwright): ana sayfa, okuyucu, acil sayfası ve panel; masaüstü (Chromium, Firefox, + # WebKit) ve telefon/tablet; her Playwright sürümü kendi tarayıcılarıyla (eski telefonlar da bağlanır). + # Browser tests (Playwright): homepage, reader, emergency page and panel; desktop (Chromium, Firefox, WebKit) + # and phones/tablets; every Playwright version brings its own browsers (old phones connect too). + e2e: + name: E2E (${{ matrix.name }}) + needs: test + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # Destek sınırları: işletim sistemi ya da cihaz için son sürümler ve ESR'ler. + # Support limits: the last versions for an OS or a device, and the ESR releases. + include: + # e2e/package-lock.json'daki sürüm / the version in e2e/package-lock.json + - name: latest browsers + slug: latest + # Firefox 140 güncel ESR / Firefox 140 is the current ESR + - name: Chrome 139, Firefox 140 ESR, Safari 26.0 + slug: chrome139 + playwright: 1.54.2 + - name: Chrome 130, Firefox 131, Safari 18.0 + slug: chrome130 + playwright: 1.48.2 + # Chrome 128 macOS 10.15'te son / Chrome 128 is the last one on macOS 10.15 + - name: Chrome 128, Firefox 128 ESR, Safari 18.0 + slug: chrome128 + playwright: 1.46.1 + # Chrome 116 macOS 10.13/10.14'te, Firefox 115 ESR Windows 7/8.1'de son + # Chrome 116 is the last on macOS 10.13/10.14, Firefox 115 ESR the last on Windows 7/8.1 + - name: Chrome 116, Firefox 115 ESR, Safari 17.0 + slug: chrome116 + playwright: 1.37.1 + image: jammy + # Chrome 109 Windows 7/8.1'de, Safari 16 iPhone 8 ve X'te son + # Chrome 109 is the last on Windows 7/8.1, Safari 16 the last on the iPhone 8 and X + - name: Chrome 109, Firefox 107, Safari 16.4 + slug: chrome109 + playwright: 1.29.2 + image: jammy + # Safari 15 iPhone 6s ve 7'de son / Safari 15 is the last on the iPhone 6s and 7 + - name: Chrome 102, Firefox 99, Safari 15.4 + slug: chrome102 + playwright: 1.22.2 + image: focal + steps: + - uses: actions/checkout@v7.0.1 + + # Test işinde derlenen amd64 imajı / the amd64 image built in the test job + - uses: actions/download-artifact@v8.0.2 + with: + name: has-disk-image-amd64 + path: ${{ runner.temp }} + + - name: İmajı yükle / load the image + run: gunzip -c "$RUNNER_TEMP/has-disk-amd64.tar.gz" | docker load + + - name: HAS konteyneri, hesap, iki ZIM / HAS container, account, two ZIMs + run: bash e2e/prepare.sh has-disk:ci + + - name: Sürüm / version + id: ver + env: + VERSION: ${{ matrix.playwright }} + run: echo "playwright=${VERSION:-$(node -p "require('./e2e/package-lock.json').packages['node_modules/@playwright/test'].version")}" >> "$GITHUB_OUTPUT" + + - name: Playwright ${{ steps.ver.outputs.playwright }} + env: + CI: '1' + VERSION: ${{ steps.ver.outputs.playwright }} + FLAVOR: ${{ matrix.image || 'noble' }} + run: bash e2e/run.sh "$VERSION" "$FLAVOR" + + - name: Rapor / report + if: always() + uses: actions/upload-artifact@v7.0.2 + with: + name: e2e-${{ matrix.slug }}-playwright${{ steps.ver.outputs.playwright }}-${{ matrix.image || 'noble' }} + path: | + e2e/playwright-report/ + e2e/test-results/ + retention-days: 14 + if-no-files-found: ignore + publish: name: Yayımla / publish - needs: [lint, test] + needs: [lint, test, e2e] if: >- github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml deleted file mode 100644 index f201e25..0000000 --- a/.github/workflows/e2e.yml +++ /dev/null @@ -1,126 +0,0 @@ -name: E2E - -# Tarayıcı testleri (Playwright): Docker imajı açılır, ana sayfa, okuyucu, acil sayfası ve yönetim paneli -# masaüstünde (Chromium, Firefox, WebKit) ve telefon/tabletlerde (Pixel, Galaxy, iPhone SE, büyük iPhone, -# iPad, Android'de Firefox) denenir. Her Playwright sürümü kendi tarayıcılarıyla gelir; eski sürümler hâlâ -# kullanılan eski tarayıcıları dener (afette eski telefonlar da bağlanır). -# Browser tests (Playwright): the Docker image is started and the homepage, reader, emergency page and admin -# panel are tested on desktop (Chromium, Firefox, WebKit) and on phones/tablets (Pixel, Galaxy, iPhone SE, -# a large iPhone, iPad, Firefox on Android). Every Playwright version ships its own browsers; the older ones -# test older browsers people still use (old phones connect to the box in a disaster too). - -on: - push: - branches: ['**'] - paths: - - 'docker/**' - - 'admin/**' - - 'www/**' - - 'scripts/**' - - 'config/**' - - 'e2e/**' - - '.github/workflows/e2e.yml' - pull_request: - paths: - - 'docker/**' - - 'admin/**' - - 'www/**' - - 'scripts/**' - - 'config/**' - - 'e2e/**' - - '.github/workflows/e2e.yml' - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: e2e-${{ github.ref }} - cancel-in-progress: true - -jobs: - e2e: - name: E2E (${{ matrix.name }}) - runs-on: ubuntu-latest - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - # Destek sınırları: işletim sistemi ya da cihaz için son sürümler ve ESR'ler. - # Support limits: the last versions for an OS or a device, and the ESR releases. - include: - # e2e/package-lock.json'daki sürüm / the version in e2e/package-lock.json - - name: latest browsers - slug: latest - # Firefox 140 güncel ESR / Firefox 140 is the current ESR - - name: Chrome 139, Firefox 140 ESR, Safari 26.0 - slug: chrome139 - playwright: 1.54.2 - - name: Chrome 130, Firefox 131, Safari 18.0 - slug: chrome130 - playwright: 1.48.2 - # Chrome 128 macOS 10.15'te son / Chrome 128 is the last one on macOS 10.15 - - name: Chrome 128, Firefox 128 ESR, Safari 18.0 - slug: chrome128 - playwright: 1.46.1 - # Chrome 116 macOS 10.13/10.14'te, Firefox 115 ESR Windows 7/8.1'de son - # Chrome 116 is the last on macOS 10.13/10.14, Firefox 115 ESR the last on Windows 7/8.1 - - name: Chrome 116, Firefox 115 ESR, Safari 17.0 - slug: chrome116 - playwright: 1.37.1 - image: jammy - # Chrome 109 Windows 7/8.1'de, Safari 16 iPhone 8 ve X'te son - # Chrome 109 is the last on Windows 7/8.1, Safari 16 the last on the iPhone 8 and X - - name: Chrome 109, Firefox 107, Safari 16.4 - slug: chrome109 - playwright: 1.29.2 - image: jammy - # Safari 15 iPhone 6s ve 7'de son / Safari 15 is the last on the iPhone 6s and 7 - - name: Chrome 102, Firefox 99, Safari 15.4 - slug: chrome102 - playwright: 1.22.2 - image: focal - steps: - - uses: actions/checkout@v7.0.1 - - - uses: docker/setup-buildx-action@v4.4.1 - - # Docker iş akışının amd64 önbelleği kullanılır / uses the amd64 cache of the Docker workflow - - name: İmaj / image - uses: docker/build-push-action@v7.4.0 - env: - DOCKER_BUILD_RECORD_UPLOAD: 'false' - with: - context: . - file: docker/Dockerfile - platforms: linux/amd64 - load: true - tags: has-disk:e2e - cache-from: type=gha,scope=amd64 - - - name: HAS konteyneri, hesap, iki ZIM / HAS container, account, two ZIMs - run: bash e2e/prepare.sh has-disk:e2e - - - name: Sürüm / version - id: ver - env: - VERSION: ${{ matrix.playwright }} - run: echo "playwright=${VERSION:-$(node -p "require('./e2e/package-lock.json').packages['node_modules/@playwright/test'].version")}" >> "$GITHUB_OUTPUT" - - - name: Playwright ${{ steps.ver.outputs.playwright }} - env: - CI: '1' - VERSION: ${{ steps.ver.outputs.playwright }} - FLAVOR: ${{ matrix.image || 'noble' }} - run: bash e2e/run.sh "$VERSION" "$FLAVOR" - - - name: Rapor / report - if: always() - uses: actions/upload-artifact@v7.0.2 - with: - name: e2e-${{ matrix.slug }}-playwright${{ steps.ver.outputs.playwright }}-${{ matrix.image || 'noble' }} - path: | - e2e/playwright-report/ - e2e/test-results/ - retention-days: 14 - if-no-files-found: ignore diff --git a/e2e/README.md b/e2e/README.md index 9966463..b39297a 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -6,7 +6,7 @@ Docker imajını açıp ana sayfayı, HAS okuyucusunu, acil sayfasını ve yöne **Cihazlar** (`playwright.config.js`): masaüstünde Chromium, Firefox, WebKit; Android telefon (Pixel, Galaxy S9+) ve tablet (Galaxy Tab S4); iPhone SE (320 px, en dar ekran), büyük iPhone, iPad Mini; Android'de Firefox (telefon genişliği). -**Tarayıcı sürümleri** (`.github/workflows/e2e.yml`): her Playwright sürümü kendi tarayıcılarıyla gelir. En güncel sürümün yanında eski sürümler de çalışır: Chrome 139 / Firefox 140 ESR / Safari 26, Chrome 130 / Firefox 131 / Safari 18, Chrome 128 / Firefox 128 ESR, Chrome 116 / Firefox 115 ESR / Safari 17, Chrome 109 / Firefox 107 / Safari 16.4, Chrome 102 / Firefox 99 / Safari 15.4 (iPhone 6s ve 7'nin son Safari'si). Eski sürümler aynı `package.json`'da takma adla kilitli (`"playwright-1.22.2": "npm:@playwright/test@1.22.2"`); `run.sh` o klasörü imajda `@playwright/test`'in yerine bağlar. +**Tarayıcı sürümleri** (`.github/workflows/docker.yml`, `e2e` işi; Docker testlerinde derlenen amd64 imajını kullanır): her Playwright sürümü kendi tarayıcılarıyla gelir. En güncel sürümün yanında eski sürümler de çalışır: Chrome 139 / Firefox 140 ESR / Safari 26, Chrome 130 / Firefox 131 / Safari 18, Chrome 128 / Firefox 128 ESR, Chrome 116 / Firefox 115 ESR / Safari 17, Chrome 109 / Firefox 107 / Safari 16.4, Chrome 102 / Firefox 99 / Safari 15.4 (iPhone 6s ve 7'nin son Safari'si). Eski sürümler aynı `package.json`'da takma adla kilitli (`"playwright-1.22.2": "npm:@playwright/test@1.22.2"`); `run.sh` o klasörü imajda `@playwright/test`'in yerine bağlar. **Neler deneniyor:** sayfalar açılıyor ve telefonda yatay taşmıyor, betik hatası yok; menü kurulu servislere göre; arama ve kitap bağlantıları okuyucuda açılıyor; okuyucuda içerikteki bağlantılar tıklanıyor, kaynaklar arası geçiş, arama, rastgele sayfa, dil, tema, kitaplık sayfası ve oradan kitap açma; panelde arayüzden giriş/çıkış, hata metninin seçili dilde görünmesi, dile göre gruplu içerik, grup seçimi ve gruplar arası seçim, seçimin yenilemede kalması, seçili doğrulama, silme onayı penceresi, tema. @@ -26,7 +26,7 @@ Starts the Docker image and tests the homepage, the HAS reader, the emergency pa **Devices** (`playwright.config.js`): Chromium, Firefox and WebKit on desktop; Android phones (Pixel, Galaxy S9+) and a tablet (Galaxy Tab S4); iPhone SE (320 px, the narrowest screen), a large iPhone, iPad Mini; Firefox on Android (phone width). -**Browser versions** (`.github/workflows/e2e.yml`): every Playwright version ships its own browsers. Next to the latest, older versions run too: Chrome 139 / Firefox 140 ESR / Safari 26, Chrome 130 / Firefox 131 / Safari 18, Chrome 128 / Firefox 128 ESR, Chrome 116 / Firefox 115 ESR / Safari 17, Chrome 109 / Firefox 107 / Safari 16.4, Chrome 102 / Firefox 99 / Safari 15.4 (the last Safari on the iPhone 6s and 7). The older versions are locked in the same `package.json` under an alias (`"playwright-1.22.2": "npm:@playwright/test@1.22.2"`); `run.sh` mounts that folder over `@playwright/test` inside the image. +**Browser versions** (`.github/workflows/docker.yml`, the `e2e` job; it reuses the amd64 image built by the Docker tests): every Playwright version ships its own browsers. Next to the latest, older versions run too: Chrome 139 / Firefox 140 ESR / Safari 26, Chrome 130 / Firefox 131 / Safari 18, Chrome 128 / Firefox 128 ESR, Chrome 116 / Firefox 115 ESR / Safari 17, Chrome 109 / Firefox 107 / Safari 16.4, Chrome 102 / Firefox 99 / Safari 15.4 (the last Safari on the iPhone 6s and 7). The older versions are locked in the same `package.json` under an alias (`"playwright-1.22.2": "npm:@playwright/test@1.22.2"`); `run.sh` mounts that folder over `@playwright/test` inside the image. **What is tested:** pages open without horizontal overflow on phones and without script errors; the menu follows the installed services; search and book links open in the reader; in the reader, links inside the content, switching sources, search, random page, language, theme, the library page and opening a book from it; in the panel, logging in and out through the page, error text in the selected language, content grouped by language, group selection and selection across groups, the selection surviving a refresh, verifying the selection, the delete confirmation dialog, theme. From 7d5b67b10a8375ff27e897f659a43f9b1c19dcab Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 18:27:20 +0300 Subject: [PATCH 45/65] perf(docker): send precompressed pages with gzip_static MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nginx compressed the pages and has.js again on every request. install-homepage.sh now writes a .gz copy next to each page when HAS_GZIP=1 (set by the Docker entrypoint) and nginx sends it with gzip_static on. The copies are rewritten on every install, so no stale copy is left; json files and Kiwix are still compressed on the fly. On the Pi (IIAB nginx) nothing changes: without HAS_GZIP the script only removes old copies. Measured with wrk (HTTP/1.1, 50 connections, Accept-Encoding: gzip) in Docker, not on a Pi, before → after, requests/s: - 1 core: homepage ~960 → ~21,000, has.js ~1,720 → ~30,350, reader ~2,000 → ~28,000, emergency page ~1,790 → ~28,800. - 4 cores: homepage ~3,800 → ~107,000, has.js ~6,900 → ~125,600. gzip -9 copies are slightly smaller than nginx level 5 (homepage 10,151 → 10,127 bytes). The earlier ab numbers were uncompressed: ab speaks HTTP/1.0 and nginx only compresses HTTP/1.1 by default (gzip_http_version), so wrk is used for this one. test.sh: index.html.gz exists, every page unpacks to the same bytes as the plain page, Vary: Accept-Encoding is sent. 152/152 locally; ETag and 304 work with the .gz copy. nginx sayfaları ve has.js'i her istekte yeniden sıkıştırıyordu. install-homepage.sh artık HAS_GZIP=1 olduğunda (Docker başlangıcı verir) her sayfanın yanına .gz kopyası yazıyor, nginx gzip_static ile onu gönderiyor. Kopyalar her kurulumda yeniden yazılır, eski kopya kalmaz; json dosyaları ve Kiwix yine anında sıkıştırılır. Pi'de (IIAB nginx) değişiklik yok: HAS_GZIP olmadan betik yalnız eski kopyaları siler. Docker'da wrk ile ölçüldü (HTTP/1.1, 50 bağlantı, Accept-Encoding: gzip), Pi değil, önce → sonra, istek/sn: - 1 çekirdek: ana sayfa ~960 → ~21.000, has.js ~1.720 → ~30.350, okuyucu ~2.000 → ~28.000, acil sayfası ~1.790 → ~28.800. - 4 çekirdek: ana sayfa ~3.800 → ~107.000, has.js ~6.900 → ~125.600. gzip -9 kopyaları nginx'in 5. düzeyinden biraz küçük (ana sayfa 10.151 → 10.127 bayt). Önceki ab ölçümleri sıkıştırmasızdı: ab HTTP/1.0 konuşuyor, nginx varsayılan olarak yalnız HTTP/1.1'i sıkıştırıyor (gzip_http_version); bu ölçümde wrk kullanıldı. test.sh: index.html.gz var, her sayfa açılınca düz sayfayla aynı, Vary: Accept-Encoding gönderiliyor. Yerelde 152/152; ETag ve 304 .gz kopyasıyla çalışıyor. --- docker/entrypoint.sh | 3 ++- docker/nginx.conf | 5 +++++ docker/test.sh | 8 ++++++++ scripts/install-homepage.sh | 8 ++++++++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 7b2aa48..977e34c 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -11,7 +11,8 @@ LIB=/library/zims/library.xml mkdir -p /library/zims/content /library/www/html/home # Ana sayfa her açılışta imajdaki sürümle güncellenir (Pi'de install-homepage.sh'yi elle çalıştırmakla aynı). # The homepage is refreshed from the image on every start (same as running install-homepage.sh on the Pi). -HAS_SIZES=0 /opt/has/scripts/install-homepage.sh >/dev/null # boyutlar arka planda / sizes in the background +# HAS_GZIP=1: sayfaların .gz kopyaları (nginx gzip_static) / .gz copies of the pages (nginx gzip_static) +HAS_GZIP=1 HAS_SIZES=0 /opt/has/scripts/install-homepage.sh >/dev/null # boyutlar arka planda / sizes in the background # Disk sağlığı (dolu, salt okunur, dosya sistemi hatası) ana sayfadaki uyarı için disk.json'a; Pi'deki # has-disk-health.timer gibi açılışta ve 6 saatte bir. / Disk health (full, read-only, filesystem errors) goes to # disk.json for the homepage warning; at start and every 6 hours, like has-disk-health.timer on the Pi. diff --git a/docker/nginx.conf b/docker/nginx.conf index c3043e5..bab11e5 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -26,6 +26,11 @@ http { # Sıkıştırma: sayfalar ve has.js yaklaşık üçte bire iner (zayıf Wi-Fi, çok bağlantı). # Compression: pages and has.js shrink to about a third (weak Wi-Fi, many clients). gzip on; + # Sayfalar ve has.js için install-homepage.sh'nin yazdığı .gz kopyası gönderilir (her istekte sıkıştırma yok; + # 1 çekirdekte ana sayfa ~1.000 → ~21.000 istek/sn). Kopyası olmayan (json, Kiwix) anında sıkıştırılır. + # For pages and has.js the .gz copy written by install-homepage.sh is sent (no compression per request; + # homepage on 1 core ~1,000 → ~21,000 req/s). Files without a copy (json, Kiwix) are compressed on the fly. + gzip_static on; gzip_comp_level 5; gzip_min_length 1024; gzip_vary on; diff --git a/docker/test.sh b/docker/test.sh index d1f9b05..962053d 100755 --- a/docker/test.sh +++ b/docker/test.sh @@ -214,6 +214,14 @@ check "disk.json: disk sağlığı yazıldı / disk health written" has "$(curl gz() { local h; h=$(curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' "$BASE$1"); has "$h" '^content-encoding: gzip'; } check "gzip: ana sayfa / homepage" gz /home/ check "gzip: has.js" gz /home/has.js +# gzip_static: install-homepage.sh .gz kopyalarını yazar; açılmış hâli sayfanın kendisiyle aynı olmalı (eski kopya kalmamalı). +# gzip_static: install-homepage.sh writes the .gz copies; unpacked they must equal the page itself (no stale copy). +check "gzip_static: .gz kopyası / copy: index.html.gz" exists /library/www/html/home/index.html.gz +gz_same() { local a b; a=$(curl -s "$BASE$1" | sha256sum); b=$(curl -s --compressed "$BASE$1" | sha256sum); [ "$a" = "$b" ]; } +for p in /home/ /home/has.js /home/acil.html /home/oku.html; do + check "gzip_static: açılınca aynı / unpacks to the same page: $p" gz_same "$p" +done +check "gzip: Vary: Accept-Encoding" has "$(curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' "$BASE/home/has.js")" '^vary: accept-encoding' check "services.json JSON türünde / served as JSON" has "$(curl -sI "$BASE/home/services.json")" '^content-type: application/json' ahdr=$(curl -sI "$BASE/admin/") check "panel: X-Frame-Options DENY" has "$ahdr" '^x-frame-options: deny' diff --git a/scripts/install-homepage.sh b/scripts/install-homepage.sh index ce5312e..f2716d9 100755 --- a/scripts/install-homepage.sh +++ b/scripts/install-homepage.sh @@ -15,6 +15,14 @@ fi # www/home altındaki tüm sayfalar (ana sayfa, acil, okuyucu) ve ortak betik (has.js: tema, metinler) # every page under www/home (home, emergency, reader) and the shared script (has.js: theme, texts) cp "$SRC"/*.html "$SRC"/*.js "$DST/" +# HAS_GZIP=1 (Docker): sayfaların önceden sıkıştırılmış kopyaları (.gz); nginx gzip_static her istekte yeniden +# sıkıştırmak yerine bunları gönderir. Her kurulumda yeniden yazılır, eski kopya kalmaz. Pi'de (IIAB nginx) kapalı. +# HAS_GZIP=1 (Docker): precompressed copies (.gz) of the pages; nginx gzip_static sends them instead of compressing +# on every request. Rewritten on every install, so no stale copy is left. Off on the Pi (IIAB nginx). +for f in "$SRC"/*.html "$SRC"/*.js; do + f="$DST/$(basename "$f")" + if [ "${HAS_GZIP:-0}" = 1 ]; then gzip -9 -c "$f" >"$f.gz" && touch -r "$f" "$f.gz"; else rm -f "$f.gz"; fi +done # Ana sayfa yalnız kurulu servisleri (harita, Kolibri, yönetim) gösterir / the homepage only lists installed services "$(dirname "$0")/services.sh" # Boyutlar: hiç internet görmemiş kutuda da görünsün diye repodaki liste (config/sizes.json) başlangıç olarak From 7a58325b6321a38c1a28cb96db9a7ed646b513b4 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 18:32:04 +0300 Subject: [PATCH 46/65] docs: add CONTRIBUTING with adding content, services, code style and tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit .editorconfig already pointed to CONTRIBUTING.md, which did not exist. It covers: - adding a ZIM: the content.conf line, the homepage CATS item (zim is matched as a prefix), regenerating config/sizes.json with catalog-sizes.sh, the texts in has.js; - adding a service module in scripts/services.d (check, size, typical, data-service); - code style: EditorConfig, Prettier 3.10.0 for JS/JSON/YAML, HTML by hand with no outside resources and support down to Chrome 102 / Firefox 99 / Safari 15.4, ShellCheck 0.10.0, no "| grep -q" under pipefail, Go standard library with vet/test, comments in Turkish and English, commit messages; - running docker/test.sh and the browser tests. README's repo layout lists it. .editorconfig CONTRIBUTING.md'yi gösteriyordu ama dosya yoktu. İçerik: - ZIM ekleme: content.conf satırı, ana sayfadaki CATS öğesi (zim ön ek olarak eşlenir), catalog-sizes.sh ile config/sizes.json'u yeniden üretme, has.js'teki metinler; - scripts/services.d'ye servis modülü ekleme (check, size, typical, data-service); - kod biçimi: EditorConfig, JS/JSON/YAML için Prettier 3.10.0, HTML elle, dışarıdan kaynak yok, Chrome 102 / Firefox 99 / Safari 15.4'e kadar destek, ShellCheck 0.10.0, pipefail altında "| grep -q" yok, Go'da standart kitaplık + vet/test, yorumlar Türkçe ve İngilizce, commit mesajları; - docker/test.sh ve tarayıcı testlerini çalıştırma. README'deki repo yapısında yer alıyor. --- CONTRIBUTING.md | 186 ++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 2 + 2 files changed, 188 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..725685f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,186 @@ +# Katkı / Contributing + +- [English](#english): [adding content](#adding-content-zim), [adding a service](#adding-a-service), [code style](#code-style), [tests](#tests) +- [Türkçe](#türkçe): [içerik ekleme](#zim-içerik-ekleme), [servis ekleme](#servis-ekleme), [kod biçimi](#kod-biçimi), [testler](#testler) + +## English + +Before starting, write "I'm taking this" under the issue so two people do not work on the same thing. Keep pull +requests small and about one topic. + +### Adding content (ZIM) + +1. **Find the name.** Look the file up in the Kiwix catalog ( or + ). The *prefix* is the file name without the date: `wikibooks_tr_all_maxi_2026-09.zim` + → `wikibooks_tr_all_maxi`. The *folder* is the directory under `download.kiwix.org/zim/` (`wikibooks`, `other`, + `zimit`, `stack_exchange`, ...). +2. **`config/content.conf`:** add one line, ` # Turkish note / English note`. + `scripts/download-content.sh` downloads the newest version of every line, on the Pi and in Docker alike. The + note after `#` is shown in the admin panel; the panel groups by the language code in the prefix (`_tr_`, `_en_`, + `_mul_`). A line that starts with `#` is skipped: put large or optional content there. + The default list should only contain content that allows commercial use; NC-licensed content goes in as a + commented-out line. +3. **Homepage, `www/home/index.html`:** add an item to the right category in `CATS`: + + ```js + { name:{tr:"Vikikitap", en:"Wikibooks (Turkish)"}, desc:{tr:"Açık ders kitapları.", en:"Open textbooks."}, + lang:"TR", size:"~27 MB", zim:"wikibooks_tr_all" }, + ``` + + `zim` is matched as a prefix (an installed `wikibooks_tr_all_maxi_2026-09.zim` matches `wikibooks_tr_all`). + `name` and `desc` take `{tr, en}`, or a plain string when the name is the same in both. `size` is only a fallback: + the exact size comes from `sizes.json` (next step), the size of an installed file from the disk. +4. **Sizes, `config/sizes.json`:** regenerate the starter list so a box that has never been online shows the new size: + + ```sh + SIZES_OUT=config/sizes.json scripts/catalog-sizes.sh # needs internet, fetches the 4.4 MB Kiwix catalog + ``` + + The Docker build does this by itself; online, the box refreshes it at install, after downloads and (in Docker) + every 6 hours. The file is + generated, so Prettier skips it. Regenerate it now and then even without new content: sizes change with every + Kiwix release. +5. **Texts:** labels for buttons and messages live in `www/home/has.js` (`TEXT[section][tr|en]`; a key missing in + another language falls back to Turkish). The panel's error codes must exist in both languages; `go test` checks it. +6. **Check:** build the image, run `docker/test.sh` (see [tests](#tests)), open `/admin` and see the new line in the + content list. + +Vital information (first aid, the emergency page) must match its source word for word; give the source in the commit. + +### Adding a service + +Map, Kolibri and the panel are modules: one file per service in `scripts/services.d/.sh`. +`scripts/services.sh` runs them (at install, on every container start) and writes `services.json`, which the homepage +and the panel read. + +```sh +# shellcheck shell=bash disable=SC2034 # sourced by services.sh +label_tr="Harita"; label_en="Map"; url="/maps" +check(){ [ -f /library/www/maps/index.html ]; } # 0 when installed +size(){ du -sbL /library/www/maps | cut -f1; } # optional: bytes on disk when installed +typical=178257920 # optional: approximate bytes when not installed (give the source) +``` + +`check` and `size` run on every start: keep them fast and offline. On the homepage, a `CATS` item with +`url:"/maps", service:"maps"` turns on when the service is installed; a top menu link uses +`data-service="maps"` (several names: the first installed one wins). Example: `scripts/services.d/maps.sh`. + +### Code style + +- **All files:** `.editorconfig` (UTF-8, LF, final newline, two-space indent; tabs in Go). +- **Comments and messages:** every comment has a Turkish and an English line; text the user sees exists in both + languages. +- **JavaScript, JSON, YAML:** Prettier 3.10.0 with `.prettierrc.json` (120 columns, single quotes under `e2e/`): + `npx prettier@3.10.0 --check .` +- **HTML pages** (`www/home/`, `admin/web/`) are kept by hand (inline script and style, `.prettierignore`). They must + not load anything from outside (scripts, styles, fonts): there is no internet in a disaster, and `docker/test.sh` + checks it. They must keep working in the oldest browsers the tests cover (Chrome 102, Firefox 99, Safari 15.4). +- **Shell:** bash with `set -euo pipefail` (or `-uo` where the script handles errors itself), clean under + ShellCheck 0.10.0 `--severity=warning`. Under `pipefail` do not write `cmd | grep -q`: grep exiting early kills + the left side with SIGPIPE and the check fails at random; capture the output first. Anything downloaded is pinned + to a version and a SHA-256. +- **Go** (`admin/`): standard library only, `gofmt`, `go vet ./...`, `go test ./...` (the Docker build runs both). +- **Commits:** a short English subject, preferably in the Conventional Commits form (`feat:`, `fix:`, `docs:`, + `perf:`, `ci:`, ...); the body says why, in English and then Turkish. Measured changes carry the numbers. + +### Tests + +```sh +docker build -f docker/Dockerfile -t has-disk:test . +docker/test.sh has-disk:test # homepage, Kiwix, panel, persistence, security +docker/test.sh has-disk:test --download # also downloads a real ZIM through the panel (~15 MB, internet) +docker/test.sh has-disk:test --platform linux/arm/v7 # another architecture, through QEMU +``` + +Browser tests: [e2e/README.md](e2e/README.md). On every push `.github/workflows/docker.yml` builds the image for five +architectures, runs `docker/test.sh` on each and the browser tests on seven browser versions. + +## Türkçe + +İşe başlamadan issue'nun altına "bunu ben alıyorum" yaz, iki kişi aynı işi yapmasın. PR'lar küçük ve tek konulu +olsun. + +### ZIM içerik ekleme + +1. **Adı bul.** Dosyayı Kiwix kataloğunda bul ( ya da ). + *Ön ek*, dosya adının tarihsiz kısmıdır: `wikibooks_tr_all_maxi_2026-09.zim` → `wikibooks_tr_all_maxi`. + *Klasör*, `download.kiwix.org/zim/` altındaki dizindir (`wikibooks`, `other`, `zimit`, `stack_exchange`, ...). +2. **`config/content.conf`:** bir satır ekle: ` <ön ek> # Türkçe not / English note`. + `scripts/download-content.sh` her satırın en yeni sürümünü indirir; Pi'de de Docker'da da aynı. `#` sonrasındaki + not yönetim panelinde görünür; panel ön ekteki dil koduna göre gruplar (`_tr_`, `_en_`, `_mul_`). `#` ile başlayan + satır atlanır: büyük ya da isteğe bağlı içerik böyle girer. + Varsayılan listede yalnız ticari kullanıma açık lisanslı içerik olsun; NC lisanslı içerik yorum satırı olarak + girer. +3. **Ana sayfa, `www/home/index.html`:** `CATS` içinde doğru kategoriye bir öğe ekle: + + ```js + { name:{tr:"Vikikitap", en:"Wikibooks (Turkish)"}, desc:{tr:"Açık ders kitapları.", en:"Open textbooks."}, + lang:"TR", size:"~27 MB", zim:"wikibooks_tr_all" }, + ``` + + `zim` ön ek olarak eşlenir (kurulu `wikibooks_tr_all_maxi_2026-09.zim`, `wikibooks_tr_all` ile eşleşir). + `name` ve `desc` `{tr, en}` alır; ad iki dilde aynıysa düz metin de olur. `size` yalnız yedektir: kesin boyut + `sizes.json`'dan (sonraki adım), kurulu dosyanın boyutu diskten gelir. +4. **Boyutlar, `config/sizes.json`:** hiç internet görmemiş kutuda da yeni boyut görünsün diye başlangıç listesini + yeniden üret: + + ```sh + SIZES_OUT=config/sizes.json scripts/catalog-sizes.sh # internet ister, 4,4 MB'lık Kiwix kataloğunu indirir + ``` + + Docker derlemesi bunu kendisi yapar; internet varsa kutu kurulumda, indirmeden sonra ve (Docker'da) 6 saatte + bir tazeler. Dosya betikle + üretildiği için Prettier ona dokunmaz. Yeni içerik olmasa da ara sıra yeniden üret: boyutlar her Kiwix sürümüyle + değişir. +5. **Metinler:** düğme ve mesaj metinleri `www/home/has.js`'de (`TEXT[bölüm][tr|en]`; başka dilde eksik anahtar + Türkçeden gelir). Panelin hata kodları iki dilde de olmalı; `go test` buna bakar. +6. **Dene:** imajı derle, `docker/test.sh`'yi çalıştır ([testler](#testler)), `/admin`'i aç ve yeni satırı içerik + listesinde gör. + +Hayati bilgi (ilk yardım, acil sayfası) kaynağıyla birebir olmalı; kaynağı commit'te ver. + +### Servis ekleme + +Harita, Kolibri ve panel birer modül: her servis için `scripts/services.d/.sh` dosyası. `scripts/services.sh` +bunları çalıştırır (kurulumda, her konteyner açılışında) ve ana sayfayla panelin okuduğu `services.json`'u yazar. + +```sh +# shellcheck shell=bash disable=SC2034 # services.sh içine alınır +label_tr="Harita"; label_en="Map"; url="/maps" +check(){ [ -f /library/www/maps/index.html ]; } # kuruluysa 0 +size(){ du -sbL /library/www/maps | cut -f1; } # isteğe bağlı: kuruluysa diskteki bayt +typical=178257920 # isteğe bağlı: kurulu değilken yaklaşık bayt (kaynağını yaz) +``` + +`check` ve `size` her açılışta çalışır: hızlı ve internetsiz olsun. Ana sayfada `url:"/maps", service:"maps"` olan +`CATS` öğesi servis kurulunca açılır; üst menü bağlantısı `data-service="maps"` kullanır (birden çok ad: ilk kurulu +olan). Örnek: `scripts/services.d/maps.sh`. + +### Kod biçimi + +- **Tüm dosyalar:** `.editorconfig` (UTF-8, LF, dosya sonu satırı, iki boşluk girinti; Go'da sekme). +- **Yorumlar ve mesajlar:** her yorumun bir Türkçe, bir İngilizce satırı var; kullanıcının gördüğü metin iki dilde. +- **JavaScript, JSON, YAML:** Prettier 3.10.0, `.prettierrc.json` ile (120 sütun, `e2e/` altında tek tırnak): + `npx prettier@3.10.0 --check .` +- **HTML sayfaları** (`www/home/`, `admin/web/`) elle düzenlenir (satır içi betik ve stil, `.prettierignore`). + Dışarıdan hiçbir şey (betik, stil, yazı tipi) yüklememeli: afette internet yok, `docker/test.sh` buna bakar. + Testlerin kapsadığı en eski tarayıcılarda (Chrome 102, Firefox 99, Safari 15.4) çalışmaya devam etmeli. +- **Kabuk:** bash, `set -euo pipefail` (betik hatayı kendisi ele alıyorsa `-uo`), ShellCheck 0.10.0 + `--severity=warning` temiz. `pipefail` altında `komut | grep -q` yazma: grep erken çıkınca soldaki komut SIGPIPE + alır, kontrol rastgele düşer; çıktıyı önce değişkene al. İndirilen her şey sürüme ve SHA-256'ya sabit. +- **Go** (`admin/`): yalnız standart kitaplık, `gofmt`, `go vet ./...`, `go test ./...` (Docker derlemesi ikisini de + çalıştırır). +- **Commit:** kısa İngilizce başlık, tercihen Conventional Commits biçiminde (`feat:`, `fix:`, `docs:`, `perf:`, + `ci:`, ...); gövde nedenini önce İngilizce, sonra Türkçe anlatır. Ölçülen değişiklikte sayılar yazılır. + +### Testler + +```sh +docker build -f docker/Dockerfile -t has-disk:test . +docker/test.sh has-disk:test # ana sayfa, Kiwix, panel, kalıcılık, güvenlik +docker/test.sh has-disk:test --download # panelden gerçek bir ZIM de indirir (~15 MB, internet) +docker/test.sh has-disk:test --platform linux/arm/v7 # başka mimari, QEMU ile +``` + +Tarayıcı testleri: [e2e/README.md](e2e/README.md). Her push'ta `.github/workflows/docker.yml` imajı beş mimari için +derler, her birinde `docker/test.sh`'yi, yedi tarayıcı sürümünde tarayıcı testlerini çalıştırır. diff --git a/README.md b/README.md index 327fdc4..3961dbc 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,7 @@ config/iiab-overrides.yml Internet-in-a-Box settings config/content.conf list of content to download www/home/index.html homepage www/home/acil.html emergency page (Turkish, sourced from AFAD and EPA) +CONTRIBUTING.md adding content or a service, code style, tests ``` ### Troubleshooting @@ -290,6 +291,7 @@ config/iiab-overrides.yml Internet-in-a-Box ayarları config/content.conf indirilecek içerik listesi www/home/index.html ana sayfa www/home/acil.html acil durum sayfası (AFAD ve EPA kaynaklı) +CONTRIBUTING.md içerik/servis ekleme, kod biçimi, testler ``` ### Sorun giderme From 06ef8b0e269f34ae1f5d76aa22b208465d95cbff Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 18:48:39 +0300 Subject: [PATCH 47/65] style: format the Docker workflow and the Prettier settings with Prettier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CONTRIBUTING says `npx prettier@3.10.0 --check .` passes; it did not for these two files. Only quotes and the overrides line change (single → double quotes in docker.yml). actionlint is clean. CONTRIBUTING `npx prettier@3.10.0 --check .` geçer diyor; bu iki dosyada geçmiyordu. Yalnız tırnaklar ve overrides satırı değişti (docker.yml'de tek → çift tırnak). actionlint temiz. --- .github/workflows/docker.yml | 68 ++++++++++++++++++------------------ .prettierrc.json | 4 +-- 2 files changed, 35 insertions(+), 37 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 8c4a0eb..055495e 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -12,39 +12,39 @@ name: Docker on: push: - branches: ['**'] - tags: ['v*'] + branches: ["**"] + tags: ["v*"] paths: - - 'docker/**' - - 'admin/**' - - 'scripts/services.sh' - - 'scripts/services.d/**' - - 'scripts/install-homepage.sh' - - 'compose.yaml' - - '.dockerignore' - - 'config/**' - - 'scripts/download-content.sh' - - 'scripts/verify-content.sh' - - 'www/**' - - 'e2e/**' - - '.github/workflows/docker.yml' + - "docker/**" + - "admin/**" + - "scripts/services.sh" + - "scripts/services.d/**" + - "scripts/install-homepage.sh" + - "compose.yaml" + - ".dockerignore" + - "config/**" + - "scripts/download-content.sh" + - "scripts/verify-content.sh" + - "www/**" + - "e2e/**" + - ".github/workflows/docker.yml" pull_request: paths: - - 'docker/**' - - 'admin/**' - - 'scripts/services.sh' - - 'scripts/services.d/**' - - 'scripts/install-homepage.sh' - - 'compose.yaml' - - '.dockerignore' - - 'config/**' - - 'scripts/download-content.sh' - - 'scripts/verify-content.sh' - - 'www/**' - - 'e2e/**' - - '.github/workflows/docker.yml' + - "docker/**" + - "admin/**" + - "scripts/services.sh" + - "scripts/services.d/**" + - "scripts/install-homepage.sh" + - "compose.yaml" + - ".dockerignore" + - "config/**" + - "scripts/download-content.sh" + - "scripts/verify-content.sh" + - "www/**" + - "e2e/**" + - ".github/workflows/docker.yml" schedule: - - cron: '23 4 * * 1' + - cron: "23 4 * * 1" workflow_dispatch: permissions: @@ -87,7 +87,7 @@ jobs: # kapatıyor (actions/runner-images#14790, moby/profiles#21; 29.4.3'te düzeldi). 24.04'te Docker 28.0.4. # 386 on ubuntu-24.04: ubuntu-latest (26.04) ships Docker 29.4.2, which blocks socketcall on 32-bit x86 # (actions/runner-images#14790, moby/profiles#21; fixed in 29.4.3). 24.04 has Docker 28.0.4. - - { platform: linux/386, scope: '386', runner: ubuntu-24.04, qemu: false, full: false } + - { platform: linux/386, scope: "386", runner: ubuntu-24.04, qemu: false, full: false } steps: - uses: actions/checkout@v7.0.1 @@ -126,7 +126,7 @@ jobs: env: # Adı okunmayan .dockerbuild kayıtları yüklenmesin; özet yine yazılır. # Do not upload the opaque .dockerbuild records; the summary is still written. - DOCKER_BUILD_RECORD_UPLOAD: 'false' + DOCKER_BUILD_RECORD_UPLOAD: "false" with: context: . file: docker/Dockerfile @@ -170,7 +170,7 @@ jobs: - name: İmaj testi / image test env: - HAS_TEST_TIMEOUT: '600' + HAS_TEST_TIMEOUT: "600" HAS_TEST_LOGS: ${{ runner.temp }}/report/container.log PLATFORM: ${{ matrix.platform }} DOWNLOAD: ${{ matrix.full && '1' || '' }} @@ -272,7 +272,7 @@ jobs: - name: Playwright ${{ steps.ver.outputs.playwright }} env: - CI: '1' + CI: "1" VERSION: ${{ steps.ver.outputs.playwright }} FLAVOR: ${{ matrix.image || 'noble' }} run: bash e2e/run.sh "$VERSION" "$FLAVOR" @@ -330,7 +330,7 @@ jobs: - name: Tüm mimariler / all platforms uses: docker/build-push-action@v7.4.0 env: - DOCKER_BUILD_RECORD_UPLOAD: 'false' + DOCKER_BUILD_RECORD_UPLOAD: "false" with: context: . file: docker/Dockerfile diff --git a/.prettierrc.json b/.prettierrc.json index 4696505..c3f02b8 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,6 +1,4 @@ { "printWidth": 120, - "overrides": [ - { "files": "e2e/**/*.js", "options": { "singleQuote": true } } - ] + "overrides": [{ "files": "e2e/**/*.js", "options": { "singleQuote": true } }] } From 483477348ff2e5526860c2bb3bd2de25b9d7fbab Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 18:59:53 +0300 Subject: [PATCH 48/65] refactor(home): drop the unused search flag from the content list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The search box used to offer only the items marked search:true. It now lists every installed book, so the flag was no longer read anywhere; it only confused new entries. docker/test.sh --download 177/177, browser tests (desktop Chromium) 40/40. Arama kutusu eskiden yalnız search:true işaretli öğeleri gösteriyordu. Artık kurulu bütün kitapları listelediği için işaret hiçbir yerde okunmuyordu; yeni girdilerde yalnız kafa karıştırıyordu. docker/test.sh --download 177/177, tarayıcı testleri (masaüstü Chromium) 40/40. --- www/home/index.html | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/www/home/index.html b/www/home/index.html index dc3e5a4..b76a475 100644 --- a/www/home/index.html +++ b/www/home/index.html @@ -196,39 +196,39 @@ Cihazda bulunamayan ZIM'ler gri klasörle "henüz yüklenmedi" görünür. */ const CATS = [ { title:{tr:"Ansiklopedi", en:"Encyclopedia"}, items:[ - { name:{tr:"Vikipedi (Türkçe)", en:"Wikipedia (Turkish)"}, desc:{tr:"Türkçe Vikipedi'nin resimli tam kopyası.", en:"The full Turkish Wikipedia with images."}, lang:"TR", size:"~9 GB", zim:"wikipedia_tr_all_maxi", search:true }, - { name:"Wikipedia (English)", desc:{tr:"Tüm İngilizce Wikipedia, resimleriyle birlikte.", en:"All of the English Wikipedia, with images."}, lang:"EN", size:"~120 GB", zim:"wikipedia_en_all_maxi", search:true }, + { name:{tr:"Vikipedi (Türkçe)", en:"Wikipedia (Turkish)"}, desc:{tr:"Türkçe Vikipedi'nin resimli tam kopyası.", en:"The full Turkish Wikipedia with images."}, lang:"TR", size:"~9 GB", zim:"wikipedia_tr_all_maxi" }, + { name:"Wikipedia (English)", desc:{tr:"Tüm İngilizce Wikipedia, resimleriyle birlikte.", en:"All of the English Wikipedia, with images."}, lang:"EN", size:"~120 GB", zim:"wikipedia_en_all_maxi" }, ]}, { title:{tr:"Türkçe Kitaplık", en:"Turkish Library"}, items:[ - { name:{tr:"Vikisözlük", en:"Wiktionary (Turkish)"}, desc:{tr:"Türkçe sözlük, köken bilgisi ve çeviriler.", en:"Turkish dictionary, word origins and translations."}, lang:"TR", size:"~810 MB", zim:"wiktionary_tr_all", search:true }, + { name:{tr:"Vikisözlük", en:"Wiktionary (Turkish)"}, desc:{tr:"Türkçe sözlük, köken bilgisi ve çeviriler.", en:"Turkish dictionary, word origins and translations."}, lang:"TR", size:"~810 MB", zim:"wiktionary_tr_all" }, { name:{tr:"Vikikitap", en:"Wikibooks (Turkish)"}, desc:{tr:"Açık ders kitapları ve el kitapları.", en:"Open textbooks and handbooks."}, lang:"TR", size:"~27 MB", zim:"wikibooks_tr_all" }, { name:{tr:"Vikikaynak", en:"Wikisource (Turkish)"}, desc:{tr:"Telifsiz metinler, kanunlar, klasikler.", en:"Public-domain texts, laws, classics."}, lang:"TR", size:"~68 MB", zim:"wikisource_tr_all" }, { name:{tr:"Vikisöz", en:"Wikiquote (Turkish)"}, desc:{tr:"Özlü sözler ve alıntılar.", en:"Sayings and quotations."}, lang:"TR", size:"~59 MB", zim:"wikiquote_tr_all" }, - { name:{tr:"iFixit (Türkçe)", en:"iFixit (Turkish)"}, desc:{tr:"Cihaz ve araç tamiri için Türkçe adım adım rehberler.", en:"Step-by-step repair guides for devices and vehicles, in Turkish."}, lang:"TR", size:"~3,6 GB", zim:"ifixit_tr_all", search:true }, + { name:{tr:"iFixit (Türkçe)", en:"iFixit (Turkish)"}, desc:{tr:"Cihaz ve araç tamiri için Türkçe adım adım rehberler.", en:"Step-by-step repair guides for devices and vehicles, in Turkish."}, lang:"TR", size:"~3,6 GB", zim:"ifixit_tr_all" }, { name:{tr:"PhET Simülasyonları", en:"PhET Simulations"}, desc:{tr:"Fizik, kimya ve matematik etkileşimli deneyleri.", en:"Interactive physics, chemistry and maths experiments."}, lang:"TR", size:"~107 MB", zim:"phet_tr_all" }, ]}, { title:{tr:"Haritalar ve Navigasyon", en:"Maps and Navigation"}, items:[ { name:{tr:"Dünya Haritası", en:"World Map"}, desc:{tr:"Avrupa ve Orta Doğu sokak seviyesinde, dünyanın geri kalanı şehir seviyesinde.", en:"Street level for Europe and the Middle East, city level for the rest of the world."}, lang:"—", size:"—", url:"/maps", service:"maps" }, ]}, { title:{tr:"Hayatta Kalma ve Hazırlık", en:"Survival and Preparedness"}, items:[ - { name:{tr:"Afet Sonrası Kitaplığı", en:"Post-Disaster Library"}, desc:{tr:"Barınak, enerji, tarım ve yeniden yapılanma üzerine kitaplar.", en:"Books on shelter, energy, farming and rebuilding."}, lang:"EN", size:"~615 MB", zim:"zimgit-post-disaster_en", search:true }, + { name:{tr:"Afet Sonrası Kitaplığı", en:"Post-Disaster Library"}, desc:{tr:"Barınak, enerji, tarım ve yeniden yapılanma üzerine kitaplar.", en:"Books on shelter, energy, farming and rebuilding."}, lang:"EN", size:"~615 MB", zim:"zimgit-post-disaster_en" }, { name:{tr:"Su Arıtma", en:"Water Treatment"}, desc:{tr:"İçme suyu bulma, arıtma ve saklama.", en:"Finding, treating and storing drinking water."}, lang:"EN", size:"~20 MB", zim:"zimgit-water_en" }, { name:{tr:"Gıda Hazırlama ve Saklama", en:"Food Preparation and Storage"}, desc:{tr:"Konserve, kurutma ve uzun süreli gıda saklama.", en:"Canning, drying and long-term food storage."}, lang:"EN", size:"~93 MB", zim:"zimgit-food-preparation_en" }, { name:{tr:"Düğümler Kitaplığı", en:"Knots Library"}, desc:{tr:"Düğüm çeşitleri ve kullanım alanları.", en:"Kinds of knots and what they are used for."}, lang:"EN", size:"~27 MB", zim:"zimgit-knots_en" }, - { name:"Ready.gov", desc:{tr:"ABD resmi afet hazırlık rehberleri: deprem, sel, yangın.", en:"Official US disaster preparedness guides: earthquake, flood, fire."}, lang:"EN", size:"~1,9 GB", zim:"ready.gov_en_all", search:true }, + { name:"Ready.gov", desc:{tr:"ABD resmi afet hazırlık rehberleri: deprem, sel, yangın.", en:"Official US disaster preparedness guides: earthquake, flood, fire."}, lang:"EN", size:"~1,9 GB", zim:"ready.gov_en_all" }, { name:"Low-tech Magazine", desc:{tr:"Elektriksiz ve düşük teknolojili pratik çözümler.", en:"Practical low-tech solutions, many without electricity."}, lang:"EN", size:"~670 MB", zim:"solar.lowtechmagazine.com_mul_all" }, - { name:"Appropedia", desc:{tr:"Uygun teknoloji wiki'si: su, güneş enerjisi, tarım, barınak.", en:"Appropriate technology wiki: water, solar energy, farming, shelter."}, lang:"EN", size:"~580 MB", zim:"appropedia_en_all", search:true }, + { name:"Appropedia", desc:{tr:"Uygun teknoloji wiki'si: su, güneş enerjisi, tarım, barınak.", en:"Appropriate technology wiki: water, solar energy, farming, shelter."}, lang:"EN", size:"~580 MB", zim:"appropedia_en_all" }, ]}, { title:{tr:"Sağlık ve İlk Yardım", en:"Health and First Aid"}, items:[ - { name:"WikiMed", desc:{tr:"Wikipedia'nın tıp maddeleri: hastalıklar, ilaçlar, anatomi.", en:"Wikipedia's medical articles: diseases, medicines, anatomy."}, lang:"EN", size:"~2 GB", zim:"wikipedia_en_medicine_maxi", search:true }, - { name:"MDWiki", desc:{tr:"Doktorlar tarafından düzenlenen tıp ansiklopedisi.", en:"A medical encyclopedia edited by doctors."}, lang:"EN", size:"~2 GB", zim:"mdwiki_en_all_maxi", search:true }, - { name:"MedlinePlus", desc:{tr:"ABD Ulusal Tıp Kütüphanesi hasta bilgilendirme sayfaları.", en:"Patient information pages of the US National Library of Medicine."}, lang:"EN", size:"~1,9 GB", zim:"medlineplus.gov_en_all", search:true }, + { name:"WikiMed", desc:{tr:"Wikipedia'nın tıp maddeleri: hastalıklar, ilaçlar, anatomi.", en:"Wikipedia's medical articles: diseases, medicines, anatomy."}, lang:"EN", size:"~2 GB", zim:"wikipedia_en_medicine_maxi" }, + { name:"MDWiki", desc:{tr:"Doktorlar tarafından düzenlenen tıp ansiklopedisi.", en:"A medical encyclopedia edited by doctors."}, lang:"EN", size:"~2 GB", zim:"mdwiki_en_all_maxi" }, + { name:"MedlinePlus", desc:{tr:"ABD Ulusal Tıp Kütüphanesi hasta bilgilendirme sayfaları.", en:"Patient information pages of the US National Library of Medicine."}, lang:"EN", size:"~1,9 GB", zim:"medlineplus.gov_en_all" }, { name:{tr:"Tıp Kitaplığı", en:"Medical Library"}, desc:{tr:"Temel tıp ve sağlık kitapları.", en:"Basic medical and health books."}, lang:"EN", size:"~67 MB", zim:"zimgit-medicine_en" }, { name:{tr:"Askeri Sahra Tıbbı", en:"Military Field Medicine"}, desc:{tr:"Sahada travma ve yaralı bakımı (FAS).", en:"Trauma and casualty care in the field (FAS)."}, lang:"EN", size:"~65 MB", zim:"irp.fas.org_en_military-medicine" }, { name:{tr:"NHS İlaç Rehberi", en:"NHS Medicines A to Z"}, desc:{tr:"İlaçların kullanımı, dozları ve yan etkileri.", en:"How medicines are used, their doses and side effects."}, lang:"EN", size:"~15 MB", zim:"nhs.uk_en_medicines" }, ]}, { title:{tr:"Tamir ve Beceriler", en:"Repair and Skills"}, items:[ - { name:"iFixit", desc:{tr:"Cihaz ve araç tamiri için adım adım rehberler.", en:"Step-by-step repair guides for devices and vehicles."}, lang:"EN", size:"~3 GB", zim:"ifixit_en_all", search:true }, + { name:"iFixit", desc:{tr:"Cihaz ve araç tamiri için adım adım rehberler.", en:"Step-by-step repair guides for devices and vehicles."}, lang:"EN", size:"~3 GB", zim:"ifixit_en_all" }, { name:{tr:"Ev Tamiri (DIY)", en:"Home Improvement (DIY)"}, desc:{tr:"Elektrik, tesisat ve yapı soruları.", en:"Electrical, plumbing and building questions."}, lang:"EN", size:"—", zim:"diy.stackexchange.com_en_all" }, { name:{tr:"Bahçecilik", en:"Gardening"}, desc:{tr:"Sebze yetiştirme, toprak ve bitki hastalıkları.", en:"Growing vegetables, soil and plant diseases."}, lang:"EN", size:"—", zim:"gardening.stackexchange.com_en_all" }, { name:{tr:"Yemek Pişirme", en:"Cooking"}, desc:{tr:"Pişirme teknikleri ve gıda güvenliği.", en:"Cooking techniques and food safety."}, lang:"EN", size:"—", zim:"cooking.stackexchange.com_en_all" }, From f08a3f975af084ecbd54816371ceb30101fa01b5 Mon Sep 17 00:00:00 2001 From: Ramazan Sancar Date: Sun, 29 Nov 2026 20:01:46 +0300 Subject: [PATCH 49/65] feat(admin): delete the selection with the password, clear ticks after a job starts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - "Delete selected" deletes the selected items that are on the device. /api/delete now takes "files" next to "file"; the password is asked once in the same dialog (the files listed one per line) and wrong attempts count towards the login limit. If any name is invalid or missing, nothing is deleted; the Kiwix library is rebuilt once at the end. The response is {"removed": [...]}. - After a download starts or a delete finishes, those items are unselected (the group box follows), so nothing is downloaded again by accident. Tests: Go (one password deletes all; wrong password, missing file, invalid name and empty selection delete nothing), docker/test.sh --download 179/179 (a missing file in the selection keeps the file, the real delete goes through "files"), browser tests 416 passed / 4 skipped on the latest browsers and on Chrome 102 / Firefox 99 / Safari 15.4 (delete-selected dialog, warning without a selection, ticks cleared after a download with a mocked server answer). - "Seçilenleri sil" seçilenlerden cihazda olanları siler. /api/delete artık "file"ın yanında "files" da alıyor; şifre aynı pencerede bir kez sorulur (dosyalar alt alta), yanlış denemeler giriş sınırına sayılır. Bir ad bile geçersiz ya da yoksa hiçbir şey silinmez; Kiwix kütüphanesi sonunda bir kez yenilenir. Cevap {"removed": [...]}. - İndirme başlayınca ya da silme bitince o öğelerin seçimi kalkar (grup kutusu da), yanlışlıkla yeniden indirilmez. Testler: Go (tek şifreyle hepsi silinir; yanlış şifre, olmayan dosya, geçersiz ad ve boş seçimde hiçbir şey silinmez), docker/test.sh --download 179/179 (seçimde olmayan dosya varsa dosya kalır, gerçek silme "files" ile), tarayıcı testleri en güncel tarayıcılarda ve Chrome 102 / Firefox 99 / Safari 15.4'te 416 geçti / 4 atlandı (seçilenleri sil penceresi, seçim yokken uyarı, taklit sunucu cevabıyla indirmeden sonra seçimin kalkması). --- admin/delete_test.go | 53 ++++++++++++++++++++++++++++++++ admin/handlers.go | 67 +++++++++++++++++++++++++++++++---------- admin/web/index.html | 34 ++++++++++++++++----- docker/README.md | 4 +-- docker/test.sh | 5 ++- e2e/tests/admin.spec.js | 39 ++++++++++++++++++++++++ www/home/has.js | 6 ++++ 7 files changed, 182 insertions(+), 26 deletions(-) diff --git a/admin/delete_test.go b/admin/delete_test.go index f2559c5..f888123 100644 --- a/admin/delete_test.go +++ b/admin/delete_test.go @@ -51,3 +51,56 @@ func TestDeleteNeedsPassword(t *testing.T) { t.Fatal("doğru şifreyle silinmedi / not deleted with the correct password") } } + +// Seçilenleri silme: tek şifreyle hepsi silinir; biri yoksa ya da adı geçersizse hiçbiri silinmez. +// Deleting the selection: one password deletes all; if one is missing or invalid, none is deleted. +func TestDeleteSelected(t *testing.T) { + lib := t.TempDir() + zdir := filepath.Join(lib, "zims", "content") + os.MkdirAll(zdir, 0o755) + a1, a2 := filepath.Join(zdir, "a_2026-01.zim"), filepath.Join(zdir, "b_2026-01.zim") + for _, f := range []string{a1, a1 + ".sha256", a2} { + os.WriteFile(f, []byte("x"), 0o644) + } + t.Setenv("KIWIX_LIB_CMD", "true") + + st := &store{path: filepath.Join(t.TempDir(), "users.json")} + if err := st.setPassword("deneme", "deneme-sifre-123"); err != nil { + t.Fatal(err) + } + a := newApp(config{prefix: "/admin", data: t.TempDir(), library: lib}, st) + h := a.routes() + tok := a.ses.create("deneme") + del := func(body string) (int, string) { + r := httptest.NewRequest("POST", "/admin/api/delete", strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + r.AddCookie(&http.Cookie{Name: cookieName, Value: tok}) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Body.String() + } + exists := func(p string) bool { _, err := os.Stat(p); return err == nil } + + if c, _ := del(`{"files":["a_2026-01.zim","b_2026-01.zim"],"password":"yanlis-sifre-12"}`); c != http.StatusForbidden { + t.Fatalf("yanlış şifre / wrong password: %d", c) + } + if c, _ := del(`{"files":["a_2026-01.zim","yok_2026-01.zim"],"password":"deneme-sifre-123"}`); c != http.StatusNotFound { + t.Fatalf("olmayan dosya / missing file: %d", c) + } + if c, _ := del(`{"files":["a_2026-01.zim","../users.json"],"password":"deneme-sifre-123"}`); c != http.StatusBadRequest { + t.Fatalf("geçersiz ad / invalid name: %d", c) + } + if c, _ := del(`{"files":[],"password":"deneme-sifre-123"}`); c != http.StatusBadRequest { + t.Fatalf("boş seçim / empty selection: %d", c) + } + if !exists(a1) || !exists(a2) { + t.Fatal("hatalı istekte dosya silindi / a file was deleted by a failed request") + } + c, body := del(`{"files":["a_2026-01.zim","b_2026-01.zim","a_2026-01.zim"],"password":"deneme-sifre-123"}`) + if c != http.StatusOK || !strings.Contains(body, `"removed":["a_2026-01.zim","b_2026-01.zim"]`) { + t.Fatalf("seçilenleri silme / delete selected: %d %s", c, body) + } + if exists(a1) || exists(a1+".sha256") || exists(a2) { + t.Fatal("seçilenler silinmedi / the selection was not deleted") + } +} diff --git a/admin/handlers.go b/admin/handlers.go index cd347e5..d05c0ae 100644 --- a/admin/handlers.go +++ b/admin/handlers.go @@ -487,18 +487,41 @@ func (a *app) verify(w http.ResponseWriter, r *http.Request) { } // remove silmeden önce oturumdaki kullanıcının şifresini yeniden ister; şifre sunucuda doğrulanır, -// yanlış denemeler giriş ile aynı sınıra takılır. +// yanlış denemeler giriş ile aynı sınıra takılır. Tek dosya ("file") ya da seçilenler ("files") silinir; +// biri bile geçersiz ya da yoksa hiçbiri silinmez. Kiwix kütüphanesi sonunda bir kez yenilenir. // remove asks for the logged-in user's password again before deleting; it is checked on the server -// and wrong attempts count towards the same limit as logins. +// and wrong attempts count towards the same limit as logins. Deletes one file ("file") or the selected +// ones ("files"); if any is invalid or missing, none is deleted. The Kiwix library is rebuilt once at the end. func (a *app) remove(w http.ResponseWriter, r *http.Request) { var req struct { - File string `json:"file"` - Password string `json:"password"` + File string `json:"file"` + Files []string `json:"files"` + Password string `json:"password"` } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil || !zimName.MatchString(req.File) { + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + fail(w, http.StatusBadRequest, "bad_request") + return + } + names := req.Files + if req.File != "" { + names = append([]string{req.File}, names...) + } + if len(names) == 0 { fail(w, http.StatusBadRequest, "invalid_file") return } + seen := map[string]bool{} + var files []string + for _, f := range names { + if !zimName.MatchString(f) { + fail(w, http.StatusBadRequest, "invalid_file") + return + } + if !seen[f] { + seen[f] = true + files = append(files, f) + } + } ip := clientIP(r) if d := a.lim.blocked(ip); d > 0 { failWait(w, d) @@ -515,21 +538,33 @@ func (a *app) remove(w http.ResponseWriter, r *http.Request) { fail(w, http.StatusConflict, "busy") return } - p := filepath.Join(a.cfg.zimDir(), req.File) - if _, err := os.Stat(p); err != nil { - fail(w, http.StatusNotFound, "file_not_found") - return + for _, f := range files { + if _, err := os.Stat(filepath.Join(a.cfg.zimDir(), f)); err != nil { + fail(w, http.StatusNotFound, "file_not_found") + return + } + } + removed := []string{} + var rmErr error + for _, f := range files { + p := filepath.Join(a.cfg.zimDir(), f) + if rmErr = os.Remove(p); rmErr != nil { + break + } + os.Remove(p + ".sha256") + removed = append(removed, f) + } + if len(removed) > 0 { + lib := env("KIWIX_LIB_CMD", "iiab-make-kiwix-lib") + if path, err := exec.LookPath(lib); err == nil { + a.work.start("library", nil, path) + } } - if err := os.Remove(p); err != nil { + if rmErr != nil { fail(w, 500, "server_error") return } - os.Remove(p + ".sha256") - lib := env("KIWIX_LIB_CMD", "iiab-make-kiwix-lib") - if path, err := exec.LookPath(lib); err == nil { - a.work.start("library", nil, path) - } - writeJSON(w, 200, map[string]string{"removed": req.File}) + writeJSON(w, 200, map[string][]string{"removed": removed}) } func (a *app) stopJob(w http.ResponseWriter, r *http.Request) { diff --git a/admin/web/index.html b/admin/web/index.html index 2fa7f4c..eba8a20 100644 --- a/admin/web/index.html +++ b/admin/web/index.html @@ -33,6 +33,7 @@ dialog h2{margin:0} dialog .in{padding:10px 12px} dialog .btns{display:flex;gap:8px;justify-content:flex-end} + #confirmFile{display:block;white-space:pre-line;overflow-wrap:anywhere;max-height:40vh;overflow:auto} button.danger{background:#B00000;color:#fff;border:1px solid #B00000} h3.grp{font-size:13px;margin:14px 0 0;padding:6px 8px;background:#EEF2F5;border-left:4px solid #006699;display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap} h3.grp label{display:flex;gap:6px;align-items:center;cursor:pointer} @@ -128,6 +129,7 @@

+ @@ -144,7 +146,7 @@

-

+

@@ -191,6 +193,11 @@

/* Uzun ZIM adları _ ve . sonrasında satır kırar / long ZIM names wrap after _ and . */ const brk = s => esc(s).replace(/([_.])/g, "$1"); const selected = () => [...document.querySelectorAll("#content input[data-prefix]:checked")]; +/* İşi başlatılan ya da silinen öğelerin seçimi kalkar (grup kutusu da güncellenir); yanlışlıkla yeniden indirilmez. + Items whose job started or that were deleted are unselected (the group box follows); no accidental re-download. */ +function unselect(keep){ + for (const i of selected()) if (!keep(i)) { i.checked = false; i.dispatchEvent(new Event("change")); } +} async function api(path, body){ const opt = body === undefined ? {} : {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(body)}; @@ -284,7 +291,7 @@

+ @@ -264,7 +277,7 @@