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> call( - String method, - String path, [ - Map? data, - ]) async { - final request = http.Request(method, Uri.parse('$taskHubApiUrl$path')); - request.headers['Content-Type'] = 'application/json'; - if (token != null) request.headers['Authorization'] = 'Bearer $token'; - if (data != null) request.body = jsonEncode(data); - final streamed = await request.send().timeout(const Duration(seconds: 12)); - final body = await http.Response.fromStream(streamed); - final decoded = jsonDecode(body.body) as Map; - if (body.statusCode >= 400) { - if (body.statusCode == 401) { - token = null; - await _storage.delete(key: 'taskhub_token'); - } - throw _ApiError( - '${decoded['error'] ?? 'Request failed'} (${body.statusCode})', - ); - } - return decoded; - } - - Future authenticate( - String email, - String password, - bool register, - ) async { - final result = await call( - 'POST', - '/api/v1/auth/${register ? 'register' : 'login'}', - {'email': email, 'password': password}, - ); - token = result['token'] as String; - await _storage.write(key: 'taskhub_token', value: token); - } - - Future logout() async { - try { - await call('POST', '/api/v1/auth/logout'); - } finally { - token = null; - await _storage.delete(key: 'taskhub_token'); - } - } -} +import 'main.dart'; class GroupHubPage extends StatefulWidget { const GroupHubPage({required this.onDeadlinesChanged, super.key}); @@ -90,7 +14,7 @@ class GroupHubPage extends StatefulWidget { } class _GroupHubPageState extends State { - final _api = _GroupApi(); + final _api = TaskHubApi.shared; final _email = TextEditingController(); final _password = TextEditingController(); final _name = TextEditingController(); @@ -105,7 +29,7 @@ class _GroupHubPageState extends State { @override void initState() { super.initState(); - if (!_pagesDemoWithoutApi) { + if (!pagesDemoWithoutApi) { _restore(); } } @@ -121,7 +45,7 @@ class _GroupHubPageState extends State { Future _restore() async { await _perform(() async { - await _api.restore(); + // The app restores the shared session before constructing this page. if (_api.token != null) await _load(); }); } @@ -258,7 +182,7 @@ class _GroupHubPageState extends State { @override Widget build(BuildContext context) { - if (_pagesDemoWithoutApi) { + if (pagesDemoWithoutApi) { return Column( children: [ const TaskHubHeader(subtitle: 'Shared class groups'), @@ -298,7 +222,13 @@ class _GroupHubPageState extends State { padding: const EdgeInsets.fromLTRB(18, 0, 18, 40), children: [ if (_api.token == null) ...[ - const Text('Sign in to share your group schedule'), + const Text('Sign in to sync your planner and share groups'), + TextButton( + onPressed: _busy + ? null + : () => _perform(() => accountAction(context, 'recover')), + child: const Text('Recover account with code'), + ), TextField( controller: _email, keyboardType: TextInputType.emailAddress, @@ -321,6 +251,7 @@ class _GroupHubPageState extends State { _password.text, _register, ); + if (!mounted) return; _password.clear(); await _load(); }), @@ -335,6 +266,37 @@ class _GroupHubPageState extends State { ), ), ] else ...[ + Wrap( + children: [ + TextButton( + onPressed: _busy + ? null + : () => _perform( + () => accountAction(context, 'password'), + ), + child: const Text('Change password'), + ), + TextButton( + onPressed: _busy + ? null + : () => _perform( + () => accountAction(context, 'recovery-code'), + ), + child: const Text('Recovery code'), + ), + TextButton( + onPressed: _busy + ? null + : () => _perform(() async { + await accountAction(context, 'delete'); + if (_api.token == null) { + widget.onDeadlinesChanged([]); + } + }), + child: const Text('Delete account'), + ), + ], + ), Row( children: [ const Expanded( @@ -355,6 +317,7 @@ class _GroupHubPageState extends State { ? null : () => _perform(() async { await _api.logout(); + if (!mounted) return; widget.onDeadlinesChanged([]); setState(() { _groups = []; diff --git a/lib/main.dart b/lib/main.dart index e6e5602..6ed97a5 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,9 +1,10 @@ -import 'dart:convert'; - import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; + +import 'planner_sync.dart'; +import 'taskhub_api.dart'; + import 'package:webview_flutter/webview_flutter.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -72,6 +73,7 @@ class TaskHubApp extends StatefulWidget { } class _TaskHubAppState extends State { + final _sync = PlannerSync(TaskHubApi.shared); int _tab = 0; bool _loading = true; List _lessons = []; @@ -97,45 +99,43 @@ class _TaskHubAppState extends State { @override void initState() { super.initState(); - _load(); + _sync.addListener(_plannerChanged); + _sync.start(); } - Future _load() async { - final SharedPreferences prefs = await SharedPreferences.getInstance(); - - final List lessonJson = - jsonDecode(prefs.getString('taskhub_lessons') ?? '[]') as List; - final List deadlineJson = jsonDecode( - prefs.getString('taskhub_deadlines') ?? '[]', - ) as List; - + void _plannerChanged() { if (!mounted) return; setState(() { - _lessons = lessonJson - .map((dynamic e) => Lesson.fromJson(e as Map)) + _loading = _sync.loading; + if (_loading) _groupDeadlines = []; + _lessons = (_sync.state['lessons'] as List) + .map((e) => Lesson.fromJson(Map.from(e as Map))) .toList(); - _deadlines = deadlineJson - .map((dynamic e) => DeadlineItem.fromJson(e as Map)) + _deadlines = (_sync.state['deadlines'] as List) + .map( + (e) => DeadlineItem.fromJson(Map.from(e as Map)), + ) .toList(); - _loading = false; }); - await _syncReminders(); + _syncReminders(); + } + + @override + void dispose() { + _sync.removeListener(_plannerChanged); + _sync.dispose(); + super.dispose(); } Future _saveLessons() async { - final SharedPreferences prefs = await SharedPreferences.getInstance(); - await prefs.setString( - 'taskhub_lessons', - jsonEncode(_lessons.map((Lesson e) => e.toJson()).toList()), + await _sync.edit( + _lessons.map((e) => e.toJson()).toList(), + _deadlines.map((e) => e.toJson()).toList(), ); } Future _saveDeadlines() async { - final SharedPreferences prefs = await SharedPreferences.getInstance(); - await prefs.setString( - 'taskhub_deadlines', - jsonEncode(_deadlines.map((DeadlineItem e) => e.toJson()).toList()), - ); + await _saveLessons(); await _syncReminders(); } @@ -235,6 +235,71 @@ class _TaskHubAppState extends State { ), ); return Scaffold( + appBar: AppBar( + title: Text( + TaskHubApi.shared.userId == null + ? 'TaskHub · On this device' + : 'TaskHub · Cloud planner', + ), + bottom: _sync.error == null + ? null + : PreferredSize( + preferredSize: const Size.fromHeight(108), + child: Padding( + padding: const EdgeInsets.all(8), + child: Column( + children: [ + Text(_sync.error!, maxLines: 2), + if (_sync.conflict) + Row( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + TextButton( + onPressed: () async { + try { + await _sync.resolve( + keepLocal: false, + ); + } catch (_) { + /* Retry remains available. */ + } + }, + child: const Text( + 'Use cloud version', + ), + ), + TextButton( + onPressed: () async { + try { + await _sync.resolve( + keepLocal: true, + ); + } catch (_) { + /* Retry remains available. */ + } + }, + child: const Text('Keep this device'), + ), + ], + ), + ], + ), + ), + ), + actions: [ + if (TaskHubApi.shared.userId != null) + TextButton( + onPressed: _sync.importGuest, + child: const Text('Import guest planner'), + ), + IconButton( + onPressed: _sync.sync, + icon: const Icon(Icons.sync), + tooltip: 'Sync planner', + ), + ], + ), body: SafeArea( child: wide ? Row( diff --git a/lib/planner_sync.dart b/lib/planner_sync.dart new file mode 100644 index 0000000..27860e9 --- /dev/null +++ b/lib/planner_sync.dart @@ -0,0 +1,210 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'taskhub_api.dart'; + +/// A pending write is scoped to one account and retains its original revision. +/// Conflicts require an explicit choice; they never silently overwrite data. +class PlannerSync extends ChangeNotifier { + final TaskHubApi api; + PlannerSync(this.api); + Map state = {'revision': 0, 'lessons': [], 'deadlines': []}; + bool loading = true; + bool pending = false; + bool conflict = false; + String? error; + int? _account; + int _generation = 0; + int _edits = 0; + bool _running = false; + bool _disposed = false; + Timer? _timer; + Future _persistence = Future.value(); + String get _key => 'planner_account_$_account'; + + Future start() async { + try { + if (!pagesDemoWithoutApi) await api.restore(); + } catch (_) { + if (api.userId == null) await api.clearSession(); + error = 'Could not restore your session. Sign in when online.'; + } + if (_disposed) return; + api.addListener(_sessionChanged); + await _switchAccount(); + _timer = Timer.periodic(const Duration(seconds: 30), (_) => sync()); + } + + void _sessionChanged() { + final deleted = api.deletedAccount; + if (deleted != null) { + api.deletedAccount = null; + unawaited(_purgeAccount(deleted)); + } + if (_account != api.userId) unawaited(_switchAccount()); + } + + Future _purgeAccount(int id) async { + await _persistence.catchError((Object _) {}); + final prefs = await SharedPreferences.getInstance(); + await prefs.remove('planner_account_$id'); + await prefs.remove('planner_account_${id}_conflict_backup'); + } + + Future _switchAccount() async { + final generation = ++_generation; + _account = api.userId; + loading = true; + pending = false; + conflict = false; + if (!_disposed) notifyListeners(); + final prefs = await SharedPreferences.getInstance(); + if (generation != _generation) return; + final saved = prefs.getString(_key); + try { + if (saved != null) { + final data = jsonDecode(saved) as Map; + state = Map.from(data['state'] as Map); + pending = data['pending'] == true; + } else { + state = { + 'revision': 0, + 'lessons': _account == null + ? jsonDecode(prefs.getString('taskhub_lessons') ?? '[]') + : [], + 'deadlines': _account == null + ? jsonDecode(prefs.getString('taskhub_deadlines') ?? '[]') + : [], + }; + } + } catch (_) { + if (saved != null) { + await prefs.setString('${_key}_unreadable_backup', saved); + } + if (generation != _generation) return; + state = {'revision': 0, 'lessons': [], 'deadlines': []}; + error = 'Saved planner could not be read. Original storage was retained.'; + } + loading = false; + if (!_disposed) notifyListeners(); + await sync(); + } + + Future _save() { + final key = _key; + final value = jsonEncode({'state': state, 'pending': pending}); + _persistence = _persistence.catchError((Object _) {}).then((_) async { + final prefs = await SharedPreferences.getInstance(); + if (!await prefs.setString(key, value)) { + throw StateError('Could not save planner'); + } + }); + return _persistence; + } + + Future edit(List lessons, List deadlines) async { + if (loading) return; + state = {...state, 'lessons': lessons, 'deadlines': deadlines}; + _edits++; + pending = _account != null; + await _save(); + if (!_disposed) notifyListeners(); + await sync(); + } + + Future sync() async { + if (_running || + loading || + conflict || + _account == null || + api.token == null) { + return; + } + _running = true; + final generation = _generation; + final edits = _edits; + try { + if (pending) { + final result = await api.call('PUT', '/api/v1/state', Map.of(state)); + if (generation != _generation) return; + state = {...state, 'revision': result['revision']}; + pending = edits != _edits; + } else { + final result = await api.call('GET', '/api/v1/state'); + if (generation != _generation || edits != _edits) return; + state = result; + } + error = null; + await _save(); + } catch (e) { + if (generation != _generation) return; + conflict = e.toString().contains('revision_conflict'); + error = conflict + ? 'This planner changed on another device. Choose which version to keep.' + : 'Changes are saved on this device. Cloud sync will retry.'; + } finally { + _running = false; + if (!_disposed) notifyListeners(); + } + if (pending && !conflict && error == null) await sync(); + } + + Future importGuest() async { + if (_account == null || loading || conflict) return; + final generation = _generation; + final prefs = await SharedPreferences.getInstance(); + final saved = prefs.getString('planner_account_null'); + final guest = saved == null + ? { + 'lessons': jsonDecode(prefs.getString('taskhub_lessons') ?? '[]'), + 'deadlines': jsonDecode( + prefs.getString('taskhub_deadlines') ?? '[]', + ), + } + : (jsonDecode(saved) as Map)['state'] as Map; + if (generation != _generation) return; + List merge(String key) { + final result = List.from(state[key] as List); + final ids = result.map((e) => (e as Map)['id']).toSet(); + for (final raw in guest[key] as List) { + final item = Map.from(raw as Map); + item['id'] = 'guest_${item['id']}'; + if (ids.add(item['id'])) result.add(item); + } + return result; + } + + await edit(merge('lessons'), merge('deadlines')); + } + + Future resolve({required bool keepLocal}) async { + final generation = _generation; + final remote = await api.call('GET', '/api/v1/state'); + if (generation != _generation) return; + // Retain the discarded version for recovery on this device. + final prefs = await SharedPreferences.getInstance(); + await prefs.setString( + '${_key}_conflict_backup', + jsonEncode(keepLocal ? remote : state), + ); + state = keepLocal ? {...state, 'revision': remote['revision']} : remote; + pending = keepLocal; + conflict = false; + error = null; + await _save(); + if (!_disposed) notifyListeners(); + await sync(); + } + + @override + void dispose() { + _disposed = true; + _generation++; + _timer?.cancel(); + api.removeListener(_sessionChanged); + super.dispose(); + } +} diff --git a/lib/taskhub_api.dart b/lib/taskhub_api.dart new file mode 100644 index 0000000..c95837a --- /dev/null +++ b/lib/taskhub_api.dart @@ -0,0 +1,129 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:http/http.dart' as http; + +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 TaskHubApi extends ChangeNotifier { + static final shared = TaskHubApi(); + int? userId; + int? deletedAccount; + static const _storage = FlutterSecureStorage(); + String? token; + + Future restore() async { + final session = await _storage.read(key: 'taskhub_session'); + if (session != null) { + final saved = jsonDecode(session) as Map; + token = saved['token'] as String; + userId = saved['userId'] as int; + } else { + token = await _storage.read(key: 'taskhub_token'); + if (token != null) { + final me = await call('GET', '/api/v1/auth/me'); + userId = me['id'] as int; + } + } + notifyListeners(); + } + + Future> call( + String method, + String path, [ + Map? data, + ]) async { + if (kReleaseMode && !kIsWeb && !taskHubApiUrl.startsWith('https://')) { + throw const ApiError('This release requires a configured HTTPS server.'); + } + final requestToken = token; + final request = http.Request(method, Uri.parse('$taskHubApiUrl$path')); + request.headers['Content-Type'] = 'application/json'; + if (token != null) request.headers['Authorization'] = 'Bearer $token'; + if (data != null) request.body = jsonEncode(data); + final streamed = await request.send().timeout(const Duration(seconds: 12)); + final body = await http.Response.fromStream(streamed) + .timeout(const Duration(seconds: 12)); + Map decoded; + try { + decoded = jsonDecode(body.body) as Map; + } catch (_) { + throw ApiError( + 'Server returned an invalid response (${body.statusCode})', + ); + } + if (body.statusCode >= 400) { + if (body.statusCode == 401 && + token == requestToken && + decoded['error'] == 'unauthorized') { + token = null; + userId = null; + notifyListeners(); + await _storage.delete(key: 'taskhub_token'); + await _storage.delete(key: 'taskhub_session'); + } + throw ApiError( + '${decoded['error'] ?? 'Request failed'} (${body.statusCode})', + ); + } + return decoded; + } + + Future authenticate( + String email, + String password, + bool register, + ) async { + final result = await call( + 'POST', + '/api/v1/auth/${register ? 'register' : 'login'}', + {'email': email, 'password': password}, + ); + token = result['token'] as String; + userId = (result['user'] as Map)['id'] as int; + await _storage.write( + key: 'taskhub_session', + value: jsonEncode({'token': token, 'userId': userId}), + ); + await _storage.delete(key: 'taskhub_token'); + notifyListeners(); + } + + Future clearSession({bool deleted = false}) async { + if (deleted) deletedAccount = userId; + token = null; + userId = null; + await _storage.delete(key: 'taskhub_token'); + await _storage.delete(key: 'taskhub_session'); + notifyListeners(); + } + + Future logout() async { + try { + await call('POST', '/api/v1/auth/logout'); + } finally { + token = null; + userId = null; + notifyListeners(); + await _storage.delete(key: 'taskhub_token'); + await _storage.delete(key: 'taskhub_session'); + } + } +} diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index e71a16d..5da87d9 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,6 +6,18 @@ #include "generated_plugin_registrant.h" +#include +#include +#include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); + g_autoptr(FlPluginRegistrar) flutter_timezone_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterTimezonePlugin"); + flutter_timezone_plugin_register_with_registrar(flutter_timezone_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); } diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 2e1de87..a1f0055 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,9 +3,13 @@ # list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_linux + flutter_timezone + url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 9bf5e53..1358f7e 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,10 +5,18 @@ import FlutterMacOS import Foundation +import flutter_local_notifications +import flutter_secure_storage_macos +import flutter_timezone import shared_preferences_foundation +import url_launcher_macos import webview_flutter_wkwebview func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) + FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin")) + FlutterTimezonePlugin.register(with: registry.registrar(forPlugin: "FlutterTimezonePlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin")) } diff --git a/pubspec.lock b/pubspec.lock index 65af698..65149ac 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1,6 +1,14 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" async: dependency: transitive description: @@ -33,6 +41,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.3" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + url: "https://pub.dev" + source: hosted + version: "1.2.1" collection: dependency: transitive description: @@ -41,6 +57,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + crypto: + dependency: transitive + description: + name: crypto + sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 + url: "https://pub.dev" + source: hosted + version: "3.0.8" cupertino_icons: dependency: "direct main" description: @@ -49,6 +73,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.9" + dbus: + dependency: transitive + description: + name: dbus + sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383 + url: "https://pub.dev" + source: hosted + version: "0.7.15" + equatable: + dependency: transitive + description: + name: equatable + sha256: ea36e500cbf0ec18361deabca755434f73e42fe53c5130021c7e2d6b5ebe1702 + url: "https://pub.dev" + source: hosted + version: "3.0.0" fake_async: dependency: transitive description: @@ -86,16 +126,160 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_local_notifications: + dependency: "direct main" + description: + name: flutter_local_notifications + sha256: "19ffb0a8bb7407875555e5e98d7343a633bb73707bae6c6a5f37c90014077875" + url: "https://pub.dev" + source: hosted + version: "19.5.0" + flutter_local_notifications_linux: + dependency: transitive + description: + name: flutter_local_notifications_linux + sha256: e3c277b2daab8e36ac5a6820536668d07e83851aeeb79c446e525a70710770a5 + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_local_notifications_platform_interface: + dependency: transitive + description: + name: flutter_local_notifications_platform_interface + sha256: "277d25d960c15674ce78ca97f57d0bae2ee401c844b6ac80fcd972a9c99d09fe" + url: "https://pub.dev" + source: hosted + version: "9.1.0" + flutter_local_notifications_windows: + dependency: transitive + description: + name: flutter_local_notifications_windows + sha256: "8d658f0d367c48bd420e7cf2d26655e2d1130147bca1eea917e576ca76668aaf" + url: "https://pub.dev" + source: hosted + version: "1.0.3" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea" + url: "https://pub.dev" + source: hosted + version: "9.2.4" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688 + url: "https://pub.dev" + source: hosted + version: "1.2.3" + flutter_secure_storage_macos: + dependency: transitive + description: + name: flutter_secure_storage_macos + sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247" + url: "https://pub.dev" + source: hosted + version: "3.1.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709 + url: "https://pub.dev" + source: hosted + version: "3.1.2" flutter_test: dependency: "direct dev" description: flutter source: sdk version: "0.0.0" + flutter_timezone: + dependency: "direct main" + description: + name: flutter_timezone + sha256: "7830bc64bef0b003468fc1f58fc3f3faf54817f8cd6e68fa818b306560410d68" + url: "https://pub.dev" + source: hosted + version: "5.1.1" flutter_web_plugins: dependency: transitive description: flutter source: sdk version: "0.0.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + jni: + dependency: transitive + description: + name: jni + sha256: d8df6dab6847855512fe44dd9032b0bbe34dda7bf7597e41d30750879779813f + url: "https://pub.dev" + source: hosted + version: "1.1.1" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" + url: "https://pub.dev" + source: hosted + version: "1.0.4+1" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" leak_tracker: dependency: transitive description: @@ -128,6 +312,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" matcher: dependency: transitive description: @@ -152,6 +344,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.18.3" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e + url: "https://pub.dev" + source: hosted + version: "9.5.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + url: "https://pub.dev" + source: hosted + version: "3.0.0" path: dependency: transitive description: @@ -160,6 +368,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" path_provider_linux: dependency: transitive description: @@ -184,6 +416,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" platform: dependency: transitive description: @@ -200,6 +440,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.8" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" shared_preferences: dependency: "direct main" description: @@ -309,6 +565,86 @@ packages: url: "https://pub.dev" source: hosted version: "0.7.12" + timezone: + dependency: "direct main" + description: + name: timezone + sha256: dd14a3b83cfd7cb19e7888f1cbc20f258b8d71b54c06f79ac585f14093a287d1 + url: "https://pub.dev" + source: hosted + version: "0.10.1" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda + url: "https://pub.dev" + source: hosted + version: "6.3.3" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" + url: "https://pub.dev" + source: hosted + version: "6.3.33" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" + url: "https://pub.dev" + source: hosted + version: "6.4.2" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" + url: "https://pub.dev" + source: hosted + version: "3.2.3" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" + url: "https://pub.dev" + source: hosted + version: "3.2.6" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" + url: "https://pub.dev" + source: hosted + version: "3.1.6" vector_math: dependency: transitive description: @@ -365,6 +701,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.26.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" xdg_directories: dependency: transitive description: @@ -373,6 +717,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" sdks: dart: ">=3.13.4 <4.0.0" flutter: ">=3.44.0" diff --git a/test/planner_sync_test.dart b/test/planner_sync_test.dart new file mode 100644 index 0000000..3b40da3 --- /dev/null +++ b/test/planner_sync_test.dart @@ -0,0 +1,117 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:taskhub/planner_sync.dart'; +import 'package:taskhub/taskhub_api.dart'; + +class FakeApi extends TaskHubApi { + Map remote = {'revision': 0, 'lessons': [], 'deadlines': []}; + bool offline = false; + FakeApi() { + token = 'fake'; + userId = 1; + } + @override + Future restore() async {} + @override + Future> call( + String method, + String path, [ + Map? data, + ]) async { + if (offline) throw Exception('offline'); + if (method == 'GET') return Map.of(remote); + if (data!['revision'] != remote['revision']) { + throw const ApiError('revision_conflict (409)'); + } + remote = {...data, 'revision': (remote['revision'] as int) + 1}; + return {'revision': remote['revision']}; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() => SharedPreferences.setMockInitialValues({})); + test('pending changes survive controller restart and retry', () async { + final api = FakeApi(); + final first = PlannerSync(api); + await first.start(); + api.offline = true; + await first.edit([ + {'id': 'local'}, + ], []); + expect(first.pending, true); + first.dispose(); + final second = PlannerSync(api); + await second.start(); + expect(second.state['lessons'], [ + {'id': 'local'}, + ]); + api.offline = false; + await second.sync(); + expect(second.pending, false); + expect(api.remote['lessons'], [ + {'id': 'local'}, + ]); + second.dispose(); + }); + test('conflicts preserve local changes until explicit resolution', () async { + final api = FakeApi(); + final sync = PlannerSync(api); + await sync.start(); + api.remote = { + 'revision': 1, + 'lessons': [ + {'id': 'remote'}, + ], + 'deadlines': [], + }; + await sync.edit([ + {'id': 'local'}, + ], []); + expect(sync.conflict, true); + expect(api.remote['lessons'], [ + {'id': 'remote'}, + ]); + await sync.resolve(keepLocal: true); + expect(api.remote['lessons'], [ + {'id': 'local'}, + ]); + expect(sync.conflict, false); + sync.dispose(); + }); + test('guest import is explicit and repeatable without duplicates', () async { + SharedPreferences.setMockInitialValues({ + 'taskhub_lessons': '[{"id":"guest"}]', + }); + final api = FakeApi(); + final sync = PlannerSync(api); + await sync.start(); + expect(sync.state['lessons'], isEmpty); + await sync.importGuest(); + await sync.importGuest(); + expect(api.remote['lessons'], [ + {'id': 'guest_guest'}, + ]); + sync.dispose(); + }); + test( + 'switching accounts never uploads the previous pending planner', + () async { + final api = FakeApi(); + final sync = PlannerSync(api); + await sync.start(); + api.offline = true; + await sync.edit([ + {'id': 'private-user-one'}, + ], []); + api.userId = 2; + api.remote = {'revision': 0, 'lessons': [], 'deadlines': []}; + api.offline = false; + api.notifyListeners(); + await Future.delayed(const Duration(milliseconds: 50)); + expect(sync.state['lessons'], isEmpty); + expect(api.remote['lessons'], isEmpty); + sync.dispose(); + }, + ); +} diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 8b6d468..ee67b42 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,15 @@ #include "generated_plugin_registrant.h" +#include +#include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterSecureStorageWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); + FlutterTimezonePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterTimezonePluginCApi")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); } diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index b93c4c3..6b603f5 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,9 +3,14 @@ # list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_windows + flutter_timezone + url_launcher_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + flutter_local_notifications_windows + jni ) set(PLUGIN_BUNDLED_LIBRARIES)