chore: import MCTF services

- Added all seven issued service trees without omissions.
- Preserved the supplied runtime configuration, binaries, and assets.
This commit is contained in:
TakuyaYagam1 committed 2026-11-29 12:25:29 +03:00
commit 13f936bee9
1222 files changed
+21280

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
# Independent local tooling checkout
/wahrwelt-a-d-setup/
# Issued credentials and VPN material
*.ovpn
*.vpn
openconnect.conf
openvpn*.conf
wg*.conf
/team[0-9]*/
vpn/
*.age
*.age.gz
*_token.txt
*-token.txt
token.txt
tokens/
credentials/
secrets/
.netrc
.pgpass
*.key
*.p12
*.pfx
id_rsa*
id_ed25519*
# Environment files
.env
.env.*
!.env.example
!.env.sample
# Runtime state, databases, logs and captures
*.db
*.db-*
*.sqlite
*.sqlite-*
*.sqlite3
*.rdb
*.aof
*.dump
*.pid
*.sock
*.log
*.pcap
*.pcapng
*.cap
volumes/
logs/
runtime/
# Downloaded and extracted archives
*.zip
*.7z
*.rar
*.tar
*.tar.gz
*.tar.bz2
*.tar.xz
*.tgz
*.tbz2
*.txz
archives/
extracted/
unpacked/
# Caches and local tooling
__pycache__/
*.py[cod]
.pytest_cache/
.ruff_cache/
.mypy_cache/
.cache/
.venv/
venv/
node_modules/
.npm/
.pnpm-store/
.yarn/cache/
.gradle/
.idea/
.vscode/
.DS_Store
# Worktrees, coverage and build outputs
.worktrees/
coverage/
.coverage
htmlcov/
**/target/
**/build/
**/dist/
**/out/
**/.next/
**/.nuxt/
*.tsbuildinfo
# Issued services are committed exactly as provided, including their env files.
!braindance/**
!chrome-ledger/**
!dark-tariff/**
!delamain/**
!pamsave/**
!sondib/**
!towercore/**
# Local operator toolkit is maintained in its own repository.
/wahrwelt-a-d-setup/
+13
View File
@@ -0,0 +1,13 @@
.git
.vs
out
ci
handouts
checker
exploits
*.md
**/__pycache__
**/*.pyc
**/*.pyo
**/.venv
data
+16
View File
@@ -0,0 +1,16 @@
ARG PYTHON_IMAGE=python:3.12-slim
FROM ${PYTHON_IMAGE}
WORKDIR /app
COPY backend/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY backend/app.py .
COPY backend/gunicorn.conf.py .
COPY frontend ./static
RUN mkdir -p /data
ENV PORT=5000 BD_SECRET_FILE=/data/secret.bin
EXPOSE 5000
CMD ["gunicorn", "--config", "gunicorn.conf.py", "-w", "1", "--threads", "16", "-k", "gthread", \
"--timeout", "30", "-b", "0.0.0.0:5000", "app:app"]
+632
View File
@@ -0,0 +1,632 @@
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):
return hmac.new(SECRET, f'{rec_id}:{len(layer_list)}'.encode(), 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')
SNAPSHOT_INTERVAL = float(os.environ.get('SNAPSHOT_INTERVAL_SECONDS', '15'))
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 _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)
with open(STATE_FILE + '.tmp', 'w') as f:
json.dump(snapshot, f, default=_json_value, separators=(',', ':'))
os.replace(STATE_FILE + '.tmp', STATE_FILE)
except OSError:
with LOCK:
DIRTY = True
app.logger.exception('Could not save state')
def _load_state():
try:
with open(STATE_FILE) as f:
data = json.load(f)
except (OSError, ValueError):
return
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 != '-' and rsrc in RECORDS:
srec2 = RECORDS[rsrc]
if src == rsrc and 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)
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):
layers_param = request.args.get('layers', '')
sig = request.args.get('sig', '')
wanted = [t for t in layers_param.split(',') if t]
with LOCK:
rec = RECORDS.get(rid)
if rec is None:
return (jsonify(error='not found'), 404)
if sig != trailer_sig(rid, wanted):
return (jsonify(error='bad signature'), 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')))
+15
View File
@@ -0,0 +1,15 @@
import sys
worker_tmp_dir = '/tmp'
backlog = 256
worker_connections = 256
keepalive = 15
graceful_timeout = 30
def worker_exit(server, worker):
for name in ('app', 'bd_app', 'bi_app'):
module = sys.modules.get(name)
if module is not None and hasattr(module, '_save_state'):
module._save_state(force=True)
+2
View File
@@ -0,0 +1,2 @@
Flask==3.0.3
gunicorn==23.0.0
+39
View File
@@ -0,0 +1,39 @@
services:
braindance:
build: .
restart: unless-stopped
init: true
cpus: "1.0"
mem_limit: 512m
memswap_limit: 512m
pids_limit: 128
stop_grace_period: 45s
ulimits:
nofile: {soft: 1024, hard: 1024}
tmpfs:
- /tmp:size=64m,mode=1777
logging:
driver: json-file
options: {max-size: "10m", max-file: "3"}
env_file: env
environment:
PYTHONUNBUFFERED: "1"
PYTHONDONTWRITEBYTECODE: "1"
RETENTION_SECONDS: ${RETENTION_SECONDS:-1800}
FLAG_LIFETIME_SECONDS: ${FLAG_LIFETIME_SECONDS:-300}
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-15}
SNAPSHOT_INTERVAL_SECONDS: ${SNAPSHOT_INTERVAL_SECONDS:-15}
MAX_DATA_BYTES: ${BD_MAX_DATA_BYTES:-67108864}
ports:
- "5000:5000"
volumes:
- braindance-data:/data
healthcheck:
test: ["CMD", "python", "-c",
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/health', timeout=2).close()"]
interval: 10s
timeout: 3s
start_period: 10s
retries: 3
volumes:
braindance-data:
Executable
+2
View File
@@ -0,0 +1,2 @@
PORT=5000
BD_SECRET_FILE=/data/secret.bin
+643
View File
@@ -0,0 +1,643 @@
(() => {
const LAYERS = {
video: {label:'Видео', c:'var(--cy)', hex:'#2de2e6', pub:true},
audio: {label:'Аудио', c:'var(--gr)', hex:'#3dff9a', pub:true},
thermal: {label:'Тепловой канал', c:'var(--or)', hex:'#ff8a2a', pub:false},
emotion: {label:'Эмоции', c:'var(--mg)', hex:'#ff2a6d', pub:false},
};
const S = {token:null, user:null, view:'market', sort:'latest', tag:'', q:'', rec:null, col:null, cache:{}};
const $ = s => document.querySelector(s);
const $$ = s => [...document.querySelectorAll(s)];
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const short = id => String(id).slice(0, 8);
const store = {
get(k){ try { return JSON.parse(localStorage.getItem(k)); } catch(e){ return null; } },
set(k,v){ try { v == null ? localStorage.removeItem(k) : localStorage.setItem(k, JSON.stringify(v)); } catch(e){} },
};
let wireN = 0;
function wire(msg, cls){
const l = $('#wire-l'), d = document.createElement('div');
d.innerHTML = '<span class="ts">' + new Date().toLocaleTimeString('ru-RU') + '</span><span class="' + (cls||'') + '">' + esc(msg) + '</span>';
l.prepend(d);
while (l.children.length > 200) l.lastChild.remove();
$('#wire-last').textContent = msg;
$('#wire-n').textContent = ++wireN;
}
function toast(msg, kind){
const col = {ok:'var(--gr)', er:'var(--rd)', warn:'var(--yl)'}[kind] || 'var(--cy)';
const lab = {ok:'готово', er:'ошибка', warn:'уведомление'}[kind] || 'информация';
const t = document.createElement('div');
t.className = 'toast'; t.style.setProperty('--c', col);
t.innerHTML = '<small>' + lab + '</small>' + esc(msg);
$('#toasts').append(t);
setTimeout(() => { t.classList.add('out'); setTimeout(() => t.remove(), 260); }, 3200);
}
$('#wire-h').onclick = () => $('#wire').classList.toggle('on');
function localizeError(message){
const messages = {
'bad username': 'Некорректный псевдоним',
'exists': 'Псевдоним уже занят',
'unauthorized': 'Требуется авторизация',
'not found': 'Не найдено',
'too large': 'Запись слишком большая',
'bad magic': 'Неверный заголовок BDv1',
'bad layer b64': 'Некорректные данные канала Base64',
'no META': 'Отсутствует блок META',
'source not found': 'Исходная запись не найдена',
'forbidden source': 'Нет доступа к исходной записи',
'forbidden': 'Доступ запрещён',
'no such record': 'Запись не найдена',
'private collection': 'Коллекция закрыта',
'bad signature': 'Неверная подпись',
'no such fortress': 'Крепость не найдена',
'bad flag': 'Некорректные данные хранилища',
'bad icebreaker': 'Некорректный ледокол',
'bad cell': 'Некорректная ячейка',
'bad op': 'Некорректная команда',
'vm timeout': 'Превышено время работы виртуальной машины',
'bad code': 'Некорректный код программы',
};
const text = String(message);
if (text.startsWith('vm error:')) return 'Ошибка виртуальной машины';
return messages[text] || 'Не удалось выполнить запрос';
}
async function api(path, opt = {}){
const o = {method: opt.method || 'GET', headers: {}};
if (S.token) o.headers.Authorization = 'Bearer ' + S.token;
if (opt.json !== undefined){ o.headers['Content-Type'] = 'application/json'; o.body = JSON.stringify(opt.json); }
else if (opt.body !== undefined) o.body = opt.body;
let r, j = null;
try { r = await fetch(path, o); }
catch(e){ setLink(false); wire('ОШИБКА ' + o.method + ' ' + path + ' :: нет связи', 'er'); return {ok:false, status:0, data:null}; }
try { j = await r.json(); } catch(e){}
if (j && j.error) j.error = localizeError(j.error);
if (!opt.quiet || !r.ok) wire((r.ok ? 'ПРИЁМ ' : 'ОШИБКА ') + r.status + ' ' + o.method + ' ' + path + (!r.ok && j && j.error ? ' :: ' + j.error : ''), r.ok ? '' : 'er');
return {ok:r.ok, status:r.status, data:j};
}
function setLink(up){
$('#link').classList.toggle('up', up);
$('#linktx').textContent = up ? 'связь установлена' : 'нет связи';
}
function rng(str){
let h = 2166136261 >>> 0;
for (const c of String(str)){ h ^= c.charCodeAt(0); h = Math.imul(h, 16777619); }
return () => { h ^= h << 13; h ^= h >>> 17; h ^= h << 5; return ((h >>> 0) % 100000) / 100000; };
}
function paintScene(cv, id){
const x = cv.getContext('2d'), w = cv.width, hh = cv.height, R = rng(id);
const hue = Math.floor(R()*360), hue2 = (hue + 120 + R()*120) % 360;
let g = x.createLinearGradient(0, 0, 0, hh);
g.addColorStop(0, `hsl(${hue},60%,6%)`);
g.addColorStop(.6, `hsl(${hue2},75%,${18 + R()*10}%)`);
g.addColorStop(1, `hsl(${hue},50%,4%)`);
x.fillStyle = g; x.fillRect(0, 0, w, hh);
const sx = w*(.15 + R()*.7), sy = hh*(.28 + R()*.2), sr = hh*(.1 + R()*.12);
g = x.createRadialGradient(sx, sy, 0, sx, sy, sr*3.2);
g.addColorStop(0, `hsla(${hue2},100%,72%,.95)`); g.addColorStop(.28, `hsla(${hue2},100%,55%,.4)`); g.addColorStop(1, 'transparent');
x.fillStyle = g; x.fillRect(0, 0, w, hh);
for (let i = 0; i < 40; i++){ x.fillStyle = `rgba(255,255,255,${R()*.5})`; x.fillRect(R()*w, R()*hh*.5, 1, 1); }
for (let L = 0; L < 3; L++){
const base = hh*(.62 + L*.14), light = 14 - L*4;
let px = -R()*20;
while (px < w){
const bw = w*(.035 + R()*.075), bh = hh*(.12 + R()*(.5 - L*.12));
x.fillStyle = `hsl(${hue},35%,${light}%)`;
x.fillRect(px, base - bh, bw, hh);
if (R() > .7){ x.fillRect(px + bw*.45, base - bh - hh*.06, 1.5, hh*.06); }
if (L > 0){
const wc = R() > .5 ? hue2 : 48;
for (let wy = base - bh + 4; wy < hh - 3; wy += 5)
for (let wx = px + 3; wx < px + bw - 3; wx += 4)
if (R() > .8){ x.fillStyle = `hsla(${wc},100%,${60 + R()*25}%,${.35 + R()*.5})`; x.fillRect(wx, wy, 1.6, 2); }
}
if (L === 2 && R() > .82){
const sc = R() > .5 ? '#ff2a6d' : '#2de2e6';
x.fillStyle = sc; x.shadowColor = sc; x.shadowBlur = 8;
x.fillRect(px + 2, base - bh + 6, Math.max(3, bw*.3), hh*.12);
x.shadowBlur = 0;
}
px += bw + R()*3;
}
}
x.fillStyle = 'rgba(0,0,0,.28)';
for (let y = 0; y < hh; y += 3) x.fillRect(0, y, w, 1);
}
function avatar(name){
const R = rng('av:' + name), hue = Math.floor(R()*360), c1 = `hsl(${hue},90%,60%)`, c2 = `hsl(${(hue+160)%360},90%,60%)`;
let cells = '';
for (let y = 0; y < 5; y++) for (let x = 0; x < 3; x++){
if (R() > .5){
const col = R() > .3 ? c1 : c2;
cells += `<rect x="${x*4+2}" y="${y*4+2}" width="4" height="4" fill="${col}"/>`;
if (x < 2) cells += `<rect x="${(4-x)*4+2}" y="${y*4+2}" width="4" height="4" fill="${col}"/>`;
}
}
return `<svg class="av" viewBox="0 0 24 24"><rect width="24" height="24" fill="#05070c"/>${cells}<path d="M0 0h6M0 0v6M24 24h-6M24 24v-6" stroke="${c1}" stroke-width="1.2"/></svg>`;
}
function b64bytes(b){ try { const s = atob(b), a = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) a[i] = s.charCodeAt(i); return a; } catch(e){ return new Uint8Array(); } }
function bytesText(a){ try { return new TextDecoder('utf-8', {fatal:true}).decode(a); } catch(e){ return null; } }
function printable(a){ for (const c of a) if (c < 9 || (c > 13 && c < 32) || c === 127) return false; return true; }
function hexdump(a){
let out = '';
for (let i = 0; i < a.length; i += 16){
const row = a.slice(i, i + 16);
const hx = [...row].map(v => v.toString(16).padStart(2, '0')).join(' ').padEnd(47);
const tx = [...row].map(v => v >= 32 && v < 127 ? String.fromCharCode(v) : '.').join('');
out += '<span class="o">' + i.toString(16).padStart(6, '0') + '</span> ' + hx + ' ' + esc(tx) + '\n';
}
return out || '<span class="o">(пусто)</span>';
}
function paintWave(cv, bytes, hex, locked){
const r = cv.getBoundingClientRect(), dpr = window.devicePixelRatio || 1;
cv.width = Math.max(1, r.width*dpr); cv.height = Math.max(1, r.height*dpr);
const x = cv.getContext('2d'), w = cv.width, h = cv.height, mid = h/2;
x.clearRect(0, 0, w, h);
const bars = Math.floor(w / (3*dpr));
x.fillStyle = hex;
for (let i = 0; i < bars; i++){
let v;
if (locked) v = .05;
else if (!bytes.length) v = .03;
else { const b = bytes[Math.floor(i / bars * bytes.length)] || 0, n = bytes[(Math.floor(i / bars * bytes.length) + 1) % bytes.length] || 0; v = .12 + ((b*7 + n*3) % 97) / 97 * .8 * (0.55 + .45*Math.sin(i/7)); }
const bh = Math.max(1, v*(h - 8));
x.globalAlpha = .45 + v*.55;
x.fillRect(i*3*dpr, mid - bh/2, 2*dpr, bh);
}
x.globalAlpha = 1;
}
function renderChip(){
const c = $('#opchip');
if (S.user){
c.innerHTML = avatar(S.user) + '<div><div class="who">' + esc(S.user) + '</div><div class="rk">оператор</div></div>';
c.onclick = () => go('rig');
} else {
c.innerHTML = '<div><div class="who text-accent">Подключиться</div><div class="rk">гость</div></div>';
c.onclick = openAuth;
}
}
function openAuth(){ $('#au').classList.add('on'); setTimeout(() => $('#au-u').focus(), 50); }
function setSession(token, user){
S.token = token; S.user = user;
store.set('nm.session', token ? {token, user} : null);
renderChip();
if (S.view === 'rig') loadRig();
}
$$('[data-at]').forEach(b => b.onclick = () => {
$$('[data-at]').forEach(x => x.classList.toggle('on', x === b));
$('#au-new').classList.toggle('is-hidden', (b.dataset.at === 'new' ? '' : 'none') === 'none');
$('#au-tok').classList.toggle('is-hidden', (b.dataset.at === 'tok' ? '' : 'none') === 'none');
});
async function register(){
const u = $('#au-u').value.trim();
if (!u) return toast('укажите псевдоним', 'warn');
const r = await api('/register', {method:'POST', json:{username:u, bio:$('#au-b').value}});
if (!r.ok) return toast(r.status === 409 ? 'псевдоним уже занят' : (r.data && r.data.error) || 'не удалось зарегистрироваться', 'er');
setSession(r.data.token, r.data.username);
$('#au').classList.remove('on');
toast('профиль создан: ' + r.data.username, 'ok');
}
async function restore(tok, quiet){
const keep = S.token; S.token = tok;
const r = await api('/me', {quiet:true});
if (!r.ok){ S.token = keep; if (!quiet) toast('токен отклонён', 'er'); return false; }
setSession(tok, r.data.username);
if (!quiet) toast('сессия восстановлена: ' + r.data.username, 'ok');
return true;
}
$('#au-go').onclick = register;
$('#au-u').onkeydown = $('#au-b').onkeydown = e => { if (e.key === 'Enter') register(); };
$('#au-tgo').onclick = async () => { const t = $('#au-t').value.trim(); if (t && await restore(t)) $('#au').classList.remove('on'); };
function needAuth(){ if (S.token) return true; toast('сначала подключитесь', 'warn'); openAuth(); return false; }
function go(v, arg){
const h = arg ? v + '/' + encodeURIComponent(arg) : v;
if (location.hash === '#' + h) route(); else location.hash = h;
}
function route(){
const [v, a] = location.hash.replace(/^#/, '').split('/');
const view = ['market','studio','vault','rig','user'].includes(v) ? v : 'market';
S.view = view;
$$('.view').forEach(e => e.classList.toggle('on', e.id === 'v-' + view));
$$('nav a').forEach(e => e.classList.toggle('on', e.dataset.go === view));
$('#nav').classList.remove('open');
window.scrollTo(0, 0);
if (view === 'market') loadMarket();
if (view === 'studio') renderManifest();
if (view === 'vault') loadCols(a ? decodeURIComponent(a) : null);
if (view === 'rig') loadRig();
if (view === 'user') loadUser(decodeURIComponent(a || ''));
}
document.addEventListener('click', e => {
const g = e.target.closest('[data-go]');
if (g){ e.preventDefault(); go(g.dataset.go); }
const c = e.target.closest('[data-close]');
if (c) c.closest('.ov').classList.remove('on');
const u = e.target.closest('[data-user]');
if (u){ e.stopPropagation(); $('#pb').classList.remove('on'); go('user', u.dataset.user); }
});
$$('.ov').forEach(o => o.addEventListener('mousedown', e => { if (e.target === o) o.classList.remove('on'); }));
document.addEventListener('keydown', e => { if (e.key === 'Escape') $$('.ov.on').forEach(o => o.classList.remove('on')); });
$('#burger').onclick = () => $('#nav').classList.toggle('open');
window.addEventListener('hashchange', route);
function card(r){
const d = document.createElement('div');
d.className = 'card';
d.innerHTML =
'<div class="th"><canvas width="320" height="180"></canvas><span class="id">#' + esc(short(r.id)) + '</span>' +
'<span class="pr' + (r.price ? '' : ' free') + '">' + (r.price ? esc(r.price) + ' эб.' : 'бесплатно') + '</span><span class="rec">BD</span></div>' +
'<div class="cb"><div class="t">' + esc(r.title || 'Без названия') + '</div>' +
'<div class="o"><a data-user="' + esc(r.owner) + '">@' + esc(r.owner) + '</a><span>&#9829; ' + (r.likes|0) + '</span></div>' +
'<div class="chips">' + (r.tags||[]).map(t => '<span class="chip">' + esc(t) + '</span>').join('') + '</div></div>';
paintScene(d.querySelector('canvas'), r.id);
d.onclick = e => { if (!e.target.closest('[data-user]')) openRecord(r.id); };
return d;
}
function fillGrid(el, recs, emptyMsg){
el.innerHTML = '';
if (!recs.length){ el.innerHTML = '<div class="empty grid-empty"><b>Нет сигнала</b>' + esc(emptyMsg || 'здесь пока ничего нет') + '</div>'; return; }
recs.forEach(r => el.append(card(r)));
}
async function loadMarket(){
let recs;
$('#m-more').classList.add('is-hidden');
const filtering = S.q || S.tag;
if (filtering){
const p = new URLSearchParams(); if (S.q) p.set('q', S.q); if (S.tag) p.set('tag', S.tag);
const r = await api('/search?' + p, {quiet:true}); recs = r.ok ? r.data.results : [];
} else if (S.sort === 'trending'){
const r = await api('/trending', {quiet:true}); recs = r.ok ? r.data.records : [];
} else {
const r = await api('/gallery', {quiet:true}); recs = r.ok ? r.data.records.slice().reverse() : [];
$('#m-count').textContent = r.ok ? r.data.total : 0;
let cursor = r.ok ? r.data.next_cursor : null;
$('#m-more').classList.toggle('is-hidden', !cursor);
$('#m-more').onclick = async () => {
const button = $('#m-more'); button.disabled = true;
const page = await api('/gallery?before=' + encodeURIComponent(cursor));
button.disabled = false;
if (!page.ok) return;
page.data.records.slice().reverse().forEach(record => $('#m-grid').append(card(record)));
cursor = page.data.next_cursor;
button.classList.toggle('is-hidden', !cursor);
};
const dl = $('#s-srcs'); dl.innerHTML = '';
recs.slice(0, 60).forEach(x => { const o = document.createElement('option'); o.value = x.id; o.label = (x.title || 'Без названия') + ' @' + x.owner; dl.append(o); });
}
const f = $('#m-filter');
if (filtering){
f.classList.toggle('is-hidden', ('') === 'none');
f.innerHTML = '<span class="mute filter-label">ФИЛЬТР</span>' +
(S.q ? '<span class="chip y">q: ' + esc(S.q) + '</span>' : '') +
(S.tag ? '<span class="chip y">#' + esc(S.tag) + '</span>' : '') +
'<span class="chip m" id="m-reset">&times; сбросить</span><span class="mute text-11">' + recs.length + ' найдено</span>';
$('#m-reset').onclick = () => { S.q = ''; S.tag = ''; $('#m-q').value = ''; loadMarket(); loadTags(); };
} else f.classList.toggle('is-hidden', ('none') === 'none');
fillGrid($('#m-grid'), recs, filtering ? 'по вашему запросу ничего не найдено' : 'создайте первую запись');
loadTags(); loadFeed();
}
async function loadTags(){
const r = await api('/tags', {quiet:true}); if (!r.ok) return;
const t = Object.entries(r.data.tags).sort((a, b) => b[1] - a[1]).slice(0, 40);
$('#m-tagn').textContent = Object.keys(r.data.tags).length;
const el = $('#m-tags');
el.innerHTML = t.length ? '' : '<span class="mute">&mdash;</span>';
t.forEach(([n, c]) => {
const s = document.createElement('span');
s.className = 'chip' + (S.tag === n ? ' on' : '');
s.innerHTML = esc(n) + ' <b>' + c + '</b>';
s.onclick = () => { S.tag = S.tag === n ? '' : n; loadMarket(); };
el.append(s);
});
}
async function loadFeed(){
const r = await api('/feed', {quiet:true}); if (!r.ok) return;
const seen = [], el = $('#m-feed');
r.data.recent.forEach(n => { if (!seen.includes(n)) seen.push(n); });
el.innerHTML = seen.length ? '' : '<div class="empty">тишина</div>';
seen.slice(0, 10).forEach((n, i) => {
const d = document.createElement('div');
d.className = 'li'; d.dataset.user = n;
d.innerHTML = avatar(n) + '<span class="nm">' + esc(n) + '</span><span class="x">' + (i === 0 ? 'сейчас' : '-' + i) + '</span>';
el.append(d);
});
}
$$('#m-sort button').forEach(b => b.onclick = () => {
S.sort = b.dataset.s;
$$('#m-sort button').forEach(x => x.classList.toggle('on', x === b));
loadMarket();
});
const runQuery = () => { S.q = $('#m-q').value.trim(); loadMarket(); };
$('#m-go').onclick = runQuery;
$('#m-q').onkeydown = e => { if (e.key === 'Enter') runQuery(); };
async function tickTicker(){
const [s, f] = await Promise.all([api('/stats', {quiet:true}), api('/feed', {quiet:true})]);
if (!s.ok){ setLink(false); return; }
setLink(true);
const parts = [
'<span>ОПЕРАТОРЫ <b>' + s.data.users + '</b></span>',
'<span>ЗАПИСИ <b>' + s.data.records + '</b></span>',
'<span>КОЛЛЕКЦИИ <b>' + s.data.collections + '</b></span>',
'<span>ТЕГИ <b>' + s.data.tags + '</b></span>',
];
if (f.ok) f.data.recent.slice(0, 8).forEach(n => parts.push('<span>СИГНАЛ &rsaquo; <em>@' + esc(n) + '</em> в сети</span>'));
$('#ticker').innerHTML = parts.join('');
}
let playT = null, playStart = 0;
function stopPlay(){ cancelAnimationFrame(playT); playT = null; $('#pb-screen').classList.remove('playing'); }
function startPlay(){
const dur = 12000;
$('#pb-screen').classList.add('playing');
playStart = performance.now();
const ph = $('#pb-tracks .phead'), tr = $('#pb-tracks');
const step = now => {
const p = ((now - playStart) % dur) / dur;
const w = tr.clientWidth - 118;
ph.style.transform = 'translateX(' + (p * w) + 'px)';
const sec = p * dur / 1000 * 10;
$('#pb-tc').textContent = [Math.floor(sec/3600), Math.floor(sec/60)%60, Math.floor(sec)%60].map(v => String(v).padStart(2, '0')).join(':');
playT = requestAnimationFrame(step);
};
playT = requestAnimationFrame(step);
}
$('#pb-play').onclick = () => playT ? stopPlay() : startPlay();
async function openRecord(id){
const r = await api('/records/' + encodeURIComponent(id));
if (!r.ok) return toast('запись недоступна', 'er');
const d = r.data; S.rec = d;
stopPlay();
$('#pb-t').textContent = d.title || 'Без названия';
paintScene($('#pb-cv'), d.id);
$('#pb-screen').classList.remove('thermal');
$('#pb-hl').textContent = '#' + d.id;
$('#pb-hb').textContent = '@' + d.owner;
const own = S.user && S.user === d.owner;
$('#pb-meta').innerHTML =
'<dt>ID</dt><dd>' + esc(d.id) + '</dd>' +
'<dt>Владелец</dt><dd><a data-user="' + esc(d.owner) + '">@' + esc(d.owner) + '</a>' + (own ? ' <span class="chip y owner-badge">вы</span>' : '') + '</dd>' +
'<dt>Цена</dt><dd class="text-accent">' + (d.price ? esc(d.price) + ' эб.' : 'бесплатно') + '</dd>';
$('#pb-tags').innerHTML = (d.tags||[]).map(t => '<span class="chip" data-tag="' + esc(t) + '">#' + esc(t) + '</span>').join('');
$$('#pb-tags [data-tag]').forEach(c => c.onclick = () => { S.tag = c.dataset.tag; S.q = ''; $('#pb').classList.remove('on'); go('market'); loadMarket(); });
$('#pb-likes').textContent = d.likes | 0;
$('#pb-sig').innerHTML = d.trailer ? 'трейлер &middot; <b>' + esc((d.trailer.layers || '').split(',').map(n => LAYERS[n]?.label || n).join(', ') || '—') + '</b><br>подпись <b>' + esc(d.trailer.sig) + '</b>' : '';
const layers = d.layers || {};
const names = Object.keys(LAYERS);
const tr = $('#pb-tracks');
tr.innerHTML = '';
let first = null;
names.forEach(n => {
const L = LAYERS[n], has = n in layers, lock = !has && !L.pub && !own;
if (!has && !lock) return;
const bytes = has ? b64bytes(layers[n]) : new Uint8Array();
const t = document.createElement('div');
t.className = 'trk' + (lock ? ' lock' : '');
t.style.setProperty('--c', L.c);
t.innerHTML = '<div class="tn">' + L.label + '<small>' + (lock ? 'закрытый' : bytes.length + ' Б' + (L.pub ? '' : ' &middot; закрытый')) + '</small></div><div class="tw"><canvas></canvas>' + (lock ? '<span>&#9632; ЗАШИФРОВАНО &#9632;</span>' : '') + '</div>';
tr.append(t);
t._paint = () => paintWave(t.querySelector('canvas'), bytes, L.hex, lock);
t.onclick = () => {
$$('#pb-tracks .trk').forEach(x => x.classList.toggle('sel', x === t));
$('#pb-screen').classList.toggle('thermal', n === 'thermal' && !lock);
inspect(n, bytes, lock);
};
if (!first && !lock) first = t;
});
if (!tr.children.length) tr.innerHTML = '<div class="empty">no channels in this pressing</div>';
const ph = document.createElement('div'); ph.className = 'phead'; tr.append(ph);
$('#pb-chn').textContent = Object.keys(layers).length + ' кан.';
$('#pb').classList.add('on');
requestAnimationFrame(() => {
$$('#pb-tracks .trk').forEach(t => t._paint && t._paint());
if (first) first.click(); else $('#pb-insp').innerHTML = '';
});
loadComments(d.id);
}
function inspect(n, bytes, lock){
const el = $('#pb-insp');
el.style.setProperty('--c', LAYERS[n].c);
if (lock){ el.innerHTML = '<div class="insp-h"><b>' + LAYERS[n].label + '</b><span class="mute text-11">только владельцу</span></div><pre class="dump"><span class="o">канал закрыт &mdash; биржа не передаёт его содержимое</span></pre>'; return; }
const txt = bytesText(bytes), canText = txt !== null && printable(bytes);
let mode = canText ? 'text' : 'hex';
const draw = () => {
el.innerHTML = '<div class="insp-h"><b>' + LAYERS[n].label + '</b><div class="seg width-120"><button data-m="text"' + (mode === 'text' ? ' class="on"' : '') + (canText ? '' : ' disabled') + '>текст</button><button data-m="hex"' + (mode === 'hex' ? ' class="on"' : '') + '>16-рич.</button></div></div>' +
'<pre class="dump">' + (mode === 'text' ? esc(txt) || '<span class="o">(пусто)</span>' : hexdump(bytes)) + '</pre>';
el.querySelectorAll('[data-m]').forEach(b => b.onclick = () => { mode = b.dataset.m; draw(); });
};
draw();
}
async function loadComments(id){
const r = await api('/records/' + encodeURIComponent(id) + '/comments', {quiet:true});
const el = $('#pb-cmts');
const list = r.ok ? r.data.comments : [];
el.innerHTML = list.length ? '' : '<div class="mute text-12">комментариев пока нет</div>';
list.forEach(c => {
const d = document.createElement('div');
d.className = 'cm';
d.innerHTML = '<div class="u" data-user="' + esc(c.user) + '">@' + esc(c.user) + '<span>' + new Date(c.ts*1000).toLocaleTimeString('ru-RU') + '</span></div><div class="tx">' + esc(c.text) + '</div>';
el.append(d);
});
el.scrollTop = el.scrollHeight;
}
$('#pb-csend').onclick = async () => {
if (!needAuth() || !S.rec) return;
const t = $('#pb-cin').value.trim(); if (!t) return;
const r = await api('/records/' + encodeURIComponent(S.rec.id) + '/comments', {method:'POST', json:{text:t}});
if (r.ok){ $('#pb-cin').value = ''; loadComments(S.rec.id); }
};
$('#pb-cin').onkeydown = e => { if (e.key === 'Enter') $('#pb-csend').click(); };
$('#pb-like').onclick = async () => {
if (!needAuth() || !S.rec) return;
const r = await api('/records/' + encodeURIComponent(S.rec.id) + '/like', {method:'POST'});
if (r.ok){ $('#pb-likes').textContent = r.data.likes; toast('отметка «Нравится» добавлена', 'ok'); }
};
$('#pb-remix').onclick = () => {
if (!S.rec) return;
$('#s-src').value = S.rec.id;
if (!$('#s-title').value) $('#s-title').value = (S.rec.title || 'Без названия') + ' (ремикс)';
$('#pb').classList.remove('on'); stopPlay();
go('studio');
};
$('#pb-collect').onclick = async () => {
if (!needAuth() || !S.rec) return;
const r = await api('/collections', {quiet:true});
const el = $('#cp-list'); el.innerHTML = '';
const cols = r.ok ? r.data.collections : [];
if (!cols.length) el.innerHTML = '<div class="empty"><b>Нет коллекций</b><a data-go="vault" data-close>сначала создайте коллекцию</a></div>';
cols.forEach(c => {
const d = document.createElement('div');
d.className = 'li';
d.innerHTML = '<span class="nm">' + esc(c.name) + '</span><span class="x">' + c.items + ' записей &middot; ' + esc(short(c.id)) + '</span>';
d.onclick = async () => {
const a = await api('/collections/' + encodeURIComponent(c.id) + '/records', {method:'POST', json:{record_id:S.rec.id}});
if (a.ok){ toast('добавлено в ' + c.name, 'ok'); $('#cp').classList.remove('on'); }
};
el.append(d);
});
$('#cp').classList.add('on');
};
window.addEventListener('resize', () => { if ($('#pb').classList.contains('on')) $$('#pb-tracks .trk').forEach(t => t._paint && t._paint()); });
new MutationObserver(() => { if (!$('#pb').classList.contains('on')) stopPlay(); }).observe($('#pb'), {attributes:true});
const enc = s => { const b = new TextEncoder().encode(s); let o = ''; b.forEach(c => o += String.fromCharCode(c)); return btoa(o); };
function buildBD(){
const L = ['BDv1'];
const src = $('#s-src').value.trim();
L.push('META owner=' + (S.user || 'anon') + (src ? ' source=' + src : ''));
const t = $('#s-title').value.trim(); if (t) L.push('TITLE ' + t);
$('#s-tags').value.trim().toLowerCase().split(/\s+/).filter(Boolean).forEach(x => L.push('TAG ' + x));
const p = parseInt($('#s-price').value, 10) || 0; if (p > 0) L.push('PRICE ' + p);
['video','audio','thermal','emotion'].forEach(n => { const v = $('#s-' + n).value; if (v) L.push('LAYER ' + n + ' ' + enc(v)); });
return L.join('\n');
}
function renderManifest(){
const bd = buildBD();
$('#s-size').textContent = new Blob([bd]).size + ' Б';
$('#s-mani').innerHTML = bd.split('\n').map(line => {
const [k, ...rest] = line.split(' ');
if (k === 'BDv1') return '<span class="mg">' + k + '</span>';
if (k === 'LAYER'){
const b = rest[1] || '';
return '<span class="kw">LAYER</span> <span class="ar">' + esc(rest[0]) + '</span> <span class="b6">' + esc(b.length > 48 ? b.slice(0, 48) + '…' : b) + '</span>';
}
return '<span class="kw">' + esc(k) + '</span> ' + esc(rest.join(' '));
}).join('\n');
}
$$('#v-studio .in').forEach(i => i.addEventListener('input', renderManifest));
$('#s-clear').onclick = () => { $$('#v-studio .in').forEach(i => i.value = i.type === 'number' ? 0 : ''); renderManifest(); };
$('#s-press').onclick = async () => {
if (!needAuth()) return;
const btn = $('#s-press'); btn.disabled = true;
const r = await api('/records', {method:'POST', body:buildBD()});
btn.disabled = false;
if (!r.ok) return toast('не удалось создать запись: ' + ((r.data && r.data.error) || r.status), 'er');
toast('создана запись #' + short(r.data.id) + ' · ' + (r.data.layers || []).map(n => LAYERS[n]?.label || n).join(', '), 'ok');
wire('создана запись ' + r.data.id + ' каналы=' + (r.data.layers || []).map(n => LAYERS[n]?.label || n).join(','), 'ok');
go('market');
setTimeout(() => openRecord(r.data.id), 120);
};
async function loadCols(open){
const el = $('#c-list');
if (!S.token){ el.innerHTML = '<div class="empty">подключитесь для управления коллекциями</div>'; $('#c-n').textContent = 0; if (open) openCol(open); return; }
const r = await api('/collections', {quiet:true});
const cols = r.ok ? r.data.collections : [];
$('#c-n').textContent = cols.length;
el.innerHTML = cols.length ? '' : '<div class="empty">пока нет</div>';
cols.forEach(c => {
const d = document.createElement('div');
d.className = 'li' + (S.col === c.id ? ' sel' : '');
d.dataset.id = c.id;
d.innerHTML = '<span class="nm">' + esc(c.name) + '</span><span class="x">' + c.items + '</span>';
d.onclick = () => go('vault', c.id);
el.append(d);
});
if (open) openCol(open);
}
async function openCol(cid){
const r = await api('/collections/' + encodeURIComponent(cid));
if (!r.ok){ toast(r.status === 403 ? 'коллекция закрыта' : 'коллекция не найдена', 'er'); return; }
const d = r.data; S.col = d.id;
$$('#c-list .li').forEach(x => x.classList.toggle('sel', x.dataset.id === d.id));
$('#c-title').textContent = d.name;
$('#c-meta').innerHTML = esc(short(d.id)) + ' &middot; @' + esc(d.owner) + ' &middot; ' + d.total + ' записей';
$('#c-addrow').classList.toggle('is-hidden', (S.user === d.owner ? '' : 'none') === 'none');
fillGrid($('#c-grid'), d.items, 'коллекция пуста');
let offset = d.next_offset;
$('#c-more').classList.toggle('is-hidden', offset === null);
$('#c-more').onclick = async () => {
const button = $('#c-more'); button.disabled = true;
const page = await api('/collections/' + encodeURIComponent(cid) + '?offset=' + offset);
button.disabled = false;
if (!page.ok) return;
page.data.items.forEach(record => $('#c-grid').append(card(record)));
offset = page.data.next_offset;
button.classList.toggle('is-hidden', offset === null);
};
}
$('#c-make').onclick = async () => {
if (!needAuth()) return;
const r = await api('/collections', {method:'POST', json:{name:$('#c-name').value.trim() || 'Без названия', public:$('#c-pub').checked}});
if (r.ok){ $('#c-name').value = ''; toast('коллекция создана', 'ok'); go('vault', r.data.id); }
};
$('#c-open').onclick = () => { const v = $('#c-open-id').value.trim(); if (v) go('vault', v); };
$('#c-addbtn').onclick = async () => {
if (!needAuth() || !S.col) return;
const v = $('#c-add').value.trim(); if (!v) return;
const r = await api('/collections/' + encodeURIComponent(S.col) + '/records', {method:'POST', json:{record_id:v}});
if (r.ok){ $('#c-add').value = ''; toast('запись добавлена', 'ok'); openCol(S.col); loadCols(); }
else toast((r.data && r.data.error) || 'операция не удалась', 'er');
};
async function loadRig(){
if (!S.token){
$('#rig-in').classList.toggle('is-hidden', ('none') === 'none');
$('#rig-out').innerHTML = '<div class="panel"><div class="empty auth-empty"><b>Нет нейросвязи</b>создайте профиль или восстановите сессию для доступа к терминалу<div class="mt-18"><button class="btn y" id="rig-auth">Подключиться</button></div></div></div>';
$('#rig-auth').onclick = openAuth;
return;
}
$('#rig-out').innerHTML = '';
$('#rig-in').classList.toggle('is-hidden', ('') === 'none');
const me = await api('/me', {quiet:true});
if (!me.ok){ setSession(null, null); return loadRig(); }
const u = await api('/users/' + encodeURIComponent(me.data.username), {quiet:true});
$('#r-av').innerHTML = avatar(me.data.username);
$('#r-name').textContent = me.data.username;
$('#r-bio').textContent = me.data.bio || '— описание не указано —';
$('#r-recs').textContent = me.data.records.length;
$('#r-fol').textContent = u.ok ? u.data.followers : 0;
$('#r-fng').textContent = me.data.following.length;
$('#r-tokv').textContent = S.token;
fillGrid($('#r-grid'), u.ok ? u.data.records.slice().reverse() : [], 'создайте первую запись в студии');
const fl = $('#r-following');
fl.innerHTML = me.data.following.length ? '' : '<div class="empty">подписок пока нет</div>';
me.data.following.forEach(n => { const d = document.createElement('div'); d.className = 'li'; d.dataset.user = n; d.innerHTML = avatar(n) + '<span class="nm">' + esc(n) + '</span>'; fl.append(d); });
}
$('#r-tokshow').onclick = () => { const t = $('#r-tok'); t.classList.toggle('show'); $('#r-tokshow').textContent = t.classList.contains('show') ? 'Скрыть' : 'Показать'; };
$('#r-tokcp').onclick = async () => { try { await navigator.clipboard.writeText(S.token); toast('токен скопирован', 'ok'); } catch(e){ toast('нет доступа к буферу обмена', 'er'); } };
$('#r-out').onclick = () => { setSession(null, null); toast('сеанс завершён', 'warn'); go('market'); };
$('#r-pull').onclick = async () => {
const r = await api('/flag');
const v = $('#r-vault');
if (r.ok && r.data.flag){ v.className = 'vault'; v.textContent = r.data.flag; }
else { v.className = 'vault no'; v.textContent = 'на этом терминале нет закрытого эмоционального канала'; }
};
async function loadUser(name){
const r = await api('/users/' + encodeURIComponent(name));
if (!r.ok){ $('#u-h').textContent = 'неизвестно'; fillGrid($('#u-grid'), [], 'оператор не найден'); return; }
const d = r.data;
$('#u-h').textContent = d.username;
$('#u-av').innerHTML = avatar(d.username);
$('#u-name').textContent = d.username;
$('#u-bio').textContent = d.bio || '—';
$('#u-fol').textContent = d.followers;
$('#u-n').textContent = d.records.length;
$('#u-follow').classList.toggle('is-hidden', (S.user === d.username ? 'none' : '') === 'none');
$('#u-follow').onclick = async () => {
if (!needAuth()) return;
const f = await api('/users/' + encodeURIComponent(d.username) + '/follow', {method:'POST'});
if (f.ok){ toast('вы подписались на ' + d.username, 'ok'); loadUser(d.username); }
};
fillGrid($('#u-grid'), d.records.slice().reverse(), 'записей пока нет');
}
(async () => {
renderChip();
const s = store.get('nm.session');
if (s && s.token) await restore(s.token, true);
route();
tickTicker();
setInterval(tickTicker, 15000);
})();
})();
+264
View File
@@ -0,0 +1,264 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NEUROMARKET</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cpath d='M4 4h18l6 6v18H4z' fill='%2306080e' stroke='%23f3e600' stroke-width='2'/%3E%3Cpath d='M10 22V10l12 12V10' fill='none' stroke='%232de2e6' stroke-width='2.5'/%3E%3C/svg%3E">
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
<svg class="svg-filter" width="0" height="0">
<filter id="thermal"><feColorMatrix type="matrix" values=".33 .33 .33 0 0 .33 .33 .33 0 0 .33 .33 .33 0 0 0 0 0 1 0"/><feComponentTransfer><feFuncR type="table" tableValues="0 .1 .9 1 1"/><feFuncG type="table" tableValues="0 0 .2 .8 1"/><feFuncB type="table" tableValues=".2 .6 .1 0 .6"/></feComponentTransfer></filter>
</svg>
<header class="top">
<div class="top-in">
<button class="burger" id="burger" aria-label="Меню"><svg width="18" height="18" viewBox="0 0 18 18" stroke="currentColor" stroke-width="2"><path d="M2 4h14M2 9h14M2 14h9"/></svg></button>
<div class="brand" data-go="market">
<svg viewBox="0 0 40 40"><path d="M3 3h26l8 8v26H3z" fill="none" stroke="#f3e600" stroke-width="2"/><path d="M11 29V11l18 18V11" fill="none" stroke="#2de2e6" stroke-width="3"/><path d="M29 3v8h8" fill="none" stroke="#f3e600" stroke-width="2"/></svg>
<div><div class="nm" data-t="NEUROMARKET">NEURO<b>MARKET</b></div><div class="sub">биржа брейндансов &middot; сектор 7</div></div>
</div>
<nav id="nav">
<a data-go="market"><i>01</i>Рынок</a>
<a data-go="studio"><i>02</i>Студия</a>
<a data-go="vault"><i>03</i>Коллекции</a>
<a data-go="rig"><i>04</i>Терминал</a>
</nav>
<div class="sp"></div>
<div class="link" id="link"><div class="led"></div><span id="linktx">нет связи</span></div>
<div class="opchip" id="opchip"></div>
</div>
<div class="tick"><div class="lb">ЭФИР</div><div class="rail"><div class="run" id="ticker"><span>ожидание подключения&hellip;</span></div></div></div>
</header>
<main>
<section class="view" id="v-market">
<div class="vh">
<h1><small>// записей в сети: <b id="m-count">0</b></small>Рынок</h1>
<div class="row">
<div class="seg" id="m-sort"><button data-s="latest" class="on">Новые</button><button data-s="trending">Популярные</button></div>
<button class="btn y" data-go="studio"><svg viewBox="0 0 14 14" fill="currentColor"><circle cx="7" cy="7" r="5"/></svg>Записать</button>
</div>
</div>
<div class="cols">
<aside class="stack">
<div class="panel c">
<div class="ph">Поиск<span class="k">/search</span></div>
<div class="pb">
<input class="in" id="m-q" placeholder="название или псевдоним&hellip;" autocomplete="off">
<div class="row mt-10"><button class="btn sm wide" id="m-go">Найти</button></div>
</div>
</div>
<div class="panel">
<div class="ph">Теги<span class="k" id="m-tagn">0</span></div>
<div class="pb"><div class="chips" id="m-tags"><span class="mute">&mdash;</span></div></div>
</div>
<div class="panel m">
<div class="ph">Последние сигналы<span class="k">/feed</span></div>
<div class="lst" id="m-feed"></div>
</div>
</aside>
<div>
<div class="row market-filter is-hidden" id="m-filter"></div>
<div class="grid" id="m-grid"></div>
<button class="btn wide mt-12 is-hidden" id="m-more">Показать ещё</button>
</div>
</div>
</section>
<section class="view" id="v-studio">
<div class="vh"><h1><small>// создайте новый брейнданс <b>BDv1</b></small>Студия</h1></div>
<div class="cols e">
<div class="panel">
<div class="ph">Сессия<span class="k">запись</span></div>
<div class="pb">
<label class="f">Название</label>
<input class="in" id="s-title" maxlength="80" placeholder="Крыша, 03:12, кислотный дождь">
<div class="row">
<div class="g"><label class="f">Теги <span class="u">латиницей, через пробел</span></label><input class="in" id="s-tags" placeholder="rain neon rooftop"></div>
<div class="width-120"><label class="f">Цена, евробаксы</label><input class="in" id="s-price" type="number" min="0" value="0"></div>
</div>
<div class="lay channel-video"><div class="lh">Видео<span>открытый</span></div><textarea class="in" id="s-video" placeholder="что увидели глаза"></textarea></div>
<div class="lay channel-audio"><div class="lh">Аудио<span>открытый</span></div><textarea class="in" id="s-audio" placeholder="что услышали уши"></textarea></div>
<div class="lay channel-thermal"><div class="lh">Тепловой канал<span>закрытый</span></div><textarea class="in" id="s-thermal" placeholder="тепловые следы"></textarea></div>
<div class="lay channel-emotion"><div class="lh">Эмоции<span>закрытый</span></div><textarea class="in" id="s-emotion" placeholder="какие чувства это вызвало"></textarea></div>
<label class="f">Источник ремикса <span class="u">необязательно</span></label>
<input class="in" id="s-src" list="s-srcs" placeholder="ID исходной записи" autocomplete="off">
<datalist id="s-srcs"></datalist>
<div class="row mt-16">
<button class="btn y solid" id="s-press"><svg viewBox="0 0 14 14" fill="currentColor"><circle cx="7" cy="7" r="5"/></svg>Создать запись</button>
<button class="btn d" id="s-clear">Очистить</button>
</div>
</div>
</div>
<div class="stack">
<div class="panel c">
<div class="ph">Манифест<span class="k" id="s-size">0 Б</span></div>
<div class="pb"><pre class="mani" id="s-mani"></pre></div>
</div>
<div class="panel m">
<div class="ph">Каналы</div>
<div class="pb mute text-12">
Видео и аудио доступны в каждой копии. Тепловой и эмоциональный каналы закрыты на терминале владельца &mdash; покупатели получают только открытую версию. Ремикс переносит каналы исходной записи в вашу новую запись.
</div>
</div>
</div>
</div>
</section>
<section class="view" id="v-vault">
<div class="vh"><h1><small>// подборки записей</small>Коллекции</h1></div>
<div class="cols">
<aside class="stack">
<div class="panel">
<div class="ph">Новая коллекция</div>
<div class="pb">
<input class="in" id="c-name" maxlength="60" placeholder="Ночные повторы">
<label class="f collection-public"><input type="checkbox" id="c-pub" checked> Открытая</label>
<button class="btn sm wide mt-10" id="c-make">Создать</button>
</div>
</div>
<div class="panel c">
<div class="ph">Мои коллекции<span class="k" id="c-n">0</span></div>
<div class="lst" id="c-list"></div>
</div>
<div class="panel m">
<div class="ph">Открыть по ID</div>
<div class="pb"><div class="row"><input class="in g" id="c-open-id" placeholder="ID коллекции"><button class="btn sm" id="c-open">Открыть</button></div></div>
</div>
</aside>
<div class="panel">
<div class="ph"><span id="c-title">Коллекция не выбрана</span><span class="k" id="c-meta"></span></div>
<div class="pb">
<div class="row collection-add is-hidden" id="c-addrow">
<input class="in g" id="c-add" list="s-srcs" placeholder="ID записи">
<button class="btn sm y" id="c-addbtn">Добавить запись</button>
</div>
<div class="grid" id="c-grid"><div class="empty"><b>Пусто</b>выберите коллекцию слева</div></div>
<button class="btn wide mt-12 is-hidden" id="c-more">Показать ещё</button>
</div>
</div>
</div>
</section>
<section class="view" id="v-rig">
<div class="vh"><h1><small>// консоль оператора</small>Терминал</h1></div>
<div id="rig-out"></div>
<div class="cols r is-hidden" id="rig-in">
<div class="stack">
<div class="panel">
<div class="pb">
<div class="idcard"><div class="big" id="r-av"></div><div><h2 id="r-name"></h2><div class="bio" id="r-bio"></div></div></div>
<div class="stats"><div><b id="r-recs">0</b><span>Записи</span></div><div><b id="r-fol">0</b><span>Подписчики</span></div><div><b id="r-fng">0</b><span>Подписки</span></div></div>
</div>
</div>
<div class="panel c">
<div class="ph">Мои записи<span class="k">/me</span></div>
<div class="pb"><div class="grid" id="r-grid"></div></div>
</div>
</div>
<div class="stack">
<div class="panel m">
<div class="ph">Кэш эмоций<span class="k">закрытый</span></div>
<div class="pb">
<div class="mute text-12">Последний закрытый эмоциональный канал на этом терминале.</div>
<div id="r-vault" class="vault no">&mdash;</div>
<button class="btn m sm wide mt-12" id="r-pull">Расшифровать</button>
</div>
</div>
<div class="panel">
<div class="ph">Токен сессии</div>
<div class="pb">
<div class="tok" id="r-tok"><code id="r-tokv"></code><button class="btn sm d" id="r-tokshow">Показать</button><button class="btn sm" id="r-tokcp">Копировать</button></div>
<button class="btn d sm wide mt-12" id="r-out">Выйти</button>
</div>
</div>
<div class="panel c">
<div class="ph">Подписки</div>
<div class="lst" id="r-following"></div>
</div>
</div>
</div>
</section>
<section class="view" id="v-user">
<div class="vh"><h1><small>// досье оператора</small><span id="u-h">&mdash;</span></h1><button class="btn y" id="u-follow">Подписаться</button></div>
<div class="cols">
<aside class="panel">
<div class="pb">
<div class="big profile-avatar" id="u-av"></div>
<dl class="kv mt-14"><dt>Псевдоним</dt><dd id="u-name"></dd><dt>О себе</dt><dd id="u-bio"></dd><dt>Подписчики</dt><dd id="u-fol"></dd><dt>Записи</dt><dd id="u-n"></dd></dl>
</div>
</aside>
<div class="grid" id="u-grid"></div>
</div>
</section>
</main>
<div class="ov" id="pb">
<div class="dlg">
<div class="dh"><span class="tag">BD</span><span class="tt" id="pb-t"></span><button class="x-btn" data-close>&times;</button></div>
<div class="db">
<div class="l">
<div class="screen" id="pb-screen">
<canvas width="640" height="320" id="pb-cv"></canvas>
<div class="hud"><div class="scan"></div><div class="c a"></div><div class="c b"></div><div class="c cc"></div><div class="c d"></div><div class="tl" id="pb-hl"></div><div class="tr" id="pb-hr">&#9679; ЗАПИСЬ</div><div class="bl" id="pb-hb"></div>
<div class="play" id="pb-play"><svg viewBox="0 0 24 24"><path d="M6 4l14 8-14 8z"/></svg></div></div>
</div>
<div class="tline">
<div class="tl-h"><span class="tc" id="pb-tc">00:00:00</span><span>шкала времени</span><span class="sp"></span><span id="pb-chn"></span></div>
<div class="tracks" id="pb-tracks"></div>
</div>
<div class="insp" id="pb-insp"></div>
</div>
<div class="r">
<dl class="kv" id="pb-meta"></dl>
<div class="chips mt-12" id="pb-tags"></div>
<div class="acts">
<button class="btn m sm" id="pb-like">&#9829; <span id="pb-likes">0</span></button>
<button class="btn sm" id="pb-remix">Ремикс</button>
<button class="btn y sm" id="pb-collect">В коллекцию</button>
</div>
<div class="sig" id="pb-sig"></div>
<div class="sec">Комментарии</div>
<div class="cmts" id="pb-cmts"></div>
<div class="row"><input class="in g" id="pb-cin" maxlength="200" placeholder="напишите что-нибудь&hellip;"><button class="btn sm" id="pb-csend">Отправить</button></div>
</div>
</div>
</div>
</div>
<div class="ov" id="au">
<div class="dlg sm">
<div class="dh"><span class="tag">ID</span><span class="tt">Подключиться</span><button class="x-btn" data-close>&times;</button></div>
<div class="tabs2"><button class="on" data-at="new">Новый профиль</button><button data-at="tok">Токен</button></div>
<div class="pb" id="au-new">
<label class="f">Псевдоним</label><input class="in" id="au-u" maxlength="64" autocomplete="off" placeholder="v_ghost">
<label class="f">О себе</label><input class="in" id="au-b" maxlength="140" autocomplete="off" placeholder="сны на продажу">
<button class="btn y solid wide mt-16" id="au-go">Создать профиль</button>
</div>
<div class="pb is-hidden" id="au-tok">
<label class="f">Токен сессии</label><input class="in" id="au-t" autocomplete="off" placeholder="вставьте токен">
<button class="btn y solid wide mt-16" id="au-tgo">Восстановить сессию</button>
</div>
</div>
</div>
<div class="ov" id="cp">
<div class="dlg sm">
<div class="dh"><span class="tag">+</span><span class="tt">Добавить в коллекцию</span><button class="x-btn" data-close>&times;</button></div>
<div class="lst" id="cp-list"></div>
</div>
</div>
<div class="toasts" id="toasts"></div>
<div class="wire" id="wire">
<div class="wh" id="wire-h"><b>Журнал</b><span>приём/передача</span><span class="last" id="wire-last"></span><span id="wire-n">0</span></div>
<div class="wl" id="wire-l"></div>
</div>
<script src="/static/app.js"></script>
</body>
</html>
+336
View File
@@ -0,0 +1,336 @@
:root{
--bg:#05070c;--bg2:#090c15;--panel:#0b101b;--panel2:#0e1422;--line:#18223a;--line2:#26365a;
--cy:#2de2e6;--yl:#f3e600;--mg:#ff2a6d;--gr:#3dff9a;--rd:#ff3b4e;--or:#ff8a2a;
--tx:#c9dfee;--hi:#f2fbff;--dim:#5e7089;--dim2:#36445c;
--head:"Bahnschrift","DIN Alternate","Roboto Condensed","Arial Narrow",sans-serif;
--mono:"Cascadia Mono","JetBrains Mono",Consolas,"Liberation Mono",monospace;
}
*{box-sizing:border-box}
html,body{margin:0;min-height:100%}
body{
background:
linear-gradient(rgba(45,226,230,.035) 1px,transparent 1px) 0 0/100% 4px,
radial-gradient(1100px 520px at 85% -8%,rgba(45,226,230,.09),transparent 60%),
radial-gradient(900px 600px at -10% 110%,rgba(255,42,109,.08),transparent 60%),
var(--bg);
background-attachment:fixed;
color:var(--tx);font:13px/1.5 var(--mono);letter-spacing:.2px;overflow-x:hidden;
}
body::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:900;box-shadow:inset 0 0 160px rgba(0,0,0,.85)}
::selection{background:var(--yl);color:#000}
a{color:var(--cy);text-decoration:none}
button{font:inherit}
::-webkit-scrollbar{width:8px;height:8px}
::-webkit-scrollbar-thumb{background:var(--line2)}
::-webkit-scrollbar-track{background:#06090f}
.top{position:sticky;top:0;z-index:50;background:rgba(5,7,12,.92);backdrop-filter:blur(6px);border-bottom:1px solid var(--line)}
.top-in{max-width:1320px;margin:0 auto;padding:0 18px;height:62px;display:flex;align-items:center;gap:26px}
.brand{display:flex;align-items:center;gap:11px;cursor:pointer;user-select:none}
.brand svg{width:34px;height:34px;flex:none}
.brand .nm{font:700 23px/1 var(--head);letter-spacing:3px;color:var(--hi);position:relative}
.brand .nm b{color:var(--yl);font-weight:700}
.brand .nm::before,.brand .nm::after{content:attr(data-t);position:absolute;inset:0;opacity:0}
.brand:hover .nm::before{opacity:.8;color:var(--mg);animation:gl1 .35s steps(2) 2}
.brand:hover .nm::after{opacity:.8;color:var(--cy);animation:gl2 .35s steps(2) 2}
@keyframes gl1{0%{clip-path:inset(0 0 60% 0);transform:translate(-3px,0)}100%{clip-path:inset(55% 0 0 0);transform:translate(2px,0)}}
@keyframes gl2{0%{clip-path:inset(40% 0 20% 0);transform:translate(3px,0)}100%{clip-path:inset(0 0 70% 0);transform:translate(-2px,0)}}
.brand .sub{font:10px/1 var(--mono);color:var(--dim);letter-spacing:2.5px;margin-top:5px;text-transform:uppercase}
nav{display:flex;gap:2px;height:100%}
nav a{display:flex;align-items:center;gap:7px;padding:0 15px;height:100%;color:var(--dim);font:600 13px var(--head);letter-spacing:2px;text-transform:uppercase;position:relative;transition:color .15s}
nav a i{font-style:normal;font:10px var(--mono);color:var(--dim2)}
nav a:hover{color:var(--tx)}
nav a.on{color:var(--yl)}
nav a.on::after{content:"";position:absolute;left:10px;right:10px;bottom:-1px;height:2px;background:var(--yl);box-shadow:0 0 10px var(--yl)}
.top .sp{flex:1}
.link{display:flex;align-items:center;gap:8px;font-size:11px;color:var(--dim);letter-spacing:1px;text-transform:uppercase}
.link .led{width:8px;height:8px;background:var(--rd);box-shadow:0 0 8px var(--rd);transform:rotate(45deg)}
.link.up .led{background:var(--gr);box-shadow:0 0 9px var(--gr)}
.opchip{display:flex;align-items:center;gap:10px;padding:6px 12px 6px 8px;border:1px solid var(--line2);cursor:pointer;clip-path:polygon(0 0,calc(100% - 9px) 0,100% 9px,100% 100%,0 100%);transition:border-color .15s}
.opchip:hover{border-color:var(--cy)}
.opchip .av{width:26px;height:26px;flex:none}
.opchip .who{font:600 13px var(--head);letter-spacing:1.5px;color:var(--hi);text-transform:uppercase}
.opchip .rk{font-size:10px;color:var(--dim)}
.burger{display:none}
.tick{border-bottom:1px solid var(--line);background:linear-gradient(90deg,rgba(243,230,0,.06),transparent 30%);height:26px;overflow:hidden;display:flex;align-items:center;font-size:11px}
.tick .lb{flex:none;background:var(--yl);color:#000;font:700 11px var(--head);letter-spacing:2px;padding:0 12px 0 18px;height:100%;display:flex;align-items:center;clip-path:polygon(0 0,100% 0,calc(100% - 10px) 100%,0 100%)}
.tick .rail{flex:1;overflow:hidden;white-space:nowrap;mask-image:linear-gradient(90deg,transparent,#000 4%,#000 96%,transparent)}
.tick .run{display:inline-block;padding-left:100%;animation:run 60s linear infinite}
.tick .run span{margin-right:38px;color:var(--dim)}
.tick .run b{color:var(--cy);font-weight:400}
.tick .run em{color:var(--mg);font-style:normal}
@keyframes run{to{transform:translateX(-100%)}}
main{max-width:1320px;margin:0 auto;padding:22px 18px 90px}
.view{display:none;animation:vin .25s ease-out}
.view.on{display:block}
@keyframes vin{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
.vh{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:18px}
.vh h1{margin:0;font:700 30px/1 var(--head);letter-spacing:4px;text-transform:uppercase;color:var(--hi)}
.vh h1 small{display:block;font:11px var(--mono);letter-spacing:2px;color:var(--dim);margin-bottom:8px}
.vh h1 small b{color:var(--yl);font-weight:400}
.cols{display:grid;grid-template-columns:270px minmax(0,1fr);gap:20px;align-items:start}
.cols.r{grid-template-columns:minmax(0,1fr) 380px}
.cols.e{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
.panel{background:linear-gradient(180deg,var(--panel),var(--bg2));border:1px solid var(--line);position:relative;clip-path:polygon(0 0,calc(100% - 14px) 0,100% 14px,100% 100%,14px 100%,0 calc(100% - 14px))}
.panel::before{content:"";position:absolute;top:0;left:0;width:36px;height:2px;background:var(--yl)}
.panel.c::before{background:var(--cy)}
.panel.m::before{background:var(--mg)}
.ph{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:11px 14px;border-bottom:1px solid var(--line);font:600 12px var(--head);letter-spacing:2.5px;text-transform:uppercase;color:var(--hi)}
.ph .k{font:10px var(--mono);color:var(--dim);letter-spacing:1px}
.pb{padding:14px}
.stack{display:flex;flex-direction:column;gap:20px}
label.f{display:block;font-size:10px;letter-spacing:1.5px;text-transform:uppercase;color:var(--dim);margin:12px 0 5px}
label.f:first-child{margin-top:0}
label.f .p{float:right;color:var(--mg)}
label.f .u{float:right;color:var(--cy)}
.in,textarea.in,select.in{width:100%;background:#04060b;border:1px solid var(--line2);color:var(--hi);padding:9px 11px;font:13px var(--mono);outline:none;transition:border-color .15s,box-shadow .15s;border-radius:0}
.in::placeholder{color:var(--dim2)}
.in:focus{border-color:var(--cy);box-shadow:0 0 0 1px var(--cy),0 0 18px rgba(45,226,230,.12)}
textarea.in{resize:vertical;min-height:64px}
.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.row>.g{flex:1;min-width:0}
.btn{--c:var(--cy);display:inline-flex;align-items:center;justify-content:center;gap:8px;cursor:pointer;background:transparent;border:1px solid var(--c);color:var(--c);padding:9px 16px;font:600 12px var(--head);letter-spacing:2px;text-transform:uppercase;transition:background .12s,color .12s,box-shadow .12s;clip-path:polygon(0 0,calc(100% - 9px) 0,100% 9px,100% 100%,9px 100%,0 calc(100% - 9px));white-space:nowrap}
.btn:hover{background:var(--c);color:#000;box-shadow:0 0 16px var(--c)}
.btn:disabled{opacity:.4;pointer-events:none}
.btn.y{--c:var(--yl)}.btn.m{--c:var(--mg)}.btn.g{--c:var(--gr)}.btn.d{--c:var(--dim)}
.btn.solid{background:var(--c);color:#000}
.btn.solid:hover{filter:brightness(1.15)}
.btn.sm{padding:6px 11px;font-size:11px;letter-spacing:1.5px}
.btn.wide{width:100%}
.btn svg{width:14px;height:14px}
.chip{display:inline-flex;align-items:center;gap:5px;font-size:10px;letter-spacing:1px;text-transform:uppercase;padding:2px 8px;border:1px solid var(--line2);color:var(--dim);cursor:pointer;transition:.12s;white-space:nowrap}
.chip:hover{color:var(--cy);border-color:var(--cy)}
.chip.on{color:#000;background:var(--cy);border-color:var(--cy)}
.chip.y{color:var(--yl);border-color:rgba(243,230,0,.4)}
.chip.m{color:var(--mg);border-color:rgba(255,42,109,.45)}
.chip b{font-weight:400;color:var(--dim2)}
.chip.on b{color:#035}
.chips{display:flex;flex-wrap:wrap;gap:6px}
.seg{display:flex;border:1px solid var(--line2)}
.seg button{flex:1;background:none;border:0;color:var(--dim);padding:7px 10px;cursor:pointer;font:600 11px var(--head);letter-spacing:1.5px;text-transform:uppercase}
.seg button+button{border-left:1px solid var(--line2)}
.seg button.on{background:var(--yl);color:#000}
.empty{padding:34px 16px;text-align:center;color:var(--dim);font-size:12px;letter-spacing:1px}
.empty b{display:block;font:600 15px var(--head);letter-spacing:3px;color:var(--dim2);margin-bottom:6px;text-transform:uppercase}
.mute{color:var(--dim)}
.kv{display:grid;grid-template-columns:auto 1fr;gap:6px 14px;font-size:12px}
.kv dt{color:var(--dim);text-transform:uppercase;font-size:10px;letter-spacing:1.5px;padding-top:2px}
.kv dd{margin:0;color:var(--hi);word-break:break-all}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(232px,1fr));gap:16px}
.card{background:var(--panel);border:1px solid var(--line);cursor:pointer;position:relative;transition:border-color .15s,transform .15s;clip-path:polygon(0 0,100% 0,100% calc(100% - 14px),calc(100% - 14px) 100%,0 100%)}
.card:hover{border-color:var(--cy);transform:translateY(-2px)}
.card:hover .th::after{opacity:1}
.th{position:relative;aspect-ratio:16/9;overflow:hidden;background:#000}
.th canvas{width:100%;height:100%;display:block}
.th::after{content:"";position:absolute;inset:0;background:linear-gradient(transparent 45%,rgba(45,226,230,.18) 50%,transparent 55%) 0 0/100% 300%;opacity:0;animation:sweep 1.6s linear infinite;transition:opacity .2s}
@keyframes sweep{from{background-position:0 100%}to{background-position:0 0}}
.th .id{position:absolute;left:8px;top:7px;font-size:10px;color:rgba(255,255,255,.7);letter-spacing:1px;text-shadow:0 0 4px #000}
.th .pr{position:absolute;right:0;top:8px;background:var(--yl);color:#000;font:700 11px var(--head);letter-spacing:1px;padding:2px 9px 2px 12px;clip-path:polygon(7px 0,100% 0,100% 100%,0 100%)}
.th .pr.free{background:var(--gr)}
.th .rec{position:absolute;left:8px;bottom:7px;display:flex;align-items:center;gap:5px;font-size:9px;letter-spacing:2px;color:#fff}
.th .rec::before{content:"";width:6px;height:6px;border-radius:50%;background:var(--rd);box-shadow:0 0 6px var(--rd);animation:blink 1.4s steps(1) infinite}
@keyframes blink{50%{opacity:0}}
.cb{padding:10px 12px 12px}
.cb .t{font:600 15px/1.25 var(--head);letter-spacing:.8px;color:var(--hi);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.cb .o{font-size:11px;color:var(--mg);margin:2px 0 8px;display:flex;justify-content:space-between}
.cb .o span{color:var(--dim)}
.cb .chips{gap:4px;height:20px;overflow:hidden}
.cb .chip{font-size:9px;padding:1px 6px}
.lst{display:flex;flex-direction:column}
.li{display:flex;align-items:center;gap:10px;padding:9px 14px;border-bottom:1px solid var(--line);cursor:pointer;transition:background .1s}
.li:last-child{border-bottom:0}
.li:hover{background:rgba(45,226,230,.05)}
.li .av{width:24px;height:24px;flex:none}
.li .nm{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--hi)}
.li .x{font-size:10px;color:var(--dim)}
.li.sel{background:rgba(243,230,0,.06);box-shadow:inset 2px 0 var(--yl)}
.ov{position:fixed;inset:0;z-index:200;background:rgba(2,3,6,.82);backdrop-filter:blur(3px);display:none;align-items:flex-start;justify-content:center;padding:40px 16px;overflow:auto}
.ov.on{display:flex;animation:fade .18s}
@keyframes fade{from{opacity:0}}
.dlg{width:100%;max-width:1180px;background:var(--bg2);border:1px solid var(--line2);position:relative;clip-path:polygon(0 0,calc(100% - 22px) 0,100% 22px,100% 100%,22px 100%,0 calc(100% - 22px));animation:pop .22s ease-out}
.dlg.sm{max-width:440px}
@keyframes pop{from{transform:scale(.985);opacity:0}}
.dh{display:flex;align-items:center;gap:14px;padding:14px 18px;border-bottom:1px solid var(--line);background:linear-gradient(90deg,rgba(243,230,0,.07),transparent 40%)}
.dh .tag{background:var(--yl);color:#000;font:700 11px var(--head);letter-spacing:2px;padding:3px 10px}
.dh .tt{font:700 19px var(--head);letter-spacing:2px;color:var(--hi);text-transform:uppercase;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.x-btn{background:none;border:1px solid var(--line2);color:var(--dim);width:32px;height:32px;cursor:pointer;font-size:16px;flex:none}
.x-btn:hover{border-color:var(--mg);color:var(--mg)}
.db{display:grid;grid-template-columns:1fr 340px;gap:0}
.db>.l{padding:18px;border-right:1px solid var(--line);min-width:0}
.db>.r{padding:18px;min-width:0}
.screen{position:relative;aspect-ratio:16/8;background:#000;overflow:hidden;border:1px solid var(--line2)}
.screen canvas{width:100%;height:100%;display:block;transition:filter .3s}
.screen.thermal canvas{filter:url(#thermal) contrast(1.2)}
.screen .hud{position:absolute;inset:0;pointer-events:none;font-size:10px;letter-spacing:1.5px;color:rgba(255,255,255,.75)}
.screen .hud .c{position:absolute;width:18px;height:18px;border:2px solid var(--yl)}
.screen .hud .c.a{left:10px;top:10px;border-right:0;border-bottom:0}
.screen .hud .c.b{right:10px;top:10px;border-left:0;border-bottom:0}
.screen .hud .c.cc{left:10px;bottom:10px;border-right:0;border-top:0}
.screen .hud .c.d{right:10px;bottom:10px;border-left:0;border-top:0}
.screen .hud .tl{position:absolute;left:36px;top:13px}
.screen .hud .tr{position:absolute;right:36px;top:13px;color:var(--yl)}
.screen .hud .bl{position:absolute;left:36px;bottom:13px}
.screen .hud .scan{position:absolute;left:0;right:0;height:30%;background:linear-gradient(transparent,rgba(45,226,230,.12),transparent);animation:vscan 3.2s linear infinite}
@keyframes vscan{from{top:-30%}to{top:100%}}
.screen .play{position:absolute;inset:0;margin:auto;width:64px;height:64px;border:2px solid var(--yl);background:rgba(0,0,0,.5);cursor:pointer;display:flex;align-items:center;justify-content:center;transform:rotate(45deg);transition:.15s;pointer-events:auto}
.screen .play svg{transform:rotate(-45deg);width:24px;height:24px;fill:var(--yl)}
.screen .play:hover{background:var(--yl)}
.screen .play:hover svg{fill:#000}
.screen.playing .play{opacity:0}
.screen.playing:hover .play{opacity:1}
.tline{margin-top:14px;border:1px solid var(--line);background:#04060b}
.tl-h{display:flex;align-items:center;gap:12px;padding:7px 10px;border-bottom:1px solid var(--line);font-size:10px;color:var(--dim);letter-spacing:1.5px;text-transform:uppercase}
.tl-h .tc{color:var(--yl);font-size:12px;letter-spacing:1px}
.tl-h .sp{flex:1}
.tracks{position:relative}
.trk{display:grid;grid-template-columns:118px 1fr;border-bottom:1px solid var(--line);cursor:pointer;height:44px}
.trk:last-child{border-bottom:0}
.trk .tn{display:flex;flex-direction:column;justify-content:center;padding:0 10px;border-right:1px solid var(--line);font:600 12px var(--head);letter-spacing:2px;text-transform:uppercase;color:var(--c)}
.trk .tn small{font:9px var(--mono);letter-spacing:1px;color:var(--dim)}
.trk .tw{position:relative;overflow:hidden}
.trk .tw canvas{width:100%;height:100%;display:block}
.trk:hover{background:rgba(255,255,255,.02)}
.trk.sel{background:rgba(255,255,255,.035);box-shadow:inset 3px 0 var(--c)}
.trk.lock .tw{background:repeating-linear-gradient(-45deg,transparent 0 6px,rgba(255,42,109,.07) 6px 12px)}
.trk.lock .tw span{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:10px;letter-spacing:3px;color:var(--mg)}
.phead{position:absolute;top:0;bottom:0;left:118px;width:2px;background:var(--yl);box-shadow:0 0 10px var(--yl);pointer-events:none;transform-origin:left}
.phead::before{content:"";position:absolute;top:-1px;left:-5px;border:6px solid transparent;border-top-color:var(--yl)}
.insp{margin-top:14px}
.insp-h{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
.insp-h b{font:600 13px var(--head);letter-spacing:2px;text-transform:uppercase;color:var(--c,var(--cy))}
pre.dump{margin:0;background:#04060b;border:1px solid var(--line);padding:12px;color:var(--tx);font:12px/1.55 var(--mono);white-space:pre-wrap;word-break:break-all;max-height:220px;overflow:auto}
pre.dump .o{color:var(--dim2)}
.sig{margin-top:14px;font-size:11px;color:var(--dim);border-left:2px solid var(--line2);padding:4px 10px}
.sig b{color:var(--cy);font-weight:400}
.acts{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin:16px 0}
.cmts{display:flex;flex-direction:column;gap:8px;max-height:240px;overflow:auto;margin-bottom:10px}
.cm{border-left:2px solid var(--line2);padding:3px 10px}
.cm .u{font-size:11px;color:var(--mg);cursor:pointer}
.cm .u span{color:var(--dim2);margin-left:6px}
.cm .tx{color:var(--tx);word-break:break-word}
.sec{font:600 11px var(--head);letter-spacing:2.5px;text-transform:uppercase;color:var(--dim);margin:18px 0 10px;display:flex;align-items:center;gap:10px}
.sec::after{content:"";flex:1;height:1px;background:var(--line)}
.lay{border:1px solid var(--line);margin-top:10px;--c:var(--cy)}
.lay .lh{display:flex;align-items:center;justify-content:space-between;padding:7px 10px;background:#070a12;font:600 11px var(--head);letter-spacing:2px;text-transform:uppercase;color:var(--c)}
.lay .lh span{font:10px var(--mono);color:var(--dim);letter-spacing:1px}
.lay textarea{border:0;border-top:1px solid var(--line);min-height:54px}
.mani{margin:0;background:#020306;border:1px solid var(--line);padding:14px;font:12px/1.65 var(--mono);color:var(--tx);white-space:pre-wrap;word-break:break-all;min-height:280px;max-height:520px;overflow:auto}
.mani .kw{color:var(--yl)}
.mani .ar{color:var(--cy)}
.mani .b6{color:var(--dim)}
.mani .mg{color:var(--mg)}
.idcard{display:grid;grid-template-columns:96px minmax(0,1fr);gap:16px;align-items:center}
.idcard .big{width:96px;height:96px;border:1px solid var(--line2);padding:6px}
.big svg{width:100%;height:100%;display:block}
.idcard h2{margin:0;font:700 26px/1 var(--head);letter-spacing:3px;text-transform:uppercase;color:var(--hi);word-break:break-all}
.idcard .bio{color:var(--dim);margin-top:6px;font-size:12px}
.stats{display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid var(--line);margin-top:16px}
.stats div{padding:12px 14px;border-right:1px solid var(--line)}
.stats div:last-child{border-right:0}
.stats b{display:block;font:700 24px/1 var(--head);color:var(--yl)}
.stats span{font-size:10px;letter-spacing:1.5px;text-transform:uppercase;color:var(--dim)}
.tok{display:flex;gap:8px;align-items:center;background:#04060b;border:1px solid var(--line);padding:8px 10px;font-size:12px}
.tok code{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--tx);filter:blur(4px);transition:filter .2s}
.tok.show code{filter:none}
.vault{border:1px dashed rgba(61,255,154,.5);background:rgba(61,255,154,.04);padding:14px;color:var(--gr);word-break:break-all;font-size:13px;margin-top:12px}
.vault.no{border-color:var(--line2);background:none;color:var(--dim)}
.tabs2{display:flex;border-bottom:1px solid var(--line)}
.tabs2 button{flex:1;background:none;border:0;padding:12px;cursor:pointer;color:var(--dim);font:600 12px var(--head);letter-spacing:2px;text-transform:uppercase;border-bottom:2px solid transparent;margin-bottom:-1px}
.tabs2 button.on{color:var(--yl);border-bottom-color:var(--yl)}
.toasts{position:fixed;right:18px;top:96px;z-index:400;display:flex;flex-direction:column;gap:8px;pointer-events:none}
.toast{min-width:260px;max-width:360px;background:var(--panel2);border:1px solid var(--line2);border-left:3px solid var(--c,var(--cy));padding:10px 14px;font-size:12px;color:var(--hi);animation:tin .2s ease-out;box-shadow:0 8px 30px rgba(0,0,0,.5)}
.toast small{display:block;font:600 10px var(--head);letter-spacing:2px;text-transform:uppercase;color:var(--c,var(--cy));margin-bottom:2px}
.toast.out{animation:tout .25s forwards}
@keyframes tin{from{transform:translateX(30px);opacity:0}}
@keyframes tout{to{transform:translateX(30px);opacity:0}}
.wire{position:fixed;left:0;right:0;bottom:0;z-index:150;background:rgba(5,7,12,.97);border-top:1px solid var(--line2);transform:translateY(calc(100% - 28px));transition:transform .25s}
.wire.on{transform:none}
.wire .wh{height:28px;display:flex;align-items:center;gap:12px;padding:0 18px;cursor:pointer;font-size:10px;letter-spacing:2px;text-transform:uppercase;color:var(--dim)}
.wire .wh b{color:var(--yl);font-weight:400}
.wire .wh .last{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-transform:none;letter-spacing:.5px;color:var(--dim2)}
.wire .wl{height:180px;overflow:auto;padding:6px 18px;font-size:11px;border-top:1px solid var(--line)}
.wire .wl div{padding:1px 0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.wire .wl .ts{color:var(--dim2);margin-right:10px}
.wire .wl .er{color:var(--rd)}.wire .wl .ok{color:var(--gr)}.wire .wl .in{color:var(--cy)}
.brand .nm,nav a{white-space:nowrap}
@media(max-width:1180px){
.top-in{gap:16px}
.brand .sub,nav a i,.link span{display:none}
nav a{padding:0 11px}
}
@media(max-width:1060px){
.cols,.cols.r,.cols.e{grid-template-columns:minmax(0,1fr)}
.db{grid-template-columns:1fr}
.db>.l{border-right:0;border-bottom:1px solid var(--line)}
}
@media(max-width:820px){
.top-in{gap:12px;height:56px}
.brand .sub{display:none}
nav{position:fixed;top:56px;left:0;right:0;height:auto;flex-direction:column;background:var(--bg2);border-bottom:1px solid var(--line);display:none}
nav.open{display:flex}
nav a{height:46px}
.burger{display:flex;background:none;border:1px solid var(--line2);color:var(--tx);width:36px;height:36px;align-items:center;justify-content:center;cursor:pointer}
.link span{display:none}
.opchip .rk{display:none}
.vh h1{font-size:24px}
.acts{grid-template-columns:1fr}
.ov{padding:12px 8px}
}
.svg-filter{position:absolute}
.mt-10{margin-top:10px}
.market-filter{margin-bottom:12px;}
.width-120{width:120px}
.channel-video{--c:var(--cy)}
.channel-audio{--c:var(--gr)}
.channel-thermal{--c:var(--or)}
.channel-emotion{--c:var(--mg)}
.mt-16{margin-top:16px}
.text-12{font-size:12px}
.collection-public{display:flex;align-items:center;gap:8px;cursor:pointer;margin-top:10px}
.collection-add{margin-bottom:14px}
.is-hidden{display:none!important}
.mt-12{margin-top:12px}
.profile-avatar{width:100%;aspect-ratio:1;border:1px solid var(--line2);padding:10px}
.mt-14{margin-top:14px}
.opchip .who.text-accent,.kv dd.text-accent{color:var(--yl)}
.grid-empty{grid-column:1/-1}
.filter-label{font-size:11px;letter-spacing:1px}
.text-11{font-size:11px}
.owner-badge{margin-left:6px}
.auth-empty{padding:60px 16px}
.mt-18{margin-top:18px}
nav a{letter-spacing:1px;padding-left:11px;padding-right:11px}
.btn{letter-spacing:1px}
.trk .tn{letter-spacing:.5px}
.opchip{min-width:0;max-width:220px}
.opchip>div{min-width:0}
.opchip .who{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
@media(max-width:600px){
.top-in{padding:0 12px;gap:8px}
.burger{flex:none}
.brand{gap:6px;flex:none}
.brand svg{width:28px;height:28px}
.brand .nm{font-size:16px;letter-spacing:2px}
.top .sp,.top .link{display:none}
.opchip{flex:1;padding:6px;gap:6px}
.opchip .who{font-size:11px;letter-spacing:.5px}
.stats div{padding:10px 8px}
.stats span{letter-spacing:.5px}
}
+16
View File
@@ -0,0 +1,16 @@
.DS_Store
._*
__pycache__
*.py[cod]
.env
.env.*
.venv
venv
ledger_data
state
*.sqlite
*.sqlite3
*.sqlite3-*
*.key
*.key.pem
*.log
+15
View File
@@ -0,0 +1,15 @@
FROM python:3.12-slim-bookworm
WORKDIR /app
COPY backend/requirements.txt ./
RUN pip install --root-user-action=ignore --no-cache-dir -r requirements.txt
COPY backend/app ./backend/app/
COPY run.py ./
COPY frontend ./frontend/
RUN useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin chrome-ledger \
&& install -d -m 0700 -o chrome-ledger -g chrome-ledger /var/lib/chrome-ledger
USER chrome-ledger
+5
View File
@@ -0,0 +1,5 @@
from flask import current_app
def ledger():
return current_app.extensions["ledger"]
+8
View File
@@ -0,0 +1,8 @@
from flask import abort, request
def json_object():
payload = request.get_json(silent=True)
if not isinstance(payload, dict):
abort(400, "Expected a JSON object")
return payload
+68
View File
@@ -0,0 +1,68 @@
import re
import sqlite3
from uuid import uuid4
from flask import Blueprint, abort, current_app, g
from werkzeug.security import check_password_hash, generate_password_hash
from backend.app.common.utils import account_namespace, utc_now, valid_text
from backend.app.infrastructure.persistence import repositories
from backend.app.infrastructure.persistence.connection import database
from backend.app.api.request import json_object
from backend.app.api.session import owner_session, sign_in
USERNAME = re.compile(r"[A-Za-z0-9_-]{3,32}")
BAD_CREDENTIALS = "Invalid username or password"
bp = Blueprint("auth", __name__)
@bp.post("/register")
def register():
payload = json_object()
username = payload.get("username")
password = payload.get("password")
if not isinstance(username, str) or not USERNAME.fullmatch(username):
abort(400, "Username must contain 3-32 ASCII letters, digits, _ or -")
if not valid_text(password, 8, 128):
abort(400, "Password must contain 8-128 ASCII characters")
user_id = str(uuid4())
namespace = account_namespace(username)
password_hash = generate_password_hash(password, method="scrypt")
connection = database()
try:
with connection:
repositories.create_user(connection, user_id, username, namespace, password_hash, utc_now().isoformat())
except sqlite3.IntegrityError:
abort(409, "Username is already taken")
return sign_in(user_id, username), 201
@bp.post("/login")
def login():
payload = json_object()
username = payload.get("username")
password = payload.get("password")
valid_username = isinstance(username, str) and USERNAME.fullmatch(username)
valid_password = valid_text(password, 8, 128)
row = repositories.get_user_by_username(database(), username if valid_username else "")
correct = check_password_hash(
row["password_hash"] if row else current_app.extensions["ledger"].dummy_hash,
password if valid_password else "",
)
if not correct or row is None or not valid_password:
abort(401, BAD_CREDENTIALS)
return sign_in(row["id"], row["username"])
@bp.get("/home/api/me")
@owner_session
def me():
return g.user
@bp.delete("/home/api/logout")
@owner_session
def logout():
connection = database()
with connection:
repositories.delete_auth_session(connection, g.token_id)
return "", 204
+49
View File
@@ -0,0 +1,49 @@
from flask import Blueprint, g, request, abort
from backend.app.infrastructure.persistence import repositories
from backend.app.infrastructure.persistence.connection import database
from backend.app.application import implants
from backend.app.api.request import json_object
from backend.app.api.context import ledger
from backend.app.api.session import owner_session, claimed_username
bp = Blueprint("implants", __name__, url_prefix="/home/api")
@bp.post("/register_implant")
@owner_session
def register_implant():
return implants.register(database(), ledger(), g.user["id"], json_object()), 201
@bp.get("/implants")
@owner_session
def list_implants():
return implants.list_owned(database(), g.user["id"])
@bp.get("/telemetry")
@owner_session
def telemetry():
username = request.args.get("username") or g.user["username"]
if claimed_username(g.token) != username:
return {"error": "access denied"}, 403
user = repositories.get_user_by_username(database(), username)
if user is None:
abort(404)
return implants.telemetry(database(), user["id"])
@bp.get("/implants/<implant_id>")
@owner_session
def implant_passport(implant_id):
return implants.passport(database(), ledger(), implant_id, g.user["id"])
@bp.route("/check_certificate/<implant_id>/check", methods=["GET", "POST"])
@owner_session
def check_certificate(implant_id):
payload = json_object() if request.method == "POST" else None
return implants.check_certificate(database(), ledger(), implant_id, g.user["id"], payload)
@bp.post("/reissue/<implant_id>")
@owner_session
def reissue_certificate(implant_id):
return implants.reissue(database(), ledger(), implant_id, json_object()), 200
+14
View File
@@ -0,0 +1,14 @@
from flask import Blueprint
from backend.app.infrastructure.persistence.connection import database
from backend.app.application import implants
from backend.app.api.session import owner_session
from backend.app.api.context import ledger
bp = Blueprint("registry", __name__, url_prefix="/home/api")
@bp.get("/registry")
@owner_session
def registry():
return implants.registry(database(), ledger())
+66
View File
@@ -0,0 +1,66 @@
from functools import wraps
from flask import abort, g, request
from obsigil import Obsigil, ObsigilError, generate_uuid7
from backend.app.api.context import ledger
from backend.app.common.constants import AUTH_AUDIENCE, AUTH_LIFETIME
from backend.app.common.utils import utc_now
from backend.app.infrastructure.persistence import repositories
from backend.app.infrastructure.persistence.connection import database
def sign_in(user_id, username):
now = int(utc_now().timestamp())
expires_at = now + int(AUTH_LIFETIME.total_seconds())
tid = generate_uuid7()
token = Obsigil.mint(
clauses={}, mandate_key=ledger().obsigil_key, tid=tid,
sub=user_id, aud=[AUTH_AUDIENCE], exp=expires_at,
manifest={"iss": AUTH_AUDIENCE, "claims": {"username": username}},
).token()
connection = database()
with connection:
repositories.delete_auth_session(connection, g.token_id)
repositories.create_auth_session(connection, tid, user_id, expires_at)
return {"id": user_id, "username": username, "access_token": token}
def claimed_username(token):
claims = Obsigil(token, max_decoded_len=4096).claims() or {}
username = claims.get("username")
return username if isinstance(username, str) else None
def load_identity():
g.user = None
g.token = None
g.token_id = None
authorization = request.headers.get("Authorization", "").split()
if len(authorization) != 2 or authorization[0].lower() != "bearer":
return
token = authorization[1]
if len(token) > 4096:
return
now = int(utc_now().timestamp())
try:
clauses = Obsigil(
token, keys=ledger().obsigil_key, audience=AUTH_AUDIENCE,
now=now, max_decoded_len=4096,
).clauses()
except ObsigilError:
return
user_id = clauses.get("sub")
if not isinstance(user_id, str) or clauses.get("aud") != [AUTH_AUDIENCE]:
return
row = repositories.get_auth_user(database(), clauses["tid"], user_id, clauses["exp"], now)
if row is not None:
g.user = dict(row)
g.token = token
g.token_id = clauses["tid"]
def owner_session(route):
@wraps(route)
def guarded(*args, **kwargs):
if g.user is None:
abort(401, "Authentication required")
return route(*args, **kwargs)
return guarded
+36
View File
@@ -0,0 +1,36 @@
from pathlib import Path
from flask import Blueprint, abort, make_response, send_from_directory
from werkzeug.security import safe_join
from backend.app.api.context import ledger
bp = Blueprint("console", __name__)
@bp.get("/", defaults={"path": ""})
@bp.get("/<path:path>")
def console(path):
static_root = ledger().static_root
public_root = static_root / "public"
if path.startswith("src/"):
source_path = path.removeprefix("src/")
source_root = static_root / "src"
target = safe_join(str(source_root), source_path)
if target and Path(target).is_file():
return send_from_directory(source_root, source_path)
abort(404)
target = safe_join(str(public_root), path)
if path and path != "index.html" and target and Path(target).is_file():
return send_from_directory(public_root, path)
pages = {"", "login", "home", "home/register_implant", "home/check_certificate", "home/reissue", "home/implants", "home/registry"}
if path not in pages and not (
(path.startswith("home/implants/") and len(path.split("/")) == 3)
or (path.startswith("home/check_certificate/") and len(path.split("/")) == 4 and path.endswith("/check"))
):
abort(404)
index = public_root / "index.html"
if not index.is_file():
abort(503, "Console not found")
response = make_response(index.read_text(encoding="utf-8"))
response.headers["Cache-Control"] = "no-store"
return response
+64
View File
@@ -0,0 +1,64 @@
import json
from hmac import compare_digest
from Crypto.Random import get_random_bytes
from backend.app.common.constants import HEX_CHALLENGE
from backend.app.common.errors import LedgerError
from backend.app.common.utils import utc_now, valid_text
from backend.app.infrastructure.security import certificates, envelopes, keys
from backend.app.infrastructure.persistence import repositories
def implant(connection, implant_id, owner_id=None):
row = repositories.get_implant(connection, implant_id)
if row is None or (owner_id is not None and row["user_id"] != owner_id):
raise LedgerError(404, "Implant not found")
return row
def challenge(connection, ledger, implant_id, owner_id):
with connection:
connection.execute("BEGIN IMMEDIATE")
implant(connection, implant_id)
current = repositories.get_current_certificate(connection, implant_id)
if current is None or not certificates.valid(certificates.load_certificate(current["cert_pem"]), ledger.ca):
raise LedgerError(409, "Implant has no valid certificate")
nonce = get_random_bytes(32).hex()
repositories.create_implant_challenge(connection, nonce, implant_id, current["serial"], utc_now())
return {"id": implant_id, "challenge": nonce, "certificate_serial": current["serial"], "certificate": dict(current)}
def read_details(connection, ledger, implant_id, owner_id, payload):
invalid = "Invalid certificate, signature or challenge"
pem = payload.get("certificate")
signature = payload.get("signature")
nonce = payload.get("nonce")
if not valid_text(pem, 1, 60_000) or not isinstance(signature, str) or not isinstance(nonce, str):
raise LedgerError(401, invalid)
if not HEX_CHALLENGE.fullmatch(nonce):
raise LedgerError(401, invalid)
try:
certificate = certificates.load_certificate(pem)
except ValueError:
raise LedgerError(401, invalid) from None
with connection:
connection.execute("BEGIN IMMEDIATE")
row = implant(connection, implant_id)
if not compare_digest(certificates.subject_implant_id(certificate), implant_id):
raise LedgerError(401, invalid)
stored = repositories.get_certificate(connection, implant_id, format(certificate.serial_number, "x"))
if stored is None or stored["revoked_at"]:
raise LedgerError(401, invalid)
if not certificates.valid(certificates.load_certificate(stored["cert_pem"]), ledger.ca):
raise LedgerError(401, invalid)
if not keys.verify_implant_signature(certificate.public_key(), signature, nonce):
raise LedgerError(401, invalid)
consumed = repositories.consume_implant_challenge(
connection, nonce, implant_id, stored["serial"],
(utc_now() - ledger.challenge_lifetime).isoformat(),
)
if not consumed:
raise LedgerError(401, invalid)
details = json.loads(envelopes.decode_envelope(ledger.master_key, row["details"], implant_id))
return {"id": implant_id, "certificate": dict(stored), **details}
+68
View File
@@ -0,0 +1,68 @@
from hashlib import sha256
from cryptography import x509
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from backend.app.common.errors import LedgerError
from backend.app.common.utils import utc_now, valid_text
from backend.app.infrastructure.security import certificates, keys
def public_key(payload):
pem = payload.get("public_key_pem")
if not valid_text(pem, 1, 60_000):
raise LedgerError(400, "Provide a public key in PEM format")
try:
return keys.parse_public_key(pem)
except keys.UnsupportedKeyType:
raise LedgerError(400, "Supported keys are ECDSA P-256 and RSA with at least 2048 bits") from None
except ValueError:
raise LedgerError(400, "Invalid PEM public key") from None
def signing_request(payload):
pem = payload.get("csr_pem")
if not valid_text(pem, 1, 60_000):
raise LedgerError(400, "Provide a signed CSR in PEM format")
try:
request = x509.load_pem_x509_csr(pem.encode("ascii"))
if not request.is_signature_valid:
raise ValueError
key_pem = request.public_key().public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo,
).decode("ascii")
except (ValueError, UnsupportedAlgorithm):
raise LedgerError(400, "Invalid CSR or CSR signature") from None
key = public_key({"public_key_pem": key_pem})
return key, sha256(request.public_bytes(serialization.Encoding.DER)).hexdigest()
def issue(ledger, implant_id, key, now, display_name=""):
pem = certificates.issue_certificate(ledger.ca_key, ledger.ca, implant_id, key, now, display_name)
certificate = certificates.load_certificate(pem)
return {
"serial": format(certificate.serial_number, "x"),
"cert_pem": pem,
"fingerprint": certificate.fingerprint(hashes.SHA256()).hex(),
"created_at": now.isoformat(),
"not_after": certificate.not_valid_after_utc.isoformat(),
}
def describe(row, ca):
certificate = certificates.load_certificate(row["cert_pem"])
result = certificates.describe(certificate, ca)
if row["revoked_at"]:
status = "revoked"
elif result["valid"]:
status = "active"
elif certificate.not_valid_after_utc < utc_now():
status = "expired"
else:
status = "invalid"
result.update(
status=status, valid=status == "active", fingerprint=row["fingerprint"],
revoked_at=row["revoked_at"],
cert_pem=row["cert_pem"],
)
return result
+112
View File
@@ -0,0 +1,112 @@
import json
from uuid import uuid4
from backend.app.common.errors import LedgerError
from backend.app.common.utils import utc_now, valid_text
from backend.app.infrastructure.security import envelopes, keys
from backend.app.infrastructure.security.certificates import load_certificate, valid
from backend.app.infrastructure.persistence import repositories
from backend.app.application import access, certificates
def implant_text(value, label):
if isinstance(value, str) and value.isascii():
value = value.strip()
if not valid_text(value, 1, 80):
raise LedgerError(400, f"{label} must contain 1-80 ASCII characters")
return value
def register(connection, ledger, owner_id, payload):
details = {
name: implant_text(payload.get(name), label)
for name, label in (("project_codename", "Project codename"), ("installed_by", "Organization code"))
}
display_name = implant_text(payload.get("display_name"), "Name")
model = implant_text(payload.get("model"), "Model")
key = certificates.public_key(payload)
implant_id = str(uuid4())
now = utc_now()
certificate = certificates.issue(ledger, implant_id, key, now, display_name)
details_bytes = json.dumps(details, separators=(",", ":")).encode("utf-8")
record = envelopes.encode_envelope(ledger.master_key, details_bytes, implant_id)
with connection:
repositories.create_implant(
connection, implant_id, owner_id, display_name, model, record, now.isoformat(),
)
repositories.create_certificate(connection, implant_id, certificate)
repositories.create_implant_telemetry(
connection, implant_id, payload["display_name"], payload["model"], payload["public_key_pem"],
details["project_codename"], details["installed_by"],
)
return {"id": implant_id, "cert_pem": certificate["cert_pem"]}
def list_owned(connection, owner_id):
return {"implants": [dict(row) for row in repositories.list_implants(connection, owner_id)]}
def telemetry(connection, owner_id):
return {"telemetry": [dict(row) for row in repositories.list_telemetry(connection, owner_id)]}
def passport(connection, ledger, implant_id, viewer_id):
row = access.implant(connection, implant_id, viewer_id)
result = {name: row[name] for name in ("id", "display_name", "model", "created_at")}
result["owner"] = row["owner"]
certificate = repositories.get_latest_certificate(connection, implant_id)
result["certificate"] = certificates.describe(certificate, ledger.ca)
result["cert_pem"] = certificate["cert_pem"]
result["user_id"] = row["user_id"]
return result
def check_certificate(connection, ledger, implant_id, owner_id, payload=None):
result = access.challenge(connection, ledger, implant_id, owner_id) if payload is None else access.read_details(connection, ledger, implant_id, owner_id, payload)
result["certificate"] = certificates.describe(result["certificate"], ledger.ca)
return result
def reissue(connection, ledger, implant_id, payload):
key, digest = certificates.signing_request(payload)
with connection:
connection.execute("BEGIN IMMEDIATE")
row = access.implant(connection, implant_id)
current = repositories.get_current_certificate(connection, implant_id)
if current is None:
raise LedgerError(409, "Implant has no valid certificate")
if payload.get("certificate_serial") != current["serial"]:
raise LedgerError(401, "Specify the current certificate serial number")
previous = load_certificate(current["cert_pem"])
if not valid(previous, ledger.ca):
raise LedgerError(409, "Implant has no valid certificate")
message = f"reissue:{implant_id}:{current['serial']}:{digest}"
signature = payload.get("signature")
if not isinstance(signature, str):
raise LedgerError(401, "Invalid signature for the current key")
current_key_authorized = keys.verify_implant_signature(previous.public_key(), signature, message)
if not current_key_authorized and not keys.verify_implant_signature(key, signature, message):
raise LedgerError(401, "Invalid signature for the current key")
now = utc_now()
details = json.loads(envelopes.decode_envelope(ledger.master_key, row["details"], implant_id))
certificate = current
if current_key_authorized:
issued = certificates.issue(ledger, implant_id, key, now, row["display_name"])
repositories.revoke_certificates(connection, implant_id, now.isoformat())
repositories.create_certificate(connection, implant_id, issued)
certificate = repositories.get_certificate(connection, implant_id, issued["serial"])
result = {name: row[name] for name in ("id", "display_name", "model", "created_at", "owner", "user_id")}
result.update(success=True, cert_pem=certificate["cert_pem"], **details)
result["certificate"] = certificates.describe(certificate, ledger.ca)
return result
def registry(connection, ledger):
results = {}
for row in repositories.list_registry(connection):
if row["id"] not in results:
results[row["id"]] = {name: row[name] for name in ("id", "display_name", "model", "created_at", "owner")}
results[row["id"]]["certificates"] = []
results[row["id"]]["certificates"].append(certificates.describe(row, ledger.ca))
return {"results": list(results.values())}
+85
View File
@@ -0,0 +1,85 @@
import os
import sqlite3
from contextlib import closing
from pathlib import Path
from types import SimpleNamespace
from Crypto.Random import get_random_bytes
from flask import Flask
from werkzeug.exceptions import HTTPException
from werkzeug.security import generate_password_hash
from backend.app.common.constants import LIFETIME
from backend.app.common.errors import LedgerError
from backend.app.common.utils import utc_now
from backend.app.infrastructure.security.certificates import load_or_create_ca
from backend.app.infrastructure.persistence.connection import close_database, database_path, initialize
from backend.app.api import views
from backend.app.api.session import load_identity
from backend.app.api.routes import auth, implants, registry
def load_key(state_dir, name, size=32):
path = state_dir / name
if path.is_file():
key = path.read_bytes()
if len(key) != size:
raise RuntimeError(f"Invalid state key: {name}")
return key
key = get_random_bytes(size)
with path.open("xb") as handle:
os.chmod(path, 0o600)
handle.write(key)
return key
def create_app(database_path_override=None):
db_path = Path(database_path_override or database_path())
initialize(db_path)
state_dir = db_path.parent / "state"
state_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
with closing(sqlite3.connect(db_path)) as connection:
has_implants = connection.execute("SELECT EXISTS(SELECT 1 FROM implants)").fetchone()[0]
required = ("master.key", "ca.key.pem", "ca.cert.pem")
if has_implants and any(not (state_dir / name).is_file() for name in required):
raise RuntimeError("Existing implants require the original master key and CA files; restore the state directory")
if (state_dir / "ca.key.pem").is_file() != (state_dir / "ca.cert.pem").is_file():
raise RuntimeError("Both CA key and certificate must be present")
master_key = load_key(state_dir, "master.key")
ca_key, ca = load_or_create_ca(state_dir, utc_now())
app = Flask(__name__, static_folder=None)
app.config.update(
DATABASE=str(db_path),
MAX_CONTENT_LENGTH=65_536,
)
app.extensions["ledger"] = SimpleNamespace(
ca_key=ca_key, ca=ca, master_key=master_key,
obsigil_key=load_key(state_dir, "obsigil.key", 64),
dummy_hash=generate_password_hash(get_random_bytes(32).hex(), method="scrypt"),
challenge_lifetime=LIFETIME,
static_root=Path(__file__).resolve().parents[3] / "frontend",
)
app.before_request(load_identity)
for blueprint in (auth.bp, implants.bp, registry.bp, views.bp):
app.register_blueprint(blueprint)
app.teardown_appcontext(close_database)
@app.errorhandler(LedgerError)
def service_error(error):
return {"error": str(error)}, error.status
@app.errorhandler(HTTPException)
def http_error(error):
response = error.get_response()
response.set_data(app.json.dumps({"error": error.description}))
response.mimetype = "application/json"
return response
@app.after_request
def protect_private_responses(response):
if response.is_json:
response.headers["Cache-Control"] = "no-store"
return response
return app
+10
View File
@@ -0,0 +1,10 @@
import re
from datetime import timedelta
LIFETIME = timedelta(seconds=60)
AUTH_LIFETIME = timedelta(hours=12)
AUTH_AUDIENCE = "chrome-ledger"
HEX_CHALLENGE = re.compile(r"[0-9a-fA-F]{64}")
+4
View File
@@ -0,0 +1,4 @@
class LedgerError(Exception):
def __init__(self, status, message):
super().__init__(message)
self.status = status
+17
View File
@@ -0,0 +1,17 @@
import unicodedata
from datetime import UTC, datetime
def utc_now():
return datetime.now(UTC)
def account_namespace(username):
return unicodedata.normalize("NFKC", username).casefold()
def valid_text(value, minimum, maximum):
if not isinstance(value, str):
return False
if len(value) < minimum or len(value) > maximum:
return False
return value.isascii()
@@ -0,0 +1,37 @@
import os
import sqlite3
from contextlib import closing
from pathlib import Path
from flask import current_app, g
from backend.app.infrastructure.persistence.schema import SCHEMA
def database_path():
default = Path(__file__).resolve().parents[4] / "ledger_data" / "ledger.sqlite3"
return Path(os.environ.get("LEDGER_DB", default)).resolve()
def initialize(path):
path = Path(path)
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
with closing(sqlite3.connect(path)) as connection:
connection.execute("PRAGMA auto_vacuum = INCREMENTAL")
connection.execute("PRAGMA journal_mode = WAL")
connection.execute("PRAGMA busy_timeout = 5000")
connection.execute("PRAGMA foreign_keys = ON")
connection.executescript(SCHEMA)
connection.execute("PRAGMA user_version = 9")
def database():
if "database" not in g:
connection = sqlite3.connect(current_app.config["DATABASE"], timeout=5)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA busy_timeout = 5000")
connection.execute("PRAGMA foreign_keys = ON")
g.database = connection
return g.database
def close_database(_error):
connection = g.pop("database", None)
if connection is not None:
connection.close()
@@ -0,0 +1,126 @@
from backend.app.common.constants import LIFETIME
def get_user_by_username(connection, username):
return connection.execute(
"SELECT id, username, namespace, password_hash FROM users WHERE username = ?", (username,),
).fetchone()
def create_auth_session(connection, tid, user_id, expires_at):
connection.execute(
"INSERT INTO auth_sessions (tid, user_id, expires_at) VALUES (?, ?, ?)",
(tid, user_id, expires_at),
)
def get_auth_user(connection, tid, user_id, expires_at, now):
return connection.execute(
"SELECT u.id, u.username FROM auth_sessions s JOIN users u ON u.id = s.user_id "
"WHERE s.tid = ? AND s.user_id = ? AND s.expires_at = ? AND s.expires_at > ?",
(tid, user_id, expires_at, now),
).fetchone()
def delete_auth_session(connection, tid):
connection.execute("DELETE FROM auth_sessions WHERE tid = ?", (tid,))
def create_user(connection, user_id, username, namespace, password_hash, created_at):
connection.execute(
"INSERT INTO users (id, username, namespace, password_hash, created_at) VALUES (?, ?, ?, ?, ?)",
(user_id, username, namespace, password_hash, created_at),
)
def create_implant(connection, implant_id, user_id, display_name, model, details, created_at):
connection.execute(
"INSERT INTO implants "
"(id, user_id, display_name, model, details, created_at) "
"VALUES (?, ?, ?, ?, ?, ?)",
(implant_id, user_id, display_name, model, details, created_at),
)
def create_implant_telemetry(connection, implant_id, display_name, model, public_key_pem, project_codename, installed_by):
connection.execute(
"INSERT INTO implant_telemetry "
"(implant_id, display_name, model, public_key_pem, project_codename, installed_by) VALUES (?, ?, ?, ?, ?, ?)",
(implant_id, display_name, model, public_key_pem, project_codename, installed_by),
)
def get_implant(connection, implant_id):
return connection.execute(
"SELECT i.*, u.username AS owner "
"FROM implants i JOIN users u ON u.id = i.user_id WHERE i.id = ?", (implant_id,),
).fetchone()
def list_implants(connection, owner_id):
return connection.execute(
"SELECT i.id, i.display_name, i.model, i.created_at, u.username AS owner "
"FROM implants i JOIN users u ON u.id = i.user_id "
"WHERE i.user_id = ? ORDER BY i.created_at DESC, i.id DESC", (owner_id,),
).fetchall()
def list_telemetry(connection, owner_id):
return connection.execute(
"SELECT t.display_name, t.model, t.public_key_pem, t.project_codename, t.installed_by "
"FROM implants i JOIN implant_telemetry t ON t.implant_id = i.id "
"WHERE i.user_id = ? ORDER BY i.created_at DESC, i.id DESC", (owner_id,),
).fetchall()
def list_registry(connection):
return connection.execute(
"SELECT i.id, i.display_name, i.model, i.created_at, u.username AS owner, "
"c.cert_pem, c.fingerprint, c.revoked_at "
"FROM implants i JOIN users u ON u.id = i.user_id "
"JOIN implant_certificates c ON c.implant_id = i.id "
"ORDER BY i.created_at DESC, i.id DESC, c.rowid DESC",
).fetchall()
def create_certificate(connection, implant_id, certificate):
connection.execute(
"INSERT INTO implant_certificates "
"(serial, implant_id, cert_pem, fingerprint, created_at, not_after) VALUES (?, ?, ?, ?, ?, ?)",
(certificate["serial"], implant_id, certificate["cert_pem"], certificate["fingerprint"],
certificate["created_at"], certificate["not_after"]),
)
def revoke_certificates(connection, implant_id, now):
connection.execute(
"UPDATE implant_certificates SET revoked_at = ? WHERE implant_id = ? AND revoked_at IS NULL",
(now, implant_id),
)
def get_current_certificate(connection, implant_id):
return connection.execute(
"SELECT * FROM implant_certificates WHERE implant_id = ? AND revoked_at IS NULL "
"ORDER BY rowid DESC LIMIT 1", (implant_id,),
).fetchone()
def get_latest_certificate(connection, implant_id):
return connection.execute(
"SELECT * FROM implant_certificates WHERE implant_id = ? ORDER BY rowid DESC LIMIT 1",
(implant_id,),
).fetchone()
def get_certificate(connection, implant_id, serial):
return connection.execute(
"SELECT * FROM implant_certificates WHERE implant_id = ? AND serial = ?",
(implant_id, serial),
).fetchone()
def create_implant_challenge(connection, nonce, implant_id, serial, now):
connection.execute(
"DELETE FROM implant_challenges WHERE created_at <= ?", ((now - LIFETIME).isoformat(),),
)
connection.execute(
"INSERT INTO implant_challenges (nonce, implant_id, certificate_serial, created_at) "
"VALUES (?, ?, ?, ?)", (nonce, implant_id, serial, now.isoformat()),
)
def consume_implant_challenge(connection, nonce, implant_id, certificate_serial, cutoff):
return connection.execute(
"DELETE FROM implant_challenges WHERE nonce = ? AND implant_id = ? AND certificate_serial = ? AND created_at > ?",
(nonce, implant_id, certificate_serial, cutoff),
).rowcount
@@ -0,0 +1,51 @@
SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
namespace TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS users_created_at ON users (created_at);
CREATE TABLE IF NOT EXISTS auth_sessions (
tid TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS auth_sessions_user_id ON auth_sessions (user_id);
CREATE INDEX IF NOT EXISTS auth_sessions_expires_at ON auth_sessions (expires_at);
CREATE TABLE IF NOT EXISTS implants (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id),
display_name TEXT NOT NULL CHECK(length(trim(display_name)) BETWEEN 1 AND 80),
model TEXT NOT NULL DEFAULT '',
details TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS implants_user_id ON implants (user_id);
CREATE INDEX IF NOT EXISTS implants_created_at ON implants (created_at);
CREATE TABLE IF NOT EXISTS implant_telemetry (
implant_id TEXT PRIMARY KEY REFERENCES implants(id) ON DELETE CASCADE,
display_name TEXT NOT NULL,
model TEXT NOT NULL,
public_key_pem TEXT NOT NULL,
project_codename TEXT NOT NULL,
installed_by TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS implant_certificates (
serial TEXT PRIMARY KEY,
implant_id TEXT NOT NULL REFERENCES implants(id) ON DELETE CASCADE,
cert_pem TEXT NOT NULL,
fingerprint TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL,
not_after TEXT NOT NULL,
revoked_at TEXT
);
CREATE TABLE IF NOT EXISTS implant_challenges (
nonce TEXT PRIMARY KEY,
implant_id TEXT NOT NULL REFERENCES implants(id) ON DELETE CASCADE,
certificate_serial TEXT NOT NULL REFERENCES implant_certificates(serial),
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS implant_challenges_created_at ON implant_challenges (created_at);
"""
@@ -0,0 +1,105 @@
import os
from datetime import timedelta
from cryptography import x509
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
from backend.app.common.utils import utc_now
ORGANIZATION = "Chrome Ledger"
def certificate_builder(subject, issuer, public_key, now, days):
return (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(public_key)
.serial_number(x509.random_serial_number())
.not_valid_before(now)
.not_valid_after(now + timedelta(days=days))
)
def create_ca(now):
key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, "Chrome Ledger Root CA"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, ORGANIZATION),
])
certificate = (
certificate_builder(name, name, key.public_key(), now, 365)
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
.sign(key, hashes.SHA256())
)
return key, certificate
def load_or_create_ca(state_dir, now):
key_path = state_dir / "ca.key.pem"
cert_path = state_dir / "ca.cert.pem"
if key_path.is_file() and cert_path.is_file():
key = serialization.load_pem_private_key(key_path.read_bytes(), password=None)
ca = x509.load_pem_x509_certificate(cert_path.read_bytes())
key_bytes = key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
ca_bytes = ca.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
if key_bytes != ca_bytes:
raise ValueError("CA key does not match its certificate")
return key, ca
key, ca = create_ca(now)
key_path.write_bytes(
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
)
)
os.chmod(key_path, 0o600)
cert_path.write_bytes(ca.public_bytes(serialization.Encoding.PEM))
return key, ca
def issue_certificate(ca_key, ca, implant_id, public_key, now, display_name=""):
common_name = display_name[:64]
subject = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, implant_id),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, ORGANIZATION),
])
certificate = (
certificate_builder(subject, ca.subject, public_key, now, 30)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.SubjectAlternativeName([
x509.UniformResourceIdentifier(f"urn:chrome-ledger:implant:{implant_id}"),
]), critical=False)
.sign(ca_key, hashes.SHA256())
)
return certificate.public_bytes(serialization.Encoding.PEM).decode("ascii")
def load_certificate(pem):
return x509.load_pem_x509_certificate(pem.encode("ascii"))
def subject_implant_id(certificate):
attributes = certificate.subject.get_attributes_for_oid(NameOID.ORGANIZATIONAL_UNIT_NAME)
return attributes[0].value if len(attributes) == 1 else ""
def valid(certificate, ca):
now = utc_now()
if not (certificate.not_valid_before_utc <= now <= certificate.not_valid_after_utc
and ca.not_valid_before_utc <= now <= ca.not_valid_after_utc):
return False
try:
certificate.verify_directly_issued_by(ca)
except (InvalidSignature, ValueError, UnsupportedAlgorithm):
return False
return True
def describe(certificate, ca):
return {
"subject": certificate.subject.rfc4514_string(),
"issuer": certificate.issuer.rfc4514_string(),
"serial": format(certificate.serial_number, "x"),
"not_before": certificate.not_valid_before_utc.isoformat(),
"not_after": certificate.not_valid_after_utc.isoformat(),
"valid": valid(certificate, ca),
}
@@ -0,0 +1,34 @@
import base64
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
NONCE_SIZE = 16
TAG_SIZE = 16
def seal(key, plaintext, associated_data):
cipher = AES.new(key, AES.MODE_GCM, nonce=get_random_bytes(NONCE_SIZE))
cipher.update(associated_data)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
return cipher.nonce + ciphertext + tag
def unseal(key, envelope, associated_data):
cipher = AES.new(key, AES.MODE_GCM, nonce=envelope[:NONCE_SIZE])
cipher.update(associated_data)
plaintext = cipher.decrypt_and_verify(
envelope[NONCE_SIZE:-TAG_SIZE],
envelope[-TAG_SIZE:],
)
return plaintext
def encode_envelope(key, secret, implant_id):
associated_data = implant_id.encode("ascii")
envelope = seal(key, secret, associated_data)
return base64.b64encode(envelope).decode("ascii")
def decode_envelope(key, envelope, implant_id):
associated_data = implant_id.encode("ascii")
decoded = base64.b64decode(envelope, validate=True)
return unseal(key, decoded, associated_data).decode("utf-8")
+34
View File
@@ -0,0 +1,34 @@
import base64
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
class UnsupportedKeyType(ValueError):
pass
def parse_public_key(pem):
if not isinstance(pem, str):
raise ValueError("PEM must be a string")
try:
key = serialization.load_pem_public_key(pem.encode("utf-8"))
except (ValueError, UnsupportedAlgorithm):
raise ValueError("Invalid PEM public key") from None
if isinstance(key, rsa.RSAPublicKey) and key.key_size >= 2048:
return key
if isinstance(key, ec.EllipticCurvePublicKey) and isinstance(key.curve, ec.SECP256R1):
return key
raise UnsupportedKeyType("Unsupported public key type")
def verify_implant_signature(public_key, signature, nonce):
try:
signed = base64.b64decode(signature, validate=True)
if isinstance(public_key, ec.EllipticCurvePublicKey):
public_key.verify(signed, nonce.encode("ascii"), ec.ECDSA(hashes.SHA256()))
else:
public_key.verify(signed, nonce.encode("ascii"), padding.PKCS1v15(), hashes.SHA256())
except (InvalidSignature, ValueError):
return False
return True
+6
View File
@@ -0,0 +1,6 @@
Flask==3.1.3
Werkzeug==3.1.9
gunicorn==27.0.1
pycryptodome==4.5.0
cryptography==50.0.2
obsigil==1.0.0
+13
View File
@@ -0,0 +1,13 @@
FROM python:3.12-slim-bookworm
RUN useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin ledger-cleaner \
&& install -d -m 0700 -o ledger-cleaner -g ledger-cleaner /var/lib/chrome-ledger
COPY --chmod=755 cleaner.sh /cleaner.sh
COPY cleaner.py /cleaner.py
USER ledger-cleaner
HEALTHCHECK --interval=10m --timeout=5s --start-period=90s --retries=2 CMD python3 -c "import os,time; p='/tmp/cleaner-last-success'; raise SystemExit(0 if os.path.exists(p) and time.time()-os.path.getmtime(p)<720 else 1)"
CMD ["/cleaner.sh"]
+54
View File
@@ -0,0 +1,54 @@
import os
import sqlite3
from datetime import UTC, datetime, timedelta
RETENTION = timedelta(minutes=10)
def main():
connection = sqlite3.connect(os.environ["LEDGER_DB"], timeout=5)
connection.execute("PRAGMA busy_timeout = 5000")
connection.execute("PRAGMA foreign_keys = ON")
tables = {
row[0]
for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'table'")
}
cutoff = (datetime.now(UTC) - RETENTION).isoformat()
deleted = []
if "auth_sessions" in tables:
cursor = connection.execute(
"DELETE FROM auth_sessions WHERE expires_at <= ?",
(int(datetime.now(UTC).timestamp()),),
)
deleted.append(f"sessions={cursor.rowcount}")
if "implant_challenges" in tables:
cursor = connection.execute(
"DELETE FROM implant_challenges WHERE created_at <= ?",
(cutoff,),
)
deleted.append(f"challenges={cursor.rowcount}")
if "implants" in tables:
cursor = connection.execute(
"DELETE FROM implants WHERE created_at <= ?",
(cutoff,),
)
deleted.append(f"implants={cursor.rowcount}")
if "users" in tables and "implants" in tables:
cursor = connection.execute(
"DELETE FROM users WHERE created_at <= ? "
"AND NOT EXISTS (SELECT 1 FROM implants WHERE implants.user_id = users.id)",
(cutoff,),
)
deleted.append(f"users={cursor.rowcount}")
connection.commit()
connection.execute("PRAGMA wal_checkpoint(PASSIVE)")
connection.execute("PRAGMA optimize")
connection.execute("PRAGMA incremental_vacuum").fetchall()
connection.close()
print("cleaned " + " ".join(deleted), flush=True)
if __name__ == "__main__":
main()
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
while true; do
if python3 /cleaner.py; then
touch /tmp/cleaner-last-success
fi
sleep 600
done
+80
View File
@@ -0,0 +1,80 @@
name: chrome-ledger
services:
service:
build: .
command: ["python", "run.py"]
environment:
LEDGER_DB: "/var/lib/chrome-ledger/ledger.sqlite3"
PYTHONDONTWRITEBYTECODE: "1"
PYTHONUNBUFFERED: "1"
ports:
- "8081:8080"
volumes:
- ledger_data:/var/lib/chrome-ledger
restart: unless-stopped
read_only: true
tmpfs:
- /tmp:size=64m,mode=1777
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
stop_grace_period: 20s
deploy:
resources:
limits:
cpus: "2.0"
memory: 512M
pids: 256
reservations:
cpus: "0.25"
memory: 128M
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/login', timeout=3).close()"]
interval: 10s
timeout: 5s
start_period: 15s
retries: 3
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
cleaner:
build: ./cleaner
depends_on:
- service
environment:
LEDGER_DB: "/var/lib/chrome-ledger/ledger.sqlite3"
PYTHONDONTWRITEBYTECODE: "1"
PYTHONUNBUFFERED: "1"
volumes:
- ledger_data:/var/lib/chrome-ledger
restart: unless-stopped
read_only: true
tmpfs:
- /tmp:size=16m,mode=1777
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.25"
memory: 64M
pids: 64
reservations:
cpus: "0.05"
memory: 16M
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes:
ledger_data:
name: chrome-ledger-data
+41
View File
@@ -0,0 +1,41 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chrome Ledger</title>
<link rel="stylesheet" href="/src/shared/styles/main.css">
</head>
<body>
<div class="layout signed-out" id="layout">
<header class="topbar">
<div class="topbar-inner">
<a class="brand" href="/">
<span class="brand-mark" aria-hidden="true"></span>
Chrome Ledger
</a>
<nav id="nav" aria-label="Основная навигация">
<a href="/home/implants" data-auth>Импланты</a>
<a href="/home/registry" data-auth>Реестр</a>
<a href="/home/register_implant" data-auth>Новый имплант</a>
<a href="/home/check_certificate" data-auth>Проверка</a>
<a href="/home/reissue" data-auth>Перевыпуск</a>
</nav>
<div class="account" id="account">
<span id="username"></span>
<button class="secondary" type="button" id="logout">Выйти</button>
<a class="account-login" href="/login" id="login-link">Войти</a>
</div>
</div>
</header>
<main class="workspace">
<div class="content" id="view"></div>
<div class="circuit" aria-hidden="true">
<div class="chip"><span></span></div>
<div class="scanline"></div>
</div>
</main>
</div>
<script src="/src/app/main.js" type="module"></script>
</body>
</html>
+151
View File
@@ -0,0 +1,151 @@
import { api } from '../shared/api/client.js';
import { state, setSession } from '../shared/session.js';
import { renderLogin } from '../features/auth/login.js';
import { renderIssue } from '../features/implants/create.js';
import { renderList } from '../features/implants/list.js';
import { renderCard } from '../features/implants/details.js';
import { renderHolder } from '../features/implants/holder.js';
import { renderReissue } from '../features/implants/reissue.js';
import { renderRegistry } from '../features/implants/registry.js';
const nav = document.querySelector('#nav');
const username = document.querySelector('#username');
const layout = document.querySelector('#layout');
const logout = document.querySelector('#logout');
const loginLink = document.querySelector('#login-link');
const pageTitles = {
'/login': 'Вход',
'/home': 'Главная',
'/home/register_implant': 'Новый имплант',
'/home/check_certificate': 'Проверка',
'/home/reissue': 'Перевыпуск',
'/home/implants': 'Импланты',
'/home/registry': 'Реестр сертификатов',
};
function go(path, { replace = false } = {}) {
if (replace) history.replaceState(null, '', path);
else history.pushState(null, '', path);
render();
}
function syncChrome() {
const signedIn = Boolean(state.user);
layout.classList.toggle('signed-out', !signedIn);
username.textContent = state.user ? state.user.username : '';
logout.hidden = !signedIn;
loginLink.hidden = signedIn;
for (const link of nav.querySelectorAll('[data-auth]')) {
link.hidden = !signedIn;
}
for (const link of nav.querySelectorAll('a')) {
const href = link.getAttribute('href');
const active = href === location.pathname
|| (href === '/home/implants' && location.pathname.startsWith('/home/implants/'))
|| (href === '/home/check_certificate' && location.pathname.startsWith('/home/check_certificate/'));
link.classList.toggle('active', active);
if (active) link.setAttribute('aria-current', 'page');
else link.removeAttribute('aria-current');
}
const routeTitle = location.pathname.startsWith('/home/implants/')
? 'Карточка импланта'
: location.pathname.startsWith('/home/check_certificate/') ? 'Проверка' : pageTitles[location.pathname];
document.title = routeTitle ? `${routeTitle} · Chrome Ledger` : 'Chrome Ledger';
}
function render() {
const path = location.pathname;
const publicPage = path === '/login';
if (path === '/') return go(state.user ? '/home' : '/login', { replace: true });
if (!state.user && !publicPage) return go('/login', { replace: true });
if (state.user && path === '/login') return go('/home', { replace: true });
syncChrome();
if (path === '/login') return renderLogin(go);
if (path === '/home') {
document.querySelector('#view').innerHTML = '<section class="page"><div class="panel welcome"><h1>Добро пожаловать в Chrome Ledger!</h1></div></section>';
return;
}
if (path === '/home/register_implant') return renderIssue();
if (path === '/home/check_certificate') return renderHolder();
if (path === '/home/reissue') {
const params = new URLSearchParams(location.search);
return renderReissue(params.get('id') || '', params.get('serial') || '');
}
const check = path.match(/^\/home\/check_certificate\/([^/]+)\/check$/);
if (check) return renderHolder(decodeURIComponent(check[1]));
if (path === '/home/implants') return renderList();
if (path === '/home/registry') return renderRegistry();
const card = path.match(/^\/home\/implants\/([^/]+)$/);
if (card) return renderCard(decodeURIComponent(card[1]));
go('/home', { replace: true });
}
window.addEventListener('ledger:session-expired', () => go('/login', { replace: true }));
logout.addEventListener('click', async (event) => {
const button = event.currentTarget;
button.disabled = true;
try {
await api('/logout', { method: 'DELETE' });
setSession(null);
go('/login', { replace: true });
} catch (error) {
window.alert(error.message);
} finally {
button.disabled = false;
}
});
document.addEventListener('input', ({ target }) => {
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
target.setCustomValidity(/[^\x00-\x7F]/.test(target.value)
? 'Допустимы только английские буквы, цифры и символы ASCII' : '');
}
});
document.addEventListener('click', (event) => {
if (
event.defaultPrevented
|| event.button !== 0
|| event.metaKey
|| event.ctrlKey
|| event.shiftKey
|| event.altKey
) {
return;
}
const link = event.target.closest('a');
if (!link) {
return;
}
if (link.target && link.target !== '_self') {
return;
}
if (link.hasAttribute('download')) {
return;
}
const url = new URL(link.href, location.origin);
if (url.origin !== location.origin) {
return;
}
event.preventDefault();
go(url.pathname + url.search);
});
window.addEventListener('popstate', render);
async function start() {
if (state.token) {
const token = state.token;
try {
const user = await api('/me');
if (state.token === token) state.user = user;
} catch (error) {
if (state.token === token) window.alert(error.message);
}
}
render();
}
start();
+71
View File
@@ -0,0 +1,71 @@
import { api } from '../../shared/api/client.js';
import { setSession } from '../../shared/session.js';
import { setError } from '../../shared/ui/dom.js';
const view = document.querySelector('#view');
export function renderLogin(go) {
let registering = false;
view.innerHTML = `
<section class="page login">
<header class="page-header">
<h1 id="login-title">Войти в <span>личный кабинет</span></h1>
</header>
<form class="panel fields" id="login-form">
<h2 id="login-form-title">Учетные данные</h2>
<label>
Имя пользователя
<input id="login-username" required autocomplete="username" minlength="3" maxlength="32" pattern="[A-Za-z0-9_\\-]{3,32}">
</label>
<label>
Пароль
<input id="login-password" type="password" required minlength="8" maxlength="128" autocomplete="current-password">
</label>
<p class="error" id="login-error" role="alert" hidden></p>
<div class="actions">
<button type="submit" id="login-submit">Войти</button>
<button class="secondary" type="button" id="login-toggle">Создать аккаунт</button>
</div>
</form>
</section>`;
const form = document.querySelector('#login-form');
const title = document.querySelector('#login-title');
const userInput = document.querySelector('#login-username');
const password = document.querySelector('#login-password');
const problem = document.querySelector('#login-error');
const submit = document.querySelector('#login-submit');
const toggle = document.querySelector('#login-toggle');
const setMode = (next) => {
registering = next;
title.innerHTML = next ? 'Создать <span>аккаунт</span>' : 'Войти в <span>личный кабинет</span>';
submit.textContent = next ? 'Создать аккаунт' : 'Войти';
toggle.textContent = next ? 'У меня есть аккаунт' : 'Создать аккаунт';
password.autocomplete = next ? 'new-password' : 'current-password';
password.value = '';
setError(problem, '');
};
toggle.addEventListener('click', () => setMode(!registering));
form.addEventListener('submit', async (event) => {
event.preventDefault();
setError(problem, '');
submit.disabled = true;
toggle.disabled = true;
try {
setSession(await api(registering ? '/register' : '/login', {
method: 'POST',
body: { username: userInput.value, password: password.value },
}));
go('/home', { replace: true });
} catch (error) {
setError(problem, error.message);
} finally {
submit.disabled = false;
toggle.disabled = false;
}
});
}
@@ -0,0 +1,3 @@
export const certificateStatus = {
active: 'Действует', revoked: 'Отозван', expired: 'Срок истёк', invalid: 'Недействителен',
};
+96
View File
@@ -0,0 +1,96 @@
import { api } from '../../shared/api/client.js';
import { escapeHtml, setError, showResultDialog } from '../../shared/ui/dom.js';
const view = document.querySelector('#view');
export function renderIssue() {
view.innerHTML = `
<section class="page">
<header class="page-header">
<p class="eyebrow"><a href="/home/implants">Импланты</a> / Новый имплант</p>
<h1>Новый <span>имплант</span></h1>
<p class="intro">Зарегистрируйте устройство и выпустите сертификат</p>
</header>
<form class="panel fields" id="issue-form">
<h2>Сведения об импланте</h2>
<div class="field-grid">
<label>Название
<input id="issue-name" required minlength="1" maxlength="80" autocomplete="off">
</label>
<label>Модель
<input id="issue-model" required minlength="1" maxlength="80" autocomplete="off">
</label>
</div>
<div class="field-grid">
<label>Код проекта
<input id="issue-project" required minlength="1" maxlength="80" autocomplete="off">
</label>
<label>Код организации
<input id="issue-organization" required minlength="1" maxlength="80" autocomplete="off">
</label>
</div>
<p class="notice">Код проекта и код организации — приватные данные, необходимые для учёта происхождения импланта. Не раскрывайте их значения третьим лицам</p>
<label>
Открытый ключ
<textarea id="issue-key" class="mono" rows="7" spellcheck="false" required placeholder="-----BEGIN PUBLIC KEY-----&#10;...&#10;-----END PUBLIC KEY-----"></textarea>
<small>Полный открытый ключ в формате PEM: ECDSA P-256 или RSA от 2048 бит</small>
</label>
<p class="notice">После выпуска сохраните сертификат</p>
<p class="error" id="issue-error" role="alert" hidden></p>
<div class="actions">
<button type="submit" id="issue-submit">Выпустить сертификат</button>
</div>
</form>
<div id="issue-result"></div>
</section>`;
const form = document.querySelector('#issue-form');
const key = document.querySelector('#issue-key');
const problem = document.querySelector('#issue-error');
const submit = document.querySelector('#issue-submit');
const result = document.querySelector('#issue-result');
form.addEventListener('submit', async (event) => {
event.preventDefault();
setError(problem, '');
result.innerHTML = '';
const body = {
public_key_pem: key.value,
display_name: document.querySelector('#issue-name').value,
model: document.querySelector('#issue-model').value,
project_codename: document.querySelector('#issue-project').value,
installed_by: document.querySelector('#issue-organization').value,
};
submit.disabled = true;
submit.textContent = 'Оформляем сертификат…';
try {
const data = await api('/register_implant', { method: 'POST', body });
form.reset();
result.innerHTML = `
<dialog class="issue-dialog" aria-labelledby="issue-result-title">
<section class="panel fields" aria-live="polite">
<h2 id="issue-result-title">Сертификат выпущен</h2>
<p class="success-message">Имплант зарегистрирован. Сохраните сертификат перед продолжением работы</p>
<dl class="details">
<dt>ID импланта</dt>
<dd class="mono">${escapeHtml(data.id)}</dd>
</dl>
<label>Сертификат (PEM)
<textarea class="mono" readonly rows="5">${escapeHtml(data.cert_pem)}</textarea>
</label>
<div class="actions">
<button class="secondary" type="button" data-close-dialog>Закрыть</button>
</div>
</section>
</dialog>`;
showResultDialog(result);
} catch (error) {
setError(problem, error.message);
} finally {
submit.disabled = false;
submit.textContent = 'Выпустить сертификат';
}
});
}
+55
View File
@@ -0,0 +1,55 @@
import { api } from '../../shared/api/client.js';
import { state } from '../../shared/session.js';
import { certificateStatus } from './certificate.js';
import { dateTime, escapeHtml, readOnlyField } from '../../shared/ui/dom.js';
const view = document.querySelector('#view');
export async function renderCard(id) {
const route = location.pathname;
view.innerHTML = '<section class="page"><div class="panel loading" aria-live="polite">Загружаем карточку…</div></section>';
try {
const base = '/implants/' + encodeURIComponent(id);
const implant = await api(base);
if (location.pathname !== route || !state.user) return;
const certificate = implant.certificate;
view.innerHTML = `<section class="page">
<header class="page-header">
<p class="eyebrow"><a href="/home/implants">Импланты</a> / Карточка</p>
<h1>${escapeHtml(implant.display_name)}</h1>
<p class="intro">Сведения об устройстве и сертификаты</p>
</header>
<section class="panel fields summary-panel">
<div class="result-heading">
<h2>Сведения об импланте</h2>
<span class="status ${certificate.valid ? 'status-valid' : 'status-invalid'}">
${escapeHtml(certificateStatus[certificate.status] || certificate.status)}
</span>
</div>
<dl class="details">
<dt>ID</dt><dd class="mono">${escapeHtml(id)}</dd>
<dt>Модель</dt><dd>${escapeHtml(implant.model || 'Не указана')}</dd>
<dt>Создан</dt><dd>${escapeHtml(dateTime(implant.created_at))}</dd>
<dt>Сертификат</dt><dd>${escapeHtml(certificateStatus[certificate.status] || certificate.status)}</dd>
</dl>
</section>
<section class="panel fields">
<h2>Публичный сертификат</h2>
<dl class="details">
<dt>Серийный номер</dt><dd class="mono">${escapeHtml(certificate.serial)}</dd>
<dt>Действует до</dt><dd>${escapeHtml(dateTime(certificate.not_after))}</dd>
<dt>SHA-256</dt><dd class="mono">${escapeHtml(certificate.fingerprint)}</dd>
${certificate.revoked_at ? `<dt>Отозван</dt><dd>${escapeHtml(dateTime(certificate.revoked_at))}</dd>` : ''}
</dl>
${readOnlyField('Сертификат (PEM)', certificate.cert_pem, 4)}
</section>
</section>`;
} catch (error) {
if (location.pathname !== route) return;
view.innerHTML = `<section class="page"><div class="panel fields">
<p class="error" role="alert">${escapeHtml(error.message)}</p>
<div><a class="text-link" href="/home/implants">Вернуться к имплантам</a></div>
</div></section>`;
}
}
+101
View File
@@ -0,0 +1,101 @@
import { api } from '../../shared/api/client.js';
import { escapeHtml, setError, readOnlyField, showResultDialog } from '../../shared/ui/dom.js';
const view = document.querySelector('#view');
export function renderHolder(wanted = '') {
view.innerHTML = `<section class="page">
<header class="page-header">
<p class="eyebrow">/Проверка</p>
<h1>Проверка</h1>
<p class="intro">Проверьте данные своего сертификата</p>
</header>
<ol class="steps" aria-label="Порядок доступа">
<li>Получите верификатор</li>
<li>Подпишите строку закрытым ключом</li>
<li>Отправьте подпись в base64</li>
</ol>
<form class="panel fields" id="challenge-form">
<h2>Получить верификатор</h2>
<label>ID импланта
<input class="mono" id="holder-id" required spellcheck="false" autocomplete="off"
value="${escapeHtml(wanted)}">
</label>
<button type="submit">Получить верификатор</button>
</form>
<form class="panel fields" id="holder-form" hidden>
<h2>Подписать верификатор</h2>
<div id="holder-challenge"></div>
<label>Подпись в base64
<textarea class="mono" id="holder-signature" required rows="4" spellcheck="false"></textarea>
<small>Подпишите точную ASCII-строку выше закрытым ключом импланта</small>
</label>
<button type="submit">Посмотреть данные</button>
</form>
<p class="error" id="holder-error" role="alert" hidden></p>
<div id="holder-result" aria-live="polite"></div>
</section>`;
const challengeForm = document.querySelector('#challenge-form');
const holderForm = document.querySelector('#holder-form');
const challengeField = document.querySelector('#holder-challenge');
const result = document.querySelector('#holder-result');
const problem = document.querySelector('#holder-error');
let pending = null;
challengeForm.addEventListener('submit', async (event) => {
event.preventDefault();
const button = challengeForm.querySelector('button');
button.disabled = true;
pending = null;
holderForm.hidden = true;
result.innerHTML = '';
setError(problem, '');
try {
const id = document.querySelector('#holder-id').value.trim();
const base = '/check_certificate/' + encodeURIComponent(id);
const challenge = await api(base + '/check');
pending = { id, nonce: challenge.challenge, certificate: challenge.certificate.cert_pem };
history.replaceState(null, '', '/home/check_certificate/' + encodeURIComponent(id) + '/check');
challengeField.innerHTML = readOnlyField('Сертификат (PEM)', pending.certificate, 4)
+ readOnlyField('Верификатор: подпишите эту ASCII-строку', pending.nonce, 2);
document.querySelector('#holder-signature').value = '';
holderForm.hidden = false;
} catch (error) {
setError(problem, error.message);
} finally {
button.disabled = false;
}
});
holderForm.addEventListener('submit', async (event) => {
event.preventDefault();
if (!pending) return;
const button = holderForm.querySelector('button');
button.disabled = true;
setError(problem, '');
try {
const data = await api('/check_certificate/' + encodeURIComponent(pending.id) + '/check', {
method: 'POST', body: { certificate: pending.certificate, nonce: pending.nonce,
signature: document.querySelector('#holder-signature').value.trim() },
});
result.innerHTML = `
<dialog class="issue-dialog" aria-labelledby="holder-result-title">
<section class="panel fields" aria-live="polite">
<h2 id="holder-result-title">Данные импланта</h2>
${readOnlyField('Код проекта', data.project_codename, 1)}
${readOnlyField('Код организации', data.installed_by, 1)}
<div class="actions">
<button class="secondary" type="button" data-close-dialog>Закрыть</button>
</div>
</section>
</dialog>`;
showResultDialog(result);
pending = null;
holderForm.hidden = true;
} catch (error) {
setError(problem, error.message);
} finally {
button.disabled = false;
}
});
if (wanted) challengeForm.requestSubmit();
}
+48
View File
@@ -0,0 +1,48 @@
import { api } from '../../shared/api/client.js';
import { state } from '../../shared/session.js';
import { dateTime, escapeHtml } from '../../shared/ui/dom.js';
const view = document.querySelector('#view');
export async function renderList() {
view.innerHTML = `<section class="page">
<header class="page-header page-header-row">
<div>
<h1>Мои <span>импланты</span></h1>
<p class="intro">Управляйте сертификатами зарегистрированных устройств</p>
</div>
<a class="button-link" id="implant-add" href="/home/register_implant" hidden>Добавить имплант</a>
</header>
<div class="record-list" id="implant-list" aria-live="polite">
<p class="panel loading">Загружаем импланты…</p>
</div>
</section>`;
const list = document.querySelector('#implant-list');
const add = document.querySelector('#implant-add');
try {
const { implants } = await api('/implants');
if (!list.isConnected || !state.user) return;
add.hidden = !implants.length;
list.innerHTML = implants.map((implant) => `
<article class="panel fields">
<div class="record-heading">
<div>
<h2>${escapeHtml(implant.display_name)}</h2>
<p>${escapeHtml(implant.model || 'Модель не указана')}</p>
</div>
<a class="text-link" href="/home/implants/${encodeURIComponent(implant.id)}">Открыть карточку</a>
</div>
<dl class="details compact-details">
<dt>ID</dt><dd class="mono">${escapeHtml(implant.id)}</dd>
<dt>Создан</dt><dd>${escapeHtml(dateTime(implant.created_at))}</dd>
</dl>
</article>`).join('') || `
<div class="panel empty-state fields">
<h2>Имплантов пока нет</h2>
<p>Добавьте первый имплант, чтобы выпустить сертификат</p>
<div><a class="button-link" href="/home/register_implant">Добавить имплант</a></div>
</div>`;
} catch (error) {
if (list.isConnected) list.innerHTML = `<p class="panel error" role="alert">${escapeHtml(error.message)}</p>`;
}
}
+74
View File
@@ -0,0 +1,74 @@
import { api } from '../../shared/api/client.js';
import { state } from '../../shared/session.js';
import { certificateStatus } from './certificate.js';
import { dateTime, escapeHtml, readOnlyField } from '../../shared/ui/dom.js';
const view = document.querySelector('#view');
export async function renderRegistry() {
view.innerHTML = `<section class="page">
<header class="page-header">
<p class="eyebrow">/Реестр</p>
<h1>Публичные <span>сертификаты</span></h1>
<p class="intro">Импланты всех пользователей и история выпущенных сертификатов</p>
</header>
<div class="record-list" id="registry-list" aria-live="polite">
<p class="panel loading">Загружаем реестр…</p>
</div>
<div class="actions">
<button class="secondary" id="registry-prev" type="button" disabled>Назад</button>
<span id="registry-page" aria-live="polite"></span>
<button class="secondary" id="registry-next" type="button" disabled>Далее</button>
</div>
</section>`;
const list = document.querySelector('#registry-list');
const previous = document.querySelector('#registry-prev');
const next = document.querySelector('#registry-next');
const counter = document.querySelector('#registry-page');
try {
const { results } = await api('/registry');
if (!list.isConnected || !state.user) return;
let page = 0;
const renderPage = () => {
list.innerHTML = results.slice(page * 20, (page + 1) * 20).map((implant) => `
<article class="panel fields">
<div class="record-heading">
<h2>${escapeHtml(implant.display_name)}</h2>
<span class="counter">${implant.certificates.length}</span>
</div>
<dl class="details">
<dt>ID импланта</dt><dd class="mono">${escapeHtml(implant.id)}</dd>
<dt>Модель</dt><dd>${escapeHtml(implant.model || 'Не указана')}</dd>
<dt>Владелец</dt><dd>${escapeHtml(implant.owner)}</dd>
<dt>Создан</dt><dd>${escapeHtml(dateTime(implant.created_at))}</dd>
</dl>
${implant.certificates.map((certificate) => `
<details class="certificate-record">
<summary>
<span class="mono">${escapeHtml(certificate.serial)}</span>
<span class="status ${certificate.valid ? 'status-valid' : 'status-invalid'}">${escapeHtml(certificateStatus[certificate.status] || certificate.status)}</span>
</summary>
<div class="fields">
<dl class="details">
<dt>SHA-256</dt><dd class="mono">${escapeHtml(certificate.fingerprint)}</dd>
<dt>Субъект</dt><dd>${escapeHtml(certificate.subject)}</dd>
<dt>Удостоверяющий центр</dt><dd>${escapeHtml(certificate.issuer)}</dd>
<dt>Действует с</dt><dd>${escapeHtml(dateTime(certificate.not_before))}</dd>
<dt>Действует до</dt><dd>${escapeHtml(dateTime(certificate.not_after))}</dd>
${certificate.revoked_at ? `<dt>Отозван</dt><dd>${escapeHtml(dateTime(certificate.revoked_at))}</dd>` : ''}
</dl>
${readOnlyField('Сертификат (PEM)', certificate.cert_pem, 4)}
</div>
</details>`).join('')}
</article>`).join('') || '<div class="panel empty-state">В реестре пока нет имплантов</div>';
previous.disabled = page === 0;
next.disabled = (page + 1) * 20 >= results.length;
counter.textContent = `Страница ${page + 1} из ${Math.max(1, Math.ceil(results.length / 20))} · Имплантов: ${results.length}`;
};
previous.addEventListener('click', () => { if (page > 0) { page -= 1; renderPage(); } });
next.addEventListener('click', () => { if ((page + 1) * 20 < results.length) { page += 1; renderPage(); } });
renderPage();
} catch (error) {
if (list.isConnected) list.innerHTML = `<p class="panel error" role="alert">${escapeHtml(error.message)}</p>`;
}
}
+96
View File
@@ -0,0 +1,96 @@
import { api } from '../../shared/api/client.js';
import { escapeHtml, setError, readOnlyField, showResultDialog } from '../../shared/ui/dom.js';
const view = document.querySelector('#view');
export function renderReissue(wanted = '', serial = '') {
view.innerHTML = `<section class="page">
<header class="page-header">
<p class="eyebrow">/Перевыпуск</p>
<h1>Перевыпуск</h1>
</header>
<form class="panel fields" id="reissue-form">
<label>ID импланта
<input class="mono" id="reissue-id" required spellcheck="false" autocomplete="off" value="${escapeHtml(wanted)}">
</label>
<label>Серийный номер текущего сертификата
<input class="mono" id="reissue-serial" required maxlength="40" pattern="[0-9a-f]+"
spellcheck="false" autocomplete="off" value="${escapeHtml(serial)}">
</label>
<label>Подписанный CSR (PEM)
<textarea class="mono" id="reissue-csr" required rows="6" maxlength="60000" spellcheck="false"
placeholder="-----BEGIN CERTIFICATE REQUEST-----"></textarea>
</label>
<label>Подпись текущим ключом в base64
<textarea class="mono" id="reissue-signature" required rows="4" spellcheck="false"></textarea>
<small><a class="text-link" id="signature-rules-link" href="#signature-rules">Правила подписи</a></small>
</label>
<button type="submit">Перевыпустить сертификат</button>
</form>
<dialog class="issue-dialog" id="signature-rules" aria-labelledby="signature-rules-title">
<section class="panel fields">
<h2 id="signature-rules-title">Правила подписи</h2>
<p>Вычислите SHA-256 от DER-представления подписанного CSR. Запишите хеш строчными шестнадцатеричными символами.</p>
<p>Подставьте ID импланта, серийный номер текущего сертификата и хеш в ASCII-строку без перевода строки в конце:</p>
<code>reissue:&lt;ID импланта&gt;:&lt;серийный номер&gt;:&lt;SHA256(CSR_DER)&gt;</code>
<p>Подпишите строку текущим закрытым ключом импланта: ECDSA с SHA-256 или RSA PKCS#1 v1.5 с SHA-256</p>
<p>Преобразуйте полученную подпись в Base64 и вставьте её в поле «Подпись текущим ключом в base64»</p>
<div class="actions">
<button class="secondary" type="button" data-close-dialog>Закрыть</button>
</div>
</section>
</dialog>
<p class="error" id="reissue-error" role="alert" hidden></p>
<div id="reissue-result" aria-live="polite"></div>
</section>`;
const form = document.querySelector('#reissue-form');
const result = document.querySelector('#reissue-result');
const problem = document.querySelector('#reissue-error');
const rules = document.querySelector('#signature-rules');
document.querySelector('#signature-rules-link').addEventListener('click', (event) => {
event.preventDefault();
rules.showModal();
});
rules.querySelector('[data-close-dialog]').addEventListener('click', () => rules.close());
form.addEventListener('submit', async (event) => {
event.preventDefault();
const button = form.querySelector('button');
button.disabled = true;
result.innerHTML = '';
setError(problem, '');
try {
const id = document.querySelector('#reissue-id').value.trim();
const data = await api('/reissue/' + encodeURIComponent(id), {
method: 'POST', body: { csr_pem: document.querySelector('#reissue-csr').value.trim(),
certificate_serial: document.querySelector('#reissue-serial').value.trim(),
signature: document.querySelector('#reissue-signature').value.trim() },
});
const certificate = data.certificate;
result.innerHTML = `<dialog class="issue-dialog" aria-labelledby="reissue-result-title">
<section class="panel fields">
<h2 id="reissue-result-title">Сертификат перевыпущен</h2>
${[
['ID импланта', data.id], ['Название', data.display_name], ['Модель', data.model],
['Владелец', data.owner], ['ID владельца', data.user_id], ['Создан', data.created_at],
['Код проекта', data.project_codename], ['Код организации', data.installed_by],
['Владелец сертификата', certificate.subject], ['Издатель', certificate.issuer],
['Серийный номер', certificate.serial], ['Действует с', certificate.not_before],
['Действует до', certificate.not_after], ['Статус', certificate.valid ? 'Действует' : 'Недействителен'],
['SHA-256', certificate.fingerprint],
].map(([label, value]) => readOnlyField(label, value, 1)).join('')}
${readOnlyField('Сертификат (PEM)', data.cert_pem, 4)}
<div class="actions">
<button class="secondary" type="button" data-close-dialog>Закрыть</button>
</div>
</section>
</dialog>`;
showResultDialog(result);
document.querySelector('#reissue-serial').value = certificate.serial;
document.querySelector('#reissue-signature').value = '';
} catch (error) {
setError(problem, error.message);
} finally {
button.disabled = false;
}
});
}
+34
View File
@@ -0,0 +1,34 @@
import { state, setSession } from '../session.js';
export async function api(path, { method = 'GET', body } = {}) {
if (path !== '/login' && path !== '/register') path = '/home/api' + path;
const token = state.token;
let response;
try {
response = await fetch(path, {
method,
credentials: 'omit',
headers: {
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
...(token ? { Authorization: 'Bearer ' + token } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch {
throw new Error('Нет связи с Chrome Ledger');
}
if (response.status === 204) return null;
const data = await response.json().catch(() => null);
if (!response.ok || data === null) {
if (response.status === 401 && token && state.token === token && data && data.error === 'Authentication required') {
setSession(null);
window.dispatchEvent(new Event('ledger:session-expired'));
}
if (data && data.error) {
throw new Error(data.error);
}
throw new Error('Сервис вернул неожиданный ответ');
}
return data;
}
+8
View File
@@ -0,0 +1,8 @@
export const state = { user: null, token: sessionStorage.getItem('ledger-token') };
export function setSession(data) {
state.user = data ? { id: data.id, username: data.username } : null;
state.token = data ? data.access_token : null;
if (state.token) sessionStorage.setItem('ledger-token', state.token);
else sessionStorage.removeItem('ledger-token');
}
+476
View File
@@ -0,0 +1,476 @@
:root {
color-scheme: dark;
font-family: var(--sans);
--sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
--text: #e8eef6;
--ink: #080b11;
--panel: #10151e;
--line: #303b4b;
--muted: #aeb9c8;
--accent: #9db2c9;
--accent-edge: #5b7794;
--signal: #89b1ad;
--danger: #d99cac;
color: var(--text);
background: var(--ink);
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace;
--gutter: clamp(16px, 4vw, 56px);
}
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; min-width: 280px; }
button, input, textarea, select { font: inherit; }
a { color: inherit; }
[hidden] { display: none !important; }
.layout {
min-height: 100vh;
background:
radial-gradient(ellipse at 97% 53%, #32293d49, transparent 42%),
radial-gradient(ellipse at 70% 12%, #1b313e65, transparent 45%),
linear-gradient(#9db2c909 1px, transparent 1px),
linear-gradient(90deg, #9db2c909 1px, transparent 1px),
var(--ink);
background-size: auto, auto, 44px 44px, 44px 44px, auto;
}
.topbar {
position: sticky;
top: 0;
z-index: 10;
border-bottom: 1px solid var(--line);
background: #0c1018f5;
backdrop-filter: blur(12px);
}
.topbar-inner {
max-width: 1440px;
min-height: 74px;
margin-inline: auto;
padding-inline: var(--gutter);
display: flex;
align-items: center;
gap: clamp(16px, 4vw, 54px);
}
.brand {
display: inline-flex;
align-items: center;
gap: 11px;
color: var(--accent);
font: 21px var(--mono);
letter-spacing: -.07em;
text-decoration: none;
white-space: nowrap;
}
.brand-mark {
display: grid;
place-items: center;
flex: 0 0 auto;
width: 25px;
height: 25px;
background: var(--accent);
clip-path: polygon(23% 0, 100% 0, 100% 77%, 77% 100%, 0 100%, 0 23%);
}
.brand-mark::after {
content: '';
width: 15px;
height: 15px;
background: var(--ink);
clip-path: polygon(30% 0, 100% 0, 100% 29%, 44% 29%, 29% 44%, 29% 71%, 100% 71%, 100% 100%, 0 100%, 0 30%);
}
#nav { display: flex; align-self: stretch; gap: 4px; align-items: stretch; }
#nav a {
display: grid;
align-content: center;
padding: 10px 12px;
border-block: 2px solid transparent;
color: var(--muted);
font: 14px var(--mono);
text-decoration: none;
}
#nav a:hover { color: var(--signal); }
#nav a.active {
color: var(--signal);
border-bottom-color: var(--signal);
background: #89b1ad12;
}
.account {
margin-left: auto;
display: flex;
align-items: center;
gap: 13px;
color: var(--muted);
font: 13px var(--mono);
}
.account span { overflow-wrap: anywhere; min-width: 0; }
.account-login { color: var(--signal); font: 14px var(--mono); text-underline-offset: 4px; }
.workspace {
width: min(100%, 1380px);
margin: 0 auto;
padding: clamp(32px, 5vw, 70px) var(--gutter) 64px;
display: grid;
grid-template-columns: minmax(0, 860px) minmax(260px, 360px);
gap: clamp(20px, 4vw, 58px);
align-items: start;
}
.content { min-width: 0; }
.content > .error { margin-bottom: 15px; }
.signed-out .workspace {
grid-template-columns: minmax(0, 510px) minmax(0, 440px);
justify-content: center;
align-items: center;
min-height: calc(100vh - 75px);
}
.circuit {
--trace: #89b1ad19;
position: sticky;
top: 24px;
display: grid;
place-items: center;
aspect-ratio: 4 / 5;
overflow: hidden;
border: 1px solid #3a555e;
background:
linear-gradient(135deg, #9db2c90a 0 39%, transparent 39% 75%, #77628418 75%),
repeating-linear-gradient(0deg, transparent 0 27px, var(--trace) 28px, transparent 29px),
repeating-linear-gradient(90deg, transparent 0 27px, var(--trace) 28px, transparent 29px),
radial-gradient(ellipse at 52% 46%, #20343e, #0b111b 68%);
clip-path: polygon(0 0, calc(100% - 30px) 0, 100% 30px, 100% 100%, 30px 100%, 0 calc(100% - 30px));
isolation: isolate;
}
.circuit::before, .circuit::after {
content: '';
position: absolute;
inset: 14px;
pointer-events: none;
}
.circuit::before {
border: 1px solid #89b1ad36;
background:
linear-gradient(90deg, var(--signal) 0 27px, transparent 27px) top left,
linear-gradient(270deg, var(--accent-edge) 0 32px, transparent 32px) bottom right;
background-size: 100% 2px;
background-repeat: no-repeat;
}
.circuit::after {
inset: 25px;
border: 1px dashed #89b1ad2e;
}
.chip {
z-index: 1;
display: grid;
place-items: center;
width: 48%;
aspect-ratio: 1;
transform: rotate(-24deg);
border: 1px solid #5d7f86;
background: #111923;
box-shadow: inset 0 0 25px #89b1ad20, 0 0 45px #89b1ad22, 7px 8px 0 #77628430;
}
.chip::before, .chip::after {
content: '';
position: absolute;
width: 140%;
height: 58%;
background: repeating-linear-gradient(0deg, var(--signal) 0 1px, transparent 1px 11px);
z-index: -1;
opacity: .38;
}
.chip::after { transform: rotate(90deg); }
.chip span {
display: grid;
place-items: center;
width: 74%;
aspect-ratio: 1;
border: 1px solid #496d73;
background: #121d2a;
box-shadow: 0 0 0 4px #0a141e;
}
.chip span::after {
content: '';
width: 65%;
aspect-ratio: 1;
background: var(--accent-edge);
clip-path: polygon(27% 0, 100% 0, 100% 29%, 40% 29%, 29% 40%, 29% 71%, 100% 71%, 100% 100%, 0 100%, 0 27%);
}
.scanline {
position: absolute;
z-index: 2;
inset: 12% 14px auto;
height: 2px;
opacity: 0;
background: linear-gradient(90deg, transparent, var(--signal), transparent);
box-shadow: 0 0 18px #89b1ad47;
animation: scan 8s ease-in-out infinite;
}
@keyframes scan {
0%, 15% { top: 12%; opacity: 0; }
27% { opacity: .4; }
65% { opacity: .4; }
78%, 100% { top: 87%; opacity: 0; }
}
h1, h2, p, dl { margin: 0; }
h1 {
font-size: clamp(34px, 4vw, 56px);
font-weight: 800;
line-height: .98;
letter-spacing: -.065em;
text-transform: uppercase;
}
h1 span { display: block; color: var(--accent); }
h2 { font-size: 20px; font-weight: 800; }
.page-header { margin-bottom: 26px; }
.welcome { text-align: center; }
.page-header-row { display: flex; justify-content: space-between; align-items: end; gap: 24px; }
.page-header-row .button-link { flex: 0 0 auto; margin-bottom: 4px; }
.intro { color: var(--muted); max-width: 62ch; margin-top: 14px; line-height: 1.6; }
.eyebrow {
margin-bottom: 11px;
color: var(--signal);
font: 700 13px/1.4 var(--mono);
letter-spacing: .04em;
text-transform: uppercase;
}
.eyebrow a { text-underline-offset: 4px; }
.mono { font-family: var(--mono); }
.valid { color: var(--signal); }
.invalid, .error { color: var(--danger); }
.error { overflow-wrap: anywhere; border-left: 2px solid var(--danger); padding-left: 10px; }
.muted { color: var(--muted); }
.panel {
position: relative;
border: 1px solid var(--line);
border-top-color: #435568;
padding: clamp(16px, 2.15vw, 29px);
background: linear-gradient(135deg, #9db2c908, transparent 55%), var(--panel);
box-shadow: 5px 5px 0 #070910;
}
.panel::before {
content: '';
position: absolute;
top: -1px;
left: -1px;
width: 64px;
height: 2px;
background: var(--signal);
pointer-events: none;
}
.panel::after {
content: '';
position: absolute;
inset: auto -1px -1px auto;
width: 45px;
height: 11px;
background: repeating-linear-gradient(125deg, var(--accent-edge) 0 2px, transparent 2px 6px);
pointer-events: none;
}
.panel + .panel { margin-top: 21px; }
.record-list { margin-top: 24px; }
.record-list { display: grid; gap: 18px; }
.record-list .panel + .panel { margin-top: 0; }
.certificate-record { padding-top: 2px; }
.certificate-record + .certificate-record { padding-top: 22px; border-top: 1px solid var(--line); }
.certificate-record > summary { cursor: pointer; }
.certificate-record > summary .status { margin-left: 12px; vertical-align: middle; }
.certificate-record > .fields { margin-top: 17px; padding-left: 20px; }
#holder-error { margin-top: 16px; }
.fields { display: grid; gap: 17px; min-width: 0; }
.fields > label, .readonly-field { display: grid; gap: 8px; min-width: 0; }
.field-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 17px; }
.field-grid > label { display: grid; gap: 8px; }
label { font-size: 14px; font-weight: 600; }
small { color: var(--muted); font: 400 13px/1.45 var(--sans); }
.optional { margin-left: 6px; color: var(--muted); font-size: 12px; font-weight: 400; }
input, textarea, select {
width: 100%;
min-width: 0;
background: #0b1019;
border: 1px solid var(--line);
border-left: 2px solid #486071;
border-radius: 0;
color: var(--text);
padding: 11px 12px;
line-height: 1.5;
transition: border-color .16s, background-color .16s;
}
input::placeholder, textarea::placeholder { color: #929fb3; }
textarea { display: block; resize: vertical; overflow-wrap: anywhere; }
textarea.mono, input.mono, select.mono { font-size: 13px; }
textarea[readonly] { background: #0f1724; }
select {
appearance: none;
padding-right: 42px;
background-image:
linear-gradient(45deg, transparent 50%, var(--muted) 50%),
linear-gradient(135deg, var(--muted) 50%, transparent 50%);
background-position: calc(100% - 18px) 50%, calc(100% - 13px) 50%;
background-size: 5px 5px;
background-repeat: no-repeat;
}
input:focus, textarea:focus, select:focus { border-color: var(--signal); background: #101923; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
button, .button-link {
position: relative;
border: 1px solid var(--accent-edge);
border-radius: 0;
padding: 10px 15px;
font-weight: 800;
font-size: 13px;
background: #2b4056;
color: var(--text);
cursor: pointer;
transition: color .16s, background-color .16s, box-shadow .16s;
}
button:hover, .button-link:hover { background: #36516b; box-shadow: 3px 3px 0 #151f2b; }
button:disabled { opacity: .64; cursor: wait; }
button.secondary { background: #121a25; border-color: #486071; color: var(--accent); }
button.secondary:hover { background: #1c2a38; box-shadow: none; }
.button-link { display: inline-block; text-decoration: none; }
.text-link { color: var(--signal); font: 14px var(--mono); text-underline-offset: 4px; }
.text-link:hover { color: var(--accent); }
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; }
.public-actions { display: flex; flex-wrap: wrap; gap: 12px 20px; margin-top: 20px; }
.details { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 12px 20px; font-size: 14px; }
.details dt { color: var(--muted); }
.details dd { margin: 0; overflow-wrap: anywhere; }
.compact-details { padding-top: 15px; border-top: 1px solid var(--line); }
.record-heading, .result-heading {
display: flex;
justify-content: space-between;
align-items: start;
gap: 18px;
}
.record-heading p { margin-top: 7px; color: var(--muted); }
.status {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
min-height: 28px;
padding: 4px 9px;
border: 1px solid var(--line);
font: 700 12px var(--mono);
}
.status-valid { color: #a9d7d1; border-color: #466d6b; background: #142523; }
.status-invalid { color: #efb4c2; border-color: #754553; background: #28181e; }
.counter {
min-width: 28px;
padding: 4px 8px;
text-align: center;
border: 1px solid var(--line);
color: var(--muted);
font: 13px var(--mono);
}
.notice {
padding: 12px 14px;
border-left: 2px solid var(--accent-edge);
background: #172130;
color: #cbd6e4;
font-size: 14px;
line-height: 1.5;
}
.success-message { color: #b8d8d4; line-height: 1.5; }
.empty-state { padding-block: 34px; }
.loading { color: var(--muted); }
.steps {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1px;
margin: 0 0 21px;
padding: 1px;
list-style-position: inside;
background: var(--line);
}
.steps li { padding: 13px 14px; background: #0d131c; color: var(--muted); font-size: 13px; line-height: 1.45; }
.issue-dialog {
width: min(760px, calc(100vw - 32px));
max-width: none;
max-height: calc(100vh - 32px);
padding: 0;
border: 0;
color: var(--text);
background: transparent;
}
.issue-dialog::backdrop {
background: #02050bcc;
backdrop-filter: blur(4px);
}
.issue-dialog > .panel {
max-height: calc(100vh - 32px);
overflow: auto;
}
@media (max-width: 900px) {
.topbar-inner { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0 12px; min-height: 64px; }
#nav { grid-row: 2; grid-column: 1 / -1; flex-wrap: wrap; }
#nav a { padding-inline: 8px; }
.brand, .account { margin-block: 12px; }
.workspace, .signed-out .workspace { grid-template-columns: minmax(0, 1fr) minmax(0, .55fr); }
.signed-out .workspace { min-height: auto; }
.circuit { top: 16px; }
}
@media (max-width: 650px) {
.workspace, .signed-out .workspace { position: relative; display: block; isolation: isolate; }
.content { position: relative; z-index: 1; }
.circuit {
width: 125px;
position: absolute;
top: 14px;
right: var(--gutter);
opacity: .29;
pointer-events: none;
mask-image: linear-gradient(225deg, #000, transparent 86%);
}
.circuit::before, .circuit::after { inset: 7px; }
.scanline { display: none; }
}
@media (max-width: 415px) {
.brand { min-width: 0; font-size: 17px; gap: 6px; line-height: 1.05; white-space: normal; }
.brand-mark { width: 20px; height: 20px; }
.brand-mark::after { width: 12px; height: 12px; }
.account { max-width: 46vw; gap: 7px; font-size: 12px; }
.account button { padding-inline: 9px; }
#nav a { font-size: 11px; padding-inline: 6px; }
h1 { font-size: clamp(27px, 9vw, 32px); }
.details { grid-template-columns: minmax(0, 1fr); gap: 3px; }
.details dd + dt { margin-top: 9px; }
}
@media (prefers-reduced-motion: reduce) {
.scanline { animation: none; }
input, textarea, select, button { transition: none; }
}
+40
View File
@@ -0,0 +1,40 @@
const dateFormat = new Intl.DateTimeFormat('ru-RU', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'UTC',
});
export function dateTime(value) {
return dateFormat.format(new Date(value)) + ' UTC';
}
export function escapeHtml(value) {
if (value === null || value === undefined) {
return '';
}
return String(value).replace(/[&<>"']/g, (character) => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
})[character]);
}
export function setError(element, message) {
element.textContent = message;
element.hidden = !message;
}
export function readOnlyField(label, value, rows = 3) {
return `<label class="readonly-field">${escapeHtml(label)}
<textarea class="mono" readonly rows="${rows}">${escapeHtml(value)}</textarea>
</label>`;
}
export function showResultDialog(container) {
const dialog = container.querySelector('dialog');
dialog.querySelector('[data-close-dialog]').addEventListener('click', () => dialog.close());
dialog.addEventListener('close', () => dialog.remove(), { once: true });
dialog.showModal();
}
+31
View File
@@ -0,0 +1,31 @@
from gunicorn.app.base import BaseApplication
from backend.app.bootstrap.factory import create_app
class LedgerApplication(BaseApplication):
def load_config(self):
settings = {
"bind": "0.0.0.0:8080",
"control_socket_disable": True,
"workers": 4,
"threads": 8,
"worker_class": "gthread",
"preload_app": True,
"timeout": 20,
"graceful_timeout": 10,
"keepalive": 5,
"backlog": 128,
"max_requests": 1000,
"max_requests_jitter": 100,
"accesslog": "-",
"errorlog": "-",
}
for key, value in settings.items():
self.cfg.set(key, value)
def load(self):
return create_app()
if __name__ == "__main__":
LedgerApplication().run()
+15
View File
@@ -0,0 +1,15 @@
FROM python:3.12.16-slim-bookworm
WORKDIR /app
COPY backend/requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY backend ./backend/
COPY frontend ./frontend/
RUN useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin darktariff
USER darktariff
CMD ["sh", "-c", "python -m backend.app.db.initialize && exec uvicorn backend.app.main:create_app --factory --host 0.0.0.0 --port 8080 --workers 4 --limit-concurrency 32"]
+24
View File
@@ -0,0 +1,24 @@
from uuid import UUID
from fastapi import APIRouter
from backend.app.db import operations
from backend.app.api.schemas import CheckStart, CheckCommit, CheckAnswer
router = APIRouter(prefix="/api/chat", tags=["chat"])
@router.get("/greeting")
async def greeting():
return await operations.chat_greeting()
@router.post("/checks", status_code=201)
async def check_start(body: CheckStart):
return await operations.check_start(body.reading_id)
@router.post("/checks/{check_id}/commit")
async def check_commit(check_id: UUID, body: CheckCommit):
return await operations.check_commit(check_id, body.round, body.values)
@router.post("/checks/{check_id}/answer")
async def check_answer(check_id: UUID, body: CheckAnswer):
return await operations.check_answer(check_id, body.round, body.data)
+9
View File
@@ -0,0 +1,9 @@
from fastapi import APIRouter
from backend.app.db import operations
router = APIRouter(prefix="/api", tags=["system"])
@router.get("/health")
async def health():
return {"ok": await operations.ping() == 1}
+22
View File
@@ -0,0 +1,22 @@
from fastapi import APIRouter
from backend.app.db import operations
from backend.app.api.schemas import ReadingIn
router = APIRouter(prefix="/api", tags=["readings"])
@router.get("/resources")
async def resources():
return await operations.resources()
@router.get("/readings")
async def readings():
return await operations.readings()
@router.get("/readings/{reading_id}")
async def reading_public(reading_id: int):
return await operations.reading_public(reading_id)
@router.post("/readings", status_code=201)
async def reading_add(body: ReadingIn):
return await operations.add_reading(body.serial, body.kind, body.model_dump(mode="json")["metrics"])
+14
View File
@@ -0,0 +1,14 @@
from fastapi import APIRouter
from backend.app.db import operations
from backend.app.api.schemas import ReceiptOpen
router = APIRouter(prefix="/api/receipts", tags=["receipts"])
@router.get("")
async def receipts():
return await operations.receipts()
@router.post("/{receipt_id}/open")
async def receipt_open(receipt_id: int, body: ReceiptOpen):
return await operations.open_receipt(receipt_id, body.calculation_id)
+36
View File
@@ -0,0 +1,36 @@
import csv
import io
from fastapi import APIRouter, Query
from fastapi.responses import Response
from backend.app.api.schemas import ReportQueryIn
from backend.app.db import operations
from backend.app.db.connection import QueryError
router = APIRouter(prefix="/api/reports", tags=["reports"])
@router.get("/finance/fields")
async def finance_fields():
return await operations.report_fields("finance")
@router.get("/finance/summary")
async def finance_summary(period: str | None = None, fields: list[str] = Query(default=[]),
sort: str = "", group_by: str = "", filter: str = "", having: str = ""):
selected = [field.strip() for item in fields for field in item.split(",") if field.strip()]
return await operations.finance_report(period, selected, sort, group_by, filter, having)
@router.post("/export")
async def export_report(body: ReportQueryIn):
fields = body.fields
if not fields:
fields = [field["id"] for field in await operations.report_fields(body.report)]
if not fields:
raise QueryError("P0400", "Unknown report type.")
report = await operations.finance_report(body.period, fields, body.sort, body.group_by, body.filter, body.having)
output = io.StringIO(newline="")
writer = csv.writer(output)
writer.writerow([column["title"] for column in report["columns"]])
writer.writerows(report["rows"])
return Response(output.getvalue(), media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="finance-{report["period"]}.csv"'})
+43
View File
@@ -0,0 +1,43 @@
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, Field
class ReadingIn(BaseModel):
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
serial: str = Field(min_length=1, max_length=128)
kind: str = Field(min_length=1, max_length=16)
metrics: dict[str, Decimal] = Field(min_length=4, max_length=4)
class CheckStart(BaseModel):
model_config = ConfigDict(extra="forbid")
reading_id: int = Field(gt=0)
class CheckCommit(BaseModel):
model_config = ConfigDict(extra="forbid")
round: int = Field(ge=1, le=10)
values: list[str] = Field(min_length=3, max_length=3)
class CheckAnswer(BaseModel):
model_config = ConfigDict(extra="forbid")
round: int = Field(ge=1, le=10)
data: dict = Field(min_length=2, max_length=2)
class ReceiptOpen(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
calculation_id: str = Field(min_length=44, max_length=44, pattern=r"^[A-Za-z0-9+/]{43}=$")
class ReportQueryIn(BaseModel):
model_config = ConfigDict(extra="forbid")
report: str
period: str
fields: list[str] = []
sort: str = ""
group_by: str = ""
filter: str = ""
having: str = ""
+18
View File
@@ -0,0 +1,18 @@
from pathlib import Path
SQL = Path(__file__).resolve().parents[2] / "database" / "sql"
FILES = (
"schema/billing.sql",
"schema/receipts.sql",
"schema/checks.sql",
"schema/reports.sql",
"functions/checks.sql",
"functions/billing.sql",
"functions/receipts.sql",
"functions/chat.sql",
"functions/reports.sql",
)
def sql():
return "\n".join((SQL / name).read_text(encoding="utf-8") for name in FILES)
+43
View File
@@ -0,0 +1,43 @@
import os
from typing import Any
import psycopg
from psycopg_pool import AsyncConnectionPool
DSN = os.environ.get(
"DATABASE_URL", "postgresql://billing:billing@127.0.0.1:5432/billing"
)
pool: AsyncConnectionPool
class QueryError(Exception):
def __init__(self, sqlstate: str, message: str):
super().__init__(message)
self.sqlstate = sqlstate
self.message = message
def query_error(exc: psycopg.Error) -> QueryError:
message = getattr(exc.diag, "message_primary", None) or str(exc).splitlines()[0]
return QueryError(exc.sqlstate or "", message)
async def open_pool():
global pool
pool = AsyncConnectionPool(
DSN, min_size=1, max_size=8, open=False, kwargs={"autocommit": True},
check=AsyncConnectionPool.check_connection,
)
await pool.open(wait=True)
async def close_pool():
await pool.close()
async def call(sql: str, params: tuple = ()) -> Any:
try:
async with pool.connection() as connection:
cursor = await connection.execute(sql, params)
row = await cursor.fetchone()
except psycopg.Error as exc:
raise query_error(exc) from None
return row[0] if row else None
+27
View File
@@ -0,0 +1,27 @@
import asyncio
import psycopg
from backend.app.db import bootstrap
from backend.app.db.connection import DSN
STARTUP_ATTEMPTS = 10
STARTUP_DELAY = 1.0
async def initialize():
for attempt in range(1, STARTUP_ATTEMPTS + 1):
try:
async with await psycopg.AsyncConnection.connect(DSN, autocommit=True, connect_timeout=5) as db:
async with db.transaction():
await db.execute("select pg_advisory_xact_lock(hashtextextended('dark-tariff:bootstrap', 0))")
await db.execute(bootstrap.sql())
return
except psycopg.OperationalError as error:
if error.sqlstate and not (error.sqlstate.startswith("08") or error.sqlstate in {"40001", "40P01", "55P03"}):
raise
if attempt == STARTUP_ATTEMPTS:
raise
await asyncio.sleep(STARTUP_DELAY)
if __name__ == "__main__":
asyncio.run(initialize())
+75
View File
@@ -0,0 +1,75 @@
import asyncio
import base64
import secrets
import psycopg
from argon2.low_level import Type, hash_secret_raw
from psycopg.types.json import Jsonb
from backend.app.db import connection
from backend.app.db.connection import call
async def resources():
return await call("select billing.resource_types()")
async def readings():
return await call("select billing.reading_list()")
async def reading_public(reading_id):
return await call("select billing.reading_public(%s::bigint)", (reading_id,))
def calculation_key(reading_id):
value = f"{reading_id}|{secrets.randbelow(10000):04d}".encode("ascii")
key = hash_secret_raw(value, bytes(16), time_cost=1, memory_cost=8192,
parallelism=1, hash_len=32, type=Type.ID, version=19)
return base64.b64encode(key).decode("ascii")
async def add_reading(serial, kind, metrics):
try:
async with connection.pool.connection() as db:
async with db.transaction():
cursor = await db.execute(
"select billing.reading_add(%s::text, %s::text, %s::jsonb)",
(serial, kind, Jsonb(metrics)),
)
reading = (await cursor.fetchone())[0]
key = await asyncio.to_thread(calculation_key, reading["id"])
cursor = await db.execute(
"select billing.receipt_issue(r, %s::text)"
" from billing.reading r where r.id = %s::bigint",
(key, reading["id"]),
)
return reading | (await cursor.fetchone())[0] | {"calculation_id": key}
except psycopg.Error as exc:
raise connection.query_error(exc) from None
async def ping():
return await call("select 1")
async def chat_greeting():
return await call("select chat.greeting()")
async def check_start(reading_id):
return await call("select chat.check_start(%s::bigint)", (reading_id,))
async def check_commit(check_id, round, values):
return await call("select chat.check_commit(%s::uuid, %s::int, %s::text[])", (check_id, round, values))
async def check_answer(check_id, round, data):
return await call("select chat.check_answer(%s::uuid, %s::int, %s::jsonb)", (check_id, round, Jsonb(data)))
async def receipts():
return await call("select billing.receipt_list()")
async def open_receipt(receipt_id, calculation_id):
return await call("select billing.receipt_open(%s::bigint, %s::text)", (receipt_id, calculation_id))
async def report_fields(report):
return await call("select billing.report_fields(%s::text)", (report,))
async def finance_report(period=None, fields=None, sort="", group_by="", filter="", having=""):
return await call(
"select jsonb_build_object('period', coalesce(%s::text, to_char(current_date, 'YYYY-MM')))"
" || billing.finance_report(%s::text, %s::text[], %s::text, %s::text, %s::text, %s::text)",
(period, period, fields or [], sort, group_by, filter, having),
)
+63
View File
@@ -0,0 +1,63 @@
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from backend.app.db.connection import QueryError, close_pool, open_pool
from backend.app.api.routes import readings, receipts, health, chat, reports
FRONTEND = Path(__file__).resolve().parents[2] / "frontend"
STATUS = {
"P0400": 400,
"P0403": 403,
"P0404": 404,
"P0409": 409,
}
@asynccontextmanager
async def lifespan(_: FastAPI):
await open_pool()
yield
await close_pool()
def create_app() -> FastAPI:
app = FastAPI(
title="dark-tariff",
lifespan=lifespan,
docs_url=None,
redoc_url=None,
openapi_url=None,
max_body_size=65536,
)
for router in (readings.router, receipts.router, health.router, chat.router, reports.router):
app.include_router(router)
@app.exception_handler(QueryError)
async def query_error(_, exc: QueryError):
status = STATUS.get(exc.sqlstate, 500)
return JSONResponse(
{"detail": exc.message if status != 500 else "The service could not process the request."},
status_code=status,
)
app.mount("/static", StaticFiles(directory=FRONTEND), name="static")
@app.middleware("http")
async def revalidate_static(request, call_next):
response = await call_next(request)
if request.url.path.startswith("/static/"):
response.headers["Cache-Control"] = "no-cache"
if request.url.path.startswith("/api/") and request.method == "POST":
response.headers["Cache-Control"] = "no-store"
return response
@app.get("/", include_in_schema=False)
async def index():
return FileResponse(FRONTEND / "public" / "index.html")
return app
+109
View File
@@ -0,0 +1,109 @@
create or replace function billing.resource_types() returns jsonb
language sql immutable as $$
select '[
{"id": "water", "title": "Вода", "tariff": {"metric": "volume_m3", "rate": "42.10", "unit": "м³"}, "metrics": [
{"key": "volume_m3", "label": "Объём", "unit": "м³", "min": 0, "max": 999999999},
{"key": "temperature_c", "label": "Температура", "unit": "°C", "min": -273.15, "max": 1000},
{"key": "pressure_bar", "label": "Давление", "unit": "бар", "min": 0, "max": 999999999},
{"key": "flow_m3h", "label": "Расход", "unit": "м³/ч", "min": 0, "max": 999999999}
]},
{"id": "air", "title": "Воздух", "tariff": {"metric": "volume_m3", "rate": "25.50", "unit": "м³"}, "metrics": [
{"key": "volume_m3", "label": "Объём", "unit": "м³", "min": 0, "max": 999999999},
{"key": "temperature_c", "label": "Температура", "unit": "°C", "min": -273.15, "max": 1000},
{"key": "pressure_kpa", "label": "Давление", "unit": "кПа", "min": 0, "max": 999999999},
{"key": "humidity_pct", "label": "Влажность", "unit": "%", "min": 0, "max": 100}
]},
{"id": "power", "title": "Электроэнергия", "tariff": {"metric": "energy_kwh", "rate": "7.35", "unit": "кВт⋅ч"}, "metrics": [
{"key": "energy_kwh", "label": "Энергия", "unit": "кВт⋅ч", "min": 0, "max": 999999999},
{"key": "voltage_v", "label": "Напряжение", "unit": "В", "min": 0, "max": 999999999},
{"key": "current_a", "label": "Сила тока", "unit": "А", "min": 0, "max": 999999999},
{"key": "frequency_hz", "label": "Частота", "unit": "Гц", "min": 0, "max": 999999999}
]},
{"id": "heat", "title": "Тепло", "tariff": {"metric": "energy_gcal", "rate": "2300.00", "unit": "Гкал"}, "metrics": [
{"key": "energy_gcal", "label": "Тепловая энергия", "unit": "Гкал", "min": 0, "max": 999999999},
{"key": "volume_m3", "label": "Объём теплоносителя", "unit": "м³", "min": 0, "max": 999999999},
{"key": "supply_temperature_c", "label": "Температура подачи", "unit": "°C", "min": -273.15, "max": 1000},
{"key": "return_temperature_c", "label": "Температура обратки", "unit": "°C", "min": -273.15, "max": 1000}
]},
{"id": "waste", "title": "Отходы", "tariff": {"metric": "mass_kg", "rate": "12.00", "unit": "кг"}, "metrics": [
{"key": "mass_kg", "label": "Масса", "unit": "кг", "min": 0, "max": 999999999},
{"key": "volume_m3", "label": "Объём", "unit": "м³", "min": 0, "max": 999999999},
{"key": "density_kg_m3", "label": "Плотность", "unit": "кг/м³", "min": 0, "max": 999999999},
{"key": "humidity_pct", "label": "Влажность", "unit": "%", "min": 0, "max": 100}
]}
]'::jsonb
$$;
create or replace function billing.reading_list() returns jsonb
language sql stable as $$
select coalesce(jsonb_agg(jsonb_build_object('id', r.id, 'parameters', r.parameters) order by r.created_at desc, r.id desc), '[]'::jsonb)
from billing.reading r
$$;
create or replace function billing.reading_public(p_id bigint) returns jsonb
language plpgsql stable as $$
declare
v_reading jsonb;
begin
select jsonb_build_object('id', r.id, 'parameters', r.parameters) into v_reading
from billing.reading r where r.id = p_id;
if not found then
raise exception 'Reading not found.' using errcode = 'P0404';
end if;
return v_reading;
end;
$$;
create or replace function billing.reading_add(p_serial text, p_kind text, p_metrics jsonb)
returns jsonb
language plpgsql as $$
declare
v_resource jsonb;
v_metric jsonb;
v_text text;
v_value numeric;
v_metrics jsonb := '{}'::jsonb;
v_reading billing.reading;
v_parameters jsonb;
begin
if p_serial is null or btrim(p_serial) = '' or length(p_serial) > 128 then
raise exception 'Enter a meter serial ID between 1 and 128 characters.' using errcode = 'P0400';
end if;
select item into v_resource
from jsonb_array_elements(billing.resource_types()) item
where item ->> 'id' = p_kind;
if v_resource is null then
raise exception 'Select a valid resource type.' using errcode = 'P0400';
end if;
if jsonb_typeof(p_metrics) is distinct from 'object' then
raise exception 'Provide all four metrics for the selected resource type.' using errcode = 'P0400';
end if;
if (select count(*) from jsonb_object_keys(p_metrics)) <> 4
or not p_metrics ?& array(select item ->> 'key' from jsonb_array_elements(v_resource -> 'metrics') item) then
raise exception 'Provide all four metrics for the selected resource type.' using errcode = 'P0400';
end if;
for v_metric in select * from jsonb_array_elements(v_resource -> 'metrics') loop
v_text := p_metrics ->> (v_metric ->> 'key');
if v_text is null or length(v_text) > 32 then
raise exception 'All metrics are required and must be numeric.' using errcode = 'P0400';
end if;
begin
v_value := v_text::numeric;
exception when invalid_text_representation or numeric_value_out_of_range then
raise exception 'All metrics are required and must be numeric.' using errcode = 'P0400';
end;
if v_value not between (v_metric ->> 'min')::numeric and (v_metric ->> 'max')::numeric then
raise exception 'Metric "%" is out of range.', v_metric ->> 'key' using errcode = 'P0400';
end if;
v_metrics := v_metrics || jsonb_build_object(v_metric ->> 'key', v_value);
end loop;
v_parameters := chat.make_parameters();
insert into billing.reading (serial, kind, metrics, n, h, y, w, parameters)
values (btrim(p_serial), p_kind, v_metrics, (v_parameters ->> 'n')::integer,
array(select x::bit varying from jsonb_array_elements_text(v_parameters -> 'h') x),
(v_parameters ->> 'y')::bit varying, (v_parameters ->> 'w')::integer,
v_parameters ->> 'parameters') returning * into v_reading;
return jsonb_build_object('id', v_reading.id, 'parameters', v_reading.parameters,
'verification_id', v_parameters ->> 'verification_id');
end;
$$;
+4
View File
@@ -0,0 +1,4 @@
create or replace function chat.greeting() returns jsonb
language sql immutable as $$
select jsonb_build_object('role', 'bot', 'text', 'Здравствуйте! Я умный помощник сервиса Dark Tariff. Чем могу помочь?', 'prompt', 'Введите ID показания.')
$$;
+204
View File
@@ -0,0 +1,204 @@
create or replace function chat.pack(p_bits bit varying) returns bytea
language sql immutable strict as $$
select substring(varbit_send(p_bits) from 5)
$$;
create or replace function chat.dot(p_h bit varying[], p_v bit varying) returns bit varying
language sql immutable strict as $$
select string_agg((bit_count(bits & p_v) % 2)::text, '' order by ord)::bit varying
from unnest(p_h) with ordinality as rows(bits, ord)
$$;
create or replace function chat.permute(p_v bit varying, p_order integer[]) returns bit varying
language sql immutable strict as $$
select string_agg(get_bit(p_v, pos)::text, '' order by ord)::bit varying
from unnest(p_order) with ordinality as positions(pos, ord)
$$;
create or replace function chat.hash(p_text text) returns text
language sql immutable strict as $$
select encode(digest(p_text, 'sha256'), 'hex')
$$;
create or replace function chat.challenge() returns integer
language plpgsql volatile as $$
declare
v integer;
begin
loop
v := get_byte(gen_random_bytes(1), 0);
exit when v < 200;
end loop;
v := v % 100;
return case when v < 70 then 0 when v < 95 then 1 else 2 end;
end;
$$;
create or replace function chat.make_parameters() returns jsonb
language plpgsql volatile as $$
declare
v_n integer := 1024;
v_m integer := 512;
v_w integer := 112;
v_s bit varying := repeat('0', v_n)::bit varying;
v_h bit varying[] := array[]::bit varying[];
v_y bit varying;
v_row bit varying;
v_bytes bytea := ''::bytea;
v_params text;
v_pos integer;
begin
for v_pos in select i from generate_series(0, v_n - 1) i order by gen_random_bytes(16) limit v_w loop
v_s := set_bit(v_s, v_pos, 1);
end loop;
for v_pos in 0..v_m - 1 loop
v_row := set_bit(repeat('0', v_m)::bit varying, v_pos, 1)
|| ('x' || encode(gen_random_bytes(v_m / 8), 'hex'))::bit varying;
v_h := array_append(v_h, v_row);
v_bytes := v_bytes || chat.pack(v_row);
end loop;
v_y := chat.dot(v_h, v_s);
v_params := replace(encode(convert_to(v_n::text || '|' || encode(v_bytes, 'hex') || '|'
|| v_y::text || '|' || v_w::text, 'UTF8'), 'base64'), E'\n', '');
return jsonb_build_object('n', v_n, 'h', to_jsonb(v_h), 'y', v_y::text, 'w', v_w,
'parameters', v_params,
'verification_id', replace(encode(chat.pack(v_s), 'base64'), E'\n', ''));
end;
$$;
create or replace function chat.valid_response(p_reading billing.reading, p_values text[], p_challenge integer, p_data jsonb)
returns boolean
language plpgsql immutable as $$
declare
v_text text := p_data ->> 'v';
v_v bit varying;
v_t bit varying;
v_p integer[];
v_a text;
v_b text;
v_c text;
begin
if jsonb_typeof(p_data) is distinct from 'object' or v_text is null
or length(v_text) <> p_reading.n or v_text !~ '^[01]+$' then
return false;
end if;
if (select count(*) from jsonb_object_keys(p_data)) <> 2 then
return false;
end if;
v_v := v_text::bit varying;
if p_challenge in (0, 1) then
if jsonb_typeof(p_data -> 'p') is distinct from 'array' then
return false;
end if;
if jsonb_array_length(p_data -> 'p') <> p_reading.n
or exists (select 1 from jsonb_array_elements(p_data -> 'p') x
where jsonb_typeof(x) <> 'number' or x::text !~ '^(0|[1-9][0-9]{0,4})$') then
return false;
end if;
select array_agg(x::text::integer order by ord) into v_p
from jsonb_array_elements(p_data -> 'p') with ordinality as positions(x, ord);
if (select count(distinct x) from unnest(v_p) x) <> p_reading.n
or (select min(x) from unnest(v_p) x) <> 0
or (select max(x) from unnest(v_p) x) <> p_reading.n - 1 then
return false;
end if;
v_a := chat.hash('a|' || array_to_string(v_p, ',') || '|'
|| (chat.dot(p_reading.h, v_v) # case when p_challenge = 1 then p_reading.y
else repeat('0', bit_length(p_reading.y))::bit varying end)::text);
if p_challenge = 0 then
v_b := chat.hash('b|' || chat.permute(v_v, v_p)::text);
return v_a = p_values[1] and v_b = p_values[2];
end if;
v_c := chat.hash('c|' || chat.permute(v_v, v_p)::text);
return v_a = p_values[1] and v_c = p_values[3];
elsif p_challenge = 2 then
v_text := p_data ->> 't';
if v_text is null or length(v_text) <> p_reading.n or v_text !~ '^[01]+$' then
return false;
end if;
v_t := v_text::bit varying;
return bit_count(v_t) = p_reading.w
and chat.hash('b|' || v_v::text) = p_values[2]
and chat.hash('c|' || (v_v # v_t)::text) = p_values[3];
end if;
return false;
end;
$$;
create or replace function chat.check_start(p_reading bigint) returns jsonb
language plpgsql as $$
declare
v_id uuid;
begin
perform 1 from billing.reading where id = p_reading and created_at > now() - interval '10 minutes' for key share;
if not found then
raise exception 'Reading not found.' using errcode = 'P0404';
end if;
insert into chat.check_session (reading_id) values (p_reading) returning id into v_id;
return jsonb_build_object('id', v_id, 'round', 1, 'stage', 'commit',
'message', 'Step 1 of 10. Submit three values.');
end;
$$;
create or replace function chat.check_commit(p_id uuid, p_round integer, p_values text[]) returns jsonb
language plpgsql as $$
declare
v_session chat.check_session;
v_challenge integer;
begin
select * into v_session from chat.check_session where id = p_id for update;
if not found then
raise exception 'Verification not found.' using errcode = 'P0404';
end if;
if v_session.complete or v_session.round <> p_round or v_session.challenge is not null then
raise exception 'This step is already complete or awaiting an answer.' using errcode = 'P0409';
end if;
if cardinality(p_values) is distinct from 3
or exists (select 1 from unnest(p_values) x where x is null or x !~ '^[0-9a-f]{64}$') then
raise exception 'Invalid data format.' using errcode = 'P0400';
end if;
v_challenge := chat.challenge();
update chat.check_session set data = p_values, challenge = v_challenge where id = p_id;
return jsonb_build_object('round', p_round, 'stage', 'answer', 'challenge', v_challenge,
'message', format('Step %s of 10. Challenge: %s. Submit an answer.', p_round, v_challenge));
end;
$$;
create or replace function chat.check_answer(p_id uuid, p_round integer, p_data jsonb) returns jsonb
language plpgsql as $$
declare
v_session chat.check_session;
v_reading billing.reading;
begin
select * into v_session from chat.check_session where id = p_id for update;
if not found then
raise exception 'Verification not found.' using errcode = 'P0404';
end if;
if v_session.complete or v_session.round <> p_round or v_session.challenge is null then
raise exception 'This step is already complete or awaiting data.' using errcode = 'P0409';
end if;
select * into v_reading from billing.reading
where id = v_session.reading_id and created_at > now() - interval '10 minutes';
if not found then
delete from chat.check_session where id = p_id;
return jsonb_build_object('stage', 'failed', 'message', 'The reading is no longer available.');
end if;
if not coalesce(chat.valid_response(v_reading, v_session.data, v_session.challenge, p_data), false) then
delete from chat.check_session where id = p_id;
return jsonb_build_object('stage', 'failed', 'message', 'Verification failed. Try again.');
end if;
if p_round = 10 then
update chat.check_session set complete = true, challenge = null, data = null where id = p_id;
return jsonb_build_object('stage', 'done', 'reading_id', v_reading.id,
'message', 'Verification complete.',
'reading', jsonb_build_object('id', v_reading.id, 'serial', v_reading.serial,
'kind', v_reading.kind, 'metrics', v_reading.metrics,
'created_at', v_reading.created_at));
end if;
update chat.check_session set round = p_round + 1, challenge = null, data = null where id = p_id;
return jsonb_build_object('round', p_round + 1, 'stage', 'commit',
'message', format('Step %s of 10. Submit three values.', p_round + 1));
end;
$$;
drop function if exists chat.check_file(uuid);
+47
View File
@@ -0,0 +1,47 @@
create or replace function billing.receipt_issue(p_reading billing.reading, p_key text) returns jsonb
language plpgsql as $$
declare
v_tariff jsonb;
v_quantity numeric;
v_rate numeric(12, 2);
v_total numeric(22, 2);
v_id bigint;
begin
select item -> 'tariff' into v_tariff
from jsonb_array_elements(billing.resource_types()) item where item ->> 'id' = p_reading.kind;
v_quantity := (p_reading.metrics ->> (v_tariff ->> 'metric'))::numeric;
v_rate := (v_tariff ->> 'rate')::numeric;
v_total := round(v_quantity * v_rate, 2);
insert into billing.receipt (reading_id, key_digest, data)
values (p_reading.id, digest(p_key, 'sha256'), jsonb_build_object(
'reading', jsonb_build_object('id', p_reading.id, 'serial', p_reading.serial, 'kind', p_reading.kind,
'metrics', p_reading.metrics, 'created_at', p_reading.created_at, 'parameters', p_reading.parameters),
'calculation', jsonb_build_object('metric', v_tariff ->> 'metric', 'quantity', v_quantity,
'unit', v_tariff ->> 'unit', 'unit_price', v_rate::text, 'amount', v_total::text,
'currency', 'EDD', 'formula', 'quantity * unit_price')
)) returning id into v_id;
return jsonb_build_object('receipt_id', v_id);
end;
$$;
create or replace function billing.receipt_list() returns jsonb
language sql stable as $$
select coalesce(jsonb_agg(jsonb_build_object('id', id, 'created_at', created_at)
order by created_at desc, id desc), '[]'::jsonb)
from billing.receipt
$$;
create or replace function billing.receipt_open(p_id bigint, p_key text) returns jsonb
language plpgsql stable as $$
declare
v_receipt billing.receipt;
begin
select c.* into v_receipt from billing.receipt c join billing.reading r on r.id = c.reading_id
where c.id = p_id and r.created_at > now() - interval '10 minutes';
if not found or p_key is null or digest(p_key, 'sha256') is distinct from v_receipt.key_digest then
raise exception 'Receipt unavailable. Check the receipt ID and calculation ID.' using errcode = 'P0403';
end if;
return jsonb_build_object('id', v_receipt.id, 'reading_id', v_receipt.reading_id,
'created_at', v_receipt.created_at) || v_receipt.data;
end;
$$;
+58
View File
@@ -0,0 +1,58 @@
create or replace function billing.report_fields(p_report text) returns jsonb
language sql stable as $$
select coalesce(jsonb_agg(jsonb_build_object('id', id, 'title', title) order by position, id), '[]'::jsonb)
from billing.report_field where report_types @> array[p_report]
$$;
create or replace function billing.finance_report(
p_period text, p_fields text[], p_sort text, p_group_by text, p_filter text, p_having text
) returns jsonb
language plpgsql stable as $$
declare
v_period text := coalesce(p_period, to_char(current_date, 'YYYY-MM'));
v_fields text[] := p_fields;
v_columns jsonb;
v_context text;
v_select text;
v_group text;
v_values text;
v_rows jsonb;
begin
if v_period !~ '^[0-9]{4}-(0[1-9]|1[0-2])$' or left(v_period, 4) = '0000' then
raise exception 'Invalid period. Use YYYY-MM.' using errcode = 'P0400';
end if;
if coalesce(cardinality(v_fields), 0) = 0 then
select array_agg(id order by position, id) into v_fields
from billing.report_field where report_types @> array['finance'];
end if;
if exists (select 1 from unnest(v_fields) field where not exists (
select 1 from billing.report_field where id = field and report_types @> array['finance']
)) then
raise exception 'Unknown financial report column.' using errcode = 'P0400';
end if;
select string_agg(format('%s as %I', expression, id), ', ' order by position, id)
into v_context from billing.report_field
where report_types @> array['finance'] and not aggregate;
select jsonb_agg(jsonb_build_object('id', id, 'title', title) order by position, id),
string_agg(format('%s as %I', case when aggregate then expression else format('dimensions.%I', id) end, id), ', ' order by position, id),
string_agg(format('dimensions.%I', id), ', ' order by position, id) filter (where not aggregate),
string_agg(format('report.%I', id), ', ' order by position, id)
into v_columns, v_select, v_group, v_values
from billing.report_field where id = any(v_fields) and report_types @> array['finance'];
execute format(
'select coalesce(jsonb_agg(jsonb_build_array(%s)), ''[]''::jsonb) from (
select %s from billing.receipt c join billing.reading r on r.id = c.reading_id
cross join lateral (select %s) dimensions
where to_char(r.created_at, ''YYYY-MM'') = $1 and (%s)
group by %s having (%s) order by %s
) report', v_values, v_select, v_context,
coalesce(nullif(btrim(p_filter), ''), 'true'),
concat_ws(', ', coalesce(nullif(btrim(p_group_by), ''), 'period, resource, tariff'), v_group),
coalesce(nullif(btrim(p_having), ''), 'true'),
coalesce(nullif(btrim(p_sort), ''), 'resource')
) into v_rows using v_period;
return jsonb_build_object('columns', v_columns, 'rows', v_rows);
exception when syntax_error_or_access_rule_violation or data_exception then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end;
$$;
+22
View File
@@ -0,0 +1,22 @@
create extension if not exists pgcrypto;
create schema if not exists billing;
create table if not exists billing.reading (
id bigserial primary key,
serial text not null check (btrim(serial) <> '' and length(serial) <= 128),
kind text not null,
metrics jsonb not null check (jsonb_typeof(metrics) = 'object'),
created_at timestamptz not null default now(),
n integer not null,
h bit varying[] not null,
y bit varying not null,
w integer not null,
parameters text not null
);
create index if not exists reading_created_at_idx
on billing.reading (created_at);
create unique index if not exists reading_parameters_uniq
on billing.reading (digest(parameters, 'sha256'));
+12
View File
@@ -0,0 +1,12 @@
create schema if not exists chat;
create table if not exists chat.check_session (
id uuid primary key default gen_random_uuid(),
reading_id bigint not null references billing.reading (id) on delete cascade,
round integer not null default 1 check (round between 1 and 10),
challenge integer check (challenge between 0 and 2),
data text[],
complete boolean not null default false
);
create index if not exists check_session_reading_idx on chat.check_session (reading_id);
+7
View File
@@ -0,0 +1,7 @@
create table if not exists billing.receipt (
id bigserial primary key,
reading_id bigint not null unique references billing.reading (id) on delete cascade,
created_at timestamptz not null default now(),
key_digest bytea not null check (octet_length(key_digest) = 32),
data jsonb not null
);
+19
View File
@@ -0,0 +1,19 @@
create table if not exists billing.report_field (
id text primary key,
title text not null,
expression text not null,
aggregate boolean not null default false,
report_types text[] not null default '{}',
position integer not null,
created_at timestamptz not null default now()
);
insert into billing.report_field (id, title, expression, aggregate, report_types, position) values
('period', 'Период', $field$to_char(r.created_at, 'YYYY-MM')$field$, false, '{finance}', 10),
('resource', 'Ресурс', $field$coalesce((select item->>'title' from jsonb_array_elements(billing.resource_types()) item where item->>'id' = r.kind), r.kind)$field$, false, '{finance}', 20),
('tariff', 'Тариф', $field$(c.data->'calculation'->>'unit_price')::numeric$field$, false, '{finance}', 30),
('quantity', 'Количество', $field$sum((c.data->'calculation'->>'quantity')::numeric)$field$, true, '{finance}', 40),
('amount', 'Сумма', $field$sum((c.data->'calculation'->>'amount')::numeric)$field$, true, '{finance}', 50),
('readings', 'Показаний', 'count(*)', true, '{finance}', 60)
on conflict (id) do update set title = excluded.title, expression = excluded.expression,
aggregate = excluded.aggregate, report_types = excluded.report_types, position = excluded.position;
+21
View File
@@ -0,0 +1,21 @@
annotated-types==0.8.0
anyio==4.16.0
argon2-cffi==25.1.0
argon2-cffi-bindings==25.1.0
cffi==2.0.0
click==8.5.1
fastapi==0.165.0
h11==0.16.0
httptools==0.9.0
idna==3.20
psycopg==3.2.13
psycopg-binary==3.2.13
psycopg-pool==3.2.8
pycparser==2.23
pydantic==2.14.4
pydantic_core==2.50.5
starlette==1.10.0
typing-inspection==0.4.5
typing_extensions==4.16.0
uvicorn==0.34.3
uvloop==0.23.0
+5
View File
@@ -0,0 +1,5 @@
FROM postgres:16.16-bookworm
COPY --chmod=755 cleaner.sh /cleaner.sh
CMD ["/cleaner.sh"]
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
set -eu
while true; do
psql --no-psqlrc --set=ON_ERROR_STOP=1 <<'SQL'
delete from billing.reading
where created_at <= now() - interval '10 minutes';
SQL
sleep 60
done
+94
View File
@@ -0,0 +1,94 @@
name: dark-tariff
services:
db:
image: postgres:16.16-bookworm
command: ["postgres", "-c", "max_connections=64", "-c", "statement_timeout=5s", "-c", "lock_timeout=2s", "-c", "idle_in_transaction_session_timeout=5s"]
environment:
POSTGRES_USER: ${POSTGRES_USER:-billing}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-billing}
POSTGRES_DB: ${POSTGRES_DB:-billing}
volumes:
- data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-billing} -d ${POSTGRES_DB:-billing}"]
interval: 5s
timeout: 3s
retries: 12
start_period: 10s
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
pids: 256
stop_grace_period: 30s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
restart: unless-stopped
cleaner:
build: ./cleaner
environment:
PGHOST: db
PGPORT: "5432"
PGUSER: ${POSTGRES_USER:-billing}
PGPASSWORD: ${POSTGRES_PASSWORD:-billing}
PGDATABASE: ${POSTGRES_DB:-billing}
PGOPTIONS: "-c statement_timeout=30s -c lock_timeout=5s"
depends_on:
service:
condition: service_healthy
deploy:
resources:
limits:
cpus: "0.25"
memory: 128M
pids: 64
init: true
stop_grace_period: 10s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
restart: unless-stopped
service:
build: .
environment:
DATABASE_URL: postgresql://${POSTGRES_USER:-billing}:${POSTGRES_PASSWORD:-billing}@db:5432/${POSTGRES_DB:-billing}
PYTHONDONTWRITEBYTECODE: "1"
PYTHONUNBUFFERED: "1"
ports:
- "0.0.0.0:8080:8080"
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=2).close()"]
interval: 10s
timeout: 3s
start_period: 10s
retries: 3
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
pids: 256
init: true
stop_grace_period: 10s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
restart: unless-stopped
volumes:
data:
driver: local
+3
View File
@@ -0,0 +1,3 @@
POSTGRES_USER=billing
POSTGRES_PASSWORD=billing
POSTGRES_DB=billing
+150
View File
@@ -0,0 +1,150 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="theme-color" content="#101015">
<title>Передать показания — Dark Tariff</title>
<link rel="stylesheet" href="/static/src/styles/main.css">
</head>
<body>
<header class="topbar">
<div class="shell topbar-inner">
<a class="brand" href="#/submit" aria-label="Dark Tariff — главная">
<svg id="brand-mark" class="brand-mark" viewBox="0 0 36 36" aria-hidden="true">
<path class="meter-shell" d="M10 2h16l8 8v16l-8 8H10l-8-8V10z"/>
<path class="meter-screen" d="M8 8h20v10H8z"/>
<path class="meter-readout" d="M12 13h4m4 0h4"/>
<path class="meter-dial" d="M9 28a9 9 0 0 1 18 0M18 27l6-6"/>
<circle class="meter-core" cx="18" cy="27" r="2"/>
</svg><span>Dark Tariff</span>
</a>
<nav class="main-nav" aria-label="Основные разделы">
<a href="#/submit" data-route="submit">Передать показания</a>
<a href="#/history" data-route="history">Показания</a>
<a href="#/receipts" data-route="receipts">Квитанции</a>
<a href="#/finance" data-route="finance">Финансы</a>
</nav>
</div>
</header>
<main class="shell">
<section class="page" data-page="submit" aria-labelledby="submit-page-title">
<p class="eyebrow">Учёт ресурсов</p>
<h1 id="submit-page-title">Передавайте показания</h1>
<p class="intro">Фиксируйте показания в новом сервисе Night City — Dark Tariff</p>
<button id="reading-open" class="primary" type="button" disabled>Передать показания</button>
<div id="page-note" class="note" role="status" aria-live="polite" hidden></div>
</section>
<section class="page" data-page="history" aria-labelledby="history-page-title" hidden>
<p class="eyebrow">Переданные показания</p>
<h1 id="history-page-title">Показания</h1>
<div id="history-note" class="note" role="status" aria-live="polite">Загрузка…</div>
<div id="history" class="history-grid"></div>
</section>
<section class="page" data-page="receipts" aria-labelledby="receipts-page-title" hidden>
<p class="eyebrow">Расчёт ресурсов</p>
<h1 id="receipts-page-title">Квитанции</h1>
<div id="receipts-note" class="note" role="status" aria-live="polite">Загрузка…</div>
<div id="receipts" class="history-grid"></div>
</section>
<section class="page" data-page="finance" aria-labelledby="finance-page-title" hidden>
<p class="eyebrow">Финансовый отчёт</p>
<h1 id="finance-page-title">Финансы</h1>
<div class="finance-controls">
<label><span>Период</span><input id="finance-period" type="month" required></label>
<label><span>Сортировка</span><select id="finance-sort"></select></label>
<label><span>Группировка</span><select id="finance-group">
<option value="period, resource, tariff">По ресурсу и тарифу</option>
<option value="period, resource">По ресурсу</option>
<option value="period">По месяцу</option>
</select></label>
<label><span>Ресурс содержит</span><input id="finance-filter" type="text" placeholder="Например, Вода"></label>
<button id="finance-export" class="primary" type="button" disabled>Скачать CSV</button>
</div>
<fieldset class="finance-options">
<legend>Колонки отчёта</legend>
<div id="finance-fields"></div>
</fieldset>
<div id="finance-note" class="note" role="status" aria-live="polite">Загрузка…</div>
<div class="finance-scroll"><table id="finance-table" hidden></table></div>
</section>
</main>
<dialog id="reading-dialog" aria-labelledby="reading-dialog-title">
<div class="panel-head">
<h2 id="reading-dialog-title">Передать показания</h2>
<button id="reading-close" class="action" type="button" aria-label="Закрыть форму">×</button>
</div>
<form id="reading-form" autocomplete="off">
<label><span>Серийный ID счётчика</span><input name="serial" maxlength="128" required></label>
<label><span>Вид измеряемой величины</span><select name="kind" required><option value="">Выберите ресурс</option></select></label>
<div id="metric-fields" class="metric-grid"></div>
<div id="reading-note" class="note" role="status" aria-live="polite" hidden></div>
<button class="primary" type="submit">Отправить показания</button>
</form>
</dialog>
<dialog id="verification-dialog" aria-labelledby="verification-title">
<div class="panel-head">
<h2 id="verification-title">Сохраните идентификаторы</h2>
<button id="verification-close" class="action" type="button" aria-label="Закрыть идентификаторы">×</button>
</div>
<div class="verification-body">
<p>Сохраните оба идентификатора. Они показываются только один раз: для проверки показания и открытия квитанции.</p>
<p>ID показания: <strong id="verification-reading"></strong></p>
<p>ID квитанции: <strong id="verification-receipt"></strong></p>
<label><span>Идентификатор проверки</span><textarea id="verification-secret" rows="4" readonly spellcheck="false"></textarea></label>
<label><span>Расчётный идентификатор</span><textarea id="calculation-secret" rows="2" readonly spellcheck="false"></textarea></label>
</div>
</dialog>
<dialog id="receipt-dialog" aria-labelledby="receipt-dialog-title">
<div class="panel-head">
<h2 id="receipt-dialog-title">Квитанция</h2>
<button id="receipt-close" class="action" type="button" aria-label="Закрыть квитанцию">×</button>
</div>
<form id="receipt-form" autocomplete="off">
<label><span>Расчётный идентификатор</span><input name="calculation_id" type="password" minlength="44" maxlength="44" required></label>
<div id="receipt-note" class="note" role="status" aria-live="polite" hidden></div>
<button class="primary" type="submit">Открыть квитанцию</button>
</form>
<div id="receipt-content" class="verification-body" hidden>
<dl id="receipt-details" class="receipt-details"></dl>
<label><span>Публичные параметры показания</span><textarea id="receipt-parameters" rows="4" readonly spellcheck="false"></textarea></label>
</div>
</dialog>
<dialog id="reading-result-dialog" aria-labelledby="reading-result-title">
<div class="panel-head">
<h2 id="reading-result-title">Показание</h2>
<button id="reading-result-close" class="action" type="button" aria-label="Закрыть показание">×</button>
</div>
<div class="verification-body"><dl id="reading-result-details" class="receipt-details"></dl></div>
</dialog>
<section id="help-chat" class="help-chat panel" role="dialog" aria-labelledby="help-chat-title" hidden>
<div class="panel-head">
<h2 id="help-chat-title">Помощник Dark Tariff</h2>
<button id="help-close" type="button" class="action" aria-label="Закрыть чат">×</button>
</div>
<div class="help-messages" role="log" aria-live="polite">
<p id="help-message">Загрузка…</p>
</div>
<div class="help-controls">
<button id="help-question" class="action" type="button" disabled>Помогите мне проверить мои переданные показания</button>
<form id="help-form" autocomplete="off" hidden>
<label id="help-id-label"><span>ID показания</span><input id="help-id" name="reading_id" type="number" min="1" step="1" required></label>
<label id="help-data-label" hidden><span>Данные проверки (JSON)</span><textarea id="help-data" rows="5" maxlength="24000" spellcheck="false" disabled required></textarea></label>
<div id="help-note" class="note" role="status" aria-live="polite" hidden></div>
<button class="primary" type="submit">Отправить</button>
</form>
</div>
</section>
<button id="help-launcher" class="help-launcher" type="button" aria-controls="help-chat" aria-expanded="false">
<span class="help-hint">Нужна помощь?</span>
<svg class="brand-mark" viewBox="0 0 36 36" aria-hidden="true"><use href="#brand-mark"/></svg>
</button>
<script type="module" src="/static/src/main.js"></script>
</body>
</html>
+34
View File
@@ -0,0 +1,34 @@
function jsonPost(body) {
return { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) };
}
function responseError(result, fallback) {
return new Error(typeof result.detail === "string" ? result.detail : fallback);
}
export async function api(path, opts = {}) {
const response = await fetch(path, opts);
const result = await response.json();
if (!response.ok) throw responseError(result, "Проверьте поля запроса.");
return result;
}
export function post(path, body) {
return api(path, jsonPost(body));
}
export async function download(path, body, fallback) {
const response = await fetch(path, jsonPost(body));
if (!response.ok) {
const result = await response.json();
throw responseError(result, "Не удалось скачать отчёт.");
}
const url = URL.createObjectURL(await response.blob());
const link = document.createElement("a");
link.href = url;
link.download = response.headers.get("content-disposition")?.match(/filename="?([^";]+)"?/i)?.[1] || fallback;
document.body.append(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
+115
View File
@@ -0,0 +1,115 @@
import { api, post } from "../api/client.js";
import { $, cell, note } from "../shared/dom.js";
export async function initChat(resourcesPromise) {
const launcher = $("#help-launcher");
const chat = $("#help-chat");
const close = $("#help-close");
const question = $("#help-question");
const form = $("#help-form");
const input = $("#help-id");
const data = $("#help-data");
const messages = $(".help-messages");
const dialog = $("#reading-result-dialog");
const details = $("#reading-result-details");
let greeting;
let stage = "id";
let check;
let round;
function message(text, kind = "") {
messages.append(cell("p", text, kind));
messages.scrollTop = messages.scrollHeight;
}
function setOpen(open) {
chat.hidden = !open;
launcher.setAttribute("aria-expanded", String(open));
(open ? close : launcher).focus();
}
function finish() {
form.hidden = true;
form.reset();
question.hidden = false;
check = null;
}
$("#reading-result-close").addEventListener("click", () => dialog.close());
dialog.addEventListener("close", () => details.replaceChildren());
launcher.addEventListener("click", () => setOpen(chat.hidden));
close.addEventListener("click", () => setOpen(false));
chat.addEventListener("keydown", (event) => {
if (event.key === "Escape") setOpen(false);
});
question.addEventListener("click", () => {
stage = "id";
form.reset();
question.hidden = true;
form.hidden = false;
$("#help-note").hidden = true;
$("#help-id-label").hidden = false;
$("#help-data-label").hidden = true;
input.disabled = false;
data.disabled = true;
message(question.textContent, "help-user");
message(greeting.prompt);
input.focus();
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const button = event.submitter;
button.disabled = true;
$("#help-note").hidden = true;
try {
let result;
if (stage === "id") {
result = await post("/api/chat/checks", { reading_id: Number(input.value) });
check = result.id;
input.disabled = true;
data.disabled = false;
$("#help-id-label").hidden = true;
$("#help-data-label").hidden = false;
} else {
let value;
try { value = JSON.parse(data.value); }
catch { throw new Error("Проверьте формат JSON."); }
result = await post(`/api/chat/checks/${check}/${stage === "commit" ? "commit" : "answer"}`,
stage === "commit" ? { round, values: value } : { round, data: value });
}
stage = result.stage;
round = result.round;
data.value = "";
message(result.message);
if (stage === "done") {
finish();
const reading = result.reading;
const resource = (await resourcesPromise).find((item) => item.id === reading.kind);
const rows = [
["ID показания", reading.id], ["Дата показания", new Date(reading.created_at).toLocaleString("ru-RU")],
["Серийный ID", reading.serial], ["Вид ресурса", resource.title],
...resource.metrics.map((metric) => [metric.label, `${reading.metrics[metric.key]} ${metric.unit}`]),
];
details.replaceChildren();
for (const [label, value] of rows) details.append(cell("dt", label), cell("dd", value));
dialog.showModal();
} else if (stage === "failed") {
finish();
} else {
data.focus();
}
} catch (error) {
note($("#help-note"), error.message, "err");
} finally {
button.disabled = false;
}
});
try {
greeting = await api("/api/chat/greeting");
$("#help-message").textContent = greeting.text;
question.disabled = false;
} catch {
$("#help-message").textContent = "Не удалось загрузить сообщение. Обновите страницу.";
}
return () => {
setOpen(true);
if (!question.hidden) question.click();
};
}
+117
View File
@@ -0,0 +1,117 @@
import { api, download } from "../api/client.js";
import { $, cell, note } from "../shared/dom.js";
import { onRoute } from "../shared/router.js";
export function initFinance() {
const period = $("#finance-period");
const fields = $("#finance-fields");
const sort = $("#finance-sort");
const group = $("#finance-group");
const filter = $("#finance-filter");
const button = $("#finance-export");
const table = $("#finance-table");
const status = $("#finance-note");
const money = new Intl.NumberFormat("ru-RU", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const today = new Date();
period.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}`;
let loading = 0;
function selected() {
return Array.from(fields.querySelectorAll("input:checked"), (input) => input.value);
}
function query() {
const text = filter.value.trim().replace(/[\\%_]/g, "\\$&").replaceAll("'", "''");
return { report: "finance", period: period.value, fields: selected(), sort: sort.value,
group_by: group.value, filter: text ? `resource ilike '%${text}%'` : "", having: "" };
}
function selectSort() {
const ids = selected();
for (const option of sort.options) option.disabled = !ids.includes(option.value.split(" ")[0]);
if (sort.selectedOptions[0]?.disabled) sort.value = Array.from(sort.options).find((option) => !option.disabled)?.value || "";
sort.disabled = !ids.length;
}
function selectGroup() {
const dimensions = group.options[0].value.split(", ");
for (const input of fields.querySelectorAll("input")) {
if (dimensions.includes(input.value)) input.checked = group.value.split(", ").includes(input.value);
}
selectSort();
}
async function load() {
const request = ++loading;
button.disabled = true;
table.hidden = true;
note(status, "Загрузка…");
try {
if (!fields.children.length) {
const catalogue = await api("/api/reports/finance/fields");
if (request !== loading) return;
for (const field of catalogue) {
const label = document.createElement("label");
const input = document.createElement("input");
input.type = "checkbox";
input.value = field.id;
input.checked = true;
label.append(input, cell("span", field.title));
fields.append(label);
for (const direction of ["asc", "desc"]) {
const option = cell("option", `${field.title} ${direction === "asc" ? "↑" : "↓"}`);
option.value = `${field.id} ${direction}`;
sort.append(option);
}
}
sort.value = "resource asc";
selectGroup();
}
const data = query();
if (!data.fields.length) return note(status, "Выберите хотя бы одну колонку.");
const params = new URLSearchParams({ period: data.period, sort: data.sort, group_by: data.group_by, filter: data.filter, having: data.having });
for (const field of data.fields) params.append("fields", field);
const report = await api(`/api/reports/finance/summary?${params}`);
if (request !== loading) return;
const head = document.createElement("thead");
const row = document.createElement("tr");
for (const column of report.columns) {
const title = cell("th", column.title);
title.scope = "col";
row.append(title);
}
head.append(row);
const body = document.createElement("tbody");
for (const values of report.rows) {
const row = document.createElement("tr");
report.columns.forEach((column, index) => row.append(cell("td", ["tariff", "amount"].includes(column.id) ? money.format(values[index]) : values[index])));
body.append(row);
}
table.replaceChildren(head, body);
table.hidden = !report.rows.length;
status.hidden = report.rows.length > 0;
if (!report.rows.length) note(status, "За выбранный период показаний нет.");
button.disabled = false;
} catch (error) {
if (request === loading) note(status, error.message, "err");
}
}
period.addEventListener("change", load);
sort.addEventListener("change", load);
filter.addEventListener("input", load);
fields.addEventListener("change", () => { selectSort(); load(); });
group.addEventListener("change", () => { selectGroup(); load(); });
button.addEventListener("click", async () => {
const request = loading;
button.disabled = true;
try {
await download("/api/reports/export", query(), `finance-${period.value}.csv`);
} catch (error) {
note(status, error.message, "err");
} finally {
if (request === loading) button.disabled = !selected().length;
}
});
onRoute("finance", load);
}
+117
View File
@@ -0,0 +1,117 @@
import { api, post } from "../api/client.js";
import { $, cell, note } from "../shared/dom.js";
import { navigateTo, onRoute } from "../shared/router.js";
export async function initReadings(resourcesPromise, chatPromise) {
const dialog = $("#reading-dialog");
const form = $("#reading-form");
const selector = form.elements.kind;
let resources;
try {
resources = await resourcesPromise;
} catch (error) {
note($("#page-note"), error.message, "err");
note($("#history-note"), error.message, "err");
return;
}
for (const resource of resources) {
const option = cell("option", resource.title);
option.value = resource.id;
selector.append(option);
}
function renderFields() {
const fields = $("#metric-fields");
fields.replaceChildren();
const resource = resources.find((item) => item.id === selector.value);
if (!resource) return;
for (const metric of resource.metrics) {
const label = document.createElement("label");
const input = document.createElement("input");
input.type = "number";
input.name = metric.key;
input.step = "any";
input.min = metric.min;
input.max = metric.max;
input.required = true;
label.append(cell("span", `${metric.label}, ${metric.unit}`), input);
fields.append(label);
}
}
let loading = 0;
async function loadHistory() {
const request = ++loading;
const status = $("#history-note");
note(status, "Загрузка…");
try {
const readings = await api("/api/readings");
if (request !== loading) return;
const cards = $("#history");
cards.replaceChildren();
for (const reading of readings) {
const card = cell("article", "", "reading-card panel");
const label = cell("label", "");
const parameters = document.createElement("textarea");
parameters.value = reading.parameters;
parameters.readOnly = true;
parameters.rows = 4;
parameters.spellcheck = false;
label.append(cell("span", "Параметры проверки"), parameters);
const button = cell("button", "Проверка", "action reading-check");
button.type = "button";
button.setAttribute("aria-label", `Проверка показания #${reading.id}`);
button.addEventListener("click", async () => {
const openCheck = await chatPromise;
openCheck();
});
card.append(cell("h2", `ID показания: ${reading.id}`), label, button);
cards.append(card);
}
status.hidden = readings.length > 0;
if (!readings.length) note(status, "Показаний пока нет.");
} catch (error) {
if (request === loading) note(status, error.message, "err");
}
}
$("#verification-close").addEventListener("click", () => $("#verification-dialog").close());
$("#verification-dialog").addEventListener("close", () => {
$("#verification-secret").value = "";
$("#verification-reading").textContent = "";
$("#verification-receipt").textContent = "";
$("#calculation-secret").value = "";
});
selector.addEventListener("change", renderFields);
$("#reading-open").addEventListener("click", () => {
$("#reading-note").hidden = true;
dialog.showModal();
});
$("#reading-close").addEventListener("click", () => dialog.close());
form.addEventListener("submit", async (event) => {
event.preventDefault();
const button = event.submitter;
button.disabled = true;
try {
const data = new FormData(form);
const resource = resources.find((item) => item.id === data.get("kind"));
const metrics = Object.fromEntries(resource.metrics.map((metric) => [metric.key, data.get(metric.key)]));
const result = await post("/api/readings", { serial: data.get("serial").trim(), kind: resource.id, metrics });
form.reset();
renderFields();
dialog.close();
navigateTo("history");
$("#verification-reading").textContent = result.id;
$("#verification-secret").value = result.verification_id;
$("#verification-receipt").textContent = result.receipt_id;
$("#calculation-secret").value = result.calculation_id;
$("#verification-dialog").showModal();
} catch (error) {
note($("#reading-note"), error.message, "err");
} finally {
button.disabled = false;
}
});
$("#reading-open").disabled = false;
onRoute("history", loadHistory);
}
+104
View File
@@ -0,0 +1,104 @@
import { api, post } from "../api/client.js";
import { $, cell, note } from "../shared/dom.js";
import { onRoute } from "../shared/router.js";
export async function initReceipts(resourcesPromise) {
const dialog = $("#receipt-dialog");
const form = $("#receipt-form");
const details = $("#receipt-details");
const amount = new Intl.NumberFormat("ru-RU", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
let selected;
let opening = 0;
let resources;
let loading = 0;
try {
resources = await resourcesPromise;
} catch (error) {
note($("#receipts-note"), error.message, "err");
return;
}
async function loadReceipts() {
const request = ++loading;
note($("#receipts-note"), "Загрузка…");
try {
const receipts = await api("/api/receipts");
if (request !== loading) return;
const cards = $("#receipts");
cards.replaceChildren();
for (const receipt of receipts) {
const card = cell("article", "", "reading-card panel");
const time = cell("time", new Date(receipt.created_at).toLocaleString("ru-RU"));
time.dateTime = receipt.created_at;
const button = cell("button", "Открыть", "action");
button.type = "button";
button.setAttribute("aria-label", `Открыть квитанцию #${receipt.id}`);
button.addEventListener("click", () => {
opening++;
selected = receipt.id;
form.querySelector("button[type=submit]").disabled = false;
form.reset();
form.hidden = false;
$("#receipt-note").hidden = true;
$("#receipt-content").hidden = true;
details.replaceChildren();
$("#receipt-parameters").value = "";
$("#receipt-dialog-title").textContent = `Квитанция #${receipt.id}`;
dialog.showModal();
});
card.append(cell("h2", `ID квитанции: ${receipt.id}`), time, button);
cards.append(card);
}
$("#receipts-note").hidden = receipts.length > 0;
if (!receipts.length) note($("#receipts-note"), "Квитанций пока нет.");
} catch (error) {
if (request === loading) note($("#receipts-note"), error.message, "err");
}
}
$("#receipt-close").addEventListener("click", () => dialog.close());
dialog.addEventListener("close", () => {
opening++;
form.reset();
details.replaceChildren();
$("#receipt-parameters").value = "";
$("#receipt-content").hidden = true;
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const request = ++opening;
const button = event.submitter;
button.disabled = true;
try {
const receipt = await post(`/api/receipts/${selected}/open`, { calculation_id: form.elements.calculation_id.value.trim() });
if (request !== opening) return;
const reading = receipt.reading;
const calculation = receipt.calculation;
const resource = resources.find((item) => item.id === reading.kind);
const rows = [
["ID квитанции", receipt.id], ["ID показания", receipt.reading_id],
["Дата квитанции", new Date(receipt.created_at).toLocaleString("ru-RU")],
["Дата показания", new Date(reading.created_at).toLocaleString("ru-RU")],
["Серийный ID", reading.serial], ["Вид ресурса", resource.title],
...resource.metrics.map((metric) => [metric.label, `${reading.metrics[metric.key]} ${metric.unit}`]),
["Количество", `${calculation.quantity} ${calculation.unit}`],
["Тариф", `${amount.format(calculation.unit_price)} €$ / ${calculation.unit}`],
["Расчёт", `${calculation.quantity} × ${calculation.unit_price}`],
["К оплате", `${amount.format(calculation.amount)} €$`],
];
details.replaceChildren();
for (const [label, value] of rows) {
details.append(cell("dt", label), cell("dd", value, label === "К оплате" ? "receipt-total" : ""));
}
$("#receipt-parameters").value = reading.parameters;
form.reset();
form.hidden = true;
$("#receipt-content").hidden = false;
} catch (error) {
if (request === opening) note($("#receipt-note"), error.message, "err");
} finally {
if (request === opening) button.disabled = false;
}
});
onRoute("receipts", loadReceipts);
}
+13
View File
@@ -0,0 +1,13 @@
import { api } from "./api/client.js";
import { initReadings } from "./features/readings.js";
import { initReceipts } from "./features/receipts.js";
import { initChat } from "./features/chat.js";
import { initFinance } from "./features/finance.js";
import { initRouter } from "./shared/router.js";
initRouter();
const resources = api("/api/resources");
const chat = initChat(resources);
initReadings(resources, chat);
initReceipts(resources);
initFinance();
+14
View File
@@ -0,0 +1,14 @@
export const $ = (sel) => document.querySelector(sel);
export function cell(tag, text, cls) {
const element = document.createElement(tag);
element.textContent = text;
if (cls) element.className = cls;
return element;
}
export function note(element, text, kind = "ok") {
element.textContent = text;
element.className = `note ${kind}`;
element.hidden = false;
}
+45
View File
@@ -0,0 +1,45 @@
const routes = {
submit: "Передать показания",
history: "Показания",
receipts: "Квитанции",
finance: "Финансы",
};
function currentRoute() {
const route = window.location.hash.replace(/^#\//, "");
return routes[route] ? route : "submit";
}
function renderRoute() {
const route = currentRoute();
for (const page of document.querySelectorAll("[data-page]")) {
page.hidden = page.dataset.page !== route;
}
for (const link of document.querySelectorAll("[data-route]")) {
if (link.dataset.route === route) link.setAttribute("aria-current", "page");
else link.removeAttribute("aria-current");
}
document.title = routes[route] + " — Dark Tariff";
}
export function onRoute(route, callback) {
function load() {
if (window.location.hash === "#/" + route) callback();
}
window.addEventListener("hashchange", load);
load();
}
export function navigateTo(route) {
if (!routes[route]) return;
if (currentRoute() === route) renderRoute();
else window.location.hash = "#/" + route;
}
export function initRouter() {
if (!window.location.hash || !routes[window.location.hash.replace(/^#\//, "")]) {
window.history.replaceState(null, "", "#/submit");
}
window.addEventListener("hashchange", renderRoute);
renderRoute();
}
+207
View File
@@ -0,0 +1,207 @@
:root {
color-scheme: dark;
--bg: #101015;
--panel: #18181f;
--field: #111117;
--raised: #22222c;
--line: #373744;
--ink: #f3f2f5;
--dim: #aaa8b6;
--acid: #efff43;
--cyan: #70ede1;
--pink: #ff5090;
--error: #ff9dbd;
--sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
--mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { min-width: 1168px; min-height: 100vh; margin: 0; overflow-x: clip; isolation: isolate; background: var(--bg); color: var(--ink); font: 16px/1.5 var(--sans); }
body::before, body::after { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; }
body::before {
background: repeating-linear-gradient(0deg, transparent 0 3px, #70ede104 3px 4px),
linear-gradient(#70ede109 1px, transparent 1px), linear-gradient(90deg, #70ede109 1px, transparent 1px);
background-size: auto, 80px 80px, 80px 80px;
mask-image: linear-gradient(#0009, #0002);
}
body::after {
inset: -12%;
background: radial-gradient(ellipse at 80% 25%, #70ede11c, transparent 48%), radial-gradient(ellipse at 10% 85%, #efff4310, transparent 42%);
animation: ambient-drift 20s ease-in-out infinite alternate;
}
button, input, select, textarea { font: inherit; }
button { cursor: pointer; }
button:disabled { opacity: .55; cursor: default; }
:focus-visible { outline: 2px solid var(--cyan); outline-offset: 3px; }
.shell { width: 1120px; margin-inline: auto; }
.topbar { border-bottom: 1px solid var(--line); background: #0c0c11e8; box-shadow: 0 1px 0 #70ede10b; }
.topbar-inner { min-height: 80px; display: flex; align-items: center; justify-content: space-between; gap: 24px; }
.brand {
display: flex;
align-items: center;
gap: 12px;
color: var(--ink);
font-size: 24px;
font-weight: 850;
letter-spacing: -.05em;
text-decoration: none;
}
.brand-mark {
width: 34px;
height: 34px;
flex: 0 0 auto;
filter: drop-shadow(0 0 7px #efff4366);
}
.meter-shell { fill: #17190c; stroke: var(--acid); stroke-width: 2; }
.meter-screen { fill: #70ede122; stroke: var(--cyan); stroke-width: 1.5; }
.meter-readout, .meter-dial { fill: none; stroke: var(--acid); stroke-linecap: square; stroke-width: 2; }
.meter-core { fill: var(--pink); }
.main-nav { display: flex; gap: 24px; }
.main-nav a { position: relative; padding-block: 8px; color: var(--dim); text-decoration: none; font-size: 13px; font-weight: 750; letter-spacing: .025em; text-transform: uppercase; transition: color .18s ease; }
.main-nav a::after { content: ""; position: absolute; inset: auto 0 0; height: 2px; background: var(--acid); box-shadow: 0 0 12px #efff4340; transform: scaleX(0); transform-origin: left; transition: transform .2s ease; }
.main-nav a:hover::after, .main-nav a[aria-current="page"]::after { transform: scaleX(1); }
.main-nav a:hover, .main-nav a[aria-current="page"] { color: var(--acid); }
.page { position: relative; padding: 60px 0 110px; }
.page:not([hidden]) { animation: reveal .32s ease-out backwards; }
.page::before { content: ""; position: absolute; top: 38px; right: 0; width: 88px; height: 4px; background: repeating-linear-gradient(135deg, var(--acid) 0 5px, transparent 5px 10px); opacity: .65; }
h1 { margin: 14px 0 20px; font-size: 68px; font-weight: 900; letter-spacing: -.055em; line-height: 1.02; text-transform: uppercase; }
#submit-page-title { max-width: 940px; margin-top: 24px; font-size: 96px; line-height: .98; }
[data-page="submit"] { padding-top: clamp(60px, 9vh, 108px); }
.eyebrow { display: flex; align-items: center; gap: 12px; margin: 0; color: var(--cyan); font: 700 12px/1.5 var(--mono); letter-spacing: .16em; text-transform: uppercase; }
.eyebrow::before { content: ""; width: 8px; height: 8px; background: var(--acid); box-shadow: 0 0 14px #efff4340; }
.intro { max-width: 620px; margin-bottom: 28px; color: var(--dim); }
.primary, .action { min-height: 44px; padding: 11px 18px; border: 1px solid var(--line); font-weight: 750; clip-path: polygon(0 0, calc(100% - 8px) 0, 100% 8px, 100% 100%, 8px 100%, 0 calc(100% - 8px)); transition: transform .18s ease, background .18s ease, border-color .18s ease, color .18s ease; }
.primary { border-color: var(--acid); background: var(--acid); color: var(--bg); }
.primary:hover:not(:disabled) { background: #fbff9e; transform: translate(2px, -2px); }
.primary:active:not(:disabled), .action:active:not(:disabled) { transform: translateY(1px); }
.primary:focus-visible { box-shadow: inset 0 0 0 2px var(--bg); }
.action:focus-visible { box-shadow: inset 0 0 0 2px var(--cyan); }
.action { background: var(--field); color: var(--ink); }
.action:hover:not(:disabled) { border-color: var(--cyan); background: #70ede10a; color: var(--cyan); transform: translateY(-2px); }
.panel, dialog { background: linear-gradient(135deg, #70ede109, transparent 60%), var(--panel); border: 1px solid var(--line); border-radius: 0; clip-path: polygon(0 0, calc(100% - 16px) 0, 100% 16px, 100% 100%, 16px 100%, 0 calc(100% - 16px)); }
.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 16px 24px; border-bottom: 1px solid var(--line); }
.panel-head h2 { margin: 0; font: 750 18px/1.4 var(--mono); letter-spacing: -.025em; }
dialog[open], .help-chat:not([hidden]) { animation: reveal .2s ease-out backwards; }
dialog { width: 640px; max-height: calc(100vh - 32px); padding: 0; overflow: auto; color: var(--ink); }
dialog::backdrop { background: #08080dcc; backdrop-filter: blur(6px); animation: backdrop-in .2s ease-out; }
form { display: grid; gap: 20px; padding: 24px; }
label { display: grid; gap: 7px; color: var(--dim); font-size: 14px; }
input, select, textarea { width: 100%; min-width: 0; min-height: 44px; padding: 10px 12px; border: 1px solid var(--line); background: var(--field); color: var(--ink); }
input:not([type="checkbox"]), select, textarea { transition: border-color .2s ease, box-shadow .2s ease; }
input:not([type="checkbox"]):focus, select:focus, textarea:focus { border-color: var(--cyan); box-shadow: inset 3px 0 var(--cyan); }
input, textarea, time, .receipt-details dd, #verification-reading, #verification-receipt { font-family: var(--mono); font-variant-numeric: tabular-nums; }
.metric-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
.field-help { margin: 0; color: var(--dim); font-size: 13px; }
.note { margin-top: 12px; padding: 10px 14px; border-left: 2px solid var(--cyan); background: var(--field); color: var(--cyan); overflow-wrap: anywhere; }
.note.err { color: var(--error); border-color: var(--error); }
.history-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
.reading-card { position: relative; min-width: 0; padding: 24px; animation: reveal .34s ease-out backwards; transition: transform .2s ease, border-color .2s ease; }
.reading-card::before { content: ""; position: absolute; top: 0; left: 0; width: 48px; height: 3px; background: var(--acid); }
.reading-card::after { content: ""; position: absolute; right: 10px; bottom: 10px; width: 8px; height: 8px; border-right: 1px solid var(--cyan); border-bottom: 1px solid var(--cyan); opacity: .5; }
.reading-card:hover { transform: translateY(-4px); border-color: var(--cyan); }
.reading-card:nth-child(2) { animation-delay: 40ms; }
.reading-card:nth-child(3) { animation-delay: 80ms; }
.reading-card:nth-child(n+4) { animation-delay: 120ms; }
.reading-card h2 { margin: 8px 0; overflow-wrap: anywhere; font: 750 20px/1.4 var(--mono); }
.reading-check { min-height: 32px; margin-top: 16px; padding: 6px 12px; font-size: 12px; }
.help-launcher {
position: fixed;
right: 24px;
bottom: 24px;
z-index: 20;
display: flex;
align-items: center;
gap: 14px;
padding: 10px;
border: 0;
background: transparent;
color: var(--ink);
}
.help-hint {
position: relative;
padding: 10px 14px;
border: 1px solid var(--line);
border-radius: 0;
background: var(--raised);
}
.help-hint::after {
content: "";
position: absolute;
top: 50%;
right: -5px;
width: 8px;
height: 8px;
border-top: 1px solid var(--line);
border-right: 1px solid var(--line);
background: var(--raised);
transform: translateY(-50%) rotate(45deg);
}
.help-chat {
position: fixed;
right: 24px;
bottom: 100px;
z-index: 20;
width: 360px;
max-height: calc(100vh - 124px);
overflow: auto;
}
.help-chat .panel-head { min-height: 0; gap: 12px; padding: 16px; }
.help-chat .panel-head h2 { font-size: 18px; }
.help-messages p {
margin: 0 0 10px;
padding: 12px 14px;
border-left: 2px solid var(--line);
border-radius: 0;
background: var(--raised);
overflow-wrap: anywhere;
animation: reveal .2s ease-out backwards;
}
textarea { resize: vertical; font-size: 13px; line-height: 1.55; }
.verification-body { display: grid; gap: 16px; padding: 24px; }
.verification-body p { margin: 0; }
.reading-card label { margin-top: 16px; }
.help-controls { padding: 0 16px 16px; }
.help-controls .action { width: 100%; text-align: left; font-size: 13px; }
.help-controls form { gap: 12px; padding: 0; }
.help-messages { min-height: 0; max-height: 240px; overflow-y: auto; padding: 16px; }
.help-messages .help-user { color: var(--cyan); }
.reading-card time { display: block; margin: 8px 0 16px; color: var(--dim); font-size: 13px; }
.receipt-details { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; margin: 0; }
.receipt-details dt { color: var(--dim); }
.receipt-details dd { margin: 0; overflow-wrap: anywhere; }
.receipt-details .receipt-total { color: var(--acid); font-weight: 750; }
.finance-controls { display: flex; flex-wrap: wrap; align-items: end; gap: 16px; margin-block: 24px; }
.finance-controls label { display: grid; gap: 8px; }
.finance-options { margin: 0 0 24px; padding: 16px; border: 1px solid var(--line); }
#finance-fields { display: flex; flex-wrap: wrap; gap: 16px; }
#finance-fields label { display: flex; align-items: center; gap: 8px; }
#finance-fields input { width: auto; accent-color: var(--acid); }
.finance-scroll { overflow-x: auto; }
#finance-table { width: 100%; border-collapse: collapse; }
#finance-table th, #finance-table td { padding: 12px; text-align: left; white-space: nowrap; border-bottom: 1px solid var(--line); }
#finance-table th { color: var(--cyan); }
#finance-table tbody tr { transition: background .18s ease; }
#finance-table tbody tr:hover { background: #70ede107; }
@keyframes ambient-drift {
from { transform: translate(-2%, -1%); }
to { transform: translate(3%, 3%); }
}
@keyframes reveal {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes backdrop-in {
from { opacity: 0; }
to { opacity: 1; }
}
+26
View File
@@ -0,0 +1,26 @@
.PHONY: build run up down restart logs ps clean init-db
build:
docker compose -f docker-compose.yml build
run:
docker compose -f docker-compose.yml up -d --build
up: run
down:
docker compose -f docker-compose.yml down
clean:
docker compose -f docker-compose.yml down -v --remove-orphans
restart: down run
logs:
docker compose -f docker-compose.yml logs -f
ps:
docker compose -f docker-compose.yml ps
init-db: clean
docker compose -f docker-compose.yml up -d --build
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
FROM alpine:3.20
RUN apk add --no-cache cjson libpq && \
mkdir -p /var/run/delamain && \
chown root:1000 /var/run/delamain && chmod 0770 /var/run/delamain
USER 1000:1000
COPY bin/delamain-daemon /usr/local/bin/delamain-daemon
CMD ["/usr/local/bin/delamain-daemon"]
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
: "${PGHOST:=postgres}"
: "${PGUSER:=postgres}"
: "${PGDATABASE:=delamain}"
: "${PGPASSWORD:=postgres}"
: "${CLEAN_OLDER_THAN:=6 minutes}"
: "${CLEAN_EVERY:=60}"
export PGHOST PGUSER PGDATABASE PGPASSWORD
while true; do
sleep "$CLEAN_EVERY"
psql -c "DELETE FROM trips WHERE created_at < now() - interval '${CLEAN_OLDER_THAN}'"
psql -c "DELETE FROM users WHERE created_at < now() - interval '${CLEAN_OLDER_THAN}'"
done
+110
View File
@@ -0,0 +1,110 @@
services:
postgres:
image: postgres:14-alpine
container_name: delamain_postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: delamain
volumes:
- postgres_data:/var/lib/postgresql/data
- ./sql/schema.sql:/docker-entrypoint-initdb.d/01-schema.sql:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d delamain"]
interval: 5s
timeout: 5s
retries: 10
networks:
- delamain_network
ports: []
restart: unless-stopped
c-daemon:
build:
context: .
dockerfile: c.Dockerfile
container_name: delamain_c_daemon
environment:
DB_HOST: postgres
DB_PORT: "5432"
DB_USER: delamain_ro
DB_PASSWORD: delamain_ro
DB_NAME: delamain
volumes:
- daemon_sock:/var/run/delamain
networks:
- delamain_network
restart: unless-stopped
go-server:
build:
context: .
dockerfile: go.Dockerfile
container_name: delamain_go_server
environment:
DB_HOST: postgres
DB_PORT: "5432"
DB_USER: postgres
DB_PASSWORD: postgres
DB_NAME: delamain
C_SOCKET_PATH: /var/run/delamain/daemon.sock
FRONTEND_DIR: /app/frontend
volumes:
- daemon_sock:/var/run/delamain
- ./frontend:/app/frontend:ro
ports: []
depends_on:
postgres:
condition: service_healthy
c-daemon:
condition: service_started
healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8080/api/health || exit 1"]
interval: 10s
timeout: 5s
retries: 5
networks:
- delamain_network
restart: unless-stopped
nginx:
image: nginx:alpine
container_name: delamain_nginx
ports:
- "80:80"
volumes:
- ./frontend:/usr/share/nginx/html:ro
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
- go-server
networks:
- delamain_network
restart: unless-stopped
cleaner:
image: postgres:14-alpine
container_name: delamain_cleaner
entrypoint: ["sh", "/usr/local/bin/cleaner.sh"]
environment:
PGPASSWORD: postgres
PGHOST: postgres
PGUSER: postgres
PGDATABASE: delamain
CLEAN_OLDER_THAN: "6 minutes"
CLEAN_EVERY: "60"
volumes:
- ./cleaner.sh:/usr/local/bin/cleaner.sh:ro
depends_on:
postgres:
condition: service_healthy
networks:
- delamain_network
restart: unless-stopped
volumes:
postgres_data:
daemon_sock:
networks:
delamain_network:
driver: bridge
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Loaded 100 of 1222 files, more files were not shown because too many files have changed in this diff. Show more