feat(template): publish the Mithlond self-hosted Gitea template

A spare-machine Gitea forge, hardened, backed up and with CI, as a template.
Personal values are placeholders listed in the README.
This commit is contained in:
Łukasz Boryń 2026-10-16 15:00:47 +02:00
commit c12604ebb4
50 changed files with 4190 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
gitea-data/
caddy-data/
caddy-config/
HANDOFF.md
vm/
runner-data/

52
AGENTS.md Normal file
View File

@ -0,0 +1,52 @@
## Knowledge — read before you code
This project keeps an agent-first wiki at [`OKF/`](OKF/index.md)
(open-knowledge-format). Before extending or modifying mithlond:
1. Read [`OKF/index.md`](OKF/index.md), then the pages it flags for your
task — at minimum `SUMMARY.md`; `ARCHITECTURE.md` before structural
work.
2. Use the canonical vocabulary from [`OKF/CONTEXT.md`](OKF/CONTEXT.md)
in code, tests, and commit messages. Don't coin synonyms.
3. Non-trivial changes start from a blueprint in `OKF/blueprints/` — write one
(blueprint skill) before implementing; cite its number in the commit.
4. Learned something that contradicts the wiki? Update the wiki in the
same change (supersede, don't delete) or append to
`OKF/LEARNINGS.md`.
## Behavioral guardrails
- State assumptions explicitly; name the simpler approach you are
rejecting; surface tradeoffs. Push back when warranted — if something
is unclear, stop and ask rather than guess.
- Do exactly what the task requires, nothing more. No speculative
abstractions, no drive-by refactors.
- A green test suite is a claim, not a proof — verify against the
blueprint's stated check before calling work done.
## Simplicity & rigor
- **Think before coding** — when multiple interpretations exist, present
them; don't pick silently.
- **Three sieves before a line stays**: real (not speculative — no error
handling for impossible scenarios, no unrequested flexibility or
configurability), good (nameably better for the next reader), minimal
(leanest form — stdlib/existing code before new). Burden is on keeping,
not cutting. Exceptions that always pass *good*: input validation,
error handling that prevents data loss, security, accessibility,
explicitly requested behaviour.
- **Surgical changes** — match existing style; notice unrelated dead code
and mention it, don't delete it; clean up only your own mess (remove
orphans your change created, not pre-existing dead code); every changed
line should trace to the request.
- **Goal-driven execution** — turn the task into a verifiable check
before starting: "add validation" → "write tests for invalid inputs,
then make them pass"; "fix the bug" → "write a test that reproduces
it, then make it pass". For multi-step work, state a brief plan, each
step naming its own verify. Strong success criteria let you loop
independently; weak ones ("make it work") need constant clarification.
## Repo conventions — mithlond
TODO(init-octobot): no conventions detected yet — fill in once the repo
has code, tests, or a lint config to scan.

6
CLAUDE.md Normal file
View File

@ -0,0 +1,6 @@
# CLAUDE.md — mithlond
Read [`AGENTS.md`](AGENTS.md) first — it carries the full behavioral
contract (knowledge, guardrails, simplicity & rigor, repo conventions).
This file exists only because some tooling looks for `CLAUDE.md` by name;
it adds nothing AGENTS.md doesn't already say.

58
Caddyfile Normal file
View File

@ -0,0 +1,58 @@
# Global options.
# email sets the Let's Encrypt / ACME account contact (cert expiry notices).
# For the staging test (OKF/guides/06 step 5) uncomment the acme_ca line, then
# re-comment it for production (step 6). Staging avoids LE rate limits.
{
email you@example.com
# acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
}
git.example.com {
reverse_proxy gitea:3000
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
X-Content-Type-Options "nosniff"
X-Frame-Options "SAMEORIGIN"
Referrer-Policy "strict-origin-when-cross-origin"
Permissions-Policy "geolocation=(), microphone=(), camera=()"
}
encode gzip
log {
output file /data/caddy-access.log {
roll_size 10mb
roll_keep 5
}
}
}
# Optional: a second site on the apex domain, e.g. a portfolio. It runs as its
# own compose stack, joins the shared "edge" network, and this block is the only
# thing in front of it. Rename `portfolio:8000` to its service name and port, or
# delete this block and the www block below if you only host Gitea.
example.com {
reverse_proxy portfolio:8000
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
X-Content-Type-Options "nosniff"
X-Frame-Options "SAMEORIGIN"
Referrer-Policy "strict-origin-when-cross-origin"
Permissions-Policy "geolocation=(), microphone=(), camera=()"
}
encode gzip
log {
output file /data/caddy-access.log {
roll_size 10mb
roll_keep 5
}
}
}
www.example.com {
redir https://example.com{uri} permanent
}

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Lukasz Boryn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

55
OKF/ARCHITECTURE.md Normal file
View File

@ -0,0 +1,55 @@
---
type: Architecture
purpose: Map the services, their seams, and how outside traffic reaches each one.
answers:
- "What are this project's modules and seams, and how does behaviour flow through them?"
cites:
- compose.yml
- Caddyfile
- runner/config.yaml
- scripts/gitea-backup
- systemd/gitea-backup.timer
---
# Mithlond — architecture
## Request path
```
Internet
│
├─ :443 (HTTPS) ──► Router ──► :443 host ──► Caddy ──► git.example.com → gitea:3000
│ └────► example.com → portfolio:8000 (optional)
├─ :80 (ACME) ──► Router ──► :80 host ──► Caddy
├─ :2222 (SSH) ──► Router ──► :2222 host ──► Gitea container :22
└─ :2234 (admin)──► LAN only (not forwarded) ──► sshd (Arch host)
DNS: git.example.com and example.com A → home IP (Cloudflare, DNS-only)
DDNS: ddclient on the host updates both A records via the Cloudflare API
```
## Services
- **gitea** (`compose.yml:gitea`) — `gitea/gitea:1.23`, SQLite. State in the
bind-mount `./gitea-data/` → `/data`. Web on `127.0.0.1:3000` only, so the
web UI is reachable from outside only through Caddy; SSH on `0.0.0.0:2222`.
Hardening and registration lock are env vars, which win over `app.ini` on
every start (`compose.yml:GITEA__service__DISABLE_REGISTRATION`).
- **caddy** (`compose.yml:caddy`) — owns 80/443, TLS from Let's Encrypt,
certificates in `./caddy-data/`. One site block per name (`Caddyfile`).
- **runner** (`compose.yml:runner`) — `gitea/act_runner`, polls Gitea over
HTTPS and starts each job as a sibling container through the host Docker
socket. One job at a time, label `alpine` (`runner/config.yaml:capacity`).
## Seams
- **`edge` network** (`compose.yml:external: true`) — shared with an optional
apex-site stack (e.g. a portfolio), which joins it from its own compose file.
That site ships no proxy; the
`example.com` block in `Caddyfile` is the only thing in front of it.
- **Env over `app.ini`** — Gitea config that must stay put lives in
`compose.yml`; `docker compose up -d` re-applies it.
- **Backup boundary** — `gitea-data/` is the only state that matters. The
nightly `gitea-backup.timer` runs `scripts/gitea-backup`, which stops
Gitea, snapshots that directory into restic on the backup drive, and starts it again.
Caddy keeps serving the apex while Gitea is stopped.

36
OKF/CONTEXT.md Normal file
View File

@ -0,0 +1,36 @@
---
type: Glossary
purpose: Hold the one canonical glossary for Mithlond.
answers:
- "What does each domain term in this project mean, canonically?"
cites:
- compose.yml
---
# Mithlond — Vocabulary
See [ROADMAP.md](ROADMAP.md) for the project plan. Terms here are canonical; Roadmap uses these exact names.
## Terms
**Gitea** — self-hosted Git forge (issue tracker, code review, user management). Runs as a single Docker container. Public/private repos controlled per-repository.
**Caddy** — reverse proxy with automatic TLS via Let's Encrypt. Handles HTTPS termination; forwards to Gitea internally.
**Docker Compose** — multi-container orchestration tool. Single `compose.yml` defines Gitea + Caddy services, volumes, and networking.
**SQLite** — embedded database used by Gitea. No separate process; stored as a single file inside the Gitea data volume.
**DDNS (Dynamic DNS)** — mechanism that keeps a domain A record pointing at a home IP address that changes. Implemented via ddclient + Cloudflare DNS API.
**ddclient** — daemon that detects home IP changes and updates the Cloudflare DNS A record automatically.
**Gitea data volume** — Docker bind-mount directory (`./gitea-data/`) containing all Gitea state: SQLite DB, bare repos, config (`app.ini`), attachments, avatars.
**gitea dump** — built-in Gitea CLI command that produces a zip archive of all Gitea state. Alternative to raw volume copy for backups.
**Port forward** — router rule directing an external port to an internal machine port. Three required: 80 (HTTP→ACME), 443 (HTTPS), 2222 (Gitea SSH).
**Admin SSH** — SSH access to the Arch host for server management. Runs on a non-standard port (2234) to avoid conflict with Gitea SSH on 2222.
**Gitea SSH** — SSH endpoint for `git push`/`git clone` over SSH. Gitea container listens on port 22 internally, mapped to host port 2222.

89
OKF/ROADMAP.md Normal file
View File

@ -0,0 +1,89 @@
---
type: Roadmap
purpose: Carry the phased plan, its verify evidence, live risks and what stays out of scope.
answers:
- "What is this project building next, and how is each phase verified?"
cites:
- decisions/index.md
- compose.yml
---
# Mithlond Roadmap
Self-hosted Git server on a spare machine running Arch Linux. Gitea served publicly via your own domain with per-repository public/private control, plus an optional site on the apex domain. Work through the phases in order; each has a verify step. The step-by-step version is [guides/index.md](guides/index.md). See [CONTEXT.md](CONTEXT.md) for vocabulary.
## Locked decisions
The why-register: [decisions/index.md](decisions/index.md) — forge, database,
proxy, orchestration, DNS, SSH ports, manual backup format. How the pieces
connect: [ARCHITECTURE.md](ARCHITECTURE.md).
## Phases
### Phase 0 — Arch Linux base
- Install Arch Linux (headless, minimal)
- Create non-root user with sudo
- Install: `docker`, `docker-compose`, `ddclient`, `openssh`, `nftables`
- Harden SSH: key-only auth, move to port 2234 (`/etc/ssh/sshd_config`)
- Configure nftables: allow 22→2234, 80, 443, 2222; drop everything else inbound
- Enable services: `sshd`, `docker`, `nftables`
**Verify:** SSH into host on port 2234 with key only; password attempt rejected; `docker run hello-world` succeeds.
### Phase 1 — DNS and DDNS
- Point `git.example.com` A record to home IP in Cloudflare (DNS-only, grey cloud)
- Configure ddclient with Cloudflare API token, zone, record name
- Enable and start `ddclient` systemd service
**Verify:** `dig git.example.com` returns home IP; ddclient log shows successful update.
### Phase 2 — Gitea + Caddy deploy
- Write `compose.yml`: Gitea (SQLite) + Caddy services, volumes, network
- Write `Caddyfile`: `git.example.com` → `http://gitea:3000`, automatic TLS
- Router: forward external 80→80, 443→443, 2222→2222 to the server's LAN IP
- Start stack: `docker compose up -d`
- Complete Gitea install wizard (admin account, site URL, SSH clone URL with port 2222)
- Disable or require-approval for public registration
**Verify:** `https://git.example.com` loads with valid cert; create test repo; `git clone https://git.example.com/user/repo.git` from external machine succeeds; `git push` via SSH (`ssh -p 2222`) succeeds; public repo visible without login; private repo returns 404 without login.
### Phase 3 — Hardening
- fail2ban: protect admin SSH (port 2234) and Gitea login endpoint
- Gitea `app.ini`: disable raw git HTTP if not needed, set `[server] LFS_START_SERVER = false` unless needed
- Caddy security headers: `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`
- Verify nftables rules survive reboot
**Verify:** 10 failed SSH attempts trigger fail2ban ban; 10 failed Gitea logins trigger ban; headers present in `curl -I https://git.example.com`.
### Phase 4 — Backup procedure
- Archive `gitea-data/` to the portable HDD and restore-test it — procedure in [guides/10-backup-manual.md](guides/10-backup-manual.md), scripted as `scripts/backup.sh`
**Verify:** Restore test completes successfully; repos and issues intact after restore from backup. Check: `integrity_check` ok, every repo fscks clean, a throwaway Gitea boots on the restored copy.
### Phase 4b — Automated backup
- Nightly restic snapshot of `gitea-data/` to the portable HDD via systemd timer, failure mail, weekly report — [guides/11-backup-automated.md](guides/11-backup-automated.md)
**Verify:** First run, restore test, failure mail and `check --read-data` all pass; timer enabled.
### Phase 5 — Optional site on the apex domain
- Build it as its own project (e.g. a portfolio) with its own compose stack and systemd unit — not a service in this `compose.yml`
- Caddy serves `example.com` → `portfolio:8000` over the shared external `edge` Docker network; `www` → 301 → apex
- Keep it stateless if you can, so there is nothing to back up
## Risks & gotchas
- **HDD failure** — an old spinning HDD is the highest failure risk. Manual backup to portable HDD is the only mitigation. Back up before any system update.
- **ISP blocks port 80/443** — some residential ISPs block these. Test early (Phase 2 step 1). Fallback: use port 8443 for HTTPS and tell git clients to use that port; Caddy can listen on any port.
- **Dynamic IP gap** — ddclient polls on an interval; short window where IP changes and DNS is stale. Mitigated by short TTL on Cloudflare A record (1 min minimum on free plan).
- **Arch rolling release** — system updates can break Docker or nftables. Pin Gitea image to a specific tag (e.g., `gitea/gitea:1.23`), not `latest`. Test updates on a spare machine or snapshot before applying.
- **Let's Encrypt rate limits** — 5 failed cert issuances per domain per hour. Test Caddy config with `acme_ca https://acme-staging-v02.api.letsencrypt.org/directory` staging endpoint first.
- **Thermal throttling** — an old laptop under sustained load may throttle. Monitor with `sensors` package; ensure cooling is adequate for always-on operation.
## Out of scope (v1)
- CI/CD — added later as an extra phase: Gitea Actions runner on the server, see [guides/12-gitea-actions.md](guides/12-gitea-actions.md)
- Container/package registry
- Email notifications from Gitea
- Off-site backup copy (left out by default — the drive shares fire/theft risk with the server; outbound-only `restic copy` if ever wanted — see [guides/11-backup-automated.md](guides/11-backup-automated.md))
- Gitea federation (ActivityPub)
- Multiple users / organization management

30
OKF/SUMMARY.md Normal file
View File

@ -0,0 +1,30 @@
---
type: Summary
purpose: Say what Mithlond is and where to read next, for an agent landing cold.
answers:
- "What is this project, and where should an agent start reading?"
cites:
- compose.yml
- Caddyfile
- README.md
---
# Mithlond — summary
**What**: a template for running a self-hosted Gitea git forge on a spare
machine (an old laptop works) with headless Arch Linux, public at
`git.example.com` with per-repository public/private control, plus an optional
site on the apex `example.com`. Every guide was proven on a 2008 laptop; the
values you must change are placeholders, listed in the README.
**Stack**: Docker Compose running Gitea (SQLite), Caddy (automatic TLS) and a
Gitea Actions runner; ddclient + Cloudflare for DDNS; nftables and fail2ban on
the host; nightly restic backups to a portable NTFS HDD.
**Run it**: on the server, `docker compose up -d` from `~/mithlond`. The
build itself is the twelve guides in order.
**Read next**: [guides/index.md](guides/index.md) for the setup order,
[ARCHITECTURE.md](ARCHITECTURE.md) for how traffic reaches each service,
[CONTEXT.md](CONTEXT.md) for vocabulary, [decisions/index.md](decisions/index.md)
for why the stack is what it is.

View File

@ -0,0 +1,15 @@
---
type: Decision
purpose: Record why the forge is Gitea and not a heavier or less maintained alternative.
answers:
- "Which forge runs on the server: Gitea, GitLab, Gogs or Forgejo?"
cites:
- compose.yml:gitea/gitea
status: live
reversible: Forgejo is a compatible Gitea fork, so a switch is an image swap; GitLab would be a migration.
---
# 001 — Gitea as the forge
Gitea. GitLab needs 4GB+ RAM, more than an old laptop has. Gogs is unmaintained.
Forgejo is compatible but has the smaller ecosystem.

View File

@ -0,0 +1,17 @@
---
type: Decision
purpose: Record why Gitea stores its state in SQLite.
answers:
- "Which database backs Gitea: SQLite or PostgreSQL?"
cites:
- compose.yml:GITEA__database__DB_TYPE=sqlite3
status: live
reversible: Migrate to PostgreSQL later via gitea dump plus restore.
---
# 002 — SQLite as Gitea's database
SQLite. It is right-sized for personal use, needs no extra container or RAM,
and makes the backup one data directory. PostgreSQL would add a container for
no gain at this scale. Consequence: Gitea must be stopped while its data is
copied ([guides/10](../guides/10-backup-manual.md), [guides/11](../guides/11-backup-automated.md)).

View File

@ -0,0 +1,17 @@
---
type: Decision
purpose: Record why Caddy is the reverse proxy.
answers:
- "Which reverse proxy terminates TLS: Caddy, Nginx or Traefik?"
cites:
- Caddyfile
- compose.yml:caddy:2
status: live
reversible: Cheap; the proxy holds no state beyond its certificates.
---
# 003 — Caddy as reverse proxy
Caddy. Automatic Let's Encrypt removes certificate renewal from the ops
burden. Nginx with certbot means manual renewal and more config; Traefik is
overkill for two sites.

View File

@ -0,0 +1,15 @@
---
type: Decision
purpose: Record why the services run under Docker Compose.
answers:
- "What runs the services: Docker Compose or Podman?"
cites:
- compose.yml
status: live
reversible: Moderate; compose.yml would need porting.
---
# 004 — Docker Compose for orchestration
Docker Compose. 3GB headless is enough for the Docker daemon, and Gitea's
official compose files are Docker-based. Podman was the alternative.

View File

@ -0,0 +1,17 @@
---
type: Decision
purpose: Record why the server is reached through an own domain on Cloudflare DDNS.
answers:
- "How is the home server reached by name: own domain on Cloudflare or DuckDNS?"
cites:
- Caddyfile:git.example.com
status: live
reversible: Moving DNS provider means a new ddclient config and API token.
---
# 005 — Own domain with Cloudflare DDNS
Own domain `example.com`, DNS on Cloudflare, records kept current by
ddclient through Cloudflare's free API. DuckDNS is free but less professional.
Records are DNS-only (grey cloud). Setup: [guides/04](../guides/04-dns-records.md),
[guides/05](../guides/05-ddns.md).

View File

@ -0,0 +1,17 @@
---
type: Decision
purpose: Record how admin SSH and Gitea SSH share the host without colliding.
answers:
- "Which ports carry admin SSH and Gitea SSH, and which is reachable from outside?"
cites:
- compose.yml:0.0.0.0:2222:22
status: live
reversible: Cheap to renumber; exposing admin SSH publicly would reverse the security posture.
---
# 006 — Admin SSH on 2234, Gitea SSH on 2222
Admin SSH on 2234 and Gitea SSH on 2222 avoid both fighting over port 22. The
router forwards only 80, 443 and 2222; admin SSH stays LAN-only by design and is
reached from outside over the router's WireGuard
([guides/03](../guides/03-ssh-hardening.md) §7).

View File

@ -0,0 +1,17 @@
---
type: Decision
purpose: Record why the manual backup is a tar archive of the data volume.
answers:
- "What does a manual backup copy: a tar of gitea-data or a gitea dump?"
cites:
- scripts/backup.sh
status: live
reversible: Cheap; the nightly restic backup does not depend on it.
---
# 007 — Volume archive for manual backups
Stop Gitea, `tar -czpf` `./gitea-data/` to the portable HDD, start Gitea.
Simpler than `gitea dump` for a manual workflow. A tar archive, not a `cp -r`
copy: the HDD is NTFS and cannot hold the owners and modes of
`gitea-data/ssh/`. Procedure: [guides/10](../guides/10-backup-manual.md).

15
OKF/decisions/index.md Normal file
View File

