Files
mctf/braindance/backend/app.py
T

684 lines
25 KiB
Python
Executable File

import base64
import hashlib
import hmac
import heapq
from itertools import islice
from functools import lru_cache
import json
import os
import re
import secrets
import threading
import time
from flask import Flask, request, jsonify, send_from_directory, g
app = Flask(__name__, static_folder='static', static_url_path='/static')
app.config['MAX_CONTENT_LENGTH'] = 200000
LOCK = threading.RLock()
SAVE_LOCK = threading.Lock()
TOKENS = {}
ACTIVE = {}
OWNER_RECORDS = {}
OWNER_COLLECTIONS = {}
RAW_BYTES = 0
COMMENT_COUNT = 0
FOLLOW_COUNT = 0
DIRTY = False
RETENTION_SECONDS = float(os.environ.get('RETENTION_SECONDS', '1800'))
CLEANUP_INTERVAL = float(os.environ.get('CLEANUP_INTERVAL_SECONDS', '15'))
FLAG_LIFETIME = float(os.environ.get('FLAG_LIFETIME_SECONDS', '300'))
MAX_DATA_BYTES = int(os.environ.get('MAX_DATA_BYTES', str(64 * 1024 * 1024)))
MAX_OBJECTS = int(os.environ.get('MAX_OBJECTS', '10000'))
if CLEANUP_INTERVAL <= 0 or FLAG_LIFETIME <= 0 or RETENTION_SECONDS < FLAG_LIFETIME + 2 * CLEANUP_INTERVAL:
raise ValueError('RETENTION_SECONDS must cover flag lifetime plus two cleanup intervals')
USERS = {}
RECORDS = {}
COLLECTIONS = {}
COMMENTS = {}
FOLLOWS = {}
TAG_INDEX = {}
FEED = []
KNOWN_LAYERS = ['video', 'thermal', 'audio', 'emotion']
PUBLIC_LAYERS = ['video', 'audio']
PRIVATE_LAYERS = ['thermal', 'emotion']
SLUG_RE = re.compile('^[a-z0-9_-]{1,24}$')
def _load_secret():
env = os.environ.get('BD_SECRET')
if env:
return env.encode()
path = os.environ.get('BD_SECRET_FILE', '/data/secret.bin')
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
if os.path.exists(path):
with open(path, 'rb') as f:
return f.read()
s = secrets.token_bytes(24)
with open(path, 'wb') as f:
f.write(s)
return s
except OSError:
return secrets.token_bytes(24)
SECRET = _load_secret()
def new_id(n=8):
return secrets.token_hex(n)
@lru_cache(maxsize=64)
def b64(b):
return base64.b64encode(b).decode()
def auth():
hdr = request.headers.get('Authorization', '')
if not hdr.startswith('Bearer '):
return None
token = hdr[7:]
with LOCK:
name = TOKENS.get(token)
if name is not None and not getattr(g, 'auth_user', None):
g.auth_user = name
ACTIVE[name] = ACTIVE.get(name, 0) + 1
USERS[name]['last_active'] = time.time()
return name
@app.teardown_request
def release_user(error):
name = g.pop('auth_user', None)
if name:
with LOCK:
ACTIVE[name] -= 1
if not ACTIVE[name]:
del ACTIVE[name]
@app.after_request
def track_changes(response):
global DIRTY
if request.method in ('POST', 'PUT', 'PATCH', 'DELETE') and response.status_code < 400:
with LOCK:
DIRTY = True
return response
def capacity_error():
return jsonify(error='storage limit reached; retry after old data expires'), 507
def record_public(rec):
return {n: b64(rec['layers'][n]) for n in rec['public'] if n in rec['layers']}
def record_full(rec):
return {n: b64(rec['layers'][n]) for n in rec['layers']}
def record_meta(rid, rec):
return {'id': rid, 'owner': rec['owner'], 'title': rec.get('title', ''), 'tags': rec.get('tags', []), 'price': rec.get('price', 0), 'likes': rec.get('likes', 0)}
def trailer_sig(rec_id, layer_list):
payload = f"{rec_id}:{','.join(layer_list)}".encode()
return hmac.new(SECRET, payload, hashlib.sha256).hexdigest()[:24]
def parse_bd(text):
metas, layers = ([], {})
fields = {'tags': [], 'title': '', 'price': 0, 'fx': [], 'notes': []}
lines = text.replace('\r\n', '\n').split('\n')
if not lines or lines[0].strip() != 'BDv1':
raise ValueError('bad magic')
for line in lines[1:]:
line = line.rstrip()
if not line.strip():
continue
parts = line.split(' ')
kind = parts[0]
if kind == 'META':
meta = {'owner': None, 'source': '-'}
for kv in parts[1:]:
if '=' in kv:
k, v = kv.split('=', 1)
if k in meta:
meta[k] = v
metas.append(meta)
elif kind == 'LAYER' and len(parts) >= 3:
name = parts[1]
if name in KNOWN_LAYERS:
try:
layers[name] = base64.b64decode(parts[2])
except Exception:
raise ValueError('bad layer b64')
elif kind == 'TAG' and len(parts) >= 2:
s = parts[1].lower()
if SLUG_RE.match(s) and s not in fields['tags'] and len(fields['tags']) < 16:
fields['tags'].append(s)
elif kind == 'TITLE':
fields['title'] = ' '.join(parts[1:])[:80]
elif kind == 'PRICE' and len(parts) >= 2:
try:
fields['price'] = max(0, min(int(parts[1]), 10 ** 6))
except ValueError:
pass
elif kind == 'FX' and len(parts) >= 2:
if len(fields['fx']) < 16:
fields['fx'].append(parts[1][:24])
elif kind == 'NOTE':
if len(fields['notes']) < 16:
fields['notes'].append(' '.join(parts[1:])[:120])
if not metas:
raise ValueError('no META')
return (metas, layers, fields)
def touch_feed(name):
FEED.append(name)
del FEED[:-80]
STATE_FILE = os.environ.get('BD_STATE_FILE', '/data/state.json')
STATE_BACKUP = STATE_FILE + '.bak'
SNAPSHOT_INTERVAL = float(os.environ.get('SNAPSHOT_INTERVAL_SECONDS', '5'))
if SNAPSHOT_INTERVAL <= 0:
raise ValueError('SNAPSHOT_INTERVAL_SECONDS must be positive')
def _serialize_nolock():
return {
'USERS': {name: dict(user) for name, user in USERS.items()},
'RECORDS': {rid: dict(rec) for rid, rec in RECORDS.items()},
'COLLECTIONS': {cid: {**col, 'items': list(col['items'])} for cid, col in COLLECTIONS.items()},
'COMMENTS': {rid: list(comments) for rid, comments in COMMENTS.items()},
'FOLLOWS': {name: sorted(targets) for name, targets in FOLLOWS.items()},
'TAG_INDEX': {tag: list(ids) for tag, ids in TAG_INDEX.items()},
'FEED': list(FEED),
}
def _json_value(value):
if isinstance(value, bytes):
return b64(value)
if isinstance(value, set):
return sorted(value)
raise TypeError(type(value).__name__)
def _fsync_parent(path):
directory = os.path.dirname(os.path.abspath(path)) or '.'
try:
fd = os.open(directory, os.O_RDONLY)
except OSError:
return
try:
os.fsync(fd)
except OSError:
pass
finally:
os.close(fd)
def _write_snapshot(path, snapshot):
temp_path = path + '.tmp'
with open(temp_path, 'w', encoding='utf-8') as f:
json.dump(snapshot, f, default=_json_value, separators=(',', ':'))
f.flush()
os.fsync(f.fileno())
os.replace(temp_path, path)
_fsync_parent(path)
def _save_state(force=False):
global DIRTY
try:
with SAVE_LOCK:
with LOCK:
if not DIRTY and not force:
return
snapshot = _serialize_nolock()
DIRTY = False
os.makedirs(os.path.dirname(STATE_FILE) or '.', exist_ok=True)
_write_snapshot(STATE_FILE, snapshot)
try:
_write_snapshot(STATE_BACKUP, snapshot)
except OSError:
app.logger.exception('Could not update state backup')
except (OSError, TypeError, ValueError):
with LOCK:
DIRTY = True
app.logger.exception('Could not save state')
def _load_state():
data = None
loaded_from = None
for path in (STATE_FILE, STATE_FILE + '.tmp', STATE_BACKUP):
try:
with open(path, encoding='utf-8') as f:
candidate = json.load(f)
if not isinstance(candidate, dict):
raise ValueError('state root must be an object')
data = candidate
loaded_from = path
break
except (OSError, ValueError):
continue
if data is None:
if os.path.exists(STATE_FILE):
app.logger.error('Could not load state or its backups')
return
if loaded_from != STATE_FILE:
app.logger.warning('Recovered state from %s', loaded_from)
global DIRTY
DIRTY = True
with LOCK:
USERS.update(data.get('USERS', {}))
for rid, r in data.get('RECORDS', {}).items():
r['layers'] = {n: base64.b64decode(v) for n, v in r.get('layers', {}).items()}
RECORDS[rid] = r
COLLECTIONS.update(data.get('COLLECTIONS', {}))
COMMENTS.update(data.get('COMMENTS', {}))
for k, v in data.get('FOLLOWS', {}).items():
FOLLOWS[k] = set(v)
TAG_INDEX.update(data.get('TAG_INDEX', {}))
FEED.extend(data.get('FEED', []))
def _rebuild_indexes():
global RAW_BYTES, COMMENT_COUNT, FOLLOW_COUNT
now = time.time()
TOKENS.clear()
OWNER_RECORDS.clear()
OWNER_COLLECTIONS.clear()
TAG_INDEX.clear()
for name, user in USERS.items():
user.setdefault('created', now)
user.setdefault('last_active', user['created'])
TOKENS[user['token']] = name
RAW_BYTES = 0
for rid, rec in RECORDS.items():
rec.setdefault('created', now)
OWNER_RECORDS.setdefault(rec['owner'], set()).add(rid)
RAW_BYTES += sum(map(len, rec['layers'].values()))
for tag in rec.get('tags', []):
TAG_INDEX.setdefault(tag, []).append(rid)
for cid, col in COLLECTIONS.items():
col.setdefault('created', now)
OWNER_COLLECTIONS.setdefault(col['owner'], set()).add(cid)
COMMENT_COUNT = sum(map(len, COMMENTS.values()))
FOLLOW_COUNT = sum(map(len, FOLLOWS.values()))
def _cleanup(now=None):
global DIRTY, RAW_BYTES, COMMENT_COUNT, FOLLOW_COUNT
cutoff = (time.time() if now is None else now) - RETENTION_SECONDS
with LOCK:
removed = 0
for rid, rec in list(RECORDS.items()):
if rec['created'] > cutoff:
continue
RAW_BYTES -= sum(map(len, rec['layers'].values()))
del RECORDS[rid]
removed += 1
for cid, col in list(COLLECTIONS.items()):
if col['created'] <= cutoff:
del COLLECTIONS[cid]
removed += 1
else:
items = [rid for rid in col['items'] if rid in RECORDS]
removed += len(col['items']) - len(items)
col['items'] = items
for rid, comments in list(COMMENTS.items()):
kept = [c for c in comments if c['ts'] > cutoff] if rid in RECORDS else []
removed += len(comments) - len(kept)
if kept:
COMMENTS[rid] = kept
else:
COMMENTS.pop(rid, None)
owners = {r['owner'] for r in RECORDS.values()} | {c['owner'] for c in COLLECTIONS.values()}
for name, user in list(USERS.items()):
if user['last_active'] <= cutoff and name not in owners and name not in ACTIVE:
del USERS[name]
removed += 1
for name, targets in list(FOLLOWS.items()):
if name not in USERS:
del FOLLOWS[name]
else:
targets.intersection_update(USERS)
FEED[:] = [name for name in FEED if name in USERS][-80:]
if removed:
_rebuild_indexes()
b64.cache_clear()
DIRTY = True
app.logger.info('Cleaner removed %d expired objects', removed)
return removed
def _snapshot_loop():
next_save = time.monotonic() + SNAPSHOT_INTERVAL
while True:
time.sleep(CLEANUP_INTERVAL)
try:
_cleanup()
if time.monotonic() >= next_save:
_save_state()
next_save = time.monotonic() + SNAPSHOT_INTERVAL
except Exception:
app.logger.exception('Maintenance failed')
_load_state()
_rebuild_indexes()
_cleanup()
DIRTY = True
if os.environ.get('MAINTENANCE_ENABLED', '1') == '1':
threading.Thread(target=_snapshot_loop, daemon=True).start()
@app.route('/')
def index():
return send_from_directory(app.static_folder, 'index.html')
@app.route('/health')
def health():
return 'ok'
@app.route('/stats')
def stats():
with LOCK:
return jsonify(users=len(USERS), records=len(RECORDS), collections=len(COLLECTIONS), tags=len(TAG_INDEX), data_bytes=RAW_BYTES, data_limit_bytes=MAX_DATA_BYTES)
@app.route('/register', methods=['POST'])
def register():
data = request.get_json(force=True, silent=True) or {}
name = str(data.get('username', '')).strip()
bio = str(data.get('bio', ''))[:140]
if not name or len(name) > 64 or '/' in name:
return (jsonify(error='bad username'), 400)
with LOCK:
if name in USERS:
return (jsonify(error='exists'), 409)
if len(USERS) >= MAX_OBJECTS:
return capacity_error()
token = secrets.token_urlsafe(24)
USERS[name] = {'token': token, 'bio': bio, 'created': time.time(), 'last_active': time.time()}
TOKENS[token] = name
FOLLOWS.setdefault(name, set())
touch_feed(name)
return jsonify(username=name, token=token)
@app.route('/me', methods=['GET'])
def me():
user = auth()
if not user:
return (jsonify(error='unauthorized'), 401)
with LOCK:
u = USERS[user]
owned = sorted(OWNER_RECORDS.get(user, set()))
return jsonify(username=user, bio=u['bio'], records=owned, following=sorted(FOLLOWS.get(user, set())))
@app.route('/users/<name>', methods=['GET'])
def user_profile(name):
with LOCK:
u = USERS.get(name)
if not u:
return (jsonify(error='not found'), 404)
owned = [record_meta(rid, RECORDS[rid]) for rid in OWNER_RECORDS.get(name, set())]
return jsonify(username=name, bio=u['bio'], followers=sum((1 for f in FOLLOWS.values() if name in f)), records=owned)
@app.route('/users/<name>/follow', methods=['POST'])
def follow(name):
global FOLLOW_COUNT
user = auth()
if not user:
return (jsonify(error='unauthorized'), 401)
with LOCK:
if name not in USERS:
return (jsonify(error='not found'), 404)
targets = FOLLOWS.setdefault(user, set())
if name not in targets:
if len(targets) >= 128 or FOLLOW_COUNT >= 20000:
return capacity_error()
targets.add(name)
FOLLOW_COUNT += 1
return jsonify(ok=True, following=sorted(targets))
@app.route('/feed', methods=['GET'])
def feed():
with LOCK:
return jsonify(recent=list(reversed(FEED[-30:])))
@app.route('/gallery', methods=['GET'])
def gallery():
try:
limit = max(1, min(int(request.args.get('limit', 100)), 200))
except ValueError:
return jsonify(error='bad limit'), 400
before = request.args.get('before')
with LOCK:
keys = iter(reversed(RECORDS))
if before:
for rid in keys:
if rid == before:
break
else:
return jsonify(error='cursor expired'), 404
ids = list(islice(keys, limit + 1))
page = ids[:limit]
items = [record_meta(rid, RECORDS[rid]) for rid in reversed(page)]
return jsonify(records=items, next_cursor=page[-1] if len(ids) > limit else None, total=len(RECORDS))
@app.route('/search', methods=['GET'])
def search():
q = request.args.get('q', '').lower()
tag = request.args.get('tag', '').lower()
with LOCK:
res = []
for rid, r in RECORDS.items():
if tag and tag not in r.get('tags', []):
continue
if q and q not in r.get('title', '').lower() and (q not in r['owner'].lower()):
continue
res.append(record_meta(rid, r))
if len(res) == 50:
break
return jsonify(results=res[:50])
@app.route('/trending', methods=['GET'])
def trending():
with LOCK:
ranked = heapq.nlargest(20, RECORDS.items(), key=lambda kv: kv[1].get('likes', 0))
return jsonify(records=[record_meta(rid, r) for rid, r in ranked[:20]])
@app.route('/tags', methods=['GET'])
def tags():
with LOCK:
return jsonify(tags={s: len(ids) for s, ids in TAG_INDEX.items()})
@app.route('/records', methods=['POST'])
def create_record():
global RAW_BYTES
user = auth()
if not user:
return (jsonify(error='unauthorized'), 401)
body = request.get_data(as_text=True)
if len(body) > 200000:
return (jsonify(error='too large'), 413)
try:
metas, own_layers, fields = parse_bd(body)
except ValueError as e:
return (jsonify(error=str(e)), 400)
with LOCK:
if len(RECORDS) >= MAX_OBJECTS or len(OWNER_RECORDS.get(user, ())) >= 128:
return capacity_error()
head = metas[0]
src = head.get('source', '-')
if src != '-':
srec = RECORDS.get(src)
if srec is None:
return (jsonify(error='source not found'), 404)
if srec['owner'] != user and (not srec['public']):
return (jsonify(error='forbidden source'), 403)
layers = {}
ref = metas[-1]
rsrc = ref.get('source', '-')
if rsrc != '-':
srec2 = RECORDS.get(rsrc)
if srec2 is None:
return (jsonify(error='source not found'), 404)
if srec2['owner'] != user:
inherit = {n: srec2['layers'][n]
for n in srec2['public'] if n in srec2['layers']}
else:
inherit = dict(srec2['layers'])
for n, b in inherit.items():
layers[n] = b
for n, b in own_layers.items():
layers[n] = b
for fx in fields['fx']:
if fx == 'grayscale' and 'video' in layers:
pass
size = sum(map(len, layers.values()))
if size > 200000 or RAW_BYTES + size > MAX_DATA_BYTES:
return capacity_error()
rid = new_id()
RECORDS[rid] = {'owner': user, 'layers': layers, 'public': list(PUBLIC_LAYERS), 'tags': fields['tags'], 'title': fields['title'], 'price': fields['price'], 'likes': 0, 'notes': fields['notes'], 'created': time.time()}
for s in fields['tags']:
TAG_INDEX.setdefault(s, []).append(rid)
OWNER_RECORDS.setdefault(user, set()).add(rid)
RAW_BYTES += size
touch_feed(user)
return jsonify(id=rid, owner=user, layers=sorted(layers.keys()), title=fields['title'], tags=fields['tags'])
@app.route('/records/<rid>', methods=['GET'])
def get_record(rid):
user = auth()
with LOCK:
rec = RECORDS.get(rid)
if rec is None:
return (jsonify(error='not found'), 404)
layers = record_full(rec) if rec['owner'] == user else record_public(rec)
n_pub = [n for n in PUBLIC_LAYERS if n in rec['layers']]
trailer = {'layers': ','.join(n_pub), 'sig': trailer_sig(rid, n_pub)}
out = {'id': rid, 'owner': rec['owner'], 'title': rec.get('title', ''), 'tags': rec.get('tags', []), 'price': rec.get('price', 0), 'likes': rec.get('likes', 0), 'layers': layers, 'trailer': trailer}
return jsonify(out)
@app.route('/records/<rid>/like', methods=['POST'])
def like(rid):
user = auth()
if not user:
return (jsonify(error='unauthorized'), 401)
with LOCK:
rec = RECORDS.get(rid)
if rec is None:
return (jsonify(error='not found'), 404)
rec['likes'] = rec.get('likes', 0) + 1
return jsonify(ok=True, likes=rec['likes'])
@app.route('/records/<rid>/comments', methods=['GET', 'POST'])
def comments(rid):
global COMMENT_COUNT
with LOCK:
if rid not in RECORDS:
return (jsonify(error='not found'), 404)
if request.method == 'GET':
return jsonify(comments=COMMENTS.get(rid, []))
user = auth()
if not user:
return (jsonify(error='unauthorized'), 401)
data = request.get_json(force=True, silent=True) or {}
text = str(data.get('text', ''))[:200]
if len(COMMENTS.get(rid, ())) >= 100 or COMMENT_COUNT >= 20000:
return capacity_error()
COMMENTS.setdefault(rid, []).append({'user': user, 'text': text, 'ts': time.time()})
COMMENT_COUNT += 1
return jsonify(ok=True, count=len(COMMENTS[rid]))
@app.route('/collections', methods=['GET', 'POST'])
def collections():
user = auth()
if not user:
return (jsonify(error='unauthorized'), 401)
if request.method == 'GET':
with LOCK:
mine = [{'id': cid, 'name': c['name'], 'items': len(c['items'])} for cid, c in COLLECTIONS.items() if c['owner'] == user]
return jsonify(collections=mine)
data = request.get_json(force=True, silent=True) or {}
name = str(data.get('name', 'untitled'))[:60]
with LOCK:
if len(COLLECTIONS) >= MAX_OBJECTS or len(OWNER_COLLECTIONS.get(user, ())) >= 32:
return capacity_error()
cid = new_id()
COLLECTIONS[cid] = {'owner': user, 'name': name, 'items': [], 'public': bool(data.get('public', True)), 'created': time.time()}
OWNER_COLLECTIONS.setdefault(user, set()).add(cid)
return jsonify(id=cid, name=name)
@app.route('/collections/<cid>/records', methods=['POST'])
def collection_add(cid):
user = auth()
if not user:
return (jsonify(error='unauthorized'), 401)
data = request.get_json(force=True, silent=True) or {}
rid = str(data.get('record_id', ''))
with LOCK:
col = COLLECTIONS.get(cid)
if col is None:
return (jsonify(error='not found'), 404)
if col['owner'] != user:
return (jsonify(error='forbidden'), 403)
if rid not in RECORDS:
return (jsonify(error='no such record'), 404)
if rid not in col['items']:
if len(col['items']) >= 128:
return capacity_error()
col['items'].append(rid)
return jsonify(ok=True, items=len(col['items']))
@app.route('/collections/<cid>', methods=['GET'])
def collection_view(cid):
user = auth()
try:
offset = max(0, int(request.args.get('offset', 0)))
except ValueError:
return jsonify(error='bad offset'), 400
with LOCK:
col = COLLECTIONS.get(cid)
if col is None:
return (jsonify(error='not found'), 404)
if not col['public'] and col['owner'] != user:
return (jsonify(error='private collection'), 403)
items = []
for rid in col['items'][offset:offset + 20]:
rec = RECORDS.get(rid)
if rec is None:
continue
entry = record_meta(rid, rec)
entry['layers'] = record_full(rec) if rec['owner'] == user else record_public(rec)
items.append(entry)
return jsonify(id=cid, name=col['name'], owner=col['owner'], items=items, total=len(col['items']), next_offset=offset + 20 if offset + 20 < len(col['items']) else None)
@app.route('/trailer/<rid>', methods=['GET'])
def trailer(rid):
user = auth()
layers_param = request.args.get('layers', '')
sig = request.args.get('sig', '')
wanted = [t for t in layers_param.split(',') if t]
if (not wanted or len(wanted) != len(set(wanted))
or any(name not in KNOWN_LAYERS for name in wanted)):
return (jsonify(error='bad signature'), 403)
with LOCK:
rec = RECORDS.get(rid)
if rec is None:
return (jsonify(error='not found'), 404)
expected = trailer_sig(rid, wanted)
if not hmac.compare_digest(sig, expected):
return (jsonify(error='bad signature'), 403)
if rec['owner'] != user and any(name not in rec['public'] for name in wanted):
return (jsonify(error='forbidden'), 403)
out = {n: b64(rec['layers'][n]) for n in wanted if n in KNOWN_LAYERS and n in rec['layers']}
return jsonify(id=rid, layers=out)
@app.route('/preview', methods=['POST'])
def preview():
data = request.get_json(force=True, silent=True) or {}
tpl = str(data.get('template', ''))[:400]
title = str(data.get('title', 'untitled'))[:60]
mood = str(data.get('mood', 'neutral'))[:30]
return jsonify(preview=tpl.replace('{title}', title).replace('{mood}', mood))
@app.route('/flag', methods=['GET'])
def get_flag():
user = auth()
if not user:
return (jsonify(error='unauthorized'), 401)
with LOCK:
for rid in sorted(OWNER_RECORDS.get(user, ()), key=lambda rid: RECORDS[rid]['created'], reverse=True):
r = RECORDS[rid]
if 'emotion' in r['layers']:
return jsonify(flag=r['layers']['emotion'].decode('utf-8', 'replace'))
return jsonify(flag='')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', '5000')))