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/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..849f6cc
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,20 @@
+# Kod biçimi / code style: https://editorconfig.org
+# Ayrıntı / details: CONTRIBUTING.md "Kod biçimi / Code style"
+root = true
+
+[*]
+charset = utf-8
+end_of_line = lf
+insert_final_newline = true
+trim_trailing_whitespace = true
+indent_style = space
+indent_size = 2
+
+[*.go]
+indent_style = tab
+
+[*.md]
+trim_trailing_whitespace = false
+
+[Makefile]
+indent_style = tab
diff --git a/.gitattributes b/.gitattributes
index b6639ec..275b4ea 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -9,4 +9,7 @@
*.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
+*.go text eol=lf
+go.mod text eol=lf
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
new file mode 100644
index 0000000..220975f
--- /dev/null
+++ b/.github/workflows/docker.yml
@@ -0,0 +1,369 @@
+name: Docker
+
+# Ç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. amd64 imajı ilk işte bir kez derlenir; amd64 imaj testi
+# ve tarayıcı testleri onu kullanır, tarayıcı testleri diğer mimarileri beklemeden başlar.
+# 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 amd64 image is built once in the first job; the amd64 image
+# test and the browser tests reuse it, and the browser tests start without waiting for the other platforms.
+# 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: ["**"]
+ tags: ["v*"]
+ paths:
+ - "docker/**"
+ - "admin/**"
+ # İmaja scripts/ klasörünün tamamı giriyor / the whole scripts/ folder goes into the image
+ - "scripts/**"
+ - "compose.yaml"
+ - ".dockerignore"
+ - "config/**"
+ - "www/**"
+ - "e2e/**"
+ - ".github/workflows/docker.yml"
+ pull_request:
+ paths:
+ - "docker/**"
+ - "admin/**"
+ # İmaja scripts/ klasörünün tamamı giriyor / the whole scripts/ folder goes into the image
+ - "scripts/**"
+ - "compose.yaml"
+ - ".dockerignore"
+ - "config/**"
+ - "www/**"
+ - "e2e/**"
+ - ".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:
+ lint:
+ name: Dockerfile + compose
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@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
+
+ # amd64 imajı bir kez: amd64 imaj testi ve tarayıcı testleri artifact'tan yükler.
+ # The amd64 image, once: the amd64 image test and the browser tests load it from the artifact.
+ image:
+ name: Derle / build linux/amd64
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7.0.1
+
+ - uses: docker/setup-buildx-action@v4.4.1
+
+ - name: Derle / build
+ 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:ci
+ no-cache: ${{ github.event_name == 'schedule' }}
+ cache-from: type=gha,scope=amd64
+ cache-to: type=gha,scope=amd64,mode=max
+
+ - name: İmajı sakla / save the image
+ run: docker save has-disk:ci | gzip -1 > "$RUNNER_TEMP/has-disk-amd64.tar.gz"
+
+ - uses: actions/upload-artifact@v7.0.2
+ with:
+ name: has-disk-image-amd64
+ path: ${{ runner.temp }}/has-disk-amd64.tar.gz
+ retention-days: 1
+
+ test:
+ name: Test ${{ matrix.platform }}
+ needs: image
+ 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 }
+ # 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@v7.0.1
+
+ - uses: docker/setup-qemu-action@v4.4.0
+ if: matrix.qemu
+
+ - uses: docker/setup-buildx-action@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"
+
+ # amd64: ilk işte derlenen imaj / amd64: the image built in the first job
+ - uses: actions/download-artifact@v8.0.2
+ if: matrix.scope == 'amd64'
+ with:
+ name: has-disk-image-amd64
+ path: ${{ runner.temp }}
+
+ - name: İmajı yükle / load the image
+ id: load
+ if: matrix.scope == 'amd64'
+ run: gunzip -c "$RUNNER_TEMP/has-disk-amd64.tar.gz" | docker load
+
+ - name: Derle / build
+ id: build
+ if: matrix.scope != 'amd64'
+ uses: docker/build-push-action@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
+ platforms: ${{ matrix.platform }}
+ load: true
+ tags: has-disk:ci
+ no-cache: ${{ github.event_name == 'schedule' }}
+ 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' || steps.load.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 }}/report/container.log
+ PLATFORM: ${{ matrix.platform }}
+ DOWNLOAD: ${{ matrix.full && '1' || '' }}
+ 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
+ run: |
+ 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/
+ 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 > "$RUNNER_TEMP/report/compose.log" 2>&1
+ docker compose -p has-ci down
+
+ # 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@v7.0.2
+ with:
+ name: ${{ steps.env.outputs.artifact || format('has-disk-{0}', matrix.scope) }}
+ path: ${{ runner.temp }}/report/
+ 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.gen.name }}, ${{ matrix.shard }}/2)
+ # Yalnız amd64 imajını bekler, diğer mimarilerin testleriyle aynı anda koşar.
+ # Waits only for the amd64 image and runs alongside the other platforms' tests.
+ needs: image
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ # Her tarayıcı kuşağı iki parçaya bölünür (playwright --shard); her parça kendi HAS konteyneriyle ayrı
+ # makinede. Aynı anda en çok 20 iş (GitHub Free): 1 lint + 5 mimari + 14 parça.
+ # Every browser generation is split in two (playwright --shard); each part on its own machine with its own
+ # HAS container. At most 20 jobs at once (GitHub Free): 1 lint + 5 platforms + 14 parts.
+ shard: [1, 2]
+ # 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.
+ gen:
+ # 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
+
+ # İlk işte derlenen amd64 imajı / the amd64 image built in the first 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.gen.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.gen.image || 'noble' }}
+ SHARD: ${{ matrix.shard }}/2
+ run: bash e2e/run.sh "$VERSION" "$FLAVOR" --shard="$SHARD"
+
+ - name: Rapor / report
+ if: always()
+ uses: actions/upload-artifact@v7.0.2
+ with:
+ name: e2e-${{ matrix.gen.slug }}-playwright${{ steps.ver.outputs.playwright }}-${{ matrix.gen.image || 'noble' }}-${{ matrix.shard }}of2
+ path: |
+ e2e/playwright-report/
+ e2e/test-results/
+ retention-days: 14
+ if-no-files-found: ignore
+
+ publish:
+ name: Yayımla / publish
+ needs: [lint, test, e2e]
+ if: >-
+ github.event_name != 'pull_request' &&
+ (github.ref == 'refs/heads/main' ||
+ startsWith(github.ref, 'refs/tags/v'))
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ packages: write
+ steps:
+ - uses: actions/checkout@v7.0.1
+
+ - uses: docker/setup-qemu-action@v4.4.0
+
+ - uses: docker/setup-buildx-action@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@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@v4.8.0
+ 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@v7.4.0
+ env:
+ DOCKER_BUILD_RECORD_UPLOAD: "false"
+ with:
+ context: .
+ file: docker/Dockerfile
+ platforms: ${{ env.PLATFORMS }}
+ push: true
+ tags: ${{ steps.meta.outputs.tags }}
+ labels: ${{ steps.meta.outputs.labels }}
+ sbom: true
+ provenance: 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/.gitignore b/.gitignore
index 7eb99cd..5188177 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,12 @@
__MACOSX/
*.zip
Claude outputs/
+
+# Docker ile indirilen içerik / content downloaded with Docker
+library/
+
+# Tarayıcı testleri / browser tests
+e2e/node_modules/
+e2e/test-results/
+e2e/playwright-report/
+e2e/.env
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 0000000..faed3a2
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,11 @@
+# Yalnız JavaScript/JSON/YAML biçimlenir; HTML sayfaları elle düzenlenir (satır içi betik ve stil).
+# Only JavaScript/JSON/YAML are formatted; the HTML pages are kept by hand (inline scripts and styles).
+*.html
+*.md
+library/
+**/node_modules/
+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/.prettierrc.json b/.prettierrc.json
new file mode 100644
index 0000000..c3f02b8
--- /dev/null
+++ b/.prettierrc.json
@@ -0,0 +1,4 @@
+{
+ "printWidth": 120,
+ "overrides": [{ "files": "e2e/**/*.js", "options": { "singleQuote": true } }]
+}
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..9ade8c2 100644
--- a/README.md
+++ b/README.md
@@ -137,6 +137,8 @@ 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
+docs/ detailed guides (Turkish and English): install, admin panel, API, security
```
### Troubleshooting
@@ -290,6 +292,8 @@ 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
+docs/ ayrıntılı belgeler (Türkçe ve İngilizce): kurulum, panel, API, güvenlik
```
### Sorun giderme
diff --git a/admin/auth.go b/admin/auth.go
new file mode 100644
index 0000000..a4fae0e
--- /dev/null
+++ b/admin/auth.go
@@ -0,0 +1,362 @@
+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/hex"
+ "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"`
+ // Şifrenin son değiştiği an; bundan önce açılmış oturumlar geçersiz. / last password change; older sessions are invalid.
+ Changed time.Time `json:"changed"`
+}
+
+type store struct {
+ mu sync.Mutex
+ path string
+ mtime time.Time
+ Users []user `json:"users"`
+}
+
+func (s *store) load() error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.loadLocked()
+}
+
+func (s *store) loadLocked() error {
+ fi, err := os.Stat(s.path)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ b, err := os.ReadFile(s.path)
+ if err != nil {
+ return err
+ }
+ var fresh store
+ if err := json.Unmarshal(b, &fresh); err != nil {
+ return err
+ }
+ s.Users, s.mtime = fresh.Users, fi.ModTime()
+ return nil
+}
+
+// refreshLocked dosyayı her seferinde yeniden okur (birkaç yüz bayt): başka süreçten yapılan değişiklik
+// (ör. has-admin reset-password) panel yeniden başlamadan geçerli olur. Değişiklik zamanına güvenilmez;
+// FAT/exFAT gibi dosya sistemlerinde 2 saniyelik çözünürlük değişikliği gizleyebilir.
+// refreshLocked re-reads the file every time (a few hundred bytes), so a change from another process
+// (e.g. has-admin reset-password) applies without restarting the panel. Modification times are not
+// trusted: FAT/exFAT's 2-second resolution could hide a change.
+func (s *store) refreshLocked() {
+ if _, err := os.Stat(s.path); err == nil {
+ s.loadLocked()
+ }
+}
+
+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
+ }
+ if err := os.Rename(tmp, s.path); err != nil {
+ return err
+ }
+ if fi, err := os.Stat(s.path); err == nil {
+ s.mtime = fi.ModTime()
+ }
+ return nil
+}
+
+func (s *store) hasUsers() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.refreshLocked()
+ return len(s.Users) > 0
+}
+
+// changedAt kullanıcının şifresinin son değiştiği an; kullanıcı yoksa ok=false.
+// changedAt is when the user's password last changed; ok=false if the user does not exist.
+func (s *store) changedAt(name string) (time.Time, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.refreshLocked()
+ for _, u := range s.Users {
+ if u.Name == name {
+ return u.Changed, true
+ }
+ }
+ return time.Time{}, false
+}
+
+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, Changed: time.Now().UTC()}
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.refreshLocked()
+ 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()
+ s.refreshLocked()
+ 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
+
+// Oturumlar kutuda dosyada tutulur (sessions.json, 0600): kutu ya da konteyner yeniden başlayınca
+// oturum kapanmaz. Dosyada çerezdeki anahtar değil, SHA-256 özeti durur; dosyayı okuyan oturum çalamaz.
+// Şifre değişince (panelden ya da has-admin reset-password ile) o kullanıcının eski oturumları geçersiz olur.
+//
+// Sessions are kept on the box in a file (sessions.json, 0600), so they survive a restart of the box or
+// container. The file holds the SHA-256 of the cookie token, not the token, so reading it does not let
+// anyone take over a session. Changing a password (in the panel or with has-admin reset-password)
+// invalidates that user's older sessions.
+type sessions struct {
+ mu sync.Mutex
+ path string
+ m map[string]session
+}
+
+type session struct {
+ User string `json:"user"`
+ Created time.Time `json:"created"`
+ Expires time.Time `json:"expires"`
+}
+
+const sessionTTL = 12 * time.Hour
+
+func tokenKey(t string) string {
+ h := sha256.Sum256([]byte(t))
+ return hex.EncodeToString(h[:])
+}
+
+func newSessions(path string) *sessions {
+ s := &sessions{path: path, m: map[string]session{}}
+ if path != "" {
+ if b, err := os.ReadFile(path); err == nil {
+ json.Unmarshal(b, &s.m)
+ }
+ }
+ return s
+}
+
+func (s *sessions) saveLocked() {
+ if s.path == "" {
+ return
+ }
+ now := time.Now()
+ for k, v := range s.m {
+ if now.After(v.Expires) {
+ delete(s.m, k)
+ }
+ }
+ b, err := json.Marshal(s.m)
+ if err != nil {
+ return
+ }
+ tmp := s.path + ".tmp"
+ if os.WriteFile(tmp, b, 0o600) == nil {
+ os.Rename(tmp, s.path)
+ }
+}
+
+func (s *sessions) create(user string) string {
+ t := randomToken(32)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ now := time.Now().UTC()
+ s.m[tokenKey(t)] = session{User: user, Created: now, Expires: now.Add(sessionTTL)}
+ s.saveLocked()
+ return t
+}
+
+func (s *sessions) get(t string) (session, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ k := tokenKey(t)
+ v, ok := s.m[k]
+ if !ok || time.Now().After(v.Expires) {
+ if ok {
+ delete(s.m, k)
+ s.saveLocked()
+ }
+ return session{}, false
+ }
+ return v, true
+}
+
+func (s *sessions) drop(t string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ delete(s.m, tokenKey(t))
+ s.saveLocked()
+}
+
+// ---------------------------------------------------------------- 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..0e3c892
--- /dev/null
+++ b/admin/auth_test.go
@@ -0,0 +1,83 @@
+package main
+
+import (
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+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")
+ }
+}
+
+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/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/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/delete_test.go b/admin/delete_test.go
new file mode 100644
index 0000000..f888123
--- /dev/null
+++ b/admin/delete_test.go
@@ -0,0 +1,106 @@
+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")
+ }
+}
+
+// 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/errors_test.go b/admin/errors_test.go
new file mode 100644
index 0000000..8dafb4b
--- /dev/null
+++ b/admin/errors_test.go
@@ -0,0 +1,33 @@
+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")
+ // Sayfa metinleri ortak dosyada / page texts are in the shared file (www/home/has.js, section admin)
+ page, err := os.ReadFile("../www/home/has.js")
+ if err != nil {
+ t.Fatal(err)
+ }
+ 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+`:\s*"`).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..34296d5
--- /dev/null
+++ b/admin/handlers.go
@@ -0,0 +1,585 @@
+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"
+ "io"
+ "net"
+ "net/http"
+ "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: newSessions(filepath.Join(cfg.data, "sessions.json")),
+ 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
+// (www/home/has.js, admin.errors); message İngilizce açıklamadır (curl, kayıt, yeni istemciler için).
+// Error response: {"error_code": "...", "message": "..."}. The page localizes by error_code
+// (www/home/has.js, admin.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.",
+ "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.",
+ "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 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 r.Header.Get("Sec-Fetch-Site") == "cross-site" {
+ fail(w, http.StatusForbidden, "cross_origin")
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
+ next(w, r)
+ }
+}
+
+// currentUser: oturum geçerli mi ve şifre oturum açıldıktan sonra değişmedi mi.
+// currentUser: is the session valid and was the password not changed after it was opened.
+func (a *app) currentUser(r *http.Request) (string, bool) {
+ c, err := r.Cookie(cookieName)
+ if err != nil {
+ return "", false
+ }
+ s, ok := a.ses.get(c.Value)
+ if !ok {
+ return "", false
+ }
+ changed, exists := a.st.changedAt(s.User)
+ if !exists || s.Created.Before(changed) {
+ a.ses.drop(c.Value)
+ return "", false
+ }
+ return s.User, true
+}
+
+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"`
+ Lang string `json:"lang"`
+ // Kiwix kataloğundaki en yeni dosya ve kesin boyutu (sizes.json, scripts/catalog-sizes.sh)
+ // newest file in the Kiwix catalog and its exact size (sizes.json, scripts/catalog-sizes.sh)
+ Latest string `json:"latest,omitempty"`
+ LatestSize int64 `json:"latestSize,omitempty"`
+ 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).
+// 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), Lang: langOf(fields[1]), 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 sizes struct {
+ Items map[string]struct {
+ File string `json:"file"`
+ Bytes int64 `json:"bytes"`
+ } `json:"items"`
+ }
+ if b, err := os.ReadFile(filepath.Join(a.cfg.library, "www", "html", "home", "sizes.json")); err == nil {
+ json.Unmarshal(b, &sizes)
+ }
+ for i := range items {
+ if s, ok := sizes.Items[items[i].Prefix]; ok {
+ items[i].Latest, items[i].LatestSize = s.File, s.Bytes
+ }
+ }
+ 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.startItems("download", req.Prefixes, 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})
+}
+
+// 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) {
+ 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
+ }
+ 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. 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. 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"`
+ Files []string `json:"files"`
+ Password string `json:"password"`
+ }
+ 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)
+ 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
+ }
+ 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 rmErr != nil {
+ fail(w, 500, "server_error")
+ return
+ }
+ writeJSON(w, 200, map[string][]string{"removed": removed})
+}
+
+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..6752b6b
--- /dev/null
+++ b/admin/jobs.go
@@ -0,0 +1,172 @@
+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
+ items []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"`
+ Items []string `json:"items,omitempty"`
+ 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, Items: append([]string(nil), j.items...), 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, 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:]
+ }
+}
+
+// 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 {
+ return j.startItems(name, nil, cleanup, argv...)
+}
+
+// startItems start gibi; items işin kapsadığı içerikleri (ön ekleri) kaydeder, panel satırlarda "indiriliyor" gösterir.
+// startItems is like start; items records the content (prefixes) the job covers, so the panel can mark rows.
+func (j *job) startItems(name string, items []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.items = items
+ 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() {
+ // 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() {
+ 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..79a5a2a
--- /dev/null
+++ b/admin/main.go
@@ -0,0 +1,185 @@
+// 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 [--stdin] şifreyi sıfırla: rastgele ya da kendi şifren (terminalde sorar, yoksa girdiden)
+// reset: random, or your own (asked on a terminal, else read from stdin)
+// 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 (
+ "bufio"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "strings"
+ "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":
+ // --stdin: kendi şifren; terminalde iki kez sorulur (yazılan görünmez), değilse standart girdiden bir satır
+ // okunur. Seçenek yoksa rastgele üretilip yazılır.
+ // --stdin: your own password; asked twice on a terminal (typing is hidden), otherwise one line is read
+ // from standard input. Without it a random one is made and printed.
+ if len(args) < 2 || len(args) > 3 || (len(args) == 3 && args[2] != "--stdin") {
+ log.Fatal("kullanım / usage: has-admin reset-password [--stdin]")
+ }
+ pw, show := randomPassword(), true
+ if len(args) == 3 {
+ p, err := readNewPassword()
+ if err != nil {
+ log.Fatalf("HATA / ERROR: %v", err)
+ }
+ pw, show = p, false
+ }
+ if err := st.setPassword(args[1], pw); err != nil {
+ log.Fatalf("HATA / ERROR: %v", err)
+ }
+ if show {
+ fmt.Printf("Yeni şifre / new password (%s): %s\n", args[1], pw)
+ fmt.Printf("Kendi şifreni belirlemek için / to choose your own: has-admin reset-password %s --stdin\n", args[1])
+ } else {
+ fmt.Printf("Şifre değişti / password changed (%s)\n", args[1])
+ }
+ fmt.Println("Bu kullanıcının açık oturumları kapandı / this user's open sessions were closed")
+ 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())
+}
+
+var errMismatch = errors.New("şifreler aynı değil / the passwords do not match")
+
+// readNewPassword terminalde yeni şifreyi iki kez sorar, yazılanı stty ile gizler (Ctrl+C'de de geri açar);
+// terminal değilse (borudan) bir satır okur.
+// readNewPassword asks for the new password twice on a terminal, hiding the typing with stty (restored on Ctrl+C
+// too); when stdin is not a terminal (a pipe) it reads one line.
+func readNewPassword() (string, error) {
+ in := bufio.NewReader(os.Stdin)
+ read := func() string {
+ line, _ := in.ReadString('\n')
+ return strings.TrimRight(line, "\r\n")
+ }
+ if fi, err := os.Stdin.Stat(); err != nil || fi.Mode()&os.ModeCharDevice == 0 {
+ return read(), nil
+ }
+ stty := func(arg string) error {
+ c := exec.Command("stty", arg)
+ c.Stdin = os.Stdin
+ return c.Run()
+ }
+ if stty("-echo") == nil {
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, os.Interrupt)
+ go func() {
+ <-sig
+ stty("echo")
+ fmt.Fprintln(os.Stderr)
+ os.Exit(130)
+ }()
+ defer func() {
+ signal.Stop(sig)
+ stty("echo")
+ }()
+ } else {
+ fmt.Fprintln(os.Stderr, "Uyarı: yazılan şifre ekranda görünecek / warning: the password will be visible")
+ }
+ ask := func(prompt string) string {
+ fmt.Fprint(os.Stderr, prompt)
+ s := read()
+ fmt.Fprintln(os.Stderr)
+ return s
+ }
+ pw := ask("Yeni şifre / new password: ")
+ if ask("Tekrar / again: ") != pw {
+ return "", errMismatch
+ }
+ return pw, nil
+}
diff --git a/admin/session_test.go b/admin/session_test.go
new file mode 100644
index 0000000..12422af
--- /dev/null
+++ b/admin/session_test.go
@@ -0,0 +1,54 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+// Oturum yeniden başlatmada kalmalı; şifre değişince (başka süreçten bile) kapanmalı.
+// A session must survive a restart and end when the password changes (even from another process).
+func TestSessionPersistsAndPasswordChangeEndsIt(t *testing.T) {
+ data := t.TempDir()
+ users := filepath.Join(data, "users.json")
+ st := &store{path: users}
+ if err := st.setPassword("deneme", "deneme-sifre-123"); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(10 * time.Millisecond)
+ a := newApp(config{prefix: "/admin", data: data, library: data}, st)
+ tok := a.ses.create("deneme")
+ req := func(app *app) bool {
+ r := httptest.NewRequest("GET", "/admin/api/session", nil)
+ r.AddCookie(&http.Cookie{Name: cookieName, Value: tok})
+ _, ok := app.currentUser(r)
+ return ok
+ }
+ if !req(a) {
+ t.Fatal("yeni oturum geçersiz / new session invalid")
+ }
+
+ // "Yeniden başlatma": aynı dosyalardan yeni süreç / "restart": new process from the same files
+ st2 := &store{path: users}
+ st2.load()
+ b := newApp(config{prefix: "/admin", data: data, library: data}, st2)
+ if !req(b) {
+ t.Fatal("yeniden başlatmada oturum kayboldu / session lost on restart")
+ }
+
+ // Başka süreç (CLI) şifreyi değiştirir / another process (CLI) changes the password
+ time.Sleep(20 * time.Millisecond)
+ cli := &store{path: users}
+ cli.load()
+ if err := cli.setPassword("deneme", "yeni-sifre-12345"); err != nil {
+ t.Fatal(err)
+ }
+ if req(b) {
+ t.Fatal("şifre değişince oturum kapanmadı / session survived a password change")
+ }
+ if !b.st.check("deneme", "yeni-sifre-12345") {
+ t.Fatal("çalışan panel yeni şifreyi görmedi / running panel did not pick up the new password")
+ }
+}
diff --git a/admin/web/index.html b/admin/web/index.html
new file mode 100644
index 0000000..98a6344
--- /dev/null
+++ b/admin/web/index.html
@@ -0,0 +1,421 @@
+
+
+
+
+
+HAS_PrepperDisk · Yönetim / Admin
+
+
+
+
+
+
+İçeriğe geç
+
+
+
HAS_PrepperDisk ·
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
—
+
+
+
+
+
+
+
+
+
+
+
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/config/content.conf b/config/content.conf
index 55c8b14..eb8dbd6 100644
--- a/config/content.conf
+++ b/config/content.conf
@@ -4,42 +4,41 @@
# The script downloads the newest version for each line.
# Klasörler / folders: https://download.kiwix.org/zim/
# Başına # koyduğun satırlar atlanır / lines starting with # are skipped.
-# Boyutlar yaklaşıktır / sizes are approximate (2026-10).
# --- Ansiklopedi / Encyclopedia ---
-wikipedia wikipedia_tr_all_maxi # ~9 GB
-wikipedia wikipedia_en_all_maxi # ~120 GB
-# wikipedia wikipedia_en_all_nopic # ~55 GB, resimsiz / no images (küçük diskler için / for small disks)
+wikipedia wikipedia_tr_all_maxi
+wikipedia wikipedia_en_all_maxi
+# wikipedia wikipedia_en_all_nopic # resimsiz / no images (küçük diskler için / for small disks)
# --- Türkçe kitaplık / Turkish library ---
-wiktionary wiktionary_tr_all_nopic # ~810 MB Vikisözlük (katalogda yalnız resimsiz var / only nopic exists)
-wikibooks wikibooks_tr_all_maxi # ~27 MB Vikikitap: açık ders ve el kitapları / open textbooks
-wikisource wikisource_tr_all_maxi # ~68 MB Vikikaynak: telifsiz metinler, kanunlar / public-domain texts
-wikiquote wikiquote_tr_all_maxi # ~59 MB Vikisöz / quotations
-ifixit ifixit_tr_all # ~3.6 GB iFixit Türkçe tamir rehberleri / repair guides in Turkish
-phet phet_tr_all # ~107 MB PhET fizik-kimya simülasyonları / science simulations (TR)
+wiktionary wiktionary_tr_all_nopic # Vikisözlük (katalogda yalnız resimsiz var / only nopic exists)
+wikibooks wikibooks_tr_all_maxi # Vikikitap: açık ders ve el kitapları / open textbooks
+wikisource wikisource_tr_all_maxi # Vikikaynak: telifsiz metinler, kanunlar / public-domain texts
+wikiquote wikiquote_tr_all_maxi # Vikisöz / quotations
+ifixit ifixit_tr_all # iFixit Türkçe tamir rehberleri / repair guides in Turkish
+phet phet_tr_all # PhET fizik-kimya simülasyonları / science simulations (TR)
# --- Hayatta kalma kitapları / Survival books ---
-other appropedia_en_all_maxi # ~580 MB uygun teknoloji wiki: su, enerji, tarım / appropriate technology wiki
-other zimgit-post-disaster_en # ~615 MB afet sonrası kitaplığı / post-disaster library
-other zimgit-water_en # ~20 MB su arıtma / water treatment
-other zimgit-food-preparation_en # ~93 MB gıda hazırlama ve saklama / food for preppers
-other zimgit-knots_en # ~27 MB düğümler / knots
-zimit ready.gov_en_all # ~1.9 GB ABD afet hazırlık rehberi / US disaster preparedness
-zimit solar.lowtechmagazine.com_mul_all # ~670 MB düşük teknoloji çözümler / low-tech solutions
+other appropedia_en_all_maxi # uygun teknoloji wiki: su, enerji, tarım / appropriate technology wiki
+other zimgit-post-disaster_en # afet sonrası kitaplığı / post-disaster library
+other zimgit-water_en # su arıtma / water treatment
+other zimgit-food-preparation_en # gıda hazırlama ve saklama / food for preppers
+other zimgit-knots_en # düğümler / knots
+zimit ready.gov_en_all # ABD afet hazırlık rehberi / US disaster preparedness
+zimit solar.lowtechmagazine.com_mul_all # düşük teknoloji çözümler / low-tech solutions
# --- Sağlık / Health ---
-wikipedia wikipedia_en_medicine_maxi # ~2 GB WikiMed
+wikipedia wikipedia_en_medicine_maxi # WikiMed
# wikem_en_all_maxi Kiwix kataloğundan kaldırıldı (2026-10); yerine MDWiki + MedlinePlus.
# wikem_en_all_maxi was removed from the Kiwix catalog (2026-10); MDWiki + MedlinePlus cover it.
-other mdwiki_en_all_maxi # ~2.1 GB tıp ansiklopedisi / medical encyclopedia
-zimit medlineplus.gov_en_all # ~1.9 GB MedlinePlus hasta bilgilendirme / patient information (US NLM)
-other zimgit-medicine_en # ~67 MB tıp kitapları / medical books
-zimit irp.fas.org_en_military-medicine # ~65 MB askeri sahra tıbbı / military field medicine (eski ad / old name: fas-military-medicine_en)
-zimit nhs.uk_en_medicines # ~15 MB ilaç bilgileri / medicines A-Z
+other mdwiki_en_all_maxi # tıp ansiklopedisi / medical encyclopedia
+zimit medlineplus.gov_en_all # MedlinePlus hasta bilgilendirme / patient information (US NLM)
+other zimgit-medicine_en # tıp kitapları / medical books
+zimit irp.fas.org_en_military-medicine # askeri sahra tıbbı / military field medicine (eski ad / old name: fas-military-medicine_en)
+zimit nhs.uk_en_medicines # ilaç bilgileri / medicines A-Z
# --- Tamir ve beceriler / Repair & skills ---
-ifixit ifixit_en_all # ~3 GB tamir rehberleri / repair guides
+ifixit ifixit_en_all # tamir rehberleri / repair guides
stack_exchange diy.stackexchange.com_en_all # ev tamiri / home improvement
stack_exchange gardening.stackexchange.com_en_all # bahçecilik / gardening
stack_exchange cooking.stackexchange.com_en_all # yemek / cooking
@@ -49,5 +48,5 @@ stack_exchange outdoors.stackexchange.com_en_all # doğa ve kamp / outdoor
stack_exchange sustainability.stackexchange.com_en_all # sürdürülebilirlik / sustainability
# --- Büyük / Large (isteğe bağlı / optional) ---
-# zimit survivorlibrary.com_en_all # ~205 GB eski el kitapları arşivi / Survivor Library (needs 512 GB+ disk)
+# zimit survivorlibrary.com_en_all # eski el kitapları arşivi / Survivor Library (needs 512 GB+ disk)
# wikivoyage wikivoyage_en_all_maxi # seyahat rehberi / travel guide
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/docker/Dockerfile b/docker/Dockerfile
new file mode 100644
index 0000000..9abcc50
--- /dev/null
+++ b/docker/Dockerfile
@@ -0,0 +1,100 @@
+# 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)
+# 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
+# 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"
+
+# ---------------------------------------------------------------- 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/admin
+COPY admin/ ./
+# Panelin metinleri ortak dosyada; testler hata kodlarının iki dilde olduğuna bakar.
+# The panel's texts are in the shared file; the tests check every error code exists in both languages.
+COPY www/home/has.js /src/www/home/has.js
+# 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 .
+
+# ---------------------------------------------------------------- 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.
+# 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 \
+ && 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 --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
+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 ["/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
new file mode 100644
index 0000000..b4492d8
--- /dev/null
+++ b/docker/README.md
@@ -0,0 +1,127 @@
+# 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`. 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.
+
+### 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`.
+
+### 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. İç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, doğrulanır ya da silinir (silme şifreyle onaylanır); işi başlayan ya da silinen öğelerin seçimi kalkar. 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 `docker compose exec has has-admin reset-password --stdin` (iki kez sorar, yazılan görünmez; betikte `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.
+- **Oturumlar** kutuda saklanır (`/library/has-admin/sessions.json`, yalnız root okur, içinde çerez değil özeti var): konteyner ya da kutu yeniden başlayınca oturum kapanmaz (12 saat geçerli).
+- 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.
+
+### Telefondan açılmıyorsa
+
+Linux'ta (Pi, NAS, sunucu) ek ayar gerekmez: Docker portu güvenlik duvarına kendisi ekler. Windows ve macOS'ta Docker Desktop çalışır; işletim sisteminin güvenlik duvarı ilk seferde Docker Desktop için izin sorar. Bu izin uygulama başınadır, port başına değil; bir kez verilir.
+
+- **Windows:** soru çıkmadıysa ya da reddedildiyse: Windows Güvenliği → Güvenlik duvarı ve ağ koruması → Bir uygulamaya güvenlik duvarından izin ver → **Docker Desktop Backend** için **Özel** kutusunu işaretleyin. Ev ağının Ayarlar → Ağ ve İnternet'te "Özel ağ" olarak görünmesi gerekir.
+- **macOS:** Sistem Ayarları → Ağ → Güvenlik Duvarı → Seçenekler → Docker için "Gelen bağlantılara izin ver".
+- Bilgisayarın kendisinde `http://localhost:8080/home/` açılıyor ama telefonda açılmıyorsa sebep budur. Kablosuz genişletici ya da misafir ağında "istemci yalıtımı" açıksa cihazlar birbirini göremez.
+
+### 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.
+- 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
+
+`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 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
+
+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`. 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.
+
+### 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`.
+
+### 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. 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, verified or deleted (deleting asks for the password again); items whose job started or that were deleted are unselected. 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: `docker compose exec has has-admin reset-password --stdin` (asks twice, typing is hidden; in a script: `echo 'new-password' | docker compose exec -T has has-admin reset-password --stdin`). Changing a password ends that user's open sessions.
+- **Sessions** are stored on the box (`/library/has-admin/sessions.json`, root-only, holds a hash, not the cookie), so they survive a restart of the container or box (valid for 12 hours).
+- 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.
+
+### Not reachable from a phone
+
+On Linux (Pi, NAS, server) nothing else is needed: Docker adds the port to the firewall itself. On Windows and macOS Docker Desktop runs it; the OS firewall asks once to allow Docker Desktop. The permission is per app, not per port, and is given once.
+
+- **Windows:** if no prompt appeared or it was denied: Windows Security → Firewall & network protection → Allow an app through firewall → tick **Private** for **Docker Desktop Backend**. The home network should show as "Private" under Settings → Network & internet.
+- **macOS:** System Settings → Network → Firewall → Options → "Allow incoming connections" for Docker.
+- If `http://localhost:8080/home/` opens on the computer but not on a phone, this is the reason. With "client isolation" on a Wi-Fi extender or guest network, devices cannot see each other.
+
+### 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.
+- 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
+
+`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 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`.
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
new file mode 100644
index 0000000..6580cb1
--- /dev/null
+++ b/docker/entrypoint.sh
@@ -0,0 +1,53 @@
+#!/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).
+# 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.
+# Kesin ZIM boyutları da (Kiwix kataloğu, internet varsa) / the exact ZIM sizes too (Kiwix catalog, when online)
+( while :; do /opt/has/scripts/disk-health.sh >/dev/null 2>&1; /opt/has/scripts/catalog-sizes.sh >/dev/null 2>&1; sleep 21600; done ) &
+# 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" &
+# nginx işçileri: çekirdek sayısı, en çok 4; NGINX_WORKERS ile değiştirilebilir / workers: cores, at most 4; NGINX_WORKERS overrides
+workers=${NGINX_WORKERS:-$(nproc 2>/dev/null || echo 1)}
+[ -z "${NGINX_WORKERS:-}" ] && [ "$workers" -gt 4 ] && workers=4
+su-exec has nginx -e stderr -g "daemon off; worker_processes $workers;" &
+# 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.
+# 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
+) &
+
+# 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=$?
+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..1b38472
--- /dev/null
+++ b/docker/nginx.conf
@@ -0,0 +1,162 @@
+# 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).
+
+# İşçi sayısı entrypoint'te: çekirdek sayısı, en çok 4 (Pi'de 4). Çok çekirdekli makinede her işçi ayrı bellek
+# tutuyordu; 4 işçi bir Wi-Fi erişim noktasının istemcilerine fazlasıyla yetiyor.
+# The worker count is set in the entrypoint: the number of cores, at most 4 (4 on a Pi). On many-core machines each
+# worker held its own memory; 4 workers are plenty for the clients of one Wi-Fi access point.
+pid /tmp/nginx.pid;
+error_log stderr warn;
+
+events {
+ worker_connections 1024;
+}
+
+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;
+ # 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;
+ gzip_proxied any;
+ 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;
+ fastcgi_temp_path /tmp/nginx-fastcgi;
+ 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
+ root /library/www/html;
+
+ add_header X-Content-Type-Options nosniff always;
+ add_header Referrer-Policy no-referrer always;
+
+ location = / {
+ return 302 /home/;
+ }
+
+ # Sayfalar simgeyi kendisi verir; Kiwix içerik sayfalarının istediği /favicon.ico için boş cevap (konsolda 404 yok).
+ # The pages bring their own icon; /favicon.ico requested by Kiwix content pages gets an empty answer (no 404 in the console).
+ location = /favicon.ico {
+ return 204;
+ }
+
+ location / {
+ 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://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;
+ }
+
+ # 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/reader.html#library;
+ }
+ 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://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
new file mode 100755
index 0000000..7990b84
--- /dev/null
+++ b/docker/test.sh
@@ -0,0 +1,490 @@
+#!/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)
+#
+# 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).
+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
+
+REPO=$(cd "$(dirname "$0")/.." && pwd)
+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; }
+section() { echo; echo "## $*"; }
+
+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"; }
+# 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
+ 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
+}
+# Sağlık kontrolü yalnız nginx'e bakar; panel QEMU'da birkaç saniye sonra açılabilir, kurulum kodunu bekle.
+# The healthcheck only covers nginx; under QEMU the panel can start a few seconds later, so wait for the code.
+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
+}
+# 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
+ --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
+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
+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/reader.html /home/has.js /home/services.json /home/disk.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 "/admin → /admin/" test "$(location "$BASE/admin")" = /admin/
+check "/kiwix/ → HAS okuyucusu / reader" test "$(location "$BASE/kiwix/")" = "/home/reader.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" 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 "disk.json: disk sağlığı yazıldı / disk health written" has "$(curl -s "$BASE/home/disk.json")" '"warnings":\['
+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/reader.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'
+# Kiwix içerik sayfalarının istediği simge: 404 yerine boş cevap (konsolda hata yok) / no 404 for the icon Kiwix pages ask for
+check "favicon.ico: 204" test "$(code "$BASE/favicon.ico")" = 204
+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/reader.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
+ # Tema ve metinler ortak betikte / theme and texts come from the shared script
+ if [[ $html == *'src="/home/has.js"'* && $html == *'class="theme"'* ]]; then ok "tema seçimi / theme choice: $p"; else bad "tema seçimi yok / no theme choice: $p"; fi
+done
+hasjs=$(curl -s "$BASE/home/has.js")
+check "has.js: tema ve dil / theme and language" has "$hasjs" 'has-theme.*|has-lang'
+oku=$(curl -s "$BASE/home/reader.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 sayfada TR/EN seçimi / homepage has TR/EN choice" has "$(curl -s "$BASE/home/")" 'data-lang="en"'
+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/home/has.js") # metinler ortak dosyada / texts live in the shared file
+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
+req POST /job/stop '{}'; expect "girişsiz durdurma reddedilir / stop needs login" 401 login_required
+# Yanlış yöntem 405, bilinmeyen uç 404, 64 KB'tan büyük gövde 413 (nginx) / wrong method 405, unknown endpoint 404, body over 64 KB 413 (nginx)
+for p in /delete /download /verify /job/stop; do
+ check "GET $p reddedilir / is refused (405)" test "$(code "$API$p")" = 405
+done
+check "bilinmeyen uç / unknown endpoint 404" test "$(code "$API/yok")" = 404
+# Gövde dosyadan: Windows'ta komut satırı 32 KB ile sınırlı / body from a file: the command line is limited to 32 KB on Windows
+printf '{"user":"%s"}' "$(head -c 70000 /dev/zero | tr '\0' a)" >"$WORK/big.json"
+check "64 KB'tan büyük gövde / body over 64 KB (413)" test "$(code -X POST -H 'Content-Type: application/json' --data-binary @"$WORK/big.json" "$API/login")" = 413
+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\""
+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":['
+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 "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"* ]]; }
+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
+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.
+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)
+ 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 /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
+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
+ # Seçilenlerden biri yoksa hiçbiri silinmez / if one of the selection is missing, none is deleted
+ req POST /delete "{\"files\":[\"$F\",\"yok_2026-01.zim\"],\"password\":\"$PASS\"}"; expect "seçilenlerde olmayan dosya / missing file in the selection" 404 file_not_found
+ check "hatalı seçimde dosya kaldı / file kept after the failed request" catalog_has yes
+ req POST /delete "{\"files\":[\"$F\"],\"password\":\"$PASS\"}"; expect "seçilenleri şifreyle silme / delete selected with password" 200 removed
+ wait_job library
+ req GET /status
+ # 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
+
+# ---------------------------------------------------------------- komut satırından şifre / CLI password reset
+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
+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}')
+# QEMU altında ps ikinci sütunu {nginx} gösterir; desen bu yüzden başa sabitlenmez.
+# 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() {
+ 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.
+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 (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\":\"$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 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 · memory ${mem:-?} · $versions"
+ } >>"$GITHUB_STEP_SUMMARY"
+fi
+[ "$failed" = 0 ]
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..de3c739
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,38 @@
+# HAS_Disk belgeleri / documentation
+
+*English below.*
+
+## Türkçe
+
+Kısa kurulum ve donanım listesi ana [README](../README.md)'de. Buradaki belgeler ayrıntı için.
+
+| Belge | Ne anlatıyor |
+| --- | --- |
+| [Kurulum ve güncelleme rehberi](./tr-TR/guide.md) | Pi ve Docker kurulumu, içerik indirme, güncelleme, yedekleme; komutlar ve çıktılarının anlamı |
+| [Yönetim paneli](./tr-TR/admin-panel.md) | İlk kurulum kodu, giriş, şifre sıfırlama, içerik indirme / doğrulama / silme, bildirimler |
+| [Panel API'si](./tr-TR/api.md) | Uçlar, istek ve cevap örnekleri, hata kodları |
+| [İçerik ekleme](./tr-TR/adding-content.md) | Yeni ZIM ve servis ekleme, lisans kuralı, boyut listesi |
+| [Testler](./tr-TR/testing.md) | İmaj testi, tarayıcı testleri, CI |
+| [Güvenlik](./tr-TR/security.md) | Kutunun neye karşı korunduğu, neyi kaydetmediği, ne zaman dışarı bağlandığı |
+| [Sorun giderme](./tr-TR/troubleshooting.md) | Sık görülen sorunlar ve çözümleri |
+| [Kararlar](./tr-TR/decisions.md) | Neden Go, neden gzip_static, neden 4 nginx işçisi gibi kararlar ve ölçümleri |
+
+Belgeler iki dilde: Türkçe `tr-TR/`, İngilizce `en-US/` klasöründe, dosya adları aynı. Birinde değişiklik yapınca ötekini de güncelleyin.
+
+## English
+
+The short install and the hardware list are in the main [README](../README.md). These documents go into detail.
+
+| Document | What it covers |
+| --- | --- |
+| [Install and update guide](./en-US/guide.md) | Installing on a Pi and with Docker, downloading content, updating, backups; commands and what their output means |
+| [Admin panel](./en-US/admin-panel.md) | First-run setup code, login, password reset, downloading / verifying / deleting content, notices |
+| [Panel API](./en-US/api.md) | Endpoints, request and response examples, error codes |
+| [Adding content](./en-US/adding-content.md) | Adding a ZIM or a service, the license rule, the size list |
+| [Testing](./en-US/testing.md) | Image test, browser tests, CI |
+| [Security](./en-US/security.md) | What the box protects against, what it does not record, when it connects out |
+| [Troubleshooting](./en-US/troubleshooting.md) | Common problems and fixes |
+| [Decisions](./en-US/decisions.md) | Why Go, why gzip_static, why 4 nginx workers and similar decisions, with measurements |
+
+The documents come in two languages: Turkish in `tr-TR/`, English in `en-US/`, with the same file names. When you change one, update the other.
+
diff --git a/docs/en-US/adding-content.md b/docs/en-US/adding-content.md
new file mode 100644
index 0000000..5a6bf8e
--- /dev/null
+++ b/docs/en-US/adding-content.md
@@ -0,0 +1,72 @@
+# Adding content
+
+[Türkçe](../tr-TR/adding-content.md) · [All documents](../README.md)
+
+Content is a list of Kiwix ZIM files in `config/content.conf`. The same list and the same script are used on the Pi and in Docker.
+
+## Download something without changing the repo
+
+To try a ZIM or keep a personal list, write a list file in the same format and pass it to the script:
+
+```bash
+sudo ./scripts/download-content.sh /path/my-list.conf # Pi
+docker compose exec has /opt/has/scripts/download-content.sh /library/my-list.conf # Docker (the file inside ./library)
+```
+
+The admin panel only offers the lines of `config/content.conf`.
+
+## Adding a ZIM to the default list
+
+1. **Find the name.** Look the file up at [download.kiwix.org/zim](https://download.kiwix.org/zim/) or [library.kiwix.org](https://library.kiwix.org). 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. **Check the license.** The default list only holds content that allows commercial use. Content with a non-commercial (NC) license goes in as a commented-out line, so whoever wants it turns it on. The license is on the Kiwix library page of the book and in its ZIM metadata.
+3. **`config/content.conf`:** add one line:
+
+ ```
+ wikibooks wikibooks_tr_all_maxi # Vikikitap: açık ders ve el kitapları / open textbooks
+ ```
+
+ - `download-content.sh` downloads the newest version of each line.
+ - The note after `#` shows in the admin panel. Write it in Turkish and English.
+ - The panel groups by the language code in the prefix (`_tr_`, `_en_`, `_mul_`).
+ - A line starting with `#` is skipped: large or optional content goes there.
+4. **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 it is the same in both languages.
+ - `size` is only a fallback. The homepage shows the exact size from `sizes.json` (next step), or the size of the installed file from the disk.
+5. **Sizes, `config/sizes.json`:** regenerate the starter list, so a box that has never been online shows the new size too:
+
+ ```bash
+ 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; an online box refreshes it at install, after downloads and (in Docker) every 6 hours. Regenerate it now and then even without new content: sizes change with every Kiwix release. If the catalog cannot be reached, the old file stays.
+6. **Check.** Build the image and run the image test ([testing](./testing.md)), open `/admin` and look for the new row, download it, then open it from the homepage.
+
+Vital information (first aid, the emergency page) must match its source word for word; give the source in the commit.
+
+## Adding a service
+
+Maps, Kolibri and the panels are modules: one file per service in `scripts/services.d/.sh`. `scripts/services.sh` runs them (at install, and on every container start) and writes `services.json`, which the homepage and the panel read.
+
+```bash
+# 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"`; with several names the first installed one wins (for example `data-service="has-admin iiab-admin"`).
+- Example: `scripts/services.d/maps.sh`.
+
+## Texts
+
+Button and message texts 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.
diff --git a/docs/en-US/admin-panel.md b/docs/en-US/admin-panel.md
new file mode 100644
index 0000000..8f254c4
--- /dev/null
+++ b/docs/en-US/admin-panel.md
@@ -0,0 +1,62 @@
+# Admin panel
+
+[Türkçe](../tr-TR/admin-panel.md) · [All documents](../README.md)
+
+The HAS admin panel runs in the Docker image at `http://:8080/admin/`. It downloads, verifies and deletes content with the same scripts as the Pi. On the Pi the Internet-in-a-Box console is at `/admin` instead; the HAS panel is not installed there yet. The API behind the page: [panel API](./api.md).
+
+## First setup
+
+1. Get the setup code: `docker compose logs has | grep "setup code"` or `docker compose exec has has-admin setup-code`.
+2. Open `/admin/`, enter the code, choose a user name (2–32 characters: letters, digits, `.`, `_`, `-`) and a password (at least 10 characters).
+3. You are logged in. The code is deleted and cannot be used again; there is no default password.
+
+## Logging in and out
+
+- The session lasts 12 hours and survives a container restart. **log out** at the top ends it on the server too.
+- After 5 wrong passwords from one device the panel makes you wait (1 minute, doubling up to 15 minutes); the page says how long.
+
+### Forgot the password
+
+```bash
+docker compose exec has has-admin reset-password admin # resets it to a random password and prints it
+docker compose exec has has-admin reset-password admin --stdin # asks twice for a password of your choice (hidden)
+```
+
+Both end the user's open sessions.
+
+## The page
+
+| Section | What it shows |
+|---|---|
+| **Status** | Disk used / free / total, number and size of ZIM files, when it was checked |
+| **Services** | Every service module (Kiwix, maps, Kolibri, admin): installed or not, with a link when installed |
+| **Content** | Every line of `config/content.conf`, one table per language (Turkish, English, multilingual) |
+| **Job** | The running or last job (download, verification, library rebuild) and its output |
+
+### Content table
+
+Each row: the ZIM name, its folder and the newest size in the Kiwix catalog, the note from `content.conf`, and whether it is on the device (file name and size). When the catalog has a newer file than the one on the device, the row says **New version available**.
+
+- Tick rows, or tick a group header to select the whole language. The selection can span groups and survives the page refreshing itself.
+- **Download selected**: downloads the newest version of each selected item (resumes if interrupted).
+- **Verify selected**: checks the selected files that are on the device against their SHA-256; **Verify all**: every file.
+- **Delete selected** / **Delete** on a row: opens a dialog listing the files and asks for your password again. If one of the files is missing, nothing is deleted.
+
+After a job starts or a delete finishes, those ticks clear, so nothing is downloaded twice by accident.
+
+### While a job runs
+
+- The rows of a download say **Queued**, **Downloading 42.5%**, **Downloaded** or **Failed (details in the Job section)**.
+- A notice at the bottom says when a download starts and when a download or verification finishes or ends with an error. Close it with **×**; it closes by itself after a few seconds (errors stay longer). Screen readers announce it.
+- Only one job runs at a time; another one gets "Another job is running; wait for it to finish.".
+- **Stop** ends the running job. A stopped download resumes where it left off next time.
+
+## Language and theme
+
+TR / EN and the theme (system, dark, light) at the top; the choice is shared with the homepage, the reader and the emergency page.
+
+## What the panel does not do
+
+- It does not install or remove services (maps, Kolibri); see [decisions](./decisions.md).
+- It does not edit `content.conf`; add content as in [adding content](./adding-content.md).
+- It does not manage more than one user from the page; a second user can be added only by setting its password with `has-admin reset-password `.
diff --git a/docs/en-US/api.md b/docs/en-US/api.md
new file mode 100644
index 0000000..35fe3d2
--- /dev/null
+++ b/docs/en-US/api.md
@@ -0,0 +1,178 @@
+# Panel API
+
+[Türkçe](../tr-TR/api.md) · [All documents](../README.md)
+
+The admin panel (`admin/`, Go) serves a small JSON API under `/admin/api/`. The panel page uses it; it also works with `curl`. The prefix can be changed with `HAS_ADMIN_PREFIX` (default `/admin`).
+
+## Rules for every request
+
+- **Session:** logging in sets the `has_admin` cookie (`HttpOnly`, `SameSite=Strict`, path `/admin`, 12 hours). A session ends on logout, after 12 hours, or when the user's password changes.
+- **Requests that change something** (`POST`) need:
+ - a JSON body with `Content-Type: application/json`; anything else gets `415 json_required`;
+ - not to come from another site: a browser's `Sec-Fetch-Site: cross-site` gets `403 cross_origin`;
+ - a body of at most 64 KB.
+- The box's address (IP, port, `box.lan`) is never checked, so the panel works however people reach it.
+- **Failed logins:** after 5 wrong passwords (or setup codes) from one IP, every attempt waits; the wait starts at 1 minute and doubles up to 15 minutes. The answer is `429 too_many_attempts` with a `wait` field in seconds. A successful login clears the count.
+- **Every response** carries `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, `Cache-Control: no-store` and a `Content-Security-Policy` with `frame-ancestors 'none'`.
+
+## Errors
+
+```json
+{"error_code": "wrong_password", "message": "Wrong password."}
+```
+
+`error_code` is fixed and meant for programs; `message` is a plain English explanation. The panel page shows its own text for each code in the selected language (`www/home/has.js`, section `admin.errors`); a test checks that every code exists in both languages.
+
+| HTTP | `error_code` | When |
+|---|---|---|
+| 400 | `bad_request` | The body is not valid JSON or has the wrong shape |
+| 400 | `invalid_name` | User name is not 2–32 characters of letters, digits, `.`, `_`, `-` |
+| 400 | `short_password` | Password shorter than 10 characters |
+| 400 | `choose_content` | Nothing selected (download, verify) |
+| 400 | `not_in_list` | A selected item is not in `config/content.conf` |
+| 400 | `invalid_file` | A file name is not a plain `*.zim` name (no paths) |
+| 401 | `login_required` | No valid session |
+| 401 | `wrong_login` | Wrong user name or password (the same answer for an unknown user) |
+| 403 | `wrong_setup_code` | Wrong first-run setup code |
+| 403 | `wrong_password` | Wrong password when deleting |
+| 403 | `cross_origin` | The request came from another site |
+| 404 | `file_not_found` | A file to delete or verify is not on the disk |
+| 409 | `setup_done` | First-run setup was already done |
+| 409 | `busy` | Another job (download, verify, library rebuild) is running |
+| 415 | `json_required` | The body is not JSON |
+| 429 | `too_many_attempts` | Too many failed attempts; `wait` says how many seconds |
+| 500 | `content_unreadable` | `config/content.conf` could not be read |
+| 500 | `server_error` | Anything else |
+
+## Endpoints
+
+| Method and path | Login | What it does |
+|---|---|---|
+| `GET /admin/api/session` | no | Is setup needed, who is logged in |
+| `POST /admin/api/setup` | no | First-run setup: creates the user with the setup code |
+| `POST /admin/api/login` | no | Log in |
+| `POST /admin/api/logout` | no | Log out |
+| `GET /admin/api/status` | yes | Disk, ZIM files, content list, services |
+| `GET /admin/api/job` | yes | The current or last job and its output |
+| `POST /admin/api/download` | yes | Download the selected items |
+| `POST /admin/api/verify` | yes | Verify all or the selected ZIM files |
+| `POST /admin/api/delete` | yes | Delete one or the selected ZIM files (password needed) |
+| `POST /admin/api/job/stop` | yes | Stop the running job |
+
+A wrong method (for example `GET /admin/api/delete`) gets `405`.
+
+### `GET /admin/api/session`
+
+```json
+{"setup": true, "user": ""}
+```
+
+`setup: true` means no user exists yet and the page shows the setup form. After login `user` holds the name.
+
+### `POST /admin/api/setup`
+
+```json
+{"code": "k3v9q-…", "user": "admin", "password": "at-least-10-chars"}
+```
+
+`200 {"user": "admin"}` and a session cookie. The code is in the container log, or `has-admin setup-code` prints it; it is deleted after use. Errors: `wrong_setup_code`, `invalid_name`, `short_password`, `setup_done`, `too_many_attempts`.
+
+### `POST /admin/api/login`
+
+```json
+{"user": "admin", "password": "…"}
+```
+
+`200 {"user": "admin"}` and a session cookie. Errors: `wrong_login`, `too_many_attempts`.
+
+### `POST /admin/api/logout`
+
+Body `{}`. `200 {"ok": true}`; the session is removed on the server too.
+
+### `GET /admin/api/status`
+
+```json
+{
+ "checked": "2026-11-30T10:00:00+03:00",
+ "disk": {"total": 1000204886016, "free": 52613349376},
+ "zims": [{"name": "wikibooks_tr_all_maxi_2026-09.zim", "size": 26889216, "sha256": true}],
+ "content": [
+ {"folder": "wikibooks", "prefix": "wikibooks_tr_all_maxi", "note": "Vikikitap…", "lang": "tr",
+ "installed": "wikibooks_tr_all_maxi_2026-09.zim", "size": 26889216,
+ "latest": "wikibooks_tr_all_maxi_2026-09.zim", "latestSize": 26889216}
+ ],
+ "services": {"services": {"kiwix": {"installed": true, "label": {"tr": "Kütüphane", "en": "Library"}, "url": "/home/reader.html#library"}}}
+}
+```
+
+- `disk`: bytes on the `/library` disk.
+- `zims`: the files in `/library/zims/content`; `sha256: true` when a `.zim.sha256` sits next to it.
+- `content`: every line of `config/content.conf`. `installed` / `size` when a file with that prefix is on the disk; `latest` / `latestSize` from the Kiwix catalog (`sizes.json`), so the page can say "new version available".
+- `services`: the same `services.json` the homepage reads.
+
+### `GET /admin/api/job`
+
+```json
+{"name": "download", "items": ["wikibooks_tr_all_maxi"], "running": true,
+ "started": "2026-11-30T10:01:00+03:00", "exitCode": 0,
+ "lines": [">> wikibooks_tr_all_maxi_2026-09.zim indiriliyor / downloading (25 MB)", "######### 42.5%"]}
+```
+
+- `name`: `download`, `verify` or `library`.
+- `items`: the prefixes a download covers (the page uses it to mark rows).
+- `lines`: the last 400 lines of the script's output. curl's progress bar replaces its own line instead of adding new ones. The full output of the last job is also kept in `/library/has-admin/last-job.log`.
+- When the job ends: `running: false`, `finished` and `exitCode` (`0` success).
+
+### `POST /admin/api/download`
+
+```json
+{"prefixes": ["wikibooks_tr_all_maxi", "nhs.uk_en_medicines"]}
+```
+
+`202 {"started": true}`. Only lines from `config/content.conf` can be chosen; if one prefix is unknown, nothing starts (`not_in_list`). No text from the request reaches the script. Runs `scripts/download-content.sh`, the same script as on the Pi.
+
+### `POST /admin/api/verify`
+
+`{}` verifies every ZIM; `{"files": ["a_2026-01.zim"]}` only those. `202 {"started": true}`. Errors: `choose_content` (empty list), `invalid_file`, `file_not_found`, `busy`.
+
+### `POST /admin/api/delete`
+
+```json
+{"files": ["a_2026-01.zim", "b_2026-01.zim"], "password": "…"}
+```
+
+`{"file": "a_2026-01.zim", …}` deletes one. The logged-in user's password is checked again (wrong attempts count towards the login limit). If any name is invalid or missing, nothing is deleted. Each `.zim` and its `.zim.sha256` are removed, then the Kiwix library is rebuilt once. `200 {"removed": ["a_2026-01.zim", "b_2026-01.zim"]}`.
+
+### `POST /admin/api/job/stop`
+
+Body `{}`. `200 {"stopped": true}` (`false` if nothing was running). The script and its children (curl) get `SIGTERM`; a stopped download resumes where it left off next time.
+
+## Example with curl
+
+```bash
+B=http://localhost:8080/admin/api
+curl -c jar -H 'Content-Type: application/json' -d '{"user":"admin","password":"…"}' $B/login
+curl -b jar $B/status
+curl -b jar -H 'Content-Type: application/json' -d '{"prefixes":["nhs.uk_en_medicines"]}' $B/download
+curl -b jar $B/job
+```
+
+## Command line (`has-admin`)
+
+| Command | What it does |
+|---|---|
+| `has-admin` | Starts the server (Docker starts it on its own) |
+| `has-admin setup-code` | Prints the first-run setup code, or says a user already exists |
+| `has-admin reset-password ` | Resets the password to a random one and prints it |
+| `has-admin reset-password --stdin` | Sets a password of your choice: asked twice with hidden typing on a terminal, or read from a pipe |
+
+A password change ends that user's open sessions. In Docker: `docker compose exec has has-admin …`.
+
+| Variable | Default | Meaning |
+|---|---|---|
+| `HAS_ADMIN_ADDR` | `127.0.0.1:8090` | Listen address (behind nginx only) |
+| `HAS_ADMIN_PREFIX` | `/admin` | URL prefix |
+| `HAS_ADMIN_DATA` | `/library/has-admin` | Users, sessions, setup code, last job log |
+| `HAS_REPO` | `/opt/has` | Where `scripts/` and `config/` are |
+| `HAS_LIBRARY` | `/library` | The content disk |
+| `KIWIX_LIB_CMD` | `iiab-make-kiwix-lib` (Docker: `kiwix-library`) | Command that rebuilds the Kiwix library after a delete or download |
diff --git a/docs/en-US/decisions.md b/docs/en-US/decisions.md
new file mode 100644
index 0000000..b77b4a7
--- /dev/null
+++ b/docs/en-US/decisions.md
@@ -0,0 +1,71 @@
+# Decisions
+
+[Türkçe](../tr-TR/decisions.md) · [All documents](../README.md)
+
+Why things are the way they are, with the measurements behind them. Measurements were taken in Docker on a Windows machine, not on a Pi; the method and raw numbers are in the Docker pull request ([#66](https://github.com/schematrix/HAS_Disk/pull/66)).
+
+## Structure
+
+**Docker lives in this repo and uses the same scripts as the Pi.** A separate fork falls behind. The image keeps the Internet-in-a-Box layout (`/library/zims`, `/library/www/html`), so `install-homepage.sh`, `download-content.sh` and `verify-content.sh` run unchanged in both.
+
+**Services are modules (`scripts/services.d/`).** The homepage used to show maps, Kolibri and the admin console as installed even when they were not. Each service is now a small file that says whether it is installed; the result goes to `services.json`. Without the file the homepage behaves as before.
+
+**The panel does not install or remove services (yet).** On a Pi that means running Internet-in-a-Box's installer as root from a web page (long, needs internet, can break the system if interrupted); in Docker it would turn the panel into a remote software installer. Maps can become a one-click download (they are files) after the maps PR; Kolibri needs its own solution. Open.
+
+## Admin panel
+
+**Go, standard library only.** Measured on the same endpoint (`/api/status`, 300 ZIM entries + disk), 3,000 requests, 50 concurrent:
+
+| | Go | Python |
+|---|---|---|
+| Requests/s, 1 core | **1,918 req/s** | 49 req/s |
+| Requests/s, 0.25 core | **437 req/s** | 8 req/s |
+| Slowest 1%, 0.25 core | **397 ms** | 11.7 s |
+| Memory | **2–10 MB** | 11–19 MB |
+| Added to the image | **6.6 MB** | 42.3 MB |
+
+Many people connect to the box in a disaster, often on weak hardware, so the 0.25-core numbers matter most. No third-party modules: nothing to audit or update.
+
+**No default password.** A default password is never changed on many boxes. The first account needs a one-time code from the log; a forgotten password is reset from the command line (like Uptime Kuma), not from the web.
+
+**CSRF protection does not compare addresses.** The first version compared the request's origin with the box's address and blocked logins whenever the box was reached by another name or port (IP, `box.lan`, a forwarded port). In a disaster nobody knows which address people use. Now: JSON body required, `Sec-Fetch-Site: cross-site` refused, `SameSite=Strict` cookie.
+
+## Downloads and content
+
+**curl instead of wget.** Resumes reliably (`-C -`, 5 retries) and drops a dependency: Alpine's wget 1.25.0 had two high-severity issues without a fix at the time.
+
+**Official static kiwix-tools, pinned by version and SHA-256.** The same binaries Kiwix publishes, for every platform, without depending on a distribution's package.
+
+**kiwix-manage stays (20 MB).** It builds `library.xml`. Writing that file another way would lose the book metadata (titles, languages) the catalog and the reader use.
+
+**Exact sizes from the Kiwix catalog.** The "~" estimates in `content.conf` and on the homepage were often wrong. `catalog-sizes.sh` writes the real sizes to `sizes.json` at install, after downloads, every 6 hours in Docker and at build time; without internet the last known values stay. The map's size is measured on the device.
+
+## Web server
+
+**The Kiwix catalog is cached for 10 seconds.** Kiwix builds the catalog on every request. With the cache and `proxy_cache_lock`, a burst of clients costs one build. Kiwix sends `max-age=0`, which has to be ignored; without that every request waited 5 seconds on the lock. Kiwix catalog, 4 cores: 8,440 → **35,569 req/s**.
+
+**No kept-open connections to Kiwix.** kiwix-serve runs with few threads and idle connections kept them busy: articles 4,469 req/s with keep-alive, **6,820 req/s** without.
+
+**Precompressed pages (`gzip_static`).** nginx compressed every page on every request. The Docker start now writes a `.gz` copy of each page. Homepage on one core: 962 → **21,036 req/s**. (`ab` speaks HTTP/1.0, which nginx does not compress by default; these numbers come from `wrk`.)
+
+**At most 4 nginx workers.** One worker per core started 17 workers in Docker Desktop's VM. Four are plenty for one Wi-Fi access point; idle memory 19.3 → **11.3 MiB** on a 16-core machine (no change on a 4-core Pi).
+
+**kiwix-serve keeps its default 4 threads.** Tried 2, 4, 8 and 16: on 4 cores, 16 threads made search ~30% faster but doubled the slowest 1% for articles; on one core 8 and 16 slowed everything down.
+
+**util-linux-misc removed (2.3 MB).** It was there only for `mountpoint`; `findmnt --mountpoint` (already in the image and on the Pi) reads the mount table instead. Image 76.5 → 73.8 MB.
+
+## Reader
+
+**A reader page around Kiwix.** kiwix-serve 3.8 serves book pages to be shown inside its own viewer; opened directly, their links do not work. The HAS reader shows them in a frame with its own bar (home, library, source, search, random), so links from the homepage open somewhere useful.
+
+**"All sources" searches one language.** Kiwix refuses to search books in different languages together (by design, [libkiwix#838](https://github.com/kiwix/libkiwix/pull/838)). The reader adds `books.filter.lang` and offers a language picker; suggested upstream: [libkiwix#1434](https://github.com/kiwix/libkiwix/issues/1434).
+
+## Pages
+
+**The emergency page in English uses the original wording where it exists.** The CDC and EPA parts are quoted from the English pages; the AFAD and Istanbul health directorate parts are translated and say so. Vital information must match its source.
+
+**Lighthouse was used to find bugs, not for scores.** It found layout shifts while loading and a `favicon.ico` 404 on every page; those were fixed. SEO and HTTPS scores do not apply to an offline box served over `http://box.lan`.
+
+## CI
+
+**The amd64 image is built once; the browser tests are split in two per generation.** After the Docker and browser-test workflows were merged, the browser tests waited for all five platform tests and a run took 12–13 minutes. Now they wait only for the amd64 image and run as 14 parallel jobs (GitHub Free allows 20 at once): **~8 minutes**, with the same coverage.
diff --git a/docs/en-US/guide.md b/docs/en-US/guide.md
new file mode 100644
index 0000000..9694b8c
--- /dev/null
+++ b/docs/en-US/guide.md
@@ -0,0 +1,214 @@
+# Install and update guide
+
+[Türkçe](../tr-TR/guide.md) · [All documents](../README.md)
+
+There are two ways to run HAS_Disk:
+
+| | Raspberry Pi (Internet-in-a-Box) | Docker |
+| --- | --- | --- |
+| For | A Pi 5 that becomes the box itself: Wi-Fi hotspot, maps, Kolibri | Any computer that already runs Docker: PC, laptop, NAS, a 64-bit Pi |
+| Wi-Fi hotspot | Yes, set up by the installer | No; the computer's own network is used |
+| Maps, Kolibri, IIAB console | Yes | No |
+| Admin panel (`/admin`) | IIAB console | HAS panel ([admin panel](./admin-panel.md)) |
+| Install time | 30–60 min + content downloads | A few minutes + content downloads |
+
+Both use the same scripts (`scripts/`), the same content list (`config/content.conf`) and the same folder layout (`/library`).
+
+The scripts print every message in Turkish and English (`Türkçe / English`); the tables below quote the English half.
+
+## Raspberry Pi
+
+The hardware list is in the [README](../../README.md#hardware). Steps 1–5 need internet.
+
+### 1. Operating system
+
+Flash **Raspberry Pi OS Lite (64-bit)** to the SD card with [Raspberry Pi Imager](https://www.raspberrypi.com/software/). In Imager's settings enable SSH and set a user name and password. Boot the Pi with the SSD attached and connect it to your router with Ethernet.
+
+### 2. Get the repo
+
+```bash
+sudo apt update && sudo apt full-upgrade -y
+sudo apt install -y git
+git clone https://github.com/schematrix/HAS_Disk.git
+cd HAS_Disk
+chmod +x install.sh scripts/*.sh
+```
+
+The repo used to be called `HAS_Prepper_Disk`; GitHub redirects the old address.
+
+### 3. Mount the SSD at `/library`
+
+Find the disk with `lsblk` (usually `nvme0n1`), then:
+
+```bash
+sudo ./scripts/setup-ssd.sh /dev/nvme0n1
+```
+
+| Output | Meaning |
+| --- | --- |
+| `!!! /dev/nvme0n1 is not ext4 (…). It will be formatted and EVERYTHING ON IT ERASED.` | The disk has another file system. The script asks before formatting; answer no if the disk holds data you need. |
+| `Warning: /library is not empty and will be hidden by the SSD` | Files already in `/library` on the SD card will not be visible while the SSD is mounted (they are not deleted). |
+| `UUID=… /library ext4 defaults,noatime,nofail 0 2` | The line added to `/etc/fstab`; `nofail` lets the Pi boot even if the SSD is missing. |
+| `done: /dev/nvme0n1 -> /library` | Mounted, and mounted again at every boot. |
+| `/dev/nvme0n1 already mounted at /library` | Nothing to do. |
+
+### 4. Install
+
+```bash
+sudo ./install.sh
+```
+
+The script asks for the Wi-Fi name and password (8–63 characters), writes the settings and installs Internet-in-a-Box. **If the Pi reboots or the install stops, run the same command again;** it continues where it left off.
+
+| Output | Meaning |
+| --- | --- |
+| `Warning: /library is not on a separate disk. Content will go to the SD card.` | Step 3 was skipped. You can continue (it asks), but large content will fill the SD card. |
+| `settings written: /etc/iiab/local_vars.yml` | The Wi-Fi name, password and the settings from `config/iiab-overrides.yml` were written. |
+| `if the Pi reboots, run again: sudo ./install.sh` | Expected during the install. |
+| `ZIM warnings are expected before downloading content.` | The health check at the end complains about missing ZIM files; that is normal before step 5. |
+
+Internet-in-a-Box asks three things of its own: a password for the `iiab-admin` user (used for `http:///admin`, write it down), a key press to confirm you will re-run the command if something goes wrong, and Enter to reboot at the end. After the reboot run `sudo ./install.sh` once more; it skips the finished part and installs the homepage.
+
+### 5. Download content
+
+Choose what to download in `config/content.conf` ([adding content](./adding-content.md)), then:
+
+```bash
+sudo ./scripts/download-content.sh
+```
+
+The defaults need about 160 GB and can take many hours. If a download stops, run the script again: it resumes. For each line it looks up the newest version in the Kiwix catalog, checks free space (keeping 5 GB free, `RESERVE_GB`), downloads with resume and verifies the SHA-256 checksum.
+
+| Line starts with | Meaning |
+| --- | --- |
+| `>> Kiwix catalog …` / `>> … downloading (… MB)` | Work starts: catalog lookup, or a download with its size. A progress bar follows. |
+| `== … already present` | That version is already on the disk. Nothing downloaded. |
+| `sha256 verifying checksum` / `sha256 checksum OK` | The downloaded file matches the publisher's checksum. |
+| `warning: no .sha256 published, accepted unverified` | Kiwix did not publish a checksum for this file; it is kept, but not verified. |
+| `OK … done` | Downloaded, verified and moved into place. |
+| `-- removing old version …` | A newer version arrived; the older file and its `.sha256` are removed. |
+| `-- removing stale partial download …` | A half-finished download of an older version is removed. |
+| `!! … not found in the Kiwix catalog` | The name in `content.conf` changed or was retired. Check [download.kiwix.org/zim](https://download.kiwix.org/zim/). |
+| `!! not enough space: needed … MB + 5 GB headroom, free … MB` | Skipped. Free space or remove items from the list. |
+| `!! … download failed (re-run to resume)` | Network problem. Run the script again. |
+| `!! … checksum mismatch, corrupt file deleted` | The file was damaged; it was deleted. Run the script again. |
+| `!! catalog unreachable, falling back to directory listings` | The catalog did not answer; the script finds files from the download folders instead. |
+| `>> rebuilding Kiwix library` | The library is rebuilt so the new books appear without a restart. |
+
+The script exits with `0` when everything succeeded and `1` when at least one item failed (the others still finish).
+
+If an SSD is configured for `/library` but not mounted, the script stops before downloading: reconnect it, run `sudo mount /library` and retry.
+
+### 6. Maps
+
+Open `http:///admin` (user `iiab-admin`) and choose the regions in the maps section of **Install Content**.
+
+### 7. Use it
+
+Join the Wi-Fi network you created and open ****.
+
+### Check the box
+
+```bash
+./scripts/status.sh
+```
+
+It only reads and needs no `sudo`. Each line starts with `OK` (fine) or `!!` (problem, with the fix next to it): free space, the `/library` disk, web / Kiwix / hotspot / DHCP services, the hotspot bridge, missing or unfinished ZIMs, ZIMs not yet in the Kiwix library, CPU temperature and under-voltage. The last line says `all good` or `N problem(s) found`; the exit code is `0` or `1`, so it can run from cron. Fixes are in [troubleshooting](./troubleshooting.md).
+
+```bash
+sudo ./scripts/disk-health.sh
+```
+
+Checks the disk and the power supply (also every 6 hours on its own). `OK disk and power healthy`, or `!!` lines; the same warnings show in red at the top of the homepage.
+
+```bash
+./scripts/verify-content.sh # /library/zims/content
+./scripts/verify-content.sh /media/backup # another folder or one .zim file
+```
+
+Checks every ZIM offline against the saved `.zim.sha256` (or with `zimcheck` when there is none: `sudo apt install zim-tools`). `>> checking: …` for each file, `!!` for a failure, and a summary `N ZIM checked, M failed`. Exit code `0` all good, `1` a check failed, `2` the check could not start (for example no complete ZIM files).
+
+## Docker
+
+Needs Docker with Compose v2 (`docker compose version`). Platforms: `linux/amd64`, `linux/arm64`, `linux/arm/v7`, `linux/arm/v6`, `linux/386`.
+
+### Start
+
+```bash
+git clone https://github.com/schematrix/HAS_Disk.git && cd HAS_Disk
+docker compose up -d --build
+```
+
+`--build` builds the image on your machine (a few minutes). Once the image is published at `ghcr.io/schematrix/has-disk`, `docker compose up -d` downloads it instead.
+
+Homepage: `http://:8080/home/`. Content goes to `./library` next to `compose.yaml`.
+
+| Setting | Example | What it does |
+| --- | --- | --- |
+| `HAS_PORT` | `HAS_PORT=80 docker compose up -d` | The port on your machine (default 8080). |
+| `HAS_LIBRARY` | `HAS_LIBRARY=/mnt/ssd/library docker compose up -d` | Where content and panel data are kept (default `./library`). |
+| `NGINX_WORKERS` | in `compose.yaml` under `environment:` | nginx workers; default is the core count, at most 4. |
+
+These can also go into a `.env` file next to `compose.yaml`.
+
+### First login
+
+```bash
+docker compose logs has | grep "setup code"
+```
+
+```
+2026/11/30 10:00:00 İlk kurulum: /admin/ adresinde kullanıcı oluşturun. Kurulum kodu / first-run setup code: k3v9q-…
+```
+
+Open `http://:8080/admin/`, enter the code and choose a user name and password. The code works once and is deleted afterwards. `docker compose exec has has-admin setup-code` prints it again (or says a user already exists). Details: [admin panel](./admin-panel.md).
+
+### Download content
+
+From the panel (choose, then **Download selected**), or:
+
+```bash
+docker compose exec has /opt/has/scripts/download-content.sh
+```
+
+The output is the same as on the Pi (table above). Kiwix sees the new books without a restart.
+
+### Check
+
+```bash
+docker compose ps # STATUS: Up … (healthy)
+docker compose exec has /opt/has/scripts/verify-content.sh
+docker compose logs has # nginx, Kiwix and panel messages
+```
+
+`(healthy)` means the homepage answers inside the container. `(unhealthy)` means it has not answered for a few minutes; check the log.
+
+## Updating
+
+| What | Raspberry Pi | Docker |
+| --- | --- | --- |
+| HAS (homepage, scripts, panel) | `cd HAS_Disk && git pull && sudo ./scripts/install-homepage.sh` | `git pull && docker compose up -d --build` (or `docker compose pull && docker compose up -d` with the published image) |
+| Content | `sudo ./scripts/download-content.sh` | `docker compose exec has /opt/has/scripts/download-content.sh`, or the panel |
+| Internet-in-a-Box | See the [Internet-in-a-Box documentation](https://wiki.iiab.io/go/FAQ) | — |
+
+Content updates use the same script as the first download: `== … already present` means up to date; when a newer version is downloaded and verified, the old file is removed (`-- removing old version`). The panel shows "new version available" when the catalog has a newer file.
+
+In Docker the container is replaced on update, but everything in `./library` stays: ZIM files, users and sessions (`library/has-admin`).
+
+## Backup and moving
+
+- Everything the box keeps is under `/library` (Docker: the `HAS_LIBRARY` folder): `zims/content/` (ZIM files and their `.zim.sha256`), `has-admin/` (panel users), `www/html/home/` (homepage, regenerated on start).
+- Copy each `.zim` together with its `.zim.sha256`, then check the copy offline: `./scripts/verify-content.sh /path/to/copy`.
+- To move a Docker box, stop it (`docker compose down`), copy the `library` folder, start it on the new machine.
+
+## Removing
+
+- Docker: `docker compose down` stops and removes the container; `./library` stays. Delete that folder to remove the content too.
+- Pi, original homepage back: `sudo cp /library/www/html/home/index.html.iiab-original /library/www/html/home/index.html`
+
+## References
+
+- [Internet-in-a-Box](https://github.com/iiab/iiab) and its [FAQ](https://wiki.iiab.io/go/FAQ)
+- [Kiwix](https://kiwix.org), [kiwix-serve](https://wiki.kiwix.org/wiki/Kiwix-serve), ZIM files: [download.kiwix.org/zim](https://download.kiwix.org/zim/)
+- [Raspberry Pi Imager](https://www.raspberrypi.com/software/)
+- [Docker Compose](https://docs.docker.com/compose/)
diff --git a/docs/en-US/security.md b/docs/en-US/security.md
new file mode 100644
index 0000000..ea071ba
--- /dev/null
+++ b/docs/en-US/security.md
@@ -0,0 +1,64 @@
+# Security
+
+[Türkçe](../tr-TR/security.md) · [All documents](../README.md)
+
+## What the box is for
+
+The box serves content to the people on its own network (the Pi's Wi-Fi hotspot, or the local network of the Docker machine). It is **not meant to be reachable from the internet.** It serves plain HTTP: there is no certificate an offline box could use on `box.lan`.
+
+| Risk | What is done |
+|---|---|
+| Someone on the network changes or deletes content | Only the admin panel can, and only after login; deleting asks for the password again |
+| Password guessing | After 5 wrong attempts from one IP, a wait from 1 minute up to 15 minutes |
+| A web page on another site makes the browser act in the panel (CSRF) | JSON body required, `Sec-Fetch-Site: cross-site` refused, `SameSite=Strict` cookie |
+| The panel shown inside another site (clickjacking) | `X-Frame-Options: DENY`, CSP `frame-ancestors 'none'` |
+| Passwords leaking from the disk | PBKDF2-SHA256 with 600,000 rounds and a random salt; sessions stored as a hash, not the cookie itself |
+| Reading files that should not be served | The web root is `/library/www/html`; ZIM files, `library.xml` and panel data are outside it; `../` paths are refused |
+| A bug in a service taking over the system | In Docker: no root processes except the panel, read-only root file system, `no-new-privileges`, only `SETUID`, `SETGID`, `DAC_OVERRIDE` kept |
+
+**Wi-Fi:** the panel password travels unencrypted on the network. Use a hotspot password (WPA2) so only people who joined can see the traffic, and do not forward port 8080 from your router.
+
+## Accounts
+
+- No default password. The first account is created with a one-time setup code written to the log; the code file is readable only by root (`600`) and is deleted after use.
+- Panel data is in `/library/has-admin` (`700`): `users.json`, `sessions.json` (both `600`), the setup code and the last job log.
+- A session lasts 12 hours, ends on logout and when the password changes. Password reset needs access to the machine (`has-admin reset-password`), not the web page.
+
+## What runs where (Docker)
+
+| Process | User | Listens on |
+|---|---|---|
+| nginx | `has` (not root) | `0.0.0.0:8080`, the only port open to the outside |
+| kiwix-serve | `has` | `127.0.0.1:8081`, behind nginx |
+| has-admin (panel) | root (the download script writes to `/library`) | `127.0.0.1:8090`, behind nginx |
+
+If the panel stops, only the panel restarts; the homepage and Kiwix stay up.
+
+## What the box records
+
+- **No access log:** nginx does not record who opened which page (`access_log off`).
+- The panel keeps the output of the last job (`last-job.log`) and the sessions; no visitor data.
+- Docker's own log has the start-up messages and errors (`docker compose logs has`).
+
+## When the box connects out
+
+Only for content, and only when it has internet:
+
+| When | To | Why |
+|---|---|---|
+| Downloading content (by hand or from the panel) | `library.kiwix.org` (catalog), `download.kiwix.org` and its mirrors | Find the newest version, download it, get its SHA-256 |
+| At start and every 6 hours (Docker), at install (Pi) | `library.kiwix.org` | Refresh the exact sizes (`sizes.json`); without internet nothing is sent and the old file stays |
+| While building the image | `download.kiwix.org`, Alpine and Go package servers, `library.kiwix.org` | Build-time only |
+
+No telemetry, no update check, no other address. Without internet everything keeps working.
+
+## Supply chain
+
+- Base image pinned to a version (`alpine:3.24.4`, `golang:1.27.3-alpine3.24`); kiwix-tools pinned to a version and a SHA-256 per platform.
+- `apk upgrade` on every build picks up Alpine security fixes; the image is rebuilt weekly.
+- The panel uses only Go's standard library (no third-party modules).
+- GitHub Actions are pinned to version tags; the image is published only from `main` or a `v*` tag, after every test passed.
+
+## Reporting a problem
+
+Open an issue in the repository. For something that should not be public, contact the maintainer directly through GitHub first.
diff --git a/docs/en-US/testing.md b/docs/en-US/testing.md
new file mode 100644
index 0000000..5cd22e9
--- /dev/null
+++ b/docs/en-US/testing.md
@@ -0,0 +1,84 @@
+# Testing
+
+[Türkçe](../tr-TR/testing.md) · [All documents](../README.md)
+
+Three layers, all runnable on your own machine and all run by CI on every push:
+
+| Layer | What it checks | Where |
+|---|---|---|
+| Image test | The container as a whole: start-up, homepage, Kiwix, panel, persistence, security settings | `docker/test.sh` |
+| Browser tests | The pages in real browsers on desktop, phones and tablets, old and new | `e2e/` |
+| Code checks | Go tests, ShellCheck, hadolint, actionlint, Prettier | `admin/`, scripts, workflows |
+
+## Image test (`docker/test.sh`)
+
+```bash
+docker build -f docker/Dockerfile -t has-disk:test .
+docker/test.sh has-disk:test # about 2 min
+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 platform through QEMU (slow)
+```
+
+It starts the container with the same hardening as `compose.yaml` (read-only root, most capabilities dropped, `no-new-privileges`) on port 18090 and checks, section by section: the image metadata, start-up, the web server (redirects, headers, gzip, files that must not be served, path traversal), first-run setup, CSRF and bad input, downloads and verification (`--download`), restart and persistence, the command line (`has-admin`), security (no root processes, only port 8080 open, no capabilities) and memory and shutdown time.
+
+```
+## web
+ok - / → /home/
+ok - gzip_static: unpacks to the same page: /home/
+FAIL - …
+…
+# size: 74 MB · memory: 11.3MiB · kiwix-tools 3.8.2 nginx version: nginx/1.30.8 alpine 3.24.4
+# result: 153 ok, 0 failed
+```
+
+Each line is `ok` or `FAIL` with what was checked (in Turkish and English). The exit code is `0` only when nothing failed. On a failure the last 80 lines of the container log are printed; `HAS_TEST_LOGS=` keeps the whole log.
+
+| Variable | Default | Meaning |
+|---|---|---|
+| `HAS_TEST_PORT` | `18090` | Port for the test container |
+| `HAS_TEST_TIMEOUT` | `240` | Seconds to wait for start-up (QEMU needs more) |
+| `HAS_TEST_LOGS` | — | File to copy the container log to |
+
+## Browser tests (`e2e/`)
+
+They run in the official Playwright Docker image, so nothing is installed on your machine.
+
+```bash
+docker build -f docker/Dockerfile -t has-disk:test .
+e2e/prepare.sh has-disk:test # container on its own network, an account and two small ZIMs (internet)
+e2e/run.sh # latest browsers, every device
+e2e/run.sh 1.22.2 focal # Chrome 102, Firefox 99, Safari 15.4
+e2e/run.sh "" noble --project=iphone-se tests/reader.spec.js # one device, one file
+e2e/run.sh "" noble --shard=1/2 # half of the tests (what CI does)
+```
+
+- **Devices:** desktop Chromium, Firefox and WebKit; Android phones (Pixel, Galaxy S9+) and a tablet (Galaxy Tab S4); iPhone SE (320 px, the narrowest), a large iPhone, iPad Mini; Firefox at phone width.
+- **Browser generations** (`.github/workflows/docker.yml`): the latest, 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. Older Playwright versions are locked in `e2e/package.json` under an alias; `run.sh` mounts the right one.
+- **Files:** `home.spec.js` (homepage, emergency page), `reader.spec.js` (HAS reader), `admin.spec.js` (panel), `a11y.spec.js` (axe-core, WCAG 2.2 A/AA, light and dark theme; keyboard), `browsers.spec.js`.
+- Tests run one at a time (one server with a shared job queue and login limit). A wrong password is never sent to the real server; the panel's error texts are tested with a mocked server answer.
+- In CI a failed test is retried once; a test that passes only on the retry is reported as **flaky**, which the run summary shows. Treat flaky tests as bugs.
+- Results: `e2e/playwright-report/` (HTML), and for failures `e2e/test-results/` with a screenshot and a trace (`npx playwright show-trace trace.zip`).
+
+## Code checks
+
+```bash
+docker run --rm -v "$PWD/admin:/src" -w /src golang:1.27.3-alpine3.24 sh -c 'gofmt -l . ; go vet ./... && go test ./...'
+docker run --rm -v "$PWD:/mnt" -w /mnt koalaman/shellcheck:v0.10.0 --severity=warning $(git ls-files '*.sh')
+docker run --rm -i hadolint/hadolint:v2.15.1 < docker/Dockerfile
+docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:1.7.7
+npx prettier@3.10.0 --check .
+```
+
+The Docker build also runs `go vet` and `go test`; the image is not built if they fail.
+
+## CI (`.github/workflows/docker.yml`)
+
+On every push to any branch, on pull requests, weekly and by hand:
+
+1. **Dockerfile + compose:** hadolint and `docker compose config`.
+2. **Build linux/amd64:** builds the amd64 image once and hands it on as an artifact.
+3. **Test per platform:** `docker/test.sh` on amd64 (with `--download` and a compose start), arm64 (on an ARM runner), arm/v7, arm/v6 (QEMU) and 386. Each job leaves a report named after the platform, OS and Docker version (`environment.txt`, `packages.txt`, `test.txt`, the container log).
+4. **E2E:** seven browser generations × two shards = 14 jobs, waiting only for the amd64 image.
+5. **Publish:** only from `main` or a `v*` tag and only when everything passed: pushes the multi-platform image to `ghcr.io`.
+
+A run takes about 8 minutes.
diff --git a/docs/en-US/troubleshooting.md b/docs/en-US/troubleshooting.md
new file mode 100644
index 0000000..fbc793f
--- /dev/null
+++ b/docs/en-US/troubleshooting.md
@@ -0,0 +1,66 @@
+# Troubleshooting
+
+[Türkçe](../tr-TR/troubleshooting.md) · [All documents](../README.md)
+
+Start with the health check on a Pi (`./scripts/status.sh`) or the container state in Docker (`docker compose ps`, `docker compose logs has`). What their output means is in the [guide](./guide.md#check-the-box).
+
+## Docker
+
+**The page opens on the computer but not on a phone.**
+On Linux nothing else is needed: Docker adds the port to the firewall. On Windows and macOS the OS firewall must allow Docker Desktop once:
+- Windows: Windows Security → Firewall & network protection → Allow an app through firewall → tick **Private** for **Docker Desktop Backend**; the home network must be "Private" under Settings → Network & internet.
+- macOS: System Settings → Network → Firewall → Options → allow incoming connections for Docker.
+- Guest networks and Wi-Fi extenders with "client isolation" do not let devices see each other.
+
+**`docker compose up -d` says the image cannot be pulled.**
+The image is published only after the Docker work is merged. Until then build it: `docker compose up -d --build`.
+
+**The container keeps restarting or is `(unhealthy)`.**
+`docker compose logs has` shows why. If kiwix-serve or nginx stops, the container stops and Docker restarts it; a stopped panel restarts on its own and is not a reason.
+
+**The 386 image has no network.**
+Only on Docker 29.4.2: its security profile blocked the 32-bit x86 network call ([moby/profiles#21](https://github.com/moby/profiles/pull/21)). Update Docker (29.4.3 or later).
+
+**Port 8080 is taken.** `HAS_PORT=8081 docker compose up -d`.
+
+## Admin panel
+
+**Forgot the password.** `docker compose exec has has-admin reset-password ` (random) or `… --stdin` (your own). See [admin panel](./admin-panel.md#forgot-the-password).
+
+**"Too many attempts. Try again in N s."** Five wrong passwords from this device; wait the time shown (at most 15 minutes). A successful login clears it.
+
+**"Another job is running; wait for it to finish."** Only one download, verification or library rebuild runs at a time. Wait, or press **Stop** in the Job section.
+
+**A download failed (row says "Failed").** The Job section shows the line starting with `!!`; the meanings are in the [guide](./guide.md#5-download-content). Running the download again resumes it.
+
+**The setup code is not in the log.** A user already exists (`docker compose exec has has-admin setup-code` says so). Reset that user's password instead.
+
+## Homepage and reader
+
+**A book is listed but says "not installed yet".** Its ZIM is not on the device, or its name changed in the Kiwix catalog. Download it from the panel or with `download-content.sh`.
+
+**The library page stays empty in an old browser.** Kiwix's library page cannot draw its list in older browsers (e.g. Chrome 102, Safari 15); after a few seconds the reader lists the books on the device itself.
+
+**Search across "All sources" only shows one language.** Kiwix does not search books in different languages together; the reader searches the language chosen next to "All sources" ([kiwix/libkiwix#1434](https://github.com/kiwix/libkiwix/issues/1434)).
+
+**Book collections (Water Treatment, Knots, Food for Preppers, Post-Disaster, Medicine) keep loading.** They keep their book list in the browser's local database. iPhone Safari private tabs and the captive portal window block that; open them in a normal Safari tab.
+
+**A newly downloaded book does not appear.** The Kiwix catalog is cached for 10 seconds; reload. If it still does not appear, rebuild the library: Pi `sudo iiab-make-kiwix-lib`, Docker `docker compose exec has kiwix-library`.
+
+## Raspberry Pi
+
+**`ssh user@hostname.local` stops working after install.** Internet-in-a-Box renames the Pi to `box`: use `ssh user@box.local` or the IP address (`arp -a` on your computer, or the router's device list).
+
+**The hotspot does not appear.** Connect over Ethernet, check `sudo iiab-diagnostics`, and make sure the install finished: `/etc/iiab/install-flags/iiab-complete` must exist.
+
+**"invalid WPA passphrase length" in the log.** Wi-Fi passwords must be 8–63 characters. Fix `hostapd_password` in `/etc/iiab/local_vars.yml` and `wpa_passphrase` in `/etc/hostapd/hostapd.conf`, then `sudo systemctl restart hostapd`.
+
+**Devices say "incorrect password" or drop after a few seconds.** Usually the hotspot bridge `br0` is down (`ip -br addr show br0`, `bridge link`). The fix is in the [README](../../README.md#troubleshooting).
+
+**Map downloads fail with "connection reset by peer".** The map server is blocked in some countries (e.g. Turkey). The README shows how to use Cloudflare WARP for the download.
+
+**The disk is full or read-only.** The red warning at the top of the homepage comes from `disk-health.sh`. Check with `sudo ./scripts/disk-health.sh`; remove content from the list or use a bigger disk; a read-only remount usually means file system errors (run `fsck` with the disk unmounted).
+
+**Under-voltage warning.** Use a 5V/5A supply; a weak supply or battery can corrupt the disk.
+
+**Restoring the original homepage:** `sudo cp /library/www/html/home/index.html.iiab-original /library/www/html/home/index.html`
diff --git a/docs/tr-TR/adding-content.md b/docs/tr-TR/adding-content.md
new file mode 100644
index 0000000..661a612
--- /dev/null
+++ b/docs/tr-TR/adding-content.md
@@ -0,0 +1,72 @@
+# İçerik ekleme
+
+[English](../en-US/adding-content.md) · [Tüm belgeler](../README.md)
+
+İçerik, `config/content.conf`'taki Kiwix ZIM dosyalarının listesidir. Pi'de de Docker'da da aynı liste ve aynı betik kullanılır.
+
+## Depoyu değiştirmeden bir şey indirmek
+
+Bir ZIM'i denemek ya da kendi listenizi tutmak için aynı biçimde bir liste dosyası yazıp betiğe verin:
+
+```bash
+sudo ./scripts/download-content.sh /yol/benim-listem.conf # Pi
+docker compose exec has /opt/has/scripts/download-content.sh /library/benim-listem.conf # Docker (dosya ./library içinde)
+```
+
+Yönetim paneli yalnız `config/content.conf`'taki satırları gösterir.
+
+## Varsayılan listeye ZIM eklemek
+
+1. **Adı bulun.** Dosyayı [download.kiwix.org/zim](https://download.kiwix.org/zim/) ya da [library.kiwix.org](https://library.kiwix.org)'da bulun. *Ö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. **Lisansa bakın.** Varsayılan listede yalnız ticari kullanıma izin veren içerik olur. Ticari olmayan (NC) lisanslı içerik yorum satırı olarak girer; isteyen açar. Lisans, kitabın Kiwix kitaplığı sayfasında ve ZIM meta verisinde yazar.
+3. **`config/content.conf`:** bir satır ekleyin:
+
+ ```
+ wikibooks wikibooks_tr_all_maxi # Vikikitap: açık ders ve el kitapları / open textbooks
+ ```
+
+ - `download-content.sh` her satırın en yeni sürümünü indirir.
+ - `#` sonrasındaki not yönetim panelinde görünür. Türkçe ve İngilizce yazın.
+ - 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.
+4. **Ana sayfa, `www/home/index.html`:** `CATS` içinde doğru kategoriye bir öğe ekleyin:
+
+ ```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; iki dilde aynıysa düz metin de olur.
+ - `size` yalnız yedektir. Ana sayfa kesin boyutu `sizes.json`'dan (sonraki adım), kurulu dosyanın boyutunu diskten gösterir.
+5. **Boyutlar, `config/sizes.json`:** hiç internet görmemiş kutuda da yeni boyut görünsün diye başlangıç listesini yeniden üretin:
+
+ ```bash
+ 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; internete bağlı kutu kurulumda, indirmeden sonra ve (Docker'da) 6 saatte bir tazeler. Yeni içerik olmasa da ara sıra yeniden üretin: boyutlar her Kiwix sürümüyle değişir. Katalog alınamazsa eski dosya kalır.
+6. **Deneyin.** İmajı derleyip imaj testini çalıştırın ([testler](./testing.md)), `/admin`'de yeni satıra bakın, indirin, sonra ana sayfadan açın.
+
+Hayati bilgi (ilk yardım, acil sayfası) kaynağıyla birebir olmalı; kaynağı commit'te verin.
+
+## Servis eklemek
+
+Harita, Kolibri ve paneller birer modül: her servis için `scripts/services.d/.sh` dosyası. `scripts/services.sh` bunları çalıştırır (kurulumda ve her konteyner açılışında) ve ana sayfayla panelin okuduğu `services.json`'u yazar.
+
+```bash
+# 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ın)
+```
+
+- `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 varsa ilk kurulu olan seçilir (ör. `data-service="has-admin iiab-admin"`).
+- Örnek: `scripts/services.d/maps.sh`.
+
+## 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.
diff --git a/docs/tr-TR/admin-panel.md b/docs/tr-TR/admin-panel.md
new file mode 100644
index 0000000..8400474
--- /dev/null
+++ b/docs/tr-TR/admin-panel.md
@@ -0,0 +1,62 @@
+# Yönetim paneli
+
+[English](../en-US/admin-panel.md) · [Tüm belgeler](../README.md)
+
+HAS yönetim paneli Docker imajında `http://:8080/admin/` adresinde çalışır. İçeriği Pi'dekiyle aynı betiklerle indirir, doğrular ve siler. Pi'de `/admin`'de Internet-in-a-Box paneli var; HAS paneli orada henüz kurulmuyor. Sayfanın arkasındaki API: [panel API'si](./api.md).
+
+## İlk kurulum
+
+1. Kurulum kodunu alın: `docker compose logs has | grep "setup code"` ya da `docker compose exec has has-admin setup-code`.
+2. `/admin/` adresini açın, kodu girin, kullanıcı adı (2–32 karakter: harf, rakam, `.`, `_`, `-`) ve şifre (en az 10 karakter) belirleyin.
+3. Giriş yapılmış olur. Kod silinir, bir daha kullanılamaz; varsayılan şifre yok.
+
+## Giriş ve çıkış
+
+- Oturum 12 saat sürer, konteyner yeniden başlasa da kalır. Üstteki **çıkış** oturumu sunucuda da kapatır.
+- Aynı cihazdan 5 yanlış şifreden sonra panel bekletir (1 dakika, her seferinde iki katı, en çok 15 dakika); sayfa ne kadar bekleneceğini yazar.
+
+### Şifreyi unuttum
+
+```bash
+docker compose exec has has-admin reset-password admin # şifreyi rastgele bir şifreyle sıfırlar ve yazar
+docker compose exec has has-admin reset-password admin --stdin # istediğiniz şifreyi iki kez sorar (yazılan görünmez)
+```
+
+İkisi de kullanıcının açık oturumlarını kapatır.
+
+## Sayfa
+
+| Bölüm | Ne gösterir |
+|---|---|
+| **Durum** | Diskte dolu / boş / toplam, ZIM dosyalarının sayısı ve boyutu, son kontrol zamanı |
+| **Servisler** | Her servis modülü (Kiwix, harita, Kolibri, yönetim): kurulu mu, kuruluysa bağlantısı |
+| **İçerik** | `config/content.conf`'un her satırı, dile göre ayrı tablolarda (Türkçe, İngilizce, çok dilli) |
+| **İş** | Çalışan ya da son iş (indirme, doğrulama, kütüphane yenileme) ve çıktısı |
+
+### İçerik tablosu
+
+Her satırda: ZIM adı, klasörü ve Kiwix kataloğundaki en yeni boyutu, `content.conf`'taki not, cihazda olup olmadığı (dosya adı ve boyutu). Katalogda cihazdakinden yeni bir dosya varsa satırda **Yeni sürüm var** yazar.
+
+- Satırları işaretleyin ya da bir dilin tamamını seçmek için grup başlığını işaretleyin. Seçim gruplar arasında yapılabilir, sayfa kendini yenilese de kalır.
+- **Seçilenleri indir**: seçilen her öğenin en yeni sürümünü indirir (yarıda kalırsa kaldığı yerden).
+- **Seçilenleri doğrula**: seçilenlerden cihazda olanları SHA-256 ile denetler; **Hepsini doğrula**: bütün dosyaları.
+- **Seçilenleri sil** / satırdaki **Sil**: dosyaları listeleyen bir pencere açar ve şifrenizi yeniden sorar. Dosyalardan biri yoksa hiçbiri silinmez.
+
+İş başlayınca ya da silme bitince o işaretler kalkar; böylece bir şey yanlışlıkla iki kez indirilmez.
+
+### İş sürerken
+
+- İndirilen satırlarda **Sırada**, **İndiriliyor 42.5%**, **İndirildi** ya da **İndirilemedi (ayrıntı İş bölümünde)** yazar.
+- Sayfanın altındaki bildirim indirme başlayınca ve indirme ya da doğrulama bitince ya da hatayla sonlanınca çıkar. **×** ile kapanır; birkaç saniye sonra kendiliğinden de kapanır (hatalar daha uzun kalır). Ekran okuyucu duyurur.
+- Aynı anda tek iş çalışır; başka bir iş "Başka bir iş çalışıyor; bitmesini bekleyin." uyarısı alır.
+- **Durdur** çalışan işi bitirir. Durdurulan indirme bir sonraki seferde kaldığı yerden sürer.
+
+## Dil ve tema
+
+Üstte TR / EN ve tema (sistem, koyu, açık); seçim ana sayfa, okuyucu ve acil sayfasıyla ortak.
+
+## Panelin yapmadıkları
+
+- Servis kurmaz ya da kaldırmaz (harita, Kolibri); bkz. [kararlar](./decisions.md).
+- `content.conf`'u düzenlemez; içerik [içerik ekleme](./adding-content.md)'deki gibi eklenir.
+- Sayfadan birden çok kullanıcı yönetmez; ikinci bir kullanıcı yalnız `has-admin reset-password ` ile şifresi konarak eklenebilir.
diff --git a/docs/tr-TR/api.md b/docs/tr-TR/api.md
new file mode 100644
index 0000000..7523092
--- /dev/null
+++ b/docs/tr-TR/api.md
@@ -0,0 +1,178 @@
+# Panel API'si
+
+[English](../en-US/api.md) · [Tüm belgeler](../README.md)
+
+Yönetim paneli (`admin/`, Go) `/admin/api/` altında küçük bir JSON API sunar. Panel sayfası bunu kullanır; `curl` ile de çalışır. Önek `HAS_ADMIN_PREFIX` ile değiştirilebilir (varsayılan `/admin`).
+
+## Her istek için kurallar
+
+- **Oturum:** giriş `has_admin` çerezini yazar (`HttpOnly`, `SameSite=Strict`, yol `/admin`, 12 saat). Oturum çıkışta, 12 saat sonra ya da kullanıcının şifresi değişince kapanır.
+- **Bir şey değiştiren istekler** (`POST`) için:
+ - `Content-Type: application/json` ile JSON gövde gerekir; başka bir şey `415 json_required` alır;
+ - istek başka bir siteden gelmemeli: tarayıcının `Sec-Fetch-Site: cross-site` başlığı `403 cross_origin` alır;
+ - gövde en çok 64 KB olabilir.
+- Kutunun adresi (IP, port, `box.lan`) hiç denetlenmez; panel kutuya hangi adresle gelinirse gelinsin çalışır.
+- **Hatalı girişler:** bir IP'den 5 yanlış şifre (ya da kurulum kodu) sonrası her deneme bekler; bekleme 1 dakikadan başlar, her seferinde iki katına çıkar, en çok 15 dakika. Cevap `429 too_many_attempts` ve saniye cinsinden `wait` alanıdır. Başarılı giriş sayacı sıfırlar.
+- **Her cevapta** `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, `Cache-Control: no-store` ve `frame-ancestors 'none'` içeren bir `Content-Security-Policy` var.
+
+## Hatalar
+
+```json
+{"error_code": "wrong_password", "message": "Wrong password."}
+```
+
+`error_code` sabittir, programlar içindir; `message` İngilizce kısa açıklamadır. Panel sayfası her kod için seçili dilde kendi metnini gösterir (`www/home/has.js`, `admin.errors` bölümü); her kodun iki dilde de olduğuna bir test bakar.
+
+| HTTP | `error_code` | Ne zaman |
+|---|---|---|
+| 400 | `bad_request` | Gövde geçerli JSON değil ya da biçimi yanlış |
+| 400 | `invalid_name` | Kullanıcı adı 2–32 karakter değil (harf, rakam, `.`, `_`, `-`) |
+| 400 | `short_password` | Şifre 10 karakterden kısa |
+| 400 | `choose_content` | Hiçbir şey seçilmemiş (indirme, doğrulama) |
+| 400 | `not_in_list` | Seçilen bir öğe `config/content.conf`'ta yok |
+| 400 | `invalid_file` | Dosya adı düz bir `*.zim` adı değil (yol olamaz) |
+| 401 | `login_required` | Geçerli oturum yok |
+| 401 | `wrong_login` | Kullanıcı adı ya da şifre yanlış (olmayan kullanıcıda da aynı cevap) |
+| 403 | `wrong_setup_code` | İlk kurulum kodu yanlış |
+| 403 | `wrong_password` | Silmede şifre yanlış |
+| 403 | `cross_origin` | İstek başka bir siteden geldi |
+| 404 | `file_not_found` | Silinecek ya da doğrulanacak dosya diskte yok |
+| 409 | `setup_done` | İlk kurulum zaten yapılmış |
+| 409 | `busy` | Başka bir iş (indirme, doğrulama, kütüphane yenileme) çalışıyor |
+| 415 | `json_required` | Gövde JSON değil |
+| 429 | `too_many_attempts` | Çok fazla hatalı deneme; `wait` kaç saniye bekleneceğini söyler |
+| 500 | `content_unreadable` | `config/content.conf` okunamadı |
+| 500 | `server_error` | Diğer her şey |
+
+## Uçlar
+
+| Yöntem ve yol | Giriş | Ne yapar |
+|---|---|---|
+| `GET /admin/api/session` | hayır | Kurulum gerekiyor mu, kim giriş yapmış |
+| `POST /admin/api/setup` | hayır | İlk kurulum: kurulum koduyla kullanıcıyı oluşturur |
+| `POST /admin/api/login` | hayır | Giriş |
+| `POST /admin/api/logout` | hayır | Çıkış |
+| `GET /admin/api/status` | evet | Disk, ZIM dosyaları, içerik listesi, servisler |
+| `GET /admin/api/job` | evet | Çalışan ya da son iş ve çıktısı |
+| `POST /admin/api/download` | evet | Seçilenleri indirir |
+| `POST /admin/api/verify` | evet | Bütün ya da seçilen ZIM'leri doğrular |
+| `POST /admin/api/delete` | evet | Bir ya da seçilen ZIM'leri siler (şifre gerekir) |
+| `POST /admin/api/job/stop` | evet | Çalışan işi durdurur |
+
+Yanlış yöntem (ör. `GET /admin/api/delete`) `405` alır.
+
+### `GET /admin/api/session`
+
+```json
+{"setup": true, "user": ""}
+```
+
+`setup: true` henüz kullanıcı olmadığı, sayfanın kurulum formunu göstereceği anlamına gelir. Girişten sonra `user` adı taşır.
+
+### `POST /admin/api/setup`
+
+```json
+{"code": "k3v9q-…", "user": "admin", "password": "en-az-10-karakter"}
+```
+
+`200 {"user": "admin"}` ve oturum çerezi. Kod konteyner kaydında; `has-admin setup-code` de yazar. Kullanıldıktan sonra silinir. Hatalar: `wrong_setup_code`, `invalid_name`, `short_password`, `setup_done`, `too_many_attempts`.
+
+### `POST /admin/api/login`
+
+```json
+{"user": "admin", "password": "…"}
+```
+
+`200 {"user": "admin"}` ve oturum çerezi. Hatalar: `wrong_login`, `too_many_attempts`.
+
+### `POST /admin/api/logout`
+
+Gövde `{}`. `200 {"ok": true}`; oturum sunucuda da silinir.
+
+### `GET /admin/api/status`
+
+```json
+{
+ "checked": "2026-11-30T10:00:00+03:00",
+ "disk": {"total": 1000204886016, "free": 52613349376},
+ "zims": [{"name": "wikibooks_tr_all_maxi_2026-09.zim", "size": 26889216, "sha256": true}],
+ "content": [
+ {"folder": "wikibooks", "prefix": "wikibooks_tr_all_maxi", "note": "Vikikitap…", "lang": "tr",
+ "installed": "wikibooks_tr_all_maxi_2026-09.zim", "size": 26889216,
+ "latest": "wikibooks_tr_all_maxi_2026-09.zim", "latestSize": 26889216}
+ ],
+ "services": {"services": {"kiwix": {"installed": true, "label": {"tr": "Kütüphane", "en": "Library"}, "url": "/home/reader.html#library"}}}
+}
+```
+
+- `disk`: `/library` diskinin bayt cinsinden toplamı ve boşu.
+- `zims`: `/library/zims/content`'teki dosyalar; yanında `.zim.sha256` varsa `sha256: true`.
+- `content`: `config/content.conf`'un her satırı. O ön ekle başlayan dosya diskte varsa `installed` / `size`; Kiwix kataloğundan (`sizes.json`) `latest` / `latestSize`, sayfa böylece "yeni sürüm var" diyebiliyor.
+- `services`: ana sayfanın okuduğu `services.json`'un aynısı.
+
+### `GET /admin/api/job`
+
+```json
+{"name": "download", "items": ["wikibooks_tr_all_maxi"], "running": true,
+ "started": "2026-11-30T10:01:00+03:00", "exitCode": 0,
+ "lines": [">> wikibooks_tr_all_maxi_2026-09.zim indiriliyor / downloading (25 MB)", "######### 42.5%"]}
+```
+
+- `name`: `download`, `verify` ya da `library`.
+- `items`: indirmenin kapsadığı ön ekler (sayfa satırları işaretlemek için kullanır).
+- `lines`: betik çıktısının son 400 satırı. curl'ün ilerleme çubuğu yeni satır eklemez, kendi satırını yeniler. Son işin tam çıktısı `/library/has-admin/last-job.log`'da da tutulur.
+- İş bitince: `running: false`, `finished` ve `exitCode` (`0` başarılı).
+
+### `POST /admin/api/download`
+
+```json
+{"prefixes": ["wikibooks_tr_all_maxi", "nhs.uk_en_medicines"]}
+```
+
+`202 {"started": true}`. Yalnız `config/content.conf`'taki satırlar seçilebilir; bir ön ek bile bilinmiyorsa hiçbir şey başlamaz (`not_in_list`). İstekteki hiçbir metin betiğe gitmez. Pi'dekiyle aynı betik olan `scripts/download-content.sh`'yi çalıştırır.
+
+### `POST /admin/api/verify`
+
+`{}` bütün ZIM'leri, `{"files": ["a_2026-01.zim"]}` yalnız onları doğrular. `202 {"started": true}`. Hatalar: `choose_content` (boş liste), `invalid_file`, `file_not_found`, `busy`.
+
+### `POST /admin/api/delete`
+
+```json
+{"files": ["a_2026-01.zim", "b_2026-01.zim"], "password": "…"}
+```
+
+`{"file": "a_2026-01.zim", …}` tek dosya siler. Giriş yapmış kullanıcının şifresi yeniden sorulur (yanlış denemeler giriş sınırına sayılır). Bir ad bile geçersiz ya da yoksa hiçbir şey silinmez. Her `.zim` ve `.zim.sha256`'sı silinir, sonra Kiwix kütüphanesi bir kez yenilenir. `200 {"removed": ["a_2026-01.zim", "b_2026-01.zim"]}`.
+
+### `POST /admin/api/job/stop`
+
+Gövde `{}`. `200 {"stopped": true}` (çalışan iş yoksa `false`). Betik ve alt süreçleri (curl) `SIGTERM` alır; durdurulan indirme bir sonraki seferde kaldığı yerden sürer.
+
+## curl ile örnek
+
+```bash
+B=http://localhost:8080/admin/api
+curl -c jar -H 'Content-Type: application/json' -d '{"user":"admin","password":"…"}' $B/login
+curl -b jar $B/status
+curl -b jar -H 'Content-Type: application/json' -d '{"prefixes":["nhs.uk_en_medicines"]}' $B/download
+curl -b jar $B/job
+```
+
+## Komut satırı (`has-admin`)
+
+| Komut | Ne yapar |
+|---|---|
+| `has-admin` | Sunucuyu başlatır (Docker kendisi başlatır) |
+| `has-admin setup-code` | İlk kurulum kodunu yazar ya da kullanıcı zaten var der |
+| `has-admin reset-password ` | Şifreyi rastgele bir şifreyle sıfırlar ve yazar |
+| `has-admin reset-password --stdin` | İstenen şifreyi koyar: terminalde iki kez, yazılan görünmeden sorar; borudan da okur |
+
+Şifre değişince o kullanıcının açık oturumları kapanır. Docker'da: `docker compose exec has has-admin …`.
+
+| Değişken | Varsayılan | Anlamı |
+|---|---|---|
+| `HAS_ADMIN_ADDR` | `127.0.0.1:8090` | Dinleme adresi (yalnız nginx arkasından) |
+| `HAS_ADMIN_PREFIX` | `/admin` | Adres öneki |
+| `HAS_ADMIN_DATA` | `/library/has-admin` | Kullanıcılar, oturumlar, kurulum kodu, son iş kaydı |
+| `HAS_REPO` | `/opt/has` | `scripts/` ve `config/` klasörlerinin yeri |
+| `HAS_LIBRARY` | `/library` | İçerik diski |
+| `KIWIX_LIB_CMD` | `iiab-make-kiwix-lib` (Docker: `kiwix-library`) | Silme ya da indirmeden sonra Kiwix kütüphanesini yenileyen komut |
diff --git a/docs/tr-TR/decisions.md b/docs/tr-TR/decisions.md
new file mode 100644
index 0000000..4c366e0
--- /dev/null
+++ b/docs/tr-TR/decisions.md
@@ -0,0 +1,71 @@
+# Kararlar
+
+[English](../en-US/decisions.md) · [Tüm belgeler](../README.md)
+
+İşlerin neden böyle olduğu ve arkasındaki ölçümler. Ölçümler Windows'ta Docker'da alındı, Pi'de değil; yöntem ve ham sayılar Docker PR'ında ([#66](https://github.com/schematrix/HAS_Disk/pull/66)).
+
+## Yapı
+
+**Docker bu depoda ve Pi ile aynı betikleri kullanıyor.** Ayrı bir fork geride kalır. İmaj Internet-in-a-Box'ın düzenini (`/library/zims`, `/library/www/html`) koruyor; `install-homepage.sh`, `download-content.sh` ve `verify-content.sh` ikisinde de değişmeden çalışıyor.
+
+**Servisler modül (`scripts/services.d/`).** Ana sayfa harita, Kolibri ve yönetim panelini cihazda olmasalar da "Kurulu" gösteriyordu. Her servis artık kurulu olup olmadığını söyleyen küçük bir dosya; sonuç `services.json`'a yazılıyor. Dosya yoksa ana sayfa eskisi gibi davranıyor.
+
+**Panel servis kurmuyor ya da kaldırmıyor (şimdilik).** Pi'de bu, Internet-in-a-Box kurulumunu web sayfasından root olarak çalıştırmak demek (uzun sürer, internet ister, yarıda kalırsa sistemi bozabilir); Docker'da paneli uzaktan program kuran bir araca çevirir. Harita, harita PR'ından sonra tek tıkla indirme olabilir (dosyadan ibaret); Kolibri'nin ayrı bir çözümü gerekir. Açık konu.
+
+## Yönetim paneli
+
+**Go, yalnız standart kütüphane.** Aynı uçta ölçüldü (`/api/status`, 300 ZIM satırı + disk), 3.000 istek, 50 eşzamanlı:
+
+| | Go | Python |
+|---|---|---|
+| İstek/sn, 1 çekirdek | **1.918 istek/sn** | 49 istek/sn |
+| İstek/sn, 0,25 çekirdek | **437 istek/sn** | 8 istek/sn |
+| En yavaş %1, 0,25 çekirdek | **397 ms** | 11,7 sn |
+| Bellek | **2–10 MB** | 11–19 MB |
+| İmaja eklenen | **6,6 MB** | 42,3 MB |
+
+Afette kutuya çok kişi bağlanır, donanım çoğu zaman zayıftır; bu yüzden 0,25 çekirdekteki fark en önemlisi. Üçüncü taraf modül yok: denetlenecek ya da güncellenecek bir şey yok.
+
+**Varsayılan şifre yok.** Varsayılan şifre birçok kutuda hiç değiştirilmez. İlk hesap kayıttaki tek kullanımlık kodu ister; unutulan şifre web'den değil komut satırından sıfırlanır (Uptime Kuma'daki gibi).
+
+**CSRF koruması adres karşılaştırmıyor.** İlk sürüm isteğin geldiği yeri kutunun adresiyle karşılaştırıyordu; kutuya başka bir ad ya da portla gelinince (IP, `box.lan`, yönlendirilmiş port) girişi engelliyordu. Afette insanların hangi adresi kullanacağı bilinmez. Şimdi: JSON gövde zorunlu, `Sec-Fetch-Site: cross-site` reddediliyor, `SameSite=Strict` çerez.
+
+## İndirme ve içerik
+
+**wget yerine curl.** Kaldığı yerden güvenilir sürdürüyor (`-C -`, 5 deneme) ve bir bağımlılığı kaldırıyor: Alpine'deki wget 1.25.0'da o sırada düzeltmesi olmayan iki yüksek düzeyli açık vardı.
+
+**Resmî statik kiwix-tools, sürüm ve SHA-256'ya sabit.** Kiwix'in her mimari için yayımladığı dosyaların aynısı; bir dağıtımın paketine bağlı değil.
+
+**kiwix-manage kalıyor (20 MB).** `library.xml`'i o kuruyor. Bu dosyayı başka yoldan yazmak, kataloğun ve okuyucunun kullandığı kitap bilgilerini (başlık, dil) kaybettirir.
+
+**Kesin boyutlar Kiwix kataloğundan.** `content.conf`'taki ve ana sayfadaki "~" tahminler çoğu zaman yanlıştı. `catalog-sizes.sh` gerçek boyutları kurulumda, indirmeden sonra, Docker'da 6 saatte bir ve imaj derlenirken `sizes.json`'a yazıyor; internet yoksa son bilinen değerler kalıyor. Harita boyutu cihazda ölçülüyor.
+
+## Web sunucusu
+
+**Kiwix kataloğu 10 saniye önbellekte.** Kiwix kataloğu her istekte yeniden üretiyor. Önbellek ve `proxy_cache_lock` ile aynı anda gelen istekler tek üretimle karşılanıyor. Kiwix `max-age=0` gönderiyor, bunun yok sayılması gerekiyor; yoksa her istek kilitte 5 saniye bekliyordu. Kiwix kataloğu, 4 çekirdek: 8.440 → **35.569 istek/sn**.
+
+**Kiwix'e açık bağlantı tutulmuyor.** kiwix-serve az iş parçacığıyla çalışıyor, boştaki bağlantılar onları meşgul ediyordu: makaleler açık bağlantıyla 4.469 istek/sn, onsuz **6.820 istek/sn**.
+
+**Önceden sıkıştırılmış sayfalar (`gzip_static`).** nginx her sayfayı her istekte yeniden sıkıştırıyordu. Docker açılışı artık her sayfanın `.gz` kopyasını yazıyor. Tek çekirdekte ana sayfa: 962 → **21.036 istek/sn**. (`ab` HTTP/1.0 konuşuyor, nginx bunu varsayılan olarak sıkıştırmıyor; bu sayılar `wrk` ile.)
+
+**En çok 4 nginx işçisi.** Çekirdek başına bir işçi, Docker Desktop'ın sanal makinesinde 17 işçi açıyordu. Bir Wi-Fi erişim noktası için 4 fazlasıyla yetiyor; 16 çekirdekli makinede boştaki bellek 19,3 → **11,3 MiB** (4 çekirdekli Pi'de değişmez).
+
+**kiwix-serve varsayılan 4 iş parçacığında.** 2, 4, 8 ve 16 denendi: 4 çekirdekte 16 iş parçacığı aramayı ~%30 hızlandırdı ama makalelerde en yavaş %1'i iki katına çıkardı; tek çekirdekte 8 ve 16 her şeyi yavaşlattı.
+
+**util-linux-misc çıkarıldı (2,3 MB).** Yalnız `mountpoint` için vardı; yerine imajda ve Pi'de zaten olan, bağlama tablosuna bakan `findmnt --mountpoint` kullanılıyor. İmaj 76,5 → 73,8 MB.
+
+## Okuyucu
+
+**Kiwix'in çevresinde bir okuyucu sayfası.** kiwix-serve 3.8 kitap sayfalarını kendi görüntüleyicisinin içinde gösterilmek üzere sunuyor; doğrudan açılınca bağlantıları çalışmıyor. HAS okuyucusu onları kendi çubuğuyla (ana sayfa, kütüphane, kaynak, arama, rastgele) bir çerçevede gösteriyor; ana sayfadaki bağlantılar böylece işe yarar bir yerde açılıyor.
+
+**"Tüm kaynaklar" tek dilde arıyor.** Kiwix farklı dillerdeki kitaplarda birlikte aramayı reddediyor (bilerek, [libkiwix#838](https://github.com/kiwix/libkiwix/pull/838)). Okuyucu `books.filter.lang` ekliyor ve dil seçimi sunuyor; Kiwix'e öneri: [libkiwix#1434](https://github.com/kiwix/libkiwix/issues/1434).
+
+## Sayfalar
+
+**Acil sayfasının İngilizcesi asıl metni varsa onu kullanıyor.** CDC ve EPA kısımları İngilizce sayfalarından alındı; AFAD ve İstanbul İl Sağlık Müdürlüğü kısımları çeviri ve bunu belirtiyor. Hayati bilgi kaynağıyla birebir olmalı.
+
+**Lighthouse puan için değil, hata bulmak için kullanıldı.** Yüklenirken sayfanın kaymasını ve her sayfadaki `favicon.ico` 404'ünü buldu; ikisi düzeltildi. SEO ve HTTPS puanları `http://box.lan` üzerinden sunulan çevrimdışı bir kutu için geçerli değil.
+
+## CI
+
+**amd64 imajı bir kez derleniyor; tarayıcı testleri kuşak başına iki parça.** Docker ve tarayıcı testi iş akışları birleşince tarayıcı testleri beş mimarinin testini bekliyordu, bir koşu 12–13 dakika sürüyordu. Şimdi yalnız amd64 imajını bekliyor ve 14 paralel iş olarak koşuyor (GitHub Free aynı anda 20'ye izin veriyor): aynı kapsamla **~8 dakika**.
diff --git a/docs/tr-TR/guide.md b/docs/tr-TR/guide.md
new file mode 100644
index 0000000..10e583f
--- /dev/null
+++ b/docs/tr-TR/guide.md
@@ -0,0 +1,214 @@
+# Kurulum ve güncelleme rehberi
+
+[English](../en-US/guide.md) · [Tüm belgeler](../README.md)
+
+HAS_Disk iki yolla çalışır:
+
+| | Raspberry Pi (Internet-in-a-Box) | Docker |
+| --- | --- | --- |
+| Kimin için | Kutunun kendisi olacak bir Pi 5: Wi-Fi erişim noktası, harita, Kolibri | Docker çalışan herhangi bir bilgisayar: PC, dizüstü, NAS, 64 bit Pi |
+| Wi-Fi erişim noktası | Var, kurulum betiği kurar | Yok; bilgisayarın kendi ağı kullanılır |
+| Harita, Kolibri, IIAB paneli | Var | Yok |
+| Yönetim paneli (`/admin`) | IIAB paneli | HAS paneli ([yönetim paneli](./admin-panel.md)) |
+| Kurulum süresi | 30–60 dk + içerik indirme | Birkaç dakika + içerik indirme |
+
+İkisi de aynı betikleri (`scripts/`), aynı içerik listesini (`config/content.conf`) ve aynı klasör düzenini (`/library`) kullanır.
+
+Betikler her mesajı Türkçe ve İngilizce yazar (`Türkçe / English`); aşağıdaki tablolarda Türkçe kısmı var.
+
+## Raspberry Pi
+
+Donanım listesi [README](../../README.md#donanım)'de. 1–5. adımlar internet ister.
+
+### 1. İşletim sistemi
+
+[Raspberry Pi Imager](https://www.raspberrypi.com/software/) ile SD karta **Raspberry Pi OS Lite (64-bit)** yazın. Imager'ın ayarlarında SSH'yi açın, kullanıcı adı ve şifre belirleyin. SSD takılıyken Pi'yi açın ve Ethernet ile modeme bağlayın.
+
+### 2. Depoyu indirin
+
+```bash
+sudo apt update && sudo apt full-upgrade -y
+sudo apt install -y git
+git clone https://github.com/schematrix/HAS_Disk.git
+cd HAS_Disk
+chmod +x install.sh scripts/*.sh
+```
+
+Deponun eski adı `HAS_Prepper_Disk`; GitHub eski adresi yeni adrese yönlendiriyor.
+
+### 3. SSD'yi `/library`'ye bağlayın
+
+Diski `lsblk` ile bulun (genelde `nvme0n1`), sonra:
+
+```bash
+sudo ./scripts/setup-ssd.sh /dev/nvme0n1
+```
+
+| Çıktı | Anlamı |
+| --- | --- |
+| `!!! /dev/nvme0n1 ext4 değil (…). Formatlanacak ve ÜZERİNDEKİ HER ŞEY SİLİNECEK.` | Diskte başka bir dosya sistemi var. Betik formatlamadan önce sorar; diskte gerekli veri varsa hayır deyin. |
+| `Uyarı: /library boş değil, içindekiler SSD bağlanınca gizlenecek` | SD karttaki `/library` içindeki dosyalar SSD bağlıyken görünmez (silinmez). |
+| `UUID=… /library ext4 defaults,noatime,nofail 0 2` | `/etc/fstab`'a eklenen satır; `nofail` SSD takılı değilse de Pi'nin açılmasını sağlar. |
+| `Tamam: /dev/nvme0n1 -> /library` | Bağlandı, her açılışta yeniden bağlanacak. |
+| `/dev/nvme0n1 zaten /library altında bağlı` | Yapılacak bir şey yok. |
+
+### 4. Kurulum
+
+```bash
+sudo ./install.sh
+```
+
+Betik Wi-Fi adını ve şifresini (8–63 karakter) sorar, ayarları yazar ve Internet-in-a-Box'ı kurar. **Pi yeniden başlarsa ya da kurulum durursa aynı komutu yeniden çalıştırın;** kaldığı yerden sürer.
+
+| Çıktı | Anlamı |
+| --- | --- |
+| `Uyarı: /library ayrı bir diske bağlı değil. İçerikler SD karta yazılır.` | 3. adım atlanmış. Devam edilebilir (sorar), ama büyük içerik SD kartı doldurur. |
+| `Ayarlar yazıldı: /etc/iiab/local_vars.yml` | Wi-Fi adı, şifresi ve `config/iiab-overrides.yml`'deki ayarlar yazıldı. |
+| `Pi yeniden başlarsa tekrar çalıştır: sudo ./install.sh` | Kurulum sırasında beklenen bir durum. |
+| `İçerikler henüz indirilmediyse ZIM uyarıları normaldir` | Sondaki sağlık kontrolü eksik ZIM dosyalarından yakınır; 5. adımdan önce bu normal. |
+
+Internet-in-a-Box kendisi üç şey sorar: `iiab-admin` kullanıcısı için şifre (`http:///admin` için, bir yere yazın), bir şey ters giderse komutu yeniden çalıştıracağınızı onaylamak için bir tuş ve sonda yeniden başlatmak için Enter. Yeniden başladıktan sonra `sudo ./install.sh`'yi bir kez daha çalıştırın; biten kısmı atlar, ana sayfayı kurar.
+
+### 5. İçerik indirme
+
+Ne indirileceğini `config/content.conf`'ta seçin ([içerik ekleme](./adding-content.md)), sonra:
+
+```bash
+sudo ./scripts/download-content.sh
+```
+
+Varsayılan liste yaklaşık 160 GB ister, saatler sürebilir. İndirme yarıda kalırsa betiği yeniden çalıştırın, kaldığı yerden sürer. Her satır için Kiwix kataloğunda en yeni sürüme bakar, boş yere bakar (5 GB boş bırakır, `RESERVE_GB`), kaldığı yerden indirir ve SHA-256 değerini doğrular.
+
+| Satır başı | Anlamı |
+| --- | --- |
+| `>> Kiwix kataloğu alınıyor` / `>> … indiriliyor (… MB)` | İş başlıyor: katalog sorgusu ya da boyutuyla bir indirme. Ardından ilerleme çubuğu gelir. |
+| `== … zaten var` | O sürüm diskte zaten var, bir şey indirilmedi. |
+| `sha256 hesaplanıyor` / `sha256 doğru` | İndirilen dosya yayıncının sağlama toplamıyla aynı. |
+| `Uyarı: … için .sha256 yayımlanmamış, doğrulanmadan kabul edildi` | Kiwix bu dosya için sağlama toplamı yayımlamamış; dosya tutuldu ama doğrulanmadı. |
+| `OK … tamamlandı` | İndirildi, doğrulandı ve yerine kondu. |
+| `-- eski sürüm siliniyor …` | Yeni sürüm geldi; eski dosya ve `.sha256`'sı silindi. |
+| `-- eski yarım indirme siliniyor …` | Eski bir sürümün yarım kalmış indirmesi silindi. |
+| `!! … bulunamadı` | `content.conf`'taki ad değişmiş ya da kaldırılmış. [download.kiwix.org/zim](https://download.kiwix.org/zim/)'e bakın. |
+| `!! … için yer yok: gerekli … MB + 5 GB pay, boş … MB` | Atlandı. Yer açın ya da listeden çıkarın. |
+| `!! … indirilemedi (tekrar çalıştır)` | Ağ sorunu. Betiği yeniden çalıştırın. |
+| `!! … sha256 uyuşmuyor, bozuk dosya silindi` | Dosya bozuk inmiş, silindi. Betiği yeniden çalıştırın. |
+| `!! Katalog alınamadı, klasör listesine düşülüyor` | Katalog cevap vermedi; betik dosyaları indirme klasörlerinden buluyor. |
+| `>> Kiwix kütüphanesi güncelleniyor` | Kütüphane yeniden kuruluyor, yeni kitaplar yeniden başlatmadan görünür. |
+
+Her şey başarılıysa çıkış kodu `0`, en az bir öğe başarısızsa `1` (diğerleri yine biter).
+
+`/library` için SSD ayarlanmış ama bağlı değilse betik indirmeden önce durur: SSD'yi takın, `sudo mount /library` çalıştırın ve yeniden deneyin.
+
+### 6. Harita
+
+`http:///admin` adresini açın (kullanıcı `iiab-admin`), **Install Content** menüsünün harita bölümünden bölgeleri seçin.
+
+### 7. Kullanım
+
+Oluşturduğunuz Wi-Fi ağına bağlanın ve **** adresini açın.
+
+### Kutuyu denetleme
+
+```bash
+./scripts/status.sh
+```
+
+Yalnız okur, `sudo` istemez. Her satır `OK` (sorun yok) ya da `!!` (sorun, yanında çözümü) ile başlar: boş yer, `/library` diski, web / Kiwix / erişim noktası / DHCP servisleri, erişim noktası köprüsü, eksik ya da yarım ZIM'ler, Kiwix kütüphanesinde olmayan ZIM'ler, CPU sıcaklığı ve düşük voltaj. Son satır `Her şey yolunda` ya da `N sorun bulundu` der; çıkış kodu `0` ya da `1`, cron'dan da çalışabilir. Çözümler [sorun giderme](./troubleshooting.md)'de.
+
+```bash
+sudo ./scripts/disk-health.sh
+```
+
+Diski ve güç kaynağını denetler (kendiliğinden de 6 saatte bir). `OK disk ve güç sağlıklı` ya da `!!` satırları; aynı uyarılar ana sayfanın üstünde kırmızı görünür.
+
+```bash
+./scripts/verify-content.sh # /library/zims/content
+./scripts/verify-content.sh /media/yedek # başka bir klasör ya da tek bir .zim
+```
+
+Her ZIM'i internetsiz, kaydedilmiş `.zim.sha256` ile (yoksa `zimcheck` ile: `sudo apt install zim-tools`) denetler. Her dosya için `>> Doğrulanıyor: …`, hata için `!!` ve sonda `N ZIM kontrol edildi, M hata`. Çıkış kodu `0` hepsi sağlam, `1` bir denetim başarısız, `2` denetim başlayamadı (ör. tamamlanmış ZIM yok).
+
+## Docker
+
+Compose v2'li Docker gerekir (`docker compose version`). Mimariler: `linux/amd64`, `linux/arm64`, `linux/arm/v7`, `linux/arm/v6`, `linux/386`.
+
+### Başlatma
+
+```bash
+git clone https://github.com/schematrix/HAS_Disk.git && cd HAS_Disk
+docker compose up -d --build
+```
+
+`--build` imajı sizin makinenizde derler (birkaç dakika). İmaj `ghcr.io/schematrix/has-disk`'te yayımlanınca `docker compose up -d` onu indirir.
+
+Ana sayfa: `http://:8080/home/`. İçerik `compose.yaml`'ın yanındaki `./library` klasörüne gider.
+
+| Ayar | Örnek | Ne yapar |
+| --- | --- | --- |
+| `HAS_PORT` | `HAS_PORT=80 docker compose up -d` | Makinedeki port (varsayılan 8080). |
+| `HAS_LIBRARY` | `HAS_LIBRARY=/mnt/ssd/library docker compose up -d` | İçeriğin ve panel verisinin tutulduğu yer (varsayılan `./library`). |
+| `NGINX_WORKERS` | `compose.yaml`'da `environment:` altında | nginx işçi sayısı; varsayılan çekirdek sayısı, en çok 4. |
+
+Bunlar `compose.yaml`'ın yanındaki `.env` dosyasına da yazılabilir.
+
+### İlk giriş
+
+```bash
+docker compose logs has | grep "setup code"
+```
+
+```
+2026/11/30 10:00:00 İlk kurulum: /admin/ adresinde kullanıcı oluşturun. Kurulum kodu / first-run setup code: k3v9q-…
+```
+
+`http://:8080/admin/` adresini açın, kodu girin, kullanıcı adı ve şifre belirleyin. Kod bir kez çalışır, sonra silinir. `docker compose exec has has-admin setup-code` kodu yeniden yazar (ya da kullanıcı zaten var der). Ayrıntı: [yönetim paneli](./admin-panel.md).
+
+### İçerik indirme
+
+Panelden (seçin, **Seçilenleri indir**) ya da:
+
+```bash
+docker compose exec has /opt/has/scripts/download-content.sh
+```
+
+Çıktı Pi'dekiyle aynı (yukarıdaki tablo). Kiwix yeni kitapları yeniden başlatmadan görür.
+
+### Denetleme
+
+```bash
+docker compose ps # STATUS: Up … (healthy)
+docker compose exec has /opt/has/scripts/verify-content.sh
+docker compose logs has # nginx, Kiwix ve panel mesajları
+```
+
+`(healthy)` ana sayfanın konteyner içinde cevap verdiği anlamına gelir. `(unhealthy)` birkaç dakikadır cevap vermediği anlamına gelir; kayda bakın.
+
+## Güncelleme
+
+| Ne | Raspberry Pi | Docker |
+| --- | --- | --- |
+| HAS (ana sayfa, betikler, panel) | `cd HAS_Disk && git pull && sudo ./scripts/install-homepage.sh` | `git pull && docker compose up -d --build` (yayımlanan imajla: `docker compose pull && docker compose up -d`) |
+| İçerik | `sudo ./scripts/download-content.sh` | `docker compose exec has /opt/has/scripts/download-content.sh` ya da panel |
+| Internet-in-a-Box | [Internet-in-a-Box belgelerine](https://wiki.iiab.io/go/FAQ) bakın | — |
+
+İçerik güncellemesi ilk indirmeyle aynı betikle yapılır: `== … zaten var` güncel demek; yeni sürüm indirilip doğrulanınca eski dosya silinir (`-- eski sürüm siliniyor`). Katalogda daha yeni dosya varsa panel "yeni sürüm var" gösterir.
+
+Docker'da güncellemede konteyner yenilenir, ama `./library` içindeki her şey kalır: ZIM dosyaları, kullanıcılar ve oturumlar (`library/has-admin`).
+
+## Yedekleme ve taşıma
+
+- Kutunun tuttuğu her şey `/library` altında (Docker'da `HAS_LIBRARY` klasörü): `zims/content/` (ZIM dosyaları ve `.zim.sha256`'ları), `has-admin/` (panel kullanıcıları), `www/html/home/` (ana sayfa, açılışta yeniden yazılır).
+- Her `.zim`'i `.zim.sha256`'sıyla birlikte kopyalayın, sonra kopyayı internetsiz denetleyin: `./scripts/verify-content.sh /kopyanın/yolu`.
+- Docker kutusunu taşımak için durdurun (`docker compose down`), `library` klasörünü kopyalayın, yeni makinede başlatın.
+
+## Kaldırma
+
+- Docker: `docker compose down` konteyneri durdurur ve kaldırır; `./library` kalır. İçeriği de silmek için o klasörü silin.
+- Pi, eski ana sayfaya dönüş: `sudo cp /library/www/html/home/index.html.iiab-original /library/www/html/home/index.html`
+
+## Kaynaklar
+
+- [Internet-in-a-Box](https://github.com/iiab/iiab) ve [SSS](https://wiki.iiab.io/go/FAQ)
+- [Kiwix](https://kiwix.org), [kiwix-serve](https://wiki.kiwix.org/wiki/Kiwix-serve), ZIM dosyaları: [download.kiwix.org/zim](https://download.kiwix.org/zim/)
+- [Raspberry Pi Imager](https://www.raspberrypi.com/software/)
+- [Docker Compose](https://docs.docker.com/compose/)
diff --git a/docs/tr-TR/security.md b/docs/tr-TR/security.md
new file mode 100644
index 0000000..91c6431
--- /dev/null
+++ b/docs/tr-TR/security.md
@@ -0,0 +1,64 @@
+# Güvenlik
+
+[English](../en-US/security.md) · [Tüm belgeler](../README.md)
+
+## Kutu ne için
+
+Kutu, kendi ağındaki insanlara içerik sunar (Pi'nin Wi-Fi erişim noktası ya da Docker makinesinin yerel ağı). **İnternetten erişilmek için tasarlanmadı.** Düz HTTP sunar: çevrimdışı bir kutunun `box.lan` için kullanabileceği bir sertifika yok.
+
+| Risk | Ne yapılıyor |
+|---|---|
+| Ağdaki biri içeriği değiştirir ya da siler | Yalnız yönetim paneli yapabilir, o da girişten sonra; silme şifreyi yeniden sorar |
+| Şifre tahmini | Bir IP'den 5 yanlış denemeden sonra 1 dakikadan 15 dakikaya kadar bekleme |
+| Başka bir sitedeki sayfa tarayıcıya panelde iş yaptırır (CSRF) | JSON gövde zorunlu, `Sec-Fetch-Site: cross-site` reddedilir, `SameSite=Strict` çerez |
+| Panel başka bir sitenin içinde gösterilir (clickjacking) | `X-Frame-Options: DENY`, CSP `frame-ancestors 'none'` |
+| Şifrelerin diskten sızması | PBKDF2-SHA256, 600.000 tur ve rastgele tuz; oturumlar çerezin kendisi değil özeti olarak saklanır |
+| Sunulmaması gereken dosyaların okunması | Web kökü `/library/www/html`; ZIM dosyaları, `library.xml` ve panel verisi bunun dışında; `../` yolları reddedilir |
+| Bir servisteki hatanın sistemi ele geçirmesi | Docker'da: panel dışında root süreç yok, salt okunur kök dosya sistemi, `no-new-privileges`, yalnız `SETUID`, `SETGID`, `DAC_OVERRIDE` yetkileri |
+
+**Wi-Fi:** panel şifresi ağda şifrelenmeden gider. Erişim noktasına şifre koyun (WPA2), trafiği yalnız ağa katılanlar görebilsin; modemde 8080 portunu dışarı açmayın.
+
+## Hesaplar
+
+- Varsayılan şifre yok. İlk hesap, kayda yazılan tek kullanımlık kurulum koduyla açılır; kod dosyasını yalnız root okuyabilir (`600`), kullanıldıktan sonra silinir.
+- Panel verisi `/library/has-admin`'de (`700`): `users.json`, `sessions.json` (ikisi de `600`), kurulum kodu ve son iş kaydı.
+- Oturum 12 saat sürer, çıkışta ve şifre değişince kapanır. Şifre sıfırlama web sayfasından değil, makineye erişimle yapılır (`has-admin reset-password`).
+
+## Ne nerede çalışıyor (Docker)
+
+| Süreç | Kullanıcı | Dinlediği yer |
+|---|---|---|
+| nginx | `has` (root değil) | `0.0.0.0:8080`, dışarıya açık tek port |
+| kiwix-serve | `has` | `127.0.0.1:8081`, nginx arkasında |
+| has-admin (panel) | root (indirme betiği `/library`'ye yazar) | `127.0.0.1:8090`, nginx arkasında |
+
+Panel durursa yalnız panel yeniden başlar; ana sayfa ve Kiwix açık kalır.
+
+## Kutu neyi kaydeder
+
+- **Erişim kaydı yok:** nginx kimin hangi sayfayı açtığını kaydetmez (`access_log off`).
+- Panel son işin çıktısını (`last-job.log`) ve oturumları tutar; ziyaretçi verisi yok.
+- Docker'ın kendi kaydında açılış mesajları ve hatalar var (`docker compose logs has`).
+
+## Kutu ne zaman dışarı bağlanır
+
+Yalnız içerik için ve yalnız internet varsa:
+
+| Ne zaman | Nereye | Neden |
+|---|---|---|
+| İçerik indirirken (elle ya da panelden) | `library.kiwix.org` (katalog), `download.kiwix.org` ve yansıları | En yeni sürümü bulmak, indirmek, SHA-256 değerini almak |
+| Açılışta ve 6 saatte bir (Docker), kurulumda (Pi) | `library.kiwix.org` | Kesin boyutları tazelemek (`sizes.json`); internet yoksa bir şey gönderilmez, eski dosya kalır |
+| İmaj derlenirken | `download.kiwix.org`, Alpine ve Go paket sunucuları, `library.kiwix.org` | Yalnız derlemede |
+
+Telemetri yok, güncelleme denetimi yok, başka bir adres yok. İnternet yokken her şey çalışmaya devam eder.
+
+## Tedarik zinciri
+
+- Taban imaj sürüme sabit (`alpine:3.24.4`, `golang:1.27.3-alpine3.24`); kiwix-tools sürüme ve mimari başına SHA-256'ya sabit.
+- Her derlemede `apk upgrade` Alpine'in güvenlik düzeltmelerini alır; imaj haftada bir yeniden derlenir.
+- Panel yalnız Go'nun standart kütüphanesini kullanır (üçüncü taraf modül yok).
+- GitHub Actions sürüm etiketlerine sabit; imaj yalnız `main`'den ya da `v*` etiketinden, bütün testler geçtikten sonra yayımlanır.
+
+## Sorun bildirme
+
+Depoda issue açın. Herkese açık olmaması gereken bir şeyse önce bakımcıya GitHub üzerinden doğrudan yazın.
diff --git a/docs/tr-TR/testing.md b/docs/tr-TR/testing.md
new file mode 100644
index 0000000..cd5c8f0
--- /dev/null
+++ b/docs/tr-TR/testing.md
@@ -0,0 +1,84 @@
+# Testler
+
+[English](../en-US/testing.md) · [Tüm belgeler](../README.md)
+
+Üç katman var; hepsi kendi makinenizde çalışır, CI her push'ta hepsini çalıştırır:
+
+| Katman | Neye bakar | Nerede |
+|---|---|---|
+| İmaj testi | Konteynerin bütünü: açılış, ana sayfa, Kiwix, panel, kalıcılık, güvenlik ayarları | `docker/test.sh` |
+| Tarayıcı testleri | Sayfalar gerçek tarayıcılarda: masaüstü, telefon, tablet; eski ve yeni sürümler | `e2e/` |
+| Kod denetimleri | Go testleri, ShellCheck, hadolint, actionlint, Prettier | `admin/`, betikler, iş akışları |
+
+## İmaj testi (`docker/test.sh`)
+
+```bash
+docker build -f docker/Dockerfile -t has-disk:test .
+docker/test.sh has-disk:test # yaklaşık 2 dk
+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 (yavaş)
+```
+
+Konteyneri `compose.yaml`'daki güvenlik ayarlarıyla (salt okunur kök, yetkilerin çoğu kapalı, `no-new-privileges`) 18090 portunda açar ve bölüm bölüm denetler: imaj bilgileri, açılış, web sunucusu (yönlendirmeler, başlıklar, gzip, sunulmaması gereken dosyalar, yol aşımı), ilk kurulum, CSRF ve hatalı girdi, indirme ve doğrulama (`--download`), yeniden başlatma ve kalıcılık, komut satırı (`has-admin`), güvenlik (root süreç yok, yalnız 8080 açık, yetki yok), bellek ve kapanış süresi.
+
+```
+## web
+ok - / → /home/
+ok - gzip_static: açılınca aynı / unpacks to the same page: /home/
+FAIL - …
+…
+# boyut / size: 74 MB · bellek / memory: 11.3MiB · kiwix-tools 3.8.2 nginx version: nginx/1.30.8 alpine 3.24.4
+# sonuç / result: 153 ok, 0 hata / failed
+```
+
+Her satır `ok` ya da `FAIL` ve neyin denendiği (Türkçe ve İngilizce). Hiçbir şey düşmediyse çıkış kodu `0`. Bir şey düşerse konteyner kaydının son 80 satırı yazılır; `HAS_TEST_LOGS=` kaydın tamamını saklar.
+
+| Değişken | Varsayılan | Anlamı |
+|---|---|---|
+| `HAS_TEST_PORT` | `18090` | Test konteynerinin portu |
+| `HAS_TEST_TIMEOUT` | `240` | Açılış için beklenecek saniye (QEMU daha uzun ister) |
+| `HAS_TEST_LOGS` | — | Konteyner kaydının kopyalanacağı dosya |
+
+## Tarayıcı testleri (`e2e/`)
+
+Resmî Playwright Docker imajında çalışır; makinenize bir şey kurulmaz.
+
+```bash
+docker build -f docker/Dockerfile -t has-disk:test .
+e2e/prepare.sh has-disk:test # kendi ağında konteyner, bir hesap ve iki küçük ZIM (internet)
+e2e/run.sh # en güncel tarayıcılar, bütün cihazlar
+e2e/run.sh 1.22.2 focal # Chrome 102, Firefox 99, Safari 15.4
+e2e/run.sh "" noble --project=iphone-se tests/reader.spec.js # tek cihaz, tek dosya
+e2e/run.sh "" noble --shard=1/2 # testlerin yarısı (CI'daki gibi)
+```
+
+- **Cihazlar:** masaüstünde Chromium, Firefox, WebKit; Android telefon (Pixel, Galaxy S9+) ve tablet (Galaxy Tab S4); iPhone SE (320 px, en dar), büyük iPhone, iPad Mini; telefon genişliğinde Firefox.
+- **Tarayıcı kuşakları** (`.github/workflows/docker.yml`): en güncel, 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. Eski Playwright sürümleri `e2e/package.json`'da takma adla kilitli; `run.sh` doğrusunu bağlar.
+- **Dosyalar:** `home.spec.js` (ana sayfa, acil sayfası), `reader.spec.js` (HAS okuyucusu), `admin.spec.js` (panel), `a11y.spec.js` (axe-core, WCAG 2.2 A/AA, açık ve koyu tema; klavye), `browsers.spec.js`.
+- Testler sırayla koşar (tek sunucu, ortak iş kuyruğu ve giriş sınırı). Gerçek sunucuya hiç yanlış şifre gönderilmez; panelin hata metinleri taklit edilen sunucu cevabıyla denenir.
+- CI'da düşen test bir kez yeniden denenir; yalnız ikinci denemede geçen test **flaky** olarak raporlanır, koşu özeti bunu gösterir. Flaky testleri hata sayın.
+- Sonuçlar: `e2e/playwright-report/` (HTML); düşen testler için `e2e/test-results/` içinde ekran görüntüsü ve iz dosyası (`npx playwright show-trace trace.zip`).
+
+## Kod denetimleri
+
+```bash
+docker run --rm -v "$PWD/admin:/src" -w /src golang:1.27.3-alpine3.24 sh -c 'gofmt -l . ; go vet ./... && go test ./...'
+docker run --rm -v "$PWD:/mnt" -w /mnt koalaman/shellcheck:v0.10.0 --severity=warning $(git ls-files '*.sh')
+docker run --rm -i hadolint/hadolint:v2.15.1 < docker/Dockerfile
+docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:1.7.7
+npx prettier@3.10.0 --check .
+```
+
+Docker derlemesi de `go vet` ve `go test` çalıştırır; düşerlerse imaj derlenmez.
+
+## CI (`.github/workflows/docker.yml`)
+
+Her dala push'ta, PR'larda, haftada bir ve elle:
+
+1. **Dockerfile + compose:** hadolint ve `docker compose config`.
+2. **linux/amd64 derleme:** amd64 imajını bir kez derler, artifact olarak sonraki işlere verir.
+3. **Mimari başına test:** `docker/test.sh` amd64'te (`--download` ve compose ile açılışla), arm64'te (ARM makinesinde), arm/v7 ve arm/v6'da (QEMU) ve 386'da. Her iş adında mimari, işletim sistemi ve Docker sürümü olan bir rapor bırakır (`environment.txt`, `packages.txt`, `test.txt`, konteyner kaydı).
+4. **E2E:** yedi tarayıcı kuşağı × iki parça = 14 iş; yalnız amd64 imajını bekler.
+5. **Yayın:** yalnız `main`'den ya da `v*` etiketinden ve her şey geçince: çok mimarili imajı `ghcr.io`'ya gönderir.
+
+Bir koşu yaklaşık 8 dakika sürer.
diff --git a/docs/tr-TR/troubleshooting.md b/docs/tr-TR/troubleshooting.md
new file mode 100644
index 0000000..1aee4a6
--- /dev/null
+++ b/docs/tr-TR/troubleshooting.md
@@ -0,0 +1,66 @@
+# Sorun giderme
+
+[English](../en-US/troubleshooting.md) · [Tüm belgeler](../README.md)
+
+Pi'de sağlık kontrolüyle (`./scripts/status.sh`), Docker'da konteynerin durumuyla (`docker compose ps`, `docker compose logs has`) başlayın. Çıktılarının anlamı [rehberde](./guide.md#kutuyu-denetleme).
+
+## Docker
+
+**Sayfa bilgisayarda açılıyor, telefonda açılmıyor.**
+Linux'ta başka bir şey gerekmez: Docker portu güvenlik duvarına kendisi ekler. Windows ve macOS'ta işletim sisteminin güvenlik duvarı Docker Desktop'a bir kez izin vermeli:
+- Windows: Windows Güvenliği → Güvenlik duvarı ve ağ koruması → Bir uygulamanın güvenlik duvarından geçmesine izin ver → **Docker Desktop Backend** için **Özel**'i işaretleyin; ev ağı Ayarlar → Ağ ve İnternet altında "Özel" olmalı.
+- macOS: Sistem Ayarları → Ağ → Güvenlik Duvarı → Seçenekler → Docker için gelen bağlantılara izin verin.
+- Misafir ağlar ve "istemci yalıtımı" açık Wi-Fi genişleticiler cihazların birbirini görmesine izin vermez.
+
+**`docker compose up -d` imajı indiremediğini söylüyor.**
+İmaj, Docker işi birleştirildikten sonra yayımlanacak. O zamana kadar derleyin: `docker compose up -d --build`.
+
+**Konteyner sürekli yeniden başlıyor ya da `(unhealthy)`.**
+`docker compose logs has` nedenini gösterir. kiwix-serve ya da nginx durursa konteyner durur ve Docker yeniden başlatır; duran panel kendiliğinden yeniden başlar, neden o olmaz.
+
+**386 imajının ağı yok.**
+Yalnız Docker 29.4.2'de: o sürümün güvenlik profili 32 bit x86'nın ağ çağrısını kapatıyordu ([moby/profiles#21](https://github.com/moby/profiles/pull/21)). Docker'ı güncelleyin (29.4.3 ya da sonrası).
+
+**8080 portu dolu.** `HAS_PORT=8081 docker compose up -d`.
+
+## Yönetim paneli
+
+**Şifremi unuttum.** `docker compose exec has has-admin reset-password ` (rastgele) ya da `… --stdin` (kendi şifreniz). Bkz. [yönetim paneli](./admin-panel.md#şifreyi-unuttum).
+
+**"Çok fazla deneme. N sn sonra tekrar deneyin."** Bu cihazdan 5 yanlış şifre; yazan süre kadar bekleyin (en çok 15 dakika). Başarılı giriş sayacı sıfırlar.
+
+**"Başka bir iş çalışıyor; bitmesini bekleyin."** Aynı anda tek indirme, doğrulama ya da kütüphane yenileme çalışır. Bekleyin ya da İş bölümünde **Durdur**'a basın.
+
+**İndirme başarısız (satırda "İndirilemedi").** İş bölümünde `!!` ile başlayan satır var; anlamları [rehberde](./guide.md). İndirmeyi yeniden başlatmak kaldığı yerden sürdürür.
+
+**Kurulum kodu kayıtta yok.** Kullanıcı zaten var (`docker compose exec has has-admin setup-code` bunu söyler). O kullanıcının şifresini sıfırlayın.
+
+## Ana sayfa ve okuyucu
+
+**Bir kitap listede ama "Henüz yüklenmedi" yazıyor.** ZIM'i cihazda yok ya da Kiwix kataloğundaki adı değişmiş. Panelden ya da `download-content.sh` ile indirin.
+
+**Eski bir tarayıcıda kitaplık sayfası boş kalıyor.** Kiwix'in kitaplık sayfası eski tarayıcılarda (ör. Chrome 102, Safari 15) listeyi çizemiyor; birkaç saniye sonra okuyucu cihazdaki kitapları kendisi listeler.
+
+**"Tüm kaynaklar" araması tek dilde sonuç gösteriyor.** Kiwix farklı dillerdeki kitaplarda birlikte arama yapmaz; okuyucu "Tüm kaynaklar"ın yanında seçilen dilde arar ([kiwix/libkiwix#1434](https://github.com/kiwix/libkiwix/issues/1434)).
+
+**Kitap koleksiyonları (Su Arıtma, Düğümler, Gıda, Afet Sonrası, Tıp) hep yükleniyor.** Kitap listelerini tarayıcının yerel veritabanında tutarlar. iPhone Safari gizli sekmeleri ve bağlanma (captive portal) penceresi bunu engeller; normal bir Safari sekmesinde açın.
+
+**Yeni indirilen kitap görünmüyor.** Kiwix kataloğu 10 saniye önbellekte; sayfayı yenileyin. Yine görünmüyorsa kütüphaneyi yenileyin: Pi `sudo iiab-make-kiwix-lib`, Docker `docker compose exec has kiwix-library`.
+
+## Raspberry Pi
+
+**Kurulumdan sonra `ssh kullanici@hostname.local` çalışmıyor.** Internet-in-a-Box Pi'nin adını `box` yapar: `ssh kullanici@box.local` ya da IP adresi (bilgisayarda `arp -a` ya da modemin cihaz listesi).
+
+**Erişim noktası görünmüyor.** Ethernet ile bağlanın, `sudo iiab-diagnostics`'e bakın ve kurulumun bittiğinden emin olun: `/etc/iiab/install-flags/iiab-complete` olmalı.
+
+**Kayıtta "invalid WPA passphrase length".** Wi-Fi şifresi 8–63 karakter olmalı. `/etc/iiab/local_vars.yml`'deki `hostapd_password` ile `/etc/hostapd/hostapd.conf`'taki `wpa_passphrase`'i düzeltin, sonra `sudo systemctl restart hostapd`.
+
+**Cihazlar "şifre yanlış" diyor ya da birkaç saniyede kopuyor.** Genelde erişim noktası köprüsü `br0` kapalıdır (`ip -br addr show br0`, `bridge link`). Çözüm [README](../../README.md#sorun-giderme)'de.
+
+**Harita indirmeleri "connection reset by peer" ile düşüyor.** Harita sunucusu bazı ülkelerde (ör. Türkiye) engelli. README'de indirme için Cloudflare WARP'ın nasıl kullanılacağı var.
+
+**Disk dolu ya da salt okunur.** Ana sayfanın üstündeki kırmızı uyarı `disk-health.sh`'den gelir. `sudo ./scripts/disk-health.sh` ile bakın; listeden içerik çıkarın ya da daha büyük disk kullanın; salt okunur yeniden bağlanma genelde dosya sistemi hatası demektir (disk bağlı değilken `fsck` çalıştırın).
+
+**Düşük voltaj uyarısı.** 5V/5A güç kaynağı kullanın; zayıf kaynak ya da akü diski bozabilir.
+
+**Eski ana sayfaya dönüş:** `sudo cp /library/www/html/home/index.html.iiab-original /library/www/html/home/index.html`
diff --git a/e2e/README.md b/e2e/README.md
new file mode 100644
index 0000000..b39297a
--- /dev/null
+++ b/e2e/README.md
@@ -0,0 +1,33 @@
+# Tarayıcı testleri / Browser tests (Playwright)
+
+## Türkçe
+
+Docker imajını açıp ana sayfayı, HAS okuyucusunu, acil sayfasını ve yönetim panelini gerçek tarayıcılarda dener.
+
+**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/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.
+
+```sh
+docker build -f docker/Dockerfile -t has-disk:test .
+e2e/prepare.sh has-disk:test # konteyner, hesap, iki küçük ZIM (internet ister)
+e2e/run.sh # en güncel tarayıcılar
+e2e/run.sh 1.22.2 focal # Chrome 102, Firefox 99, Safari 15.4
+e2e/run.sh "" noble --project=iphone-se
+```
+
+Makineye tarayıcı kurulmaz; testler resmî Playwright Docker imajında çalışır. Testler sırayla koşar (tek sunucu, ortak iş kuyruğu ve giriş sınırı). Yanlış şifre gerçek sunucuda denenmez (ortak giriş sınırını tüketir), panelin hata metni sunucu cevabı taklit edilerek denenir; sunucu tarafı `docker/test.sh`'de.
+
+## English
+
+Starts the Docker image and tests the homepage, the HAS reader, the emergency page and the admin panel in real browsers.
+
+**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/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.
+
+Nothing is installed on the machine; the tests run in the official Playwright Docker image. Tests run one at a time (one server with a shared job queue and login limit). A wrong password is never sent to the real server (it would use up the shared login limit); the panel's error text is tested with a mocked server answer, the server side is in `docker/test.sh`.
diff --git a/e2e/package-lock.json b/e2e/package-lock.json
new file mode 100644
index 0000000..a0d2766
--- /dev/null
+++ b/e2e/package-lock.json
@@ -0,0 +1,353 @@
+{
+ "name": "has-e2e",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "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",
+ "playwright-1.46.1": "npm:@playwright/test@1.46.1",
+ "playwright-1.48.2": "npm:@playwright/test@1.48.2",
+ "playwright-1.54.2": "npm:@playwright/test@1.54.2"
+ }
+ },
+ "node_modules/@playwright/test": {
+ "version": "1.65.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz",
+ "integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright": "1.65.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.11",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz",
+ "integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "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",
+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/playwright": {
+ "version": "1.65.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
+ "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.65.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/playwright-1.22.2": {
+ "name": "@playwright/test",
+ "version": "1.22.2",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.22.2.tgz",
+ "integrity": "sha512-cCl96BEBGPtptFz7C2FOSN3PrTnJ3rPpENe+gYCMx4GNNDlN4tmo2D89y13feGKTMMAIVrXfSQ/UmaQKLy1XLA==",
+ "deprecated": "Please update to the latest version of Playwright to test up-to-date browsers.",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@types/node": "*",
+ "playwright-core": "1.22.2"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/playwright-1.22.2/node_modules/playwright-core": {
+ "version": "1.22.2",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.22.2.tgz",
+ "integrity": "sha512-w/hc/Ld0RM4pmsNeE6aL/fPNWw8BWit2tg+TfqJ3+p59c6s3B6C8mXvXrIPmfQEobkcFDc+4KirNzOQ+uBSP1Q==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/playwright-1.29.2": {
+ "name": "@playwright/test",
+ "version": "1.29.2",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.29.2.tgz",
+ "integrity": "sha512-+3/GPwOgcoF0xLz/opTnahel1/y42PdcgZ4hs+BZGIUjtmEFSXGg+nFoaH3NSmuc7a6GSFwXDJ5L7VXpqzigNg==",
+ "deprecated": "Please update to the latest version of Playwright to test up-to-date browsers.",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@types/node": "*",
+ "playwright-core": "1.29.2"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/playwright-1.29.2/node_modules/playwright-core": {
+ "version": "1.29.2",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.29.2.tgz",
+ "integrity": "sha512-94QXm4PMgFoHAhlCuoWyaBYKb92yOcGVHdQLoxQ7Wjlc7Flg4aC/jbFW7xMR52OfXMVkWicue4WXE7QEegbIRA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/playwright-1.37.1": {
+ "name": "@playwright/test",
+ "version": "1.37.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.37.1.tgz",
+ "integrity": "sha512-bq9zTli3vWJo8S3LwB91U0qDNQDpEXnw7knhxLM0nwDvexQAwx9tO8iKDZSqqneVq+URd/WIoz+BALMqUTgdSg==",
+ "deprecated": "Please update to the latest version of Playwright to test up-to-date browsers.",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@types/node": "*",
+ "playwright-core": "1.37.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.2"
+ }
+ },
+ "node_modules/playwright-1.37.1/node_modules/playwright-core": {
+ "version": "1.37.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.37.1.tgz",
+ "integrity": "sha512-17EuQxlSIYCmEMwzMqusJ2ztDgJePjrbttaefgdsiqeLWidjYz9BxXaTaZWxH1J95SHGk6tjE+dwgWILJoUZfA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/playwright-1.46.1": {
+ "name": "@playwright/test",
+ "version": "1.46.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.46.1.tgz",
+ "integrity": "sha512-Fq6SwLujA/DOIvNC2EL/SojJnkKf/rAwJ//APpJJHRyMi1PdKrY3Az+4XNQ51N4RTbItbIByQ0jgd1tayq1aeA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright": "1.46.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright-1.46.1/node_modules/playwright": {
+ "version": "1.46.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.46.1.tgz",
+ "integrity": "sha512-oPcr1yqoXLCkgKtD5eNUPLiN40rYEM39odNpIb6VE6S7/15gJmA1NzVv6zJYusV0e7tzvkU/utBFNa/Kpxmwng==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.46.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.2"
+ }
+ },
+ "node_modules/playwright-1.46.1/node_modules/playwright-core": {
+ "version": "1.46.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.46.1.tgz",
+ "integrity": "sha512-h9LqIQaAv+CYvWzsZ+h3RsrqCStkBHlgo6/TJlFst3cOTlLghBQlJwPOZKQJTKNaD3QIB7aAVQ+gfWbN3NXB7A==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright-1.48.2": {
+ "name": "@playwright/test",
+ "version": "1.48.2",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.48.2.tgz",
+ "integrity": "sha512-54w1xCWfXuax7dz4W2M9uw0gDyh+ti/0K/MxcCUxChFh37kkdxPdfZDw5QBbuPUJHr1CiHJ1hXgSs+GgeQc5Zw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright": "1.48.2"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright-1.48.2/node_modules/playwright": {
+ "version": "1.48.2",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.48.2.tgz",
+ "integrity": "sha512-NjYvYgp4BPmiwfe31j4gHLa3J7bD2WiBz8Lk2RoSsmX38SVIARZ18VYjxLjAcDsAhA+F4iSEXTSGgjua0rrlgQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.48.2"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.2"
+ }
+ },
+ "node_modules/playwright-1.48.2/node_modules/playwright-core": {
+ "version": "1.48.2",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.48.2.tgz",
+ "integrity": "sha512-sjjw+qrLFlriJo64du+EK0kJgZzoQPsabGF4lBvsid+3CNIZIYLgnMj9V6JY5VhM2Peh20DJWIVpVljLLnlawA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright-1.54.2": {
+ "name": "@playwright/test",
+ "version": "1.54.2",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.54.2.tgz",
+ "integrity": "sha512-A+znathYxPf+72riFd1r1ovOLqsIIB0jKIoPjyK2kqEIe30/6jF6BC7QNluHuwUmsD2tv1XZVugN8GqfTMOxsA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright": "1.54.2"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright-1.54.2/node_modules/playwright": {
+ "version": "1.54.2",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.54.2.tgz",
+ "integrity": "sha512-Hu/BMoA1NAdRUuulyvQC0pEqZ4vQbGfn8f7wPXcnqQmM+zct9UliKxsIkLNmz/ku7LElUNqmaiv1TG/aL5ACsw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.54.2"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.2"
+ }
+ },
+ "node_modules/playwright-1.54.2/node_modules/playwright-core": {
+ "version": "1.54.2",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.54.2.tgz",
+ "integrity": "sha512-n5r4HFbMmWsB4twG7tJLDN9gmBUeSPcsBZiWSE4DnYz9mJMAFqr2ID7+eGC9kpEnxExJ1epttwR59LEWCk8mtA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.65.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
+ "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/e2e/package.json b/e2e/package.json
new file mode 100644
index 0000000..170efda
--- /dev/null
+++ b/e2e/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "has-e2e",
+ "private": true,
+ "description": "HAS tarayıcı testleri / browser tests (Playwright)",
+ "scripts": {
+ "test": "playwright test"
+ },
+ "devDependencies": {
+ "@playwright/test": "1.65.1",
+ "playwright-1.54.2": "npm:@playwright/test@1.54.2",
+ "playwright-1.48.2": "npm:@playwright/test@1.48.2",
+ "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",
+ "axe-core": "4.14.0"
+ }
+}
diff --git a/e2e/playwright.config.js b/e2e/playwright.config.js
new file mode 100644
index 0000000..9ba7ed6
--- /dev/null
+++ b/e2e/playwright.config.js
@@ -0,0 +1,56 @@
+// Tarayıcı testleri (Playwright): ana sayfa, okuyucu, acil sayfası, yönetim paneli; masaüstü ve telefon/tablet.
+// Browser tests (Playwright): homepage, reader, emergency page, admin panel; desktop and phone/tablet.
+//
+// Düz CommonJS nesnesi (defineConfig değil): CI eski Playwright sürümlerini de (1.22'ye kadar) çalıştırır.
+// A plain CommonJS object (not defineConfig): CI also runs older Playwright versions (back to 1.22).
+//
+// Sunucu: e2e/prepare.sh'nin açtığı HAS konteyneri (HAS_URL). Ayrıntı: e2e/README.md
+// Server: the HAS container started by e2e/prepare.sh (HAS_URL). Details: e2e/README.md
+const { devices } = require('@playwright/test');
+
+// Cihaz adları sürümden sürüme değişir; ilk bulunan kullanılır, hiçbiri yoksa proje atlanır.
+// Device names change between versions; the first one found is used, the project is skipped if none exists.
+const pick = (...names) => names.map((n) => devices[n]).find(Boolean);
+
+const targets = [
+ // masaüstü, üç tarayıcı motoru / desktop, the three engines
+ ['desktop-chromium', pick('Desktop Chrome')],
+ ['desktop-firefox', pick('Desktop Firefox')],
+ ['desktop-webkit', pick('Desktop Safari')],
+ // Android telefon ve tablet (Chromium) / Android phone and tablet (Chromium)
+ ['android-pixel', pick('Pixel 7', 'Pixel 5')],
+ ['android-galaxy-s9', pick('Galaxy S9+')],
+ ['android-tablet', pick('Galaxy Tab S4')],
+ // iPhone ve iPad (WebKit); iPhone SE 320 px ile en dar ekran / iPhone and iPad (WebKit); iPhone SE is the narrowest at 320 px
+ ['iphone-se', pick('iPhone SE')],
+ ['iphone-large', pick('iPhone 15 Pro Max', 'iPhone 14 Pro Max', 'iPhone 13 Pro Max', 'iPhone 12 Pro Max')],
+ ['ipad-mini', pick('iPad Mini')],
+ // Android'de Firefox: Playwright Firefox'ta mobil kipini taklit etmez, telefon genişliği ve UA verilir.
+ // Firefox on Android: Playwright does not emulate mobile mode in Firefox, so phone width and UA are set.
+ [
+ 'android-firefox',
+ {
+ browserName: 'firefox',
+ viewport: { width: 360, height: 740 },
+ userAgent: 'Mozilla/5.0 (Android 14; Mobile; rv:131.0) Gecko/131.0 Firefox/131.0',
+ },
+ ],
+];
+
+module.exports = {
+ testDir: 'tests',
+ timeout: 90000,
+ expect: { timeout: 15000 },
+ forbidOnly: !!process.env.CI,
+ retries: process.env.CI ? 1 : 0,
+ // Tek sunucu, ortak durum (iş kuyruğu, giriş sınırı): testler sırayla.
+ // One server with shared state (job queue, login limit): tests run one at a time.
+ workers: 1,
+ reporter: process.env.CI ? [['list'], ['github'], ['html', { open: 'never' }]] : [['list']],
+ use: {
+ baseURL: process.env.HAS_URL || 'http://127.0.0.1:18095',
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ },
+ projects: targets.filter(([, device]) => device).map(([name, device]) => ({ name, use: { ...device } })),
+};
diff --git a/e2e/prepare.sh b/e2e/prepare.sh
new file mode 100644
index 0000000..c66bf73
--- /dev/null
+++ b/e2e/prepare.sh
@@ -0,0 +1,67 @@
+#!/usr/bin/env bash
+# Tarayıcı testleri için HAS konteynerini açar: kendi Docker ağında, compose.yaml'daki güvenlik ayarlarıyla;
+# yönetici hesabını kurar, iki küçük ZIM indirir (bir İngilizce, bir Türkçe) ve testlerin ortamını yazar.
+# Starts the HAS container for the browser tests: on its own Docker network with the compose.yaml hardening;
+# creates the admin account, downloads two small ZIMs (one English, one Turkish) and writes the test environment.
+#
+# Kullanım / usage: e2e/prepare.sh IMAGE
+# Çıktı / output: e2e/.env (HAS_URL, HAS_USER, HAS_PASS, HAS_BOOKS); CI'da ayrıca $GITHUB_ENV / also $GITHUB_ENV in CI
+# Ortam / environment: HAS_E2E_NET (has-e2e), HAS_E2E_NAME (has-e2e-web), HAS_E2E_PORT (18095)
+set -euo pipefail
+docker() { MSYS_NO_PATHCONV=1 command docker "$@"; }
+
+IMAGE=${1:?kullanım / usage: e2e/prepare.sh IMAGE}
+NET=${HAS_E2E_NET:-has-e2e}
+NAME=${HAS_E2E_NAME:-has-e2e-web}
+PORT=${HAS_E2E_PORT:-18095}
+USER_NAME=e2e-admin
+PASS=e2e-password-0001
+ZIMS='"nhs.uk_en_medicines","wikibooks_tr_all_maxi"' # ~15 MB + ~27 MB
+API=http://127.0.0.1:$PORT/admin/api
+DIR=$(cd "$(dirname "$0")" && pwd)
+JAR=$(mktemp)
+trap 'rm -f "$JAR"' EXIT
+
+docker network inspect "$NET" >/dev/null 2>&1 || docker network create "$NET" >/dev/null
+docker rm -fv "$NAME" >/dev/null 2>&1 || true
+docker run -d --name "$NAME" --network "$NET" -p "127.0.0.1:$PORT:8080" \
+ --read-only --tmpfs /tmp --cap-drop ALL --cap-add SETUID --cap-add SETGID --cap-add DAC_OVERRIDE \
+ --security-opt no-new-privileges:true "$IMAGE" >/dev/null
+
+code=""
+for _ in $(seq 1 120); do
+ logs=$(docker logs "$NAME" 2>&1)
+ code=$(sed -n 's/.*first-run setup code: //p' <<<"$logs" | tail -1 | tr -d '\r')
+ [ -n "$code" ] && curl -fs -o /dev/null "http://127.0.0.1:$PORT/home/" && break
+ sleep 1
+done
+[ -n "$code" ] || { echo "kurulum kodu yok / no setup code" >&2; docker logs "$NAME" >&2; exit 1; }
+
+post() { curl -fsS -b "$JAR" -c "$JAR" -H 'Content-Type: application/json' -d "$2" "$API/$1"; }
+post setup "{\"code\":\"$code\",\"user\":\"$USER_NAME\",\"password\":\"$PASS\"}" >/dev/null
+post download "{\"prefixes\":[$ZIMS]}" >/dev/null
+echo "İndiriliyor / downloading: $ZIMS"
+for _ in $(seq 1 300); do
+ job=$(curl -fsS -b "$JAR" "$API/job")
+ [[ $job == *'"running":false'* ]] && break
+ sleep 2
+done
+[[ $job == *'"exitCode":0'* ]] || { echo "indirme başarısız / download failed: $job" >&2; exit 1; }
+
+status=$(curl -fsS -b "$JAR" "$API/status")
+books=$(grep -o '"name":"[^"]*\.zim"' <<<"$status" | cut -d'"' -f4 | sed 's/\.zim$//' | sort -r | paste -sd, -)
+[ -n "$books" ] || { echo "kitap yok / no books" >&2; exit 1; }
+# Kiwix kataloğu kitapları görene kadar bekle / wait until the Kiwix catalog lists the books
+for _ in $(seq 1 30); do
+ catalog=$(curl -fsS "http://127.0.0.1:$PORT/kiwix/catalog/v2/entries?count=-1")
+ [[ $catalog == *"${books%%,*}"* ]] && break
+ sleep 1
+done
+
+{
+ echo "HAS_URL=http://$NAME:8080"
+ echo "HAS_USER=$USER_NAME"
+ echo "HAS_PASS=$PASS"
+ echo "HAS_BOOKS=$books"
+} | tee "$DIR/.env"
+if [ -n "${GITHUB_ENV:-}" ]; then cat "$DIR/.env" >>"$GITHUB_ENV"; fi
diff --git a/e2e/run.sh b/e2e/run.sh
new file mode 100644
index 0000000..d95d1ce
--- /dev/null
+++ b/e2e/run.sh
@@ -0,0 +1,42 @@
+#!/usr/bin/env bash
+# Playwright testlerini resmî Playwright imajında, HAS konteyneriyle aynı Docker ağında çalıştırır.
+# Tarayıcılar ve sistem kütüphaneleri imajda; makineye bir şey kurulmaz.
+# Runs the Playwright tests in the official Playwright image, on the same Docker network as the HAS container.
+# The browsers and their system libraries come with the image; nothing is installed on the machine.
+#
+# Kullanım / usage: e2e/run.sh [SÜRÜM / VERSION] [IMAJ / IMAGE: noble|jammy|focal] [playwright test seçenekleri / options]
+# e2e/run.sh # package-lock.json'daki sürüm / the version in package-lock.json
+# e2e/run.sh 1.22.2 focal # eski tarayıcılar: Chrome 102, Firefox 99, Safari 15.4 / older browsers
+# e2e/run.sh "" noble --project=iphone-se # tek cihaz / one device
+#
+# Eski sürümler aynı package.json'da takma adla kilitli ("playwright-1.22.2": "npm:@playwright/test@1.22.2");
+# imajda node_modules/playwright- node_modules/@playwright/test'in yerine bağlanır (bağımlılıkları kendi içinde).
+# Older versions are locked in the same package.json under an alias ("playwright-1.22.2": "npm:@playwright/test@1.22.2");
+# inside the image node_modules/playwright- is mounted over node_modules/@playwright/test (its deps are nested in it).
+set -euo pipefail
+docker() { MSYS_NO_PATHCONV=1 command docker "$@"; }
+
+DIR=$(cd "$(dirname "$0")" && pwd)
+win() { if command -v cygpath >/dev/null; then cygpath -w "$1"; else echo "$1"; fi; }
+# Dosya yolu node'a argüman olarak verilir (Windows'ta çevrilmiş) / the path goes to node as an argument (converted on Windows)
+LATEST=$(node -p "require(process.argv[1]).packages['node_modules/@playwright/test'].version" "$(win "$DIR/package-lock.json")")
+VERSION=${1:-$LATEST}
+FLAVOR=${2:-noble}
+shift $(($# < 2 ? $# : 2))
+NET=${HAS_E2E_NET:-has-e2e}
+
+[ -f "$DIR/.env" ] || { echo "önce / first: e2e/prepare.sh IMAGE" >&2; exit 1; }
+
+[ -d "$DIR/node_modules/@playwright/test" ] || (cd "$DIR" && PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm ci --no-audit --no-fund)
+mounts=(-v "$(win "$DIR"):/e2e")
+if [ "$VERSION" != "$LATEST" ]; then
+ R="$DIR/node_modules/playwright-$VERSION"
+ [ "$(node -p "require(process.argv[1]).version" "$(win "$R/package.json")" 2>/dev/null)" = "$VERSION" ] ||
+ { echo "package.json'da yok / not in package.json: \"playwright-$VERSION\": \"npm:@playwright/test@$VERSION\"" >&2; exit 1; }
+ mounts+=(-v "$(win "$R"):/e2e/node_modules/@playwright/test:ro")
+fi
+
+echo "Playwright $VERSION ($FLAVOR)"
+docker run --rm --network "$NET" --ipc=host --env-file "$(win "$DIR/.env")" -e CI="${CI:-}" \
+ "${mounts[@]}" -w /e2e "mcr.microsoft.com/playwright:v$VERSION-$FLAVOR" \
+ node node_modules/@playwright/test/cli.js test "$@"
diff --git a/e2e/tests/a11y.spec.js b/e2e/tests/a11y.spec.js
new file mode 100644
index 0000000..a223649
--- /dev/null
+++ b/e2e/tests/a11y.spec.js
@@ -0,0 +1,78 @@
+// 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: 'acil, İngilizce / emergency, English', url: '/home/acil.html', ready: 'body', lang: 'en' },
+ { name: 'okuyucu / reader', url: () => `/home/reader.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);
+ if (p.lang) await page.click(`[data-lang="${p.lang}"]`);
+ 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/e2e/tests/admin.spec.js b/e2e/tests/admin.spec.js
new file mode 100644
index 0000000..58c3586
--- /dev/null
+++ b/e2e/tests/admin.spec.js
@@ -0,0 +1,309 @@
+// Yönetim paneli / admin panel
+const { test, expect } = require('@playwright/test');
+const { USER, PASS, BOOKS, watchErrors, expectNoHorizontalScroll, login, themeOf } = require('./common');
+
+async function openPanel(page) {
+ await login(page);
+ await page.goto('/admin/');
+ await page.click('[data-lang="tr"]');
+ await expect(page.locator('#panel')).toBeVisible();
+ await expect(page.locator('h3.grp').first()).toBeVisible();
+ // Bildirim yalnız iş başlayınca/bitince görünür / the notice only shows when a job starts or ends
+ await expect(page.locator('#toast')).toBeHidden();
+}
+
+test.describe('yönetim paneli / admin panel', () => {
+ test('arayüzden giriş ve çıkış / log in and out through the page', async ({ page }) => {
+ const errors = watchErrors(page);
+ await page.goto('/admin/');
+ await expect(page.locator('#login')).toBeVisible();
+ await expectNoHorizontalScroll(page);
+ await page.fill('#login input[name="user"]', USER);
+ await page.fill('#login input[name="password"]', PASS);
+ await page.click('#login button');
+ await expect(page.locator('#panel')).toBeVisible();
+ await expect(page.locator('#who')).toContainText(USER);
+ await page.click('#out');
+ await expect(page.locator('#login')).toBeVisible();
+ expect(errors).toEqual([]);
+ });
+
+ test('hata metni seçili dilde / error text in the selected language', async ({ page }) => {
+ // Sunucu cevabı taklit edilir: gerçek yanlış şifre ortak giriş sınırını tüketirdi.
+ // The server answer is mocked: a real wrong password would use up the shared login limit.
+ await page.route('**/admin/api/login', (route) =>
+ route.fulfill({
+ status: 401,
+ contentType: 'application/json',
+ body: JSON.stringify({ error_code: 'wrong_login', message: 'Wrong user name or password.' }),
+ }),
+ );
+ await page.goto('/admin/');
+ await page.click('[data-lang="tr"]');
+ await page.fill('#login input[name="user"]', USER);
+ await page.fill('#login input[name="password"]', 'yanlis-sifre');
+ await page.click('#login button');
+ await expect(page.locator('#err')).toHaveText('Kullanıcı adı ya da şifre yanlış.');
+ await page.click('[data-lang="en"]');
+ await page.click('#login button');
+ await expect(page.locator('#err')).toHaveText('Wrong user name or password.');
+ });
+
+ test('içerik dile göre gruplu, telefonda taşmaz / content grouped by language, fits phones', async ({ page }) => {
+ const errors = watchErrors(page);
+ await openPanel(page);
+ const groups = page.locator('h3.grp');
+ await expect(groups.nth(0)).toContainText('Türkçe');
+ await expect(groups.nth(1)).toContainText('İngilizce');
+ await expect(groups.nth(0)).toContainText(/\d+\/\d+ cihazda/);
+ // Her grubun kendi tablosu var / each group has its own table
+ expect(await page.locator('#content table.ct').count()).toBe(await groups.count());
+ await page.click('[data-lang="en"]');
+ await expect(groups.nth(0)).toContainText('Turkish');
+ await expect(groups.nth(1)).toContainText('English');
+ await expectNoHorizontalScroll(page);
+ expect(errors).toEqual([]);
+ });
+
+ test('grup seçimi ve gruplar arası seçim / group select and selection across groups', async ({ page }) => {
+ await openPanel(page);
+ const trGroup = page.locator('h3.grp').nth(0);
+ const trBox = trGroup.locator('input[data-group]');
+ const trRows = page.locator('#content table.ct').nth(0).locator('input[data-prefix]');
+ const enRows = page.locator('#content table.ct').nth(1).locator('input[data-prefix]');
+ const n = await trRows.count();
+ expect(n).toBeGreaterThan(1);
+
+ await trBox.check();
+ for (let i = 0; i < n; i++) await expect(trRows.nth(i)).toBeChecked();
+ // Bir satırı kaldırınca grup kutusu yarım seçili / unchecking one row makes the group box indeterminate
+ await trRows.nth(0).uncheck();
+ expect(await trBox.evaluate((e) => e.indeterminate)).toBe(true);
+ // Aynı anda İngilizceden de seçilebilir / English items can be selected at the same time
+ await enRows.nth(0).check();
+ expect(await page.locator('#content input[data-prefix]:checked').count()).toBe(n);
+ // Yarım seçili kutuya tıklamak hepsini seçer, ikinci tıklama hepsini kaldırır (tarayıcının davranışı).
+ // Clicking a half-selected box selects all, a second click clears all (browser behaviour).
+ await trBox.click();
+ for (let i = 0; i < n; i++) await expect(trRows.nth(i)).toBeChecked();
+ await trBox.click();
+ for (let i = 0; i < n; i++) await expect(trRows.nth(i)).not.toBeChecked();
+ await expect(enRows.nth(0)).toBeChecked();
+ });
+
+ test('seçim yenilemede korunur / the selection survives a refresh', async ({ page }) => {
+ await openPanel(page);
+ const row = page.locator('#content table.ct').nth(1).locator('input[data-prefix]').nth(2);
+ await row.check();
+ // Dil değiştirmek tabloyu yeniden çizer / switching language redraws the tables
+ await page.click('[data-lang="en"]');
+ await expect(page.locator('h3.grp').nth(0)).toContainText('Turkish');
+ await expect(page.locator('#content table.ct').nth(1).locator('input[data-prefix]').nth(2)).toBeChecked();
+ });
+
+ test('seçim yoksa uyarı / a warning without a selection', async ({ page }) => {
+ await openPanel(page);
+ await page.click('#dl');
+ await expect(page.locator('#err')).toHaveText('İndirilecek içeriği seçin.');
+ // Yalnız cihazda olmayan seçiliyse doğrulama uyarır / verify warns when nothing selected is on the device
+ const missing = page.locator('#content input[data-prefix][data-file=""]').first();
+ await missing.check();
+ await page.click('#verifySel');
+ await expect(page.locator('#err')).toHaveText('Doğrulamak için cihazda olan içerik seçin.');
+ await page.click('#delSel');
+ await expect(page.locator('#err')).toHaveText('Silmek için cihazda olan içerik seçin.');
+ await expect(page.locator('#confirm')).toBeHidden();
+ });
+
+ test('seçilenleri doğrula / verify selected', async ({ page }) => {
+ test.skip(!BOOKS.length, 'kitap yok / no books');
+ await openPanel(page);
+ await page.locator(`#content input[data-file="${BOOKS[0]}.zim"]`).check();
+ await page.click('#verifySel');
+ await expect(page.locator('#err')).toBeHidden();
+ await expect(page.locator('#jobname')).toContainText('Doğrulama');
+ await expect(page.locator('#jobname')).toContainText('bitti', { timeout: 120000 });
+ await expect(page.locator('#log')).toContainText(BOOKS[0]);
+ // Seçilmeyen kitap doğrulanmadı / the book that was not selected was not verified
+ if (BOOKS[1]) await expect(page.locator('#log')).not.toContainText(BOOKS[1]);
+ });
+
+ test('silme onayı penceresi, vazgeç / delete confirmation dialog, cancel', async ({ page }) => {
+ test.skip(!BOOKS.length, 'kitap yok / no books');
+ await openPanel(page);
+ const file = `${BOOKS[0]}.zim`;
+ await page.click(`button[data-del="${file}"]`);
+ await expect(page.locator('#confirm')).toBeVisible();
+ await expect(page.locator('#confirmFile')).toHaveText(file);
+ await expect(page.locator('#confirmPw')).toHaveValue('');
+ await page.click('#confirmCancel');
+ await expect(page.locator('#confirm')).toBeHidden();
+ await expect(page.locator(`button[data-del="${file}"]`)).toBeVisible();
+ });
+
+ test('indirme başlayınca seçim kalkar / starting a download clears the selection', async ({ page }) => {
+ // Gerçek indirme başlatılmaz (ortak iş kuyruğu), sunucu cevabı taklit edilir.
+ // No real download is started (shared job queue); the server answer is mocked.
+ let sent = null;
+ await page.route('**/admin/api/download', (route) => {
+ sent = route.request().postDataJSON();
+ return route.fulfill({ status: 202, contentType: 'application/json', body: '{"started":true}' });
+ });
+ await openPanel(page);
+ const table = page.locator('#content table.ct').first();
+ const boxes = table.locator('input[data-prefix]');
+ const group = page.locator('#content input[data-group]').first();
+ await group.check();
+ await page.click('#dl');
+ await expect.poll(() => sent && sent.prefixes.length).toBe(await boxes.count());
+ for (let i = 0; i < (await boxes.count()); i++) await expect(boxes.nth(i)).not.toBeChecked();
+ await expect(group).not.toBeChecked();
+ await expect(page.locator('#toast')).toBeVisible();
+ await expect(page.locator('#toastMsg')).toContainText('İndirme başladı');
+ await page.click('#toastClose');
+ await expect(page.locator('#toast')).toBeHidden();
+ });
+
+ test('indirme sürerken satır durumu ve bitince bildirim / row status during a download and a notice at the end', async ({
+ page,
+ }) => {
+ // İş durumu taklit edilir: önce iki içerik indiriliyor/sırada, sonra iş biter.
+ // The job state is mocked: first two items downloading/queued, then the job ends.
+ await openPanel(page);
+ const missing = page.locator('#content input[data-prefix][data-file=""]');
+ const [a, b] = [await missing.nth(0).getAttribute('data-prefix'), await missing.nth(1).getAttribute('data-prefix')];
+ let calls = 0;
+ await page.route('**/admin/api/job', (route) => {
+ calls++;
+ const running = calls < 3;
+ const body = {
+ name: 'download',
+ items: [a, b],
+ running,
+ exitCode: 0,
+ lines: running
+ ? [
+ '>> Kiwix kataloğu alınıyor / fetching Kiwix catalog',
+ `>> ${a}_2026-01.zim indiriliyor / downloading (1 MB)`,
+ '#### 42.5%',
+ ]
+ : [`OK ${a}_2026-01.zim tamamlandı / done`, `OK ${b}_2026-01.zim tamamlandı / done`],
+ };
+ return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) });
+ });
+ await page.evaluate(() => job());
+ await expect(page.locator(`[data-jobst="${a}"]`)).toHaveText('İndiriliyor 42.5%');
+ await expect(page.locator(`[data-jobst="${b}"]`)).toHaveText('Sırada');
+ await expect(page.locator('#toastMsg')).toHaveText('İndirme bitti.', { timeout: 15000 });
+ await expect(page.locator(`[data-jobst="${a}"]`)).toBeHidden();
+ });
+
+ test('seçilenleri sil penceresi, vazgeç / delete selected dialog, cancel', async ({ page }) => {
+ test.skip(!BOOKS.length, 'kitap yok / no books');
+ await openPanel(page);
+ const files = BOOKS.map((b) => `${b}.zim`);
+ for (const f of files) await page.locator(`#content input[data-file="${f}"]`).check();
+ // Cihazda olmayan seçim pencereye girmez / a selected item that is not on the device stays out
+ await page.locator('#content input[data-prefix][data-file=""]').first().check();
+ await page.click('#delSel');
+ await expect(page.locator('#confirm')).toBeVisible();
+ await expect(page.locator('#confirmQ')).toHaveText(files.length > 1 ? 'Silinecek dosyalar:' : 'Silinecek dosya:');
+ await expect(page.locator('#confirmFile')).toHaveText(files.join('\n'));
+ await expect(page.locator('#confirmPw')).toHaveValue('');
+ await page.click('#confirmCancel');
+ await expect(page.locator('#confirm')).toBeHidden();
+ for (const f of files) await expect(page.locator(`button[data-del="${f}"]`)).toBeVisible();
+ });
+
+ test('iş yokken durdur ve satır durumları gizli / without a running job, Stop and row status are hidden', async ({
+ page,
+ }) => {
+ await page.route('**/admin/api/job', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: '{"name":"","running":false,"exitCode":0,"lines":[]}',
+ }),
+ );
+ await openPanel(page);
+ await expect(page.locator('#stop')).toBeHidden();
+ const rows = page.locator('[data-jobst]');
+ for (let i = 0; i < (await rows.count()); i++) await expect(rows.nth(i)).toBeHidden();
+ });
+
+ test('silmede yanlış şifre: pencere açık kalır, hata görünür / wrong password on delete: the dialog stays, the error shows', async ({
+ page,
+ }) => {
+ test.skip(!BOOKS.length, 'kitap yok / no books');
+ // Gerçek sunucuya yanlış şifre gönderilmez (ortak giriş sınırı); cevap taklit edilir.
+ // No wrong password reaches the real server (shared login limit); the answer is mocked.
+ await page.route('**/admin/api/delete', (route) =>
+ route.fulfill({
+ status: 403,
+ contentType: 'application/json',
+ body: '{"error_code":"wrong_password","message":"Wrong password."}',
+ }),
+ );
+ await openPanel(page);
+ const file = `${BOOKS[0]}.zim`;
+ await page.click(`button[data-del="${file}"]`);
+ await page.fill('#confirmPw', 'yanlis-sifre-123');
+ await page.click('#confirmOk');
+ await expect(page.locator('#confirmErr')).toBeVisible();
+ await expect(page.locator('#confirmErr')).toHaveText('Şifre yanlış.');
+ await expect(page.locator('#confirm')).toBeVisible();
+ await expect(page.locator('#confirmPw')).toHaveValue('');
+ await page.click('#confirmCancel');
+ await expect(page.locator(`button[data-del="${file}"]`)).toBeVisible();
+ });
+
+ test('kurulum formu: şifreler aynı değilse istek gitmez / setup form: mismatched passwords send nothing', async ({
+ page,
+ }) => {
+ let sent = 0;
+ await page.route('**/admin/api/session', (route) =>
+ route.fulfill({ status: 200, contentType: 'application/json', body: '{"setup":true,"user":""}' }),
+ );
+ await page.route('**/admin/api/setup', (route) => {
+ sent++;
+ return route.fulfill({ status: 500, contentType: 'application/json', body: '{}' });
+ });
+ await page.goto('/admin/');
+ await page.click('[data-lang="tr"]');
+ await expect(page.locator('#setup')).toBeVisible();
+ await expect(page.locator('#login')).toBeHidden();
+ await expect(page.locator('#panel')).toBeHidden();
+ await page.fill('#setup input[name="code"]', 'abcde-12345');
+ await page.fill('#setup input[name="user"]', 'deneme');
+ await page.fill('#setup input[name="password"]', 'sifre-0000000001');
+ await page.fill('#setup input[name="password2"]', 'sifre-0000000002');
+ await page.locator('#setup button').first().click();
+ await expect(page.locator('#err')).toHaveText('Şifreler aynı değil.');
+ expect(sent).toBe(0);
+ });
+
+ test('oturum düşerse giriş ekranına döner / an expired session returns to the login form', async ({ page }) => {
+ await openPanel(page);
+ await page.route('**/admin/api/status', (route) =>
+ route.fulfill({
+ status: 401,
+ contentType: 'application/json',
+ body: '{"error_code":"login_required","message":"Log in first."}',
+ }),
+ );
+ await page.route('**/admin/api/session', (route) =>
+ route.fulfill({ status: 200, contentType: 'application/json', body: '{"setup":false,"user":""}' }),
+ );
+ await page.evaluate(() => refresh());
+ await expect(page.locator('#login')).toBeVisible();
+ await expect(page.locator('#panel')).toBeHidden();
+ });
+
+ test('tema seçimi / theme choice', async ({ page }) => {
+ await openPanel(page);
+ await page.selectOption('#theme', 'dark');
+ expect(await themeOf(page)).toBe('dark');
+ await page.selectOption('#theme', 'light');
+ expect(await themeOf(page)).toBe('light');
+ });
+});
diff --git a/e2e/tests/browsers.spec.js b/e2e/tests/browsers.spec.js
new file mode 100644
index 0000000..c1fddcf
--- /dev/null
+++ b/e2e/tests/browsers.spec.js
@@ -0,0 +1,10 @@
+// Hangi tarayıcı sürümüyle denendiği rapora yazılır / records which browser version the run used
+const { test, expect } = require('@playwright/test');
+
+test('tarayıcı sürümü / browser version', async ({ browser, browserName, page }, testInfo) => {
+ const ua = await page.evaluate(() => navigator.userAgent);
+ const line = `${testInfo.project.name}: ${browserName} ${browser.version()} (${ua})`;
+ console.log(line);
+ testInfo.annotations.push({ type: 'browser', description: line });
+ expect(browser.version()).toBeTruthy();
+});
diff --git a/e2e/tests/common.js b/e2e/tests/common.js
new file mode 100644
index 0000000..ca16aff
--- /dev/null
+++ b/e2e/tests/common.js
@@ -0,0 +1,40 @@
+// Testlerin ortak yardımcıları / helpers shared by the tests
+const { expect } = require('@playwright/test');
+
+const USER = process.env.HAS_USER || 'e2e-admin';
+const PASS = process.env.HAS_PASS || 'e2e-password-0001';
+// prepare.sh'nin indirdiği kitaplar (dosya adı .zim'siz) / books downloaded by prepare.sh (file name without .zim)
+const BOOKS = (process.env.HAS_BOOKS || '').split(',').filter(Boolean);
+
+// Sayfanın kendi betik hataları (Kiwix içeriği hariç) / the page's own script errors (not Kiwix content)
+function watchErrors(page) {
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(String(e)));
+ page.on('console', (m) => {
+ if (m.type() !== 'error') return;
+ const url = (m.location() || {}).url || '';
+ // Kiwix'in CSP başlığını eski Safari tanımıyor ('allow-downloads'); tarayıcının uyarısı, sayfanın hatası değil.
+ // Older Safari does not know a flag in Kiwix's CSP header ('allow-downloads'); a browser warning, not a page error.
+ if (/Content Security Policy/.test(m.text())) return;
+ if (!url.includes('/kiwix/')) errors.push(`${m.text()} (${url})`);
+ });
+ return errors;
+}
+
+// Sayfa yatay kaymamalı (telefonda en sık bozulan şey) / no horizontal scrolling (what breaks most on phones)
+async function expectNoHorizontalScroll(page) {
+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
+ expect(overflow, 'yatay kaydırma / horizontal overflow (px)').toBeLessThanOrEqual(1);
+}
+
+// API ile giriş; çerez sayfanın bağlamına yazılır / log in through the API; the cookie lands in the page context
+async function login(page) {
+ const r = await page.request.post('/admin/api/login', { data: { user: USER, password: PASS } });
+ expect(r.status(), await r.text()).toBe(200);
+}
+
+async function themeOf(page) {
+ return page.evaluate(() => document.documentElement.dataset.theme || 'light');
+}
+
+module.exports = { USER, PASS, BOOKS, watchErrors, expectNoHorizontalScroll, login, themeOf };
diff --git a/e2e/tests/home.spec.js b/e2e/tests/home.spec.js
new file mode 100644
index 0000000..c6e5fd3
--- /dev/null
+++ b/e2e/tests/home.spec.js
@@ -0,0 +1,173 @@
+// Ana sayfa ve acil sayfası / homepage and emergency page
+const { test, expect } = require('@playwright/test');
+const { BOOKS, watchErrors, expectNoHorizontalScroll, themeOf } = require('./common');
+
+test.describe('ana sayfa / homepage', () => {
+ test('açılır, telefonda taşmaz, hata yok / opens, fits phones, no errors', async ({ page }) => {
+ const errors = watchErrors(page);
+ await page.goto('/home/');
+ await expect(page.locator('#search')).toBeVisible();
+ await expectNoHorizontalScroll(page);
+ expect(errors).toEqual([]);
+ });
+
+ test('menü kurulu servislere göre / menu follows the installed services', async ({ page }) => {
+ await page.goto('/home/');
+ await expect(page.locator('a[data-service="kiwix"]')).toBeVisible();
+ await expect(page.locator('a[data-service="kiwix"]')).toHaveAttribute('href', '/home/reader.html#library');
+ await expect(page.locator('a[data-service="has-admin iiab-admin"]')).toBeVisible();
+ // Harita bu imajda yok: menüde görünmemeli / no map in this image: hidden in the menu
+ await expect(page.locator('a[data-service="maps"]')).toBeHidden();
+ });
+
+ test('kurulu olmayan servis ve kitap bağlantısız / services and books not installed have no link', async ({
+ page,
+ }) => {
+ await page.goto('/home/');
+ await page.click('[data-lang="tr"]');
+ // Harita bu imajda yok / no map in this image
+ const map = page.locator('#forums tr', { hasText: 'Dünya Haritası' });
+ await expect(map).toHaveCount(1);
+ await expect(map.locator('a.fname')).toHaveCount(0);
+ await expect(map).toContainText('Henüz yüklenmedi');
+ // Türkçe Vikipedi indirilmedi / Turkish Wikipedia is not downloaded
+ const wiki = page.locator('#forums tr', { hasText: 'Vikipedi (Türkçe)' });
+ await expect(wiki.locator('a.fname')).toHaveCount(0);
+ await expect(wiki).toContainText('Henüz yüklenmedi');
+ });
+
+ test('disk uyarısı yalnız sorun varken / the disk warning only when there is a problem', async ({ page }) => {
+ await page.goto('/home/');
+ await expect(page.locator('#forums td.cat').first()).toBeVisible();
+ await expect(page.locator('#disk')).toBeHidden();
+ await page.route('**/home/disk.json', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: '{"warnings":["/library %95 dolu / 95% full"]}',
+ }),
+ );
+ await page.reload();
+ await expect(page.locator('#disk')).toBeVisible();
+ await expect(page.locator('#disk')).toContainText('%95 dolu');
+ });
+
+ test('boş arama bir yere gitmez / an empty search goes nowhere', async ({ page }) => {
+ await page.goto('/home/');
+ await page.fill('#q', ' ');
+ await page.press('#q', 'Enter');
+ await page.waitForTimeout(500);
+ await expect(page).toHaveURL(/\/home\/$/);
+ });
+
+ test('aramada kurulu kitaplar, arama okuyucuda açılır / installed books in search, results open in the reader', async ({
+ page,
+ }) => {
+ await page.goto('/home/');
+ for (const b of BOOKS) await expect(page.locator(`#book option[value="${b}"]`)).toHaveCount(1);
+ await page.fill('#q', 'water');
+ await page.locator('#search button, #search [type="submit"]').first().click();
+ await expect(page).toHaveURL(/\/home\/reader\.html#search\?.*pattern=water/);
+ });
+
+ test('kitap bağlantısı okuyucuya gider / book links go to the reader', async ({ page }) => {
+ test.skip(!BOOKS.length, 'kitap yok / no books');
+ await page.goto('/home/');
+ const link = page.locator(`a[href="/home/reader.html#${BOOKS[0]}"]`).first();
+ await expect(link).toBeVisible();
+ await link.click();
+ await expect(page).toHaveURL(new RegExp(`/home/reader\\.html#${BOOKS[0].replace(/\./g, '\\.')}`));
+ });
+
+ test('dil: TR ve EN, tüm HAS sayfalarında ortak / language: TR and EN, shared by all HAS pages', async ({ page }) => {
+ await page.goto('/home/');
+ await page.click('[data-lang="en"]');
+ await expect(page.locator('html')).toHaveAttribute('lang', 'en');
+ await expect(page.locator('[data-t="emergency"]')).toHaveText('Emergency');
+ await expect(page.locator('#forums td.cat').first()).toHaveText('Encyclopedia');
+ await expect(page.locator('#book option').first()).toHaveText('Whole library');
+ await expect(page.locator('#stats')).toContainText('ready to use');
+ await expectNoHorizontalScroll(page);
+ await page.reload();
+ await expect(page.locator('[data-t="emergency"]')).toHaveText('Emergency');
+ // Seçim panelde ve okuyucuda da geçerli / the choice also applies to the panel and the reader
+ await page.goto('/admin/');
+ await expect(page.locator('html')).toHaveAttribute('lang', 'en');
+ await page.goto('/home/reader.html');
+ await expect(page.locator('html')).toHaveAttribute('lang', 'en');
+ await page.goto('/home/');
+ await page.click('[data-lang="tr"]');
+ await expect(page.locator('[data-t="emergency"]')).toHaveText('Acil Durum');
+ await expect(page.locator('#forums td.cat').first()).toHaveText('Ansiklopedi');
+ });
+
+ test('tema: koyu, açık, sistem; yeniden yüklemede kalır / theme: dark, light, system; kept on reload', async ({
+ page,
+ }) => {
+ await page.goto('/home/');
+ const select = page.locator('select.theme').first();
+ await select.selectOption('dark');
+ expect(await themeOf(page)).toBe('dark');
+ await page.reload();
+ expect(await themeOf(page)).toBe('dark');
+ await select.selectOption('light');
+ expect(await themeOf(page)).toBe('light');
+ // Sistem: cihazın ayarını izler / system follows the device setting
+ await select.selectOption('system');
+ await page.emulateMedia({ colorScheme: 'dark' });
+ await expect.poll(() => themeOf(page)).toBe('dark');
+ await page.emulateMedia({ colorScheme: 'light' });
+ await expect.poll(() => themeOf(page)).toBe('light');
+ });
+});
+
+test.describe('acil sayfası / emergency page', () => {
+ test('112 görünür, taşmaz, hata yok / shows 112, fits, no errors', async ({ page }) => {
+ const errors = watchErrors(page);
+ await page.goto('/home/acil.html');
+ await expect(page.locator('body')).toContainText('112');
+ await expectNoHorizontalScroll(page);
+ expect(errors).toEqual([]);
+ });
+
+ test('dil: TR ve EN, kaynak satırlarıyla / language: TR and EN, with source lines', async ({ page }) => {
+ const errors = watchErrors(page);
+ await page.goto('/home/acil.html');
+ await page.click('[data-lang="tr"]');
+ await expect(page.locator('.l-tr .alarm')).toBeVisible();
+ await expect(page.locator('.l-en')).toBeHidden();
+ await expect(page.locator('html')).toHaveAttribute('lang', 'tr');
+ await page.click('[data-lang="en"]');
+ await expect(page.locator('html')).toHaveAttribute('lang', 'en');
+ await expect(page.locator('.l-tr')).toBeHidden();
+ await expect(page.locator('.l-en .alarm')).toContainText('112');
+ await expect(page.locator('#en-water')).toContainText('2 drops per quart or litre');
+ await expect(page.locator('#en-during .src')).toContainText('translated from Turkish');
+ await expect(page.locator('.skip')).toHaveText('Skip to content');
+ // Her bölümün iki dilde de kaynak satırı var / every section has a source line in both languages
+ expect(await page.locator('.l-en td.src').count()).toBe(await page.locator('.l-tr td.src').count());
+ await expectNoHorizontalScroll(page);
+ await page.click('[data-lang="tr"]');
+ await expect(page.locator('.l-tr .alarm')).toBeVisible();
+ expect(errors).toEqual([]);
+ });
+
+ test('yazdırırken dil, tema ve içindekiler gizli / printing hides language, theme and contents', async ({ page }) => {
+ await page.goto('/home/acil.html');
+ await page.click('[data-lang="tr"]');
+ await page.emulateMedia({ media: 'print' });
+ await expect(page.locator('.lang')).toBeHidden();
+ await expect(page.locator('.l-tr .toc')).toBeHidden();
+ await expect(page.locator('.crumb')).toBeHidden();
+ // İçerik ve kaynaklar basılır / the content and sources are printed
+ await expect(page.locator('.l-tr .alarm')).toBeVisible();
+ await expect(page.locator('.l-tr td.src').first()).toBeVisible();
+ await expect(page.locator('.l-en')).toBeHidden();
+ });
+
+ test('ana sayfadan açılır / opens from the homepage', async ({ page }) => {
+ await page.goto('/home/');
+ await page.locator('a[href="/home/acil.html"]').first().click();
+ await expect(page).toHaveURL(/\/home\/acil\.html$/);
+ });
+});
diff --git a/e2e/tests/reader.spec.js b/e2e/tests/reader.spec.js
new file mode 100644
index 0000000..afaf20b
--- /dev/null
+++ b/e2e/tests/reader.spec.js
@@ -0,0 +1,248 @@
+// HAS okuyucusu: Kiwix içeriği HAS çubuğuyla / HAS reader: Kiwix content with the HAS bar
+const { test, expect } = require('@playwright/test');
+const { BOOKS, watchErrors, expectNoHorizontalScroll, themeOf } = require('./common');
+
+const frameUrl = (page) =>
+ page.evaluate(() => {
+ try {
+ return document.getElementById('frame').contentWindow.location.href;
+ } catch (e) {
+ return '';
+ }
+ });
+
+test.describe('okuyucu, kitaplık olmadan / reader without a library', () => {
+ test('Kiwix kataloğu yoksa mesaj, çerçeve gizli / no Kiwix catalog: a message, no frame', async ({ page }) => {
+ await page.route('**/kiwix/catalog/**', (route) => route.abort());
+ await page.goto('/home/reader.html');
+ await expect(page.locator('#msg')).toBeVisible();
+ await expect(page.locator('#msg')).toHaveText(/Kütüphaneye ulaşılamadı|Could not reach the library/);
+ await expect(page.locator('#frame')).toBeHidden();
+ });
+
+ test('cihazda kitap yoksa mesaj, dil seçimi gizli / no books: a message, no language picker', async ({ page }) => {
+ await page.route('**/kiwix/catalog/**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/atom+xml',
+ body: '',
+ }),
+ );
+ await page.goto('/home/reader.html');
+ await expect(page.locator('#msg')).toHaveText(/henüz kaynak yok|No sources on this device/);
+ await expect(page.locator('#frame')).toBeHidden();
+ await expect(page.locator('#slang')).toBeHidden();
+ });
+
+ test('tek dilde kitap: dil seçimi gizli, aramada filtre yok / one language: no picker, no filter', async ({
+ page,
+ }) => {
+ test.skip(!BOOKS.length, 'kitap yok / no books');
+ const b = BOOKS[0];
+ const feed = `Tek kitaptur
+ `;
+ await page.route('**/kiwix/catalog/**', (route) =>
+ route.fulfill({ status: 200, contentType: 'application/atom+xml', body: feed }),
+ );
+ await page.goto(`/home/reader.html#${b}`);
+ await expect.poll(() => frameUrl(page)).toContain(`/kiwix/content/${b}`);
+ await page.selectOption('#books', '');
+ await expect(page.locator('#slang')).toBeHidden();
+ await page.fill('#q', 'a');
+ await page.press('#q', 'Enter');
+ await expect.poll(() => frameUrl(page)).toMatch(/\/kiwix\/search\?/);
+ expect(await frameUrl(page)).not.toContain('books.filter.lang');
+ });
+});
+
+test.describe('okuyucu / reader', () => {
+ test.beforeEach(() => test.skip(!BOOKS.length, 'kitap yok / no books (prepare.sh)'));
+
+ test('kitap çerçevede açılır, çubuk telefona sığar / the book opens in the frame, the bar fits phones', async ({
+ page,
+ }) => {
+ const errors = watchErrors(page);
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await expect.poll(() => frameUrl(page)).toContain(`/kiwix/content/${BOOKS[0]}`);
+ await expect(page.frameLocator('#frame').locator('body')).not.toBeEmpty();
+ await expectNoHorizontalScroll(page);
+ // Çubuk en fazla iki satır / the bar takes at most two rows
+ const barHeight = await page.locator('.bar').evaluate((e) => e.getBoundingClientRect().height);
+ expect(barHeight).toBeLessThan(120);
+ // İframe görünür alanı kaplar / the frame fills the visible area
+ const frameHeight = await page.locator('#frame').evaluate((e) => e.getBoundingClientRect().height);
+ expect(frameHeight).toBeGreaterThan(200);
+ expect(errors).toEqual([]);
+ });
+
+ test('içerikteki bağlantı tıklanır, adres güncellenir / links inside the content work and update the address', async ({
+ page,
+ }) => {
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await expect.poll(() => frameUrl(page)).toContain(`/kiwix/content/${BOOKS[0]}`);
+ const frame = page.frameLocator('#frame');
+ const link = frame.locator('a[href]:not([href^="http"]):not([href^="#"]):not([href^="mailto"])').first();
+ await expect(link).toBeVisible();
+ const before = await frameUrl(page);
+ await link.click();
+ await expect.poll(() => frameUrl(page)).not.toBe(before);
+ // Adres çubuğu çerçevedeki sayfayı gösterir / the address bar follows the page in the frame
+ await expect.poll(() => page.evaluate(() => location.hash)).toContain(BOOKS[0]);
+ });
+
+ test('kaynaklar arası geçiş / switching between sources', async ({ page }) => {
+ test.skip(BOOKS.length < 2, 'iki kitap gerekir / needs two books');
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ for (const b of BOOKS) await expect(page.locator(`#books option[value="${b}"]`)).toHaveCount(1);
+ await page.selectOption('#books', BOOKS[1]);
+ await expect.poll(() => frameUrl(page)).toContain(`/kiwix/content/${BOOKS[1]}`);
+ await expect(page).toHaveURL(new RegExp(`#${BOOKS[1].replace(/\./g, '\\.')}`));
+ });
+
+ test('hızlı kaynak değişiminde son seçim kalır / the last choice wins when switching sources quickly', async ({
+ page,
+ }) => {
+ test.skip(BOOKS.length < 2, 'iki kitap gerekir / needs two books');
+ // Önceki sayfanın geç gelen yüklemesi yeni seçimi ezmemeli (CI'da iPhone'da bir kez görüldü).
+ // A late load of the previous page must not undo the new choice (seen once on the iPhone in CI).
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await expect(page.locator(`#books option[value="${BOOKS[1]}"]`)).toHaveCount(1);
+ for (const b of [BOOKS[1], BOOKS[0], BOOKS[1]]) await page.selectOption('#books', b);
+ await expect.poll(() => frameUrl(page)).toContain(`/kiwix/content/${BOOKS[1]}`);
+ await expect(page.locator('#books')).toHaveValue(BOOKS[1]);
+ await expect(page).toHaveURL(new RegExp(`#${BOOKS[1].replace(/\./g, '\\.')}`));
+ });
+
+ test('tüm kaynaklarda arama: farklı dillerde hata yok / searching all sources: no error with several languages', async ({
+ page,
+ }) => {
+ test.skip(BOOKS.length < 2, 'iki dilde kitap gerekir / needs books in two languages');
+ // Kiwix farklı dillerdeki kitaplarda birlikte aramayı reddeder (400 "Invalid request"); okuyucu dil filtresi ekler.
+ // Kiwix refuses to search books in different languages together (400 "Invalid request"); the reader adds a language filter.
+ const statuses = [];
+ page.on('response', (r) => {
+ if (r.url().includes('/kiwix/search')) statuses.push(r.status());
+ });
+ await page.goto('/home/reader.html#search?pattern=a');
+ await expect.poll(() => frameUrl(page)).toMatch(/\/kiwix\/search\?.*books\.filter\.lang=(tur|eng)/);
+ await expect(page.frameLocator('#frame').locator('body')).not.toContainText('Invalid request');
+ expect(statuses.length).toBeGreaterThan(0);
+ expect(statuses.filter((s) => s >= 400)).toEqual([]);
+ await expect(page.locator('#q')).toHaveAttribute('placeholder', /(Türkçe|İngilizce|Turkish|English)/);
+ });
+
+ test('arama dili seçimi: yalnız tüm kaynaklarda görünür, seçilen dilde arar / search language: only with all sources, searches in the chosen language', async ({
+ page,
+ }) => {
+ test.skip(BOOKS.length < 2, 'iki dilde kitap gerekir / needs books in two languages');
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await expect.poll(() => frameUrl(page)).toContain(`/kiwix/content/${BOOKS[0]}`);
+ // Bir kaynak seçiliyken dil seçimi gizli / hidden while a source is selected
+ await expect(page.locator('#slang')).toBeHidden();
+ await page.selectOption('#books', '');
+ await expect(page.locator('#slang')).toBeVisible();
+ const langs = await page.locator('#slang option').evaluateAll((o) => o.map((x) => x.value));
+ expect(langs.length).toBeGreaterThan(1);
+ for (const l of langs) {
+ await page.selectOption('#slang', l);
+ await page.fill('#q', 'a');
+ await page.press('#q', 'Enter');
+ await expect.poll(() => frameUrl(page)).toContain(`books.filter.lang=${l}`);
+ await expect(page.frameLocator('#frame').locator('body')).not.toContainText('Invalid request');
+ }
+ });
+
+ test('arama çerçevede, seçili kaynakta / search runs in the frame, in the selected source', async ({ page }) => {
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await expect.poll(() => frameUrl(page)).toContain(`/kiwix/content/${BOOKS[0]}`);
+ await page.fill('#q', 'water');
+ await page.press('#q', 'Enter');
+ await expect.poll(() => frameUrl(page)).toMatch(/\/kiwix\/search\?.*pattern=water/);
+ expect(await frameUrl(page)).toContain(`books.name=${BOOKS[0]}`);
+ });
+
+ test('rastgele sayfa / random page', async ({ page }) => {
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await expect.poll(() => frameUrl(page)).toContain(`/kiwix/content/${BOOKS[0]}`);
+ const before = await frameUrl(page);
+ await page.click('#random');
+ await expect.poll(() => frameUrl(page)).not.toBe(before);
+ expect(await frameUrl(page)).toContain(`/kiwix/content/${BOOKS[0]}`);
+ });
+
+ test('ana sayfa düğmesi / home button', async ({ page }) => {
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await page.click('.bar a.home');
+ await expect(page).toHaveURL(/\/home\/$/);
+ });
+
+ test('dil: TR ve EN / language: TR and EN', async ({ page }) => {
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await page.click('[data-lang="en"]');
+ await expect(page.locator('html')).toHaveAttribute('lang', 'en');
+ await expect(page.locator('#books option').first()).toHaveText(/all/i);
+ await page.click('[data-lang="tr"]');
+ await expect(page.locator('html')).toHaveAttribute('lang', 'tr');
+ });
+
+ test('tema seçimi / theme choice', async ({ page }) => {
+ await page.goto(`/home/reader.html#${BOOKS[0]}`);
+ await page.selectOption('#theme', 'dark');
+ expect(await themeOf(page)).toBe('dark');
+ await page.selectOption('#theme', 'light');
+ expect(await themeOf(page)).toBe('light');
+ });
+});
+
+test.describe('kitaplık / library', () => {
+ test.beforeEach(() => test.skip(!BOOKS.length, 'kitap yok / no books (prepare.sh)'));
+
+ test('/kiwix/ okuyucunun kitaplığına gider / /kiwix/ goes to the reader library', async ({ page }) => {
+ await page.goto('/kiwix/');
+ await expect(page).toHaveURL(/\/home\/reader\.html#library/);
+ await expect.poll(() => frameUrl(page)).toContain('/kiwix/?has=1');
+ });
+
+ test('kitaplıkta kitaba tıklayınca okuyucuda açılır / a book clicked in the library opens in the reader', async ({
+ page,
+ }, testInfo) => {
+ await page.goto('/home/reader.html#library');
+ const book = page.frameLocator('#frame').locator('a[href*="viewer#"]').first();
+ const drawn = await book.waitFor({ timeout: 15000 }).then(
+ () => true,
+ () => false,
+ );
+ if (drawn) {
+ await book.click();
+ } else {
+ // Eski tarayıcı: Kiwix kitaplığı liste çizemedi, okuyucu cihazdaki kaynakları düz liste olarak gösterir.
+ // Older browser: Kiwix's library drew no list, the reader shows the sources on the device as a plain list.
+ testInfo.annotations.push({
+ type: 'note',
+ description: 'Kiwix kitaplığı çizilmedi, yedek liste / Kiwix library not drawn, fallback list',
+ });
+ const fallback = page.locator('#msg ul.fallback a').first();
+ await expect(fallback).toBeVisible({ timeout: 20000 });
+ await fallback.click();
+ }
+ await expect(page).not.toHaveURL(/#library/);
+ await expect.poll(() => frameUrl(page)).toContain('/kiwix/content/');
+ });
+
+ test('koyu temada kitaplık da koyu / the library follows the dark theme', async ({ page }) => {
+ await page.goto('/home/reader.html#library');
+ await expect.poll(() => frameUrl(page)).toContain('/kiwix/?has=1');
+ await page.selectOption('#theme', 'dark');
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ try {
+ return !!document.getElementById('frame').contentDocument.getElementById('has-dark');
+ } catch (e) {
+ return false;
+ }
+ }),
+ )
+ .toBe(true);
+ });
+});
diff --git a/scripts/catalog-sizes.sh b/scripts/catalog-sizes.sh
new file mode 100644
index 0000000..cc8b5f1
--- /dev/null
+++ b/scripts/catalog-sizes.sh
@@ -0,0 +1,57 @@
+#!/usr/bin/env bash
+# config/content.conf'taki her ZIM'in en yeni sürümünü ve gerçek boyutunu Kiwix kataloğundan alır,
+# ana sayfanın ve yönetim panelinin okuduğu sizes.json'a yazar. İnternet yoksa eski dosya kalır.
+# Looks up the newest version and real size of each ZIM in config/content.conf in the Kiwix catalog and
+# writes them to sizes.json, read by the homepage and the admin panel. Without internet the old file stays.
+#
+# 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="${SIZES_OUT:-$WEB/home/sizes.json}"
+CATALOG_URL="${CATALOG_URL:-https://library.kiwix.org/catalog/v2/entries?count=-1}"
+
+CAT="${CATALOG_FILE:-}"
+if [ -z "$CAT" ]; then
+ CAT=$(mktemp)
+ trap 'rm -f "$CAT"' EXIT
+ if ! curl -fsSL -m 300 "$CATALOG_URL" -o "$CAT"; then
+ echo "!! Katalog alınamadı, boyutlar güncellenmedi / catalog unreachable, sizes not updated" >&2
+ exit 0
+ fi
+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)
+ 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}"
+ n=$((n + 1))
+done <"$CONF"
+
+[ "$n" -gt 0 ] || { echo "!! Katalogda eşleşen içerik yok / no matching content in the catalog" >&2; exit 0; }
+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 (+$kept eski / kept) → $OUT"
diff --git a/scripts/disk-health.sh b/scripts/disk-health.sh
index a6807db..958136c 100755
--- a/scripts/disk-health.sh
+++ b/scripts/disk-health.sh
@@ -15,7 +15,9 @@ OUT="$WEB/home/disk.json"
warn=()
add(){ warn+=("$1"); echo "!! $1"; }
-if mountpoint -q "$LIB"; then
+# findmnt bağlama tablosuna bakar (mountpoint yalnız aygıt numarasını karşılaştırır); Docker imajında util-linux-misc yok.
+# findmnt reads the mount table (mountpoint only compares device numbers); the Docker image has no util-linux-misc.
+if findmnt -rn --mountpoint "$LIB" >/dev/null; then
src=$(findmnt -no SOURCE "$LIB")
case ",$(findmnt -no OPTIONS "$LIB")," in
*,ro,*) add "Disk salt okunur moda geçmiş. Bu genellikle dosya sistemi hatası demektir; içerikleri yedekleyin.";;
diff --git a/scripts/download-content.sh b/scripts/download-content.sh
index d9670ea..a414674 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; }
@@ -22,7 +24,7 @@ RESERVE_GB="${RESERVE_GB:-5}"
BASE=https://download.kiwix.org/zim
CATALOG_URL="${CATALOG_URL:-https://library.kiwix.org/catalog/v2/entries?count=-1}"
-if ! mountpoint -q /library; then
+if ! findmnt -rn --mountpoint /library >/dev/null; then
if findmnt --fstab --mountpoint /library >/dev/null; then
echo "HATA / ERROR: /library için ayarlı disk bağlı değil / the configured disk for /library is not mounted" >&2
echo "Diski bağlayıp tekrar çalıştır / mount the disk and retry: sudo mount /library" >&2
@@ -86,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
@@ -136,13 +142,16 @@ 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 || {
+# İndirilen katalogla kesin boyutları güncelle (tam content.conf) / refresh exact sizes from the downloaded catalog (full content.conf)
+[ -n "$CAT" ] && CATALOG_FILE="$CAT" "$(dirname "$0")/catalog-sizes.sh" >/dev/null 2>&1
+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
diff --git a/scripts/install-homepage.sh b/scripts/install-homepage.sh
index 3fbb2e9..f2716d9 100755
--- a/scripts/install-homepage.sh
+++ b/scripts/install-homepage.sh
@@ -12,6 +12,25 @@ DST=/library/www/html/home
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/"
+# 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
+# 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"
echo "Geri almak için / to restore: sudo cp $DST/index.html.iiab-original $DST/index.html"
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; }
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..8a0912c
--- /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="/home/reader.html#library"
+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..ce76aa3
--- /dev/null
+++ b/scripts/services.d/maps.sh
@@ -0,0 +1,10 @@
+# shellcheck shell=bash disable=SC2034 # services.sh içine alınır / sourced by services.sh
+# 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(){ [ -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
new file mode 100755
index 0000000..cd0ad16
--- /dev/null
+++ b/scripts/services.sh
@@ -0,0 +1,56 @@
+#!/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
+# 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
+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=""; typical=""
+ check(){ return 1; }
+ size(){ :; }
+ # shellcheck source=/dev/null
+ . "$mod"
+ if check >/dev/null 2>&1; then installed=true; else installed=false; fi
+ # İ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")" "$extra"
+ ) || 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/acil.html b/www/home/acil.html
index ff2d176..397ba30 100644
--- a/www/home/acil.html
+++ b/www/home/acil.html
@@ -3,7 +3,10 @@
-HAS_PrepperDisk :: Acil Durum
+HAS_PrepperDisk :: Acil Durum
+
+
+
+İçeriğe geç
Etikette oran yazmıyorsa çamaşır suyuyla tahmine dayalı doz verme, suyu kaynat.
Kaynatma ve çamaşır suyu ağır metalleri, tuzları ve çoğu kimyasalı temizlemez. Üstünde yüzen madde olan, koyu renkli ya da kötü kokan suyu kullanma.
-
Kaynak: kaynatma süresi ABD Hastalık Kontrol Merkezi (CDC), “How to Make Water Safe in an Emergency”; çamaşır suyu ABD Çevre Koruma Ajansı (EPA), “Emergency Disinfection of Drinking Water” — galon (3,8 litre) başına %6’lık çamaşır suyundan 8 damla; litre başına 2 damla buradan hesaplanmıştır.
+
Kaynak: kaynatma süresi ABD Hastalık Kontrol Merkezi (CDC), “How to Make Water Safe in an Emergency”; çamaşır suyu ABD Çevre Koruma Ajansı (EPA), “Emergency Disinfection of Drinking Water” — EPA ve CDC tablolarında %6’lık çamaşır suyundan litre (quart) başına 2 damla, galon (3,8 litre) başına 8 damla.
@@ -132,8 +189,127 @@
“Sağlık ve İlk Yardım” ve “Hayatta Kalma ve Hazırlık” bölümlerinde. Bu sayfa resmi kaynakların özetidir; sağlık ekiplerinin ve yetkililerin
talimatları her zaman önceliklidir.
Drop, cover, hold on: in a safe spot, drop to your knees, take cover protecting your head and neck, and hold on to something fixed so you do not fall.
+
Do not run to the stairs or the exits. Do not go out on a balcony, and do not jump from a balcony or a window.
+
Do not use the lift.
+
Do not strike matches or lighters; do not touch electrical switches.
+
Stay away from cupboards, shelves and windows that are not secured.
+
If you are outdoors: drop in an open space away from buildings, trees, poles and power lines. Move away from the foot of slopes and from the seashore.
+
If you are in a vehicle: if the spot is safe, pull over to the right without blocking the road, stop, and wait in the vehicle until the shaking ends. If you are somewhere unsafe, such as on a bridge or next to a tree or a pole, stop the vehicle, leave the key in the ignition and go to an open area.
+
+
Source, translated from Turkish: AFAD Bursa Provincial Directorate, “Deprem” (Earthquake) (bursa.afad.gov.tr/deprem); AFAD Istanbul Provincial Directorate, “Deprem Sonrası İlk 6 Saate Dikkat” (Mind the first 6 hours after an earthquake), 02.03.2021.
+
+
+
+
If you are trapped under debris
+
+
Check your situation without panicking.
+
If you cannot move, do not attempt anything that risks your life to get out. Rescue teams will try to reach you.
+
Keep your movements under control to save your energy.
+
If you can use your hands or feet, make yourself heard by tapping on water, heating or gas pipes or on the floor.
+
If you can use your voice, listen for the rescue teams and call out to them, but use your energy carefully.
+
Do not strike matches or lighters.
+
+
Source, translated from Turkish: AFAD Bursa Provincial Directorate, “Deprem” (Earthquake) — “Yıkıntı altında mahsur kaldıysanız” (If you are trapped under debris).
+
+
+
+
After an earthquake
+
+
First make sure you are safe, then see whether anyone around you needs help.
+
Put on your shoes. Check whether you or your family are injured.
+
Turn off the stove and the water valve. If there is no smell of gas, switch off the electricity at the main switch. If you smell gas, close the gas valve, open the windows and doors and leave the building at once.
+
Take your emergency bag, leave the building and walk to the nearest assembly area. Stay there until the authorities call you.
+
Large earthquakes are followed by aftershocks. Do not enter damaged buildings until the shaking has stopped completely. During aftershocks, also drop, cover and hold on.
+
Do not use your car for the first 6 hours, so that emergency vehicles can get through; keep the roads clear.
+
Stay away from damaged buildings and power lines. Help elderly people, babies and people with disabilities.
+
+
Source, translated from Turkish: AFAD Istanbul Provincial Directorate, “Deprem Sonrası İlk 6 Saate Dikkat”; AFAD Bursa Provincial Directorate, “Deprem” (Earthquake) and “Afete Hazır Aile” (Disaster-ready family).
+
+
+
+
Drinking water
+
+
Boil or disinfect water before drinking it if you are not sure it is clean.
+
If water is cloudy, let it settle and filter it through a clean cloth, paper towel, or coffee filter.
+
Boiling: bring clear water to a rolling boil for 1 minute (at elevations above 6,500 feet, about 2,000 metres, boil for 3 minutes).
+
Bleach: only use regular, unscented chlorine bleach products that are suitable for disinfection and sanitization as indicated on the label. Do not use scented, color safe, or bleaches with added cleaners. If the label says 6% sodium hypochlorite, add 2 drops per quart or litre of water. Double the amount of bleach if the water is cloudy, colored, or very cold. Stir and let stand for 30 minutes. The water should have a slight chlorine odor. If it doesn’t, repeat the dosage and let stand for another 15 minutes before use.
+
If the label gives no concentration, do not guess a bleach dose; boil the water instead.
+
Boiling or disinfection will not destroy other contaminants, such as heavy metals, salts, and most other chemicals. Do not use water with floating material in it or water that has a dark color or questionable odor.
+
+
Source: boiling, US Centers for Disease Control and Prevention (CDC), “How to Make Water Safe in an Emergency”; bleach, US Environmental Protection Agency (EPA), “Emergency Disinfection of Drinking Water” — in the EPA and CDC tables, 2 drops of 6% bleach per quart or litre, 8 drops per gallon (3.8 litres). Wording from the original English pages.
+
+
+
+
Communication
+
+
Do not make calls through the operator, so that the lines do not get jammed; use text messages and internet-based apps instead.
+
Use the phone only to report emergencies and fires.
+
Listen to the warnings given on the radio and other mass media.
+
Choose a contact person outside the area in advance; everyone in the family lets that person know how they are.
+
+
Source, translated from Turkish: AFAD Istanbul Provincial Directorate, “Deprem Sonrası İlk 6 Saate Dikkat”; AFAD Bursa Provincial Directorate, “Deprem” (Earthquake) and “Afete Hazır Aile” (Disaster-ready family).
+
+
+
+
Protect yourself from carbon monoxide
+
+
Do not run a generator, a barbecue or a car engine in a closed or poorly ventilated place. Tents and caravans count as closed spaces.
+
Where a stove, a water heater or a boiler is used, do not block the ventilation openings; do not sleep in a room with a burning heater.
+
If you have a headache, dizziness, weakness or tiredness, get into fresh air, get others out too, and call 112.
+
+
Source, translated from Turkish: Istanbul Provincial Health Directorate, “Karbonmonoksit Zehirlenmesi” (Carbon monoxide poisoning).
+
+
+
+
Disaster and emergency bag (first 72 hours)
+
+
Food and water
+
First-aid supplies
+
Torch and whistle
+
Copies of important documents (keep one copy with your contact person outside the area too)
+
Next to your bed: water, a whistle, a torch and shoes
+
+
Source, translated from Turkish: AFAD Bursa Provincial Directorate, “Afete Hazır Aile” (Disaster-ready family).
+
+
+
+
More
+
Detailed resources on first aid, water treatment and shelter are in the “Health and First Aid” and
+ “Survival and Preparedness” sections of the homepage. This page is a summary of official sources;
+ instructions from health teams and the authorities always come first.
+
+
-
HAS_PrepperDisk · Bu sayfa çevrimdışı çalışır, yazdırılabilir.