@ -0,0 +1,15 @@
---
type: Index
---
# Decisions
The why-register. One line per settled decision: question — verdict — status.
- [001](R-001-gitea-forge.md) — Which forge runs on the server: Gitea, GitLab, Gogs or Forgejo? — Gitea — live
- [002](R-002-sqlite.md) — Which database backs Gitea: SQLite or PostgreSQL? — SQLite — live
- [003](R-003-caddy.md) — Which reverse proxy terminates TLS: Caddy, Nginx or Traefik? — Caddy — live
- [004](R-004-docker-compose.md) — What runs the services: Docker Compose or Podman? — Docker Compose — live
- [005](R-005-domain-cloudflare-ddns.md) — How is the home server reached by name: own domain on Cloudflare or DuckDNS? — own domain, Cloudflare DDNS — live
- [006](R-006-ssh-ports.md) — Which ports carry admin SSH and Gitea SSH, and which is reachable from outside? — 2234 LAN-only, 2222 public — live
- [007](R-007-tar-volume-archive.md) — What does a manual backup copy: a tar of gitea-data or a gitea dump? — tar of gitea-data — live

View File

@ -0,0 +1,211 @@
---
type: Guide
purpose: Install headless Arch Linux on an old laptop or mini PC from a live USB.
answers:
- "How is the base OS installed on the server?"
---
# 01 — Arch Linux Install
Headless Arch Linux on BIOS-based hardware (an old laptop works well). No desktop environment. Ethernet recommended during install.
## Prerequisites
- USB drive ≥ 1GB
- Arch Linux ISO: https://archlinux.org/download/
- Tool to write ISO: `dd` on Linux/macOS, Rufus or Etcher on Windows
- Ethernet cable connected to router
## 1. Write bootable USB
```bash
# Linux/macOS — replace /dev/sdX with your USB device
dd if=archlinux-*.iso of=/dev/sdX bs=4M status=progress oflag=sync
```
## 2. Boot from USB
Enter BIOS (usually F2, F12 or Del, depending on the vendor). Set USB as first boot device. Save and reboot.
## 3. Verify internet and clock
```bash
ping -c 3 archlinux.org
```
If no connection: `ip link` to find interface name, then `dhcpcd <interface>`.
Sync the clock. An old laptop very likely has a dead CMOS battery, so the clock
resets to its factory date on every power-off. A wrong clock makes `pacstrap` fail with GPG
signature errors that look like a broken mirror.
```bash
timedatectl set-ntp true
sleep 10
timedatectl # confirm the date is correct and "System clock synchronized: yes"
```
## 4. Partition disk
Find the disk name. **Do not assume `/dev/sda`** — with the installer USB
plugged in, the USB stick itself is often `/dev/sda` and the internal drive is
`/dev/sdb`. Partitioning the wrong one destroys the installer mid-install.
```bash
lsblk -o NAME,SIZE,MODEL,TRAN
```
Pick the device with `TRAN=sata` — the internal laptop HDD (~120–320GB). Never
the `TRAN=usb` device (the ~57.7G Kingston DataTraveler installer).
Store it once so the rest of this section can't pick the wrong disk:
```bash
DISK=/dev/sdX # replace sdX with the TRAN=sata device
lsblk "$DISK" # verify: correct size, no usb model name
```
Partition with fdisk (MBR layout for BIOS hardware):
```bash
fdisk "$DISK"
```
Inside fdisk:
```
o # new MBR partition table
n # new partition
p # primary
1 # partition 1
<enter> # default start
+512M # 512MB for /boot
n # new partition
p # primary
2 # partition 2
<enter> # default start
+2G # 2GB swap
n # new partition
p # primary
3 # partition 3
<enter> # default start
<enter> # rest of disk for /
t # change type
2 # select partition 2
82 # Linux swap
w # write and exit
```
## 5. Format partitions
```bash
mkfs.ext4 "${DISK}1" # /boot
mkswap "${DISK}2"
swapon "${DISK}2"
mkfs.ext4 "${DISK}3" # /
```
## 6. Mount
```bash
mount "${DISK}3" /mnt
mkdir /mnt/boot
mount "${DISK}1" /mnt/boot
```
## 7. Install base system
```bash
pacstrap -K /mnt \
base base-devel linux linux-firmware \
intel-ucode \
grub \
networkmanager \
openssh \
docker docker-compose \
ddclient \
nftables \
fail2ban \
vim \
sudo
```
## 8. Generate fstab
```bash
genfstab -U /mnt >> /mnt/etc/fstab
cat /mnt/etc/fstab # verify — three entries: /boot, swap, /
```
## 9. chroot
```bash
arch-chroot /mnt
```
## 10. Configure locale and timezone
```bash
# Set timezone — replace with your zone
ln -sf /usr/share/zoneinfo/Europe/Warsaw /etc/localtime
hwclock --systohc
# Locale
sed -i 's/#en_US.UTF-8/en_US.UTF-8/' /etc/locale.gen
locale-gen
echo "LANG=en_US.UTF-8" > /etc/locale.conf
```
## 11. Hostname
```bash
echo "mithlond" > /etc/hostname
```
Add to `/etc/hosts`:
```
127.0.0.1 localhost
::1 localhost
127.0.1.1 mithlond.localdomain mithlond
```
## 12. Install GRUB bootloader
`$DISK` does not exist inside the chroot — type the real device from step 4
(the `TRAN=sata` one), with no partition number.
```bash
grub-install --target=i386-pc /dev/sdX
grub-mkconfig -o /boot/grub/grub.cfg # picks up intel-ucode automatically
```
## 13. Create user
```bash
# Set root password (needed for recovery only)
passwd
# Create non-root user
useradd -m -G wheel,docker -s /bin/bash admin
passwd admin
# Allow wheel group to use sudo
sed -i 's/# %wheel ALL=(ALL:ALL) ALL/%wheel ALL=(ALL:ALL) ALL/' /etc/sudoers
```
## 14. Enable services
```bash
systemctl enable sshd
systemctl enable NetworkManager
systemctl enable docker
```
**Do not enable `nftables` or `fail2ban` here.** Both are installed but have no
configuration yet. Enabling `nftables` now loads Arch's stock ruleset, which
permits port 22 and rejects everything else — so the moment SSH moves to port
2234 in [03-ssh-hardening.md](03-ssh-hardening.md) you lock yourself out and
have to walk back to the machine. They get enabled with their real configs in
[03](03-ssh-hardening.md), [08-firewall.md](08-firewall.md) and
[09-fail2ban.md](09-fail2ban.md).

View File

@ -0,0 +1,132 @@
---
type: Guide
purpose: Make the laptop behave as an always-on server with a fixed LAN address.
answers:
- "How does the laptop become an always-on server with a fixed IP?"
---
# 02 — Server First Boot
Turn the fresh install into an always-on headless server. Step 1 still runs
inside the chroot from [01-arch-install.md](01-arch-install.md).
## 1. Stop the lid from suspending the server
This is a laptop acting as a headless server. systemd's default is to suspend on
lid close, which takes the whole box off the network.
Use a drop-in, not an append to `logind.conf`. The drop-in carries its own
`[Login]` header, so it cannot land in the wrong section, and a package upgrade
that rewrites the shipped file leaves it untouched:
```bash
mkdir -p /etc/systemd/logind.conf.d
cat > /etc/systemd/logind.conf.d/10-lid.conf <<'EOF'
[Login]
HandleLidSwitch=ignore
HandleLidSwitchExternalPower=ignore
HandleLidSwitchDocked=ignore
EOF
```
All three keys are needed. `HandleLidSwitch` covers battery only —
a server that is permanently plugged in follows
`HandleLidSwitchExternalPower`, so setting just the first one is the common
way to end up with a box that still suspends.
Takes effect on the reboot in step 2. **Verify after that reboot** — this
setting fails silently, and the symptom (a server that vanishes when the lid is
shut) looks like a network or power fault:
```bash
systemd-analyze cat-config systemd/logind.conf | grep -i lidswitch
```
Expect the three commented defaults, then your three uncommented overrides
below them. Overrides win by appearing later. If only commented lines appear,
the drop-in did not land — likely written outside the chroot.
Applying it on an already-running system needs no reboot:
```bash
sudo systemctl restart systemd-logind
```
## 2. Exit and reboot
```bash
exit # leave chroot
umount -R /mnt
reboot
```
Remove USB when machine restarts.
## 3. First login and network
Log in as `admin`. Check network:
```bash
nmcli device status
# if ethernet not connected:
nmcli connection up "Wired connection 1"
```
Verify internet: `ping -c 3 archlinux.org`
Turn off wifi. A server with two interfaces on the same subnet gets two
addresses, and the router's port forwards only target one of them:
```bash
nmcli radio wifi off
```
Note the ethernet address and MAC — every later doc depends on them:
```bash
ip -4 addr show # 192.168.1.50
ip link # note the MAC of the wired interface
```
## 4. Pin the server's IP at the router
DHCP will move this address on its own. When it relocates the server, SSH
breaks and it looks exactly like a dead host. Every
port forward in [03](03-ssh-hardening.md) and [06](06-docker-deploy.md) fails
silently the next time it happens.
Reserve it at the router — a DHCP reservation is better than a static address on
the host, because the router then never offers that IP to anything else.
*Adapt if yours differs: menu names below are from one TP-Link model.*
Browse to the router's admin page (often `http://192.168.1.1`), log in, then:
```
Advanced → Network → DHCP Server → Address Reservation → Add
MAC Address: <server MAC from ip link>
IP Address: 192.168.1.50
```
Save, reboot the server, confirm the address held:
```bash
ip -4 addr show
```
While you are in the admin panel, close two defaults that undercut everything
in [08-firewall.md](08-firewall.md):
```
Advanced → NAT Forwarding → UPnP → disable
Advanced → System Tools → Administration → Remote Management → disable
```
UPnP lets any device on the LAN open ports through the firewall without asking.
Remote Management exposes the router's own admin UI to the internet, and on
port 443 it also collides with the forward Caddy needs in
[06-docker-deploy.md](06-docker-deploy.md).
## Next step
Continue with [03-ssh-hardening.md](03-ssh-hardening.md).

View File

@ -0,0 +1,227 @@
---
type: Guide
purpose: Lock admin SSH to keys on port 2234, LAN-only, with WireGuard for remote access.
answers:
- "How is admin SSH to the host hardened?"
---
# 03 — SSH Hardening
Key-only SSH auth on non-standard port. Password auth disabled. Applies to admin SSH only (host management). Git SSH on port 2222 is handled by the Gitea container.
## Prerequisites
- Arch Linux installed and accessible on LAN
- SSH key pair generated on your local machine
- Know the server's local IP: run `ip a` on server or check router DHCP table
## 1. Copy your public key to the server
Run this from your **local machine**, not the server:
```bash
ssh-copy-id -p 22 admin@192.168.1.50
```
If `ssh-copy-id` is not available:
```bash
cat ~/.ssh/id_ed25519.pub | ssh admin@192.168.1.50 \
"mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
```
Test key login works **before** disabling password auth:
```bash
ssh -p 22 admin@192.168.1.50
# should log in without asking for password
```
## 2. Confirm nothing will block the new port
Before moving SSH off port 22, make sure no firewall is rejecting 2234. A loaded
ruleset that permits only port 22 means the restart in step 3 locks you out.
```bash
systemctl is-active nftables # expect: inactive
sudo nft list ruleset # expect: no output
```
If a ruleset is loaded, flush it — `systemctl stop nftables` does **not** remove
already-loaded rules from the kernel:
```bash
sudo nft flush ruleset
sudo systemctl disable nftables
```
The host firewall gets its real config and is re-enabled in
[08-firewall.md](08-firewall.md). Until then this box must
stay LAN-only — no router port-forwards.
## 3. Harden sshd config
Use a drop-in rather than editing `/etc/ssh/sshd_config`. The stock file stays
untouched, so package upgrades never conflict and `diff` stays readable.
```bash
sudo tee /etc/ssh/sshd_config.d/99-hardening.conf > /dev/null <<'EOF'
Port 2234
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthenticationMethods publickey
X11Forwarding no
AllowUsers admin
EOF
```
`KbdInteractiveAuthentication no` matters: without it OpenSSH can still offer
keyboard-interactive as a password path, which `PasswordAuthentication no` alone
does not close.
Validate before applying — this parses the config without touching the running
daemon:
```bash
sudo sshd -t && echo "CONFIG OK"
```
Do not continue unless it prints `CONFIG OK`.
Requires `Include /etc/ssh/sshd_config.d/*.conf` in `/etc/ssh/sshd_config`
(present by default on Arch) and no active `sshd.socket` (socket activation
overrides the `Port` directive):
```bash
grep -n "^Include" /etc/ssh/sshd_config
systemctl is-active sshd.socket # expect: inactive or not-found
```
## 4. Restart sshd
```bash
sudo systemctl restart sshd
```
Established sessions survive an sshd restart — your current session stays alive.
**Warning:** Do NOT close your current SSH session yet. Open a second terminal and test:
```bash
ssh -p 2234 admin@192.168.1.50
```
If it connects — the old session is safe to close. If it fails — fix the config in the still-open session.
## 5. Verify the hardening from your local machine
Run all four. The first must succeed; the last three must fail exactly as shown.
```bash
# key auth on the new port — must print OK
ssh -p 2234 -o BatchMode=yes -o PasswordAuthentication=no admin@192.168.1.50 'echo OK'
# password auth — must return: Permission denied (publickey)
ssh -p 2234 -o PubkeyAuthentication=no -o PreferredAuthentications=password \
-o BatchMode=yes admin@192.168.1.50
# root login — must return: Permission denied (publickey)
ssh -p 2234 -o BatchMode=yes root@192.168.1.50
# old port — must return: Connection refused
ssh -p 22 -o BatchMode=yes admin@192.168.1.50
```
Read the failure messages carefully. `Connection refused` means the host is
reachable and nothing is listening — expected on port 22. `No route to host` on
a host that answers `ping` means a firewall is rejecting that port, not that
sshd is misconfigured.
## 6. Configure fail2ban for SSH
Create `/etc/fail2ban/jail.d/sshd.conf`:
```ini
[sshd]
enabled = true
port = 2234
backend = systemd
maxretry = 5
bantime = 1h
findtime = 10m
```
No `logpath` — with `backend = systemd` fail2ban reads the journal, and Arch
does not always define the `%(sshd_log)s` macro, which aborts jail startup.
Type `port` carefully. Nothing cross-checks it against sshd's own config, and
once [09](09-fail2ban.md) points bans at nftables it becomes the port
the ban rule blocks. Wrong here means bans that register and block nothing —
see [09](09-fail2ban.md) §4.
```bash
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd
```
Expect `Journal matches: _SYSTEMD_UNIT=sshd.service`. A non-zero `Total failed`
is normal — the rejected logins from step 5 count.
## 7. Remote admin: WireGuard, never a port-forward
**Admin SSH (2234) is never port-forwarded** — decided when the box went
public; an external probe confirms 2234 *filtered*. Only 80, 443 and 2222 are
forwarded ([06](06-docker-deploy.md) §1, once [09](09-fail2ban.md) is done). From outside the LAN,
`ssh -p 2234 …@git.example.com` therefore times out, by design.
To administer from anywhere, tunnel onto `192.168.1.0/24` through the router's
built-in **WireGuard server** (many consumer routers have one; adapt if yours differs): the
router listens on one UDP port but answers nothing without a valid key, and
nothing on the server itself is exposed.
On the router: VPN Server → WireGuard → add a peer (client) → download its
config. **Before installing it, check for a key-export bug seen on some routers**: after a
VPN server reset, a regenerated profile has come back with the client's
`PrivateKey` set to the **server's own** key (self-pairing — no handshake ever
completes, `wg show` reports 0 B received):
```bash
sed -n 's/^PrivateKey = //p' <downloaded-client.conf> | wg pubkey
# must NOT print the router's own public key (shown on its WireGuard page)
getent hosts example.com # must match the config's Endpoint IP — ISPs rotate it
```
If the pubkey matches, regenerate the peer on the router (firmware bug, no fix
on this end). If the Endpoint IP is stale, edit it to the current one.
On the client (laptop), `wireguard-tools` installed:
```bash
sudo systemctl stop wg-quick@wg0
sudo systemctl reset-failed wg-quick@wg0 2>/dev/null
sudo ip link delete wg0 2>/dev/null
sudo cp <downloaded-client.conf> /etc/wireguard/wg0.conf
sudo systemctl start wg-quick@wg0
sudo wg show wg0 # want a recent "latest handshake"
ping -c1 192.168.1.50 && ssh -p 2234 admin@192.168.1.50
```
The stop/reset-failed/delete dance is not optional: `systemctl restart` fails
with `wg0' already exists` if the interface is up outside systemd's
bookkeeping (common after sleep/resume), and a bare `start` silently no-ops if
the unit still thinks it is active.
## Checklist
- [ ] Key login works on port 2234
- [ ] Password login rejected on port 2234
- [ ] Root login rejected
- [ ] Port 22 refuses connections
- [ ] fail2ban watching port 2234
- [x] 2234 **not** forwarded (LAN-only); remote admin via router WireGuard (§7)
## Next step
Continue with [04-dns-records.md](04-dns-records.md).

View File

@ -0,0 +1,127 @@
---
type: Guide
purpose: Rule out CGNAT and create the Cloudflare records and API token.
answers:
- "Which DNS records and Cloudflare token does the server need?"
---
# 04 — DNS Records
Point your domain at your home IP. Keeping it pointed there when the IP
changes is [05-ddns.md](05-ddns.md).
## Prerequisites
- Domain registered and DNS managed by Cloudflare (free plan is sufficient)
- Arch Linux server running, internet connected
## 0. Pre-flight: confirm you are not behind CGNAT
If your ISP uses Carrier-Grade NAT (CGNAT), inbound port-forwarding is impossible and the entire public-access plan fails. Test this before buying a domain or deploying.
The test is whether your **router's WAN IP is publicly routable**. Read it from
the router admin page (on TP-Link: `Advanced → Status → Internet`; adapt if
yours differs).
- WAN IP in the shared-address range `100.64.0.0`–`100.127.255.255`, or in a
private range (`10.x`, `172.16.x`–`172.31.x`, `192.168.x`) → **you are behind
CGNAT.**
- WAN IP is any other address → not behind CGNAT. Proceed.
As a cross-check, compare it against your IP as the internet sees it:
```bash
curl -s https://ifconfig.me/ip
```
A **match** confirms it. A **mismatch does not by itself mean CGNAT** — on a
line with a forced daily reconnect the IP is reassigned on every forced daily reconnect, so the two
readings disagree whenever a reconnect lands between them. Re-read both within a
minute of each other before concluding anything. Judge by the range, not by the
match.
CGNAT remedies (pick one):
- Ask ISP for a public/static IP (often free or small fee).
- Switch to Cloudflare Tunnel (no port-forward needed, but breaks the DNS-only SSH-on-2222 model — SSH would need a separate path).
Do not continue until `curl ifconfig.me` matches your router WAN IP.
## 1. Add A record in Cloudflare
In Cloudflare dashboard → your domain → DNS → Records → Add record:
| Field | Value |
|---|---|
| Type | A |
| Name | git |
| IPv4 address | your current home IP |
| Proxy status | DNS only (grey cloud) |
| TTL | 1 min |
This creates `git.example.com`. DNS-only (grey cloud) is required — Cloudflare proxy does not pass SSH traffic on port 2222.
Find your current home IP: https://ifconfig.me or `curl ifconfig.me`
Optional: a second site on the apex (e.g. a portfolio) needs two more records on the same zone — the apex, and
`www` pointing at it:
| Type | Name | Value | Proxy | TTL |
|---|---|---|---|---|
| A | `@` | your current home IP | DNS only | 1 min |
| CNAME | `www` | `example.com` | DNS only | 1 min |
The apex is an `A` record, tracked by ddclient in its own right, rather than a
CNAME onto `git.`. Cloudflare would flatten an apex CNAME and it would resolve,
but it would chain the portfolio's availability to the forge's record for no
gain. Two independent `A` records, one ddclient config, both names updated in
the same run. That is why [05](05-ddns.md) step 1 lists two hostnames rather than one. `www`
needs no ddclient entry — it is a CNAME and follows the apex.
## 2. Create Cloudflare API token
Cloudflare dashboard → My Profile → API Tokens → Create Token:
- Use template: **Edit zone DNS**
- Restrict to `example.com`, not all zones
- Copy the token — shown once only
ddclient needs **both** `Zone:DNS:Edit` and `Zone:Zone:Read`. It does not take a
Zone ID from the config — it looks the zone up itself by name against
`/zones?name=<zone>`, which is a `Zone:Zone:Read` call, then edits the A record.
The **Edit zone DNS** template already grants both, so use the template rather
than hand-building the token.
The dashboard has been reorganised at least once; there is no longer a section
labelled *Zone Resources*. Permissions are grouped under scope headers instead,
and the zone restriction lives on the header rather than in its own block. Chase
the **end state**, not the labels: the token must carry `Zone:DNS:Edit` and
`Zone:Zone:Read`, and no more zones than it needs.
Verify what you actually got before configuring anything, using the token itself:
```bash
curl -s "https://api.cloudflare.com/client/v4/zones?name=example.com" \
-H "Authorization: Bearer YOUR_CLOUDFLARE_API_TOKEN" |
grep -o '"permissions":\[[^]]*\]'
```
Expect `#zone:read` and `#dns_records:edit` in the list. This is the real check —
it reads the token's effective grants regardless of what the UI called them.
Do **not** use `/client/v4/user/tokens/verify` for this. An account-owned token
(`cfat_` prefix) returns `Invalid API Token` from that endpoint even when it is
perfectly valid, because the endpoint only serves user-owned tokens. A working
token that appears dead will send you rebuilding a credential that was fine.
The token is a live secret from the moment it is created. It belongs in exactly
one place — `/etc/ddclient/ddclient.conf` on the server, `0600 root:root`. Do not
paste it into chat, a shell command (it lands in `~/.bash_history`), a note, or
this repo. If it reaches any of those, roll it: create the replacement first,
swap it in, confirm `SUCCESS` in the journal, then delete the old one.
## Checklist
- [ ] CGNAT ruled out (router WAN IP is publicly routable, not `100.64/10` or RFC1918)
- [ ] Cloudflare token scoped to `example.com` with `Zone:DNS:Edit` + `Zone:Zone:Read`, confirmed via `/zones?name=` permissions output
- [ ] A record exists for `git.example.com` in Cloudflare (DNS-only)
- [ ] A record exists for the apex `example.com`, plus a `www` CNAME onto it (both DNS-only)

