Add CLI for managing SFTP recording backups
Android checks / cli (push) Canceled after 0s
Android checks / verify (push) Canceled after 0s

This commit is contained in:
Meghdad committed 2026-10-16 16:04:53 +03:30
1 parent 27cf823959
commit 8588c2f3ad
21 files changed
+1732 -2

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
"""Remember backup CLI. No watch, account, or application config file required."""
__version__ = "0.1.0"
+3
View File
@@ -0,0 +1,3 @@
from .cli import main
raise SystemExit(main())
+358
View File
@@ -0,0 +1,358 @@
"""The `remember` command. All destinations are explicit; no remembered server/config file."""
import argparse
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
import paramiko
from . import __version__
from .model import Error, date, duration, safe
from .repository import Repository, download
from .store import Source, Store
def parser():
common = argparse.ArgumentParser(add_help=False)
for flags, kwargs in [
(("-P", "--port"), dict(type=int, help="SSH port (like scp -P)")),
(("-i", "--identity"), dict(help="SSH private-key file; otherwise use SSH agent/default keys")),
(("--host-key",), dict(help="verified SHA256:... host fingerprint instead of known_hosts")),
(("--known-hosts",), dict(help="OpenSSH known_hosts file (default: ~/.ssh/known_hosts)")),
(("--password",), dict(action="store_true", help="prompt for an SSH password (never place it in arguments)")),
(("--ask-passphrase",), dict(action="store_true", help="prompt for an encrypted private key's passphrase")),
(("--timeout",), dict(type=int, help="connection and socket timeout in seconds (default: 30)")),
(("--json",), dict(action="store_true", help="machine-readable JSON on stdout; diagnostics on stderr")),
]:
common.add_argument(*flags, default=argparse.SUPPRESS, **kwargs)
root = argparse.ArgumentParser(prog="remember", parents=[common], description="Work with Remember backups over SFTP or on disk. No application config file required.",
epilog="Example: remember ls user@server:/backups/remember --search meeting\nRemote paths also accept sftp://user@host:2222/path and [user@][IPv6]:/path.",
formatter_class=argparse.RawDescriptionHelpFormatter)
root.add_argument("--version", action="version", version=f"remember-backup {__version__}")
commands = root.add_subparsers(dest="command", required=True)
def command(name, help, aliases=()):
child = commands.add_parser(name, aliases=aliases, parents=[common], help=help, description=help)
child.add_argument("source", metavar="SOURCE", help="[user@]host:/backup/root, SSH URL, or local directory")
return child
def filters(child):
child.add_argument("--search", help="case-insensitive title/ID search")
child.add_argument("--since", type=parse_date, help="created on/after this UTC date or ISO timestamp")
child.add_argument("--until", type=parse_date, help="created before this UTC date or ISO timestamp (exclusive)" )
child.add_argument("--marked", action="store_true", help="only recordings with bookmarks")
child.add_argument("--sort", choices=["created", "title", "duration", "bytes"], default="created")
child.add_argument("--reverse", action="store_true", help="reverse the default sort (created: newest first)")
child.add_argument("--limit", type=positive, help="maximum number of matched recordings")
filters(command("ls", "List and search completed recordings", aliases=["list"]))
filters(command("stats", "Summarize completed recordings, audio bytes, time, and bookmarks"))
child = command("info", "Show metadata, SHA-256, and bookmarks", aliases=["stat"])
child.add_argument("id", help="full recording ID or unambiguous prefix; 'latest' selects newest")
child = command("marks", "Show a recording's bookmarks as timestamps")
child.add_argument("id")
child = command("get", "Download selected audio + metadata; verify before publishing", aliases=["cp"])
child.add_argument("ids", nargs="+", help="recording IDs/prefixes or latest")
child.add_argument("-o", "--output", required=True, metavar="DIRECTORY")
transfer_options(child)
child = command("sync", "Incrementally download backups; never propagate server deletions locally")
child.add_argument("output", metavar="DIRECTORY")
filters(child); transfer_options(child)
child = command("verify", "Read audio and check every size and SHA-256 (uses download bandwidth)", aliases=["check"])
child.add_argument("ids", nargs="*", help="IDs/prefixes; omit to verify every completed recording")
command("doctor", "Report invalid manifests, missing/orphaned audio, uploads, and damaged trash")
child = command("play", "Verify a temporary local copy, then play with ffplay, mpv, or afplay")
child.add_argument("id")
child.add_argument("--player", help="blocking player command, e.g. 'mpv --no-video'; no shell is used")
child = command("rename", "Rename a backup's title in metadata; never rename its stable file ID")
child.add_argument("id"); child.add_argument("title")
child.add_argument("--dry-run", action="store_true")
child = command("rm", "Move selected backups to server-side trash (reversible)", aliases=["remove"])
child.add_argument("ids", nargs="+")
child.add_argument("-y", "--yes", action="store_true", help="confirm the explicitly selected recordings without prompting")
child.add_argument("--dry-run", action="store_true")
command("trash", "List recoverable trash entries, including interrupted moves")
child = command("restore", "Restore a trash entry, verify its audio, and refuse existing-file conflicts")
child.add_argument("id", help="trash ID or unambiguous prefix")
child.add_argument("--dry-run", action="store_true")
child = command("purge", "Permanently delete explicitly selected trash entries; cannot be undone")
child.add_argument("ids", nargs="+", help="trash IDs/prefixes (no implicit 'all')")
child.add_argument("-y", "--yes", action="store_true")
child.add_argument("--dry-run", action="store_true")
return root
def positive(value):
try:
result = int(value)
if result > 0:
return result
except ValueError:
pass
raise argparse.ArgumentTypeError("must be a positive integer")
def parse_date(value):
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
return int(parsed.replace(tzinfo=timezone.utc).timestamp() * 1000) if parsed.tzinfo is None else int(parsed.timestamp() * 1000)
except (ValueError, OverflowError) as exc:
raise argparse.ArgumentTypeError("use YYYY-MM-DD or an ISO timestamp") from exc
def transfer_options(child):
child.add_argument("--force", action="store_true", help="replace differing local audio only after successful verification")
child.add_argument("--no-resume", action="store_true", help="restart this tool's partial downloads from zero")
child.add_argument("--dry-run", action="store_true", help="show selected transfers without writing local files")
def selected(clips, selectors):
result = []
for selector in selectors:
if selector == "latest":
matches = clips[:1]
else:
if not re.fullmatch(r"[a-fA-F0-9-]{4,36}", selector):
raise Error("Use a full recording ID, a prefix of at least four characters, or latest")
exact = [clip for clip in clips if clip.id == selector]
matches = exact or [clip for clip in clips if clip.id.lower().startswith(selector.lower())]
if len(matches) != 1:
raise Error(f"{safe(selector)}: {'ambiguous prefix; use more of the ID' if matches else 'no completed recording found'}")
if matches[0].id not in {clip.id for clip in result}:
result.append(matches[0])
return result
def filtered(clips, args):
result = [clip for clip in clips if
(not args.search or args.search.casefold() in (clip.title + " " + clip.id).casefold()) and
(args.since is None or clip.raw["created"] >= args.since) and
(args.until is None or clip.raw["created"] < args.until) and
(not args.marked or clip.marks)]
key = (lambda clip: clip.title.casefold()) if args.sort == "title" else (lambda clip: clip.raw[args.sort])
result.sort(key=lambda clip: (key(clip), clip.id), reverse=(args.sort == "created") != args.reverse)
return result[:args.limit] if args.limit else result
def output(value, args):
if getattr(args, "json", False):
print(json.dumps(value, ensure_ascii=False, allow_nan=False))
elif isinstance(value, str):
print(safe(value))
else:
print(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False))
def table(headers, rows):
rows = [[safe(value) for value in row] for row in rows]
if not rows:
print("No matching recordings.")
return
widths = [max(len(header), *(len(row[i]) for row in rows)) for i, header in enumerate(headers)]
for row in [headers, *rows]:
print(" ".join(value.ljust(width) for value, width in zip(row, widths)).rstrip())
def human_bytes(value):
amount = float(value)
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
if amount < 1024 or unit == "TiB":
return f"{amount:.1f} {unit}" if unit != "B" else f"{value} B"
amount /= 1024
def download_progress(clip_id, args):
last = [0.0]
def report(done, total):
now = time.monotonic()
if sys.stderr.isatty() and not getattr(args, "json", False) and (now - last[0] >= .5 or done == total):
last[0] = now
print(f"\r{clip_id[:12]} {done / total:6.1%} {human_bytes(done)} / {human_bytes(total)}", end="\n" if done == total else "", file=sys.stderr, flush=True)
return report
def confirm(args, message):
if args.dry_run or args.yes:
return
if getattr(args, "json", False) or not sys.stdin.isatty():
raise Error("Confirmation required: review with --dry-run, then pass --yes")
print(message, file=sys.stderr)
print("Type yes to continue: ", file=sys.stderr, end="", flush=True)
if input().strip() != "yes":
raise Error("Cancelled; no changes made")
def trash_selection(entries, selectors):
chosen = []
for selector in selectors:
if not re.fullmatch(r"[a-f0-9]{4,32}", selector):
raise Error("Use a trash ID or a prefix of at least four characters")
matches = [item for item in entries if item["trash_id"].startswith(selector)]
if len(matches) != 1:
raise Error(f"Trash ID {safe(selector)} is missing or ambiguous")
entry = matches[0]
if entry["state"] == "damaged":
raise Error(f"Trash entry requires manual inspection: {safe(entry.get('error'))}")
if entry not in chosen:
chosen.append(entry)
return chosen
def player_command(value):
if value:
result = shlex.split(value, posix=os.name != "nt")
if result:
return result
raise Error("Player command is empty")
for executable, options in [("ffplay", ["-nodisp", "-autoexit"]), ("mpv", ["--no-video"]), ("afplay", [])]:
if shutil.which(executable):
return [executable, *options]
raise Error("Install ffplay/mpv, or pass --player 'your blocking audio player'")
def run(args):
options = {key: getattr(args, key) for key in ("port", "identity", "host_key", "known_hosts", "password", "ask_passphrase", "timeout") if hasattr(args, key)}
if options.get("timeout", 30) <= 0:
raise Error("Timeout must be positive")
source = Source.parse(args.source)
with Store(source, **options) as store:
repo = Repository(store)
command = {"list": "ls", "stat": "info", "cp": "get", "check": "verify", "remove": "rm"}.get(args.command, args.command)
if command in ("trash", "restore", "purge"):
entries = repo.trash()
if command == "trash":
if getattr(args, "json", False):
output(entries, args)
else:
table(["TRASH ID", "STATE", "DELETED (UTC)", "TITLE"], [[item["trash_id"], item["state"], date(item.get("deleted", 0)), item.get("manifest", {}).get("title", item.get("error", ""))] for item in entries])
return 1 if any(item["state"] != "complete" for item in entries) else 0
chosen = trash_selection(entries, [args.id] if command == "restore" else args.ids)
if command == "purge":
confirm(args, "Permanently delete these trash entries (cannot be undone):\n" + "\n".join(item["trash_id"] + " " + safe(item["manifest"]["title"]) for item in chosen))
results = []
for entry in chosen:
result = {"trash_id": entry["trash_id"], "id": entry["manifest"]["id"], "action": command, "dry_run": args.dry_run}
try:
if not args.dry_run:
repo.restore(entry) if command == "restore" else repo.purge(entry)
except (Error, OSError) as exc:
result["error"] = str(exc)
results.append(result)
output(results, args)
return 1 if any("error" in result for result in results) else 0
clips, issues = repo.inventory()
if command == "doctor":
trash = repo.trash()
trash_issues = [entry for entry in trash if entry["state"] != "complete"]
output({"completed": len(clips), "issues": issues, "trash_issues": trash_issues}, args)
return 1 if issues or trash_issues else 0
for issue in issues:
print(f"warning: {safe(issue['file'])}: {safe(issue['problem'])}", file=sys.stderr)
if command in ("ls", "stats", "sync"):
clips = filtered(clips, args)
elif command in ("info", "marks", "play", "rename"):
clips = selected(clips, [args.id])
elif command in ("get", "rm") or command == "verify" and args.ids:
clips = selected(clips, args.ids)
if command == "ls":
if getattr(args, "json", False):
output([clip.summary() for clip in clips], args)
else:
table(["ID", "CREATED (UTC)", "DURATION", "SIZE", "MARKS", "TITLE"], [[clip.id, date(clip.raw["created"]), duration(clip.raw["duration"]), human_bytes(clip.raw["bytes"]), len(clip.marks), clip.title] for clip in clips])
elif command == "stats":
result = {"recordings": len(clips), "bytes": sum(clip.raw["bytes"] for clip in clips), "duration_ms": sum(clip.raw["duration"] for clip in clips), "bookmarks": sum(len(clip.marks) for clip in clips), "invalid_or_incomplete": len(issues)}
if getattr(args, "json", False):
output(result, args)
else:
print(f"Recordings: {result['recordings']}\nAudio: {human_bytes(result['bytes'])}\nDuration: {duration(result['duration_ms'])}\nBookmarks: {result['bookmarks']}\nIssues: {result['invalid_or_incomplete']}")
elif command == "info":
clip = clips[0]
if getattr(args, "json", False):
output(clip.summary(), args)
else:
print(f"Title: {safe(clip.title)}\nID: {clip.id}\nCreated: {date(clip.raw['created'])}\nDuration: {duration(clip.raw['duration'])}\nAudio: {human_bytes(clip.raw['bytes'])} ({clip.raw['bytes']} bytes)\nSHA-256: {clip.raw['sha256']}\nBookmarks: {len(clip.marks)}")
for i, mark in enumerate(clip.marks, 1):
print(f" {i:3d} {duration(mark)} ({mark} ms)")
elif command == "marks":
marks = [{"number": i + 1, "milliseconds": mark, "time": duration(mark)} for i, mark in enumerate(clips[0].marks)]
if getattr(args, "json", False):
output(marks, args)
else:
table(["MARK", "TIME", "MILLISECONDS"], [[item["number"], item["time"], item["milliseconds"]] for item in marks])
elif command == "verify":
results = []
for clip in clips:
try:
repo.verify(clip)
results.append({"id": clip.id, "ok": True})
except (Error, OSError) as exc:
results.append({"id": clip.id, "ok": False, "error": str(exc)})
output(results, args)
return 1 if any(not item["ok"] for item in results) or issues else 0
elif command in ("get", "sync"):
results = []
for clip in clips:
if args.dry_run:
results.append({"id": clip.id, "bytes": clip.raw["bytes"], "action": "download or verify existing", "dry_run": True})
continue
try:
result = download(store, clip, args.output, force=args.force, resume=not args.no_resume, progress=download_progress(clip.id, args))
results.append(result)
if not getattr(args, "json", False):
print(f"{result['status']}: {safe(result['file'])}", file=sys.stderr)
except (Error, OSError) as exc:
results.append({"id": clip.id, "status": "failed", "error": str(exc)})
output(results, args)
return 1 if any(item.get("status") == "failed" for item in results) or issues else 0
elif command == "play":
player = player_command(args.player)
with tempfile.TemporaryDirectory(prefix="remember-play-") as folder:
result = download(store, clips[0], folder, progress=download_progress(clips[0].id, args))
# Server titles never form commands or local paths. Keep the verified file until the player exits.
subprocess.run([*player, result["file"]], check=True, stdout=sys.stderr)
output({"id": clips[0].id, "played": True}, args)
elif command == "rename":
if not 1 <= len(args.title.strip()) <= 200:
raise Error("Title must contain 1–200 characters")
value = {**clips[0].raw, "title": args.title.strip()} if args.dry_run else repo.rename_title(clips[0], args.title)
output({"id": clips[0].id, "title": value["title"], "dry_run": args.dry_run}, args)
elif command == "rm":
confirm(args, "Move these recordings to recoverable trash:\n" + "\n".join(clip.id + " " + safe(clip.title) for clip in clips))
# Validate all selections before making the first change.
for clip in clips:
repo.unchanged(clip)
results = []
for clip in clips:
result = {"id": clip.id, "title": clip.title, "action": "trash", "dry_run": args.dry_run}
try:
if not args.dry_run:
result["trash_id"] = repo.remove(clip)["trash_id"]
except (Error, OSError) as exc:
result["error"] = str(exc)
results.append(result)
output(results, args)
return 1 if any("error" in result for result in results) else 0
return 0
def main(argv=None):
args = parser().parse_args(argv)
try:
return run(args)
except KeyboardInterrupt:
print("Interrupted; unverified downloads remain resumable. Inspect trash for interrupted moves.", file=sys.stderr)
return 130
except BrokenPipeError:
return 0
except (Error, OSError, ValueError, EOFError, paramiko.SSHException, subprocess.SubprocessError) as exc:
if getattr(args, "json", False):
print(json.dumps({"error": str(exc)}, ensure_ascii=False), file=sys.stderr)
else:
print("remember: " + safe(exc), file=sys.stderr)
return 1
+117
View File
@@ -0,0 +1,117 @@
"""The watch's version-1 completion manifest, never a source of filesystem paths."""
import hashlib
import json
import re
from dataclasses import dataclass
from datetime import datetime, timezone
MAX_METADATA = 128 * 1024
MAX_AUDIO = 500 * 1024 * 1024
CHUNK = 64 * 1024
ID = re.compile(r"[a-fA-F0-9-]{36}\Z")
class Error(Exception):
"""An actionable CLI error, without a traceback or credential dump."""
def safe(value):
"""Do not let remote titles/filenames inject terminal control sequences."""
return "".join(c if c.isprintable() else ascii(c)[1:-1] for c in str(value))
def _object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise Error(f"Duplicate metadata field: {safe(key)}")
result[key] = value
return result
def load_json(data):
if len(data) > MAX_METADATA:
raise Error("Metadata exceeds 128 KiB")
try:
def constant(_):
raise Error("Non-finite JSON numbers are not supported")
return json.loads(data, object_pairs_hook=_object, parse_constant=constant)
except (ValueError, UnicodeError, RecursionError) as exc:
raise Error("Invalid JSON metadata") from exc
def json_bytes(value):
data = (json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n").encode("utf-8")
if len(data) > MAX_METADATA:
raise Error("Metadata exceeds 128 KiB")
return data
def integer(value, name, low=-(2**63), high=2**63 - 1):
if type(value) is not int or not low <= value <= high:
raise Error(f"Invalid {name}")
return value
@dataclass(frozen=True)
class Clip:
id: str
raw: dict
encoded: bytes
@classmethod
def parse(cls, data, expected_id):
doc = load_json(data)
if not isinstance(doc, dict) or type(doc.get("version")) is not int or doc["version"] != 1:
raise Error("Unsupported manifest version")
if not ID.fullmatch(expected_id) or doc.get("id") != expected_id:
raise Error("Manifest ID does not match its filename")
if not isinstance(doc.get("title"), str):
raise Error("Invalid title")
integer(doc.get("created"), "creation timestamp")
integer(doc.get("duration"), "duration", 0)
integer(doc.get("bytes"), "audio size", 1, MAX_AUDIO)
digest = doc.get("sha256")
if not isinstance(digest, str) or not re.fullmatch(r"[a-f0-9]{64}", digest):
raise Error("Invalid SHA-256")
marks = doc.get("marks", [])
if not isinstance(marks, list) or len(marks) > 10000:
raise Error("Invalid bookmarks")
for mark in marks:
integer(mark, "bookmark timestamp")
return cls(expected_id, doc, data)
@property
def title(self):
return self.raw["title"][:200]
@property
def marks(self):
return [min(max(mark, 0), self.raw["duration"]) for mark in self.raw.get("marks", [])]
def summary(self):
return {**self.raw, "title": self.title, "marks": self.marks}
def duration(milliseconds):
seconds = milliseconds // 1000
return f"{seconds // 3600:02d}:{seconds // 60 % 60:02d}:{seconds % 60:02d}"
def date(milliseconds):
try:
return datetime.fromtimestamp(milliseconds / 1000, timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
except (OverflowError, OSError, ValueError):
return str(milliseconds)
def hash_stream(stream, maximum=None):
digest = hashlib.sha256()
size = 0
while chunk := stream.read(CHUNK):
size += len(chunk)
if maximum is not None and size > maximum:
raise Error("Audio exceeds its declared size")
digest.update(chunk)
return size, digest.hexdigest()
+298
View File
@@ -0,0 +1,298 @@
"""Versioned backup operations, verified downloads, and recoverable server-side trash."""
import contextlib
import hashlib
import os
import re
import stat
import time
import uuid
from pathlib import Path
from .model import CHUNK, ID, MAX_METADATA, Clip, Error, hash_stream, integer, json_bytes, load_json, safe
TRASH = ".remember-trash"
class Repository:
def __init__(self, store):
self.store = store
def clip(self, clip_id):
if not isinstance(clip_id, str) or not ID.fullmatch(clip_id):
raise Error("Invalid recording ID")
clip = Clip.parse(self.store.read(f"{clip_id}.json"), clip_id)
audio = self.store.stat(f"{clip_id}.m4a")
if not stat.S_ISREG(audio.st_mode) or audio.st_size != clip.raw["bytes"]:
raise Error("Missing, linked, or wrong-size audio")
return clip
def inventory(self):
clips, issues, names = [], [], set()
for name, attrs in self.store.entries():
names.add(name)
if not re.fullmatch(r"[a-fA-F0-9-]{36}\.json", name):
continue
try:
if not stat.S_ISREG(attrs.st_mode):
raise Error("Not a regular manifest")
clips.append(self.clip(name[:-5]))
except (Error, OSError, ValueError, TypeError) as exc:
issues.append({"file": name, "problem": str(exc)})
valid = {clip.id for clip in clips}
for name in sorted(names):
if name.endswith(".upload"):
issues.append({"file": name, "problem": "incomplete upload (may still be active)"})
elif re.fullmatch(r"[a-fA-F0-9-]{36}\.m4a", name) and name[:-4] not in valid:
issues.append({"file": name, "problem": "audio without a valid completion manifest"})
elif name.startswith(".remember-") and name.endswith(".tmp"):
issues.append({"file": name, "problem": "unfinished CLI metadata write"})
clips.sort(key=lambda item: (item.raw["created"], item.id), reverse=True)
return clips, issues
def unchanged(self, clip):
if self.store.read(f"{clip.id}.json") != clip.encoded:
raise Error("Manifest changed; refresh and retry")
audio = self.store.stat(f"{clip.id}.m4a")
if not stat.S_ISREG(audio.st_mode) or audio.st_size != clip.raw["bytes"]:
raise Error("Audio changed; refresh and retry")
if any(self.store.exists(clip.id + suffix) for suffix in (".m4a.upload", ".json.upload")):
raise Error("An upload for this recording may be active; wait before modifying it")
def verify(self, clip):
with self.store.open(f"{clip.id}.m4a") as stream:
size, digest = hash_stream(stream, clip.raw["bytes"])
if size != clip.raw["bytes"] or digest != clip.raw["sha256"]:
raise Error("Audio size/SHA-256 verification failed")
def rename_title(self, clip, title):
title = title.strip()
if not 1 <= len(title) <= 200:
raise Error("Title must contain 1–200 characters")
self.unchanged(clip)
updated = {**clip.raw, "title": title}
self.store.atomic_write(f"{clip.id}.json", json_bytes(updated), expected=clip.encoded)
return updated
def _trash_directory(self, trash_id):
if not isinstance(trash_id, str) or not re.fullmatch(r"[a-f0-9]{32}", trash_id):
raise Error("Invalid trash ID")
return f"{TRASH}/{trash_id}"
def trash(self):
if not self.store.exists(TRASH):
return []
entries = []
for name, attrs in self.store.entries(TRASH):
try:
if not stat.S_ISDIR(attrs.st_mode):
raise Error("Not a regular trash directory")
entry = self.trash_entry(name)
entries.append(entry)
except (Error, OSError, ValueError, TypeError) as exc:
entries.append({"trash_id": name, "state": "damaged", "error": str(exc)})
return sorted(entries, key=lambda item: item.get("deleted", 0), reverse=True)
def trash_entry(self, trash_id):
base = self._trash_directory(trash_id)
record = load_json(self.store.read(f"{base}/entry.json"))
if not isinstance(record, dict) or type(record.get("version")) is not int or record["version"] != 1 or record.get("trash_id") != trash_id:
raise Error("Invalid trash entry")
integer(record.get("deleted"), "trash timestamp", 0)
original = record.get("manifest")
if not isinstance(original, dict):
raise Error("Invalid saved manifest")
clip_id = original.get("id")
if not isinstance(clip_id, str):
raise Error("Invalid saved recording ID")
Clip.parse(json_bytes(original), clip_id)
names = {name for name, _ in self.store.entries(base)}
expected = {"entry.json", f"{clip_id}.m4a", f"{clip_id}.json"}
if names - expected:
raise Error("Trash entry contains unknown files; manual inspection required")
for name in names:
if not stat.S_ISREG(self.store.stat(f"{base}/{name}").st_mode):
raise Error("Trash entry contains a linked or special file")
# Interrupted two-file moves remain visible and can be restored or purged explicitly.
complete = expected <= names
return {**record, "state": "complete" if complete else "partial", "files": sorted(names)}
def remove(self, clip):
self.unchanged(clip)
if not self.store.exists(TRASH):
self.store.mkdir(TRASH)
trash_id = uuid.uuid4().hex
base = self._trash_directory(trash_id)
self.store.mkdir(base)
record = {"version": 1, "trash_id": trash_id, "deleted": time.time_ns() // 1_000_000, "manifest": clip.raw}
self.store.atomic_write(f"{base}/entry.json", json_bytes(record))
# Remove the completion marker first; never expose a completed backup with missing audio.
self.store.rename(f"{clip.id}.json", f"{base}/{clip.id}.json")
try:
self.store.rename(f"{clip.id}.m4a", f"{base}/{clip.id}.m4a")
except BaseException as exc:
# If a concurrent watch upload published a new manifest, never overwrite it.
if not self.store.exists(f"{clip.id}.json"):
self.store.rename(f"{base}/{clip.id}.json", f"{clip.id}.json")
if isinstance(exc, (KeyboardInterrupt, SystemExit)):
raise
raise Error(f"Trash move interrupted. Inspect/restore trash entry {trash_id}") from None
return record
def restore(self, entry):
base = self._trash_directory(entry["trash_id"])
manifest = entry["manifest"]
clip_id = manifest["id"]
# Resolve interrupted removal/restoration using the saved hash, never by filename alone.
for suffix in (".m4a", ".json"):
name = clip_id + suffix
there, here = self.store.exists(f"{base}/{name}"), self.store.exists(name)
if there and here:
raise Error(f"Restore would overwrite {name}; existing backups are preserved")
if not there and not here:
raise Error(f"Neither trash nor backup root contains {name}; cannot restore")
if suffix == ".m4a":
with self.store.open(f"{base}/{name}" if there else name) as stream:
size, digest = hash_stream(stream, manifest["bytes"])
if size != manifest["bytes"] or digest != manifest["sha256"]:
raise Error("Trash audio verification failed; nothing restored")
else:
candidate = Clip.parse(self.store.read(f"{base}/{name}" if there else name), clip_id)
if candidate.raw != manifest:
raise Error("Trash manifest changed; nothing restored")
# Audio first, completion marker last. A repeated restore safely resumes an interrupted move.
for suffix in (".m4a", ".json"):
name = clip_id + suffix
if self.store.exists(f"{base}/{name}"):
self.store.rename(f"{base}/{name}", name)
self.store.remove(f"{base}/entry.json")
self.store.rmdir(base)
return manifest
def purge(self, entry):
base = self._trash_directory(entry["trash_id"])
# Only the exact, validated entry files. Never recursively remove arbitrary server paths.
current = self.trash_entry(entry["trash_id"])
if current["manifest"] != entry["manifest"]:
raise Error("Trash entry changed; refresh and retry")
for suffix in (".json", ".m4a"):
name = f"{base}/{entry['manifest']['id']}{suffix}"
if self.store.exists(name):
self.store.remove(name)
self.store.remove(f"{base}/entry.json")
self.store.rmdir(base)
@contextlib.contextmanager
def exclusive_file(path):
"""OS releases the lock on crashes; the small lock file deliberately remains in the mirror."""
descriptor = os.open(path, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
stream = os.fdopen(descriptor, "r+b")
try:
if not stat.S_ISREG(os.fstat(descriptor).st_mode) or os.fstat(descriptor).st_nlink != 1:
raise Error("Unsafe local lock file")
try:
if os.name == "nt":
import msvcrt
if os.fstat(descriptor).st_size == 0:
stream.write(b"0"); stream.flush(); stream.seek(0)
msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as exc:
raise Error("Another CLI process is using this destination") from exc
yield
finally:
stream.close()
def _regular(path):
try:
info = path.lstat()
except FileNotFoundError:
return False
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
raise Error(f"Refusing linked or special local file: {safe(path)}")
return True
def _atomic_local(path, data):
temporary = path.parent / (".remember-" + uuid.uuid4().hex + ".tmp")
try:
with temporary.open("xb") as stream:
os.chmod(temporary, 0o600)
stream.write(data); stream.flush(); os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def download(store, clip, directory, *, force=False, resume=True, progress=lambda *_: None):
"""One bounded stream, checked SHA-256, atomic publication; no local audio is overwritten implicitly."""
directory = Path(directory).expanduser().resolve()
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
final = directory / f"{clip.id}.m4a"
metadata = directory / f"{clip.id}.json"
partial = directory / f".{clip.id}.m4a.part"
receipt = directory / f".{clip.id}.part.json"
snapshot = {key: clip.raw[key] for key in ("id", "bytes", "sha256")}
with exclusive_file(directory / ".remember-lock"):
if _regular(final):
size, digest = final.stat().st_size, None
if size == clip.raw["bytes"]:
with final.open("rb") as stream:
size, digest = hash_stream(stream, clip.raw["bytes"])
if size == clip.raw["bytes"] and digest == clip.raw["sha256"]:
_regular(metadata)
_atomic_local(metadata, clip.encoded)
return {"id": clip.id, "status": "unchanged", "file": str(final), "bytes": size}
if not force:
raise Error(f"Local audio differs: {safe(final)}. Use --force to replace it")
_regular(metadata)
offset = 0
if _regular(partial) and _regular(receipt) and resume:
try:
if receipt.stat().st_size <= MAX_METADATA and load_json(receipt.read_bytes()) == snapshot:
offset = partial.stat().st_size
except Error:
pass
if offset > clip.raw["bytes"]:
offset = 0
_regular(receipt)
_atomic_local(receipt, json_bytes(snapshot))
# Retry a corrupt resumed prefix once from zero; never publish unverified audio.
for attempt in range(2):
descriptor = os.open(partial, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
with os.fdopen(descriptor, "r+b") as output:
if os.fstat(output.fileno()).st_nlink != 1 or not stat.S_ISREG(os.fstat(output.fileno()).st_mode):
raise Error("Unsafe partial download")
output.truncate(offset); output.seek(offset)
transferred = offset
with store.open(f"{clip.id}.m4a") as remote:
remote.seek(offset)
while chunk := remote.read(min(CHUNK, clip.raw["bytes"] - transferred + 1)):
transferred += len(chunk)
if transferred > clip.raw["bytes"]:
raise Error("Server audio exceeds its manifest; previous local audio retained")
output.write(chunk)
progress(transferred, clip.raw["bytes"])
output.flush(); os.fsync(output.fileno())
if transferred != clip.raw["bytes"]:
raise Error("Incomplete download; partial retained for resume")
output.seek(0)
size, digest = hash_stream(output, clip.raw["bytes"])
if size == clip.raw["bytes"] and digest == clip.raw["sha256"]:
break
partial.unlink(missing_ok=True)
if not offset or attempt:
receipt.unlink(missing_ok=True)
raise Error("SHA-256 mismatch; previous local audio retained")
offset = 0
# Refuse a concurrently created destination unless replacement was explicitly requested.
if final.exists() and not force:
raise Error("Local destination appeared during download; verified partial retained")
os.replace(partial, final)
_atomic_local(metadata, clip.encoded)
receipt.unlink(missing_ok=True)
return {"id": clip.id, "status": "downloaded", "file": str(final), "bytes": clip.raw["bytes"]}
+285
View File
@@ -0,0 +1,285 @@
"""Bounded SFTP/file operations. No remote shell, recursive traversal, or glob expansion."""
import base64
import getpass
import hashlib
import hmac
import os
import posixpath
import re
import stat
import sys
import uuid
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import unquote, urlsplit
import paramiko
from .model import Error, MAX_METADATA, safe
@dataclass(frozen=True)
class Source:
host: str | None
user: str | None
port: int | None
root: str
@classmethod
def parse(cls, value):
if not value or any(ord(c) < 32 or ord(c) == 127 for c in value):
raise Error("Source must be a directory or [user@]host:/backup/path")
if value.startswith(("sftp://", "ssh://")):
try:
uri = urlsplit(value)
if uri.password is not None or uri.query or uri.fragment or not uri.hostname or not uri.path:
raise Error("Use ssh://[user@]host[:port]/backup/path; passwords do not belong in URLs")
path = unquote(uri.path)
user = unquote(uri.username) if uri.username else None
if any(ord(c) < 32 or ord(c) == 127 for c in path + (user or "")):
raise Error("SSH paths and usernames cannot contain control characters")
return cls(uri.hostname, user, uri.port, path)
except ValueError as exc:
raise Error("Invalid SSH URL") from exc
if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", value):
raise Error("Only sftp:// and ssh:// URLs are supported")
match = re.fullmatch(r"(?:(?P<user>[^/@:]+)@)?(?:\[(?P<ipv6>[^\]]+)\]|(?P<host>[^/:]+)):(?P<root>.+)", value)
if match and not re.match(r"^[A-Za-z]:[\\/]", value):
return cls(match["ipv6"] or match["host"], match["user"], None, match["root"])
return cls(None, None, None, str(Path(value).expanduser()))
def fingerprint(key):
return "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
class Trust(paramiko.MissingHostKeyPolicy):
def __init__(self, pin, known_hosts):
self.pin = pin
self.known_hosts = known_hosts
def missing_host_key(self, client, hostname, key):
actual = fingerprint(key)
if self.pin:
if not hmac.compare_digest(self.pin, actual):
raise Error(f"Server identity mismatch for {safe(hostname)} (received {actual}); authentication blocked")
return
if not sys.stdin.isatty():
raise Error(f"Unknown SSH host {safe(hostname)} ({actual}). Verify this fingerprint, then pass --host-key {actual} or trust the host with SSH first")
print(f"Unknown SSH host: {safe(hostname)}\n{key.get_name()} {actual}\nCompare this fingerprint through a trusted channel.", file=sys.stderr)
print("Trust and remember this host? Type yes: ", file=sys.stderr, end="", flush=True)
if input().strip() != "yes":
raise Error("Host was not approved; authentication blocked")
path = self.known_hosts
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
# Append preserves unrelated OpenSSH host entries/comments. No auto-trust policy.
with path.open("a", encoding="utf-8") as output:
output.write(f"\n{hostname} {key.get_name()} {key.get_base64()}\n")
os.chmod(path, 0o600)
client.get_host_keys().add(hostname, key.get_name(), key)
def checked_path(name):
parts = name.split("/")
if not name or any(part in ("", ".", "..") or "\\" in part or "\x00" in part for part in parts):
raise Error("Unsafe backup filename")
return parts
def regular(mode):
return isinstance(mode, int) and stat.S_ISREG(mode)
def is_directory(mode):
return isinstance(mode, int) and stat.S_ISDIR(mode)
class Store:
def __init__(self, source, *, port=None, identity=None, host_key=None, known_hosts=None, password=False, ask_passphrase=False, timeout=30):
self.source = source
self.client = None
self.sftp = None
self.proxy = None
if source.host is None:
self.root = Path(source.root).resolve(strict=True)
if not self.root.is_dir():
raise Error("Local backup root is not a directory")
return
self.root = source.root
try:
config_path = Path.home() / ".ssh/config"
config = {}
if config_path.is_file():
with config_path.open() as stream:
config = paramiko.SSHConfig.from_file(stream).lookup(source.host)
if config.get("proxyjump") not in (None, "none") and not config.get("proxycommand"):
raise Error("ProxyJump is not supported yet; use a reachable SSH alias with ProxyCommand instead")
host = config.get("hostname", source.host)
user = source.user or config.get("user", getpass.getuser())
ssh_port = port if port is not None else source.port if source.port is not None else int(config.get("port", 22))
if not 1 <= ssh_port <= 65535:
raise Error("SSH port must be between 1 and 65535")
keys = [str(Path(identity).expanduser())] if identity else config.get("identityfile")
path = Path(known_hosts).expanduser() if known_hosts else Path.home() / ".ssh/known_hosts"
client = self.client = paramiko.SSHClient()
if not host_key:
client.load_system_host_keys()
if path.is_file():
client.load_host_keys(str(path))
client.set_missing_host_key_policy(Trust(host_key, path))
proxy = config.get("proxycommand")
if proxy and proxy != "none":
self.proxy = paramiko.ProxyCommand(proxy)
# Prompting for a password is explicit, but transmitting credentials always follows host verification.
secret = getpass.getpass("SSH password: ") if password else None
passphrase = getpass.getpass("SSH key passphrase: ") if ask_passphrase else None
client.connect(host, port=ssh_port, username=user, key_filename=keys, password=secret,
passphrase=passphrase,
allow_agent=not password, look_for_keys=not password, timeout=timeout,
banner_timeout=timeout, auth_timeout=timeout, channel_timeout=timeout,
sock=self.proxy, compress=False)
self.sftp = client.open_sftp()
self.sftp.get_channel().settimeout(timeout)
if self.root == "~" or self.root.startswith("~/"):
self.root = posixpath.join(self.sftp.normalize("."), self.root[2:] if self.root != "~" else "")
self.root = self.sftp.normalize(self.root)
if not is_directory(self.sftp.lstat(self.root).st_mode):
raise Error("Remote backup root is not a directory")
except BaseException:
self.close()
raise
def _path(self, name):
parts = checked_path(name)
# Inspect every intermediate component, including trash directories, without following symlinks.
current = self.root
for part in parts[:-1]:
current = posixpath.join(current, part) if self.sftp else current / part
mode = self.sftp.lstat(current).st_mode if self.sftp else current.lstat().st_mode
if not is_directory(mode):
raise Error("Backup path contains a symlink or non-directory")
return posixpath.join(self.root, name) if self.sftp else self.root.joinpath(*parts)
def entries(self, directory=None):
base = self.root if directory is None else self._path(directory)
if directory and not is_directory(self.stat(directory).st_mode):
raise Error("Backup directory is not a regular directory")
if self.sftp:
for item in self.sftp.listdir_iter(base, read_aheads=1):
yield item.filename, item
else:
with os.scandir(base) as iterator:
for item in iterator:
yield item.name, item.stat(follow_symlinks=False)
def stat(self, name):
path = self._path(name)
return self.sftp.lstat(path) if self.sftp else path.lstat()
def exists(self, name):
try:
self.stat(name)
return True
except FileNotFoundError:
return False
def open(self, name):
path = self._path(name)
if not regular(self.stat(name).st_mode):
raise Error(f"Not a regular file: {safe(name)}")
if self.sftp:
return self.sftp.open(path, "rb", bufsize=65536)
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
return os.fdopen(descriptor, "rb")
def read(self, name):
size = self.stat(name).st_size
if type(size) is not int or not 0 <= size <= MAX_METADATA:
raise Error("Metadata exceeds 128 KiB")
with self.open(name) as stream:
data = stream.read(MAX_METADATA + 1)
if len(data) > MAX_METADATA:
raise Error("Metadata exceeds 128 KiB")
return data
def mkdir(self, name):
path = self._path(name)
if self.sftp:
self.sftp.mkdir(path, mode=0o700)
else:
path.mkdir(mode=0o700)
def rename(self, old, new):
if self.exists(new):
raise Error(f"Refusing to replace {safe(new)}")
if not regular(self.stat(old).st_mode):
raise Error("Refusing to move a non-regular file")
if self.sftp:
self.sftp.rename(self._path(old), self._path(new))
else:
# Link/unlink gives no-clobber semantics on a single local filesystem.
os.link(self._path(old), self._path(new), follow_symlinks=False)
self._path(old).unlink()
def remove(self, name):
if not regular(self.stat(name).st_mode):
raise Error("Refusing to remove a non-regular file")
path = self._path(name)
self.sftp.remove(path) if self.sftp else path.unlink()
def rmdir(self, name):
if not is_directory(self.stat(name).st_mode):
raise Error("Refusing to remove a non-directory")
path = self._path(name)
self.sftp.rmdir(path) if self.sftp else path.rmdir()
def atomic_write(self, name, data, expected=None):
path = self._path(name)
temporary = posixpath.join(posixpath.dirname(name), ".remember-" + uuid.uuid4().hex + ".tmp")
temporary_path = self._path(temporary)
try:
if self.sftp:
with self.sftp.open(temporary_path, "wx") as stream:
self.sftp.chmod(temporary_path, 0o600)
stream.write(data); stream.flush()
else:
descriptor = os.open(temporary_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "wb") as stream:
stream.write(data); stream.flush(); os.fsync(stream.fileno())
if expected is not None and self.read(name) != expected:
raise Error("Manifest changed during this operation; refresh and retry")
if expected is None and self.exists(name):
raise Error(f"Refusing to replace {safe(name)}")
if self.sftp:
if expected is None:
self.sftp.rename(temporary_path, path)
else:
# OpenSSH extension: never remove the committed manifest as a fallback.
try:
self.sftp.posix_rename(temporary_path, path)
except OSError as exc:
raise Error("Server could not atomically replace the manifest; original retained. OpenSSH posix-rename support is required") from exc
else:
if expected is None:
os.link(temporary_path, path)
temporary_path.unlink()
else:
os.replace(temporary_path, path)
finally:
if self.exists(temporary):
self.remove(temporary)
def close(self):
if self.sftp:
self.sftp.close()
if self.client:
self.client.close()
if self.proxy:
self.proxy.close()
def __enter__(self):
return self
def __exit__(self, *_):
self.close()