diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..a76590a
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,5 @@
+*
+!backend
+!backend/**
+backend/**/__pycache__
+backend/**/*.sqlite3*
diff --git a/.github/workflows/backend-check.yml b/.github/workflows/backend-check.yml
new file mode 100644
index 0000000..54b38e1
--- /dev/null
+++ b/.github/workflows/backend-check.yml
@@ -0,0 +1,15 @@
+name: Backend checks
+on:
+ push:
+ paths: ['backend/**', '.github/workflows/backend-check.yml']
+ pull_request:
+ paths: ['backend/**', '.github/workflows/backend-check.yml']
+jobs:
+ backend:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.10'
+ - run: python -m unittest discover -s backend/tests -v
diff --git a/.github/workflows/deployment-check.yml b/.github/workflows/deployment-check.yml
new file mode 100644
index 0000000..5148245
--- /dev/null
+++ b/.github/workflows/deployment-check.yml
@@ -0,0 +1,22 @@
+name: Deployment checks
+on:
+ push:
+ branches: [fix/backend-reliability, feature/web-app]
+ pull_request:
+jobs:
+ containers:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: docker build -t taskhub:test .
+ - run: TASKHUB_DOMAIN=example.com docker compose config --quiet
+ - run: docker run --rm -e TASKHUB_DOMAIN=example.com -v "$PWD/deploy/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2-alpine caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
+ - run: docker run --rm taskhub:test python -m unittest discover -s backend/tests -v
+ - run: TASKHUB_DOMAIN=example.com docker compose up -d --build --wait --wait-timeout 180 api backup
+ - run: docker compose --env-file /dev/null ps
+ env:
+ TASKHUB_DOMAIN: example.com
+ - if: always()
+ run: TASKHUB_DOMAIN=example.com docker compose logs --no-color
+ - if: always()
+ run: TASKHUB_DOMAIN=example.com docker compose down -v
diff --git a/.github/workflows/flutter-check.yml b/.github/workflows/flutter-check.yml
index d2de95e..5ba52d1 100644
--- a/.github/workflows/flutter-check.yml
+++ b/.github/workflows/flutter-check.yml
@@ -1,7 +1,8 @@
name: Flutter checks
on:
push:
- branches: [feature/group-planners, feature/web-app]
+ branches: [feature/group-planners, feature/web-app, fix/backend-reliability]
+ pull_request:
workflow_dispatch:
jobs:
flutter:
@@ -11,6 +12,7 @@ jobs:
- uses: subosito/flutter-action@v2
with:
channel: stable
+ flutter-version: '3.47.8'
cache: true
- run: flutter pub get
- run: flutter analyze
diff --git a/.gitignore b/.gitignore
index 79f7eca..7837c58 100644
--- a/.gitignore
+++ b/.gitignore
@@ -46,3 +46,11 @@ app.*.map.json
# Widget Preview related
.widget_preview/
+
+# Deployment secrets and local snapshots
+.env
+android/key.properties
+*.jks
+*.keystore
+/backups/
+/data/
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..8b5ee67
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,9 @@
+FROM python:3.12-slim
+RUN useradd --uid 10001 --create-home taskhub && mkdir /data /backups && chown taskhub /data /backups
+WORKDIR /app
+COPY backend /app/backend
+USER taskhub
+ENV TASKHUB_HOST=0.0.0.0 TASKHUB_DB=/data/taskhub.sqlite3 PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
+EXPOSE 8000
+HEALTHCHECK --interval=30s --timeout=5s CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"
+CMD ["python", "-m", "backend.app"]
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
index 4d96bca..4c0128d 100644
--- a/android/app/build.gradle.kts
+++ b/android/app/build.gradle.kts
@@ -1,9 +1,17 @@
+import java.util.Properties
+
plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
+val releaseProperties = Properties()
+val releasePropertiesFile = rootProject.file("key.properties")
+if (releasePropertiesFile.exists()) {
+ releasePropertiesFile.inputStream().use { releaseProperties.load(it) }
+}
+
android {
namespace = "com.example.taskhub"
compileSdk = flutter.compileSdkVersion
@@ -30,11 +38,23 @@ android {
versionName = flutter.versionName
}
+ signingConfigs {
+ if (releasePropertiesFile.exists()) {
+ create("production") {
+ keyAlias = releaseProperties.getProperty("keyAlias")
+ keyPassword = releaseProperties.getProperty("keyPassword")
+ storeFile = file(releaseProperties.getProperty("storeFile"))
+ storePassword = releaseProperties.getProperty("storePassword")
+ }
+ }
+ }
+
buildTypes {
release {
- // TODO: Add your own signing config for the release build.
- // Signing with the debug keys for now, so `flutter run --release` works.
- signingConfig = signingConfigs.getByName("debug")
+ if (releasePropertiesFile.exists()) {
+ signingConfig = signingConfigs.getByName("production")
+ }
+ // Without a production keystore the output is unsigned, never debug-signed.
}
}
}
diff --git a/backend/README.md b/backend/README.md
index d808667..df373d0 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -53,7 +53,9 @@ Keep it in device secure storage; don't put it in the source code or a URL.
A state GET returns `{"revision":0,"lessons":[],"deadlines":[]}` for a new
account. PUT the same shape with the user's lesson and deadline JSON arrays.
The server validates required fields and limits each array to 1000 objects and
-the full request to 512 KiB. A successful PUT returns the incremented revision.
+the full request to 512 KiB. Lessons require a valid weekday and 24-hour
+`HH:MM` times with start before end; deadlines require a valid ISO date/time
+containing `T`. Titles and subjects cannot be blank. A successful PUT returns the incremented revision.
If another device already wrote a new revision, PUT returns HTTP 409
`revision_conflict`; GET the new state and ask the user how to reconcile it.
A 401 means the token is absent, invalid or expired.
@@ -72,6 +74,27 @@ Group deadlines are shared, but completion is personal: PUT
completion value; another member's checkbox is unaffected. Group owners cannot
leave their own group. Removing a deadline clears its completion records.
-The Flutter Groups tab uses these endpoints. The original personal Schedule and
-Deadlines tabs still keep their data in SharedPreferences; personal cloud sync
-is not wired up yet.
+Flutter uses these endpoints for groups and personal cloud planners. Guest data
+is separate; use Import guest planner after signing in to copy it explicitly.
+Pending edits are stored per account. Revision conflicts require an explicit
+choice and retain the discarded version locally for recovery.
+
+
+## Reliability and hosting boundaries
+
+API responses are sent after the SQLite transaction commits. A database failure
+returns an error instead of acknowledging an uncommitted change. Backend checks
+run on pull requests and pushes affecting backend code.
+
+Keep `TASKHUB_DB` outside `TASKHUB_WEB_DIR`. The static server rejects hidden
+paths, traversal outside the web root and extensions outside its asset allowlist,
+including SQLite and Python files. The web directory must contain only public
+build assets; JSON files there are public too.
+
+Deploy the bounded API behind Caddy using compose.yaml. See deploy/README.md
+and deploy/RELEASE_CHECKLIST.md for infrastructure setup and release acceptance.
+Schema version 2 adds hashed one-use recovery codes. POST account/password,
+account/recovery-code and account/delete under /api/v1 require the current
+password. POST /api/v1/auth/recover accepts email, recoveryCode and newPassword;
+it consumes the code and revokes all sessions. Account deletion removes owned
+groups as well as the personal planner.
diff --git a/backend/accounts.py b/backend/accounts.py
new file mode 100644
index 0000000..8f5e90b
--- /dev/null
+++ b/backend/accounts.py
@@ -0,0 +1,56 @@
+"""Account lifecycle endpoints; callers provide an authenticated transaction."""
+import hashlib
+import hmac
+import secrets
+
+
+def password_hash(password, salt):
+ return hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
+
+
+def valid_password(password):
+ return isinstance(password, str) and 12 <= len(password) <= 1024
+
+
+def manage(db, user_id, action, data):
+ password = data.get('password')
+ if not valid_password(password):
+ return 400, {'error': 'invalid_password'}
+ db.execute('BEGIN IMMEDIATE')
+ row = db.execute('SELECT * FROM users WHERE id=?', (user_id,)).fetchone()
+ if not hmac.compare_digest(password_hash(password, row['salt']), row['password_hash']):
+ return 401, {'error': 'invalid_credentials'}
+ if action == 'recovery-code':
+ code = secrets.token_hex(24)
+ db.execute('INSERT INTO recovery_codes(user_id,code_hash) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET code_hash=excluded.code_hash',
+ (user_id, hashlib.sha256(code.encode()).digest()))
+ return 200, {'recoveryCode': code}
+ if action == 'password':
+ new = data.get('newPassword')
+ if not valid_password(new):
+ return 400, {'error': 'password_length_must_be_12_to_1024'}
+ salt = secrets.token_bytes(16)
+ db.execute('UPDATE users SET salt=?,password_hash=? WHERE id=?', (salt, password_hash(new, salt), user_id))
+ db.execute('DELETE FROM sessions WHERE user_id=?', (user_id,))
+ db.execute('DELETE FROM recovery_codes WHERE user_id=?', (user_id,))
+ return 200, {'ok': True}
+ if action == 'delete':
+ db.execute('DELETE FROM groups WHERE owner_id=?', (user_id,))
+ db.execute('DELETE FROM users WHERE id=?', (user_id,))
+ return 200, {'ok': True}
+ return 404, {'error': 'not_found'}
+
+
+def recover(db, data):
+ email, code, password = data.get('email'), data.get('recoveryCode'), data.get('newPassword')
+ if not isinstance(email, str) or not isinstance(code, str) or len(code) != 48 or not valid_password(password):
+ return 400, {'error': 'invalid_recovery_request'}
+ db.execute('BEGIN IMMEDIATE')
+ row = db.execute('SELECT u.id,r.code_hash FROM users u JOIN recovery_codes r ON r.user_id=u.id WHERE u.email=?', (email.casefold(),)).fetchone()
+ if row is None or not hmac.compare_digest(hashlib.sha256(code.encode()).digest(), row['code_hash']):
+ return 400, {'error': 'invalid_recovery_code'}
+ salt = secrets.token_bytes(16)
+ db.execute('UPDATE users SET salt=?,password_hash=? WHERE id=?', (salt, password_hash(password, salt), row['id']))
+ db.execute('DELETE FROM sessions WHERE user_id=?', (row['id'],))
+ db.execute('DELETE FROM recovery_codes WHERE user_id=?', (row['id'],))
+ return 200, {'ok': True}
diff --git a/backend/app.py b/backend/app.py
index ebb2326..82e12bd 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -10,11 +10,15 @@
import secrets
import sqlite3
import time
+import logging
+import threading
from contextlib import contextmanager
+from datetime import datetime
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit
+from backend.accounts import manage, recover
DB_PATH = Path(os.environ.get("TASKHUB_DB", "taskhub.sqlite3"))
SESSION_LIFETIME = 30 * 24 * 3600
@@ -35,6 +39,8 @@ def valid_items(items, kind):
return False
if not item["id"] or item["id"] in ids or not item["subject"]:
return False
+ if not item["subject"].strip():
+ return False
ids.add(item["id"])
if any(type(item[key]) is not int for key in ("colorValue", "iconCodePoint")):
return False
@@ -42,6 +48,20 @@ def valid_items(items, kind):
return False
if kind == "deadlines" and type(item["completed"]) is not bool:
return False
+ if kind == "lessons":
+ if item["day"] not in ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"):
+ return False
+ if any(not re.fullmatch(r"(?:[01]\d|2[0-3]):[0-5]\d", item[key]) for key in ("start", "end")):
+ return False
+ if item["start"] >= item["end"]:
+ return False
+ else:
+ if not item["title"].strip() or "T" not in item["due"]:
+ return False
+ try:
+ datetime.fromisoformat(item["due"].replace("Z", "+00:00"))
+ except ValueError:
+ return False
return True
@@ -65,7 +85,15 @@ def database(path: Path = DB_PATH):
def initialize(path: Path = DB_PATH):
with database(path) as db:
db.execute("PRAGMA journal_mode=WAL")
+ version = db.execute("PRAGMA user_version").fetchone()[0]
+ if version > 2:
+ raise RuntimeError("Database schema is newer than this application")
db.executescript("""
+ CREATE TABLE IF NOT EXISTS auth_attempts (
+ client TEXT PRIMARY KEY,
+ window_start INTEGER NOT NULL,
+ attempts INTEGER NOT NULL
+ );
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
@@ -106,9 +134,52 @@ def initialize(path: Path = DB_PATH):
PRIMARY KEY(group_id, user_id, deadline_id),
FOREIGN KEY(group_id, user_id) REFERENCES group_members(group_id, user_id) ON DELETE CASCADE
);
+ CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires_at);
+ CREATE TABLE IF NOT EXISTS recovery_codes (
+ user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
+ code_hash BLOB NOT NULL
+ );
+ PRAGMA user_version=2;
""")
+def auth_allowed(path, client):
+ now = int(time.time())
+ with database(path) as db:
+ db.execute("BEGIN IMMEDIATE")
+ db.execute("DELETE FROM auth_attempts WHERE window_start<=?", (now - 900,))
+ db.execute("DELETE FROM sessions WHERE expires_at<=?", (now,))
+ row = db.execute("SELECT attempts FROM auth_attempts WHERE client=?", (client,)).fetchone()
+ if row and row[0] >= 20:
+ return False
+ db.execute("INSERT INTO auth_attempts VALUES(?,?,1) ON CONFLICT(client) DO UPDATE SET attempts=attempts+1", (client, now))
+ return True
+
+
+class BoundedHTTPServer(ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self, *args, **kwargs):
+ self.slots = threading.BoundedSemaphore(32)
+ super().__init__(*args, **kwargs)
+
+ def process_request(self, request, address):
+ if not self.slots.acquire(blocking=False):
+ request.close()
+ return
+ try:
+ super().process_request(request, address)
+ except BaseException:
+ self.slots.release()
+ raise
+
+ def process_request_thread(self, request, address):
+ try:
+ super().process_request_thread(request, address)
+ finally:
+ self.slots.release()
+
+
def make_handler(path: Path = DB_PATH, web_dir: Path | None = None):
allowed_origin = os.environ.get("TASKHUB_CORS_ORIGIN", "")
if web_dir is not None:
@@ -117,12 +188,25 @@ def make_handler(path: Path = DB_PATH, web_dir: Path | None = None):
class Handler(BaseHTTPRequestHandler):
server_version = "TaskHubAPI/1"
+ def setup(self):
+ super().setup()
+ self.connection.settimeout(15)
+
def _send(self, status: int, data: dict):
- body = json.dumps(data, separators=(",", ":")).encode("utf-8")
+ # Emit only after the route's database context has committed.
+ if getattr(self, "_defer_response", False):
+ self._pending_response = (status, data)
+ return
+ self._emit(status, data)
+
+ def _emit(self, status: int, data: dict):
+ body = b"" if status == HTTPStatus.NO_CONTENT else json.dumps(data, separators=(",", ":")).encode("utf-8")
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")
+ if status == 429:
+ self.send_header("Retry-After", "900")
self.send_header("X-Content-Type-Options", "nosniff")
if allowed_origin and self.headers.get("Origin") == allowed_origin:
self.send_header("Access-Control-Allow-Origin", allowed_origin)
@@ -160,7 +244,13 @@ def _web(self, route):
return False
# Flutter uses path URLs for assets. Unknown routes without an
# extension fall back to the app shell for browser navigation.
- candidate = (web_dir / route.lstrip("/")).resolve()
+ relative = Path(route.lstrip("/"))
+ # A misplaced database, configuration or source file is never an asset.
+ extensions = {".html", ".js", ".css", ".json", ".wasm", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".ttf", ".otf", ".woff", ".woff2", ".bin", ".frag"}
+ if any(part.startswith(".") for part in relative.parts) or (relative.suffix and relative.suffix.lower() not in extensions):
+ self._send(404, {"error": "not_found"})
+ return True
+ candidate = (web_dir / relative).resolve()
if not candidate.is_relative_to(web_dir):
self._send(404, {"error": "not_found"})
return True
@@ -197,10 +287,26 @@ def _route(self):
route = urlsplit(self.path).path
method = self.command
if (method, route) == ("GET", "/health"):
+ with database(path) as db:
+ db.execute("SELECT 1 FROM users LIMIT 1").fetchone()
return self._send(200, {"status": "ok"})
if method == "GET" and not route.startswith("/api/") and self._web(route):
return
+ if route == "/api/v1/auth/recover" and method == "POST":
+ client = self.client_address[0]
+ if os.environ.get("TASKHUB_TRUST_PROXY") == "1":
+ client = self.headers.get("X-Real-IP", client)
+ if not auth_allowed(path, client):
+ return self._send(429, {"error": "too_many_attempts"})
+ data = self._body()
+ with database(path) as db:
+ return self._send(*recover(db, data))
if route in ("/api/v1/auth/register", "/api/v1/auth/login") and method == "POST":
+ client = self.client_address[0]
+ if os.environ.get("TASKHUB_TRUST_PROXY") == "1":
+ client = self.headers.get("X-Real-IP", client)
+ if not auth_allowed(path, client):
+ return self._send(429, {"error": "too_many_attempts"})
data = self._body()
email = data.get("email", "")
password = data.get("password", "")
@@ -215,8 +321,11 @@ def _route(self):
password_hash = hashlib.scrypt(password.encode(), salt=salt,
n=2**14, r=8, p=1, dklen=32)
try:
- cursor = db.execute("INSERT INTO users(email,password_hash,salt,created_at) VALUES(?,?,?,?)",
- (email, password_hash, salt, int(time.time())))
+ # Avoid reusing deleted account IDs in device caches. Keep IDs
+ # exactly representable by JavaScript/web clients.
+ user_id = secrets.randbelow(2**52 - 1) + 1
+ cursor = db.execute("INSERT INTO users(id,email,password_hash,salt,created_at) VALUES(?,?,?,?,?)",
+ (user_id, email, password_hash, salt, int(time.time())))
except sqlite3.IntegrityError:
return self._send(409, {"error": "email_taken"})
user_id = cursor.lastrowid
@@ -243,6 +352,14 @@ def _route(self):
if user is None:
return self._send(401, {"error": "unauthorized"})
user_id = user["id"]
+ if method == "POST" and route in ("/api/v1/account/password", "/api/v1/account/delete", "/api/v1/account/recovery-code"):
+ data = self._body()
+ # Reauthentication is rate limited by account, independent of IP.
+ if not auth_allowed(path, "account:" + str(user_id)):
+ return self._send(429, {"error": "too_many_attempts"})
+ return self._send(*manage(db, user_id, route.rsplit("/", 1)[1], data))
+ # Membership, deadline existence and writes share one transaction.
+ db.execute("BEGIN IMMEDIATE" if method in ("POST", "PUT") else "BEGIN")
if (method, route) == ("GET", "/api/v1/auth/me"):
return self._send(200, {"id": user["id"], "email": user["email"]})
if (method, route) == ("POST", "/api/v1/auth/logout"):
@@ -416,12 +533,25 @@ def do_PUT(self):
self._handle()
def _handle(self):
+ self._defer_response = True
+ self._pending_response = None
try:
self._route()
except ValueError as exc:
self._send(400, {"error": "bad_request", "message": str(exc)})
except sqlite3.Error:
+ logging.exception("Database request failed")
self._send(500, {"error": "database_error"})
+ except (TimeoutError, ConnectionError):
+ self.close_connection = True
+ return
+ except Exception:
+ logging.exception("Unhandled request failure")
+ self._send(500, {"error": "internal_error"})
+ finally:
+ self._defer_response = False
+ if self._pending_response is not None:
+ self._emit(*self._pending_response)
return Handler
@@ -431,7 +561,7 @@ def main():
port = int(os.environ.get("TASKHUB_PORT", "8000"))
initialize(DB_PATH)
web_dir = os.environ.get("TASKHUB_WEB_DIR")
- server = ThreadingHTTPServer((host, port), make_handler(DB_PATH, Path(web_dir) if web_dir else None))
+ server = BoundedHTTPServer((host, port), make_handler(DB_PATH, Path(web_dir) if web_dir else None))
print(f"TaskHub API listening on http://{host}:{port}", flush=True)
try:
server.serve_forever()
diff --git a/backend/backup.py b/backend/backup.py
new file mode 100644
index 0000000..6c3652a
--- /dev/null
+++ b/backend/backup.py
@@ -0,0 +1,32 @@
+"""Consistent SQLite snapshot: python -m backend.backup SOURCE DESTINATION."""
+import argparse
+import os
+import sqlite3
+import tempfile
+from pathlib import Path
+
+
+def backup(source, destination):
+ source, destination = Path(source).resolve(), Path(destination).resolve()
+ if source == destination or not source.is_file():
+ raise ValueError('Source must exist and differ from destination')
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ fd, name = tempfile.mkstemp(dir=destination.parent, prefix='.backup-')
+ os.close(fd)
+ try:
+ with sqlite3.connect(source.as_uri() + '?mode=ro', uri=True) as src:
+ with sqlite3.connect(name) as dst:
+ src.backup(dst)
+ if dst.execute('PRAGMA integrity_check').fetchone()[0] != 'ok':
+ raise RuntimeError('Snapshot integrity check failed')
+ os.replace(name, destination)
+ finally:
+ Path(name).unlink(missing_ok=True)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('source')
+ parser.add_argument('destination')
+ args = parser.parse_args()
+ backup(args.source, args.destination)
diff --git a/backend/maintenance.py b/backend/maintenance.py
new file mode 100644
index 0000000..67c3b5f
--- /dev/null
+++ b/backend/maintenance.py
@@ -0,0 +1,31 @@
+"""Periodic backup worker. Mount /backups on durable, separately replicated storage."""
+import logging
+import os
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from backend.backup import backup
+
+
+def run():
+ logging.basicConfig(level=logging.INFO)
+ source = Path(os.environ.get('TASKHUB_DB', '/data/taskhub.sqlite3'))
+ destination = Path(os.environ.get('TASKHUB_BACKUPS', '/backups'))
+ while True:
+ try:
+ filename = datetime.now(timezone.utc).strftime('taskhub-%Y%m%dT%H%M%SZ.sqlite3')
+ backup(source, destination / filename)
+ (destination / 'last-success').write_text(str(int(time.time())))
+ # Retention runs only after a verified new snapshot exists.
+ for old in sorted(destination.glob('taskhub-*.sqlite3'))[:-30]:
+ old.unlink()
+ logging.info('Backup completed: %s', filename)
+ delay = 86400
+ except Exception:
+ logging.exception('Backup failed; retrying in five minutes')
+ delay = 300
+ time.sleep(delay)
+
+
+if __name__ == '__main__':
+ run()
diff --git a/backend/tests/test_accounts.py b/backend/tests/test_accounts.py
new file mode 100644
index 0000000..560d336
--- /dev/null
+++ b/backend/tests/test_accounts.py
@@ -0,0 +1,41 @@
+import unittest
+import test_api
+
+
+class AccountTest(unittest.TestCase):
+ setUp = test_api.ApiTest.setUp
+ tearDown = test_api.ApiTest.tearDown
+ request = test_api.ApiTest.request
+
+ def test_recovery_is_single_use_and_revokes_sessions(self):
+ credentials = {'email': 'recover@example.com', 'password': 'original password 123'}
+ token = self.request('POST', '/api/v1/auth/register', credentials)[1]['token']
+ status, result = self.request('POST', '/api/v1/account/recovery-code', {'password': credentials['password']}, token)
+ self.assertEqual(status, 200)
+ reset = {'email': credentials['email'], 'newPassword': 'replacement password 123', 'recoveryCode': result['recoveryCode']}
+ self.assertEqual(self.request('POST', '/api/v1/auth/recover', reset)[0], 200)
+ self.assertEqual(self.request('GET', '/api/v1/state', token=token)[0], 401)
+ self.assertEqual(self.request('POST', '/api/v1/auth/recover', reset)[0], 400)
+ self.assertEqual(self.request('POST', '/api/v1/auth/login', credentials)[0], 401)
+ credentials['password'] = reset['newPassword']
+ self.assertEqual(self.request('POST', '/api/v1/auth/login', credentials)[0], 200)
+
+ def test_change_and_delete_require_password_and_remove_owned_groups(self):
+ credentials = {'email': 'delete@example.com', 'password': 'original password 123'}
+ token = self.request('POST', '/api/v1/auth/register', credentials)[1]['token']
+ self.assertEqual(self.request('POST', '/api/v1/groups', {'name': 'Owned group'}, token)[0], 201)
+ self.assertEqual(self.request('POST', '/api/v1/account/delete', {'password': 'incorrect password'}, token)[0], 401)
+ self.assertEqual(self.request('POST', '/api/v1/account/password', {'password': credentials['password'], 'newPassword': 'new password 12345'}, token)[0], 200)
+ self.assertEqual(self.request('GET', '/api/v1/state', token=token)[0], 401)
+ credentials['password'] = 'new password 12345'
+ token = self.request('POST', '/api/v1/auth/login', credentials)[1]['token']
+ self.assertEqual(self.request('POST', '/api/v1/account/delete', {'password': credentials['password']}, token)[0], 200)
+ self.assertEqual(self.request('POST', '/api/v1/auth/login', credentials)[0], 401)
+
+ def test_deleted_account_id_is_not_reused(self):
+ credentials = {'email': 'reuse@example.com', 'password': 'original password 123'}
+ first = self.request('POST', '/api/v1/auth/register', credentials)[1]
+ self.assertEqual(self.request('POST', '/api/v1/account/delete', {'password': credentials['password']}, first['token'])[0], 200)
+ second = self.request('POST', '/api/v1/auth/register', credentials)[1]
+ self.assertNotEqual(first['user']['id'], second['user']['id'])
+ self.assertLess(second['user']['id'], 2**53)
diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py
index 729cd3f..0fd62af 100644
--- a/backend/tests/test_api.py
+++ b/backend/tests/test_api.py
@@ -68,10 +68,6 @@ def test_validation_and_login(self):
{'revision': True, 'lessons': [], 'deadlines': []}, a[1]['token'])[0], 400)
-if __name__ == '__main__':
- unittest.main()
-
-
class GroupTest(unittest.TestCase):
setUp = ApiTest.setUp
tearDown = ApiTest.tearDown
@@ -140,6 +136,7 @@ def test_serves_web_assets_and_rejects_missing_files(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
(root / 'index.html').write_text('
TaskHub')
+ (root / '.env').write_text('SECRET=value')
(root / 'main.dart.js').write_text('console.log("app")')
path = root / 'db.sqlite3'
initialize(path)
@@ -150,7 +147,10 @@ def test_serves_web_assets_and_rejects_missing_files(self):
for route, status, marker in [('/', 200, b'TaskHub'),
('/main.dart.js', 200, b'console'),
('/groups/1', 200, b'TaskHub'),
- ('/missing.js', 404, b'not_found')]:
+ ('/missing.js', 404, b'not_found'),
+ ('/db.sqlite3', 404, b'not_found'),
+ ('/.env', 404, b'not_found'),
+ ('/../outside.js', 404, b'not_found')]:
connection = HTTPConnection('127.0.0.1', server.server_port)
connection.request('GET', route)
response = connection.getresponse()
@@ -161,3 +161,52 @@ def test_serves_web_assets_and_rejects_missing_files(self):
server.shutdown()
server.server_close()
thread.join()
+
+
+class ReliabilityTest(unittest.TestCase):
+ setUp = ApiTest.setUp
+ tearDown = ApiTest.tearDown
+ request = ApiTest.request
+
+ def test_failed_commit_does_not_report_success_or_keep_account(self):
+ import sqlite3
+ from contextlib import contextmanager
+ from unittest.mock import patch
+ from backend import app
+ original = app.database
+
+ @contextmanager
+ def failing_database(path):
+ with original(path) as db:
+ yield db
+ # Let the preceding auth-rate transaction commit. Fail only after
+ # registration has inserted the account, before its commit.
+ if db.execute('SELECT COUNT(*) FROM users').fetchone()[0]:
+ raise sqlite3.OperationalError("simulated commit failure")
+
+ credentials = {'email': 'rollback@example.com', 'password': 'long password 123'}
+ with patch.object(app, 'database', failing_database):
+ self.assertEqual(self.request('POST', '/api/v1/auth/register', credentials),
+ (500, {'error': 'database_error'}))
+ self.assertEqual(self.request('POST', '/api/v1/auth/login', credentials)[0], 401)
+ self.assertEqual(self.request('POST', '/api/v1/auth/register', credentials)[0], 201)
+
+ def test_invalid_planner_never_replaces_saved_state(self):
+ token = self.request('POST', '/api/v1/auth/register',
+ {'email': 'validate@example.com', 'password': 'long password 123'})[1]['token']
+ lesson = {'id': 'one', 'day': 'Monday', 'subject': 'Math', 'room': '201',
+ 'start': '09:00', 'end': '10:00', 'colorValue': 123, 'iconCodePoint': 456}
+ for change in ({'day': 'Someday'}, {'start': '25:00'}, {'end': '08:00'},
+ {'subject': ' '}, {'start': '9:00'}):
+ state = {'revision': 0, 'lessons': [dict(lesson, **change)], 'deadlines': []}
+ self.assertEqual(self.request('PUT', '/api/v1/state', state, token)[0], 400)
+ deadline = {'id': 'task', 'subject': 'Math', 'title': 'Quiz', 'due': '2026-02-30T12:00:00',
+ 'completed': False, 'colorValue': 123, 'iconCodePoint': 456}
+ self.assertEqual(self.request('PUT', '/api/v1/state',
+ {'revision': 0, 'lessons': [], 'deadlines': [deadline]}, token)[0], 400)
+ self.assertEqual(self.request('GET', '/api/v1/state', token=token)[1],
+ {'revision': 0, 'lessons': [], 'deadlines': []})
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/backend/tests/test_operations.py b/backend/tests/test_operations.py
new file mode 100644
index 0000000..430c40e
--- /dev/null
+++ b/backend/tests/test_operations.py
@@ -0,0 +1,48 @@
+import sqlite3
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+from backend.app import initialize, auth_allowed
+from backend.backup import backup
+
+
+class OperationsTest(unittest.TestCase):
+ def test_migration_is_repeatable_and_backup_restores_data(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root) / 'source.sqlite3'
+ initialize(path)
+ with sqlite3.connect(path) as db:
+ db.execute("INSERT INTO users VALUES(1,'user@example.com',X'00',X'00',0)")
+ db.execute('PRAGMA user_version=0')
+ initialize(path)
+ initialize(path)
+ target = Path(root) / 'backup.sqlite3'
+ backup(path, target)
+ with sqlite3.connect(target) as db:
+ self.assertEqual(db.execute('PRAGMA integrity_check').fetchone()[0], 'ok')
+ self.assertEqual(db.execute('PRAGMA user_version').fetchone()[0], 2)
+ self.assertEqual(db.execute('SELECT email FROM users').fetchone()[0], 'user@example.com')
+ with self.assertRaises(ValueError):
+ backup(path, path)
+
+ def test_rate_limit_persists_and_expires(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root) / 'db.sqlite3'
+ initialize(path)
+ with patch('backend.app.time.time', return_value=1000):
+ for _ in range(20):
+ self.assertTrue(auth_allowed(path, 'client'))
+ initialize(path)
+ self.assertFalse(auth_allowed(path, 'client'))
+ self.assertTrue(auth_allowed(path, 'other'))
+ with patch('backend.app.time.time', return_value=1900):
+ self.assertTrue(auth_allowed(path, 'client'))
+
+ def test_future_schema_is_rejected(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root) / 'db.sqlite3'
+ with sqlite3.connect(path) as db:
+ db.execute('PRAGMA user_version=3')
+ with self.assertRaises(RuntimeError):
+ initialize(path)
diff --git a/compose.yaml b/compose.yaml
new file mode 100644
index 0000000..5c7ae1c
--- /dev/null
+++ b/compose.yaml
@@ -0,0 +1,55 @@
+services:
+ api:
+ build: .
+ restart: unless-stopped
+ environment:
+ TASKHUB_TRUST_PROXY: '1'
+ volumes:
+ - taskhub_data:/data
+ read_only: true
+ tmpfs: [/tmp]
+ cap_drop: [ALL]
+ security_opt: [no-new-privileges:true]
+ mem_limit: 512m
+ pids_limit: 100
+ backup:
+ build: .
+ restart: unless-stopped
+ command: [python, -m, backend.maintenance]
+ environment:
+ TASKHUB_DB: /data/taskhub.sqlite3
+ volumes:
+ # SQLite read-only connections still need writable WAL shared-memory files.
+ # backup.py opens the database with mode=ro to prohibit database writes.
+ - taskhub_data:/data
+ - taskhub_backups:/backups
+ read_only: true
+ tmpfs: [/tmp]
+ cap_drop: [ALL]
+ security_opt: [no-new-privileges:true]
+ healthcheck:
+ test: [CMD, python, -c, "import time,pathlib; assert time.time()-int(pathlib.Path('/backups/last-success').read_text()) < 90000"]
+ interval: 60s
+ start_period: 300s
+ depends_on:
+ api:
+ condition: service_healthy
+ web:
+ image: caddy:2-alpine
+ restart: unless-stopped
+ ports: ['80:80', '443:443']
+ environment:
+ TASKHUB_DOMAIN: ${TASKHUB_DOMAIN:?Set TASKHUB_DOMAIN}
+ volumes:
+ - ./deploy/Caddyfile:/etc/caddy/Caddyfile:ro
+ - ./build/web:/srv:ro
+ - caddy_data:/data
+ - caddy_config:/config
+ depends_on:
+ api:
+ condition: service_healthy
+volumes:
+ taskhub_data:
+ taskhub_backups:
+ caddy_data:
+ caddy_config:
diff --git a/deploy/Caddyfile b/deploy/Caddyfile
new file mode 100644
index 0000000..694a073
--- /dev/null
+++ b/deploy/Caddyfile
@@ -0,0 +1,22 @@
+{$TASKHUB_DOMAIN} {
+ encode zstd gzip
+ header {
+ X-Content-Type-Options nosniff
+ Referrer-Policy strict-origin-when-cross-origin
+ Strict-Transport-Security "max-age=31536000"
+ }
+ @api path /api/* /health
+ handle @api {
+ request_body {
+ max_size 512KB
+ }
+ reverse_proxy api:8000 {
+ header_up X-Real-IP {remote_host}
+ }
+ }
+ handle {
+ root * /srv
+ try_files {path} /index.html
+ file_server
+ }
+}
diff --git a/deploy/README.md b/deploy/README.md
new file mode 100644
index 0000000..0efba01
--- /dev/null
+++ b/deploy/README.md
@@ -0,0 +1,78 @@
+# Deployment runbook
+
+Prerequisites: Linux host with Docker Compose, DNS A/AAAA records pointing to it,
+ports 80/443 open, and a Flutter SDK on the build machine. Do not expose port
+8000. Caddy terminates HTTPS and overwrites X-Real-IP; trust-proxy mode is safe
+only with this private API network.
+
+Build and start from the repository root:
+
+```sh
+flutter pub get
+flutter analyze
+flutter test
+flutter build web --release
+export TASKHUB_DOMAIN=taskhub.example.com
+docker compose config
+docker compose up -d --build
+curl --fail "https://$TASKHUB_DOMAIN/health"
+```
+
+Replace the example domain with your domain. Web requests use the same origin.
+For Android release builds use `--dart-define=TASKHUB_API_URL=https://YOUR_DOMAIN`.
+
+## Backup and restore
+
+Run daily on the host (e.g. a systemd timer or cron), and before each upgrade:
+
+```sh
+docker compose exec -T api python -m backend.backup /data/taskhub.sqlite3 /data/snapshot.sqlite3
+mkdir -p backups
+chmod 700 backups
+docker compose cp api:/data/snapshot.sqlite3 backups/snapshot.sqlite3
+chmod 600 backups/snapshot.sqlite3
+```
+
+Copy snapshots to encrypted off-host storage with dated names. The command creates
+one consistent SQLite snapshot using the backup API, including committed WAL data.
+It does not configure off-host credentials or retention automatically.
+
+Restore into a new volume/deployment first and verify login, groups and planner
+state. Stop API writes before replacing the live DB; retain the previous volume
+for rollback. Never overwrite a running database or reuse stale WAL/SHM files.
+
+## Verification and limitations
+
+Run `python -m unittest discover -s backend/tests -v`. Deployment must also pass
+Docker build, HTTPS, real-device login, persistence across restart, and restore
+checks on the target host. No target host is configured by this repository.
+
+Auth endpoints allow 20 attempts per IP per 15 minutes, persisted in SQLite.
+Shared campus IPs share the allowance. Monitor 429 responses before rollout.
+Sessions expire after 30 days; expired sessions are pruned during auth attempts.
+Schema version 2 upgrades existing databases idempotently; newer schemas are
+rejected to avoid accidental downgrade writes.
+
+Compose runs a daily backup worker and exposes its backup freshness as container
+health. Configure replication of the taskhub_backups volume to off-host storage.
+Use deploy/check-health.sh on an independent monitor with TASKHUB_URL and optional
+TASKHUB_ALERT_WEBHOOK. These infrastructure destinations are deployment settings.
+
+See RELEASE_CHECKLIST.md for remaining verification on the actual target host.
+
+## Android release signing
+
+Android CI builds a debug APK to validate compilation. A distributable release
+requires your retained signing key. Keep `android/key.properties` outside git:
+
+```properties
+storeFile=/absolute/path/to/taskhub-release.jks
+storePassword=YOUR_SECRET
+keyAlias=YOUR_ALIAS
+keyPassword=YOUR_SECRET
+```
+
+Then build with `flutter build appbundle --release
+--dart-define=TASKHUB_API_URL=https://YOUR_DOMAIN` on one line. Without the file,
+release output is unsigned. Never distribute an APK signed with a debug key.
+Retain the existing application ID to preserve upgrades for existing installs.
diff --git a/deploy/RELEASE_CHECKLIST.md b/deploy/RELEASE_CHECKLIST.md
new file mode 100644
index 0000000..ce512f3
--- /dev/null
+++ b/deploy/RELEASE_CHECKLIST.md
@@ -0,0 +1,30 @@
+# Release acceptance
+
+Implemented: account-scoped personal planner cache and cloud sync, explicit
+revision conflicts, guest import, secure session storage, password change,
+single-use recovery codes, password-confirmed account deletion, API limits,
+versioned database initialization, HTTPS proxy configuration, daily consistent
+backups and independent HTTP health-check script.
+
+Recovery is by an explicitly generated recovery code, not email. Users must save
+the code before losing access. Email addresses are account identifiers and are
+not verified. Do not advertise email-based recovery.
+
+The owner must provide infrastructure configuration for deployment: domain/DNS,
+server access, off-host backup destination and alert webhook. These values must
+not be committed. Backup snapshots currently remain in the Docker backup volume;
+replicate that volume to separately managed storage and define retention.
+
+Before marking a release ready:
+- Python API tests, Flutter analyze/tests and web build pass.
+- Container image builds and Caddy config validates.
+- Test HTTPS registration, login, planner changes on two devices and conflicts.
+- Confirm pending edits survive app restart and an offline period.
+- Confirm guest data stays separate from every account.
+- Exercise recovery, password change and deletion on test accounts.
+- Restore a snapshot into a separate deployment and check its data.
+- Configure external monitoring and test an alert.
+- Check API limits under expected campus traffic and tune before public launch.
+
+Do not infer production verification from passing unit tests. Record deployment
+and two-device acceptance results for the actual release host.
diff --git a/deploy/check-health.sh b/deploy/check-health.sh
new file mode 100644
index 0000000..396dc13
--- /dev/null
+++ b/deploy/check-health.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+set -eu
+# Run on an independent monitoring host every minute.
+: "${TASKHUB_URL:?Set the public HTTPS URL}"
+if ! curl --fail --silent --show-error --max-time 10 "$TASKHUB_URL/health" >/dev/null; then
+ printf '%s\n' 'TaskHub health check failed' >&2
+ if [ -n "${TASKHUB_ALERT_WEBHOOK:-}" ]; then
+ curl --fail --silent --show-error --max-time 10 -H 'Content-Type: application/json' \
+ --data '{"text":"TaskHub health check failed"}' "$TASKHUB_ALERT_WEBHOOK"
+ fi
+ exit 1
+fi
diff --git a/lib/account_actions.dart b/lib/account_actions.dart
new file mode 100644
index 0000000..dec4ef2
--- /dev/null
+++ b/lib/account_actions.dart
@@ -0,0 +1,114 @@
+import 'package:flutter/material.dart';
+
+import 'taskhub_api.dart';
+
+Future accountAction(BuildContext context, String action) async {
+ final password = TextEditingController();
+ final replacement = TextEditingController();
+ final email = TextEditingController();
+ final code = TextEditingController();
+ final recovery = action == 'recover';
+ final accepted = await showDialog(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: Text(switch (action) {
+ 'delete' => 'Delete account and owned groups?',
+ 'password' => 'Change password',
+ 'recover' => 'Recover account',
+ _ => 'Create a recovery code',
+ }),
+ content: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (action == 'delete')
+ const Text(
+ 'This permanently deletes your account, personal planner and groups you own.',
+ ),
+ if (action == 'recovery-code')
+ const Text(
+ 'Keep the code somewhere safe. It replaces any previous code and can reset your password once.',
+ ),
+ if (recovery) ...[
+ TextField(
+ controller: email,
+ decoration: const InputDecoration(labelText: 'Email'),
+ ),
+ TextField(
+ controller: code,
+ decoration: const InputDecoration(labelText: 'Recovery code'),
+ ),
+ ] else
+ TextField(
+ controller: password,
+ obscureText: true,
+ decoration: const InputDecoration(
+ labelText: 'Current password',
+ ),
+ ),
+ if (recovery || action == 'password')
+ TextField(
+ controller: replacement,
+ obscureText: true,
+ decoration: const InputDecoration(
+ labelText: 'New password (12+ characters)',
+ ),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Continue'),
+ ),
+ ],
+ ),
+ );
+ try {
+ if (accepted != true) return;
+ final result = await TaskHubApi.shared.call(
+ 'POST',
+ recovery ? '/api/v1/auth/recover' : '/api/v1/account/$action',
+ {
+ 'password': password.text,
+ 'newPassword': replacement.text,
+ 'email': email.text.trim(),
+ 'recoveryCode': code.text.trim(),
+ },
+ );
+ if (action == 'delete' || action == 'password') {
+ await TaskHubApi.shared.clearSession(deleted: action == 'delete');
+ }
+ if (!context.mounted) return;
+ await showDialog(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: const Text('Done'),
+ content: SelectableText(
+ result['recoveryCode'] as String? ??
+ (recovery || action == 'password'
+ ? 'Sign in with your new password.'
+ : 'Account deleted.'),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ ),
+ );
+ } finally {
+ // Dialog closing animation may still use its text controllers.
+ await Future.delayed(const Duration(milliseconds: 300));
+ password.dispose();
+ replacement.dispose();
+ email.dispose();
+ code.dispose();
+ }
+}
diff --git a/lib/group_hub.dart b/lib/group_hub.dart
index 2daa5a5..de01d70 100644
--- a/lib/group_hub.dart
+++ b/lib/group_hub.dart
@@ -1,85 +1,9 @@
-import 'dart:convert';
-
-import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
-import 'package:flutter_secure_storage/flutter_secure_storage.dart';
-import 'package:http/http.dart' as http;
-
-import 'main.dart';
-
-const String _configuredApiUrl = String.fromEnvironment('TASKHUB_API_URL');
-
-bool get _pagesDemoWithoutApi =>
- kIsWeb && Uri.base.host.endsWith('.github.io') && _configuredApiUrl.isEmpty;
-
-String get taskHubApiUrl => _configuredApiUrl.isNotEmpty
- ? _configuredApiUrl.replaceFirst(RegExp(r'/$'), '')
- : kIsWeb
- ? Uri.base.origin
- : 'http://10.0.2.2:8000';
-class _ApiError implements Exception {
- const _ApiError(this.message);
- final String message;
- @override
- String toString() => message;
-}
-
-class _GroupApi {
- static const _storage = FlutterSecureStorage();
- String? token;
+import 'taskhub_api.dart';
+import 'account_actions.dart';
- Future restore() async {
- token = await _storage.read(key: 'taskhub_token');
- }
-
- Future