서버에서 바로 빌드하고 고칠 수 있게 저장소 줄바꿈을 LF로 맞췄습니다. CRLF로 들어가 있던 sh 빌드 스크립트도 이제 리눅스에서 그대로 돌아갑니다. 내용은 바뀌지 않았습니다.
279 lines
18 KiB
Python
279 lines
18 KiB
Python
"""Private member vault; SQLite transactions enforce ownership and capacity."""
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import re
|
|
import secrets
|
|
import shutil
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
|
|
SIZE = 16777216
|
|
COOKIE = 'tama_member'
|
|
|
|
|
|
class Members:
|
|
def __init__(self, data, config, password_hash, password_ok, detect, names, now):
|
|
self.data, self.config = data, config
|
|
self.hash_password, self.check_password = password_hash, password_ok
|
|
self.detect, self.names, self.now = detect, names, now
|
|
self.attempts, self.lock = {}, threading.RLock()
|
|
self.path = data / 'members.sqlite3'
|
|
with self.db() as db:
|
|
db.execute('PRAGMA journal_mode=WAL')
|
|
db.executescript('''
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id TEXT PRIMARY KEY, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL,
|
|
recovery TEXT NOT NULL, created TEXT NOT NULL, slots INTEGER NOT NULL DEFAULT 10,
|
|
disabled INTEGER NOT NULL DEFAULT 0);
|
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
token TEXT PRIMARY KEY, user TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
expires REAL NOT NULL);
|
|
CREATE TABLE IF NOT EXISTS files (
|
|
id TEXT PRIMARY KEY, user TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
sha TEXT NOT NULL, label TEXT NOT NULL, edition INTEGER NOT NULL,
|
|
created TEXT NOT NULL, size INTEGER NOT NULL, data BLOB NOT NULL,
|
|
UNIQUE(user,sha));
|
|
CREATE INDEX IF NOT EXISTS files_user ON files(user);
|
|
CREATE INDEX IF NOT EXISTS sessions_user ON sessions(user);
|
|
CREATE TABLE IF NOT EXISTS settings (id INTEGER PRIMARY KEY, enabled INTEGER NOT NULL, total_mb INTEGER NOT NULL);
|
|
INSERT OR IGNORE INTO settings VALUES(1,1,5120);
|
|
''')
|
|
|
|
@contextmanager
|
|
def db(self):
|
|
db = sqlite3.connect(self.path, timeout=30)
|
|
db.row_factory = sqlite3.Row
|
|
db.execute('PRAGMA foreign_keys=ON')
|
|
try:
|
|
with db:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
def token(self, handler):
|
|
found = re.search(r'(?:^|;\s*)tama_member=([a-f0-9]{64})(?:;|$)', handler.headers.get('Cookie', ''))
|
|
return hashlib.sha256(found[1].encode()).hexdigest() if found else ''
|
|
|
|
def user(self, handler):
|
|
with self.db() as db:
|
|
return db.execute('SELECT u.* FROM users u JOIN sessions s ON s.user=u.id WHERE s.token=? AND s.expires>? AND u.disabled=0', (self.token(handler), time.time())).fetchone()
|
|
|
|
def session(self, handler, user, extra=None):
|
|
token = secrets.token_hex(32)
|
|
with self.db() as db:
|
|
name = db.execute('SELECT username FROM users WHERE id=?', (user,)).fetchone()['username']
|
|
lifetime = 28800 if name == self.config()['username'].lower() else 604800
|
|
db.execute('DELETE FROM sessions WHERE expires<?', (time.time(),))
|
|
db.execute('INSERT INTO sessions VALUES(?,?,?)', (hashlib.sha256(token.encode()).hexdigest(), user, time.time() + lifetime))
|
|
handler.clear_admin_session()
|
|
handler.reply(200, dict(ok=True, **(extra or {})), headers={'Set-Cookie': [f'{COOKIE}={token}; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age={lifetime}', 'tama_admin=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0']})
|
|
|
|
def rate(self, handler, action, limit=None):
|
|
ip = handler.headers.get('X-Real-IP', handler.client_address[0])
|
|
key = (ip, action)
|
|
with self.lock:
|
|
for k in list(self.attempts):
|
|
self.attempts[k] = [t for t in self.attempts[k] if t > time.time() - 900]
|
|
if not self.attempts[k]:
|
|
del self.attempts[k]
|
|
attempts = self.attempts.setdefault(key, [])
|
|
if len(attempts) >= (limit or (5 if action == 'register' else 12)) or len(self.attempts) > 10000:
|
|
handler.reply(429, {'error': '시도가 많습니다. 15분 뒤 다시 시도하세요.'})
|
|
return False
|
|
attempts.append(time.time())
|
|
return True
|
|
|
|
@staticmethod
|
|
def password(value):
|
|
if not isinstance(value, str) or not 10 <= len(value) <= 128:
|
|
raise ValueError('비밀번호는 10~128자로 입력하세요.')
|
|
return value
|
|
|
|
@staticmethod
|
|
def username(value):
|
|
if not isinstance(value, str) or not re.fullmatch(r'[a-zA-Z0-9_]{4,24}', value):
|
|
raise ValueError('아이디는 영문·숫자·밑줄 4~24자로 입력하세요.')
|
|
return value.lower()
|
|
|
|
def info(self, db, user):
|
|
used = db.execute('SELECT COUNT(*) n, COALESCE(SUM(size),0) size FROM files WHERE user=?', (user['id'],)).fetchone()
|
|
rows = db.execute('SELECT id,sha,label,edition,created,size FROM files WHERE user=? ORDER BY created DESC', (user['id'],)).fetchall()
|
|
return {'authenticated': True, 'username': user['username'], 'isAdmin': user['username'] == self.config()['username'].lower(), 'usedBytes': used['size'], 'count': used['n'], 'maxFiles': user['slots'], 'quotaBytes': user['slots'] * SIZE, 'items': [self.file_info(r) for r in rows]}
|
|
|
|
def file_info(self, row):
|
|
return {'id': row['id'], 'sha256': row['sha'], 'label': row['label'], 'edition': row['edition'], 'name': self.names.get(row['edition'], '기종 미확인'), 'slug': 'personal', 'createdAt': row['created'], 'size': row['size'], 'fileUrl': '/api/member/file/' + row['id'], 'private': True}
|
|
|
|
def get(self, h, path):
|
|
if path == '/api/admin/members':
|
|
if not h.authorized():
|
|
h.reply(401, {'error': '관리자 로그인이 필요합니다.'}); return
|
|
with self.db() as db:
|
|
settings = dict(db.execute('SELECT enabled,total_mb FROM settings WHERE id=1').fetchone())
|
|
rows = db.execute('SELECT u.id,u.username,u.created,u.slots,u.disabled,COUNT(f.id) count,COALESCE(SUM(f.size),0) usedBytes FROM users u LEFT JOIN files f ON f.user=u.id GROUP BY u.id ORDER BY u.created DESC').fetchall()
|
|
h.reply(200, {'items': [dict(r) for r in rows], 'settings': settings}); return
|
|
user = self.user(h)
|
|
if path == '/api/member/me':
|
|
if not user:
|
|
h.reply(200, {'authenticated': False}); return
|
|
with self.db() as db:
|
|
result = self.info(db, user)
|
|
h.reply(200, result); return
|
|
if not user:
|
|
h.reply(401, {'error': '회원 로그인이 필요합니다.'}); return
|
|
if path == '/api/member/six.js':
|
|
code = (Path(__file__).parent / 'generated/six.js').read_bytes()
|
|
h.reply(200, code, 'application/javascript; charset=utf-8'); return
|
|
match = re.fullmatch(r'/api/member/file/([a-f0-9]{32})', path)
|
|
if match:
|
|
with self.db() as db:
|
|
row = db.execute('SELECT data,sha FROM files WHERE id=? AND user=?', (match[1], user['id'])).fetchone()
|
|
if not row:
|
|
h.reply(404, {'error': '내 보관함에서 파일을 찾지 못했습니다.'}); return
|
|
h.reply(200, row['data'], 'application/octet-stream', {'Content-Disposition': 'attachment; filename="paradise-personal-' + row['sha'][:12] + '.bin"'}); return
|
|
h.reply(404, {'error': '페이지가 없습니다.'})
|
|
|
|
def post(self, h, path, admin_only=False):
|
|
public = path in ['/api/member/register', '/api/member/login', '/api/member/recover']
|
|
admin = path.startswith('/api/admin/')
|
|
user = self.user(h)
|
|
if (admin and not h.authorized()) or (not admin and not public and not user and path != '/api/member/logout'):
|
|
h.close_connection = True
|
|
h.reply(401, {'error': '로그인이 필요합니다.'}); return
|
|
if path == '/api/member/files':
|
|
if h.headers.get('Content-Type') != 'application/octet-stream':
|
|
raise ValueError('ROM 파일 전송 형식이 잘못되었습니다.')
|
|
data = h.body(SIZE)
|
|
if len(data) != SIZE or data[:8] != b'SONIXDEV':
|
|
raise ValueError('16 MiB 파라다이스 덤프 파일을 선택하세요.')
|
|
try:
|
|
edition = self.detect(data)
|
|
except ValueError:
|
|
edition = 0
|
|
sha = hashlib.sha256(data).hexdigest()
|
|
with self.db() as db:
|
|
db.execute('BEGIN IMMEDIATE')
|
|
# Recheck account and quota inside the same transaction as the insertion.
|
|
current = db.execute('SELECT * FROM users WHERE id=? AND disabled=0', (user['id'],)).fetchone()
|
|
if not current:
|
|
raise ValueError('사용할 수 없는 계정입니다.')
|
|
old = db.execute('SELECT id FROM files WHERE user=? AND sha=?', (user['id'], sha)).fetchone()
|
|
if old:
|
|
h.reply(200, {'status': 'duplicate', 'sha256': sha, 'id': old['id']}); return
|
|
usage = db.execute('SELECT COUNT(*) n,COALESCE(SUM(size),0) size FROM files WHERE user=?', (user['id'],)).fetchone()
|
|
if usage['n'] >= current['slots'] or usage['size'] + len(data) > current['slots'] * SIZE:
|
|
raise ValueError('개인 보관함이 가득 찼습니다. 기존 파일을 삭제한 뒤 다시 저장하세요.')
|
|
cap = db.execute('SELECT total_mb FROM settings WHERE id=1').fetchone()[0] * 1048576
|
|
total = db.execute('SELECT COALESCE(SUM(size),0) FROM files').fetchone()[0]
|
|
if total + len(data) > cap or shutil.disk_usage(self.data).free < len(data) * 4 + 2 * 1024 ** 3:
|
|
raise ValueError('서버 보관 공간이 부족합니다. PC 파일을 보관하세요.')
|
|
file_id = secrets.token_hex(16)
|
|
label = self.names.get(edition, '기종 미확인') + ' · ' + self.now()[:19].replace('T', ' ')
|
|
db.execute('INSERT INTO files VALUES(?,?,?,?,?,?,?,?)', (file_id, user['id'], sha, label, edition, self.now(), len(data), data))
|
|
h.reply(200, {'status': 'stored', 'sha256': sha, 'id': file_id}); return
|
|
if h.headers.get('Content-Type', '').split(';')[0] != 'application/json':
|
|
raise ValueError('JSON 요청이 필요합니다.')
|
|
body = json.loads(h.body(4096))
|
|
if not isinstance(body, dict):
|
|
raise ValueError('요청 형식이 잘못되었습니다.')
|
|
if public:
|
|
action = path.rsplit('/', 1)[1]
|
|
if not self.rate(h, action, 8 if admin_only else None): return
|
|
cfg = self.config()
|
|
supplied_name = body.get('username')
|
|
normalized = supplied_name.strip().lower() if isinstance(supplied_name, str) else ''
|
|
is_admin = normalized == cfg['username'].lower()
|
|
username = normalized if is_admin else self.username(normalized)
|
|
if action == 'register':
|
|
password = self.password(body.get('password'))
|
|
if is_admin: raise ValueError('예약된 관리자 아이디입니다.')
|
|
password_hash = self.hash_password(password)
|
|
recovery = secrets.token_urlsafe(24)
|
|
user_id = secrets.token_hex(16)
|
|
with self.db() as db:
|
|
db.execute('BEGIN IMMEDIATE')
|
|
if not db.execute('SELECT enabled FROM settings WHERE id=1').fetchone()[0]:
|
|
raise ValueError('현재 회원가입을 받지 않습니다.')
|
|
if db.execute('SELECT COUNT(*) FROM users').fetchone()[0] >= 1000:
|
|
raise ValueError('회원가입 한도에 도달했습니다. 관리자에게 문의하세요.')
|
|
if db.execute('SELECT 1 FROM users WHERE username=?', (username,)).fetchone():
|
|
raise ValueError('이미 사용 중인 아이디입니다.')
|
|
db.execute('INSERT INTO users(id,username,password,recovery,created) VALUES(?,?,?,?,?)', (user_id, username, password_hash, hashlib.sha256(recovery.encode()).hexdigest(), self.now()))
|
|
self.session(h, user_id, {'recoveryCode': recovery}); return
|
|
with self.db() as db:
|
|
record = db.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone()
|
|
if action == 'login':
|
|
supplied = body.get('password', '')
|
|
if not isinstance(supplied, str) or len(supplied) > 128:
|
|
raise ValueError('아이디 또는 비밀번호가 다릅니다.')
|
|
stored = cfg['passwordHash'] if is_admin else record['password'] if record else cfg['passwordHash']
|
|
valid = self.check_password(supplied, stored)
|
|
if not valid or (admin_only and not is_admin) or (not is_admin and not record) or (record and record['disabled']):
|
|
h.reply(401, {'error': '아이디 또는 비밀번호가 다르거나 사용할 수 없는 계정입니다.'}); return
|
|
if is_admin and not record:
|
|
with self.db() as db:
|
|
db.execute('INSERT OR IGNORE INTO users(id,username,password,recovery,created) VALUES(?,?,?,?,?)', (secrets.token_hex(16), username, '', '', self.now()))
|
|
record = db.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone()
|
|
with self.lock:
|
|
self.attempts.pop((h.headers.get('X-Real-IP', h.client_address[0]), 'login'), None)
|
|
self.session(h, record['id']); return
|
|
password = self.password(body.get('newPassword'))
|
|
code = body.get('recoveryCode', '')
|
|
if not isinstance(code, str) or len(code) > 128 or not record or is_admin or record['disabled'] or not hmac.compare_digest(hashlib.sha256(code.encode()).hexdigest(), record['recovery']):
|
|
raise ValueError('아이디 또는 복구 코드가 다릅니다.')
|
|
recovery = secrets.token_urlsafe(24)
|
|
with self.db() as db:
|
|
db.execute('BEGIN IMMEDIATE')
|
|
fresh = db.execute('SELECT recovery,disabled FROM users WHERE id=?', (record['id'],)).fetchone()
|
|
if fresh['disabled'] or fresh['recovery'] != record['recovery']:
|
|
raise ValueError('이미 사용했거나 만료된 복구 코드입니다.')
|
|
db.execute('UPDATE users SET password=?,recovery=? WHERE id=?', (self.hash_password(password), hashlib.sha256(recovery.encode()).hexdigest(), record['id']))
|
|
db.execute('DELETE FROM sessions WHERE user=?', (record['id'],))
|
|
self.session(h, record['id'], {'recoveryCode': recovery}); return
|
|
if path == '/api/member/logout':
|
|
with self.db() as db: db.execute('DELETE FROM sessions WHERE token=?', (self.token(h),))
|
|
h.clear_admin_session()
|
|
h.reply(200, {'ok': True}, headers={'Set-Cookie': [name + '=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0' for name in [COOKIE, 'tama_admin']]}); return
|
|
if path == '/api/member/file':
|
|
with self.db() as db:
|
|
if body.get('action') == 'delete':
|
|
cur = db.execute('DELETE FROM files WHERE id=? AND user=?', (body.get('id'), user['id']))
|
|
else:
|
|
label = body.get('label', '')
|
|
if not isinstance(label, str) or not 1 <= len(label.strip()) <= 100: raise ValueError('파일 이름은 1~100자로 입력하세요.')
|
|
cur = db.execute('UPDATE files SET label=? WHERE id=? AND user=?', (label.strip(), body.get('id'), user['id']))
|
|
if not cur.rowcount:
|
|
h.reply(404, {'error': '내 보관함에서 파일을 찾지 못했습니다.'}); return
|
|
h.reply(200, {'ok': True}); return
|
|
if path in ['/api/member/password', '/api/member/delete-account']:
|
|
if user['username'] == self.config()['username'].lower():
|
|
raise ValueError('관리자 계정은 관리자 페이지에서 비밀번호를 관리하세요.')
|
|
if not self.check_password(str(body.get('currentPassword', '')), user['password']):
|
|
raise ValueError('현재 비밀번호가 다릅니다.')
|
|
with self.db() as db:
|
|
if path.endswith('delete-account'):
|
|
db.execute('DELETE FROM users WHERE id=?', (user['id'],))
|
|
else:
|
|
db.execute('UPDATE users SET password=? WHERE id=?', (self.hash_password(self.password(body.get('newPassword'))), user['id']))
|
|
db.execute('DELETE FROM sessions WHERE user=?', (user['id'],))
|
|
h.reply(200, {'ok': True}, headers={'Set-Cookie': COOKIE + '=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0'}); return
|
|
if path == '/api/admin/members':
|
|
with self.db() as db:
|
|
if body.get('action') == 'settings':
|
|
total = body.get('totalMB')
|
|
if type(body.get('enabled')) is not bool or type(total) is not int or not 160 <= total <= 20480: raise ValueError('회원 보관함 전체 한도는 160~20480 MiB입니다.')
|
|
db.execute('UPDATE settings SET enabled=?,total_mb=? WHERE id=1', (int(body['enabled']), total))
|
|
else:
|
|
slots, disabled = body.get('slots'), body.get('disabled')
|
|
if type(slots) is not int or not 1 <= slots <= 100 or type(disabled) is not bool: raise ValueError('저장 개수는 1~100개로 입력하세요.')
|
|
row = db.execute('SELECT * FROM users WHERE id=?', (body.get('id'),)).fetchone()
|
|
if not row: raise ValueError('회원을 찾지 못했습니다.')
|
|
if row['username'] == self.config()['username'].lower() and disabled: raise ValueError('관리자 계정은 정지할 수 없습니다.')
|
|
db.execute('UPDATE users SET slots=?,disabled=? WHERE id=?', (slots, int(disabled), row['id']))
|
|
if disabled: db.execute('DELETE FROM sessions WHERE user=?', (row['id'],))
|
|
h.reply(200, {'ok': True}); return
|
|
h.reply(404, {'error': '요청 경로가 없습니다.'})
|