"""Private, expiring device backups. Downloads require the uploader's cookie.""" import hashlib import json import os import re import secrets import time class DeviceBackups: def __init__(self, data, config, lock, detect): self.folder = data / 'device-downloads' self.folder.mkdir(exist_ok=True) self.config, self.lock, self.detect = config, lock, detect def cookie(self, h): m = re.search(r'(?:^|;\s*)tama_download=([a-f0-9]{64})(?:;|$)', h.headers.get('Cookie', '')) return m[1] if m else None def owner(self, token): return hashlib.sha256(token.encode()).hexdigest() def purge(self): for p in self.folder.glob('*.json'): meta = json.loads(p.read_text()) if meta['expires'] < time.time(): p.with_suffix('.bin').unlink(missing_ok=True) p.unlink() def store(self, h, data): cfg = self.config() if cfg['backupMode'] != 'server': raise ValueError('백업 방식이 변경되었습니다. 다시 시도하세요.') kind = h.headers.get('X-Backup-Kind', 'rom') if kind == 'rom': edition = self.detect(data) elif kind == 'save' and data[:8] == b'TAMASAVE' and 56 <= len(data) <= 4 * 1024 * 1024 and data[-16:-12] == b'PMXE': edition = int.from_bytes(data[-12:-8], 'little') if edition not in range(1, 7): raise ValueError('저장 데이터의 기종을 확인할 수 없습니다.') elif kind == 'aux' and cfg['features'].get('emu') and 1 <= len(data) <= 16 * 1024 * 1024: edition = 0 else: raise ValueError('지원하는 기기 백업 파일이 아닙니다.') token = self.cookie(h) or secrets.token_hex(32) owner = self.owner(token) sha = hashlib.sha256(data).hexdigest() with self.lock: self.purge() items = [json.loads(p.read_text()) for p in self.folder.glob('*.json')] old = next((m for m in items if m['owner'] == owner and m['sha256'] == sha), None) if old: meta = old else: if sum(m['size'] for m in items) + len(data) > cfg['deviceStorageMB'] * 1048576: raise ValueError('서버의 기기 백업 공간이 가득 찼습니다. 읽은 데이터는 현재 화면에 유지됩니다.') if sum(m['owner'] == owner for m in items) >= 20: raise ValueError('현재 브라우저의 임시 백업 한도에 도달했습니다. 기존 백업의 보관 기간이 지난 뒤 다시 시도하세요.') key = secrets.token_hex(16) meta = dict(id=key, owner=owner, sha256=sha, size=len(data), edition=edition, kind=kind, expires=time.time() + cfg['deviceRetentionHours'] * 3600) dest = self.folder / (key + '.bin') with dest.open('xb') as f: f.write(data) f.flush() os.fsync(f.fileno()) if hashlib.sha256(dest.read_bytes()).hexdigest() != sha: dest.unlink() raise ValueError('서버에 저장한 파일의 검증에 실패했습니다.') (self.folder / (key + '.json')).write_text(json.dumps(meta), encoding='utf-8') public = {k: v for k, v in meta.items() if k != 'owner'} public['fileUrl'] = '/api/device-backups/' + meta['id'] return public, {'Set-Cookie': 'tama_download=' + token + '; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=604800'} def download(self, h, key): with self.lock: self.purge() p = self.folder / (key + '.json') token = self.cookie(h) meta = json.loads(p.read_text()) if p.exists() else None if not meta or not token or not secrets.compare_digest(meta['owner'], self.owner(token)): return h.reply(404, {'error': '이 브라우저에서 저장한 백업이 아니거나 보관 기간이 지났습니다.'}) data = p.with_suffix('.bin').read_bytes() if hashlib.sha256(data).hexdigest() != meta['sha256']: return h.reply(500, {'error': '서버 백업 파일 검증에 실패했습니다.'}) ext = 'tamasave' if meta['kind'] == 'save' else 'bin' h.reply(200, data, 'application/octet-stream', {'Content-Disposition': f'attachment; filename="paradise-{key}.{ext}"'})