Coverage for src/web.py: 100%
694 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
1"""Web UI for icloud-docker.
3Goal — give the user a single page they can hit from any device to:
4 1) (primary) authenticate / re-authenticate Apple ID + 2FA;
5 2) (secondary) confirm config paths, mount markers, and last-sync status;
6 3) (tertiary) tail the recent log lines.
8The web server runs in a daemon thread spawned from ``main.py`` alongside
9the existing ``sync.sync()`` loop. The two share state through the
10filesystem (keyring, session cookies, log file). No new persistence layer.
12Designed for **LAN- or proxy-trusted** exposure. There is no built-in
13login on this UI — put Cloudflare Access / Authelia / Tailscale in front
14when exposing publicly. Opt-out via ``app.web_ui.enabled: false`` in
15``config.yaml``.
16"""
18__author__ = "Mandar Patil (mandarons@pm.me)"
20import base64
21import hmac
22import json
23import os
24import re
25import secrets
26import shutil
27import struct
28import tempfile
29import threading
30import time
31from typing import Any
33from flask import Flask, jsonify, redirect, render_template, request, url_for
34from werkzeug.serving import make_server
36from src import (
37 CHINA_HOME_ENDPOINT,
38 CHINA_SETUP_ENDPOINT,
39 DEFAULT_CONFIG_FILE_PATH,
40 DEFAULT_COOKIE_DIRECTORY,
41 ENV_CONFIG_FILE_PATH_KEY,
42 ENV_ICLOUD_PASSWORD_KEY,
43 config_parser,
44 dashboard_view,
45 get_logger,
46 read_config,
47 settings_view,
48 web_signals,
49)
50from src.config_utils import get_config_value_or_none
52LOGGER = get_logger()
54# Module-level holder for the live icloudpy session created during
55# POST /auth/password, so POST /auth/code can call validate_2fa_code on
56# the SAME session. Cleared after a successful trust_session or via
57# POST /auth/reset.
58_PENDING_AUTH: dict[str, Any] = {}
59_AUTH_LOCK = threading.Lock()
61# Drop stale pending auth after this many seconds. The half-finished
62# sign-in in ``_PENDING_AUTH["api"]`` holds the submitted Apple ID password
63# in process memory while waiting for the user's code or key; without an
64# expiry it would linger indefinitely if the user closed the browser tab
65# mid-flow. 10 min is generous for typing a code. The password is never
66# written anywhere.
67_PENDING_AUTH_TTL_SECONDS = 600
69# Apple IDs whose last web sign-in used a password other than the stored
70# one, so the stored copy is probably out of date. The dashboard offers to
71# remove it; nothing removes it unasked. Each maps to a keyed fingerprint
72# of the stored password it was compared with, so the notice goes away by
73# itself once that password is replaced or removed some other way (the
74# `icloud` command runs in another process). Memory only: after a restart
75# the plain stored-password notice is still shown.
76_OUTDATED_PASSWORD: dict[str, bytes] = {}
77_FINGERPRINT_KEY = secrets.token_bytes(32)
80def _fingerprint(password: str) -> bytes:
81 return hmac.new(_FINGERPRINT_KEY, password.encode("utf-8"), "sha256").digest()
84def _stale_stored_fingerprint(username: str, password: str | None) -> bytes | None:
85 """Fingerprint of the stored password if one is stored (not from the
86 environment) and differs from ``password``; otherwise None."""
87 if not password or os.environ.get(ENV_ICLOUD_PASSWORD_KEY):
88 return None
89 try:
90 stored = _stored_password(username)
91 except Exception as e: # advisory only; never fail a sign-in over it
92 LOGGER.debug(f"Web UI keyring probe raised: {e!s}")
93 return None
94 if stored is None or stored == password:
95 return None
96 return _fingerprint(stored)
99def _note_sign_in(username: str | None, *, stale_stored: bytes | None) -> None:
100 """Remember whether a completed sign-in showed the stored password is out of date."""
101 if not username:
102 return
103 with _AUTH_LOCK:
104 if stale_stored is not None:
105 _OUTDATED_PASSWORD[username] = stale_stored
106 else:
107 _OUTDATED_PASSWORD.pop(username, None)
110def _stored_password_outdated(username: str | None) -> bool:
111 """True while the stored password is still the one a sign-in showed is stale.
113 Reads the keyring only for an Apple ID that was flagged."""
114 if not username:
115 return False
116 with _AUTH_LOCK:
117 flagged = _OUTDATED_PASSWORD.get(username)
118 if flagged is None or os.environ.get(ENV_ICLOUD_PASSWORD_KEY):
119 return False
120 try:
121 stored = _stored_password(username)
122 except Exception as e: # advisory only; never break a render
123 LOGGER.debug(f"Web UI keyring probe raised: {e!s}")
124 return False
125 return stored is not None and hmac.compare_digest(_fingerprint(stored), flagged)
128def _wake_sync_loop() -> None:
129 """Cut short the auth-retry wait after a re-auth succeeds.
131 Without this the loop serves out the rest of an interval that began
132 before the problem was solved -- the user completes the sign-in and
133 the dashboard keeps reporting the sync as stopped for up to
134 ``retry_login_interval``.
136 It also clears the loop's "blocked" flag: the caller redirects to the
137 dashboard at once, seconds before the loop wakes and clears it itself,
138 so the page the user lands on would still say the sync is stopped. If
139 the loop then fails again it records the block afresh.
141 Best-effort: a missed nudge costs a delay, never correctness.
142 """
143 try:
144 web_signals.record_reauth_completed()
145 web_signals.record_auth_blocked(blocked=False)
146 except Exception as e: # noqa: BLE001 - never fail a successful sign-in
147 LOGGER.debug(f"could not signal the completed re-auth: {e!s}")
150def _pending_auth_is_stale() -> bool:
151 """True when the in-memory password is older than the TTL.
153 Caller must hold ``_AUTH_LOCK``. Returns False for an empty dict
154 (nothing to expire) and for entries that pre-date stashed_at
155 bookkeeping (defensive — we never penalise a fresh stash).
156 """
157 if not _PENDING_AUTH:
158 return False
159 stashed_at = _PENDING_AUTH.get("stashed_at")
160 if stashed_at is None:
161 return False
162 return (time.monotonic() - stashed_at) > _PENDING_AUTH_TTL_SECONDS
165def _clear_pending_auth_unlocked() -> None:
166 """Forget the pending auth, and a security-key ceremony's private cookie
167 jar with it -- it holds that ceremony's Apple session cookies, and an
168 abandoned ceremony would otherwise leave them in the temp dir until the
169 container restarts. Caller holds the lock."""
170 _discard_ceremony_dir(_PENDING_AUTH.get("cookie_dir"))
171 _PENDING_AUTH.clear()
174def _expire_stale_pending_auth_unlocked() -> None:
175 """If the pending auth is older than the TTL, wipe it. Caller holds the lock."""
176 if _pending_auth_is_stale():
177 LOGGER.info("Web UI: expiring stale _PENDING_AUTH past TTL.")
178 _clear_pending_auth_unlocked()
181# CSRF defence. Threat model: even with the default host pinned to
182# 127.0.0.1, a user who opts into LAN exposure (host: 0.0.0.0) AND lacks
183# a proper auth proxy in front would otherwise be vulnerable to a
184# same-network attacker who tricks them into loading a page that posts
185# to ``/auth/refresh-trust`` or ``/api/sync``. Double-submit cookie
186# pattern: per-process random token, set as a SameSite=Strict cookie,
187# required on every state-changing POST as either a form field
188# ``csrf_token`` or an ``X-CSRF-Token`` header. SameSite=Strict alone
189# already blocks the cross-site cookie send in modern browsers; the
190# server-side compare is belt-and-braces for older clients.
191_CSRF_TOKEN = secrets.token_urlsafe(32)
192_CSRF_COOKIE_NAME = "csrf_token"
195def _get_csrf_token() -> str:
196 """Expose the token to templates (so forms can embed it) and to
197 tests (so they can post it). Process-lifetime, regenerated on
198 restart -- enough for a single-user operator console."""
199 return _CSRF_TOKEN
202def _require_csrf() -> tuple[Any, int] | None:
203 """Validate CSRF token on the current request. Returns ``None``
204 when the request is allowed, or a ``(response, status)`` tuple
205 when it should be rejected. Use at the top of every state-
206 changing endpoint:
208 rejection = _require_csrf()
209 if rejection is not None:
210 return rejection
212 **Calling from a script / monitor.** Every state-changing endpoint
213 needs BOTH the CSRF cookie and a matching token, so a bare
214 ``curl -X POST /api/sync -d service=drive`` gets a 403. The cookie
215 is only set by a prior page load, so fetch it first and echo it
216 back in the ``X-CSRF-Token`` header::
218 curl -c jar -s http://127.0.0.1:8080/ >/dev/null
219 TOKEN=$(awk '/csrf_token/ {print $7}' jar)
220 curl -b jar -H "X-CSRF-Token: $TOKEN" \
221 -X POST http://127.0.0.1:8080/api/sync -d service=drive
223 The 403 bodies name which leg failed ("CSRF cookie missing or
224 stale" vs "CSRF token mismatch") so the fix is obvious.
225 """
226 cookie = request.cookies.get(_CSRF_COOKIE_NAME)
227 submitted = request.form.get("csrf_token") or request.headers.get("X-CSRF-Token")
228 # The cookie must match this process's token AND the submitted value
229 # must match the cookie. Browsers won't include a SameSite=Strict
230 # cookie on a cross-site POST, so the cookie absence alone is the
231 # primary signal; the form/header echo is the belt-and-braces leg.
232 if not cookie or not hmac.compare_digest(cookie, _CSRF_TOKEN):
233 return jsonify({"error": "CSRF cookie missing or stale"}), 403
234 if not submitted or not hmac.compare_digest(submitted, cookie):
235 return jsonify({"error": "CSRF token mismatch"}), 403
236 return None
239def _current_config_path() -> str:
240 """Resolve the active config path the same way sync.py does."""
241 return os.environ.get(ENV_CONFIG_FILE_PATH_KEY, DEFAULT_CONFIG_FILE_PATH)
244def _load_current_config() -> dict | None:
245 """Re-read config.yaml fresh on every request so edits show up live.
247 Defensive: mandarons' ``read_config`` reaches into
248 ``config["app"]["credentials"]["username"]`` unconditionally and
249 crashes if the credentials block is missing. Catch that so a partial
250 config (e.g. fresh install with only ``app.logger`` set) still lets
251 the web UI render the setup-needed state instead of 500-ing.
252 """
253 path = _current_config_path()
254 if not os.path.isfile(path):
255 return None
256 try:
257 return read_config(config_path=path)
258 except Exception as e:
259 # Broad on purpose: ``/api/health`` exists for external monitors
260 # and must be robust against any config-loading failure (YAML
261 # parse errors, permission denied, missing credentials block,
262 # ruamel internals raising). A 500 on /api/health blinds the
263 # monitor; rendering a "config error" state lets the user fix
264 # it via the UI.
265 LOGGER.warning(f"Web UI: read_config failed: {e!s}")
266 return None
269def _get_marker_filename(config: dict) -> str:
270 """Marker filename from ``app.mount_marker_filename`` (default ``.mounted``)."""
271 return config_parser.get_mount_marker_filename(config=config)
274def _get_require_mount_marker(config: dict, service: str) -> bool:
275 """``{drive,photos}.require_mount_marker`` for the given service."""
276 getter = getattr(config_parser, f"get_{service}_require_mount_marker")
277 return bool(getter(config=config))
280def _get_library_destinations(config: dict) -> dict[str, str]:
281 """``photos.library_destinations`` mapping (empty dict when unset)."""
282 return config_parser.get_photos_library_destinations(config=config) or {}
285def _get_configured_libraries(config: dict) -> list[str]:
286 """Libraries the operator named: ``photos.filters.libraries``, then any
287 ``photos.library_destinations`` keys, in config order.
289 Read directly rather than through ``get_photos_libraries_filter``, which
290 logs "downloading all libraries" whenever the filter is unset -- once per
291 dashboard load.
292 """
293 named = get_config_value_or_none(config=config, config_path=["photos", "filters", "libraries"]) or []
294 if isinstance(named, str):
295 # ``libraries: PrimarySync`` rather than a list -- iterating the
296 # string would list one library per character.
297 named = [named]
298 named = [n for n in named if isinstance(n, str)]
299 return list(dict.fromkeys(named + list(_get_library_destinations(config=config))))
302def _build_service(config: dict, service: str, marker_filename: str) -> dict[str, Any]:
303 """Compose a single service entry (Photos or Drive) for /api/status."""
304 if service == "photos":
305 # Read-only on purpose: ``prepare_*_destination`` calls
306 # ``join_and_ensure_path`` (mkdir), so a plain ``GET /api/status``
307 # would write to disk -- and 500 the whole dashboard on a
308 # read-only destination mount. Composing the non-mutating getters
309 # lets a read-only or absent destination degrade to
310 # ``destination_exists: false`` instead.
311 destination = os.path.join(
312 config_parser.get_root_destination_path(config=config),
313 config_parser.get_photos_destination_path(config=config),
314 )
315 interval = config_parser.get_photos_sync_interval(
316 config=config,
317 log_messages=False,
318 )
319 name = "Photos"
320 library_destinations = _get_library_destinations(config=config)
321 else:
322 destination = os.path.join(
323 config_parser.get_root_destination_path(config=config),
324 config_parser.get_drive_destination_path(config=config),
325 )
326 interval = config_parser.get_drive_sync_interval(
327 config=config,
328 log_messages=False,
329 )
330 name = "Drive"
331 library_destinations = {}
333 marker_path = os.path.join(destination, marker_filename)
334 state = web_signals.get_sync_state(service=service)
335 stats = None
336 if state:
337 completed_at = state.get("completed_at")
338 stats = {
339 "completed_at": completed_at,
340 "last_sync_relative": (web_signals.format_relative_time(completed_at) if completed_at else None),
341 "files_downloaded": state.get("files_downloaded"),
342 "files_skipped": state.get("files_skipped"),
343 "files_removed": state.get("files_removed"),
344 # Named for what it is: the last COMPLETED cycle's
345 # downloaded+skipped total. The state record overwrites per
346 # cycle rather than accumulating, so this is not a running
347 # count of files on disk.
348 "last_cycle_total": (
349 (state.get("files_downloaded") or 0) + (state.get("files_skipped") or 0)
350 if (state.get("files_downloaded") is not None or state.get("files_skipped") is not None)
351 else None
352 ),
353 "errors": state.get("errors", 0),
354 "duration_seconds": state.get("duration_seconds"),
355 }
356 return {
357 "name": name,
358 "destination": destination,
359 "destination_exists": os.path.isdir(destination),
360 "sync_interval_s": interval,
361 "require_mount_marker": _get_require_mount_marker(
362 config=config,
363 service=service,
364 ),
365 "marker_present": os.path.isfile(marker_path),
366 "marker_path": marker_path,
367 "library_destinations": library_destinations,
368 "libraries": (
369 _build_libraries(_get_configured_libraries(config=config), library_destinations)
370 if service == "photos"
371 else []
372 ),
373 "stats": stats,
374 "syncing_since_relative": (
375 web_signals.format_relative_time(state["running_since"]) if state.get("running_since") else None
376 ),
377 "force_sync_pending": service in web_signals.pending_force_syncs(),
378 }
381def _logger_filename(config: dict | None) -> str:
382 """Resolve where ``sync.py`` is writing log lines. Best-effort.
384 Reads ``app.logger.filename`` directly off the config dict to avoid
385 introducing a new ``config_parser`` helper just for this — keeps the
386 upstream PR diff small.
387 """
388 if not config:
389 return ""
390 try:
391 return config.get("app", {}).get("logger", {}).get("filename", "") or ""
392 except AttributeError:
393 return ""
396def _tail_log_file(path: str, lines: int = 200) -> list[str]:
397 """Return the last ``lines`` lines of ``path``.
399 Best-effort: missing path, unreadable file, or decode failure all
400 return an empty list. Reads from the end in 8 KiB blocks so the cost
401 is bounded by ``lines * average_line_length`` rather than file size.
402 """
403 if not path or not os.path.isfile(path):
404 return []
405 try:
406 with open(path, "rb") as f:
407 f.seek(0, os.SEEK_END)
408 size = f.tell()
409 block = 8192
410 data = b""
411 while size > 0 and data.count(b"\n") <= lines:
412 read_size = min(block, size)
413 size -= read_size
414 f.seek(size)
415 data = f.read(read_size) + data
416 return data.decode("utf-8", errors="replace").splitlines()[-lines:]
417 except OSError as e:
418 LOGGER.warning(f"Web UI could not tail log {path}: {e!s}")
419 return []
422def _build_status(config: dict | None) -> dict[str, Any]:
423 """Compose the payload returned by /api/status (and consumed by the
424 dashboard template)."""
425 if not config:
426 return {
427 "config_loaded": False,
428 "config_path": _current_config_path(),
429 "username": None,
430 "services": [],
431 }
433 marker_filename = _get_marker_filename(config=config)
434 services = []
435 if "photos" in config:
436 services.append(
437 _build_service(
438 config=config,
439 service="photos",
440 marker_filename=marker_filename,
441 ),
442 )
443 if "drive" in config:
444 services.append(
445 _build_service(
446 config=config,
447 service="drive",
448 marker_filename=marker_filename,
449 ),
450 )
452 username = config_parser.get_username(config=config)
453 trust = web_signals.get_trust_state()
454 trust_expires_at = trust.get("expires_at")
455 trust_days_remaining: int | None = None
456 if trust_expires_at:
457 try:
458 import datetime
460 exp = datetime.datetime.fromisoformat(trust_expires_at)
461 now = datetime.datetime.now(tz=exp.tzinfo) if exp.tzinfo else datetime.datetime.now()
462 trust_days_remaining = (exp - now).days
463 except (
464 ValueError,
465 TypeError,
466 ): # pragma: no cover -- defensive against malformed iso
467 trust_days_remaining = None
468 return {
469 "config_loaded": True,
470 "config_path": _current_config_path(),
471 "username": username,
472 "region": config_parser.get_region(config=config),
473 "marker_filename": marker_filename,
474 "services": services,
475 "auth_state": _detect_auth_state(username=username),
476 # Which mode the container is in, and why the loop says it is stuck.
477 # Without these the pill tells a password-free install that its
478 # keyring is populated and blames every stoppage on a second factor.
479 "password_stored": _password_is_stored(username) if username else False,
480 # Deleting the keyring entry does not stick while this is set: the
481 # sync loop writes it back every cycle.
482 "password_from_env": bool(os.environ.get(ENV_ICLOUD_PASSWORD_KEY)),
483 "stored_password_outdated": _stored_password_outdated(username),
484 "auth_blocked_reason": web_signals.get_auth_blocked().get("reason"),
485 "auth_method": web_signals.get_auth_method(username) if username else None,
486 "force_sync_pending": web_signals.pending_force_syncs(),
487 "trust_expires_at": trust_expires_at,
488 "trust_days_remaining": trust_days_remaining,
489 }
492def _build_libraries(configured: list[str], library_destinations: dict[str, str]) -> list[dict[str, Any]]:
493 """One row per photo library: where it goes and how it last went.
495 Only libraries this container actually syncs are listed: the ones the
496 operator named in config, plus any that have completed a sync or are
497 syncing right now. An account can carry libraries that never serve
498 anything -- there is nothing to do with them, so they are left out
499 rather than shown as a permanent failure. The log still records every
500 attempt, and naming a library in config always lists it.
502 Configured libraries come first, in config order.
503 """
504 states = web_signals.get_library_states()
505 rows = []
506 active = sorted(
507 n
508 for n, entry in states.items()
509 if n not in configured and (entry.get("completed_at") or entry.get("state") == "syncing")
510 )
511 for name in configured + active:
512 entry = states.get(name, {})
513 completed_at = entry.get("completed_at")
514 rows.append(
515 {
516 "name": name,
517 "subdir": library_destinations.get(name),
518 "state": entry.get("state"),
519 "error": entry.get("error"),
520 "indexing": entry.get("indexing"),
521 "completed_relative": (
522 web_signals.format_relative_time(completed_at) if completed_at else None
523 ),
524 },
525 )
526 return rows
529def _password_is_stored(username: str) -> bool:
530 """True when a password is cached for this Apple ID."""
531 try:
532 from icloudpy import utils as icloudpy_utils
534 return bool(icloudpy_utils.password_exists_in_keyring(username))
535 except Exception as e: # pragma: no cover - advisory, never breaks a render
536 LOGGER.debug(f"Web UI keyring probe raised: {e!s}")
537 return False
540def _saved_session_exists(username: str) -> bool:
541 r"""True when this Apple ID has a session file carrying a session token.
543 icloudpy names the file after the apple id with every non-``\w``
544 character dropped, plus ``.session`` (``ICloudPyService.session_path``),
545 and resumes from its ``session_token``. A file for *some other* account,
546 or one without that key, is not a credential this container can use --
547 and in a password-free setup it is the only credential there is.
548 """
549 sanitised = "".join(c for c in username if re.match(r"\w", c))
550 try:
551 with open(
552 os.path.join(DEFAULT_COOKIE_DIRECTORY, f"{sanitised}.session"),
553 encoding="utf-8",
554 ) as handle:
555 return bool(json.load(handle).get("session_token"))
556 except (OSError, ValueError):
557 return False
560def _detect_auth_state(username: str | None) -> str:
561 """Best-effort check of whether the sync loop can actually authenticate.
563 Returns one of:
564 - ``not_configured`` — no ``app.credentials.username`` in config.
565 - ``setup_needed`` — username set, but neither a cached keyring
566 password nor a saved session. The container's first 2FA flow
567 hasn't been completed.
568 - ``ready`` — username set, plus either a keyring entry or a saved
569 session. Sync loop can resume the session on the next retry.
570 - ``reauth_needed`` — a credential is present but the sync loop has
571 reported that it cannot authenticate with it.
573 Distinct from a *live* iCloud session check (which would require
574 hitting Apple). This is the cheap on-disk signal behind the pill the
575 dashboard shows before the sync loop has reported anything.
576 """
577 if not username:
578 return "not_configured"
579 try:
580 from icloudpy import utils as icloudpy_utils
582 if icloudpy_utils.password_exists_in_keyring(username):
583 # Ask the sync loop before claiming health: every on-disk
584 # signal still looks correct while an account is stuck on a
585 # second factor, so "keyring populated" alone would render a
586 # green dashboard over a sync that has not run for weeks.
587 if web_signals.get_auth_blocked().get("blocked"):
588 return "reauth_needed"
589 return "ready"
590 # An empty keyring is a supported configuration, not an unfinished
591 # setup: the sync loop runs off the saved session alone when no
592 # password is stored. Judge such a container on its session, or the
593 # dashboard would tell a deliberately password-free operator to go
594 # and finish a setup that is already finished.
595 if _saved_session_exists(username):
596 if web_signals.get_auth_blocked().get("blocked"):
597 return "reauth_needed"
598 return "ready"
599 except Exception as e:
600 LOGGER.debug(f"Web UI auth-state check raised: {e!s}")
601 return "setup_needed"
604def create_app(testing: bool = False) -> Flask:
605 """Construct the Flask app.
607 Splitting this out keeps ``tests/`` able to build the app under
608 ``TESTING=True`` without spawning a thread.
609 """
610 from werkzeug.middleware.proxy_fix import ProxyFix
612 # No ``static_folder``: templates are single-file with inline CSS and
613 # nothing ships under src/static, so wiring it would only add a 404
614 # route for /static/*.
615 template_dir = os.path.join(os.path.dirname(__file__), "templates")
616 app = Flask(__name__, template_folder=template_dir)
617 app.config["TESTING"] = testing
619 # Trust X-Forwarded-* from a single reverse-proxy hop (Cloudflare Tunnel,
620 # Authelia / Traefik). Lets ``url_for`` produce ``https://`` URLs and
621 # prevents Flask from mis-detecting the scheme when behind a TLS-
622 # terminating proxy. One hop is correct here — Cloudflare → backend.
623 app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
625 @app.after_request
626 def _no_cache(response):
627 """Defense against intermediaries (browser back/forward cache,
628 Cloudflare's auto-minify, mobile carrier proxies) serving stale
629 dashboard or auth payloads. The dashboard is always live data —
630 a cached snapshot would hide a missing mount marker or an
631 expired session."""
632 response.headers["Cache-Control"] = "private, no-store, no-cache, must-revalidate, max-age=0"
633 response.headers["Pragma"] = "no-cache"
634 response.headers["Expires"] = "0"
635 # CSRF defence: set the SameSite=Strict token cookie on every
636 # response so forms rendered server-side can read it (via the
637 # template) and same-site fetches automatically include it.
638 # ``secure=False`` because the default deployment is loopback
639 # over plain HTTP; users behind a TLS proxy benefit from the
640 # proxy's transport security, and SameSite=Strict is the load-
641 # bearing protection here regardless of TLS.
642 response.set_cookie(
643 _CSRF_COOKIE_NAME,
644 _CSRF_TOKEN,
645 samesite="Strict",
646 httponly=False,
647 secure=False,
648 path="/",
649 )
650 return response
652 @app.route("/")
653 def dashboard():
654 """Render the HTML dashboard — Apple-leaning design."""
655 config = _load_current_config()
656 status_payload = _build_status(config=config)
657 log_path = _logger_filename(config=config)
658 log_lines = _tail_log_file(path=log_path, lines=200)
659 everyone = dashboard_view.people(status_payload)
660 return render_template(
661 "dashboard.html",
662 status=status_payload,
663 people=everyone,
664 headline=dashboard_view.headline(everyone),
665 refreshing=dashboard_view.refreshing(status_payload, everyone),
666 log_summary=dashboard_view.log_summary(log_lines),
667 log_lines=log_lines,
668 log_path=log_path,
669 active_nav="dashboard",
670 version=os.environ.get("APP_VERSION", ""),
671 csrf_token=_get_csrf_token(),
672 )
674 @app.route("/api/health")
675 def health():
676 """Tiny endpoint for external monitors.
678 - 200 ``{"state": "ok"}`` when the config file is readable.
679 - 503 ``{"state": "config_missing"}`` when it isn't.
681 ``2fa_required`` is *not* a 503 — Apple sessions expire all the time
682 and the dashboard must stay reachable so the user can re-auth.
683 """
684 if not os.path.isfile(_current_config_path()):
685 return jsonify({"state": "config_missing"}), 503
686 return jsonify({"state": "ok"})
688 @app.route("/api/status")
689 def status():
690 """Live status payload for the dashboard + external consumers."""
691 config = _load_current_config()
692 payload = _build_status(config=config)
693 if not payload["config_loaded"]:
694 return jsonify(payload), 503
695 return jsonify(payload)
697 @app.route("/api/logs")
698 def logs():
699 """Last 200 lines of the configured log file. Best-effort: missing
700 or unreadable returns an empty list (never 500 — the dashboard
701 relies on this being reachable to render the rest of the page)."""
702 config = _load_current_config()
703 return jsonify(
704 {"lines": _tail_log_file(path=_logger_filename(config=config), lines=200)},
705 )
707 @app.route("/auth", methods=["GET"])
708 def auth_form():
709 """Auth form. Renders the password field by default; renders the
710 6-digit code field instead when ``_PENDING_AUTH`` indicates that
711 the password step already succeeded and 2FA is pending."""
712 return _render_auth(message=None, message_kind=None)
714 @app.route("/auth/password", methods=["POST"])
715 def auth_password():
716 """Step 1: sign in with the password, trigger 2FA push if needed.
718 The password is not saved.
720 On success of either path: redirects — to /auth (now showing the
721 code form) if 2FA is pending, or back to / if the cached session
722 was still trusted.
724 Exceptions are caught and rendered as an error pill on /auth so
725 the user sees what Apple said.
726 """
727 rejection = _require_csrf()
728 if rejection is not None:
729 return rejection
731 password = request.form.get("password", "")
732 if not password:
733 return (
734 _render_auth(message="Password is required.", message_kind="err"),
735 400,
736 )
738 config = _load_current_config()
739 username = None
740 if config:
741 try:
742 username = config_parser.get_username(config=config)
743 except (KeyError, AttributeError, TypeError): # pragma: no cover
744 # Defensive: get_username walks app.credentials.username;
745 # partial configs (no credentials block) raise. Treat as
746 # missing. Rare in practice — coverage-pragma'd because
747 # mocking get_username globally breaks _render_auth.
748 username = None
749 if not username:
750 return (
751 _render_auth(
752 message="No app.credentials.username in config.yaml — set it and reload.",
753 message_kind="err",
754 ),
755 400,
756 )
758 try:
759 api = _create_icloud_service(
760 username=username,
761 password=password,
762 cookie_directory=DEFAULT_COOKIE_DIRECTORY,
763 config=config,
764 )
765 except Exception as e:
766 LOGGER.exception("Web UI auth failed during ICloudPyService instantiation")
767 return (
768 _render_auth(
769 message=f"Authentication failed: {e!s}",
770 message_kind="err",
771 ),
772 400,
773 )
775 stale_stored = _stale_stored_fingerprint(username, password)
776 if api.requires_2fa:
777 # PR 1 / fix/ios-26.4-auth dependency — best-effort. Catches all
778 # exceptions so a missing-method or push-trigger failure doesn't
779 # block the user from typing in a code they got via SMS.
780 try:
781 trigger = getattr(api, "trigger_2fa_push_notification", None)
782 if callable(trigger):
783 trigger()
784 except Exception as e:
785 LOGGER.warning(f"Web UI 2FA push trigger failed (non-fatal): {e!s}")
786 with _AUTH_LOCK:
787 _expire_stale_pending_auth_unlocked()
788 _PENDING_AUTH["api"] = api
789 _PENDING_AUTH["username"] = username
790 _PENDING_AUTH["stale_stored"] = stale_stored
791 _PENDING_AUTH["stashed_at"] = time.monotonic()
792 return redirect(url_for("auth_form"))
794 _note_sign_in(username, stale_stored=stale_stored)
795 # No 2FA needed — the sign-in refreshed the saved session, which
796 # is all the sync loop needs. The password is not saved: the form
797 # promises that, and ENV_ICLOUD_PASSWORD or the `icloud` command's
798 # "Save password in keyring?" are the ways to opt in to storing one.
799 _wake_sync_loop()
800 return redirect(url_for("dashboard"))
802 @app.route("/auth/code", methods=["POST"])
803 def auth_code():
804 """Step 2: validate the 6-digit code on the in-flight session,
805 trust the browser, clear pending, redirect.
807 - 400 if the code field is empty or no pending auth exists.
808 - 400 + 'Code rejected' if Apple says no — pending kept so the
809 user can retry without re-entering the password.
810 - On success: validate_2fa_code -> trust_session (failures here
811 are logged but non-fatal — the code already worked) ->
812 clear pending -> redirect to /. The password is never saved.
813 """
814 rejection = _require_csrf()
815 if rejection is not None:
816 return rejection
818 code = request.form.get("code", "").strip()
819 if not code:
820 return (
821 _render_auth(message="Enter the 6-digit code.", message_kind="err"),
822 400,
823 )
825 with _AUTH_LOCK:
826 _expire_stale_pending_auth_unlocked()
827 api = _PENDING_AUTH.get("api")
828 username = _PENDING_AUTH.get("username")
829 stale_stored = _PENDING_AUTH.get("stale_stored")
830 if api is None:
831 return (
832 _render_auth(
833 message="No pending auth — submit your password first.",
834 message_kind="err",
835 ),
836 400,
837 )
839 # All exit paths from here clear ``_PENDING_AUTH`` -- including
840 # failed validate_2fa_code, rejected codes, and trust_session
841 # failures. Without the ``finally`` the previous code only cleared
842 # on the success path, leaving the password sitting in process
843 # memory if Apple raised. On rejection the user retries via
844 # /auth/refresh-trust or by re-entering the password; we'd rather
845 # they take that path than leave a stale credential in memory.
846 try:
847 try:
848 accepted = api.validate_2fa_code(code)
849 except Exception as e:
850 LOGGER.exception("Web UI: validate_2fa_code raised")
851 return (
852 _render_auth(
853 message=f"2FA validation error: {e!s}",
854 message_kind="err",
855 ),
856 400,
857 )
859 if not accepted:
860 return (
861 _render_auth(
862 message="Code rejected by Apple. Try again — make sure you copy the latest code.",
863 message_kind="err",
864 ),
865 400,
866 )
868 # Code worked. Best-effort trust so the next session resume skips
869 # 2FA; if that fails (e.g. cookie store write error) just log it
870 # — the user's auth still succeeded for this session.
871 try:
872 api.trust_session()
873 except Exception as e:
874 LOGGER.warning(f"Web UI trust_session failed (non-fatal): {e!s}")
876 # The trusted session is what the sync loop resumes; the password
877 # is not saved (see auth_password).
878 _note_sign_in(username, stale_stored=stale_stored)
879 _wake_sync_loop()
880 return redirect(url_for("dashboard"))
881 finally:
882 with _AUTH_LOCK:
883 _clear_pending_auth_unlocked()
885 @app.route("/auth/security-key", methods=["GET"])
886 def auth_security_key():
887 """Start a security-key (FIDO2/WebAuthn) re-auth ceremony.
889 Apple disables every other second factor once security keys are
890 enrolled, so the 6-digit paths (``/auth/code``, the Telegram
891 listener) can never complete for such an account -- Apple answers
892 every factor endpoint with an ``fsaChallenge`` instead of pushing
893 a code.
895 The assertion cannot be produced by this page: WebAuthn requires
896 ``rpId`` to be a registrable suffix of the page origin, and
897 Apple's ``rpId`` is ``apple.com``. Browsers additionally blocklist
898 FIDO devices from WebHID/WebUSB precisely to stop a page doing raw
899 CTAP against another origin. So the signing step runs natively on
900 whatever machine holds the key, and only the signed assertion
901 comes back here.
903 This handler authenticates with the keyring password, reads
904 Apple's challenge, stashes the live session under ``_PENDING_AUTH``
905 (same slot ``/auth/code`` uses) and renders the blob the operator
906 feeds to the signer.
907 """
908 # A plain page load must never contact Apple. Each sign-in attempt
909 # counts against a rate limit that answers 409 on /signin/init once
910 # tripped, and a reload -- or a browser prefetch -- would otherwise
911 # spend one. The challenge is only fetched when the operator asks
912 # for it, and a pending one is re-rendered rather than replaced so
913 # a command already copied stays valid.
914 with _AUTH_LOCK:
915 _expire_stale_pending_auth_unlocked()
916 pending_challenge = _PENDING_AUTH.get("fsa_challenge")
917 if pending_challenge:
918 LOGGER.info("Web UI security-key: re-rendering the pending challenge.")
919 return _render_auth(security_key_blob=_pack_challenge(pending_challenge))
920 return redirect(url_for("auth_form"))
922 @app.route("/auth/security-key/start", methods=["POST"])
923 def auth_security_key_start():
924 """Ask Apple for a challenge. This is the only path that signs in."""
925 rejection = _require_csrf()
926 if rejection is not None:
927 return rejection
929 # Pressing the button twice must not spend a second sign-in.
930 with _AUTH_LOCK:
931 _expire_stale_pending_auth_unlocked()
932 pending_challenge = _PENDING_AUTH.get("fsa_challenge")
933 if pending_challenge:
934 LOGGER.info("Web UI security-key: reusing the pending challenge.")
935 return _render_auth(security_key_blob=_pack_challenge(pending_challenge))
938 config = _load_current_config()
939 username = None
940 if config:
941 try:
942 username = config_parser.get_username(config=config)
943 except (KeyError, AttributeError, TypeError):
944 username = None
945 if not username:
946 return (
947 _render_auth(
948 message="No app.credentials.username in config.yaml — set it first.",
949 message_kind="err",
950 ),
951 400,
952 )
954 # The password typed on this page, used for this sign-in only. A
955 # stored one is the fallback for containers that opted in to
956 # storing it (ENV_ICLOUD_PASSWORD or the `icloud` command).
957 typed = request.form.get("password") or None
958 password = typed
959 if password is None:
960 try:
961 password = _stored_password(username)
962 except Exception as e:
963 LOGGER.exception("Web UI security-key: keyring lookup raised")
964 return (
965 _render_auth(message=f"Keyring lookup failed: {e!s}", message_kind="err"),
966 500,
967 )
968 if not password:
969 return (
970 _render_auth(
971 message="Enter your Apple ID password to start the security-key sign-in.",
972 message_kind="warn",
973 ),
974 400,
975 )
977 try:
978 ceremony_dir = _ceremony_cookie_dir()
979 api = _create_icloud_service(
980 username=username,
981 password=password,
982 cookie_directory=ceremony_dir,
983 config=config,
984 )
985 except Exception as e:
986 _discard_ceremony_dir(locals().get("ceremony_dir"))
987 LOGGER.exception("Web UI security-key: ICloudPyService raised")
988 if _is_signin_throttled(e):
989 return (
990 _render_auth(
991 message=(
992 "Apple is rate-limiting sign-ins for this account "
993 "and will not issue a challenge yet. Nothing is "
994 "wrong with your key — wait a while before trying "
995 "again, as each attempt extends the limit."
996 ),
997 message_kind="warn",
998 ),
999 429,
1000 )
1001 return (
1002 _render_auth(
1003 message=f"Sign-in failed: {e!s}",
1004 message_kind="err",
1005 ),
1006 400,
1007 )
1009 stale_stored = _stale_stored_fingerprint(username, typed)
1010 if not api.requires_2fa:
1011 _note_sign_in(username, stale_stored=stale_stored)
1012 _wake_sync_loop()
1013 return redirect(url_for("dashboard"))
1015 fsa = api.security_key_challenge
1016 if not fsa:
1017 return (
1018 _render_auth(
1019 message=(
1020 "Apple did not offer a security-key challenge. This "
1021 "account may still use 6-digit codes — use the form below."
1022 ),
1023 message_kind="warn",
1024 ),
1025 400,
1026 )
1028 with _AUTH_LOCK:
1029 _expire_stale_pending_auth_unlocked()
1030 _PENDING_AUTH["api"] = api
1031 _PENDING_AUTH["username"] = username
1032 _PENDING_AUTH["stale_stored"] = stale_stored
1033 _PENDING_AUTH["stashed_at"] = time.monotonic()
1034 # Keep Apple's challenge string verbatim. It is echoed back in
1035 # the assertion and Apple compares it byte-for-byte, so a
1036 # re-encode differing only in base64 padding is rejected with a
1037 # 409 -- the signer's encoding must never be trusted here.
1038 stashed = dict(fsa)
1039 _PENDING_AUTH["fsa_challenge"] = stashed
1040 _PENDING_AUTH["cookie_dir"] = ceremony_dir
1042 _record_auth_method(username, "security_key")
1043 # Render exactly what was stashed. Handing over a different
1044 # challenge than the one being waited on costs a physical touch to
1045 # discover, so the two are deliberately the same object.
1046 return _render_auth(security_key_blob=_pack_challenge(stashed))
1048 @app.route("/auth/security-key", methods=["POST"])
1049 def auth_security_key_submit():
1050 """Finish the ceremony: submit the signed assertion to Apple.
1052 The assertion is bound to the ``scnt``/``X-Apple-ID-Session-Id``
1053 of the session stashed by the GET handler, so it must be
1054 submitted with that same session -- which is why the signer
1055 never needs the password and never talks to Apple itself.
1056 """
1057 rejection = _require_csrf()
1058 if rejection is not None:
1059 return rejection
1061 raw = request.form.get("assertion", "").strip()
1062 if not raw:
1063 return (
1064 _render_auth(message="Paste the signer output.", message_kind="err"),
1065 400,
1066 )
1067 try:
1068 decoded = json.loads(base64.b64decode(raw))
1069 except Exception:
1070 return (
1071 _render_auth(
1072 message="That does not look like signer output — copy the whole line.",
1073 message_kind="err",
1074 ),
1075 400,
1076 )
1078 # The signer emits one assertion per candidate origin, because the
1079 # origin is fixed inside clientData at signing time and Apple rejects
1080 # a wrong one with the same opaque 409 it uses for everything else.
1081 signatures = decoded if isinstance(decoded, list) else [decoded]
1082 # Valid base64 JSON that is not signer output (``[]``, ``["x"]``)
1083 # must get the same answer as garbage, not a traceback.
1084 if not signatures or not all(isinstance(sig, dict) for sig in signatures):
1085 return (
1086 _render_auth(
1087 message="That does not look like signer output — copy the whole line.",
1088 message_kind="err",
1089 ),
1090 400,
1091 )
1093 with _AUTH_LOCK:
1094 _expire_stale_pending_auth_unlocked()
1095 api = _PENDING_AUTH.get("api")
1096 username = _PENDING_AUTH.get("username")
1097 pending_fsa = _PENDING_AUTH.get("fsa_challenge") or {}
1098 ceremony_dir = _PENDING_AUTH.get("cookie_dir")
1099 stale_stored = _PENDING_AUTH.get("stale_stored")
1100 issued_challenge = pending_fsa.get("challenge")
1101 if api is None:
1102 return (
1103 _render_auth(
1104 message=("Challenge expired — start a new security-key re-auth and sign the fresh challenge."),
1105 message_kind="err",
1106 ),
1107 400,
1108 )
1110 # Apple compares the echoed challenge byte-for-byte, and the signer
1111 # round-trips it through raw bytes, so it can come back re-encoded
1112 # (base64 padding Apple did not send). Compare on the decoded value
1113 # and submit the stashed original.
1114 #
1115 # A genuine mismatch means the signed challenge is not the one this
1116 # session is waiting on -- almost always a stale page, since every
1117 # page load starts a fresh Apple session with a fresh challenge.
1118 # Overwriting it here would hide that and produce an assertion whose
1119 # clientData disagrees with its challenge field, which Apple rejects
1120 # with an opaque 409. Say so instead.
1121 if issued_challenge:
1122 signed = str(signatures[0].get("challenge") or "")
1123 if _same_challenge(signed, issued_challenge):
1124 for signature in signatures:
1125 signature["challenge"] = issued_challenge
1126 else:
1127 LOGGER.warning(
1128 "Web UI security-key: signed challenge does not match the "
1129 "pending one -- stale page.",
1130 )
1131 with _AUTH_LOCK:
1132 _clear_pending_auth_unlocked()
1133 return (
1134 _render_auth(
1135 message=(
1136 "That signature is for an older challenge. Each time "
1137 "this page loads it starts a new one — reload, copy "
1138 "the command again, and re-sign."
1139 ),
1140 message_kind="err",
1141 ),
1142 400,
1143 )
1145 try:
1146 if not api.confirm_security_key(assertion=signatures[0]):
1147 LOGGER.warning("Web UI security-key: Apple refused the assertion.")
1148 return (
1149 _render_auth(
1150 message=(
1151 "Apple refused that signature. Reload to start a "
1152 "fresh challenge and sign again."
1153 ),
1154 message_kind="err",
1155 ),
1156 400,
1157 )
1159 if ceremony_dir:
1160 _publish_ceremony_session(ceremony_dir)
1161 # Apple accepting the assertion is not proof the sync loop can
1162 # sign in, and claiming success without checking is how a broken
1163 # session got reported as working before.
1164 if not _session_authenticates(username):
1165 LOGGER.warning(
1166 "Web UI security-key: assertion accepted but sign-in still "
1167 "wants a factor.",
1168 )
1169 return (
1170 _render_auth(
1171 message=(
1172 "Apple accepted your key, but sign-in still asks for "
1173 "a second factor. Start over and sign a fresh "
1174 "challenge."
1175 ),
1176 message_kind="err",
1177 ),
1178 400,
1179 )
1180 LOGGER.info("Web UI: security-key re-auth succeeded; session trusted.")
1181 _note_sign_in(username, stale_stored=stale_stored)
1182 _wake_sync_loop()
1183 # The signer clears the clipboard itself once the signature is
1184 # read, so there is nothing left for the dashboard to do here.
1185 return redirect(url_for("dashboard"))
1186 except Exception as e:
1187 LOGGER.exception("Web UI security-key: assertion submit raised")
1188 return (
1189 _render_auth(message=f"Assertion submit failed: {e!s}", message_kind="err"),
1190 400,
1191 )
1192 finally:
1193 _discard_ceremony_dir(ceremony_dir)
1194 with _AUTH_LOCK:
1195 _clear_pending_auth_unlocked()
1197 @app.route("/auth/reset", methods=["POST"])
1198 def auth_reset():
1199 """Escape hatch — clear any in-flight pending-auth state.
1201 Useful when the user closed the tab mid-2FA and wants to start
1202 over without waiting for the in-memory state to expire.
1203 """
1204 rejection = _require_csrf()
1205 if rejection is not None:
1206 return rejection
1208 with _AUTH_LOCK:
1209 _clear_pending_auth_unlocked()
1210 return redirect(url_for("auth_form"))
1212 @app.route("/auth/forget-password", methods=["POST"])
1213 def auth_forget_password():
1214 """Delete the stored password, once the session is shown to work without it.
1216 People who signed in before the sign-in page stopped saving the
1217 password may not want it on disk. Deleting it while the saved
1218 session needs it would stop sync, so the session is tried alone
1219 first, exactly as the password-free sync loop will use it.
1220 """
1221 rejection = _require_csrf()
1222 if rejection is not None:
1223 return rejection
1225 config = _load_current_config()
1226 username = None
1227 if config:
1228 try:
1229 username = config_parser.get_username(config=config)
1230 except (
1231 KeyError,
1232 AttributeError,
1233 TypeError,
1234 ): # pragma: no cover — defensive for hand-malformed configs
1235 username = None
1236 if not username:
1237 return (
1238 _render_auth(
1239 message="No app.credentials.username in config.yaml — set it first.",
1240 message_kind="err",
1241 ),
1242 400,
1243 )
1244 if os.environ.get(ENV_ICLOUD_PASSWORD_KEY):
1245 # The sync loop writes it back every cycle while this is set.
1246 return (
1247 _render_auth(
1248 message="This password comes from ENV_ICLOUD_PASSWORD; remove it there.",
1249 message_kind="err",
1250 ),
1251 400,
1252 )
1253 if not _session_authenticates(username, session_only=True):
1254 return (
1255 _render_auth(
1256 message="Sync still needs the stored password. Sign in again, then remove it.",
1257 message_kind="err",
1258 ),
1259 400,
1260 )
1262 from icloudpy import utils as icloudpy_utils
1264 try:
1265 if _stored_password(username) is not None: # a resubmit finds it gone
1266 icloudpy_utils.delete_password_in_keyring(username)
1267 except Exception as e:
1268 LOGGER.exception("Web UI: keyring delete raised")
1269 return (
1270 _render_auth(
1271 message=f"Could not remove the stored password: {e!s}",
1272 message_kind="err",
1273 ),
1274 500,
1275 )
1276 _note_sign_in(username, stale_stored=None)
1277 LOGGER.info("Web UI: stored password removed; syncing from the saved session")
1278 return _render_auth(
1279 message="Stored password removed.",
1280 message_kind="ok",
1281 )
1283 @app.route("/auth/refresh-trust", methods=["POST"])
1284 def auth_refresh_trust():
1285 """One-tap re-auth that reuses whatever credential the container has.
1287 When Apple's trusted-session lifetime is winding down (or has
1288 already expired since the last sync attempt), this lets the user
1289 kick off a fresh 2FA push without having to retype their
1290 password. Useful for "reset the clock" workflows where the
1291 password didn't change — only the trust window did.
1293 Flow:
1294 1. Look up keyring password by username from config.
1295 2. If absent → carry on without one. ``trust_session`` and the 2FA
1296 push both work from the saved session, so a password-free
1297 container can still use this button; only a session Apple has
1298 already stopped accepting needs a human with a password, and
1299 that case is reported as such.
1300 3. Spin up a transient client, fire the 2FA push if needed, stash
1301 the live session under the same _PENDING_AUTH dict /auth/code
1302 already consumes.
1303 4. Redirect to /auth — UI is now in "enter 6-digit code" mode.
1304 """
1305 rejection = _require_csrf()
1306 if rejection is not None:
1307 return rejection
1309 config = _load_current_config()
1310 username = None
1311 if config:
1312 try:
1313 username = config_parser.get_username(config=config)
1314 except (
1315 KeyError,
1316 AttributeError,
1317 TypeError,
1318 ): # pragma: no cover — defensive for hand-malformed configs
1319 username = None
1320 if not username:
1321 return (
1322 _render_auth(
1323 message="No app.credentials.username in config.yaml — set it first.",
1324 message_kind="err",
1325 ),
1326 400,
1327 )
1329 from icloudpy import exceptions as icloudpy_exceptions
1331 try:
1332 from icloudpy import utils as icloudpy_utils
1334 password = icloudpy_utils.get_password_from_keyring(username)
1335 except icloudpy_exceptions.ICloudPyNoStoredPasswordAvailableException:
1336 # Password-free container. Not an error, and not a reason to
1337 # refuse: the saved session is credential enough for both
1338 # trust_session and the 2FA push.
1339 password = None
1340 except Exception as e:
1341 LOGGER.exception("Web UI: keyring lookup raised")
1342 return (
1343 _render_auth(
1344 message=f"Keyring lookup failed: {e!s}",
1345 message_kind="err",
1346 ),
1347 500,
1348 )
1350 try:
1351 if password is None:
1352 # Session-only: the client refuses to sign in with
1353 # credentials, so a dead session surfaces as the
1354 # no-password exception below rather than a sign-in attempt.
1355 from src import sync
1357 api = sync.get_api_instance(
1358 username=username,
1359 password=None,
1360 server_region=config_parser.get_region(config=config) if config else "global",
1361 )
1362 else:
1363 api = _create_icloud_service(
1364 username=username,
1365 password=password,
1366 cookie_directory=DEFAULT_COOKIE_DIRECTORY,
1367 config=config,
1368 )
1369 except icloudpy_exceptions.ICloudPyNoStoredPasswordAvailableException:
1370 LOGGER.info("Web UI refresh-trust: no password and the saved session is not usable")
1371 return (
1372 _render_auth(
1373 message=(
1374 "The saved session is no longer valid and no password is stored. "
1375 "Enter your Apple ID password below, or run the documented "
1376 "`icloud --username=… --session-directory=…` command to sign in "
1377 "without storing one."
1378 ),
1379 message_kind="err",
1380 ),
1381 400,
1382 )
1383 except Exception as e:
1384 LOGGER.exception("Web UI refresh-trust: ICloudPyService raised")
1385 return (
1386 _render_auth(
1387 message=(
1388 f"Refresh trust failed: {e!s}. The stored password may be out of date — sign in below."
1389 ),
1390 message_kind="err",
1391 ),
1392 400,
1393 )
1395 if not api.requires_2fa:
1396 # Trust window was still alive — nothing to do, sync loop is
1397 # already authenticated. Bounce back to the dashboard with
1398 # the success state.
1399 _wake_sync_loop()
1400 return redirect(url_for("dashboard"))
1402 try:
1403 trigger = getattr(api, "trigger_2fa_push_notification", None)
1404 if callable(trigger):
1405 trigger()
1406 except Exception as e:
1407 LOGGER.warning(f"Web UI refresh-trust 2FA push failed: {e!s}")
1409 with _AUTH_LOCK:
1410 _expire_stale_pending_auth_unlocked()
1411 _PENDING_AUTH["api"] = api
1412 _PENDING_AUTH["username"] = username
1413 # Signed in with the stored password (or none): nothing stale,
1414 # whatever an abandoned earlier sign-in left here.
1415 _PENDING_AUTH["stale_stored"] = None
1416 _PENDING_AUTH["stashed_at"] = time.monotonic()
1417 return redirect(url_for("auth_form"))
1419 @app.route("/api/sync", methods=["POST"])
1420 def api_sync():
1421 """Queue an immediate sync run for one or both services.
1423 ``service=drive`` / ``service=photos`` / ``service=all``. The
1424 web thread can't run sync.sync() directly — it would race with
1425 the existing loop. Instead this touches a sentinel file in
1426 ICLOUD_DOCKER_CONFIG_DIR; ``src.sync`` checks for it at the top
1427 of each loop iteration and resets the countdown when present.
1429 Idempotent: tapping repeatedly while a request is still queued
1430 is a no-op (the sentinel just gets re-touched).
1431 """
1432 rejection = _require_csrf()
1433 if rejection is not None:
1434 return rejection
1436 service = (request.form.get("service") or request.args.get("service") or "").strip().lower()
1437 if service == "all":
1438 wanted = ("drive", "photos")
1439 elif service in ("drive", "photos"):
1440 wanted = (service,)
1441 else:
1442 return (
1443 jsonify({"error": "service must be one of: drive, photos, all"}),
1444 400,
1445 )
1447 # Honour the user's config — only queue services that are
1448 # actually configured. Avoids touching a photos sentinel on a
1449 # drive-only install.
1450 config = _load_current_config()
1451 configured = {svc for svc in ("drive", "photos") if config and svc in config}
1452 if not configured:
1453 return jsonify({"error": "no services configured"}), 400
1455 queued = [svc for svc in wanted if svc in configured and web_signals.request_force_sync(svc)]
1457 # Browser form submit gets a redirect; API consumers (curl,
1458 # monitors) get JSON. Distinguished by Accept header.
1459 if request.headers.get("Accept", "").startswith("application/json"):
1460 return jsonify({"queued": queued})
1461 return redirect(url_for("dashboard"))
1463 @app.route("/settings", methods=["GET"])
1464 def settings_page():
1465 """What this container is configured to do, and where each value
1466 came from. Read-only except for the few keys ``settings_view``
1467 marks editable."""
1468 return _render_settings()
1470 @app.route("/settings", methods=["POST"])
1471 def settings_update():
1472 """Change one editable key in config.yaml."""
1473 rejection = _require_csrf()
1474 if rejection is not None:
1475 return rejection
1476 key = (request.form.get("key") or "").strip()
1477 setting = settings_view.SETTINGS_BY_KEY.get(key)
1478 submitted = request.form.get("value", "")
1479 if setting is not None and setting.kind == "bool" and "value" not in request.form:
1480 # An unchecked checkbox submits nothing.
1481 submitted = "off"
1482 try:
1483 value = settings_view.write_setting(_current_config_path(), key, submitted)
1484 except settings_view.SettingError as e:
1485 return _render_settings(error=str(e)), 400
1486 except Exception as e: # noqa: BLE001 - report, keep the page up
1487 LOGGER.warning(f"Web UI: could not save {key}: {e!s}")
1488 return _render_settings(error=f"Could not save {key}: {e!s}"), 500
1489 LOGGER.info(f"Web UI: set {key} to {value}")
1490 return redirect(url_for("settings_page", saved=key))
1492 return app
1495def _render_settings(error: str | None = None):
1496 """Render the Settings page from a fresh read of config.yaml."""
1497 config = _load_current_config()
1498 # Photos first: it's what most people come here to change.
1499 groups: dict[str, list[dict[str, Any]]] = {name: [] for name in ("Photos", "iCloud Drive", "Notifications")}
1500 for row in settings_view.build_rows(config):
1501 groups.setdefault(row["group"], []).append(row)
1502 saved = request.args.get("saved")
1503 saved_setting = settings_view.SETTINGS_BY_KEY.get(saved or "")
1504 # A change made under Advanced lands back there, open.
1505 advanced_open = bool(error) or bool(saved_setting and saved_setting.key not in settings_view.COMMON)
1506 return render_template(
1507 "settings.html",
1508 config_path=_current_config_path(),
1509 config_loaded=config is not None,
1510 groups=groups,
1511 environment=settings_view.build_environment(),
1512 error=error,
1513 saved_label=f"{saved_setting.group} · {saved_setting.label}" if saved_setting else None,
1514 advanced_open=advanced_open,
1515 active_nav="settings",
1516 version=os.environ.get("APP_VERSION", ""),
1517 csrf_token=_get_csrf_token(),
1518 )
1521_SIGNER_PATH = os.path.join(os.path.dirname(__file__), "icloud_sign.py")
1524def _lookup_auth_method(status_payload: dict[str, Any]) -> str | None:
1525 """Recorded second factor for the configured account, if we've seen one.
1527 Drives which route the auth page leads with: an account Apple has
1528 answered with an ``fsaChallenge`` can never complete the 6-digit
1529 form, so offering it first just wastes the operator's time.
1530 """
1531 username = status_payload.get("username") if status_payload else None
1532 if not username:
1533 return None
1534 try:
1535 from src import web_signals
1537 return web_signals.get_auth_method(username)
1538 except Exception: # pragma: no cover - never break rendering over state
1539 return None
1542def _record_auth_method(username: str, method: str) -> None:
1543 """Persist the account's second factor; never fatal to the auth flow."""
1544 try:
1545 from src import web_signals
1547 web_signals.record_auth_method(username=username, method=method)
1548 except Exception as e: # pragma: no cover - bookkeeping must not break auth
1549 LOGGER.warning(f"Web UI: recording auth method failed: {e!s}")
1552def _pack_challenge(fsa: dict[str, Any]) -> str:
1553 """Pack the challenge + credential handles into one short token.
1555 Length matters: the operator copies this inside a single shell
1556 command. Packing raw bytes (2-byte length prefix each) rather than
1557 base64-of-JSON roughly halves it, and ``rpId`` is dropped entirely
1558 because Apple's is always ``apple.com``.
1559 """
1561 def decode(value: str) -> bytes:
1562 return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
1564 parts = [decode(fsa["challenge"])]
1565 parts.extend(decode(handle) for handle in fsa["keyHandles"])
1566 packed = b"".join(struct.pack("!H", len(part)) + part for part in parts)
1567 return base64.urlsafe_b64encode(packed).decode("ascii").rstrip("=")
1570def _build_signer_command(blob: str) -> str:
1571 """The self-contained form: the signer source travels inside the command.
1573 Piped to ``uv run`` on stdin, so nothing is left on the operator's disk
1574 and the machine holding the key needs no network route back to this
1575 container. Always offered, because the short form below cannot reach a
1576 dashboard that sits behind proxy authentication.
1577 """
1578 try:
1579 with open(_SIGNER_PATH, encoding="utf-8") as handle:
1580 source = handle.read()
1581 except OSError:
1582 return "src/icloud_sign.py is missing from this image."
1583 return f"uv run --quiet - {blob} <<'ICLOUDSIGN'\n{source}ICLOUDSIGN"
1586_SIGNER_REPO_RAW = "https://raw.githubusercontent.com/mandarons/icloud-docker"
1589def _signer_source_ref() -> str | None:
1590 """The release tag this image was built from, e.g. ``v1.29.0``.
1592 Release images are built from ``v*`` tags and carry the version in
1593 ``APP_VERSION``. Development and PR builds (``dev``, ``pr-123``) have no
1594 tag to point at, so they get None.
1595 """
1596 version = os.environ.get("APP_VERSION", "").strip()
1597 if not re.fullmatch(r"\d+\.\d+\.\d+", version):
1598 return None
1599 return f"v{version}"
1602def _build_short_signer_command(blob: str) -> str | None:
1603 """``uv run <signer at this release's tag> <blob>`` -- one line.
1605 Fetched from the public repo at the tag this image was built from:
1606 reachable from any machine (a dashboard behind an auth proxy, as one
1607 accepting an Apple ID password should be, cannot be fetched by uv), and
1608 readable before running. The signer declares its fido2 dependency inline
1609 (PEP 723), so no ``--with`` is needed.
1611 None for a build that is not a release; the self-contained form is then
1612 the only one offered.
1613 """
1614 ref = _signer_source_ref()
1615 if ref is None:
1616 return None
1617 return f"uv run --quiet {_SIGNER_REPO_RAW}/{ref}/src/icloud_sign.py {blob}"
1620def _stored_password(username: str) -> str | None:
1621 """The password stored in the keyring, or None if there isn't one.
1623 icloudpy raises rather than returning None for a missing entry, and a
1624 password-free container is a supported setup, not an error.
1625 """
1626 from icloudpy import exceptions as icloudpy_exceptions
1627 from icloudpy import utils as icloudpy_utils
1629 try:
1630 return icloudpy_utils.get_password_from_keyring(username) or None
1631 except icloudpy_exceptions.ICloudPyNoStoredPasswordAvailableException:
1632 return None
1635def _create_icloud_service(
1636 username: str,
1637 password: str,
1638 cookie_directory: str,
1639 config: dict[str, Any] | None,
1640) -> Any:
1641 """Instantiate ``icloudpy.ICloudPyService`` with region-specific endpoints.
1643 Mirrors ``sync.get_api_instance`` so China-region accounts hit
1644 ``icloud.com.cn`` instead of ``icloud.com`` (which fails with
1645 ``KeyError: 'webservices'``). Kept separate from ``get_api_instance``
1646 because interactive Web UI auth intentionally leaves request timeouts
1647 unbounded and does not need ``photos_require_finished_index``.
1648 """
1649 # Late import so /api/health still works if icloudpy is mid-upgrade.
1650 import icloudpy
1652 region = config_parser.get_region(config=config) if config else "global"
1653 if region == "china":
1654 return icloudpy.ICloudPyService(
1655 apple_id=username,
1656 password=password,
1657 cookie_directory=cookie_directory,
1658 home_endpoint=CHINA_HOME_ENDPOINT,
1659 setup_endpoint=CHINA_SETUP_ENDPOINT,
1660 )
1661 return icloudpy.ICloudPyService(
1662 apple_id=username,
1663 password=password,
1664 cookie_directory=cookie_directory,
1665 )
1668def _session_authenticates(username: str, *, session_only: bool = False) -> bool:
1669 """Confirm the sync loop can now sign in.
1671 Apple accepting the assertion is not the same as the loop being able
1672 to authenticate, and reporting success on the submit alone once
1673 announced a session that still wanted a second factor.
1674 ``session_only`` ignores any stored password, to check the loop could
1675 sign in without one.
1676 """
1677 try:
1678 from src import sync
1680 config = _load_current_config()
1681 # A stored password if the operator opted in to one; otherwise the
1682 # session alone, exactly as the password-free sync loop signs in.
1683 api = sync.get_api_instance(
1684 username=username,
1685 password=None if session_only else _stored_password(username),
1686 cookie_directory=DEFAULT_COOKIE_DIRECTORY,
1687 server_region=config_parser.get_region(config=config) if config else "global",
1688 )
1689 except Exception as e:
1690 LOGGER.warning(f"Web UI: session failed to authenticate: {e!s}")
1691 return False
1692 LOGGER.info(f"Web UI: session check -> requires_2fa={api.requires_2fa}")
1693 return not api.requires_2fa
1696def _same_challenge(left: str, right: str) -> bool:
1697 """Compare two base64 challenge strings by value, not spelling.
1699 Apple emits the standard alphabet unpadded; a round-trip through raw
1700 bytes can come back padded, or urlsafe. Those are the same challenge.
1701 """
1703 def decode(value: str) -> bytes | None:
1704 try:
1705 return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
1706 except (ValueError, TypeError):
1707 return None
1709 decoded = decode(left)
1710 return decoded is not None and decoded == decode(right)
1713def _is_signin_throttled(error: Exception) -> bool:
1714 """True when Apple refused to start a sign-in rather than to finish one.
1716 Apple answers a rate-limited account with 409 on ``/signin/init``, the
1717 very first SRP call, so no challenge can be issued at all. Worth
1718 distinguishing: it is not a bad password, a bad key, or a bad
1719 assertion, and retrying is what prolongs it.
1720 """
1721 text = str(error)
1722 return "signin/init" in text and "409" in text
1725def _ceremony_cookie_dir() -> str:
1726 """A private, empty cookie jar for one security-key ceremony.
1728 icloudpy loads its jar with ``ignore_expires=True``, so cookies from a
1729 dead session are replayed on every new sign-in -- an expired
1730 ``X-APPLE-WEBAUTH-TOKEN`` and friends arriving alongside a fresh SRP
1731 handshake. Apple's reply to that contradiction is 409 Conflict, which
1732 is exactly what the assertion submit kept receiving.
1734 The ceremony therefore runs against its own jar and publishes the
1735 result only once Apple has accepted it.
1736 """
1737 return tempfile.mkdtemp(prefix="icloud-securitykey-")
1740def _publish_ceremony_session(cookie_dir: str) -> None:
1741 """Move a ceremony's session files into the directory sync reads.
1743 Called only after Apple accepts the assertion and the session is
1744 trusted, so a failed attempt can never damage a working session. The
1745 previous files are kept alongside with a ``.bak`` suffix.
1746 """
1747 try:
1748 os.makedirs(DEFAULT_COOKIE_DIRECTORY, exist_ok=True)
1749 for name in os.listdir(cookie_dir):
1750 source = os.path.join(cookie_dir, name)
1751 target = os.path.join(DEFAULT_COOKIE_DIRECTORY, name)
1752 if os.path.exists(target):
1753 shutil.copy2(target, f"{target}.bak")
1754 shutil.copy2(source, target)
1755 LOGGER.info(f"Web UI: published ceremony session to {DEFAULT_COOKIE_DIRECTORY}.")
1756 except OSError:
1757 LOGGER.exception("Web UI: could not publish ceremony session")
1760def _discard_ceremony_dir(cookie_dir: str | None) -> None:
1761 """Remove a ceremony's private jar. Best-effort."""
1762 if cookie_dir:
1763 shutil.rmtree(cookie_dir, ignore_errors=True)
1766def _render_auth(
1767 message: str | None = None,
1768 message_kind: str | None = None,
1769 security_key_blob: str | None = None,
1770):
1771 """Render auth.html with the current pending state and an optional
1772 error/info pill. Factored out so the POST endpoints can reuse it.
1774 ``security_key_blob`` carries the base64 challenge bundle for the
1775 FIDO2 ceremony; when set the template shows the signer instructions
1776 instead of the 6-digit code form."""
1777 from flask import render_template as _render
1779 config = _load_current_config()
1780 status_payload = _build_status(config=config)
1781 with _AUTH_LOCK:
1782 pending = bool(_PENDING_AUTH)
1783 return _render(
1784 "auth.html",
1785 status=status_payload,
1786 pending=pending,
1787 message=message,
1788 message_kind=message_kind,
1789 active_nav="auth",
1790 version=os.environ.get("APP_VERSION", ""),
1791 csrf_token=_get_csrf_token(),
1792 security_key_blob=security_key_blob,
1793 signer_command=_build_signer_command(security_key_blob) if security_key_blob else None,
1794 signer_source_ref=_signer_source_ref(),
1795 signer_command_short=(
1796 _build_short_signer_command(security_key_blob)
1797 if security_key_blob
1798 else None
1799 ),
1800 auth_method=_lookup_auth_method(status_payload),
1801 trust_until=_month_day(status_payload.get("trust_expires_at")),
1802 )
1805def _month_day(iso: str | None) -> str | None:
1806 """``2027-02-02T…`` -> ``Feb 2`` (with the year when it isn't this one)."""
1807 import datetime
1809 if not iso:
1810 return None
1811 try:
1812 when = datetime.datetime.fromisoformat(iso)
1813 except ValueError:
1814 return None
1815 text = f"{when:%b} {when.day}"
1816 return text if when.year == datetime.date.today().year else f"{text}, {when.year}"
1819def start_in_thread(
1820 host: str = "127.0.0.1",
1821 port: int = 8080,
1822) -> threading.Thread:
1823 """Launch the Flask app on a daemon thread.
1825 The main sync loop owns the process; the web thread dies when the
1826 parent process exits. Returns the thread, or ``None`` if the port
1827 could not be bound (the sync loop continues regardless).
1829 Uses ``werkzeug.serving.make_server`` rather than ``Flask.run()``:
1830 binding happens synchronously here so a port conflict is reported
1831 as an error instead of a false "listening" line, and it avoids the
1832 dev-server banner. Deliberately dependency-free (no gunicorn) --
1833 this is a single-user, behind-a-proxy operator console (default
1834 host 127.0.0.1), not a public-facing API.
1835 """
1836 app = create_app()
1838 # Bind in the main thread so the "listening" log is truthful: a port
1839 # conflict raises here and is reported as a failure, instead of the
1840 # old optimistic log racing a background bind error.
1841 try:
1842 server = make_server(host, port, app, threaded=True)
1843 except OSError as e:
1844 LOGGER.error(f"Web UI failed to bind {host}:{port} — {e!s}")
1845 return None
1847 def _serve_bound():
1848 try:
1849 server.serve_forever()
1850 except Exception as e: # noqa: BLE001 -- daemon thread, never crash the sync loop
1851 LOGGER.error(f"Web UI server stopped: {e!s}")
1853 thread = threading.Thread(target=_serve_bound, name="icloud-web-ui", daemon=True)
1854 thread.start()
1855 LOGGER.info(f"Web UI listening on http://{host}:{port}/ (host={host}, port={port})")
1856 return thread