250
OKF/guides/05-ddns.md Normal file
View File

@ -0,0 +1,250 @@
---
type: Guide
purpose: Keep the A records on the home IP with ddclient.
answers:
- "How do the DNS records follow a changing home IP?"
---
# 05 — DDNS (ddclient)
Keep the A records from [04](04-dns-records.md) on the home IP as it changes.
## 1. Configure ddclient
The config lives in a directory, not at `/etc/ddclient.conf`:
```bash
sudo vim /etc/ddclient/ddclient.conf
```
Replace entire contents with:
```conf
syslog=yes
ssl=yes
protocol=cloudflare
usev4=webv4
webv4=ipify-ipv4
login=token
password=YOUR_CLOUDFLARE_API_TOKEN
zone=example.com
ttl=1
git.example.com,example.com
```
Replace `YOUR_CLOUDFLARE_API_TOKEN` with the token from [04](04-dns-records.md) step 2. The domain (`example.com`) and the hostnames are already filled in.
The final line is a comma-separated host list, no spaces — the forge and the
portfolio apex, both updated in one run. Both records must already exist in
Cloudflare ([04](04-dns-records.md) step 1); ddclient edits records, it does not create them. If the
apex is missing here, `git.` keeps updating happily and the portfolio record
silently goes stale at the next IP change, which presents as a Caddy or Docker
fault and is neither.
Three things about this config that differ from most guides you will find:
- **`usev4=webv4`, not `use=web`.** ddclient 4.0 deprecated the `use=`/`web=`
pair in favour of address-family-explicit options. The old spelling still
parses but logs a deprecation warning on every run.
- **`webv4=ipify-ipv4`, not `ifconfig.me`.** `webv4` accepts either a built-in
provider name or a full URL. `ifconfig.me` is neither — it is not in ddclient's
built-in list, and as a URL it is missing its scheme. `ipify-ipv4` is built in
(`https://api.ipify.org/`) and returns a bare IP with no scraping.
- **No `daemon=`.** The packaged unit hardcodes `--daemon 5m` on the command
line, which overrides anything the config file says. Setting `daemon=60` here
looks like it works and silently does nothing — see step 2.
`pid=` is also omitted: the unit runs ddclient with `--foreground` under
`Type=exec`, so systemd tracks the process directly and no pidfile is used.
Secure the file (contains API token):
```bash
sudo chmod 600 /etc/ddclient/ddclient.conf
sudo chown root:root /etc/ddclient/ddclient.conf
```
The unit declares no `User=`, so ddclient runs as root and can read a
root-owned `0600` file. The package ships this file as `root:ddclient 0640`;
tightening it to `0600 root:root` removes the group read without breaking
anything.
## 2. Set the polling interval
The packaged unit passes `--daemon 5m`, and a command-line option beats the
config file. Left alone, ddclient notices a new IP up to 5 minutes late — so
`ttl=1` on the DNS record buys you nothing. Override the interval where it is
actually read, with a drop-in:
```bash
sudo systemctl edit ddclient
```
Add:
```ini
[Service]
Environment=daemon_interval=60
```
A drop-in is used here for the same reason as
[`99-hardening.conf` in 03](03-ssh-hardening.md) — it survives package upgrades
and keeps the change visible in a diff, rather than editing a vendor unit in
place.
Confirm it took effect:
```bash
systemctl show ddclient -p Environment # expect: daemon_interval=60
```
Check `Environment`, **not** `ExecStart`. The vendor unit is:
```ini
Environment=daemon_interval=5m
ExecStart=/usr/bin/ddclient --daemon ${daemon_interval} --foreground
```
`systemctl show -p ExecStart` prints argv with variables **unexpanded**, so it
reports `--daemon ${daemon_interval}` forever, no matter what the drop-in sets.
Reading `ExecStart` here looks like the override silently failed when it is in
fact working.
> **Daily IP change.** Many residential ISPs force a reconnect every 24 hours, which assigns a new public IP. If your router is also set to restart nightly (e.g. 3 am), expect a short outage (~1–2 min for the router, plus up to 1 min for ddclient to detect the new IP and Cloudflare's 1-min TTL to expire) — roughly 3–4 min of nightly downtime. The 60-second interval set above keeps that window small; at the stock 5 minutes it is closer to 7–8 min. No manual action needed: ddclient re-points the A record automatically. The server stays powered on through a router reboot and reconnects via DHCP.
## 3. Enable and start ddclient
```bash
sudo systemctl enable ddclient
sudo systemctl start ddclient
```
Check status:
```bash
sudo systemctl status ddclient
sudo journalctl -u ddclient -n 20
```
Successful update log shows:
```
SUCCESS: [cloudflare][git.example.com]> IPv4 address set to <your IP>
```
### After any failed attempt, clear the cache before retrying
ddclient records failures in `/var/cache/ddclient/ddclient.cache` and then
refuses to retry that host for 5 minutes:
```
skipped update from <nothing> to 87.156.0.132 because it has been less than
5 minutes since the previous update attempt ..., which failed
```
A `systemctl restart` does not clear this — the cooldown lives in the cache file,
not in the process. So a config fix appears not to work, and the log shows the
*old* error being skipped rather than the new attempt. Wipe the cache instead:
```bash
sudo systemctl stop ddclient
sudo rm -f /var/cache/ddclient/ddclient.cache
sudo systemctl start ddclient
sleep 8
sudo journalctl -u ddclient -n 10 --no-pager
```
The cache is pure derived state; ddclient rebuilds it on the next run. Deleting
it also clears stale `wildcard` / `backupmx` recap warnings left behind when an
earlier run used a different protocol.
### `no zone ID found for zone <name>`
**Check the spelling in `zone=` first.** ddclient echoes the zone name back from
your config, so a typo (`exmaple.com`) produces an error that reads exactly
like a permissions problem. Only once the name is verified character-by-character
should you suspect token scope — and widen the token then, not pre-emptively.
Audit the whole file at once, with the secret masked, rather than one restart per
typo:
```bash
sudo sed 's/^password=.*/password=REDACTED/' /etc/ddclient/ddclient.conf
```
### `badauth: Bad authorization (username or password)` from `[dyndns2]`
The protocol tag in brackets is the tell. If it says `dyndns2` rather than
`cloudflare`, `protocol=` failed to parse (e.g. `claudflare`) and ddclient fell
back to its default protocol, which then failed to authenticate. This is a typo,
not a credential problem. Look further up the journal for the real cause:
```
WARNING: [file /etc/ddclient/ddclient.conf, line 4][globals][protocol]>
invalid value 'claudflare': invalid protocol: claudflare
```
An invalid `protocol=` is a warning, not a fatal error — ddclient keeps running
and reports a misleading auth failure downstream.
## 4. Test DNS resolution
From any machine:
```bash
dig git.example.com +short
# should return your home IP
```
`dig` is not installed on the dev machine and is not in a default Arch install
(`pacman -S bind`). Without it, either:
```bash
resolvectl query git.example.com
```
or, to bypass the local resolver cache entirely:
```bash
curl -s -H 'accept: application/dns-json' \
'https://cloudflare-dns.com/dns-query?name=git.example.com&type=A'
```
Prefer the DoH query right after creating the record. `systemd-resolved`
negative-caches an `NXDOMAIN` from before the record existed, so `resolvectl` can
report `not found` for minutes after the record is live and resolving worldwide.
DNS propagation can take up to 5 minutes on first setup.
## 5. Confirm ddclient can actually change the record
A `SUCCESS` on first run proves ddclient authenticated — not that it can rewrite
the record. If the A record already held the correct IP (likely, since you just
created it), the update was a no-op and Cloudflare's `modified_on` stays at the
creation time.
The real proof arrives with the next IP change. If your ISP forces a daily
reconnect, it happens within 24 hours, so check the following day:
```bash
sudo journalctl -u ddclient --since yesterday | grep SUCCESS
```
Expect a second `SUCCESS` line carrying a *different* address. Until you have
seen that, treat write access as unverified.
## Checklist
- [ ] ddclient host line lists both `git.example.com` and `example.com`
- [ ] TTL set to 1 minute
- [ ] `/etc/ddclient/ddclient.conf` is `0600 root:root` and holds the real token
- [ ] Token exists nowhere except that file (not in chat, shell history, or this repo)
- [ ] `systemctl show ddclient -p Environment` shows `daemon_interval=60`
- [ ] ddclient enabled and active, `SUCCESS` in logs tagged `[cloudflare]`
- [ ] `git.example.com` resolves to the correct IP from outside the local resolver cache
- [ ] Second `SUCCESS` observed after an IP change (proves write, not just auth)
## Next step
Continue with [06-docker-deploy.md](06-docker-deploy.md).

View File

@ -0,0 +1,194 @@
---
type: Guide
purpose: Bring up the Gitea and Caddy stack with automatic TLS.
answers:
- "How is the Docker Compose stack deployed?"
cites:
- compose.yml
- Caddyfile
---
# 06 — Docker Deploy
Deploy Gitea and Caddy using Docker Compose. Caddy handles TLS automatically via Let's Encrypt.
## Prerequisites
- Docker and Docker Compose installed (from [01-arch-install.md](01-arch-install.md))
- `git.example.com` resolving to your home IP (from [05-ddns.md](05-ddns.md))
- Router port forwards: 80, 443, 2222 pointing to server
## 1. Router port forwards
*Adapt if yours differs: menu names below are from one TP-Link model.*
On the router's admin page,
`Advanced → NAT Forwarding → Virtual Servers → Add`, once per row:
| Service Type | External port | Internal IP | Internal port | Protocol |
|---|---|---|---|---|
| http | 80 | 192.168.1.50 | 80 | TCP |
| https | 443 | 192.168.1.50 | 443 | TCP |
| gitea-ssh | 2222 | 192.168.1.50 | 2222 | TCP |
Use **Virtual Servers**, not Port Triggering.
Port 80 must be forwarded even though Gitea is HTTPS-only — Let's Encrypt's
HTTP-01 challenge answers on it, and Caddy cannot issue a certificate without
it. Caddy redirects real traffic to 443 itself.
If 443 refuses to save, the router's own Remote Management is holding it —
disable it (`Advanced → System Tools → Administration`), see
[02-server-first-boot.md](02-server-first-boot.md) step 4.
Confirm the host firewall from [08-firewall.md](08-firewall.md)
is loaded before adding these. Forwarding into a box with no ruleset exposes
every listening service on it.
## 2. Project directory
Clone or copy the project to the server. All runtime data lives in subdirectories next to `compose.yml`:
```bash
cd /home/admin/mithlond # or wherever you placed the project
# create runtime directories (gitignored)
mkdir -p gitea-data caddy-data caddy-config
# shared network with an optional apex-site stack — declared external in both compose files,
# so it must exist before either stack starts
docker network create edge
```
`compose.yml` declares `edge` as `external: true`. Without this command
`docker compose up` fails outright with `network edge declared as external, but
could not be found` — it will not create it for you.
## 3. Verify compose.yml
`compose.yml` already has the real hostname (`git.example.com`). Confirm it looks right:
```bash
grep DOMAIN compose.yml
```
## 4. Verify Caddyfile
`Caddyfile` ships with placeholder hostnames (`example.com`) and Let's Encrypt
email (`you@example.com`). Replace them:
```bash
grep -nE 'example.com|you@' Caddyfile # replace each with your own values
```
Three site blocks: `git.` → gitea, the apex → `portfolio:8000` (optional), and `www.` →
permanent redirect to the apex. Caddy requests a certificate for **every** name
it is configured to serve, so all three must resolve publicly before the
production run in step 6, or ACME fails on the ones that do not and burns rate
limit. The apex block proxies to a container in the `edge` network that is
deployed separately; until that site is up the block
answers 502 (or delete it and the `www.` block if you host only Gitea), which is expected and does not affect `git.`.
## 5. Test with Let's Encrypt staging
Before going live, test with the staging CA to avoid hitting rate limits (5 failed issuances per domain per hour).
In the global options block at the top of `Caddyfile`, uncomment the `acme_ca` line:
```
{
email you@example.com
acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
}
```
Start the stack:
```bash
docker compose up -d
```
Watch logs for cert issuance:
```bash
docker compose logs -f caddy
```
Look for: `certificate obtained successfully`. Staging certs are NOT trusted by browsers — that is expected.
Check Gitea is reachable internally:
```bash
curl -s http://localhost:3000
# should return HTML
```
## 6. Switch to production Let's Encrypt
Re-comment the `acme_ca` line in the global options block (leave `email` in place).
```bash
# Remove caddy-data to clear staging cert
docker compose down
rm -rf caddy-data
mkdir caddy-data
docker compose up -d
```
Watch logs again:
```bash
docker compose logs -f caddy
# look for: certificate obtained successfully
```
Visit `https://git.example.com` in a browser — should load with a valid (trusted) certificate.
## 7. Enable compose autostart on boot
```bash
sudo systemctl enable docker
```
Docker Compose services with `restart: unless-stopped` start automatically when Docker starts.
To make the stack start on boot without manual `docker compose up`:
Create `/etc/systemd/system/mithlond.service`:
```ini
[Unit]
Description=Mithlond Docker Compose stack
Requires=docker.service
After=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/home/admin/mithlond
ExecStart=/usr/bin/docker compose up -d
ExecStop=/usr/bin/docker compose down
User=admin
[Install]
WantedBy=multi-user.target
```
Enable it:
```bash
sudo systemctl enable mithlond
```
## Checklist
- [ ] `docker network create edge` run on the host
- [ ] Router forwards 80, 443, 2222 to server (only after [09](09-fail2ban.md))
- [ ] Staging cert issued successfully in Caddy logs
- [ ] Production cert issued — browser shows valid TLS
- [ ] `https://git.example.com` loads Gitea
- [ ] `mithlond.service` enabled — stack survives reboot
## Next step
Continue with [07-gitea-setup.md](07-gitea-setup.md).

View File

@ -0,0 +1,217 @@
---
type: Guide
purpose: Finish the Gitea install wizard, 2FA, SSH keys and tokens.
answers:
- "How is Gitea configured after the stack is up?"
cites:
- compose.yml
---
# 07 — Gitea Setup
Initial Gitea configuration via install wizard, admin hardening, 2FA, and SSH key registration.
## Prerequisites
- The stack is up on the server (from [06-docker-deploy.md](06-docker-deploy.md))
**Run this step before the port-forwards exist, not after.** Gitea's first-run
wizard hands ownership of the instance to whoever loads it first. Until the
admin account is created, a publicly reachable Gitea is a giveaway. The whole
of this doc works over an SSH tunnel with no forward in place, so there is no
reason to expose it first.
Gitea binds `127.0.0.1:3000` on the server — unreachable even from the LAN.
Reach it from the dev machine with a tunnel:
```bash
ssh -N -L 3000:127.0.0.1:3000 -p 2234 admin@192.168.1.50
```
Leave that running in its own terminal; `http://localhost:3000` is then Gitea.
Everything below happens there. Close the tunnel when done.
## 1. Install wizard
Visit `http://localhost:3000` — first visit shows the install wizard.
The redirect after **Install Gitea** goes to `https://git.example.com` and
hangs, because `ROOT_URL` says so and no forward exists yet. Expected. Go back
to `http://localhost:3000`; the install completed and you are logged in.
**Database settings** (already set via environment, verify):
- Database type: SQLite3
- Path: `/data/gitea/gitea.db`
**General settings:**
| Field | Value |
|---|---|
| Site title | your site name |
| Repository root path | `/data/git/repositories` |
| Git hooks path | `/data/gitea/git-repositories` |
| Log path | `/data/gitea/log` |
| Server domain | `git.example.com` |
| Gitea base URL | `https://git.example.com/` |
| SSH server port | `2222` |
**Admin account** — expand *Administrator Account Settings* at the bottom and
fill it in during the wizard. Skipping it leaves the instance ownerless, and the
first account to register takes it.
| Field | Value |
|---|---|
| Admin username | choose a username (not "admin" or "root") |
| Admin password | strong password (20+ chars, use a password manager) |
| Admin email | your email |
Click **Install Gitea**.
A user and an organization share one namespace in Gitea — an org is an account
type, not a separate thing. So the admin username also rules out that name for
any future org. Settle on the handle now: renaming later works and Gitea keeps a
redirect, but every clone URL already in a `.git/config` somewhere still points
at the old one.
Verify what the wizard actually wrote:
```bash
docker exec -u git gitea gitea admin user list
```
Expect one row, `IsAdmin true`.
## 2. Confirm public registration is disabled
`compose.yml` already sets `GITEA__service__DISABLE_REGISTRATION=true`, and the
wizard writes it into `app.ini`. Confirm rather than re-apply:
```bash
docker exec gitea grep DISABLE_REGISTRATION /data/gitea/conf/app.ini
```
Expect `DISABLE_REGISTRATION = true`. If it says otherwise, the env var is not
reaching the container — fix it there, not in `app.ini`, or the next
`docker compose up` overwrites your edit.
Note that `app.ini` also holds generated secrets (`*_JWT_SECRET`,
`SECRET_KEY`). Do not paste the file, or that section of it, anywhere. Delete a
secret line and restart the container to have Gitea regenerate it.
## 3. Enable 2FA for admin account
Log in as admin → User settings (top-right avatar) → Security → Two-Factor Authentication → Enroll.
Scan QR code with TOTP app (Aegis, Google Authenticator, etc.). Save backup codes in a password manager.
## 4. Register your SSH public key for git operations
User settings → SSH / GPG Keys → Add Key.
Paste your public key (`~/.ssh/id_ed25519.pub`):
```bash
# on your local machine
cat ~/.ssh/id_ed25519.pub
```
Confirm it registered:
```bash
docker exec gitea sqlite3 /data/gitea/gitea.db \
"select name,fingerprint from public_key;"
```
## 5. Test git over SSH
Gitea's SSH listener is bound to `0.0.0.0:2222`, so this works over the LAN
before any port-forward exists — use the server's LAN IP now, the hostname
after [09](09-fail2ban.md):
```bash
ssh -T git@192.168.1.50 -p 2222 # LAN, works today
ssh -T git@git.example.com -p 2222 # public, after 09
# expected: Hi there, <user>! You've successfully authenticated with the key
# named <key>, but Gitea does not provide shell access.
```
## 6. Test git over HTTPS
Needs the public hostname, so this one waits for
[09](09-fail2ban.md). The rest of this doc does not.
Create a Personal Access Token (PAT) for HTTPS push:
User settings → Applications → Generate Token. Select scopes: `repo`. Copy token.
A PAT is not a convenience here — with 2FA enrolled (step 3), your account
password no longer authenticates git over HTTPS at all. The PAT is the only
HTTPS credential. Treat it like a password: password manager, never a repo,
never a shell command.
```bash
git clone https://git.example.com/<user>/test-public.git
cd test-public
echo "hello" > test.txt
git add test.txt && git commit -m "test"
git push
# username: your Gitea user; password: the PAT
```
For convenience, configure git credential cache:
```bash
git config --global credential.helper cache
```
**For day-to-day pushes use SSH, not HTTPS.** A push over an HTTPS remote has
to prompt for the PAT, so any non-interactive push (an agent, a script, jj
without a credential helper) fails with:
```
fatal: could not read Username for 'https://git.example.com': No such device or address
```
The SSH key from step 4 needs no token. Switch an existing clone once:
```bash
git remote set-url origin ssh://git@git.example.com:2222/<user>/<repo>.git # git
jj git remote set-url origin ssh://git@git.example.com:2222/<user>/<repo>.git # jj
ssh -T -p 2222 git@git.example.com # "Hi there, <user>! …"
```
The explicit `ssh://…:2222/` form is required — the scp-style
`git@host:repo` shorthand cannot carry a port.
## 7. Create a test repository
Gitea UI → **+** → New Repository. Create one public (`test-public`) and one
private (`test-private`). Both work over the tunnel, before any forward exists.
Verify anonymously — the tunnel carries no session, so plain `curl` is already
a logged-out client:
```bash
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/<user>/test-public
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/<user>/test-private
```
Expect `200` then `404`. Gitea returns 404 rather than 403 for private repos on
purpose — a 403 would confirm the repo exists.
Delete both when done, or keep `test-public` as a scratch target.
## Checklist
- [ ] Wizard run over the SSH tunnel, before any port-forward exists
- [ ] Gitea install wizard completed, admin account created in the wizard itself
- [ ] Public registration disabled (confirmed in `app.ini`)
- [ ] Admin 2FA enabled, backup codes saved
- [ ] SSH public key registered in Gitea
- [ ] `ssh -T` test passes (LAN IP now, hostname after 09)
- [ ] HTTPS push test passes (after 09)
- [ ] Public repo visible without login
- [ ] Private repo returns 404 without login
## Next step
Continue with [08-firewall.md](08-firewall.md).

174
OKF/guides/08-firewall.md Normal file
View File

@ -0,0 +1,174 @@
---
type: Guide
purpose: Load the nftables host firewall without breaking Docker's rules.
answers:
- "How is the host firewall configured?"
---
# 08 — Firewall (nftables)
nftables host firewall. fail2ban and Gitea hardening follow in
[09-fail2ban.md](09-fail2ban.md).
## Prerequisites
- Gitea running and accessible (from [07-gitea-setup.md](07-gitea-setup.md))
- nftables installed (from [01-arch-install.md](01-arch-install.md))
## 1. nftables firewall
Create `/etc/nftables.conf`:
```bash
sudo vim /etc/nftables.conf
```
Replace contents with:
```nft
#!/usr/sbin/nft -f
# Do NOT put `flush ruleset` here. Arch's iptables is the nf_tables backend
# (`iptables --version` reports `nf_tables`), so Docker's own DNAT and forward
# rules live in this same ruleset. Flushing everything deletes them, and the
# published ports 80/443/2222 stop answering until `systemctl restart docker`.
# Replace only the table this file owns:
table inet filter
delete table inet filter
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
# established/related connections
ct state established,related accept
# loopback
iif lo accept
# ICMP (ping)
ip protocol icmp accept
ip6 nexthdr icmpv6 accept
# admin SSH
tcp dport 2234 accept
# HTTP and HTTPS (Caddy)
tcp dport { 80, 443 } accept
# Gitea SSH
tcp dport 2222 accept
}
chain forward {
type filter hook forward priority 0; policy accept;
}
chain output {
type filter hook output priority 0; policy accept;
}
}
```
The bare `table inet filter` line before the `delete` is not redundant — it
creates the table if it does not exist, so `delete` cannot fail on a first run
or after a reboot. Without it the file errors out half-applied.
What this chain does and does not cover: `input` filters traffic addressed to
**the host**, which is admin SSH on 2234. The container ports (80, 443, 2222)
arrive as DNAT and traverse `forward`, not `input` — Docker's own rules govern
those. So loosening or tightening `input` will not close a published container
port, and a mistake here shows up as *SSH lockout*, not as Gitea going down.
Apply and enable. This is the point where the firewall goes on for the first
time — [01-arch-install.md](01-arch-install.md) deliberately left it disabled so
the port change in [03](03-ssh-hardening.md) could not lock you out.
**Set a dead-man switch first.** One typo in `input` and 2234 is gone with no
console on a headless box. This schedules an unconditional revert in 5 minutes,
which you cancel by hand once you have proven you are still in:
```bash
sudo systemd-run --on-active=300 --unit=nft-panic \
/usr/sbin/nft delete table inet filter
sudo nft -f /etc/nftables.conf
```
Now, **from a second terminal on your local machine** — a new connection, not
the one already open, since an established session keeps working via
`ct state established` even when the rule that allowed it is gone:
```bash
ssh -p 2234 -o BatchMode=yes admin@192.168.1.50 'echo STILL_IN'
```
If that prints `STILL_IN`, cancel the revert and make the ruleset permanent:
```bash
sudo systemctl stop nft-panic.timer
sudo systemctl enable --now nftables
sudo nft list table inet filter
```
**`nft -f` alone does not survive a reboot.** It writes to the running kernel
only. Without `enable`, the next boot comes up with no ruleset at all — and
because everything still works, nothing tells you. If port-forwards exist by
then, the box is open. Do not skip this pair.
**`systemctl is-active nftables` reports `inactive` even when the firewall is
loaded, and that is correct.** The unit is `Type=oneshot` with
`RemainAfterExit=no`: it runs `nft -f`, exits 0, and the rules stay in the
kernel with no process behind them. Judge this unit by
`nft list table inet filter`, never by `is-active`. `is-enabled` is what tells
you it will come back after a reboot.
If it does **not**, change nothing and wait out the timer — the table deletes
itself and the box returns to open. Then fix `/etc/nftables.conf` and retry.
Recovery without the timer, at the physical console:
`sudo nft delete table inet filter`. Note that `systemctl stop nftables` does
**not** remove rules already loaded into the kernel, and `nft flush ruleset`
would take Docker's rules with it.
**External reachability** (80, 443, 2222 open; anything else closed) can only be
tested once the port-forwards exist. Those are
[06-docker-deploy.md](06-docker-deploy.md) §1, and this ruleset is exactly what
gates them — create them after the checklist at the bottom of this page passes,
not before.
## 2. Verify nftables survives reboot
This step is not a formality — it is the only thing that catches a ruleset that
was loaded by hand but never enabled.
```bash
sudo reboot
# wait ~40s, then from the dev machine:
ssh -p 2234 admin@192.168.1.50 'systemctl is-enabled nftables'
sudo nft list table inet filter # rules must still be present
```
The same reboot doubles as the autostart test for
[06](06-docker-deploy.md) §7. Confirm in one pass:
```bash
systemctl is-active docker ddclient fail2ban
cd ~/mithlond && docker compose ps # both containers Up
```
A useful negative signal during boot: port 2222 answering *Connection refused*
rather than timing out means the host is up and the firewall is permissive but
Docker has not started yet. Timeouts mean dropped packets; refusals mean
nothing is listening. They point at completely different faults.
## Checklist
- [ ] `/etc/nftables.conf` replaces only `table inet filter`, no `flush ruleset`
- [ ] nftables rules active, SSH on 2234 proven from a *new* connection
- [ ] `nft-panic` timer cancelled after that proof
- [ ] nftables survives reboot
- [ ] Docker still publishes 80/443/2222 after the ruleset loads
## Next step
Continue with [09-fail2ban.md](09-fail2ban.md).

203
OKF/guides/09-fail2ban.md Normal file
View File

@ -0,0 +1,203 @@
---
type: Guide
purpose: Ban brute force on admin SSH and Gitea logins, and harden Gitea.
answers:
- "How are brute-force logins banned and Gitea hardened?"
cites:
- compose.yml
---
# 09 — fail2ban and Gitea Hardening
fail2ban for admin SSH and Gitea logins, bans landing in nftables, and Gitea
app.ini hardening.
## Prerequisites
- nftables firewall active (from [08-firewall.md](08-firewall.md))
- fail2ban installed (from [01-arch-install.md](01-arch-install.md))
## 1. Point fail2ban at nftables
Arch's fail2ban defaults to `banaction = iptables-multiport`. Left alone, bans
are written into iptables while the real firewall lives in nftables — they
appear to work but land in a stack you are not inspecting.
Create `/etc/fail2ban/jail.d/00-banaction.conf`:
```ini
[DEFAULT]
banaction = nftables-multiport
banaction_allports = nftables-allports
```
This applies to every jail, including the `sshd` one from
[03-ssh-hardening.md](03-ssh-hardening.md).
## 2. fail2ban for Gitea
Gitea in Docker defaults to `[log] MODE = console` — everything goes to
`docker logs` and `/data/gitea/log/` stays empty. A jail pointed at
`gitea.log` then fails to start and silently protects nothing.
`compose.yml` sets `GITEA__log__MODE=console,file` to fix this. Confirm the file
exists and is growing before writing the jail:
```bash
docker exec gitea ls -la /data/gitea/log/gitea.log
```
If it is missing, the env var is not reaching the container — fix that first.
There is no point configuring a tail on a file that will never appear.
Create `/etc/fail2ban/filter.d/gitea.conf`:
```ini
[Definition]
failregex = .* Failed authentication attempt for .* from <HOST>
ignoreregex =
```
Create `/etc/fail2ban/jail.d/gitea.conf`:
```ini
[gitea]
enabled = true
port = http,https
filter = gitea
logpath = /home/admin/mithlond/gitea-data/gitea/log/gitea.log
maxretry = 10
bantime = 1h
findtime = 10m
```
Replace `/home/admin/mithlond` with your actual project path.
Restart fail2ban:
```bash
sudo systemctl restart fail2ban
sudo fail2ban-client status gitea
```
## 3. Gitea hardening
Set these in `compose.yml`, not by editing `app.ini`. Every `GITEA__*` env var is
re-applied to `app.ini` on each container start, so a hand edit to a key that is
also an env var is silently reverted at the next `docker compose up` — and a
hand edit to a key that is *not* one lives only on that server, in a file no
version control sees.
`compose.yml` already carries:
```yaml
- GITEA__service__DISABLE_REGISTRATION=true
- GITEA__service__DEFAULT_KEEP_EMAIL_PRIVATE=true
- GITEA__server__LFS_START_SERVER=false
- GITEA__openid__ENABLE_OPENID_SIGNIN=false
- GITEA__security__MIN_PASSWORD_LENGTH=12
- GITEA__security__PASSWORD_COMPLEXITY=lower,upper,digit,spec
```
`REQUIRE_SIGNIN_VIEW` stays at its default `false` on purpose — public repos
must be readable without an account. `INSTALL_LOCK` is set to `true` by the
wizard itself; confirm it rather than setting it.
Apply and confirm:
```bash
docker compose up -d # not `restart` — restart does not re-read env
docker exec gitea grep -E 'LFS_START_SERVER|MIN_PASSWORD_LENGTH|INSTALL_LOCK' \
/data/gitea/conf/app.ini
```
Do not print the whole `[server]` or `[security]` section — they contain
generated secrets (`*_JWT_SECRET`, `SECRET_KEY`). To rotate one, delete its line
and restart; Gitea regenerates it on boot.
## 4. Verify fail2ban bans work
Three things need proving here, and only the first is obvious: that the jail
counts failures, that the ban lands in nftables on the *right port*, and that a
banned host is actually turned away.
Ban a source that is not your own machine. The f2b chain hooks `input` at
priority -1, ahead of `inet filter`, and carries no `ct state established`
bypass — so banning yourself severs the session you are holding open, escape
hatch and all. A throwaway container has its own address on the docker0 bridge
and costs nothing to ban:
```bash
docker run --rm alpine sh -c 'apk add -q openssh-client; \
for i in $(seq 4); do ssh -p 2234 -o BatchMode=yes -o StrictHostKeyChecking=no baduser@192.168.1.50; done; \
sleep 45; \
for i in $(seq 4); do ssh -p 2234 -o BatchMode=yes -o StrictHostKeyChecking=no baduser@192.168.1.50; done'
```
**Four at a time, not six in a row.** OpenSSH 9.8+ enables `PerSourcePenalties`,
and after about four invalid-user attempts sshd starts dropping connections on
its own:
```
srclimit_penalise: 172.17.0.2/32: activating ipv4 penalty of 19.673 seconds
drop connection #0 from [172.17.0.2]:56240 ... penalty: attempted authentication by invalid user
```
A dropped connection never logs `Invalid user`, and that line is what the `sshd`
filter counts. sshd's own rate limiter starves fail2ban of its evidence: the
count stalls below `maxretry = 5` and no ban fires. Two rounds of four, spaced
past the penalty, stay within `findtime = 10m` and reach 8.
Then read the rule the ban generated:
```bash
sudo fail2ban-client status sshd
sudo nft list table inet f2b-table
```
`f2b-table` does not exist until the first ban — `actionstart` runs on demand —
so its absence beforehand proves nothing. Once it appears, check the port:
```
tcp dport 2234 ip saddr @addr-set-sshd reject with icmp port-unreachable
```
That number comes from `port` in `/etc/fail2ban/jail.d/sshd.conf`, not from
sshd's own config, and nothing validates it. A typo bans the IP from a port
nothing listens on: `fail2ban-client status` reports the ban, the ruleset agrees
with it, and the banned host walks back in on 2234 untouched. The server's copy
of that file said `234` for a full session before this check caught it.
Which is why the last check is not optional — go back to the banned source:
```bash
docker run --rm alpine sh -c 'apk add -q openssh-client; \
ssh -p 2234 -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=8 admin@192.168.1.50'
```
Expect `Connection refused` — `blocktype = reject` answers with ICMP port
unreachable. `Permission denied (publickey)` means the ban is cosmetic. A
*timeout* means something other than fail2ban is dropping the packets.
Unban when done:
```bash
sudo fail2ban-client set sshd unbanip 172.17.0.2
```
## Checklist
- [ ] fail2ban bans land in nftables, not iptables (`00-banaction.conf`)
- [ ] fail2ban watching admin SSH on 2234
- [ ] `gitea.log` exists on disk and grows
- [ ] fail2ban watching Gitea login log
- [ ] Gitea hardening set via `compose.yml` env, confirmed in `app.ini`
- [ ] ban registers *and* `f2b-table` rejects on 2234, not some other port
- [ ] banned source actually refused on 2234, re-tested after the ban
Only once every box above and in [08](08-firewall.md) is ticked, create the port-forwards in
[06-docker-deploy.md](06-docker-deploy.md) §1.
## Next step
Continue with [10-backup-manual.md](10-backup-manual.md).

View File

@ -0,0 +1,248 @@
---
type: Guide
purpose: Archive Gitea's data volume to the backup drive by hand and prove it restores.
answers:
- "How is a manual backup made and restore-tested?"
cites:
- scripts/backup.sh
---
# 10 — Backup Procedure (manual)
Manual backup of Gitea's data volume to the portable HDD, followed by a restore
test on a scratch copy. Validated end to end on the reference server.
Nightly automated backups (restic) are in [11-backup-automated.md](11-backup-automated.md); this manual archive remains for standalone copies.
The whole procedure is scripted in [`scripts/backup.sh`](../../scripts/backup.sh).
The manual steps below are the same commands in the same order (numbered to
match the script), for when something goes off-script.
## What gets backed up
`gitea-data/` holds all Gitea state:
| Path | Contents |
|---|---|
| `gitea-data/gitea/gitea.db` | SQLite database (users, issues, settings) |
| `gitea-data/git/repositories/` | All bare git repositories |
| `gitea-data/gitea/conf/app.ini` | Gitea configuration |
| `gitea-data/gitea/attachments/`, `avatars/` | Uploads |
| `gitea-data/ssh/` | Gitea's SSH **host keys** — `root:root`, mode 700. Lose them and every client sees a changed host-key warning on port 2222 |
Not backed up: `caddy-data/` (Caddy re-issues certs) and any stateless apex
site (rebuild it from source).
## The backup drive
| | |
|---|---|
| Drive | any USB HDD (example: 1.8T) |
| Partition | `sdb1`, **NTFS**, label **`BACKUP`** (`/dev/disk/by-label/BACKUP`) |
| Backups live in | `mithlond/` at the drive root |
**Never format the backup drive** — it holds other data. Everything here only adds files
under `mithlond/`.
Because it is NTFS, Linux owners and modes cannot be stored as files on it.
So the backup is a single `tar -p` archive, which carries them inside — never
`cp -r` the directory across.
## Prerequisites (one-time)
```bash
sudo pacman -S ntfsprogs # ntfsfix — NOT in ntfs-3g, which only has the FUSE driver
```
Already on the server: `sqlite3`, `docker`. The kernel's built-in `ntfs3`
driver does the mounting. The server has **no `git`**; repo checks run inside
the `gitea/gitea` image.
## Quick path — the script
Plug in the backup drive, then on the server as the admin user:
```bash
~/mithlond/scripts/backup.sh # back up + restore test
~/mithlond/scripts/backup.sh verify gitea-backup-YYYYMMDD-HHMM.tar.gz # re-test an old archive
```
It asks for the sudo password up front (not mid-downtime), always restarts
Gitea even if a step fails, deletes a half-written archive, removes the scratch
copy (it holds host-key copies), and unmounts the backup drive if it mounted it. If the
volume is dirty it runs the `ntfsfix` dry run and asks before clearing the
flag. Gitea is down only for step 4 (~2 min for 1.3G).
The script must exist on the server: copy it over after editing
(no `rsync` there):
```bash
ssh -p 2234 admin@192.168.1.50 'mkdir -p ~/mithlond/scripts && cat > ~/mithlond/scripts/backup.sh && chmod +x ~/mithlond/scripts/backup.sh' < scripts/backup.sh
```
## Manual procedure
All on the server (`ssh -p 2234 admin@192.168.1.50`), as the admin user.
### 1. Find the drive
```bash
lsblk -o NAME,SIZE,FSTYPE,LABEL,MOUNTPOINTS,TRAN
# expect: sdb1 1.8T ntfs BACKUP ... usb
```
### 2. Mount it
```bash
sudo mkdir -p /mnt/backup
sudo mount -t ntfs3 /dev/disk/by-label/BACKUP /mnt/backup
ls /mnt/backup # your existing files — sanity check
```
**If it fails with `wrong fs type, bad option, bad superblock`**, check why:
```bash
sudo dmesg | tail
# ntfs3(sdb1): volume is dirty and "force" flag is not set!
```
Windows left the dirty flag (unsafe eject, or Fast Startup). Full triage —
including real damage and running `chkdsk` with no Windows machine — is in
[ntfs-repair.md](ntfs-repair.md). For the common flag-only case:
```bash
sudo ntfsfix -n /dev/disk/by-label/BACKUP # dry run, writes nothing — must end "processed successfully"
sudo ntfsfix -d /dev/disk/by-label/BACKUP # only if the dry run was clean: clears flag, resets journal
sudo mount -t ntfs3 /dev/disk/by-label/BACKUP /mnt/backup
```
`ntfsfix` is not a repair tool. If the dry run reports anything but a clean
pass, follow [ntfs-repair.md](ntfs-repair.md) instead. **Never `mount -o force`** — writing to a dirty volume risks the
other data on the backup drive.
### 3. Create the backup folder
```bash
sudo mkdir -p /mnt/backup/mithlond
```
### 4. Stop Gitea, archive, start Gitea
```bash
cd ~/mithlond
docker compose stop gitea # SQLite must not be written mid-copy
NAME=gitea-backup-$(date +%Y%m%d-%H%M)
sudo tar -czpf /mnt/backup/mithlond/$NAME.tar.gz -C ~/mithlond gitea-data
docker compose start gitea # do NOT skip — miss it and Gitea stays down
```
`sudo` because `gitea-data/ssh/` is root-only. `-p` keeps owners and modes.
Only Gitea stops; Caddy keeps serving the apex site.
### 5. Checksum
```bash
cd /mnt/backup/mithlond
sudo sh -c "sha256sum $NAME.tar.gz > $NAME.tar.gz.sha256"
ls -lh /mnt/backup/mithlond
sync
```
### 6. Confirm Gitea is back
```bash
docker compose -f ~/mithlond/compose.yml ps # gitea: Up
curl -sI https://git.example.com | head -1 # from anywhere: 200 (a 502 for ~20s while it boots)
```
### 7–13. Restore test
Proves the archive restores, without touching the live stack. Extract into
`~` — `/tmp` is a 1.5G tmpfs, too small.
```bash
# 7. checksum
cd /mnt/backup/mithlond && sha256sum -c $NAME.tar.gz.sha256 # OK
# 8. contents — host keys present with root:root 700
tar -tvzf $NAME.tar.gz | grep ' gitea-data/ssh/$' # drwx------ root/root
# 9. extract to scratch
mkdir ~/restore-test && tar -xzf $NAME.tar.gz -C ~/restore-test
R=~/restore-test/gitea-data
# 10. SQLite integrity + counts
sqlite3 -readonly $R/gitea/gitea.db 'PRAGMA integrity_check;' # ok
sqlite3 -readonly $R/gitea/gitea.db \
"select 'users=' || count(*) from user; select 'repos=' || count(*) from repository;"
# 11. git fsck every repo, using the gitea image's git (read-only mount)
IMG=$(docker inspect -f '{{.Config.Image}}' gitea)
docker run --rm --user 1000:1000 --entrypoint sh -v $R/git/repositories:/r:ro $IMG -c \
'cd /r; for d in */*.git; do out=$(git -c safe.directory="*" --git-dir=$d fsck --no-progress --no-dangling 2>&1) && r=${out:-OK} || r="FAILED $out"; printf "%-36s %s\n" $d "$r"; done'
diff -rq $R/git ~/mithlond/gitea-data/git && echo identical # differs only if pushed since
# 12. boot a throwaway Gitea on the extract — no network, live stack untouched
docker run -d --rm --name gitea-restore-test --network none \
-e USER_UID=1000 -e USER_GID=1000 -v $R:/data $IMG
sleep 25
docker exec gitea-restore-test wget -qO- http://127.0.0.1:3000/api/v1/version
docker exec gitea-restore-test su git -c 'gitea admin user list'
docker stop gitea-restore-test
# 13. cleanup — the extract holds copies of the SSH host keys
rm -rf ~/restore-test
```
An empty repo (never pushed, e.g. `test-private`) reports
`notice: HEAD points to an unborn branch` — that is fine.
### 14. Unmount
```bash
cd ~ # step 5 left this shell inside /mnt/backup/mithlond
sync
sudo umount /mnt/backup # umount — no "n"
findmnt /mnt/backup # no output = unmounted
```
`umount: /mnt/backup: target is busy` means some shell is still inside the
mount — the prompt reads `[… mithlond]$` both there and in `~/mithlond`, so
it is easy to miss. Find it with
`ls -l /proc/*/cwd 2>/dev/null | grep /mnt/backup`, `cd ~` in that shell, retry.
Unplug only after `findmnt` prints nothing. Eject safely on Windows too, or the dirty
flag comes back.
A real restore from an archive: [backup-operations.md](backup-operations.md#restore-from-a-tar-archive).
## Backup frequency
No automated schedule. Back up:
- Before any system update (`pacman -Syu`)
- Before any Docker image update
- After significant work (pushed important repos, added users)
- At minimum: weekly
## Retention
Keep at least two dated archives in `BACKUP:/mithlond/`. The script reports the
count but never deletes. Delete older ones by hand when space is needed — keep
at least one that predates any recent change you haven't verified.
## Log
| Date | Archive | Size | Restore test |
|---|---|---|---|
| YYYY-MM-DD | `gitea-backup-YYYYMMDD-HHMM.tar.gz` | — | pass / fail, and what was checked |
## Next step
Continue with [11-backup-automated.md](11-backup-automated.md).
## Checklist
- [ ] Performed first backup after Gitea setup
- [ ] Restore test completed on separate directory (`~/restore-test`, throwaway container)
- [ ] Repos and users verified intact after restore (integrity_check ok, fsck clean, `gitea admin user list`)

View File

@ -0,0 +1,220 @@
---
type: Guide
purpose: Set up the nightly restic backup with failure and weekly mail.
answers:
- "How is the nightly automated backup set up?"
cites:
- scripts/gitea-backup
- systemd/gitea-backup.service
- systemd/gitea-backup.timer
---
# 11 — Automated Backup
Nightly, unattended backup of `gitea-data/` into a **restic** repository on the
portable HDD (the backup drive), with mail on failure and a weekly proof-of-life report.
Operated remotely over the router's WireGuard tunnel, so no new ports open.
The manual tar procedure in [10-backup-manual.md](10-backup-manual.md) stays: use it for an
extra standalone archive (e.g. before a risky change). Both coexist on the backup drive
under `mithlond/`.
## Design
| Choice | Why |
|---|---|
| **restic** | Incremental and deduplicated: after the first 1.3G each night adds only changes. Stores owners/modes in its own metadata, so NTFS losing them is irrelevant (`gitea-data/ssh/` comes back `root:root 700`). Encrypted at rest. |
| **Stop Gitea during the snapshot** | SQLite must not be written mid-copy. Downtime ≈ snapshot time — about a minute after the first run. |
| **03:30 nightly, systemd timer** | `Persistent=true` catches up on boot if the box was off. |
| **Keep 7 daily / 4 weekly / 12 monthly** | `restic forget --prune` after every run. |
| **Mount → back up → unmount** | The backup drive stays plugged in but mounted only ~2 min a night. `ntfs3` cannot replay the NTFS journal, so a power cut while mounted leaves it dirty and every later run fails until a human runs `ntfsfix`. The script never repairs or forces unattended. |
| **Weekly `check --read-data` + report mail (Sunday)** | Reads every pack back. The mail is proof of life: **no Sunday mail = the timer stopped firing** — failure mail alone can't catch that. |
| **Mail via Gmail SMTP (`msmtp`)** | Failure mail from `OnFailure=`, scoped to the failed run's journal. |
| **No off-site copy** | The backup drive shares fire/theft/surge risk with the server. Adding one later is outbound-only (server pushes; no open ports): a second restic repo + `restic copy`. |
## Files
| Repo path | Installed to |
|---|---|
| `scripts/gitea-backup` | `/usr/local/sbin/gitea-backup` (root-owned — never run a root unit from the user-writable `~/mithlond`) |
| `systemd/gitea-backup.service`, `.timer`, `gitea-backup-failed.service` | `/etc/systemd/system/` |
| `systemd/gitea-backup.env.example` | `/etc/gitea-backup/env` (600) |
| `systemd/msmtprc.example` | `/etc/msmtprc` (600) |
| — | `/etc/gitea-backup/restic-password` (600) |
`gitea-backup` subcommands: `init`, `run`, `snapshots`, `check`,
`restore-test`, `test-mail`, `notify-failure`. All need root.
## Setup (one-time, in order)
### 1. Copy the files to the server
From this repo on your workstation (no `rsync` on the server):
```bash
for f in scripts/gitea-backup systemd/gitea-backup.service systemd/gitea-backup.timer \
systemd/gitea-backup-failed.service systemd/gitea-backup.env.example systemd/msmtprc.example; do
ssh -p 2234 admin@192.168.1.50 "mkdir -p ~/mithlond/$(dirname $f) && cat > ~/mithlond/$f" < $f
done
```
Everything below runs **on the server**.
### 2. Packages
```bash
sudo pacman -S restic msmtp
```
### 3. Install script and units
```bash
cd ~/mithlond
sudo install -o root -g root -m 755 scripts/gitea-backup /usr/local/sbin/gitea-backup
sudo install -o root -g root -m 644 systemd/gitea-backup.service systemd/gitea-backup.timer \
systemd/gitea-backup-failed.service /etc/systemd/system/
sudo systemctl daemon-reload
```
### 4. Config and restic password
```bash
sudo install -d -o root -g root -m 700 /etc/gitea-backup
sudo install -o root -g root -m 600 systemd/gitea-backup.env.example /etc/gitea-backup/env
sudo sed -i 's/^MAILTO=.*/MAILTO=<you>@gmail.com/' /etc/gitea-backup/env # no nano/vi on the server
sudo sh -c 'umask 077; openssl rand -base64 33 > /etc/gitea-backup/restic-password'
sudo cat /etc/gitea-backup/restic-password # copy into your password manager NOW
```
**Without this password the backups cannot be decrypted** — it must live
somewhere other than the server. Label it clearly (e.g. "mithlond restic"):
it is 44 characters, the Gmail app password in step 5 is 16. Pasting the
restic one into step 5 by mistake gets a `535` from Gmail, and means it has to
be regenerated, because it has been sent to Gmail. If that happens before
`init`, just rerun the `openssl` line; after `init` use `restic key passwd`.
The server has no `nano` or `vi`; `sed` edits are used throughout (`vim`
exists if you need an editor).
### 5. Mail
Create a Gmail **app password** at <https://myaccount.google.com/apppasswords>
— Google no longer links that page from its menus, open the URL directly.
Name it `mithlond`, **Create**, copy the 16 letters. Needs 2-Step Verification
on; with only passkeys/security keys as second step, or Advanced Protection,
the page says "not available" (add an authenticator app, or use another alert
route). Then:
```bash
sudo install -o root -g root -m 600 systemd/msmtprc.example /etc/msmtprc
sudo sed -i 's/you@gmail.com/<you>@gmail.com/' /etc/msmtprc
read -rsp 'App password: ' P; echo # -s: off screen, out of history
sudo sed -i "s/REPLACE_WITH_16_CHAR_APP_PASSWORD/${P// /}/" /etc/msmtprc; unset P # strips Google's spaces
sudo grep -c REPLACE /etc/msmtprc # must print 0
sudo awk '$1=="password"{print "password length:", length($2)}' /etc/msmtprc # must be 16
sudo gitea-backup test-mail # no output = sent; check inbox and spam
```
Subject: `[mithlond] gitea-backup test mail`. If msmtp answers
`535-5.7.8 Username and Password not accepted`:
```bash
sudo grep -E '^(from|user)' /etc/msmtprc # both your full Gmail address
sudo awk '$1=="password"{print "password length:", length($2)}' /etc/msmtprc
```
Length 44 = the restic password went in (see step 4); any length ≠ 16 = not an
app password. Replace it (the placeholder is gone by now, so match the line):
```bash
read -rsp 'Gmail app password (16 letters): ' P; echo
sudo sed -i "s/^password .*/password ${P// /}/" /etc/msmtprc; unset P
```
### 6. Create the repository
The backup drive plugged in (not necessarily mounted — the script mounts it):
```bash
sudo gitea-backup init
```
Ends `created restic repository <id> at /mnt/backup/mithlond/restic`, then
`==> unmounted /mnt/backup`. If it fails with "dirty", fix per
[ntfs-repair.md](ntfs-repair.md) first.
### 7. First run, by hand
```bash
sudo systemctl start gitea-backup # blocks until done; first run uploads all 1.3G
systemctl status gitea-backup --no-pager # Result=success
journalctl -u gitea-backup -n 40 --no-pager # "gitea down Ns", snapshot id
sudo gitea-backup snapshots
```
Run it via `systemctl`, not `gitea-backup run`, so the real unit path —
including `OnFailure=` — is what gets proven. Measured on the reference server: first run
86 s Gitea downtime (1.2 GiB, all new); second run 5 s (14 KiB changed).
The unit's "1.7G memory peak" is mostly page cache from reading `gitea-data`,
not restic — `free` shows it reclaimable.
### 8. Restore test
```bash
sudo gitea-backup restore-test
```
Restores the latest snapshot into `/var/tmp/gitea-restore-test`, checks
`gitea-data/ssh/` is `root:root 700`, runs SQLite `integrity_check`, fscks
every repo inside the gitea image, boots a throwaway Gitea (`--network none`),
lists users — then deletes the scratch copy. Must end `RESTORE TEST PASSED`.
### 9. Prove failure mail
**Unplug the backup drive first, then start the run — never unplug during one.**
Check it is free: `findmnt /mnt/backup` prints nothing and
`systemctl is-active gitea-backup` is not `activating`.
```bash
sudo systemctl start gitea-backup # fails at once: "HDD 'BACKUP' not attached"
```
A `gitea-backup FAILED on mithlond (exit-code)` mail must arrive with that
error. Plug the backup drive back in.
Pulling the drive *during* a run instead (tested once, mid-prune)
proves more, and costs more:
- restic retried `input/output error` with back-off for minutes; the run
looked hung. `sudo systemctl stop gitea-backup` ended it — **a manual stop
also counts as a failure** (`Result: signal`) and sends the mail.
(Ctrl+C on `systemctl start` only stops waiting; the run continues.)
- The EXIT trap still ran: Gitea was already back (5 s down), the dead mount
was detached.
- The backup drive came back dirty with a `$MFTMirr` mismatch, then real NTFS damage →
[ntfs-repair.md](ntfs-repair.md) rung 3 (chkdsk). A stale restic lock was left too.
### 10. Enable the timer
```bash
sudo systemctl enable --now gitea-backup.timer
systemctl list-timers gitea-backup.timer # NEXT = tonight 03:30
```
Remote operation, real restore and troubleshooting:
[backup-operations.md](backup-operations.md).
## Checklist
- [ ] Packages, script, units, config installed (steps 2–4)
- [ ] Restic password stored off-server
- [ ] `test-mail` arrives (step 5)
- [ ] First run via `systemctl` succeeds (step 7)
- [ ] `restore-test` passes (step 8)
- [ ] Failure mail proven (step 9)
- [ ] Timer enabled (step 10)
- [ ] First Sunday report mail received
## Next step
Continue with [12-gitea-actions.md](12-gitea-actions.md).

View File

@ -0,0 +1,137 @@
---
type: Guide
purpose: Run a Gitea Actions runner on the server and the profile snake job.
answers:
- "How does CI run on the server?"
cites:
- runner/config.yaml
- profile/.gitea/workflows/snake.yml
---
# 12 — Gitea Actions (CI)
A CI runner on the server, and its first job: a snake that eats the
contribution heatmap on the Gitea profile page. Uses the same workflow
syntax as GitHub Actions. It needs no new port forward: the runner polls
Gitea over HTTPS like any other client.
## Design
| Choice | Why |
|---|---|
| **act_runner 0.6.1 as a compose service** | Starts and stops with the stack and survives reboots through `restart: unless-stopped`. Pinned, like the Gitea image. |
| **Jobs in sibling containers via the host Docker socket** | Every job starts in a clean container. The socket is root on the host, so anyone who can push a workflow owns the box. That is acceptable only because registration is disabled and the runner is scoped to one user (§2). Revisit before adding users. |
| **`docker_host: "-"`** | Jobs themselves do **not** get the socket. A workflow cannot start containers or reach the host's Docker. |
| **Label `alpine` → `node:24-alpine`** | The image is 62 MB, against several GB for the Ubuntu runner images, which matters on the HDD. Most JS actions and `npx` work. A copied GitHub workflow with `runs-on: ubuntu-latest` sits queued and does not break. Add Ubuntu labels on a server with more RAM and an SSD. |
| **Capacity 1, 768M per job, no cache server** | Sized for 3G RAM total: Gitea, Caddy and an apex site use about 500M, leaving about 1.9G. Raise it on a bigger machine. |
| **Instance URL is the public `https://git.example.com`** | Job containers clone and push through the same URL that `github.server_url` gives them. The server reaches its own domain by NAT hairpin (check your router supports it). |
| **Not in the backup** | `runner-data/` holds only the registration (`.runner`). If it is lost, register again (§2). Workflows live in their repos, which are in `gitea-data`. |
## Files
| Repo path | Purpose |
|---|---|
| `compose.yml` → `runner` | the service; `GITEA__actions__ENABLED=true` on `gitea` |
| `runner/config.yaml` | runner config, mounted read-only |
| `runner-data/` (gitignored, server only) | `.runner` registration state |
| `profile/` | content of the `yourname/.profile` repo (§4) |
## Setup (one-time, in order)
### 1. Copy the files to the server
From this repo on your workstation:
```bash
for f in compose.yml runner/config.yaml; do
ssh -p 2234 admin@192.168.1.50 "mkdir -p ~/mithlond/$(dirname $f) && cat > ~/mithlond/$f" < $f
done
```
`runner/config.yaml` **must** exist before step 3. If it is missing, Docker
creates an empty directory in its place and the runner fails to start.
### 2. Get a user-scoped registration token
In the browser: **avatar → Settings → Actions → Runners → Create new
Runner** (`https://git.example.com/user/settings/actions/runners`). Copy
the token.
Use this page and not *Site Administration → Runners*. A user-scoped runner
only takes jobs from your own repos.
On the server, type it in (it is not echoed and stays out of shell history):
```bash
mkdir -p ~/mithlond/runner-data
read -rsp 'token: ' t && printf '%s' "$t" > ~/mithlond/runner-data/registration-token && unset t; echo
wc -c ~/mithlond/runner-data/registration-token # about 40, not 0
```
### 3. Start
```bash
cd ~/mithlond
docker compose up -d # recreates gitea (env changed) + starts runner
docker logs runner 2>&1 | grep -E 'registered|declare|error'
```
Expect `Runner registered successfully` and then `declare successfully`. Then
remove the token, which is single-use and no longer needed:
```bash
rm ~/mithlond/runner-data/registration-token
```
The runner shows **Idle** with label `alpine` on the Runners page from step 2.
### 4. The snake on your profile page
Gitea shows the README of a repo named `.profile` on the user's profile page.
1. In the browser, create the repo `yourname/.profile`: empty, **public**. The
SVGs are embedded by raw URL, so the repo must be readable anonymously.
2. Push the template from your workstation. Copy it out first, because a
`git init` inside `profile/` would nest a repo within mithlond:
```bash
cp -r ~/Documents/mithlond/profile ~/dot-profile && cd ~/dot-profile
git init -b main && git add . && git commit -m "feat: snake on the profile page"
git remote add origin ssh://git@git.example.com:2222/yourname/.profile.git
git push -u origin main
```
3. The push triggers the workflow. Follow it at
`https://git.example.com/yourname/.profile/actions`. The first run pulls
`node:24-alpine`. After that a run takes well under a minute.
4. The workflow creates the `output` branch, and the snake appears at
`https://git.example.com/yourname`.
After that it runs daily at 05:00, outside the 03:30 backup window when Gitea
is stopped. **Actions → snake → Run workflow** re-runs it on demand. Edit
`README.md` in that repo freely; keep the `<picture>` block.
The snake only has what the heatmap has: public activity. If the graph is
nearly empty, the animation is short.
## Checks
```bash
docker compose ps # runner Up
docker logs --since 24h runner 2>&1 | tail -20 # no repeating errors
curl -sI https://git.example.com/yourname/.profile/raw/branch/output/snake.svg | head -1 # 200
```
During the nightly backup the runner logs connection errors for about a
minute while Gitea is stopped. That is expected, and it recovers by itself.
## Troubleshooting
| Symptom | Cause / fix |
|---|---|
| Job stuck *Waiting* | No runner has the label. `runs-on` must be `alpine`. |
| `runner registration token not found`, `wc -c` shows 80, 120… | Hidden `read -s` prompt took the paste more than once (e.g. 320 = 8×40). `head -c 40 f > f.new && mv f.new f`, then `docker compose restart runner`. |
| Runner restarts in a loop, logs mention `registration-token` | Token file missing or stale on first start. Repeat §2 and `docker compose up -d runner`. |
| `push` step: 403 / `permission denied` | The automatic token has no write access. Check *Repo → Settings → Actions* is enabled, and that the job is not running for a fork. |
| Snake missing on profile, raw URL 404 | No successful run yet, or the repo is private. |
| Need to re-register (new server, lost `runner-data/`) | Delete the old runner in the UI, `rm -rf runner-data`, then §2–§3. |

View File

@ -0,0 +1,93 @@
---
type: Guide
purpose: Operate, restore from and troubleshoot the backups.
answers:
- "How are backups operated, restored and fixed?"
cites:
- scripts/gitea-backup
---
# Backup Operations
Running, restoring and fixing the backups once
[11-backup-automated.md](11-backup-automated.md) is set up.
## Remote operation (from anywhere)
No ports are exposed for this. Bring up the router's WireGuard tunnel on your
laptop (setup and the router key-export bug check: [03 §7](03-ssh-hardening.md#7-remote-admin-wireguard-never-a-port-forward)):
```bash
sudo systemctl start wg-quick@wg0 && sudo wg show wg0 # recent "latest handshake"
ssh -p 2234 admin@192.168.1.50
```
Then on the server:
| Task | Command |
|---|---|
| When did it last run, did it pass? | `systemctl status gitea-backup --no-pager` |
| Log of last run | `journalctl -u gitea-backup -n 60 --no-pager` |
| Next scheduled run | `systemctl list-timers gitea-backup.timer` |
| Back up now | `sudo systemctl start gitea-backup` |
| List snapshots | `sudo gitea-backup snapshots` |
| Full integrity check | `sudo gitea-backup check` |
| Restore test | `sudo gitea-backup restore-test` |
| Pause nightly backups | `sudo systemctl disable --now gitea-backup.timer` |
## Restore from a restic snapshot
Not yet run against the live stack; `restore-test` proves the same mechanics.
```bash
sudo gitea-backup snapshots # pick an ID, or use "latest"
sudo mount -t ntfs3 /dev/disk/by-label/BACKUP /mnt/backup
cd ~/mithlond
docker compose stop gitea # Caddy keeps the apex site up
sudo mv gitea-data gitea-data.broken
sudo sh -c '. /etc/gitea-backup/env; export RESTIC_REPOSITORY RESTIC_PASSWORD_FILE;
restic restore <ID> --tag gitea --target /'
docker compose up -d gitea # up -d re-applies compose.yml env hardening
cd ~ && sudo umount /mnt/backup
```
restic restores the absolute path `/home/admin/mithlond/gitea-data`
with original owners — no `chown`. Check the site, then
`ssh -T git@git.example.com -p 2222` (no host-key warning), then remove
`gitea-data.broken`.
## Restore from a tar archive
Not yet run against the live stack — [10](10-backup-manual.md) steps 7–12 prove the archive restores
into a fresh Gitea, and these are the same mechanics. Verify the checksum first.
```bash
cd ~/mithlond
sha256sum -c /mnt/backup/mithlond/gitea-backup-YYYYMMDD-HHMM.tar.gz.sha256
docker compose stop gitea # only gitea — Caddy keeps the apex site up
sudo mv gitea-data gitea-data.broken
sudo tar -xzpf /mnt/backup/mithlond/gitea-backup-YYYYMMDD-HHMM.tar.gz -C ~/mithlond
docker compose up -d gitea # up -d, not start: re-applies compose.yml env hardening
```
No `chown` needed — `tar -p` as root restores the original owners (`1000:1000`
for data, `root:root` for `ssh/`). Check `https://git.example.com`, then
`ssh -T git@git.example.com -p 2222` (no host-key warning = host keys came
back), then remove `gitea-data.broken`.
## Troubleshooting
| Symptom | Cause / fix |
|---|---|
| Failure mail: `HDD 'BACKUP' not attached` | Unplugged or USB dropped it. Replug; `lsblk`. |
| Run hangs, journal full of `input/output error` retries | Backup drive pulled mid-run. `sudo systemctl stop gitea-backup` (Ctrl+C alone does not stop it; the stop counts as a failure — mail sent), replug, then [ntfs-repair.md](ntfs-repair.md). |
| Failure mail / error: `BACKUP is dirty` | Power cut, unsafe eject or pull while mounted. Triage in [ntfs-repair.md](ntfs-repair.md): flag only → `ntfsfix`; `$MFTMirr` mismatch → `ntfsfix -d`; `Mark volume as dirty due to NTFS errors` → chkdsk VM. |
| Failure mail: `another gitea-backup is already running` | A manual run overlapped. Harmless; next night runs. |
| No Sunday report mail | Timer not firing, or mail broken. `systemctl list-timers`, `sudo gitea-backup test-mail`, `/var/log/msmtp.log`. |
| `repository is already locked by PID … lock was created at …` | A run cut off mid-write left its lock (its release never reached the disk). Every subcommand runs `restic unlock` first, which drops locks of dead processes (not yet exercised on a real stale lock). If it persists and nothing is running: `sudo sh -c '. /etc/gitea-backup/env; export RESTIC_REPOSITORY RESTIC_PASSWORD_FILE; mount -t ntfs3 /dev/disk/by-label/BACKUP /mnt/backup && restic unlock --remove-all; cd /; umount /mnt/backup'`. |
| `$MFTMirr does not match $MFT (record 3)` from `ntfsfix -n` | Backup drive pulled while mounted. [ntfs-repair.md](ntfs-repair.md) rung 2. |
| `msmtp: 535-5.7.8 Username and Password not accepted` | Wrong secret in `/etc/msmtprc` — see [11](11-backup-automated.md) step 5 (length must be 16). |
| `hostname: command not found` | Old script — minimal Arch has no `hostname`; current script uses `uname -n`. Reinstall ([11](11-backup-automated.md) step 3). |
| `daemon-reload: command not found` | It is `sudo systemctl daemon-reload`. |
| Gitea down after a failure | The EXIT trap restarts it; if that also failed the mail says so — `docker start gitea`. |

30
OKF/guides/index.md Normal file
View File

@ -0,0 +1,30 @@
---
type: Index
---
# Guides
Every guide ends with a checklist; tick it before moving on. Router
port-forwards are created only after [09](09-fail2ban.md)'s checklist — until
then the server stays LAN-only.
## Setup order — follow top to bottom
1. [01-arch-install.md](01-arch-install.md) — base OS from a live USB: partitions, packages, bootloader, user
2. [02-server-first-boot.md](02-server-first-boot.md) — lid never suspends, first boot, network, IP pinned at the router
3. [03-ssh-hardening.md](03-ssh-hardening.md) — key-only admin SSH on 2234, LAN-only, WireGuard for remote admin
4. [04-dns-records.md](04-dns-records.md) — CGNAT check, Cloudflare A records, API token
5. [05-ddns.md](05-ddns.md) — ddclient keeps the records on the home IP
6. [06-docker-deploy.md](06-docker-deploy.md) — `compose.yml`, `Caddyfile`, TLS (staging, then production)
7. [07-gitea-setup.md](07-gitea-setup.md) — install wizard, 2FA, SSH keys, tokens
8. [08-firewall.md](08-firewall.md) — nftables host firewall, survives reboot
9. [09-fail2ban.md](09-fail2ban.md) — bans for admin SSH and Gitea logins, Gitea hardening; then port-forwards
10. [10-backup-manual.md](10-backup-manual.md) — tar archive to the backup drive plus restore test (`scripts/backup.sh`)
11. [11-backup-automated.md](11-backup-automated.md) — nightly restic to the backup drive, failure mail, weekly report
12. [12-gitea-actions.md](12-gitea-actions.md) — Actions runner on the server, profile snake
## Operations — when needed
- [maintenance.md](maintenance.md) — updates, reboots and post-reboot checks, server quirks
- [backup-operations.md](backup-operations.md) — remote operation, real restore, troubleshooting
- [ntfs-repair.md](ntfs-repair.md) — NTFS triage, chkdsk via a Windows Setup VM

117
OKF/guides/maintenance.md Normal file
View File

@ -0,0 +1,117 @@
---
type: Guide
purpose: Keep the server updated and healthy across reboots.
answers:
- "How is the server updated, rebooted and worked on?"
---
# Maintenance: Updates, Reboots, Working on the Server
How to update the box without losing anything, how to prove it came back,
and what the server does and does not have. All of it learned the hard way on the
reference server.
## The server environment
Know these before typing commands on mithlond:
| Missing / different | Use instead |
|---|---|
| no `nano`, no `vi` | `sed -i` one-liners (all docs use them); `vim` **is** installed |
| no `hostname` (no `inetutils`) | `uname -n` |
| no `git` | `git` inside the gitea image: `docker run --rm --entrypoint git gitea/gitea:1.23 …` |
| no `rsync` | copy a file: `ssh -p 2234 admin@192.168.1.50 'cat > ~/mithlond/<path>' < <path>`; a tree: `tar -cz … \| ssh … 'tar -xz -C …'` |
| no `dig` | `getent hosts <name>` |
| no passwordless `sudo` | root steps run in your own terminal over SSH |
| `/tmp` is a **1.5G tmpfs** | big scratch work goes to `~` or `/var/tmp` |
| admin SSH LAN-only | from outside: router WireGuard first ([03 §7](03-ssh-hardening.md#7-remote-admin-wireguard-never-a-port-forward)) |
Typing hazards that cost time in practice — paste these, don't retype:
- `umount`, not `unmount`; `/dev/disk/by-label/BACKUP`, not `/dev/dick/…`,
and never `/dev/sdX` by hand (an `sda1`/`sdb1` slip hit `/boot`).
- `sudo systemctl daemon-reload` — `daemon-reload` alone is not a command.
- A shell `cd`'d into a mount keeps it busy; the prompt `[… mithlond]$` looks
the same in `/mnt/backup/mithlond` and `~/mithlond`. `cd ~` first.
- **Long one-liners break when pasted** (a paste once lost everything after
`qemu-system-x86_64`). Anything over one line belongs in a script under
`scripts/`.
## System update
### 1. Back up first
```bash
sudo systemctl start gitea-backup # nightly job, run now ([11](11-backup-automated.md))
journalctl -u gitea-backup -n 20 --no-pager # "snapshot … saved", Result success
```
Optionally also a standalone tar archive: `~/mithlond/scripts/backup.sh` ([10](10-backup-manual.md)).
### 2. Upgrade — always the whole system
```bash
sudo pacman -Syu
```
Never `pacman -S <pkg>` on its own after a long gap: if the local package
database is stale, mirrors answer `404` for the old file names (seen
installing `ntfs-3g` — every mirror 404'd until one still had the
old build). Installing against a stale database is a partial upgrade, which
Arch does not support. If you see a wall of 404s, stop and run `-Syu`.
### 3. Reboot if the kernel changed
`pacman -Syu` **deletes the running kernel's modules**. Until reboot, anything
that loads a module fails — e.g. mounting the backup drive (`ntfs3`). A Docker upgrade
also leaves the old daemon running until reboot.
```bash
uname -r # running kernel
ls /usr/lib/modules # installed — if uname -r is not listed, reboot now
grep -E 'upgraded (linux|docker|containerd) ' /var/log/pacman.log | tail -3
sudo reboot
```
An old laptop takes a few minutes to come back (slow HDD, slow USB spin-up).
## After every reboot — verify
On the server:
```bash
uname -r # the new kernel
systemctl is-active mithlond fail2ban ddclient docker # all active (+ your apex site's unit)
systemctl show nftables -p Result # Result=success ("inactive" is normal: oneshot)
sudo nft list table inet filter | head -5 # table present, "policy drop"
docker ps --format '{{.Names}} {{.Status}}' # caddy, gitea, runner Up (+ the apex site)
systemctl list-timers gitea-backup.timer # NEXT = next 03:30
```
Judge the firewall by the table, never by `systemctl is-active nftables`.
From any machine:
```bash
curl -sI https://git.example.com | head -1 # 200
curl -sI https://example.com | head -1 # 200
curl -sI https://www.example.com | head -1 # 301 → apex
ssh -T -p 2222 git@git.example.com # "Hi there, …"
```
A `502` for ~20 s right after boot is Gitea still starting behind Caddy.
### `enabled` is not `started`
A unit can show `enabled` but `inactive (dead)`: it had
been enabled after the previous boot without `--now`, and the container was
started by hand. Only a reboot proves an autostart unit. When enabling a unit,
use `sudo systemctl enable --now <unit>`, and count it as proven only after
the next reboot brings it up.
## Log
| Date | Change | Verified |
|---|---|---|
| YYYY-MM-DD | `pacman -Syu`: kernel, docker, containerd versions; reboot | all checks above green |

211
OKF/guides/ntfs-repair.md Normal file
View File

@ -0,0 +1,211 @@
---
type: Guide
purpose: Repair the NTFS backup drive without reformatting it.
answers:
- "How is a dirty or damaged NTFS backup drive repaired?"
cites:
- scripts/chkdsk-vm.sh
---
# Repairing a Dirty NTFS Backup Drive
The backup drive is NTFS and also holds non-backup data, so it is never reformatted. Linux
can clear its dirty flag and fix the `$MFT` mirror (`ntfsfix`), but **has no
full NTFS repair** — real damage needs Windows `chkdsk`. With no Windows
machine, `chkdsk` runs from the official Windows 11 ISO's Setup command prompt
inside a VM on a separate Linux PC (not the server), with the backup drive passed through over
USB. Nothing gets installed and no licence is needed.
## Triage — find your rung, start there
Symptom first appears as a mount failure on mithlond:
```
mount: /mnt/backup: wrong fs type, bad option, bad superblock on /dev/sdb1 ...
ERROR: BACKUP is dirty — run by hand: ntfsfix -n /dev/disk/by-label/BACKUP, then ntfsfix -d
```
Then read the kernel log — it says which rung you are on:
```bash
journalctl -k --since "-1h" --no-pager | grep -iE 'ntfs3|sdb|I/O'
```
| Kernel log / `ntfsfix -n` says | Meaning | Go to |
|---|---|---|
| `volume is dirty and "force" flag is not set!` only; `ntfsfix -n` ends `processed successfully` with no mismatch | Flag left by an unsafe eject or Windows Fast Startup; structures fine | [Rung 1](#rung-1--clear-the-dirty-flag) |
| `ntfsfix -n`: `$MFTMirr does not match $MFT (record 3)` | Unplugged while mounted; the `$Volume` record's mirror missed a write | [Rung 2](#rung-2--fix-the-mft-mirror) |
| `Mark volume as dirty due to NTFS errors`, or the flag comes back right after rung 1/2 | Real damage (index/record) in something written at unplug time | [Rung 3](#rung-3--chkdsk-via-a-windows-setup-vm) |
| `failed to read volume at offset`, `Synchronize Cache failed`, USB resets **while plugged in** | Cable, port or drive hardware | Swap cable/port; check SMART: `sudo smartctl -a /dev/sdb` (`smartmontools`) |
Never `mount -o force` and never reformat. Every rung below runs only with
nothing using the backup drive: `findmnt /mnt/backup` prints nothing, and
`systemctl is-active gitea-backup` is not `activating`.
Always address the drive as **`/dev/disk/by-label/BACKUP`**, not `/dev/sdb1` — a
mistyped `sda1` can hit the server's own `/boot` (ntfsfix refuses only because it
is mounted).
## Rung 1 — clear the dirty flag
On mithlond (`ntfsfix` is in `ntfsprogs`, not `ntfs-3g`):
```bash
sudo ntfsfix -n /dev/disk/by-label/BACKUP # dry run — must end "processed successfully", no "does not match"
sudo ntfsfix -d /dev/disk/by-label/BACKUP # clears the flag, empties the journal
sudo gitea-backup check # mounts, reads every restic pack back
```
## Rung 2 — fix the MFT mirror
`ntfsfix -n` printing `$MFTMirr does not match $MFT (record 3)` followed by
`Remount failed: Input/output error` is expected in dry-run mode — nothing was
written yet, so the simulated remount still sees the mismatch. Record 3 is
`$Volume`, which holds the dirty flag itself; `ntfsfix` copies the good `$MFT`
record over the mirror, which is the designed fix.
```bash
sudo ntfsfix -d /dev/disk/by-label/BACKUP # "Correcting differences in $MFTMirr record 3...OK"
sudo ntfsfix -n /dev/disk/by-label/BACKUP # re-check: no mismatch, "processed successfully"
sudo gitea-backup check
```
**If the volume is dirty again straight after this `check`** (kernel log:
`Mark volume as dirty due to NTFS errors`), ntfs3 hit damage that `ntfsfix`
cannot touch → rung 3. Do not loop on `ntfsfix -d`: every rw mount of a
damaged volume risks the other data on the backup drive.
## Rung 3 — chkdsk via a Windows Setup VM
On a **separate Linux PC** with KVM (the commands assume Arch; adapt if yours
differs). Not on the server: little RAM, old CPU, live services.
Do not use Windows XP's `chkdsk /f` on the backup drive: it predates NTFS features newer
Windows writes and can "repair" them away. XP also cannot see GPT disks.
### 1. QEMU
```bash
sudo pacman -S qemu-desktop
ls -l /dev/kvm # must exist
```
### 2. The Windows 11 ISO
Microsoft issues a per-session link valid 24 h — there is no fixed URL.
1. Open <https://www.microsoft.com/software-download/windows11>.
2. *Download Windows 11 Disk Image (ISO) for x64 devices* → **Windows 11
(multi-edition ISO for x64 devices)** → **Download Now**.
3. Pick a language → **Confirm** → right-click **64-bit Download** → copy link.
4. Download (quotes required — the link contains `&`; `-C -` resumes):
```bash
mkdir -p vm && curl -L -C - -o vm/Win11_x64.iso '<pasted link>' # from the repo root
```
About 7–9 GB. `vm/` is gitignored, so the ISO stays out of git but inside the
repo; keep it for next time — rung 3 needs no new download while it is there.
### 3. Plug the backup drive into the PC
```bash
lsusb # find your drive; its ID goes in DRIVE_USB
findmnt -S LABEL=BACKUP || echo "not mounted — good"
```
If the desktop auto-mounted it, unmount it first (`udisksctl unmount -b
/dev/disk/by-label/BACKUP`) — the VM must have the drive to itself.
### 4. Boot the ISO with the backup drive passed through
Use the script — the long QEMU line is fragile to paste (a paste once
broke after `qemu-system-x86_64`, which then booted an empty VM:
"No bootable device", then an iPXE prompt):
```bash
scripts/chkdsk-vm.sh # from the repo root; uses the newest vm/Win*11*.iso
scripts/chkdsk-vm.sh path/to/Win11.iso # or an explicit ISO
```
Run it **as yourself, not with `sudo`** — root cannot open a window on the
Wayland desktop (`Authorization required, but no authorization protocol
specified`). It refuses if a QEMU is already running, the backup drive is not plugged in,
or the backup drive is mounted on the PC; asks for sudo once to `setfacl` the backup drive's USB
node (`/dev/kvm` needs nothing); boots **UEFI** (OVMF, package `edk2-ovmf`,
q35) with the ISO and the backup drive, no network. The VM's UEFI variable store is kept
in `vm/OVMF_VARS.4m.fd`.
What you see:
1. TianoCore logo, then **"Press any key to boot from CD or DVD…"** for ~5 s
— press Enter repeatedly from the moment the window opens.
2. Missed it → a boot menu (*EFI Firmware Setup / UEFI QEMU DVD-ROM / EFI
Internal Shell*): pick **UEFI QEMU DVD-ROM**, Enter, and press Enter
repeatedly again. At a `Shell>` prompt instead: type `exit`.
3. Windows logo, then (1–2 min, 9 GB ISO) the Setup language screen.
Stop QEMU (only when chkdsk is **not** running): close the window, Ctrl+C in
its terminal, or `pkill -x qemu-system-x86_64`. Check `pgrep -a qemu`; the
args after `qemu-system-x86_64` show what it was really started with.
### 5. chkdsk from the Setup command prompt
At the first Setup screen (language) press **Shift+F10**:
```
diskpart
list volume ← the backup drive: ~1863 GB, NTFS, label "BACKUP" — note its letter
exit
chkdsk X: /f ← X = that letter
```
Answer **Y** if it offers to convert lost chains to files. `/f` checks
metadata, not every sector: minutes to ~1 h over USB passthrough, and the
percentage stalls then jumps (stage 2, indexes). **Never close the window
mid-run.** Wait for the summary; photograph or note it (record in the [log](#incident-log)).
A good finish reads `… No further action is required` and `0 KB in bad
sectors`. `Unable to obtain a handle to the event log` is harmless — Setup has
no event log service, so chkdsk cannot file its report there.
If `list volume` shows no ~1863 GB volume, the passthrough failed — check
`lsusb` IDs on the host, the `setfacl` grant, and that nothing on the host
mounted it.
Then close the QEMU window (or `wpeutil shutdown`). The backup drive was never mounted on
the PC, so unplugging is safe.
### 6. Back on mithlond
One at a time; stop and investigate if any fails:
```bash
sudo gitea-backup check # "no errors were found"
sudo gitea-backup restore-test # "RESTORE TEST PASSED"
sudo gitea-backup snapshots # a snapshot from a run cut off mid-write may be missing or flagged
```
If `check` blames one snapshot (e.g. the one written at unplug time), drop it
and prune: `sudo sh -c '. /etc/gitea-backup/env; export RESTIC_REPOSITORY
RESTIC_PASSWORD_FILE; mount -t ntfs3 /dev/disk/by-label/BACKUP /mnt/backup &&
restic forget <ID> --prune; cd /; umount /mnt/backup'`, then `check` again.
Also open a few of your non-backup files on the backup drive (from the PC) to confirm
they survived.
## Avoiding a repeat
- **Never unplug the backup drive while it is mounted.** `findmnt /mnt/backup` must print
nothing. The nightly run mounts it only ~1–2 min around 03:30.
- To test the failure mail, unplug **before** starting a run, never during.
- Eject from Windows/the PC safely too; Windows Fast Startup leaves the flag.
- Longer term: a small **ext4 partition on the backup drive** for the restic repo would
make this repairable on the server with `fsck`, no Windows. `ntfsresize`
(`ntfsprogs`) / GParted can shrink NTFS from Linux — but only once the
volume is consistent, i.e. after a clean rung 3.
## Incident log
| Date | What happened | Rung | Outcome |
|---|---|---|---|
| YYYY-MM-DD | e.g. drive pulled mid-run; `$MFTMirr` mismatch | 2 | e.g. `ntfsfix -d`, `check` clean |

28
OKF/index.md Normal file
View File

@ -0,0 +1,28 @@
---
okf_version: "0.1"
---
# Mithlond — OKF index
Open-knowledge-format wiki. Agents: read this page first, then the pages your
task needs. Humans: building the server? Go straight to
[guides/index.md](guides/index.md).
## Pages
- [SUMMARY.md](SUMMARY.md) — what Mithlond is; start here cold.
- [ARCHITECTURE.md](ARCHITECTURE.md) — request path, services, seams.
- [CONTEXT.md](CONTEXT.md) — canonical vocabulary.
- [ROADMAP.md](ROADMAP.md) — phases (all done), risks, out of scope.
## Guides
- [guides/index.md](guides/index.md) — the setup order (01–12), then operations.
## Modules
- [modules/index.md](modules/index.md) — `scripts/`.
## Decisions
- [decisions/index.md](decisions/index.md) — why this stack: forge, database, proxy, ports, backups.

7
OKF/modules/index.md Normal file
View File

@ -0,0 +1,7 @@
---
type: Index
---
# Modules
- [scripts.md](scripts.md) — the three shell scripts in `scripts/`

24
OKF/modules/scripts.md Normal file
View File

@ -0,0 +1,24 @@
---
type: Module
purpose: Say what each script in scripts/ does, where it runs, and which guide drives it.
answers:
- "What does each script in scripts/ do, and where does it run?"
cites:
- scripts/backup.sh
- scripts/gitea-backup
- scripts/chkdsk-vm.sh
---
# scripts/
<!-- okf:derived begin -->
| Script | Runs on | Does | Guide |
|---|---|---|---|
| `scripts/backup.sh` | server, as the admin user | manual tar backup of `gitea-data/` to the backup drive plus restore test; `verify ARCHIVE` re-checks one | [10](../guides/10-backup-manual.md) |
| `scripts/gitea-backup` | server, root, installed to `/usr/local/sbin/` | nightly restic backup and its subcommands (`init`, `run`, `snapshots`, `check`, `restore-test`, `test-mail`, `notify-failure`) | [11](../guides/11-backup-automated.md), [ops](../guides/backup-operations.md) |
| `scripts/chkdsk-vm.sh` | a separate Linux PC, not the server | boots a Windows Setup VM with the backup drive passed through for `chkdsk` | [ntfs-repair](../guides/ntfs-repair.md) |
<!-- okf:derived end -->
`gitea-backup` runs from the systemd units in `systemd/`
(`gitea-backup.service`, `.timer`, `gitea-backup-failed.service`); the guide
for [11](../guides/11-backup-automated.md) lists where each is installed.

135
README.md Normal file
View File

@ -0,0 +1,135 @@
# Mithlond
A template for running your own Gitea git forge on a spare machine, public on
your own domain, with per-repository public/private control, hardened, backed
up every night, and with CI. Every step is written down so you can repeat it.
<img src="assets/y530-still-alive.jpeg" alt="A 2008 Lenovo IdeaPad Y530 running as the server: lid open, screen barely alive, Ethernet plugged in, a shell prompt on the screen" width="375">
*The reference server: a 2008 Lenovo IdeaPad Y530 with 3 GB of RAM, still alive.
If it runs on this, it runs on whatever you have in a drawer.*
## What you get
```
Internet → Router → Caddy (TLS) → Gitea (SQLite) git.example.com
└→ optional apex site example.com
→ Gitea SSH (port 2222)
→ Admin SSH (port 2234, LAN only; WireGuard from outside)
DNS: Cloudflare, kept on your home IP by ddclient
Backups: nightly restic to a USB drive, mail on failure, weekly report
CI: Gitea Actions runner on the same box
```
| Component | Role |
|---|---|
| Arch Linux (headless) | Host OS |
| Docker Compose | Runs Gitea, Caddy and the Actions runner |
| Gitea + SQLite | Git forge |
| Caddy | Reverse proxy, automatic Let's Encrypt TLS |
| ddclient + Cloudflare | Dynamic DNS |
| nftables + fail2ban | Host firewall, brute-force bans |
| restic + msmtp (Gmail SMTP) | Nightly backups and failure mail |
The guides document this one path. **Adapt if yours differs**: another
distribution, DNS provider, router or mail server works, but the commands and
menu names will change.
## Before you start: replace the placeholders
| Placeholder | Meaning | Where |
|---|---|---|
| `example.com`, `git.example.com`, `www.example.com` | your domain and the forge's hostname | `Caddyfile`, `compose.yml`, guides |
| `you@example.com`, `you@gmail.com` | Let's Encrypt contact; mail sender and recipient | `Caddyfile`, `systemd/msmtprc.example`, `systemd/gitea-backup.env.example` |
| `admin` | your login on the server | guides, `scripts/gitea-backup` (`STACK=`) |
| `yourname` | your Gitea username | `profile/`, guide 12 |
| `192.168.1.50`, `192.168.1.1` | the server's reserved LAN IP; the router | guides |
| `BACKUP` | filesystem label of the USB backup drive | `scripts/`, `systemd/gitea-backup.env.example` |
| `portfolio:8000` | the optional apex site's container and port | `Caddyfile` (delete the block if you host only Gitea) |
| `DRIVE_USB=0000:0000` | the backup drive's USB ID, for NTFS repair | `scripts/chkdsk-vm.sh` |
Find any you missed with `grep -rnE 'example\.com|yourname|192\.168\.1\.|you@' .`
## Setup, step by step
Do them in order and tick each guide's checklist before moving on. The router
port-forwards come only after step 9, so the server stays LAN-only until it is
hardened.
1. **Install Arch Linux** headless from a live USB: partitions, packages,
bootloader, user. → [01-arch-install](OKF/guides/01-arch-install.md)
2. **Make it a server**: closing the lid never suspends it, first boot, DHCP
reservation at the router. → [02-server-first-boot](OKF/guides/02-server-first-boot.md)
3. **Harden admin SSH**: keys only, port 2234, LAN-only, WireGuard for remote
access. → [03-ssh-hardening](OKF/guides/03-ssh-hardening.md)
4. **Create DNS records**: rule out CGNAT, add Cloudflare A records, create an
API token. → [04-dns-records](OKF/guides/04-dns-records.md)
5. **Keep DNS current** with ddclient as your home IP changes.
→ [05-ddns](OKF/guides/05-ddns.md)
6. **Deploy the stack**: copy `compose.yml` and `Caddyfile`, prove TLS on
Let's Encrypt staging, then go live. → [06-docker-deploy](OKF/guides/06-docker-deploy.md)
7. **Set up Gitea**: install wizard, 2FA, SSH keys, access tokens.
→ [07-gitea-setup](OKF/guides/07-gitea-setup.md)
8. **Turn on the firewall**: nftables without breaking Docker, survives
reboot. → [08-firewall](OKF/guides/08-firewall.md)
9. **Ban brute force and harden Gitea**: fail2ban for SSH and Gitea logins,
then create the router port-forwards. → [09-fail2ban](OKF/guides/09-fail2ban.md)
10. **Back up by hand** to a USB drive and prove the archive restores.
→ [10-backup-manual](OKF/guides/10-backup-manual.md)
11. **Automate backups**: nightly restic, failure mail, weekly report.
→ [11-backup-automated](OKF/guides/11-backup-automated.md)
12. **Add CI**: a Gitea Actions runner, with a profile-page snake as the first
job. → [12-gitea-actions](OKF/guides/12-gitea-actions.md)
When something needs doing later:
[maintenance](OKF/guides/maintenance.md) (updates, reboots, server quirks),
[backup-operations](OKF/guides/backup-operations.md) (remote operation, restore,
troubleshooting), [ntfs-repair](OKF/guides/ntfs-repair.md) (a dirty or damaged
NTFS backup drive).
## Ports
| Port | Protocol | Purpose | Forwarded by the router |
|---|---|---|---|
| 80 | TCP | HTTP (ACME challenge only, redirects to 443) | yes |
| 443 | TCP | HTTPS: Gitea web UI and git over HTTPS | yes |
| 2222 | TCP | Git over SSH | yes |
| 2234 | TCP | Admin SSH to the host | **no** |
## Repository layout
```
.
├── README.md
├── LICENSE
├── AGENTS.md # contract for AI coding agents; CLAUDE.md points here
├── assets/ # images for this README
├── compose.yml # Docker Compose stack: gitea, caddy, runner
├── Caddyfile # Caddy reverse proxy config
├── OKF/ # project wiki — start at OKF/index.md
│ ├── guides/ # setup guides 01–12 + operations (index.md)
│ ├── decisions/ # why the stack is what it is
│ ├── CONTEXT.md, ROADMAP.md, SUMMARY.md, ARCHITECTURE.md
│ └── modules/
├── scripts/
│ ├── backup.sh # manual backup + restore test (guide 10)
│ ├── chkdsk-vm.sh # Windows Setup VM for chkdsk on the backup drive — runs on a separate PC
│ └── gitea-backup # nightly restic backup, installed to /usr/local/sbin (guide 11)
├── systemd/ # gitea-backup units + config examples (guide 11)
├── runner/config.yaml # Gitea Actions runner config (guide 12)
├── profile/ # content for your <user>/.profile repo — snake workflow (guide 12)
├── vm/ # created on the repair PC — Windows ISO + UEFI vars (not committed)
├── gitea-data/ # created at runtime — Gitea volume (not committed)
├── caddy-data/ # created at runtime — TLS certs (not committed)
├── caddy-config/ # created at runtime — Caddy state (not committed)
└── runner-data/ # created at runtime — runner registration (not committed)
```
Vocabulary: [OKF/CONTEXT.md](OKF/CONTEXT.md). Plan and verify steps:
[OKF/ROADMAP.md](OKF/ROADMAP.md). Why each piece was chosen:
[OKF/decisions/index.md](OKF/decisions/index.md).
## License
[MIT](LICENSE).

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

86
compose.yml Normal file
View File

@ -0,0 +1,86 @@
services:
gitea:
image: gitea/gitea:1.23
container_name: gitea
environment:
- USER_UID=1000
- USER_GID=1000
- GITEA__database__DB_TYPE=sqlite3
- GITEA__database__PATH=/data/gitea/gitea.db
- GITEA__server__DOMAIN=git.example.com
- GITEA__server__SSH_DOMAIN=git.example.com
- GITEA__server__SSH_PORT=2222
- GITEA__server__ROOT_URL=https://git.example.com/
- GITEA__server__HTTP_PORT=3000
- GITEA__service__DISABLE_REGISTRATION=true
- GITEA__service__DEFAULT_KEEP_EMAIL_PRIVATE=true
# console alone keeps logs in `docker logs` only, leaving
# /data/gitea/log empty — the fail2ban gitea jail (OKF/guides/09) needs a real
# file on disk to tail.
- GITEA__log__MODE=console,file
# Hardening (OKF/guides/09 §3). Kept here rather than in app.ini: env wins on
# every container start, so an app.ini edit to these keys is reverted.
- GITEA__server__LFS_START_SERVER=false
- GITEA__openid__ENABLE_OPENID_SIGNIN=false
- GITEA__security__MIN_PASSWORD_LENGTH=12
- GITEA__security__PASSWORD_COMPLEXITY=lower,upper,digit,spec
# On by default since 1.21; explicit so the dependency is visible (OKF/guides/12).
- GITEA__actions__ENABLED=true
volumes:
- ./gitea-data:/data
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
ports:
- "127.0.0.1:3000:3000"
- "0.0.0.0:2222:22"
restart: unless-stopped
networks:
- gitea-net
caddy:
image: caddy:2
container_name: caddy
ports:
- "0.0.0.0:80:80"
- "0.0.0.0:443:443"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- ./caddy-data:/data
- ./caddy-config:/config
restart: unless-stopped
networks:
- gitea-net
- edge
depends_on:
- gitea
# Gitea Actions runner (OKF/guides/12). Polls Gitea over HTTPS like any outside
# client and starts each job as a sibling container through the host's
# Docker socket — root-equivalent, acceptable only because this is a
# single-user forge with registration disabled.
runner:
image: gitea/act_runner:0.6.1
container_name: runner
environment:
- CONFIG_FILE=/config.yaml
- GITEA_INSTANCE_URL=https://git.example.com
- GITEA_RUNNER_NAME=mithlond
# Read only on first start, when runner-data/.runner does not exist yet.
# Delete the file once registered.
- GITEA_RUNNER_REGISTRATION_TOKEN_FILE=/data/registration-token
volumes:
- ./runner/config.yaml:/config.yaml:ro
- ./runner-data:/data
- /var/run/docker.sock:/var/run/docker.sock
restart: unless-stopped
depends_on:
- gitea
networks:
gitea-net:
driver: bridge
# Shared with an optional second stack on the apex domain (e.g. a portfolio),
# which declares it the same way. Created once
# by hand: docker network create edge
edge:
external: true

View File

@ -0,0 +1,44 @@
# Draws the contribution heatmap as a snake game and publishes the SVGs to
# the orphan `output` branch, which README.md embeds. Runs on the mithlond
# runner (OKF/guides/12).
name: snake
on:
schedule:
# Daily, clear of the 03:30 backup window when Gitea is stopped.
- cron: "0 5 * * *"
workflow_dispatch:
push:
branches: [main]
defaults:
run:
shell: sh
jobs:
generate:
runs-on: alpine
steps:
- name: Generate SVGs from the Gitea heatmap
run: |
host=${GITHUB_SERVER_URL#https://}; host=${host%/}
# Gitea serves the same /api/v1/users/<name>/heatmap as Forgejo.
npx --yes generate-snake-animation@3.5.0 \
--forgejo_user="$host/$GITHUB_REPOSITORY_OWNER" \
--output=dist/snake.svg \
--output='dist/snake-dark.svg?palette=github-dark'
- name: Publish to the output branch
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
apk add --no-cache -q git
host=${GITHUB_SERVER_URL#https://}; host=${host%/}
cd dist
git init -q -b output
git config user.name "snake"
git config user.email "actions@$host"
git add .
git commit -qm "Update snake"
# Single orphan commit, force-pushed: old SVGs do not pile up.
git push -qf "https://x-access-token:$TOKEN@$host/$GITHUB_REPOSITORY.git" output

4
profile/README.md Normal file
View File

@ -0,0 +1,4 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://git.example.com/yourname/.profile/raw/branch/output/snake-dark.svg">
<img alt="Contribution heatmap eaten by a snake" src="https://git.example.com/yourname/.profile/raw/branch/output/snake.svg">
</picture>

32
runner/config.yaml Normal file
View File

@ -0,0 +1,32 @@
# act_runner config (OKF/guides/12). Sized for a small server: 3G RAM, spinning HDD.
# Full reference: `act_runner generate-config`.
log:
level: info
runner:
file: .runner
# One job at a time; Gitea, Caddy and an apex site already hold ~500M.
capacity: 1
timeout: 30m
# Back off to one poll per 30s when idle, sparing the SQLite DB on the HDD.
fetch_interval: 2s
fetch_interval_max: 30s
# Honest label: jobs run in Alpine with Node, not Ubuntu. A workflow copied
# from GitHub with `runs-on: ubuntu-latest` waits in the queue rather than
# failing in strange ways on a missing tool.
labels:
- "alpine:docker://node:24-alpine"
cache:
# No workflow uses actions/cache; skip running the cache server.
enabled: false
container:
network: ""
privileged: false
options: "--memory=768m --memory-swap=768m"
valid_volumes: []
# "-": find the Docker host but do NOT mount its socket into job
# containers. Jobs cannot start containers or reach the host's Docker.
docker_host: "-"
force_pull: true

232
scripts/backup.sh Executable file
View File

@ -0,0 +1,232 @@
#!/usr/bin/env bash
# Back up Gitea's data volume to the portable HDD, then prove the archive restores.
#
# Run on the server as the admin user (not root), from anywhere:
# ~/mithlond/scripts/backup.sh # back up + verify
# ~/mithlond/scripts/backup.sh verify ARCHIVE # re-verify an existing archive
#
# ARCHIVE is a path, or a bare file name inside $MOUNT/$DEST_DIR.
# Procedure and rationale: OKF/guides/10-backup-manual.md. Each step below is numbered to match.
set -euo pipefail
LABEL=${LABEL:-BACKUP} # filesystem label of the portable HDD
MOUNT=${MOUNT:-/mnt/backup}
DEST_DIR=${DEST_DIR:-mithlond} # folder at the HDD root — the rest of the drive is untouched
STACK=$(cd "$(dirname "$0")/.." && pwd)
SCRATCH=$HOME/restore-test # not /tmp: it is a 1.5G tmpfs, too small for the extract
TEST_CONTAINER=gitea-restore-test
mounted_by_us=0
gitea_stopped=0
partial_archive=
scratch_ours=0
log() { printf '\n==> %s\n' "$*"; }
die() { printf '\nERROR: %s\n' "$*" >&2; exit 1; }
usage() { sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'; exit 2; }
# Whatever fails, never leave Gitea stopped, a half-written archive, host-key
# copies in $SCRATCH, or the HDD mounted.
cleanup() {
local rc=$?
if (( gitea_stopped )); then
echo "==> restarting gitea (exit path)"
(cd "$STACK" && docker compose start gitea) \
|| echo "!! gitea did not start — run: cd $STACK && docker compose start gitea" >&2
fi
if [[ -n $partial_archive ]]; then
echo "==> removing incomplete archive $partial_archive"
sudo rm -f "$partial_archive" "$partial_archive.sha256"
fi
docker rm -f "$TEST_CONTAINER" >/dev/null 2>&1 || true
if (( scratch_ours )); then rm -rf "$SCRATCH"; fi
if (( mounted_by_us )); then
cd "$HOME" # a cwd inside $MOUNT (e.g. launched from there) makes umount "target is busy"
sync
sudo umount "$MOUNT" && echo "==> unmounted $MOUNT — safe to unplug" \
|| echo "!! umount failed — run: sudo umount $MOUNT" >&2
fi
exit "$rc"
}
trap cleanup EXIT
# 0. Preflight
preflight() {
(( EUID != 0 )) || die "run as the admin user, not root (sudo is called where needed)"
local c
for c in docker sqlite3 sha256sum tar findmnt; do
command -v "$c" >/dev/null || die "missing command: $c"
done
[[ -d $STACK/gitea-data ]] || die "no gitea-data in $STACK"
docker inspect gitea >/dev/null 2>&1 || die "no gitea container — is the stack up?"
}
# 1–2. Find the HDD by label and mount it with the kernel ntfs3 driver
mount_hdd() {
local dev=/dev/disk/by-label/$LABEL
[[ -e $dev ]] || die "HDD '$LABEL' not attached. Check: lsblk -o NAME,SIZE,FSTYPE,LABEL,TRAN"
dev=$(readlink -f "$dev")
if findmnt -rn "$MOUNT" >/dev/null; then
local src
src=$(findmnt -rno SOURCE "$MOUNT")
[[ $src == "$dev" ]] || die "$MOUNT already holds $src, not $LABEL ($dev)"
log "$LABEL ($dev) already mounted at $MOUNT — leaving it mounted afterwards"
return
fi
log "mounting $LABEL ($dev) at $MOUNT"
sudo mkdir -p "$MOUNT"
if ! sudo mount -t ntfs3 "$dev" "$MOUNT"; then
sudo dmesg | tail -n 20 | grep -q 'volume is dirty' \
|| die "mount failed and the volume is not merely dirty — see: sudo dmesg | tail"
# Windows left the dirty flag (unsafe eject / Fast Startup). Never mount -o force.
command -v ntfsfix >/dev/null || die "volume is dirty; install ntfsprogs (ntfsfix is not in ntfs-3g)"
log "volume is dirty — dry run: ntfsfix -n"
sudo ntfsfix -n "$dev" || die "ntfsfix dry run found problems — run chkdsk /f on Windows instead"
local answer
read -rp "Dry run clean. Clear the dirty flag with 'ntfsfix -d'? [y/N] " answer
[[ $answer == [yY] ]] || die "aborted — volume left dirty and unmounted"
sudo ntfsfix -d "$dev"
sudo mount -t ntfs3 "$dev" "$MOUNT"
fi
mounted_by_us=1
}
# 3–6. Stop Gitea, archive gitea-data, start Gitea, write checksum
backup() {
local dir=$MOUNT/$DEST_DIR name
name=gitea-backup-$(date +%Y%m%d-%H%M).tar.gz
archive=$dir/$name
[[ ! -e $archive ]] || die "$archive already exists"
sudo mkdir -p "$dir"
local need have
need=$(sudo du -sb "$STACK/gitea-data" | cut -f1)
have=$(df --output=avail -B1 "$MOUNT" | tail -n1)
(( have > need )) || die "not enough space on $LABEL: need $need bytes, have $have"
log "stopping gitea (SQLite must not be written mid-copy)"
cd "$STACK"
gitea_stopped=1
docker compose stop gitea
local t0=$SECONDS
# tar, not cp -r: NTFS cannot hold Linux owners/modes, and gitea-data/ssh
# (host keys) is root:root 700. -p keeps them inside the archive.
log "archiving gitea-data -> $archive"
partial_archive=$archive
sudo tar -czpf "$archive" -C "$STACK" gitea-data
log "starting gitea"
docker compose start gitea
gitea_stopped=0
echo "gitea was down $((SECONDS - t0))s"
log "writing checksum"
(cd "$dir" && sudo sh -c 'sha256sum "$1" > "$1.sha256"' sh "$name")
sync
partial_archive=
}
# 7–12. Restore test: extract to scratch, check DB + repos, boot a throwaway Gitea
verify() {
local archive=$1
[[ $archive == */* ]] || archive=$MOUNT/$DEST_DIR/$archive
[[ -f $archive && -f $archive.sha256 ]] || die "need $archive and $archive.sha256"
local dir name
dir=$(dirname "$archive") name=$(basename "$archive")
log "7. checksum"
(cd "$dir" && sha256sum -c "$name.sha256")
log "8. archive contents"
echo "entries: $(tar -tzf "$archive" | wc -l)"
tar -tvzf "$archive" | grep -E '^drwx------ root/root .* gitea-data/ssh/$' >/dev/null \
|| die "gitea-data/ssh/ missing or lost its root:root 700 — archive not restorable as-is"
echo "gitea-data/ssh/ present, root:root 700"
log "9. extracting to $SCRATCH"
[[ ! -e $SCRATCH ]] || die "$SCRATCH exists — inspect and remove it first"
mkdir "$SCRATCH"
scratch_ours=1
tar -xzf "$archive" -C "$SCRATCH"
local r=$SCRATCH/gitea-data
[[ -f $r/gitea/gitea.db && -d $r/git/repositories ]] || die "extract lacks gitea.db or repositories"
log "10. SQLite integrity"
local ok
ok=$(sqlite3 -readonly "$r/gitea/gitea.db" 'PRAGMA integrity_check;')
[[ $ok == ok ]] || die "gitea.db integrity_check: $ok"
echo "integrity_check: ok"
sqlite3 -readonly -list -noheader "$r/gitea/gitea.db" \
"select 'users=' || count(*) from user; select 'repos=' || count(*) from repository;"
# The server has no git; the gitea image does.
log "11. git fsck every repo (inside the gitea image, read-only mount)"
local img
img=$(docker inspect -f '{{.Config.Image}}' gitea)
docker run --rm --user 1000:1000 --entrypoint sh -v "$r/git/repositories:/r:ro" "$img" -c '
cd /r; fail=0
for d in */*.git; do
if out=$(git -c safe.directory="*" --git-dir="$d" fsck --no-progress --no-dangling 2>&1); then
printf "%-36s %s\n" "$d" "${out:-OK}"
else
printf "%-36s FAILED\n%s\n" "$d" "$out"; fail=1
fi
done
exit $fail' || die "git fsck failed on at least one repo"
echo
if diff -rq "$r/git" "$STACK/gitea-data/git" >/dev/null; then
echo "repos identical to live gitea-data/git"
else
echo "note: repos differ from live — expected if anything was pushed since this backup"
fi
log "12. boot a throwaway Gitea on the extract (--network none, live stack untouched)"
docker run -d --rm --name "$TEST_CONTAINER" --network none \
-e USER_UID=1000 -e USER_GID=1000 -v "$r:/data" "$img" >/dev/null
local i version=
for i in $(seq 1 30); do
version=$(docker exec "$TEST_CONTAINER" wget -qO- http://127.0.0.1:3000/api/v1/version 2>/dev/null) && break
sleep 2
done
[[ -n $version ]] || { docker logs --tail 20 "$TEST_CONTAINER"; die "restored Gitea did not answer within 60s"; }
echo "restored Gitea answers: $version"
docker exec "$TEST_CONTAINER" su git -c 'gitea admin user list'
docker stop "$TEST_CONTAINER" >/dev/null
log "13. cleanup: removing $SCRATCH (holds copies of the SSH host keys)"
rm -rf "$SCRATCH"
scratch_ours=0
log "VERIFIED: $archive"
}
# 14. Retention report — never deletes anything
retention() {
local dir=$MOUNT/$DEST_DIR n
log "backups on $LABEL"
ls -lh "$dir"
n=$(find "$dir" -maxdepth 1 -name 'gitea-backup-*.tar.gz' | wc -l)
(( n >= 2 )) || echo "note: only $n backup(s) on $LABEL — keep at least two"
}
archive=
case ${1:-} in
"")
preflight
sudo -v # ask for the password now, not during Gitea downtime
mount_hdd
backup
verify "$archive"
retention
;;
verify)
[[ -n ${2:-} ]] || usage
preflight
mount_hdd
verify "$2"
;;
*) usage ;;
esac

59
scripts/chkdsk-vm.sh Executable file
View File

@ -0,0 +1,59 @@
#!/usr/bin/env bash
# Boot the Windows 11 Setup ISO in a throwaway UEFI VM with the backup drive passed
# through over USB, so chkdsk can repair it without a Windows machine.
# Run on a separate Linux PC (not the server), as yourself — not with sudo:
# scripts/chkdsk-vm.sh [path/to/Win11.iso]
# Without an argument it uses the newest vm/Win*11*.iso in this repo.
# vm/ is gitignored: it holds the ISO and the VM's UEFI variable store.
# Then: press Enter repeatedly at "Press any key to boot from CD or DVD",
# Shift+F10 at the language screen, diskpart / list volume / exit,
# chkdsk X: /f. See OKF/guides/ntfs-repair.md rung 3.
set -euo pipefail
VM_DIR=$(cd "$(dirname "$0")/.." && pwd)/vm
if [[ -n ${1:-} ]]; then
ISO=$1
else
ISO=$(ls -t "$VM_DIR"/Win*11*.iso 2>/dev/null | head -n1) || true
fi
DRIVE_USB=0000:0000 # your drive's vendor:product ID, from lsusb
OVMF_CODE=/usr/share/edk2/x64/OVMF_CODE.4m.fd
OVMF_VARS_TEMPLATE=/usr/share/edk2/x64/OVMF_VARS.4m.fd
OVMF_VARS=$VM_DIR/OVMF_VARS.4m.fd
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
(( EUID != 0 )) || die "run as yourself: root cannot open a window on the Wayland desktop"
[[ -n $ISO && -f $ISO ]] || die "no Windows 11 ISO — pass its path, or put it in $VM_DIR/"
[[ -f $OVMF_CODE ]] || die "no UEFI firmware — sudo pacman -S edk2-ovmf"
command -v qemu-system-x86_64 >/dev/null || die "no QEMU — sudo pacman -S qemu-desktop"
[[ -w /dev/kvm ]] || die "/dev/kvm not usable"
if pgrep -x qemu-system-x86_64 >/dev/null; then
die "a QEMU is already running — close it first (pkill -x qemu-system-x86_64)"
fi
line=$(lsusb -d "$DRIVE_USB") || die "the backup drive ($DRIVE_USB) not plugged into this PC"
bus=$(awk '{print $2}' <<<"$line")
devnum=$(awk '{print substr($4,1,3)}' <<<"$line")
node=/dev/bus/usb/$bus/$devnum
if findmnt -rn -S LABEL=BACKUP >/dev/null; then
die "the backup drive is mounted on this PC — unmount it first: udisksctl unmount -b /dev/disk/by-label/BACKUP"
fi
# Raw USB access for just this device node; lasts until unplug/reboot.
if [[ ! -w $node ]]; then
echo "==> granting $USER access to $node (sudo)"
sudo setfacl -m "u:$USER:rw" "$node"
fi
mkdir -p "$VM_DIR"
[[ -f $OVMF_VARS ]] || cp "$OVMF_VARS_TEMPLATE" "$OVMF_VARS"
echo "==> booting $(basename "$ISO") with the backup drive at $node"
echo " press Enter repeatedly as soon as the window opens"
exec qemu-system-x86_64 \
-enable-kvm -machine q35 -cpu host -smp 4 -m 4G -nic none \
-drive if=pflash,format=raw,readonly=on,file="$OVMF_CODE" \
-drive if=pflash,format=raw,file="$OVMF_VARS" \
-cdrom "$ISO" -boot d \
-device qemu-xhci -device usb-host,vendorid=0x${DRIVE_USB%%:*},productid=0x${DRIVE_USB##*:}

213
scripts/gitea-backup Executable file
View File

@ -0,0 +1,213 @@
#!/usr/bin/env bash
# Nightly Gitea backup into a restic repository on the portable HDD (the backup drive).
# Installed as /usr/local/sbin/gitea-backup, run as root by gitea-backup.service.
# Setup and operation: OKF/guides/11-backup-automated.md
#
# gitea-backup init create the restic repository on the backup drive (once)
# gitea-backup run stop Gitea, snapshot gitea-data, start Gitea, prune;
# full check + weekly report mail on CHECK_WEEKDAY
# gitea-backup snapshots list snapshots
# gitea-backup check full restic check (reads every pack)
# gitea-backup restore-test restore latest snapshot to scratch, verify, boot a throwaway Gitea
# gitea-backup test-mail send a test mail to MAILTO
# gitea-backup notify-failure mail the journal of the last failed run (used by OnFailure=)
set -euo pipefail
ENV_FILE=/etc/gitea-backup/env
[[ -r $ENV_FILE ]] || { echo "ERROR: missing $ENV_FILE (run as root?)" >&2; exit 1; }
# shellcheck source=/dev/null
. "$ENV_FILE"
LABEL=${LABEL:-BACKUP}
MOUNT=${MOUNT:-/mnt/backup}
STACK=${STACK:-/home/admin/mithlond}
CHECK_WEEKDAY=${CHECK_WEEKDAY:-7} # ISO weekday (7 = Sunday) for full check + report mail
: "${RESTIC_REPOSITORY:?set in $ENV_FILE}" "${RESTIC_PASSWORD_FILE:?set in $ENV_FILE}" "${MAILTO:?set in $ENV_FILE}"
export RESTIC_REPOSITORY RESTIC_PASSWORD_FILE
export RESTIC_CACHE_DIR=${RESTIC_CACHE_DIR:-/var/cache/restic}
KEEP=(--keep-daily 7 --keep-weekly 4 --keep-monthly 12)
SCRATCH=/var/tmp/gitea-restore-test # on disk: /tmp is a 1.5G tmpfs
TEST_CONTAINER=gitea-restore-test
LOCK=/run/gitea-backup.lock
mounted_by_us=0
gitea_stopped=0
scratch_ours=0
log() { printf '==> %s\n' "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
usage() { sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'; exit 2; }
# Whatever fails: Gitea back up, no throwaway container, no scratch copy of the
# host keys, and the backup drive unmounted (a mounted NTFS volume that loses power comes
# back dirty, and every later run fails until ntfsfix).
cleanup() {
local rc=$?
if (( gitea_stopped )); then
echo "==> restarting gitea (exit path)"
docker start gitea >/dev/null || echo "!! gitea did not start — run: docker start gitea" >&2
fi
docker rm -f "$TEST_CONTAINER" >/dev/null 2>&1 || true
if (( scratch_ours )); then rm -rf "$SCRATCH"; fi
if (( mounted_by_us )); then
cd /
sync
if umount "$MOUNT"; then
echo "==> unmounted $MOUNT"
elif umount -l "$MOUNT"; then # device vanished mid-run: detach the dead mount
echo "!! $MOUNT detached lazily — device was gone" >&2
else
echo "!! umount $MOUNT failed" >&2
fi
fi
exit "$rc"
}
trap cleanup EXIT
need_root() { (( EUID == 0 )) || die "run as root: sudo gitea-backup $*"; }
lock() {
exec 9>"$LOCK"
flock -n 9 || die "another gitea-backup is already running"
}
mount_hdd() {
local dev=/dev/disk/by-label/$LABEL
[[ -e $dev ]] || die "HDD '$LABEL' not attached"
dev=$(readlink -f "$dev")
if findmnt -rn "$MOUNT" >/dev/null; then
[[ $(findmnt -rno SOURCE "$MOUNT") == "$dev" ]] || die "$MOUNT holds something other than $LABEL"
# Same device name but no longer readable = a dead mount left by an
# unplug (the replugged drive can come back under the same name).
if ! stat -t "$MOUNT/." >/dev/null 2>&1 || ! ls "$MOUNT" >/dev/null 2>&1; then
echo "!! $MOUNT is a dead mount — detaching and remounting" >&2
umount -l "$MOUNT"
else
return # mounted by someone else (e.g. scripts/backup.sh) — leave it mounted
fi
fi
mkdir -p "$MOUNT"
if ! mount -t ntfs3 "$dev" "$MOUNT"; then
# Unattended: never repair or force. A human runs ntfsfix (OKF/guides/10 §2).
dmesg | tail -n 20 | grep -q 'volume is dirty' \
&& die "$LABEL is dirty — run by hand: ntfsfix -n /dev/disk/by-label/$LABEL, then ntfsfix -d (OKF/guides/10 §2)"
die "mount $dev failed — see dmesg"
fi
mounted_by_us=1
}
repo_ok() {
restic cat config >/dev/null 2>&1 || die "no restic repo at $RESTIC_REPOSITORY — run: gitea-backup init"
# A run cut off mid-write (the backup drive pulled, power cut) can leave its lock on
# disk, and every later run would fail on it. Safe to clear here: flock
# guarantees no other gitea-backup on this host, and this host is the
# repo's only user. Without --remove-all, unlock drops only locks whose
# process is dead.
restic unlock
}
mail_report() { # subject, body on stdin
{ printf 'To: %s\nSubject: [mithlond] %s\n\n' "$MAILTO" "$1"; cat; } | msmtp "$MAILTO"
}
cmd_init() {
need_root init; lock; mount_hdd
if restic cat config >/dev/null 2>&1; then die "repo already exists at $RESTIC_REPOSITORY"; fi
[[ -s $RESTIC_PASSWORD_FILE ]] || die "empty or missing $RESTIC_PASSWORD_FILE"
mkdir -p "$RESTIC_REPOSITORY"
restic init
}
cmd_run() {
need_root run; lock; mount_hdd; repo_ok
docker inspect gitea >/dev/null 2>&1 || die "no gitea container"
log "stopping gitea (SQLite must not be written mid-snapshot)"
gitea_stopped=1
docker stop gitea >/dev/null
local t0=$SECONDS
# restic stores owners and modes itself, so NTFS losing them does not matter.
restic backup --host mithlond --tag gitea "$STACK/gitea-data"
docker start gitea >/dev/null
gitea_stopped=0
log "gitea down $((SECONDS - t0))s"
log "pruning (${KEEP[*]})"
restic forget --prune --tag gitea "${KEEP[@]}"
if [[ $(date +%u) == "$CHECK_WEEKDAY" ]]; then
log "weekly full check"
restic check --read-data
# Proof of life: no Sunday mail means the timer itself stopped firing.
restic snapshots --compact | mail_report "weekly backup report: OK (check --read-data passed)"
fi
}
cmd_restore_test() {
need_root restore-test; lock; mount_hdd; repo_ok
[[ ! -e $SCRATCH ]] || die "$SCRATCH exists — inspect and remove it first"
mkdir -p "$SCRATCH"
scratch_ours=1
log "restoring latest snapshot to $SCRATCH"
restic restore latest --tag gitea --target "$SCRATCH"
local r=$SCRATCH$STACK/gitea-data
[[ -f $r/gitea/gitea.db && -d $r/git/repositories ]] || die "restore lacks gitea.db or repositories"
[[ $(stat -c '%U:%G %a' "$r/ssh") == "root:root 700" ]] || die "gitea-data/ssh lost root:root 700"
echo "gitea-data/ssh/ root:root 700"
log "SQLite integrity"
local ok
ok=$(sqlite3 -readonly "$r/gitea/gitea.db" 'PRAGMA integrity_check;')
[[ $ok == ok ]] || die "gitea.db integrity_check: $ok"
echo "integrity_check: ok"
sqlite3 -readonly -list -noheader "$r/gitea/gitea.db" \
"select 'users=' || count(*) from user; select 'repos=' || count(*) from repository;"
log "git fsck every repo (inside the gitea image)"
local img
img=$(docker inspect -f '{{.Config.Image}}' gitea)
docker run --rm --user 1000:1000 --entrypoint sh -v "$r/git/repositories:/r:ro" "$img" -c '
cd /r; fail=0
for d in */*.git; do
if out=$(git -c safe.directory="*" --git-dir="$d" fsck --no-progress --no-dangling 2>&1); then
printf "%-36s %s\n" "$d" "${out:-OK}"
else
printf "%-36s FAILED\n%s\n" "$d" "$out"; fail=1
fi
done
exit $fail' || die "git fsck failed on at least one repo"
log "booting a throwaway Gitea on the restore (--network none)"
docker run -d --rm --name "$TEST_CONTAINER" --network none \
-e USER_UID=1000 -e USER_GID=1000 -v "$r:/data" "$img" >/dev/null
local i version=
for i in $(seq 1 30); do
version=$(docker exec "$TEST_CONTAINER" wget -qO- http://127.0.0.1:3000/api/v1/version 2>/dev/null) && break
sleep 2
done
[[ -n $version ]] || { docker logs --tail 20 "$TEST_CONTAINER"; die "restored Gitea did not answer within 60s"; }
echo "restored Gitea answers: $version"
docker exec "$TEST_CONTAINER" su git -c 'gitea admin user list'
docker stop "$TEST_CONTAINER" >/dev/null
log "RESTORE TEST PASSED"
}
cmd_notify_failure() {
# systemd hands OnFailure= units the failed run's invocation ID; scope the
# journal to exactly that run, falling back to the tail when run by hand.
local sel=(-u gitea-backup.service -n 80)
[[ -n ${MONITOR_INVOCATION_ID:-} ]] && sel=(_SYSTEMD_INVOCATION_ID="$MONITOR_INVOCATION_ID")
journalctl "${sel[@]}" --no-pager -o short-iso \
| mail_report "gitea-backup FAILED on $(uname -n) (${MONITOR_SERVICE_RESULT:-manual})"
}
case ${1:-} in
init) cmd_init ;;
run) cmd_run ;;
snapshots) need_root snapshots; lock; mount_hdd; repo_ok; restic snapshots ;;
check) need_root check; lock; mount_hdd; repo_ok; restic check --read-data ;;
restore-test) cmd_restore_test ;;
test-mail) echo "Test from gitea-backup on $(uname -n) at $(date -Is)." | mail_report "gitea-backup test mail" ;;
notify-failure) cmd_notify_failure ;;
*) usage ;;
esac

View File

@ -0,0 +1,6 @@
[Unit]
Description=Mail the journal of a failed gitea-backup run
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/gitea-backup notify-failure

View File

@ -0,0 +1,10 @@
# /etc/gitea-backup/env — root:root 600. Sourced by /usr/local/sbin/gitea-backup.
RESTIC_REPOSITORY=/mnt/backup/mithlond/restic
RESTIC_PASSWORD_FILE=/etc/gitea-backup/restic-password
# Where failure mails and the weekly report go (sent via msmtp, /etc/msmtprc).
MAILTO=you@gmail.com
# Optional overrides (defaults shown):
# LABEL=BACKUP
# MOUNT=/mnt/backup
# STACK=/home/admin/mithlond
# CHECK_WEEKDAY=7

View File

@ -0,0 +1,11 @@
[Unit]
Description=Nightly Gitea backup to the restic repo on the backup drive
Documentation=file:///home/admin/mithlond/OKF/guides/11-backup-automated.md
Requires=docker.service
After=docker.service
OnFailure=gitea-backup-failed.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/gitea-backup run
TimeoutStartSec=2h

View File

@ -0,0 +1,10 @@
[Unit]
Description=Run gitea-backup nightly at 03:30
[Timer]
OnCalendar=*-*-* 03:30:00
# Catch up on boot if the box was off at 03:30.
Persistent=true
[Install]
WantedBy=timers.target

15
systemd/msmtprc.example Normal file
View File

@ -0,0 +1,15 @@
# /etc/msmtprc — root:root 600. Holds the Gmail app password.
defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile /var/log/msmtp.log
account gmail
host smtp.gmail.com
port 587
from you@gmail.com
user you@gmail.com
password REPLACE_WITH_16_CHAR_APP_PASSWORD
account default : gmail