Skip to content
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ Every 6 hours (and 5 minutes after boot) `scripts/disk-health.sh` checks the `/l

Check now: `sudo ./scripts/disk-health.sh`. Disks behind some USB adapters don't report SMART; those checks are then skipped silently.

### "Güvendeyim" board and announcements

**http://box.lan/home/guvendeyim.html** ("I'm safe"): anyone on the network can leave their name, "safe" or "need help", an optional rough location and a short message, and search for others by name. Search ignores Turkish letters, so `ayse` finds `Ayşe`. Entries stay on this box only and are never sent anywhere. Whoever writes an entry gets a 6-digit code to delete it later.

- The page warns users not to write a full address, phone or ID number: everyone on the network can read the board.
- Limits against abuse: 10 entries per device per 10 minutes, wrong delete codes are rate limited. At 20,000 entries the board refuses new ones instead of dropping old ones; the owner can delete entries.
- Each entry is appended to `/var/lib/has-pano/guvendeyim.jsonl` as one line, so a power cut can only lose the entry being written. If unreadable lines are found at start, the file is first copied to `guvendeyim.jsonl.bozuk-<time>`.
- Box owner: `sudo ./scripts/pano.sh kayitlar Ayşe` lists matching entries with their ids, `sudo ./scripts/pano.sh sil <id>` deletes one, `temizle` wipes every entry; `sudo ./scripts/pano.sh kapat` turns the board off (`ac` turns it back on).
- Announcement at the top of the homepage, e.g. where water is handed out: `sudo ./scripts/pano.sh duyuru "Su dağıtımı 14:00'te okul bahçesinde"`; remove it with `sudo ./scripts/pano.sh duyuru-sil`.

### Repo layout

```
Expand All @@ -100,6 +110,9 @@ config/iiab-overrides.yml Internet-in-a-Box settings
config/content.conf list of content to download
www/home/index.html homepage
www/home/acil.html emergency page (Turkish, sourced from AFAD and EPA)
www/home/guvendeyim.html "I'm safe" board page
pano/ board service and nginx config
scripts/pano.sh announcements, delete entries or disable the board
```

### Troubleshooting
Expand Down Expand Up @@ -225,6 +238,16 @@ Pi'nin dahili Wi-Fi kartı sadece hotspot için kullanılıyor. Pi'nin geçici o

Hemen kontrol: `sudo ./scripts/disk-health.sh`. Bazı USB adaptörlerinin arkasındaki diskler SMART bilgisi vermez; o zaman bu kontrol sessizce atlanır.

### Güvendeyim panosu ve duyurular

**http://box.lan/home/guvendeyim.html**: ağa bağlı herkes adını, "güvendeyim" ya da "yardım lazım" durumunu, isteğe bağlı kaba bir konumu ve kısa bir mesajı bırakabilir, başkalarını isimle arayabilir. Arama Türkçe harflere takılmaz, `ayse` yazınca `Ayşe` de bulunur. Kayıtlar yalnızca bu kutuda durur, hiçbir yere gönderilmez. Kaydı yazan kişi, sonra silebilmesi için 6 haneli bir kod alır.

- Sayfa tam adres, telefon ya da kimlik numarası yazılmamasını söyler; panoyu ağa bağlı herkes okuyabilir.
- Kötüye kullanıma karşı: aynı cihazdan 10 dakikada en fazla 10 kayıt, yanlış silme kodu denemeleri sınırlı. 20.000 kayda ulaşınca pano eski kayıtları silmez, yeni kaydı reddeder; kutu sahibi kayıt silebilir.
- Her kayıt `/var/lib/has-pano/guvendeyim.jsonl` dosyasına tek satır olarak eklenir; elektrik kesilirse en fazla o an yazılan kayıt gider. Açılışta okunamayan satır bulunursa dosya önce `guvendeyim.jsonl.bozuk-<zaman>` adıyla yedeklenir.
- Kutu sahibi: `sudo ./scripts/pano.sh kayitlar Ayşe` eşleşen kayıtları numarasıyla listeler, `sudo ./scripts/pano.sh sil <numara>` tek kaydı siler, `temizle` tüm kayıtları siler; `sudo ./scripts/pano.sh kapat` panoyu kapatır (`ac` yeniden açar).
- Ana sayfanın en üstünde duyuru, ör. su dağıtımının yeri: `sudo ./scripts/pano.sh duyuru "Su dağıtımı 14:00'te okul bahçesinde"`; kaldırmak için `sudo ./scripts/pano.sh duyuru-sil`.

### Repo yapısı

```
Expand All @@ -238,6 +261,9 @@ config/iiab-overrides.yml Internet-in-a-Box ayarları
config/content.conf indirilecek içerik listesi
www/home/index.html ana sayfa
www/home/acil.html acil durum sayfası (AFAD ve EPA kaynaklı)
www/home/guvendeyim.html Güvendeyim panosu sayfası
pano/ pano servisi ve nginx ayarı
scripts/pano.sh duyuru, kayıt silme, panoyu kapatma
```

### Sorun giderme
Expand Down
5 changes: 3 additions & 2 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# HAS_PrepperDisk kurulum betiği / installer
# 1. Internet-in-a-Box ayarlarını hazırlar / prepares Internet-in-a-Box settings
# 2. Internet-in-a-Box'ı kurar / installs Internet-in-a-Box
# 3. HAS_PrepperDisk ana sayfasını kurar / installs the HAS_PrepperDisk homepage
# 3. HAS_PrepperDisk ana sayfasını ve Güvendeyim panosunu kurar / installs the homepage and board
#
# Kurulum sırasında Pi yeniden başlarsa bu betiği tekrar çalıştır.
# If the Pi reboots during install, just run this script again.
Expand Down Expand Up @@ -76,9 +76,10 @@ else
fi

# -------------------------------------------------------------- 3. ana sayfa
say "3/3 Ana sayfa / homepage"
say "3/3 Ana sayfa ve Güvendeyim panosu / homepage and board"
"$REPO/scripts/install-homepage.sh"
"$REPO/scripts/install-disk-health.sh"
"$REPO/scripts/install-pano.sh"

IP=$(hostname -I | awk '{print $1}')
say "Bitti / done"
Expand Down
27 changes: 27 additions & 0 deletions pano/has-pano-api.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[Unit]
Description=HAS_PrepperDisk: Güvendeyim panosu / "I'm safe" board
After=network.target

[Service]
Type=simple
DynamicUser=yes
StateDirectory=has-pano
StateDirectoryMode=0700
Environment=PYTHONUNBUFFERED=1
ExecStart=/usr/bin/python3 /opt/has-pano/pano-api.py
Restart=always
RestartSec=5

# Sıkılaştırma / hardening
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
LockPersonality=yes

[Install]
WantedBy=multi-user.target
209 changes: 209 additions & 0 deletions pano/pano-api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
#!/usr/bin/env python3
"""HAS_PrepperDisk Güvendeyim panosu: http://box.lan/pano/

Ağa bağlı herkes "güvendeyim" ya da "yardım lazım" kaydı bırakabilir ve isimle arayabilir.
Kayıtlar yalnızca bu kutuda durur. Kaydı yazan kişi, aldığı silme koduyla kaydını silebilir;
kutunun sahibi tüm kayıtları scripts/pano.sh ile siler.

"I'm safe" board: anyone on the network can leave an "I'm safe" or "need help" entry and search
by name. Entries stay on this box only. The writer can delete an entry with the code they get;
the box owner wipes everything with scripts/pano.sh.

GET /pano/kayitlar?q=ayse son kayıtlar ya da arama / latest entries or search
POST /pano/kayitlar {"ad","durum","yer","mesaj"} -> {"id","kod"}
POST /pano/sil {"id","kod"}
"""
import hashlib
import json
import os
import re
import secrets
import shutil
import sys
import threading
import time
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

# Satır başına bir kayıt: yeni kayıt dosyanın sonuna eklenir, elektrik kesilirse en fazla son satır yarım kalır.
# One entry per line: new entries are appended, a power cut can only cut off the last line.
DATA = os.path.join(os.environ.get("STATE_DIRECTORY", "/var/lib/has-pano"), "guvendeyim.jsonl")
PORT = int(os.environ.get("PORT", "8098"))
MAX_ENTRIES = 20000
LIMITS = {"ad": 60, "yer": 80, "mesaj": 280}
DURUMLAR = ("guvende", "yardim")
# Aynı cihazdan 10 dakikada en fazla 10 kayıt / at most 10 entries per device per 10 minutes
RATE_N, RATE_WINDOW = 10, 600

lock = threading.Lock()
added = {}
fails = {}


def load():
entries, bad = [], 0
try:
with open(DATA, encoding="utf-8", errors="replace") as f:
for line in f:
try:
entries.append(json.loads(line))
except ValueError:
bad += 1
except FileNotFoundError:
return []
if bad:
# Dosya yedeklenip okunabilen kayıtlarla yeniden yazılır; yoksa yeni kayıt yarım kalmış satırın arkasına eklenirdi.
# Keep the file aside and rewrite the readable entries, or the next entry would be glued to a cut-off line.
backup = f"{DATA}.bozuk-{datetime.now():%Y%m%d-%H%M%S}"
shutil.copy2(DATA, backup)
save(entries)
print(f"{bad} satır okunamadı, yedek / unreadable lines, backup: {backup}", file=sys.stderr, flush=True)
return entries


def line(e):
return json.dumps(e, ensure_ascii=False) + "\n"


def append(e):
with open(DATA, "a", encoding="utf-8") as f:
f.write(line(e))
f.flush()
os.fsync(f.fileno())


def save(entries):
tmp = DATA + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
f.writelines(line(e) for e in entries)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, DATA)


entries = load()

# "İ"/"I" Türkçede ayrı harfler; aramada "ayse" "Ayşe"yi, "ismail" "İsmail"i bulsun.
# Turkish dotted/dotless i and other letters fold to ASCII so "ayse" finds "Ayşe".
FOLD = str.maketrans("çğıöşüâîû", "cgiosuaiu")


def norm(s):
return " ".join(re.findall(r"\w+", s.replace("İ", "i").replace("I", "ı").lower().translate(FOLD)))


def clean(v, limit):
if not isinstance(v, str):
return ""
return " ".join("".join(c for c in v if c.isprintable()).split())[:limit]


def public(e):
return {k: e[k] for k in ("id", "ad", "durum", "yer", "mesaj", "zaman")}


class Handler(BaseHTTPRequestHandler):
def _send(self, status, payload):
body = json.dumps(payload, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)

def _json(self):
# Yalnızca JSON: başka bir site bu isteği ziyaretçinin tarayıcısından CORS ön kontrolü olmadan atamaz.
# JSON only: another site cannot send this from a visitor's browser without a CORS preflight.
if self.headers.get("Content-Type", "").split(";")[0].strip() != "application/json":
return None
try:
data = json.loads(self.rfile.read(min(int(self.headers.get("Content-Length", 0)), 2048)))
except ValueError:
return None
return data if isinstance(data, dict) else None

def do_GET(self):
url = urlparse(self.path)
if url.path != "/kayitlar":
return self._send(404, {"error": "bulunamadı / not found"})
words = norm(parse_qs(url.query).get("q", [""])[0][:100]).split()
with lock:
# Kelime başından eşleşir: "ali" "Halil"i bulmaz / matches at word starts, "ali" does not find "Halil"
found = [e for e in reversed(entries) if all(" " + w in e["ara"] for w in words)]
self._send(200, {"toplam": len(entries), "bulunan": len(found), "kayitlar": [public(e) for e in found[:100]]})

def do_POST(self):
data = self._json()
if data is None:
return self._send(400, {"error": "Geçersiz istek / bad request"})
if self.path == "/kayitlar":
return self.add(data)
if self.path == "/sil":
return self.delete(data)
self._send(404, {"error": "bulunamadı / not found"})

def add(self, data):
e = {k: clean(data.get(k), n) for k, n in LIMITS.items()}
if not e["ad"] or data.get("durum") not in DURUMLAR:
return self._send(400, {"error": "Ad ve durum gerekli / name and status required"})
kod = f"{secrets.randbelow(10**6):06d}"
with lock:
if len(self.recent(added)) >= RATE_N:
return self._send(429, {"error": "Çok fazla kayıt, biraz bekleyin / too many entries, wait a bit"})
# Dolunca eski kayıtlar silinmez, yeni kayıt reddedilir / when full, new entries are refused instead of dropping old ones
if len(entries) >= MAX_ENTRIES:
return self._send(503, {"error": "Pano dolu, kutu sahibine haber verin / the board is full, tell the box owner"})
added[self.ip()].append(time.time())
e.update(id=secrets.token_hex(6), durum=data["durum"], zaman=datetime.now().astimezone().isoformat(timespec="seconds"),
kod=hashlib.sha256(kod.encode()).hexdigest(), ara=" " + norm(" ".join((e["ad"], e["yer"], e["mesaj"]))))
try:
append(e)
except OSError as err:
return self.write_failed(err)
entries.append(e)
self._send(201, {"id": e["id"], "kod": kod})

def delete(self, data):
i, kod = data.get("id"), data.get("kod")
if not isinstance(i, str) or not isinstance(kod, str):
return self._send(400, {"error": "Geçersiz istek / bad request"})
h = hashlib.sha256(kod.strip().encode()).hexdigest()
with lock:
# Yanlış kod denemeleri sınırlı, 6 haneli kod tek tek denenemez / wrong codes are rate limited
if len(self.recent(fails)) >= RATE_N:
return self._send(429, {"error": "Çok fazla deneme, biraz bekleyin / too many tries, wait a bit"})
match = [e for e in entries if e["id"] == i and secrets.compare_digest(e["kod"], h)]
if not match:
fails[self.ip()].append(time.time())
return self._send(403, {"error": "Kod yanlış / wrong code"})
try:
save([e for e in entries if e is not match[0]])
except OSError as err:
return self.write_failed(err)
entries.remove(match[0])
self._send(200, {"ok": True})

def write_failed(self, err):
# Sayfa bunu "pano kapalı"dan ayırsın, kutu sahibi de günlükte görsün.
# Tell the page this apart from "board closed", and leave it in the journal for the box owner.
print(f"yazılamadı / write failed: {err}", file=sys.stderr, flush=True)
self._send(500, {"error": "Kayıt diske yazılamadı, kutu sahibine haber verin / could not write to disk, tell the box owner"})

def ip(self):
return self.headers.get("X-Real-IP") or self.client_address[0]

def recent(self, book):
"""Bu cihazın son RATE_WINDOW saniyedeki istek zamanları / this device's requests in the window."""
now = time.time()
book[self.ip()] = [t for t in book.get(self.ip(), []) if now - t < RATE_WINDOW]
return book[self.ip()]

def log_message(self, fmt, *args):
# Kayıt içerikleri ve IP günlüğe yazılmaz / entries and IPs are not logged
pass


if __name__ == "__main__":
ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
9 changes: 9 additions & 0 deletions pano/pano-nginx.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# HAS_PrepperDisk Güvendeyim panosu: http://box.lan/pano/ -> 127.0.0.1:8098
# Internet-in-a-Box bu klasördeki dosyaları server bloğunun içine ekler.
# Internet-in-a-Box includes files from /etc/nginx/conf.d inside its server block.
location ^~ /pano/ {
proxy_set_header X-Real-IP $remote_addr;
client_max_body_size 4k;
proxy_read_timeout 10s;
proxy_pass http://127.0.0.1:8098/;
}
2 changes: 1 addition & 1 deletion scripts/install-homepage.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ DST=/library/www/html/home
if [ -f "$DST/index.html" ] && [ ! -f "$DST/index.html.iiab-original" ]; then
cp "$DST/index.html" "$DST/index.html.iiab-original"
fi
cp "$SRC/index.html" "$SRC/acil.html" "$DST/"
cp "$SRC"/*.html "$DST/"
echo "Ana sayfa kuruldu / homepage installed: http://box.lan/home"
echo "Geri almak için / to restore: sudo cp $DST/index.html.iiab-original $DST/index.html"
36 changes: 36 additions & 0 deletions scripts/install-pano.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Güvendeyim panosunu ve duyuru alanını kurar. Tekrar çalıştırmak güvenlidir.
# Installs the "I'm safe" board and the homepage announcement. Safe to re-run.
#
# Kullanım / usage: sudo ./scripts/install-pano.sh
set -euo pipefail

REPO="$(cd "$(dirname "$0")/.." && pwd)"
SRC="$REPO/pano"
NGINX_CONF=/etc/nginx/conf.d/has-pano-nginx.conf

die(){ echo "HATA / ERROR: $*" >&2; exit 1; }
[ "$EUID" -eq 0 ] || die "sudo ile çalıştır / run with sudo: sudo ./scripts/install-pano.sh"
[ -d /etc/nginx/conf.d ] || die "nginx bulunamadı. Önce / install first: sudo ./install.sh"

install -d -m 755 /opt/has-pano
install -m 644 "$SRC/pano-api.py" /opt/has-pano/
install -m 644 "$SRC/has-pano-api.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable has-pano-api.service >/dev/null
systemctl restart has-pano-api.service

install -m 644 "$SRC/pano-nginx.conf" "$NGINX_CONF"
if nginx -t 2>/dev/null; then
systemctl reload nginx
else
rm -f "$NGINX_CONF"
nginx -t || true
die "nginx ayarı hatalı, geri alındı / nginx config failed and was removed"
fi

cat <<EOF
Güvendeyim panosu kuruldu / board installed: http://box.lan/home/guvendeyim.html
Duyuru / announcement: sudo ./scripts/pano.sh duyuru "metin"
Tüm kayıtları sil / wipe: sudo ./scripts/pano.sh temizle
EOF
Loading
Loading