organum-backup 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ {
2
+ "schema": "organum.backup.profile/v1",
3
+ "profile_id": "personal-files",
4
+ "device_id": "mac-primary",
5
+ "source_roots": [
6
+ "/Users/example/Documents"
7
+ ],
8
+ "exclude_patterns": [
9
+ "**/node_modules/**",
10
+ "**/.venv/**",
11
+ "**/__pycache__/**",
12
+ "**/.DS_Store"
13
+ ],
14
+ "downloaded_model_roots": [],
15
+ "repository": {
16
+ "kind": "local",
17
+ "location": "/Users/example/BackupTestRepository"
18
+ },
19
+ "schedule": {
20
+ "enabled": false,
21
+ "interval_hours": 24,
22
+ "local_time": "03:00",
23
+ "on_battery": "defer",
24
+ "catch_up": true
25
+ },
26
+ "transfer": {
27
+ "upload_kib_per_second": 10240
28
+ },
29
+ "retention": {
30
+ "automatic_delete": false,
31
+ "keep_daily": 30,
32
+ "keep_weekly": 12,
33
+ "keep_monthly": 12
34
+ },
35
+ "credentials": {
36
+ "password_provider": "macos-keychain",
37
+ "keychain_service": "jj.personal-backup",
38
+ "keychain_account": "personal-files"
39
+ },
40
+ "engine": {
41
+ "restic_binary": null,
42
+ "rclone_binary": null
43
+ }
44
+ }
@@ -0,0 +1,3 @@
1
+ """organum-backup - encrypted, restorable snapshots of the places agent state lives (restic + your own rclone remote)."""
2
+
3
+ __version__ = "0.4.0"
@@ -0,0 +1,480 @@
1
+ #!/usr/bin/env python3
2
+ """Fixed-profile, loopback-only UI bridge for the backup operator.
3
+
4
+ Security boundary (docs/design-desk-bootstrap.md):
5
+ - GET / never carries the session secret or bootstrap token.
6
+ - Startup prints a single-use bootstrap code to stdout (valid 120s, max 5 tries).
7
+ - POST /bootstrap exchanges that code once for the in-memory session secret.
8
+ - Idle exit after 15 minutes with no accepted request (held while a job runs).
9
+ - Real engine execution is disabled unless started with --allow-execute
10
+ (alias --allow-real-execution). --demo uses only a generated synthetic profile
11
+ and injected fake engine/key; it can never write a real backup success state.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import hmac
18
+ import json
19
+ import re
20
+ import secrets
21
+ import sys
22
+ import tempfile
23
+ import threading
24
+ import time
25
+ from datetime import datetime, timezone
26
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27
+ from pathlib import Path
28
+ from typing import Any, Callable
29
+
30
+ from organum_backup import backup_operator as engine
31
+ from organum_backup.profile_contract import BackupError, load_profile
32
+
33
+ HERE = Path(__file__).resolve().parent
34
+ HTML = HERE / "backup_desk.html"
35
+ EXAMPLE = HERE / "PROFILE_EXAMPLE.json"
36
+ MAX_BODY = 4096
37
+ ACTIONS = {"init", "backup", "snapshots", "restore"}
38
+ HEX64 = re.compile(r"[0-9a-f]{64}\Z")
39
+ JOB_ID = re.compile(r"[0-9a-f]{32}\Z")
40
+ # The page and the bridge ship together, so these are new names only (docs/design-rename.md, point 4).
41
+ STATUS_SCHEMA, JOB_SCHEMA = "organum.backup.bridge-status/v1", "organum.backup.bridge-job/v1"
42
+ SERVER_NAME = "OrganumBackupBridge/1"
43
+ BOOTSTRAP_TTL_SECONDS = 120.0
44
+ IDLE_TIMEOUT_SECONDS = 900.0
45
+ MAX_BOOTSTRAP_FAILURES = 5
46
+
47
+
48
+ class BridgeError(ValueError):
49
+ def __init__(self, code: str, status: int = 400):
50
+ super().__init__(code)
51
+ self.code = code
52
+ self.status = status
53
+
54
+
55
+ def _unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
56
+ result: dict[str, Any] = {}
57
+ for key, value in pairs:
58
+ if key in result or key in ("__proto__", "constructor", "prototype"):
59
+ raise ValueError("duplicate or unsafe key")
60
+ result[key] = value
61
+ return result
62
+
63
+
64
+ def strict_body(raw: bytes) -> dict[str, Any]:
65
+ if not 0 < len(raw) <= MAX_BODY:
66
+ raise BridgeError("BODY_SIZE_INVALID", 413)
67
+ try:
68
+ value = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique,
69
+ parse_constant=lambda _: (_ for _ in ()).throw(ValueError("nonfinite")))
70
+ except (UnicodeError, ValueError, RecursionError) as error:
71
+ raise BridgeError("BODY_JSON_INVALID") from error
72
+ if not isinstance(value, dict):
73
+ raise BridgeError("BODY_SCHEMA_INVALID")
74
+ return value
75
+
76
+
77
+ def _demo_runner(argv: list[str], env: dict[str, str]) -> engine.EngineResult:
78
+ if argv[-1] == "version":
79
+ name = "rclone" if "rclone" in Path(argv[0]).name else "restic"
80
+ return engine.EngineResult(0, name + " 0.19.1 synthetic\n")
81
+ time.sleep(0.8) # visible queued/running state; no external operation
82
+ sid = "a" * 64
83
+ if "backup" in argv:
84
+ return engine.EngineResult(0, json.dumps({"message_type": "summary", "snapshot_id": sid,
85
+ "files_new": 1, "files_changed": 0, "data_added": 14}))
86
+ if "snapshots" in argv:
87
+ return engine.EngineResult(0, json.dumps([{"id": sid, "time": datetime.now(timezone.utc).isoformat()}]))
88
+ if "restore" in argv:
89
+ return engine.EngineResult(0, json.dumps({"message_type": "summary", "files_restored": 1,
90
+ "bytes_restored": 14}))
91
+ return engine.EngineResult(0, json.dumps({"message_type": "initialized", "id": sid}))
92
+
93
+
94
+ class Bridge:
95
+ def __init__(self, profile_path: Path, *, demo: bool = False, allow_real: bool = False,
96
+ rclone_config: str | None = None,
97
+ runner: Callable | None = None, password_provider: Callable | None = None,
98
+ clock: Callable[[], float] = time.monotonic,
99
+ bootstrap_ttl: float = BOOTSTRAP_TTL_SECONDS,
100
+ idle_timeout: float = IDLE_TIMEOUT_SECONDS,
101
+ max_bootstrap_failures: int = MAX_BOOTSTRAP_FAILURES):
102
+ self.profile_path = profile_path.absolute()
103
+ self.profile, self.digest = load_profile(self.profile_path)
104
+ self.demo = demo
105
+ self.allow_real = allow_real and not demo
106
+ self.rclone_config = rclone_config
107
+ self.runner = runner if runner is not None else _demo_runner if demo else None
108
+ self.password_provider = password_provider if password_provider is not None else (lambda _: "synthetic-not-a-key") if demo else None
109
+ if demo and (self.runner is None or self.password_provider is None):
110
+ raise BridgeError("DEMO_INJECTION_REQUIRED")
111
+ if not demo and (runner is not None or password_provider is not None):
112
+ raise BridgeError("REAL_MODE_INJECTION_REFUSED")
113
+ self.bootstrap_token = secrets.token_urlsafe(32)
114
+ self.session_secret = secrets.token_urlsafe(32)
115
+ self.challenge = secrets.token_hex(16)
116
+ self.clock = clock
117
+ self.bootstrap_ttl = float(bootstrap_ttl)
118
+ self.idle_timeout = float(idle_timeout)
119
+ self.max_bootstrap_failures = int(max_bootstrap_failures)
120
+ self.started_at = self.clock()
121
+ self.last_activity = self.started_at
122
+ self.bootstrap_used = False
123
+ self.bootstrap_failures = 0
124
+ self.shutdown_requested = threading.Event()
125
+ self.guard = threading.Lock()
126
+ self.job: dict[str, Any] | None = None
127
+
128
+ def touch(self) -> None:
129
+ with self.guard:
130
+ self.last_activity = self.clock()
131
+
132
+ def is_idle(self) -> bool:
133
+ with self.guard:
134
+ if self.job is not None and self.job["phase"] in ("queued", "running"):
135
+ return False
136
+ return (self.clock() - self.last_activity) >= self.idle_timeout
137
+
138
+ def bootstrap(self, body: dict[str, Any]) -> dict[str, Any]:
139
+ if not isinstance(body, dict) or set(body) != {"token"} or not isinstance(body["token"], str):
140
+ raise BridgeError("BODY_SCHEMA_INVALID")
141
+ token = body["token"]
142
+ with self.guard:
143
+ if self.shutdown_requested.is_set():
144
+ raise BridgeError("BOOTSTRAP_LOCKED", 403)
145
+ if self.bootstrap_used:
146
+ self.bootstrap_failures += 1
147
+ if self.bootstrap_failures >= self.max_bootstrap_failures:
148
+ self.shutdown_requested.set()
149
+ raise BridgeError("BOOTSTRAP_LOCKED", 403)
150
+ raise BridgeError("BOOTSTRAP_USED", 403)
151
+ now = self.clock()
152
+ if (now - self.started_at) > self.bootstrap_ttl:
153
+ self.bootstrap_failures += 1
154
+ if self.bootstrap_failures >= self.max_bootstrap_failures:
155
+ self.shutdown_requested.set()
156
+ raise BridgeError("BOOTSTRAP_LOCKED", 403)
157
+ raise BridgeError("BOOTSTRAP_EXPIRED", 403)
158
+ if not token.isascii() or not hmac.compare_digest(token, self.bootstrap_token):
159
+ self.bootstrap_failures += 1
160
+ if self.bootstrap_failures >= self.max_bootstrap_failures:
161
+ self.shutdown_requested.set()
162
+ raise BridgeError("BOOTSTRAP_LOCKED", 403)
163
+ raise BridgeError("BOOTSTRAP_REFUSED", 403)
164
+ self.bootstrap_used = True
165
+ self.last_activity = now
166
+ return {"session": self.session_secret}
167
+
168
+ def status(self) -> dict[str, Any]:
169
+ try:
170
+ _, current = load_profile(self.profile_path)
171
+ unchanged = current == self.digest
172
+ except (BackupError, OSError):
173
+ unchanged = False
174
+ state_summary: dict[str, Any] = {"last_success_at": None, "last_error_code": None}
175
+ if unchanged and not self.demo:
176
+ try:
177
+ state_path, _ = engine.state_paths(self.profile_path, self.profile)
178
+ state = engine.read_state(state_path, self.profile, engine.now_iso())
179
+ state_summary = {"last_success_at": state["last_success_at"],
180
+ "last_error_code": state["last_error_code"]}
181
+ except (BackupError, OSError):
182
+ state_summary = {"last_success_at": None, "last_error_code": "STATE_UNAVAILABLE"}
183
+ profile = {k: v for k, v in self.profile.items() if not k.startswith("_")}
184
+ with self.guard:
185
+ active = self.job is not None and self.job["phase"] in ("queued", "running")
186
+ challenge = self.challenge
187
+ latest_job_id = self.job["id"] if self.job is not None else None
188
+ return {"schema": STATUS_SCHEMA, "mode": "synthetic_demo" if self.demo else "local_operator",
189
+ "real_execution_enabled": self.allow_real, "profile": profile,
190
+ "profile_sha256": self.digest, "profile_unchanged": unchanged,
191
+ "state": state_summary, "active_job": active, "challenge": challenge,
192
+ "latest_job_id": latest_job_id,
193
+ "demo_restore_parent": str(self.profile_path.parent) if self.demo else None,
194
+ "real_backup_observed_by_bridge": False}
195
+
196
+ def job_status(self, job_id: str) -> dict[str, Any]:
197
+ if not JOB_ID.fullmatch(job_id):
198
+ raise BridgeError("JOB_NOT_FOUND", 404)
199
+ with self.guard:
200
+ if self.job is None or self.job["id"] != job_id:
201
+ raise BridgeError("JOB_NOT_FOUND", 404)
202
+ return dict(self.job)
203
+
204
+ def admit(self, body: dict[str, Any]) -> dict[str, Any]:
205
+ if not self.demo and not self.allow_real:
206
+ raise BridgeError("REAL_EXECUTION_DISABLED", 403)
207
+ if not isinstance(body, dict):
208
+ raise BridgeError("BODY_SCHEMA_INVALID")
209
+ action = body.get("action")
210
+ if not isinstance(action, str) or action not in ACTIONS:
211
+ raise BridgeError("ACTION_INVALID")
212
+ keys = {"action", "profile_sha256", "confirmation", "challenge"}
213
+ if action == "restore":
214
+ keys |= {"snapshot", "target"}
215
+ if set(body) != keys:
216
+ raise BridgeError("BODY_SCHEMA_INVALID")
217
+ if body["profile_sha256"] != self.digest:
218
+ raise BridgeError("PROFILE_DIGEST_MISMATCH", 409)
219
+ try:
220
+ _, current = load_profile(self.profile_path)
221
+ except (BackupError, OSError) as error:
222
+ raise BridgeError("PROFILE_UNAVAILABLE", 409) from error
223
+ if current != self.digest:
224
+ raise BridgeError("PROFILE_CHANGED", 409)
225
+ phrase = "RUN " + action.upper() + " " + self.profile["profile_id"]
226
+ if body["confirmation"] != phrase:
227
+ raise BridgeError("CONFIRMATION_REQUIRED", 403)
228
+ if action == "restore":
229
+ if not isinstance(body["snapshot"], str) or not HEX64.fullmatch(body["snapshot"]):
230
+ raise BridgeError("SNAPSHOT_ID_INVALID")
231
+ if not isinstance(body["target"], str) or not 0 < len(body["target"]) <= 1024:
232
+ raise BridgeError("RESTORE_TARGET_INVALID")
233
+ if self.demo:
234
+ candidate = Path(body["target"])
235
+ if candidate.parent != self.profile_path.parent or not candidate.name.startswith("synthetic-restore-"):
236
+ raise BridgeError("DEMO_RESTORE_TARGET_REFUSED", 403)
237
+ # Let the operator enforce path, nesting and no-overwrite.
238
+ with self.guard:
239
+ if self.job is not None and self.job["phase"] in ("queued", "running"):
240
+ raise BridgeError("DUPLICATE_JOB", 409)
241
+ if body["challenge"] != self.challenge:
242
+ raise BridgeError("CHALLENGE_EXPIRED", 409)
243
+ self.challenge = secrets.token_hex(16)
244
+ job_id = secrets.token_hex(16)
245
+ self.last_activity = self.clock()
246
+ self.job = {"schema": JOB_SCHEMA, "id": job_id,
247
+ "action": action, "phase": "queued", "mode": "synthetic_demo" if self.demo else "local_operator",
248
+ "receipt": None, "error_code": None}
249
+ worker = threading.Thread(target=self._work, args=(job_id, body), daemon=True)
250
+ worker.start()
251
+ return {"job_id": job_id, "phase": "queued", "mode": "synthetic_demo" if self.demo else "local_operator"}
252
+
253
+ def _work(self, job_id: str, body: dict[str, Any]) -> None:
254
+ with self.guard:
255
+ if self.job is None or self.job["id"] != job_id:
256
+ return
257
+ self.job["phase"] = "running"
258
+ try:
259
+ receipt = engine.execute(
260
+ self.profile_path, body["action"], approved=True,
261
+ snapshot=body.get("snapshot"), target=body.get("target"),
262
+ rclone_config=self.rclone_config,
263
+ runner=self.runner, password_provider=self.password_provider,
264
+ test_mode=self.demo, expected_profile_sha256=self.digest,
265
+ )
266
+ if self.demo and receipt.get("status") != "test_only":
267
+ raise BridgeError("DEMO_RECEIPT_INVALID")
268
+ if not self.demo and receipt.get("status") == "test_only":
269
+ raise BridgeError("REAL_RECEIPT_INVALID")
270
+ error_code = receipt.get("error_code")
271
+ except BackupError as error:
272
+ receipt, error_code = None, error.code
273
+ except Exception:
274
+ receipt, error_code = None, "BRIDGE_JOB_FAILED"
275
+ with self.guard:
276
+ if self.job is not None and self.job["id"] == job_id:
277
+ self.job.update(phase="finished", receipt=receipt, error_code=error_code)
278
+ self.last_activity = self.clock()
279
+
280
+
281
+ class LoopbackServer(ThreadingHTTPServer):
282
+ daemon_threads = True
283
+ allow_reuse_address = False
284
+
285
+
286
+ def make_handler(bridge: Bridge) -> type[BaseHTTPRequestHandler]:
287
+ class Handler(BaseHTTPRequestHandler):
288
+ server_version = SERVER_NAME
289
+ sys_version = ""
290
+
291
+ def setup(self) -> None:
292
+ super().setup()
293
+ self.connection.settimeout(5)
294
+
295
+ def log_message(self, *_args: Any) -> None:
296
+ pass # never log the session, token, paths, request body or engine output
297
+
298
+ def _origin(self) -> str:
299
+ return f"http://127.0.0.1:{self.server.server_port}"
300
+
301
+ def _guard(self, *, mutation: bool, auth: bool) -> None:
302
+ if self.client_address[0] != "127.0.0.1":
303
+ raise BridgeError("LOOPBACK_ONLY", 403)
304
+ if "?" in self.path:
305
+ raise BridgeError("QUERY_REFUSED", 400)
306
+ hosts = self.headers.get_all("Host", [])
307
+ if hosts != [f"127.0.0.1:{self.server.server_port}"]:
308
+ raise BridgeError("HOST_REFUSED", 403)
309
+ origins = self.headers.get_all("Origin", [])
310
+ if (mutation and origins != [self._origin()]) or (not mutation and origins and origins != [self._origin()]):
311
+ raise BridgeError("ORIGIN_REFUSED", 403)
312
+ fetch_site = self.headers.get("Sec-Fetch-Site")
313
+ if fetch_site not in (None, "none", "same-origin"):
314
+ raise BridgeError("SITE_REFUSED", 403)
315
+ if auth:
316
+ tokens = self.headers.get_all("X-Bridge-Session", [])
317
+ if (len(tokens) != 1 or not tokens[0].isascii()
318
+ or not hmac.compare_digest(tokens[0], bridge.session_secret)):
319
+ raise BridgeError("SESSION_REFUSED", 403)
320
+
321
+ def _read_json_body(self) -> dict[str, Any]:
322
+ if self.headers.get("Transfer-Encoding") is not None:
323
+ raise BridgeError("BODY_FRAMING_INVALID")
324
+ ctype = self.headers.get("Content-Type", "").lower().replace(" ", "")
325
+ if ctype not in ("application/json", "application/json;charset=utf-8"):
326
+ raise BridgeError("CONTENT_TYPE_REFUSED", 415)
327
+ lengths = self.headers.get_all("Content-Length", [])
328
+ if len(lengths) != 1 or not lengths[0].isdigit() or not 0 < int(lengths[0]) <= MAX_BODY:
329
+ raise BridgeError("BODY_SIZE_INVALID", 413)
330
+ return strict_body(self.rfile.read(int(lengths[0])))
331
+
332
+ def _headers(self, status: int, mime: str, size: int) -> None:
333
+ self.send_response(status)
334
+ self.send_header("Content-Type", mime)
335
+ self.send_header("Content-Length", str(size))
336
+ self.send_header("Cache-Control", "no-store")
337
+ self.send_header("X-Content-Type-Options", "nosniff")
338
+ self.send_header("X-Frame-Options", "DENY")
339
+ self.send_header("Referrer-Policy", "no-referrer")
340
+ self.send_header("Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
341
+ self.end_headers()
342
+
343
+ def _json(self, status: int, value: dict[str, Any]) -> None:
344
+ payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
345
+ self._headers(status, "application/json; charset=utf-8", len(payload))
346
+ self.wfile.write(payload)
347
+
348
+ def _error(self, error: BridgeError) -> None:
349
+ self._json(error.status, {"status": "blocked", "error_code": error.code})
350
+
351
+ def _maybe_shutdown(self) -> None:
352
+ if bridge.shutdown_requested.is_set() and hasattr(self.server, "shutdown"):
353
+ threading.Thread(target=self.server.shutdown, daemon=True).start()
354
+
355
+ def do_GET(self) -> None:
356
+ try:
357
+ self._guard(mutation=False, auth=self.path != "/")
358
+ if self.path == "/":
359
+ payload = HTML.read_bytes()
360
+ if b"__BRIDGE_SESSION__" in payload:
361
+ raise BridgeError("HTML_TEMPLATE_INVALID", 500)
362
+ self._headers(200, "text/html; charset=utf-8", len(payload))
363
+ self.wfile.write(payload)
364
+ elif self.path == "/api/status":
365
+ bridge.touch()
366
+ self._json(200, bridge.status())
367
+ elif self.path.startswith("/api/job/"):
368
+ bridge.touch()
369
+ self._json(200, bridge.job_status(self.path[len("/api/job/"):]))
370
+ else:
371
+ raise BridgeError("NOT_FOUND", 404)
372
+ except BridgeError as error:
373
+ self._error(error)
374
+ except OSError:
375
+ self._error(BridgeError("LOCAL_READ_FAILED", 500))
376
+
377
+ def do_POST(self) -> None:
378
+ try:
379
+ if self.path == "/bootstrap":
380
+ self._guard(mutation=True, auth=False)
381
+ body = self._read_json_body()
382
+ self._json(200, bridge.bootstrap(body))
383
+ return
384
+ self._guard(mutation=True, auth=True)
385
+ if self.path != "/api/jobs":
386
+ raise BridgeError("NOT_FOUND", 404)
387
+ body = self._read_json_body()
388
+ bridge.touch()
389
+ self._json(202, bridge.admit(body))
390
+ except BridgeError as error:
391
+ self._error(error)
392
+ self._maybe_shutdown()
393
+
394
+ def do_OPTIONS(self) -> None:
395
+ self._error(BridgeError("METHOD_REFUSED", 405))
396
+
397
+ def do_HEAD(self) -> None:
398
+ self._error(BridgeError("METHOD_REFUSED", 405))
399
+
400
+ return Handler
401
+
402
+
403
+ def make_server(bridge: Bridge) -> LoopbackServer:
404
+ return LoopbackServer(("127.0.0.1", 0), make_handler(bridge))
405
+
406
+
407
+ def _start_watchdog(bridge: Bridge, server: LoopbackServer, stop: threading.Event, interval: float = 0.5) -> threading.Thread:
408
+ def watch() -> None:
409
+ while not stop.wait(interval):
410
+ if bridge.shutdown_requested.is_set() or bridge.is_idle():
411
+ server.shutdown()
412
+ return
413
+ thread = threading.Thread(target=watch, daemon=True)
414
+ thread.start()
415
+ return thread
416
+
417
+
418
+ def _demo_profile(root: Path) -> Path:
419
+ source = root / "synthetic-source"
420
+ source.mkdir()
421
+ (source / "synthetic-only.txt").write_text("synthetic fixture; not a personal file\n", encoding="utf-8")
422
+ profile = json.loads(EXAMPLE.read_text(encoding="utf-8"))
423
+ profile["profile_id"] = "synthetic-demo"
424
+ profile["device_id"] = "demo-mac"
425
+ profile["source_roots"] = [str(source)]
426
+ profile["repository"] = {"kind": "local", "location": str(root / "synthetic-repository")}
427
+ profile["engine"] = {"restic_binary": sys.executable, "rclone_binary": sys.executable}
428
+ path = root / "synthetic-profile.json"
429
+ path.write_text(json.dumps(profile, ensure_ascii=False), encoding="utf-8")
430
+ return path
431
+
432
+
433
+ def main(argv: list[str] | None = None) -> int:
434
+ parser = argparse.ArgumentParser(description=__doc__)
435
+ parser.add_argument("--profile", type=Path, help="fixed absolute profile file for this server session")
436
+ parser.add_argument("--demo", action="store_true", help="generated temporary synthetic profile and fake engine only")
437
+ parser.add_argument("--allow-execute", "--allow-real-execution", dest="allow_real_execution", action="store_true",
438
+ help="enable real engine execution from the desk (off by default)")
439
+ parser.add_argument("--rclone-config", help="fixed server-side explicit config path; never sent by browser")
440
+ args = parser.parse_args(argv)
441
+ if args.demo and (args.profile or args.allow_real_execution or args.rclone_config):
442
+ parser.error("--demo cannot be combined with a profile, real execution, or rclone config")
443
+ if not args.demo and (not args.profile or not args.profile.is_absolute()):
444
+ parser.error("real-profile mode requires a fixed absolute --profile")
445
+ try:
446
+ with tempfile.TemporaryDirectory(prefix="synthetic-backup-bridge-", dir="/private/tmp") if args.demo else _no_temp() as temp:
447
+ profile_path = _demo_profile(Path(temp)) if args.demo else args.profile
448
+ bridge = Bridge(profile_path, demo=args.demo, allow_real=args.allow_real_execution,
449
+ rclone_config=args.rclone_config)
450
+ try:
451
+ server = make_server(bridge)
452
+ except PermissionError as error:
453
+ raise BridgeError("LOOPBACK_BIND_REFUSED", 500) from error
454
+ except OSError as error:
455
+ raise BridgeError("LOOPBACK_BIND_FAILED", 500) from error
456
+ stop = threading.Event()
457
+ _start_watchdog(bridge, server, stop)
458
+ try:
459
+ print(f"Local-only {'SYNTHETIC DEMO' if args.demo else 'operator'}: http://127.0.0.1:{server.server_port}/", flush=True)
460
+ print(f"One-time desk code (valid {int(bridge.bootstrap_ttl)}s, paste in browser): {bridge.bootstrap_token}", flush=True)
461
+ server.serve_forever(poll_interval=0.1)
462
+ finally:
463
+ stop.set()
464
+ server.server_close()
465
+ except (BackupError, BridgeError, OSError) as error:
466
+ print(json.dumps({"status": "blocked", "error_code": getattr(error, "code", "LOCAL_IO_ERROR")}), file=sys.stderr)
467
+ return 2
468
+ return 0
469
+
470
+
471
+ class _no_temp:
472
+ def __enter__(self) -> None:
473
+ return None
474
+
475
+ def __exit__(self, *_args: Any) -> None:
476
+ return None
477
+
478
+
479
+ if __name__ == "__main__":
480
+ raise SystemExit(main())