Fresh production baseline [skip ci]

This commit is contained in:
DuneRealms 2026-11-27 23:43:05 +00:00
commit 0a11a18274
11 changed files with 229644 additions and 0 deletions

View file

@ -0,0 +1,17 @@
# DuneRealms server controls
The separate server-operations page is https://cp.dunerealms.com/servers, linked from account Administration. It preserves the account panel at the root. It manages the three existing systemd services: Arrakis, the Vaerkring lobby and the Velocity gateway. It does not create or reset worlds.
Capabilities: status, player counts, service memory, recent journal output, start/stop/restart, and one-line console commands for the two Paper servers. Proxy console input is deliberately unavailable because that service has no console FIFO. Actions are asynchronous and their outcome appears in status. Console command acceptance means delivery to the server; inspect logs for command success.
Access requires the current website session, staff role and an explicit username in private `SERVER_CONTROL_OPERATORS`. Registration/staff membership alone cannot gain server control. Mutations require the exact CP Origin. The backend replaces any supplied actor with the signed-in username and audits action type/target before dispatch; command text and credentials are not written into account audit rows.
`agent.py` is a standard-library Python service on game-host loopback port 25573. It accepts a separate 64-character bearer from `/etc/dunerealms-server-control.secret`. Only fixed units and fixed FIFO paths are available; no shell command execution or arbitrary file paths. FIFO writes use non-blocking, no-follow opens and validate the descriptor type. Each server accepts one operation at a time with a cooldown. Journal credential patterns are redacted.
The existing SSH tunnel now also forwards website-loopback 15433 to game-loopback 25573. Its restricted account key permits only PostgreSQL 5432 and control 25573 destinations. Agent port 25573 is not public. Website private settings: `SERVER_CONTROL_TOKEN` and `SERVER_CONTROL_OPERATORS`. No credentials belong in this directory.
Agent systemd service: `dunerealms-server-control`; existing tunnel: `dunerealms-inventory-tunnel`. The agent needs system service control and console FIFO access, and runs under a read-only filesystem sandbox with private temporary files. Deploy agent changes to `/opt/dunerealms/server-control/agent.py` and restart its service. Tests: `python3 -m unittest discover -s network/server-control -p test_agent.py` and the website test suite.
Live deployment 28 October 2026: website release `20261028-server-panel`, 60 website tests and 4 Python agent tests passed. Authenticated status, logs, a harmless `list` command and an idempotent `start` of the active Arrakis service passed through the public HTTPS API. Foreign-origin writes returned 403; unauthenticated controls returned 401. Browser review confirmed the operator interface. No real restart was required for the panel acceptance test.
The normal account dashboard also embeds these controls under a Servers navigation tab. The embedded view uses the same session and operator checks, hides duplicate site chrome, and reports only its layout height to its same-origin parent. The CP framing policy explicitly permits itself and the main website; other origins remain blocked.

View file

@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Private server control. Bind loopback; reach only through the restricted SSH tunnel."""
import hmac
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.request import urlopen
from urllib.parse import urlsplit, parse_qs
SERVERS = {
'arrakis': ('dune-arrakis', '/opt/dunerealms/servers/arrakis/console.fifo', 'Arrakduin'),
'lobby': ('dune-lobby', '/opt/dunerealms/lobby/console.fifo', 'Vaerkring lobby'),
'proxy': ('dune-proxy', None, 'Network gateway'),
}
LOCK = threading.Lock()
JOBS = {}
LAST = {}
SECRET = None
def run(args, timeout=8):
return subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False)
def scrub(text):
return re.sub(r'(?i)((?:password|secret|token)\s*[=:]\s*)\S+', r'\1[redacted]', text)[-60000:]
def state():
rows = []
for key, (unit, fifo, name) in SERVERS.items():
result = run(['systemctl', 'show', unit, '--property=ActiveState,SubState,MemoryCurrent,ActiveEnterTimestamp'])
values = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
with LOCK:
job = dict(JOBS[key]) if key in JOBS else None
rows.append({'id': key, 'name': name, 'state': values.get('ActiveState', 'unknown'),
'detail': values.get('SubState', ''), 'memory': values.get('MemoryCurrent'),
'since': values.get('ActiveEnterTimestamp'), 'console': bool(fifo), 'job': job})
try:
with urlopen('http://127.0.0.1:25572/status', timeout=3) as response:
network = json.load(response)
except Exception:
network = None
return {'servers': rows, 'network': network, 'checkedAt': int(time.time() * 1000)}
def perform(server, action, command, actor):
unit, fifo, _ = SERVERS[server]
print(json.dumps({'actor': actor, 'server': server, 'action': action, 'event': 'started'}), flush=True)
try:
if action == 'command':
fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
try:
if not stat.S_ISFIFO(os.fstat(fd).st_mode):
raise ValueError('Console is not a pipe')
os.write(fd, (command + '\n').encode())
finally:
os.close(fd)
message = 'Command sent. Check the console log for its result.'
else:
result = run(['systemctl', action, unit], timeout=140)
if result.returncode:
raise RuntimeError('Service action failed; check the server log.')
message = 'Service action completed.'
outcome = {'state': 'complete', 'message': message}
except Exception:
outcome = {'state': 'failed', 'message': 'Action failed. Check the server log or retry after startup.'}
with LOCK:
JOBS[server].update(outcome)
print(json.dumps({'actor': actor, 'server': server, 'action': action, **outcome}), flush=True)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def reply(self, status, body):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Cache-Control', 'no-store')
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
def authorized(self):
received = self.headers.get('Authorization', '')
return hmac.compare_digest(received.encode(), ('Bearer ' + SECRET).encode())
def do_GET(self):
if not self.authorized():
return self.reply(401, {'message': 'Unauthorized'})
url = urlsplit(self.path)
if url.path == '/servers' and not url.query:
return self.reply(200, state())
args = parse_qs(url.query)
if url.path == '/logs' and set(args) == {'server'} and len(args['server']) == 1 and args['server'][0] in SERVERS:
unit = SERVERS[args['server'][0]][0]
result = run(['journalctl', '-u', unit, '-n', '160', '--no-pager', '-o', 'cat'])
return self.reply(200, {'log': scrub(result.stdout)})
return self.reply(404, {'message': 'Not found'})
def do_POST(self):
if not self.authorized():
return self.reply(401, {'message': 'Unauthorized'})
if self.path != '/action':
return self.reply(404, {'message': 'Not found'})
try:
length = int(self.headers.get('Content-Length', '0'))
if not 0 < length <= 4096:
raise ValueError()
data = json.loads(self.rfile.read(length))
server, action = data['server'], data['action']
if server not in SERVERS or action not in ('start', 'stop', 'restart', 'command'):
raise ValueError()
command = data.get('command', '')
actor = data['actor']
if not isinstance(actor, str) or not re.fullmatch(r'[A-Za-z0-9_]{3,32}', actor):
raise ValueError()
if action == 'command' and (not SERVERS[server][1] or not isinstance(command, str) or not re.fullmatch(r'[A-Za-z][ -~]{0,239}', command)):
raise ValueError()
except (ValueError, KeyError, TypeError):
return self.reply(400, {'message': 'Invalid server action'})
with LOCK:
if JOBS.get(server, {}).get('state') == 'running' or time.monotonic() - LAST.get(server, -100) < 5:
return self.reply(409, {'message': 'A server action is already running. Wait a moment.'})
LAST[server] = time.monotonic()
JOBS[server] = {'state': 'running', 'action': action, 'startedAt': int(time.time() * 1000)}
threading.Thread(target=perform, args=(server, action, command, actor), daemon=True).start()
return self.reply(202, {'ok': True, 'message': 'Action accepted. Status will update shortly.'})
if __name__ == '__main__':
SECRET = Path('/etc/dunerealms-server-control.secret').read_text().strip()
if len(SECRET) < 64:
raise SystemExit('Private control secret is missing')
ThreadingHTTPServer(('127.0.0.1', 25573), Handler).serve_forever()

View file

@ -0,0 +1,79 @@
"""Install only the reviewed kit bridge modules; refuse unrelated source changes."""
import ast
import hashlib
import os
from pathlib import Path
import py_compile
import sys
BASELINES = {
'player_kits.py': 'fa76420423941189ba08b94382274e40762121e30b008ec0d08e35aa1a00fda3',
'kit_commerce.py': '29395a483fdb3f6d94b36fa57587e3a1391d6e4ed8a44159cbb488dd47d960e6',
}
FILES = ['player_kits.py', 'kit_commerce.py', 'kit_equipment.py', 'kit-equipment-contract.json']
def kit_body_limit(source):
tree = ast.parse(source)
candidates = [node for node in tree.body if isinstance(node, ast.FunctionDef)
and any(isinstance(value, ast.Constant) and value.value == '/kits/player/definition' for value in ast.walk(node))]
if len(candidates) != 1:
raise RuntimeError('Native office kit handler changed')
node = candidates[0]
lines = source.splitlines(keepends=True)
section = ''.join(lines[node.lineno - 1:node.end_lineno])
old, new = 'if not 0 < length <= 8192:', 'if not 0 < length <= 32768:'
if section.count(new) == 1 and old not in section:
return source
if section.count(old) != 1:
raise RuntimeError('Native office body limit changed')
lines[node.lineno - 1:node.end_lineno] = [section.replace(old, new)]
return ''.join(lines)
def install(apply=False):
source = Path(__file__).resolve().parent
target = Path('/opt/dunerealms/server-control')
plans = {}
for name in FILES:
content = (source / name).read_bytes()
destination = target / name
before = destination.read_bytes() if destination.exists() else None
if before == content:
continue
if before is not None and hashlib.sha256(before).hexdigest() != BASELINES.get(name):
raise RuntimeError('Concurrent native change detected in ' + name)
plans[destination] = content
agent = target / 'agent.py'
before = agent.read_text()
after = kit_body_limit(before)
if after != before:
plans[agent] = after.encode()
for name in ['player_kits.py', 'kit_commerce.py', 'kit_equipment.py']:
py_compile.compile(str(source / name), doraise=True)
if not apply:
print('Plan: install', len(plans), 'exact kit module/body-limit changes; no files changed')
return
originals = {path: path.read_bytes() if path.exists() else None for path in plans}
changed = []
try:
for path, content in plans.items():
temporary = path.with_name(path.name + '.kit-v3-new')
temporary.write_bytes(content)
temporary.chmod(path.stat().st_mode & 0o777 if path.exists() else 0o644)
if path.suffix == '.py':
py_compile.compile(str(temporary), doraise=True)
os.replace(temporary, path)
changed.append(path)
except Exception:
for path in reversed(changed):
if originals[path] is None:
path.unlink()
else:
path.write_bytes(originals[path])
raise
print('Installed reviewed kit metadata modules; restart the private control service to activate')
if __name__ == '__main__':
install('--apply' in sys.argv)

View file

@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS dune_kit_deliveries (
id UUID PRIMARY KEY,
buyer_uuid UUID NOT NULL,
snapshot_json TEXT NOT NULL CHECK (octet_length(snapshot_json) <= 65536),
snapshot_hash CHAR(64) NOT NULL CHECK (snapshot_hash ~ '^[a-f0-9]{64}$'),
created_at BIGINT NOT NULL CHECK (created_at > 0),
delivered_at BIGINT NULL CHECK (delivered_at IS NULL OR delivered_at > 0)
);
CREATE INDEX IF NOT EXISTS dune_kit_deliveries_pending ON dune_kit_deliveries(buyer_uuid,created_at,id) WHERE delivered_at IS NULL;

View file

@ -0,0 +1,104 @@
{
"version": 3,
"slots": [
"helmet",
"chestplate",
"leggings",
"boots"
],
"trimPatterns": [
"sentry",
"dune",
"coast",
"wild",
"ward",
"eye",
"vex",
"tide",
"snout",
"rib",
"spire",
"wayfinder",
"shaper",
"silence",
"raiser",
"host",
"flow",
"bolt"
],
"trimMaterials": [
"quartz",
"iron",
"netherite",
"redstone",
"copper",
"gold",
"emerald",
"diamond",
"lapis",
"amethyst",
"resin"
],
"bannerColors": [
"white",
"orange",
"magenta",
"light_blue",
"yellow",
"lime",
"pink",
"gray",
"light_gray",
"cyan",
"purple",
"blue",
"brown",
"green",
"red",
"black"
],
"bannerPatterns": [
"square_bottom_left",
"square_bottom_right",
"square_top_left",
"square_top_right",
"stripe_bottom",
"stripe_top",
"stripe_left",
"stripe_right",
"stripe_center",
"stripe_middle",
"stripe_downright",
"stripe_downleft",
"small_stripes",
"cross",
"straight_cross",
"triangle_bottom",
"triangle_top",
"triangles_bottom",
"triangles_top",
"diagonal_left",
"diagonal_up_right",
"diagonal_up_left",
"diagonal_right",
"circle",
"rhombus",
"half_vertical",
"half_horizontal",
"half_vertical_right",
"half_horizontal_bottom",
"border",
"curly_border",
"gradient",
"gradient_up",
"bricks",
"globe",
"creeper",
"skull",
"flower",
"mojang",
"piglin",
"flow",
"guster"
]
}

View file

@ -0,0 +1,968 @@
{
"valid": {
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
"normalized": {
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#BCA05B",
"bold": true,
"italic": false
}
]
}
},
"invalid": [
{
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "Text",
"color": "#AAAAAA",
"bold": false,
"italic": false,
"clickEvent": {
"action": "run_command",
"value": "/op"
}
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
{
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
{
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
},
{
"pattern": "invalid",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
{
"version": 3,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "command_block"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
},
{
"version": true,
"armor": {
"helmet": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"chestplate": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"leggings": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
},
"boots": {
"material": "netherite",
"name": "",
"lore": [
{
"text": "First line",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "",
"color": "#AAAAAA",
"bold": false,
"italic": false
},
{
"text": "Last line",
"color": "#AAAAAA",
"bold": false,
"italic": false
}
],
"trim": {
"pattern": "dune",
"material": "gold"
}
}
},
"banner": {
"enabled": true,
"name": "Imperial Standard",
"base": "purple",
"patterns": [
{
"pattern": "border",
"color": "yellow"
},
{
"pattern": "rhombus",
"color": "red"
}
],
"lore": [
{
"text": "Duty endures.",
"color": "#bca05b",
"bold": true,
"italic": false
}
]
}
}
]
}

View file

@ -0,0 +1,553 @@
"""Private Dunemarks kit commerce; paid orders become bound, one-use deliveries."""
import base64
import hashlib
import hmac
import json
from pathlib import Path
from functools import lru_cache
from decimal import Decimal
from player_bank import identity
from kit_equipment import validate_equipment, validate_upgrade
TIERS = ('common', 'uncommon', 'rare', 'very_rare', 'legendary')
KINDS = ('personal_sale', 'official_sale', 'faction_sale', 'server_sale')
FACTIONS = {'fremen': 'Fremen', 'atreides': 'Atreides', 'harkonnen': 'Harkonnen', 'corrino': 'Corrino', 'ordos': 'Ordos'}
MINIMUM_CENTS = (10000, 20000, 40000, 80000, 160000)
TARGETS = (3, 5, 10, 15, 25)
REWARDS_CENTS = (1000, 2500, 5000, 10000, 20000)
TITLES = ('A Stitch in the Sand', 'Colours of the Caravan', "The Caravan’s Trust", 'Patterns of Influence', 'A Legacy in Gold')
@lru_cache(maxsize=1)
def arc_definition():
path=Path(__file__).with_name('kit-quest-arc-v1.json')
if not path.is_file():
path=Path(__file__).resolve().parents[2]/'website'/'content'/'kit-quest-arc-v1.json'
data=json.loads(path.read_text(encoding='utf-8'))
if len(data.get('chapters',[]))!=5:raise RuntimeError('Invalid canonical quest arc')
for i,row in enumerate(data['chapters']):
if (row['index'],row['quality'],row['targetSales'],row['minimumPriceDunemarks']*100,row['rewardDunemarks']*100)!=(i,TIERS[i],TARGETS[i],MINIMUM_CENTS[i],REWARDS_CENTS[i]):
raise RuntimeError('Quest economy differs from the canonical arc')
return data
class Conflict(Exception):
pass
class InsufficientFunds(Exception):
pass
def allocation_cents(gross, kind='personal_sale'):
if type(gross) is not int or not 1 <= gross <= 100000000:
raise ValueError('Invalid kit price')
if kind not in KINDS:
raise ValueError('Invalid kit commerce kind')
faction = gross * 25 // 100 if kind == 'faction_sale' else 0
server = gross if kind == 'server_sale' else gross * (15 if kind == 'faction_sale' else 20 if kind == 'official_sale' else 25) // 100
return faction, server, gross - faction - server
def split_cents(gross, kind='personal_sale'):
faction, server, seller = allocation_cents(gross, kind)
if kind == 'faction_sale':
raise ValueError('Faction sales require the three-way allocation')
return server, seller
def receipt_code(key, line_id):
identity(line_id)
if not isinstance(key, bytes) or len(key) < 32:
raise RuntimeError('Private item-code key unavailable')
digest = hmac.new(key, b'dunerealms-kit-v1:' + line_id.encode('ascii'), hashlib.sha256).digest()[:20]
return 'DRK-' + base64.b32encode(digest).decode('ascii').rstrip('=')
def code_hash(code):
if not isinstance(code, str) or len(code) != 36 or not code.startswith('DRK-') or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' for c in code[4:]):
raise ValueError('Invalid item code')
return hashlib.sha256(code.encode('ascii')).hexdigest()
def initialize(cur):
cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_carts (
id VARCHAR(36) PRIMARY KEY,buyer_uuid VARCHAR(36) NOT NULL,payload_hash CHAR(64) NOT NULL,
lines_json TEXT NOT NULL,paid_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''')
cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_sales (
id VARCHAR(36) PRIMARY KEY,buyer_uuid VARCHAR(36) NOT NULL,seller_uuid VARCHAR(36) NOT NULL,
kit_id VARCHAR(36) NOT NULL,kit_version BIGINT NOT NULL,listing_id VARCHAR(36) NOT NULL,
listing_version BIGINT NOT NULL,rarity VARCHAR(16) NOT NULL,shop_type VARCHAR(8) NOT NULL,
commerce_kind VARCHAR(16) NOT NULL DEFAULT 'personal_sale',
quantity INT NOT NULL,gross_cents BIGINT NOT NULL,server_tax_cents BIGINT NOT NULL,
faction_tax_cents BIGINT NOT NULL DEFAULT 0,seller_net_cents BIGINT NOT NULL,
snapshot_json TEXT NOT NULL,code_hash CHAR(64) NOT NULL UNIQUE,
completed_at BIGINT NOT NULL,redeem_requested_at BIGINT NULL,delivered_at BIGINT NULL,
INDEX dune_kit_sales_progress(seller_uuid,rarity,delivered_at),
INDEX dune_kit_sales_pending(buyer_uuid,redeem_requested_at,delivered_at),
CHECK(quantity=1),CHECK(gross_cents>0),CHECK(server_tax_cents>=0),
CONSTRAINT dune_kit_sales_faction_nonnegative CHECK(faction_tax_cents>=0),CHECK(seller_net_cents>=0),
CONSTRAINT dune_kit_sales_conservation CHECK(gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents),
CONSTRAINT dune_kit_sales_kind CHECK(commerce_kind IN ('personal_sale','official_sale','faction_sale','server_sale'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''')
cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_arc_claims (
player_uuid VARCHAR(36) NOT NULL,stage_index INT NOT NULL,
reward_cents BIGINT NOT NULL,claimed_at BIGINT NOT NULL,
PRIMARY KEY(player_uuid,stage_index),CHECK(stage_index BETWEEN 0 AND 4),CHECK(reward_cents>0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''')
def sales_constraint_migration(cur):
"""Return one atomic MySQL8 ALTER; caller must stop checkout and back up before applying it."""
import re
cur.execute('''SELECT tc.CONSTRAINT_NAME AS name,cc.CHECK_CLAUSE AS clause
FROM information_schema.TABLE_CONSTRAINTS tc
JOIN information_schema.CHECK_CONSTRAINTS cc
ON cc.CONSTRAINT_SCHEMA=tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME=tc.CONSTRAINT_NAME
WHERE tc.TABLE_SCHEMA=DATABASE() AND tc.TABLE_NAME='dune_kit_sales' AND tc.CONSTRAINT_TYPE='CHECK' ''')
checks = cur.fetchall()
def normalize(value):
# MySQL's metadata adds character-set introducers to string CHECK literals.
value = value.replace("\\'", "'")
value = re.sub(r'_(?:utf8mb4|utf8mb3|utf8|ascii|latin1|binary)(?=\')', '', value, flags=re.I)
return re.sub(r'[\s`()]+', '', value).lower()
legacy = {'faction_tax_cents=0', 'gross_cents=server_tax_cents+seller_net_cents'}
desired = {'faction_tax_cents>=0': ('dune_kit_sales_faction_nonnegative', 'faction_tax_cents>=0'),
'gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents':
('dune_kit_sales_conservation', 'gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents'),
"commerce_kindin'personal_sale','official_sale','faction_sale','server_sale'":
('dune_kit_sales_kind', "commerce_kind IN ('personal_sale','official_sale','faction_sale','server_sale')")}
clauses = {normalize(row['clause']) for row in checks}
changes = []
cur.execute("SELECT COUNT(*) AS n FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='dune_kit_sales' AND COLUMN_NAME='commerce_kind'")
count = cur.fetchone()
if not count or type(count['n']) is not int or count['n'] not in (0, 1):
raise RuntimeError('Kit classification schema unavailable')
if count['n'] == 0:
changes.append("ADD COLUMN commerce_kind VARCHAR(16) NOT NULL DEFAULT 'personal_sale' AFTER shop_type")
for row in checks:
if normalize(row['clause']) in legacy:
if not re.fullmatch(r'[A-Za-z0-9_]{1,64}', row['name']):
raise RuntimeError('Unexpected kit constraint identity')
changes.append('DROP CHECK `' + row['name'] + '`')
names = {row['name'] for row in checks if normalize(row['clause']) not in legacy}
for normalized, (name, expression) in desired.items():
if normalized not in clauses:
if name in names:
raise RuntimeError('Conflicting kit constraint identity')
changes.append('ADD CONSTRAINT `' + name + '` CHECK(' + expression + ')')
return 'ALTER TABLE dune_kit_sales ' + ', '.join(changes) if changes else None
def listing_context(cur, buyer, listing):
cur.execute('CALL dune_kit_listing_lock(%s,%s)', (buyer,listing))
rows = cur.fetchall()
while cur.nextset():
pass
if len(rows) != 1:
raise PermissionError('Published kit listing unavailable')
return rows[0]
def listing_snapshot(row):
import re
def plain(value, limit):
if not isinstance(value,str) or not 1 <= len(value.strip()) <= limit or re.search(r'[\x00-\x1f\x7f<>§]',value):
raise ValueError('Invalid kit cosmetic text')
return value.strip()
quality = str(row.get('quality','')).lower()
kind = row.get('commerce_kind')
if quality not in TIERS or kind not in KINDS or row.get('shop_type') not in ('player','clan','official','faction','server'):
raise ValueError('Invalid listing type or quality')
shop_types = {'personal_sale': ('player','clan'), 'official_sale': ('official',), 'faction_sale': ('faction',), 'server_sale': ('server',)}
if row['shop_type'] not in shop_types[kind]:
raise ValueError('The listing category does not match its authoritative commerce kind')
color = row.get('kit_color')
if not isinstance(color,str) or not re.fullmatch(r'#[0-9a-fA-F]{6}',color):
raise ValueError('Invalid kit colour')
lore = json.loads(row.get('kit_lore_json',''))
if not isinstance(lore,list) or len(lore)>6:
raise ValueError('Invalid kit lore')
for field in ('listing_version','blueprint_version','price_cents'):
if type(row.get(field)) is not int or row[field]<1:
raise ValueError('Invalid listing revision or price')
if kind == 'personal_sale' and row['price_cents'] < MINIMUM_CENTS[TIERS.index(quality)]:
raise ValueError('Listing is below the tier minimum')
allocation_cents(row['price_cents'], kind)
seller = identity(row['seller_uuid'])
import uuid
if uuid.UUID(seller).int == 0:
raise ValueError('A real verified designer or publisher is required')
item = {'listingId':identity(row['listing_id']),'listingVersion':row['listing_version'],
'blueprintId':identity(row['blueprint_id']),'blueprintVersion':row['blueprint_version'],
'sellerUuid':seller,'clanId':identity(row['clan_id']) if row.get('clan_id') else None,
'shopType':row['shop_type'],'commerceKind':kind,'quality':quality,
'priceCents':row['price_cents'],'name':plain(row['kit_name'],64),'color':color.upper(),
'lore':[plain(line,120) for line in lore]}
equipment = row.get('kit_equipment_json')
if equipment is not None:
item['equipment'] = validate_equipment(json.loads(equipment) if isinstance(equipment, str) else equipment)
names = row.get('kit_item_names_json')
if names is not None:
names = json.loads(names) if isinstance(names, str) else names
if not isinstance(names, dict) or set(names) - {'helmet', 'chestplate', 'leggings', 'boots'} or any(not isinstance(value, str) or len(value) > 64 or re.search(r'[<>§\x00-\x1f\x7f]', value) for value in names.values()):
raise ValueError('Invalid individual item names')
item['itemNames'] = names
upgrade = row.get('kit_upgrade_json')
if upgrade is not None:
item['upgrade'] = validate_upgrade(json.loads(upgrade) if isinstance(upgrade, str) else upgrade, quality, kind)
override = row.get('seller_tier_override', 0)
if type(override) is not int or override not in (0, 1) or (kind != 'personal_sale' and override != 0):
raise ValueError('Invalid authoritative designer tier override')
item['sellerTierOverride'] = override
if kind in ('official_sale', 'faction_sale'):
office, term = row.get('office_key'), row.get('office_term')
if not isinstance(office, str) or not re.fullmatch(r'emperor|(?:house-leader|water-steward|spice-steward):(Fremen|Atreides|Harkonnen|Corrino|Ordos)', office):
raise ValueError('Canonical elected office required')
if not isinstance(term, str) or not 1 <= len(term) <= 190 or not re.fullmatch(r'[A-Za-z0-9:._-]+',term):
raise ValueError('Canonical elected term required')
item.update(officeKey=office, officeTerm=term)
if kind == 'faction_sale':
faction = row.get('faction_id')
if faction not in FACTIONS or item['officeKey'] != 'house-leader:' + FACTIONS[faction]:
raise ValueError('The owning faction and leader office must match')
item['factionId'] = faction
if kind == 'server_sale' and (type(row.get('server_authorized')) is not int or row['server_authorized'] != 1):
raise PermissionError('Current protected publisher authority required')
return item
def current_listing_authority(cur, item, locking=True, cache=None):
if item['commerceKind'] in ('official_sale', 'faction_sale'):
from player_kits import authority
owner = item['sellerUuid']
if cache is None:
offices = authority(cur, owner, locking=locking)
else:
if owner not in cache:
cache[owner] = authority(cur, owner, locking=locking)
offices = cache[owner]
if offices.get(item['officeKey']) != item['officeTerm']:
raise PermissionError('The listing belongs to an expired elected term')
def credit_sale_bank(cur, kind, owner, amount, actor, stamp, reference):
"""Fixed destinations only. Uses the enclosing checkout transaction and unique sale reference."""
import uuid
if amount == 0:
return
if kind == 'personal':
table, key, ledger = 'dune_player_banks', 'player_uuid', 'dune_player_bank_ledger'
elif kind == 'faction' and owner in FACTIONS:
table, key, ledger = 'dune_faction_bank_wallet', 'faction_id', 'dune_faction_bank_ledger'
else:
raise ValueError('Invalid sale bank destination')
cur.execute('INSERT INTO '+table+'('+key+',balance,updated_at) VALUES(%s,0,%s) ON DUPLICATE KEY UPDATE '+key+'='+key,(owner,stamp))
cur.execute('SELECT balance FROM '+table+' WHERE '+key+'=%s FOR UPDATE',(owner,))
row=cur.fetchone()
if row is None:
raise RuntimeError('Sale bank unavailable')
before=Decimal(row['balance']);after=before+amount
if before<0 or after>Decimal('1000000000000'):
raise ValueError('A sale bank limit was reached')
cur.execute('UPDATE '+table+' SET balance=%s,updated_at=%s WHERE '+key+'=%s',(after,stamp,owner))
if kind == 'personal':
cur.execute('INSERT INTO '+ledger+'(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),owner,'faction-kit-sale',amount,after,stamp,reference))
else:
cur.execute('INSERT INTO '+ledger+'(id,faction_id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),owner,actor,'faction-kit-sale',amount,after,stamp,reference))
def checkout(connect, key, payload, context=listing_context):
fields={'buyerUuid','listingId','orderLineId','listingVersion','blueprintVersion','priceCents'}
if not isinstance(payload,dict) or set(payload)!=fields:
raise ValueError('Invalid checkout fields')
buyer=identity(payload['buyerUuid']);listing=identity(payload['listingId']);line=identity(payload['orderLineId'])
for field in ('listingVersion','blueprintVersion','priceCents'):
if type(payload[field]) is not int or payload[field]<1:
raise ValueError('Review the current listing before purchasing')
code=receipt_code(key,line);digest=code_hash(code)
with connect() as con:
try:
con.begin()
with con.cursor() as cur:
cur.execute('SELECT buyer_uuid,listing_id,listing_version,kit_version,gross_cents,code_hash FROM dune_kit_sales WHERE id=%s FOR UPDATE',(line,))
old=cur.fetchone()
if old:
if (old['buyer_uuid'],old['listing_id'],old['listing_version'],old['kit_version'],old['gross_cents']) != (buyer,listing,payload['listingVersion'],payload['blueprintVersion'],payload['priceCents']):
raise Conflict('Order line already belongs to a different purchase')
if not hmac.compare_digest(old['code_hash'],digest):
raise RuntimeError('Item-code key differs from the original receipt')
con.rollback()
return {'ok':True,'alreadyPaid':True,'orderLineId':line,'code':code,'delivery':'redeem-code'}
authority=context(cur,buyer,listing)
if authority.get('buyer_uuid') != buyer or authority.get('commerce_kind') not in KINDS:
raise PermissionError('Current verified buyer and supported listing required')
item=listing_snapshot(authority)
current_listing_authority(cur,item)
if (item['listingId'],item['listingVersion'],item['blueprintVersion'],item['priceCents']) != (listing,payload['listingVersion'],payload['blueprintVersion'],payload['priceCents']):
raise Conflict('The listing changed; review its current price and design')
seller=item['sellerUuid'];tier=TIERS.index(item['quality'])
kind=item['commerceKind']
if kind == 'personal_sale' and not item['sellerTierOverride'] and tier > len(claimed(cur,seller)):
raise PermissionError('Designer has not unlocked this kit tier')
wallets={}
for player in sorted({buyer,seller} if kind in ('personal_sale','official_sale') else {buyer}):
cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE',(player,))
row=cur.fetchone()
if row is None:
raise PermissionError('Existing buyer and designer Minecraft wallets are required')
wallets[player]=Decimal(row['balance'])
gross=Decimal(item['priceCents'])/100
if wallets[buyer]<gross:
raise InsufficientFunds('Insufficient Dunemarks')
faction_cents,tax_cents,net_cents=allocation_cents(item['priceCents'],kind);tax=Decimal(tax_cents)/100
cur.execute("INSERT INTO dune_staff_bank_wallet(account_key,balance,updated_at) VALUES('network',0,0) ON DUPLICATE KEY UPDATE account_key=account_key")
cur.execute("SELECT balance FROM dune_staff_bank_wallet WHERE account_key='network' FOR UPDATE")
treasury=Decimal(cur.fetchone()['balance'])+tax
wallets[buyer]-=gross
if kind in ('personal_sale','official_sale'):
wallets[seller]+=Decimal(net_cents)/100
if treasury>Decimal('1000000000000') or any(v>Decimal('1000000000000') for v in wallets.values()):
raise ValueError('A wallet or treasury limit was reached')
stamp=now(cur)
if kind == 'faction_sale':
credit_sale_bank(cur,'personal',seller,Decimal(net_cents)/100,buyer,stamp,'kit-sale:'+line)
credit_sale_bank(cur,'faction',item['factionId'],Decimal(faction_cents)/100,buyer,stamp,'kit-sale:'+line)
cur.execute('''INSERT INTO dune_kit_sales(id,buyer_uuid,seller_uuid,kit_id,kit_version,listing_id,listing_version,rarity,shop_type,commerce_kind,quantity,gross_cents,server_tax_cents,faction_tax_cents,seller_net_cents,snapshot_json,code_hash,completed_at)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,1,%s,%s,%s,%s,%s,%s,%s)''',
(line,buyer,seller,item['blueprintId'],item['blueprintVersion'],listing,item['listingVersion'],item['quality'],item['shopType'],kind,item['priceCents'],tax_cents,faction_cents,net_cents,json.dumps(item),digest,stamp))
for player,balance in wallets.items():
cur.execute('UPDATE dune_economy_balances SET balance=%s WHERE uuid=%s',(balance,player))
cur.execute("UPDATE dune_staff_bank_wallet SET balance=%s,updated_at=%s WHERE account_key='network'",(treasury,stamp))
import uuid
cur.execute('INSERT INTO dune_staff_bank_ledger(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),buyer,'kit-sale-tax',tax,treasury,stamp,'kit-sale:'+line))
con.commit()
return {'ok':True,'alreadyPaid':False,'orderLineId':line,'code':code,'delivery':'redeem-code'}
except Exception:
con.rollback();raise
def now(cur):
cur.execute('SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED) AS now')
return int(cur.fetchone()['now'])
def cart_input(payload):
if not isinstance(payload,dict) or set(payload)!={'buyerUuid','cartId','lines'}:
raise ValueError('Invalid cart fields')
buyer=identity(payload['buyerUuid']);cart=identity(payload['cartId'])
if not isinstance(payload['lines'],list) or not 1<=len(payload['lines'])<=20:
raise ValueError('A cart must contain one to twenty kit lines')
lines=[]
for row in payload['lines']:
if not isinstance(row,dict) or set(row)!={'listingId','orderLineId','listingVersion','blueprintVersion','priceCents'}:
raise ValueError('Invalid cart line')
for field in ('listingVersion','blueprintVersion','priceCents'):
if type(row[field]) is not int or row[field]<1:raise ValueError('Invalid cart revision or price')
split_cents(row['priceCents'])
lines.append({**row,'buyerUuid':buyer,'listingId':identity(row['listingId']),'orderLineId':identity(row['orderLineId'])})
if len({row['orderLineId'] for row in lines})!=len(lines):raise ValueError('Duplicate order line')
lines.sort(key=lambda row:row['orderLineId'])
canonical=json.dumps({'buyerUuid':buyer,'cartId':cart,'lines':lines},sort_keys=True,separators=(',',':'))
return buyer,cart,lines,hashlib.sha256(canonical.encode()).hexdigest()
def checkout_cart(connect,key,payload,context=listing_context):
buyer,cart,lines,fingerprint=cart_input(payload)
with connect() as con:
# Reuse the single-line engine inside ONE outer transaction. Inner boundaries cannot commit partial carts.
class SharedTransaction:
def __enter__(self):return self
def __exit__(self,*args):pass
def cursor(self):return con.cursor()
def begin(self):pass
def commit(self):pass
def rollback(self):pass
def shared():return SharedTransaction()
try:
con.begin()
with con.cursor() as cur:
cur.execute('SELECT buyer_uuid,payload_hash FROM dune_kit_carts WHERE id=%s FOR UPDATE',(cart,))
old=cur.fetchone()
if old:
if old['buyer_uuid']!=buyer or not hmac.compare_digest(old['payload_hash'],fingerprint):
raise Conflict('This cart was already paid with different contents')
result=[checkout(shared,key,line,context) for line in lines]
if not all(row['alreadyPaid'] for row in result):
raise RuntimeError('Paid cart has an incomplete order receipt')
con.rollback()
return {'ok':True,'alreadyPaid':True,'cartId':cart,'lines':result,'delivery':'redeem-code'}
for line in lines:
cur.execute('SELECT id FROM dune_kit_sales WHERE id=%s FOR UPDATE',(line['orderLineId'],))
if cur.fetchone():raise Conflict('An order line already belongs to another purchase')
authorities={}
for listing in sorted({line['listingId'] for line in lines}):
row=context(cur,buyer,listing)
if row.get('buyer_uuid')!=buyer or row.get('commerce_kind') not in KINDS:
raise PermissionError('Current verified buyer required')
authorities[listing]=row
sellers=set();total=Decimal(0)
for line in lines:
item=listing_snapshot(authorities[line['listingId']])
current_listing_authority(cur,item)
if (item['listingId'],item['listingVersion'],item['blueprintVersion'],item['priceCents']) != (line['listingId'],line['listingVersion'],line['blueprintVersion'],line['priceCents']):
raise Conflict('A cart listing changed; review the entire cart')
if item['commerceKind']=='personal_sale' and not item['sellerTierOverride'] and TIERS.index(item['quality'])>len(claimed(cur,item['sellerUuid'])):
raise PermissionError('Designer has not unlocked this kit tier')
if item['commerceKind'] in ('personal_sale','official_sale'):
sellers.add(item['sellerUuid'])
total+=Decimal(item['priceCents'])/100
# Lock every participant in a stable global order before any line is charged.
balance=None
for player in sorted(sellers|{buyer}):
cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE',(player,))
row=cur.fetchone()
if not row:raise PermissionError('Existing Minecraft wallets required')
if player==buyer:balance=Decimal(row['balance'])
if balance is None or balance<total:raise InsufficientFunds('Insufficient Dunemarks for the entire cart')
result=[checkout(shared,key,line,lambda cursor,owner,listing:authorities[listing]) for line in lines]
cur.execute('INSERT INTO dune_kit_carts(id,buyer_uuid,payload_hash,lines_json,paid_at) VALUES(%s,%s,%s,%s,%s)',(cart,buyer,fingerprint,json.dumps(lines),now(cur)))
con.commit()
return {'ok':True,'alreadyPaid':False,'cartId':cart,'lines':result,'delivery':'redeem-code'}
except Exception:
con.rollback();raise
def stage(value):
if type(value) is not int or value not in range(5):
raise ValueError('Invalid kit tier')
return value
def claimed(cur, player):
cur.execute('SELECT stage_index FROM dune_kit_arc_claims WHERE player_uuid=%s ORDER BY stage_index', (player,))
stages = [int(row['stage_index']) for row in cur.fetchall()]
if stages != list(range(len(stages))) or len(stages) > 5:
raise RuntimeError('Invalid quest claim sequence')
return stages
def progress(cur, player, index):
# One buyer/tier/UTC delivery day. Quantity, self-sales and unpaid/unredeemed codes cannot inflate progress.
cur.execute('''SELECT COUNT(*) AS n FROM (
SELECT buyer_uuid,FLOOR(delivered_at/86400000) AS utc_day FROM dune_kit_sales
WHERE seller_uuid=%s AND rarity=%s AND buyer_uuid<>seller_uuid AND commerce_kind='personal_sale'
AND delivered_at IS NOT NULL AND quantity=1 AND gross_cents>=%s
GROUP BY buyer_uuid,FLOOR(delivered_at/86400000)
) AS qualifying''', (player, TIERS[index], MINIMUM_CENTS[index]))
return int(cur.fetchone()['n'])
def read_arc(connect, player):
player = identity(player)
definition=arc_definition()
with connect() as con:
with con.cursor() as cur:
done = claimed(cur, player)
chapters = []
for index in range(5):
count = progress(cur, player, index)
story=definition['chapters'][index]
chapters.append({'index': index, 'key': story['key'], 'quality':TIERS[index], 'title': story['title'],
'description':story['description'],'kitTemplate':story['kitTemplate'],'sales': count,
'target': TARGETS[index], 'minimumPriceDunemarks': format(Decimal(MINIMUM_CENTS[index])/100, '.2f'),
'rewardDunemarks': format(Decimal(REWARDS_CENTS[index])/100, '.2f'),
'claimed': index in done, 'unlocked': index <= len(done),
'canClaim': index == len(done) and count >= TARGETS[index]})
return {'playerUuid': player, 'title': 'The Loom of the Desert', 'chapters': chapters,
'rewardSource': 'server-bank', 'salesRule': 'Paid, delivered sales of your own designs; one external buyer per tier per UTC day.'}
def read_orders(connect, key, player):
player=identity(player)
with connect() as con:
with con.cursor() as cur:
cur.execute('''SELECT id,buyer_uuid,seller_uuid,kit_id,rarity,shop_type,commerce_kind,gross_cents,server_tax_cents,faction_tax_cents,seller_net_cents,
snapshot_json,code_hash,completed_at,redeem_requested_at,delivered_at FROM dune_kit_sales
WHERE buyer_uuid=%s OR seller_uuid=%s ORDER BY completed_at DESC,id DESC LIMIT 100''',(player,player))
orders=[]
for row in cur.fetchall():
item=json.loads(row['snapshot_json'])
entry={'orderLineId':row['id'],'side':'purchase' if row['buyer_uuid']==player else 'sale',
'name':item['name'],'quality':row['rarity'],'shopType':row['shop_type'],'commerceKind':row['commerce_kind'],
'grossDunemarks':format(Decimal(row['gross_cents'])/100,'.2f'),
'serverTaxDunemarks':format(Decimal(row['server_tax_cents'])/100,'.2f'),
'factionTaxDunemarks':format(Decimal(row['faction_tax_cents'])/100,'.2f'),
'sellerNetDunemarks':format(Decimal(row['seller_net_cents'])/100,'.2f'),
'sellerPayoutDestination':'personal-bank' if row['commerce_kind']=='faction_sale' else 'none' if row['commerce_kind']=='server_sale' else 'wallet',
'completedAt':row['completed_at'],'deliveredAt':row['delivered_at'],
'status':'delivered' if row['delivered_at'] is not None else 'pending-in-game-delivery' if row['redeem_requested_at'] is not None else 'code-ready'}
if row['buyer_uuid']==player:
code=receipt_code(key,row['id'])
if not hmac.compare_digest(code_hash(code),row['code_hash']):
raise RuntimeError('Item-code key differs from receipt')
entry['code']=code
orders.append(entry)
return {'playerUuid':player,'currency':'dunemarks','orders':orders}
def catalogue(connect):
with connect() as con:
with con.cursor() as cur:
cur.execute('CALL dune_kit_catalogue()');rows=cur.fetchall()
while cur.nextset():pass
cur.execute('SELECT listing_id,COUNT(*) AS sales FROM dune_kit_sales WHERE delivered_at IS NOT NULL AND buyer_uuid<>seller_uuid GROUP BY listing_id')
popularity={row['listing_id']:int(row['sales']) for row in cur.fetchall()}
owners=sorted({identity(row['seller_uuid']) for row in rows if row.get('commerce_kind')=='personal_sale'})
unlocked={owner:set() for owner in owners}
if owners:
cur.execute('SELECT player_uuid,stage_index FROM dune_kit_arc_claims WHERE player_uuid IN ('+','.join(['%s']*len(owners))+')',tuple(owners))
for row in cur.fetchall():unlocked[row['player_uuid']].add(int(row['stage_index']))
listings=[];office_cache={}
for row in rows:
item=listing_snapshot(row)
try:
current_listing_authority(cur,item,locking=False,cache=office_cache)
except PermissionError:
continue
if item['commerceKind']=='personal_sale':
stages=sorted(unlocked[item['sellerUuid']])
if stages!=list(range(len(stages))) or (not item['sellerTierOverride'] and TIERS.index(item['quality'])>len(stages)):continue
item['completedSales']=popularity.get(item['listingId'],0)
item['sellerName']=str(row['seller_name'])[:64]
item['priceDunemarks']=format(Decimal(item['priceCents'])/100,'.2f')
listings.append(item)
return {'currency':'dunemarks','listings':listings}
def queue_redemption(connect, player, code):
player = identity(player); digest = code_hash(code)
with connect() as con:
try:
con.begin()
with con.cursor() as cur:
cur.execute('SELECT id,buyer_uuid,delivered_at,redeem_requested_at FROM dune_kit_sales WHERE code_hash=%s FOR UPDATE', (digest,))
row = cur.fetchone()
if not row or row['buyer_uuid'] != player:
raise PermissionError('Item code is unavailable for this account')
if row['delivered_at'] is None and row['redeem_requested_at'] is None:
cur.execute('UPDATE dune_kit_sales SET redeem_requested_at=%s WHERE id=%s AND redeem_requested_at IS NULL', (now(cur), row['id']))
result = {'ok': True, 'orderLineId': row['id'], 'status': 'delivered' if row['delivered_at'] is not None else 'pending-in-game-delivery'}
con.commit()
return result
except Exception:
con.rollback();raise
def claim_arc(connect, player, index):
player = identity(player); index = stage(index)
arc_definition()
with connect() as con:
try:
con.begin()
with con.cursor() as cur:
# Central treasury lock serializes rewards across servers and makes insufficient funding retryable.
cur.execute("SELECT balance FROM dune_staff_bank_wallet WHERE account_key='network' FOR UPDATE")
treasury = cur.fetchone()
done = claimed(cur, player)
if index in done:
con.rollback();return {'ok': True, 'alreadyClaimed': True, 'stage': index}
if index != len(done) or progress(cur, player, index) < TARGETS[index]:
raise PermissionError('Complete the current sales chapter first')
reward = Decimal(REWARDS_CENTS[index])/100
if not treasury or Decimal(treasury['balance']) < reward:
con.rollback();return {'ok': False, 'pending': True, 'reason': 'server-bank-funding', 'stage': index}
cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE', (player,))
wallet = cur.fetchone()
if wallet is None:
raise PermissionError('An existing Minecraft wallet is required')
amount = Decimal(wallet['balance']) + reward
if amount > Decimal('1000000000000'):
raise ValueError('Wallet limit reached')
stamp = now(cur)
cur.execute('INSERT INTO dune_kit_arc_claims(player_uuid,stage_index,reward_cents,claimed_at) VALUES(%s,%s,%s,%s)', (player,index,REWARDS_CENTS[index],stamp))
balance = Decimal(treasury['balance'])-reward
cur.execute("UPDATE dune_staff_bank_wallet SET balance=%s,updated_at=%s WHERE account_key='network'", (balance,stamp))
cur.execute('UPDATE dune_economy_balances SET balance=%s WHERE uuid=%s', (amount,player))
import uuid
reference = 'kit-arc:'+player+':'+str(index)
cur.execute('INSERT INTO dune_staff_bank_ledger(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)', (str(uuid.uuid4()),player,'kit-arc-reward',-reward,balance,stamp,reference))
con.commit()
return {'ok': True, 'alreadyClaimed': False, 'stage': index, 'rewardDunemarks': format(reward,'.2f')}
except Exception:
con.rollback();raise

View file

@ -0,0 +1,73 @@
"""Versioned kit cosmetics; only bounded literal text and vanilla item metadata."""
import copy
import json
import re
from pathlib import Path
CONTRACT = json.loads(Path(__file__).with_name('kit-equipment-contract.json').read_text())
def exact(value, fields):
return isinstance(value, dict) and set(value) == set(fields)
def text(value, maximum):
return isinstance(value, str) and len(value.encode('utf-16-le')) // 2 <= maximum and not re.search(r'[\x00-\x1f\x7f<>§]', value)
def validate_lore(value):
if not isinstance(value, list) or len(value) > 6:
raise ValueError('Use at most six item lore lines')
result = []
for line in value:
if (not exact(line, ['text', 'color', 'bold', 'italic']) or not text(line['text'], 120)
or not isinstance(line['color'], str) or not re.fullmatch(r'#[a-f0-9]{6}', line['color'], re.I)
or type(line['bold']) is not bool or type(line['italic']) is not bool):
raise ValueError('Invalid literal item lore')
result.append({**line, 'color': line['color'].upper()})
return result
def validate_equipment(value):
if not exact(value, ['version', 'armor', 'banner']) or type(value['version']) is not int or value['version'] != 3 or not exact(value['armor'], CONTRACT['slots']):
raise ValueError('Complete version 3 kit required')
armor = {}
for slot in CONTRACT['slots']:
piece = value['armor'][slot]
if (not exact(piece, ['material', 'name', 'lore', 'trim']) or piece['material'] != 'netherite'
or not text(piece['name'], 64) or not exact(piece['trim'], ['pattern', 'material'])
or piece['trim']['pattern'] not in CONTRACT['trimPatterns'] or piece['trim']['material'] not in CONTRACT['trimMaterials']):
raise ValueError('Invalid armour piece or trim')
armor[slot] = {**piece, 'name': piece['name'].strip(), 'lore': validate_lore(piece['lore']), 'trim': dict(piece['trim'])}
banner = value['banner']
if (not exact(banner, ['enabled', 'name', 'base', 'patterns', 'lore']) or type(banner['enabled']) is not bool
or not text(banner['name'], 64) or banner['base'] not in CONTRACT['bannerColors']
or not isinstance(banner['patterns'], list) or len(banner['patterns']) > 6):
raise ValueError('Invalid banner')
for layer in banner['patterns']:
if not exact(layer, ['pattern', 'color']) or layer['pattern'] not in CONTRACT['bannerPatterns'] or layer['color'] not in CONTRACT['bannerColors']:
raise ValueError('Invalid banner layer')
return {'version': 3, 'armor': armor, 'banner': {**banner, 'name': banner['name'].strip(), 'patterns': copy.deepcopy(banner['patterns']), 'lore': validate_lore(banner['lore'])}}
def default_equipment(legacy):
lore = [{'text': line, 'color': '#AAAAAA', 'bold': False, 'italic': False} for line in legacy.get('lore', [])[:6]]
return validate_equipment({'version': 3, 'armor': {slot: {'material': 'netherite', 'name': legacy.get('itemNames', {}).get(slot, ''), 'lore': copy.deepcopy(lore), 'trim': {'pattern': 'dune', 'material': 'gold'}} for slot in CONTRACT['slots']}, 'banner': {'enabled': False, 'name': '', 'base': 'black', 'patterns': [], 'lore': []}})
def validate_upgrade(value, quality, kind):
if quality != 'legendary' or kind != 'personal_sale' or not exact(value, ['policy', 'points', 'bonuses']) or value['policy'] != 'legendary-player-v1' or type(value['points']) is not int or not 1 <= value['points'] <= 3 or not isinstance(value['bonuses'], list) or not 1 <= len(value['bonuses']) <= 3:
raise ValueError('Invalid Legendary Player Kit upgrade')
selected, total = set(), 0
for bonus in value['bonuses']:
if not exact(bonus, ['piece', 'enchantment', 'levels']) or bonus['piece'] not in CONTRACT['slots']:
raise ValueError('Invalid upgrade piece')
allowed = {'protection', 'unbreaking', 'mending', 'thorns'}
allowed.update({'helmet': ['respiration', 'aqua_affinity'], 'leggings': ['swift_sneak'], 'boots': ['feather_falling', 'depth_strider', 'soul_speed']}.get(bonus['piece'], []))
if bonus['enchantment'] not in allowed or type(bonus['levels']) is not int or not 1 <= bonus['levels'] <= 3 or (bonus['piece'], bonus['enchantment']) in selected:
raise ValueError('Invalid upgrade distribution')
selected.add((bonus['piece'], bonus['enchantment']))
total += bonus['levels']
if total != value['points']:
raise ValueError('Upgrade points do not balance')
return copy.deepcopy(value)

View file

@ -0,0 +1,152 @@
"""Term-bound office blueprints. Private bridge only; authority comes from game SQL."""
import json
import re
import uuid
import time
from kit_equipment import validate_equipment, default_equipment
HOUSES = ('Fremen', 'Harkonnen', 'Corrino', 'Atreides', 'Ordos')
class Conflict(Exception):
pass
def identity(value):
if not isinstance(value, str) or not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', value):
raise ValueError('Verified Minecraft UUID required')
return str(uuid.UUID(value))
def winner(election):
tally = election.get('tally', {}) if isinstance(election, dict) else {}
valid = []
for key, count in tally.items():
try:
player = identity(key)
except (ValueError, TypeError):
continue
if type(count) is int and count > 0:
valid.append((player, count))
return sorted(valid, key=lambda row: (-row[1], row[0]))[0][0] if valid else ''
def at(record, *keys):
for key in keys:
if not isinstance(record, dict):
return {}
record = record.get(key, record.get(str(key), {}))
return record
def interim_winner(record, kind, faction=None, now=None):
now = int(time.time() * 1000) if now is None else now
entry = at(record, 'interim', kind) if kind == 'emperor' else at(record, 'interim', 'house', faction)
try:
player = identity(entry.get('uuid'))
start, end = entry.get('startsAt'), entry.get('expiresAt')
return player if type(start) is int and type(end) is int and start <= now < end else ''
except (ValueError, TypeError, AttributeError):
return ''
def offices(record, week, player, faction):
result = {}
emperor = interim_winner(record, 'emperor') or winner(at(record, 'votes', 'emperor', week))
if player == emperor:
result['emperor'] = f'emperor:{week}:{player}'
if faction in HOUSES and player == (interim_winner(record, 'house', faction) or winner(at(record, 'votes', 'house', week, faction))):
result['house-leader:' + faction] = f'house-leader:{faction}:{week}:{player}'
for appointment, office in (('water', 'water-steward'), ('steward', 'spice-steward')):
entry = at(record, 'appointments', appointment)
if emperor and at(entry, 'week') == week and at(entry, 'emperor') == emperor and at(entry, 'house') == faction:
result[office + ':' + faction] = f'{office}:{faction}:{week}:{player}:{emperor}'
return result
def initialize(cursor):
cursor.execute('''CREATE TABLE IF NOT EXISTS dune_office_kit_definitions (
owner_uuid VARCHAR(36) NOT NULL,office_key VARCHAR(96) NOT NULL,
term_id VARCHAR(190) NOT NULL,version INTEGER NOT NULL,
kit_name VARCHAR(64) NOT NULL,color VARCHAR(7) NOT NULL,lore_json TEXT NOT NULL,
updated_at BIGINT NOT NULL,PRIMARY KEY(owner_uuid,office_key,term_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''')
cursor.execute("SELECT COUNT(*) AS n FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='dune_office_kit_definitions' AND COLUMN_NAME='equipment_json'")
if cursor.fetchone()['n'] == 0:
cursor.execute('ALTER TABLE dune_office_kit_definitions ADD COLUMN equipment_json JSON NULL')
def authority(cursor, player, locking=False):
import yaml
suffix = ' FOR SHARE' if locking else ''
cursor.execute('SELECT yaml FROM dune_politics WHERE id=1' + suffix)
row = cursor.fetchone()
if not row or not isinstance(row['yaml'], str) or len(row['yaml']) > 2097152:
raise RuntimeError('Political authority unavailable')
record = yaml.safe_load(row['yaml']) or {}
cursor.execute('SELECT faction FROM dune_players WHERE uuid=%s' + suffix, (player,))
row = cursor.fetchone()
faction = row['faction'] if row else ''
cursor.execute('SELECT FLOOR(UNIX_TIMESTAMP(CURRENT_TIMESTAMP)/604800) AS week')
week = int(cursor.fetchone()['week'])
return offices(record, week, player, faction)
def validate(data):
if not isinstance(data, dict) or set(data) != ({'uuid', 'office', 'term', 'version', 'name', 'color', 'lore'} | ({'equipment'} if 'equipment' in data else set())):
raise ValueError('Invalid blueprint fields')
if 'equipment' in data:
data = {**data, 'equipment': validate_equipment(data['equipment'])}
player = identity(data['uuid'])
if data['office'] != 'emperor' and not (isinstance(data['office'], str) and re.fullmatch(r'(house-leader|water-steward|spice-steward):(Fremen|Harkonnen|Corrino|Atreides|Ordos)', data['office'])):
raise ValueError('Invalid office')
if not isinstance(data['term'], str) or not 1 <= len(data['term']) <= 190:
raise ValueError('Invalid elected term')
if type(data['version']) is not int or not 0 <= data['version'] < 2147483647:
raise ValueError('Invalid blueprint version')
def text(value, limit):
if not isinstance(value, str) or not 1 <= len(value.strip()) <= limit or re.search(r'[\x00-\x1f\x7f<>§]', value):
raise ValueError('Use plain text for kit names and lore')
return value.strip()
name = text(data['name'], 64)
if not isinstance(data['color'], str) or not re.fullmatch(r'#[0-9A-Fa-f]{6}', data['color']):
raise ValueError('Use a six-digit colour')
if not isinstance(data['lore'], list) or len(data['lore']) > 6:
raise ValueError('Use at most six lore lines')
return {**data, 'uuid': player, 'name': name, 'color': data['color'].upper(), 'lore': [text(line, 120) for line in data['lore']]}
def read(connect, player):
player = identity(player)
with connect() as con:
with con.cursor() as cursor:
current = authority(cursor, player)
cursor.execute('SELECT office_key,term_id,version,kit_name,color,lore_json,equipment_json FROM dune_office_kit_definitions WHERE owner_uuid=%s', (player,))
definitions = {row['office_key']: row for row in cursor.fetchall() if current.get(row['office_key']) == row['term_id']}
rows = []
for office, term in current.items():
row = definitions.get(office)
rows.append({'office': office, 'term': term, 'version': row['version'] if row else 0, 'name': row['kit_name'] if row else 'Imperial Stillsuit', 'color': row['color'] if row else '#571F82', 'lore': json.loads(row['lore_json']) if row else [], 'quality': 'uncommon', 'equipment': validate_equipment(json.loads(row['equipment_json'])) if row and row.get('equipment_json') else None})
return {'playerUuid': player, 'canDesign': bool(rows), 'offices': rows}
def save(connect, payload):
data = validate(payload)
with connect() as con:
try:
con.begin()
with con.cursor() as cursor:
if authority(cursor, data['uuid'], True).get(data['office']) != data['term']:
raise PermissionError('Current elected office required')
args = (data['uuid'], data['office'], data['term'])
cursor.execute('SELECT version,equipment_json FROM dune_office_kit_definitions WHERE owner_uuid=%s AND office_key=%s AND term_id=%s FOR UPDATE', args)
row = cursor.fetchone()
if (row['version'] if row else 0) != data['version']:
raise Conflict('Blueprint changed; reload before saving')
equipment = data.get('equipment') or (validate_equipment(json.loads(row['equipment_json'])) if row and row.get('equipment_json') else default_equipment(data))
if row:
cursor.execute('''UPDATE dune_office_kit_definitions SET version=%s,kit_name=%s,color=%s,lore_json=%s,equipment_json=%s,
updated_at=CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED)
WHERE owner_uuid=%s AND office_key=%s AND term_id=%s AND version=%s''',
(data['version'] + 1, data['name'], data['color'], json.dumps(data['lore']), json.dumps(equipment)) + args + (data['version'],))
if cursor.rowcount != 1:
raise Conflict('Blueprint changed; reload before saving')
else:
cursor.execute('''INSERT INTO dune_office_kit_definitions(owner_uuid,office_key,term_id,version,kit_name,color,lore_json,equipment_json,updated_at)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED))''',
args + (1, data['name'], data['color'], json.dumps(data['lore']), json.dumps(equipment)))
con.commit()
except Exception:
con.rollback()
raise
return {'ok': True, 'uuid': data['uuid'], 'office': data['office'], 'term': data['term'], 'version': data['version'] + 1}

View file

@ -0,0 +1,56 @@
import json
import threading
import unittest
from unittest.mock import patch
from http.server import ThreadingHTTPServer
from urllib.request import Request, urlopen
from urllib.error import HTTPError
import agent
class AgentTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
agent.SECRET = 't' * 64
cls.http = ThreadingHTTPServer(('127.0.0.1', 0), agent.Handler)
threading.Thread(target=cls.http.serve_forever, daemon=True).start()
cls.url = 'http://127.0.0.1:' + str(cls.http.server_port)
@classmethod
def tearDownClass(cls):
cls.http.shutdown()
cls.http.server_close()
def request(self, path, body=None, token='t' * 64):
data = None if body is None else json.dumps(body).encode()
request = Request(self.url + path, data=data, headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
try:
with urlopen(request) as response:
return response.status, json.load(response)
except HTTPError as response:
return response.code, json.load(response)
def test_authentication_and_fixed_log_services(self):
self.assertEqual(self.request('/servers', token='wrong')[0], 401)
self.assertEqual(self.request('/logs?server=ssh')[0], 404)
self.assertEqual(self.request('/logs?server=arrakis&server=proxy')[0], 404)
def test_invalid_actions_never_start_worker(self):
with patch.object(agent, 'perform') as perform:
for data in [dict(server='ssh', action='restart', actor='owner'), dict(server='arrakis', action='shell', actor='owner'), dict(server='arrakis', action='command', command='list\nstop', actor='owner'), dict(server='proxy', action='command', command='list', actor='owner')]:
self.assertEqual(self.request('/action', data)[0], 400)
perform.assert_not_called()
def test_accepted_action_and_duplicate_block(self):
agent.JOBS.clear()
agent.LAST.clear()
with patch.object(agent, 'perform') as perform:
data = dict(server='arrakis', action='restart', actor='owner')
self.assertEqual(self.request('/action', data)[0], 202)
self.assertEqual(self.request('/action', data)[0], 409)
perform.assert_called_once_with('arrakis', 'restart', '', 'owner')
def test_redacts_credentials(self):
self.assertNotIn('hunter2', agent.scrub('rcon.password=hunter2'))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,53 @@
import copy
import json
from pathlib import Path
import unittest
from kit_equipment import default_equipment, validate_equipment, validate_upgrade
import player_kits
class KitEquipmentTest(unittest.TestCase):
def test_upgrades_reject_wrong_kind_duplicates_and_unbalanced_points(self):
value = {'policy': 'legendary-player-v1', 'points': 2,
'bonuses': [{'piece': 'helmet', 'enchantment': 'protection', 'levels': 2}]}
self.assertEqual(validate_upgrade(value, 'legendary', 'personal_sale'), value)
for quality, kind in [('rare', 'personal_sale'), ('legendary', 'server_sale')]:
with self.assertRaises(ValueError):
validate_upgrade(value, quality, kind)
for change in [dict(value, points=3), dict(value, bonuses=value['bonuses'] * 2)]:
with self.assertRaises(ValueError):
validate_upgrade(change, 'legendary', 'personal_sale')
def setUp(self):
self.fixtures = json.loads(Path(__file__).with_name('kit-equipment-fixtures.json').read_text())
def test_browser_and_native_contracts_agree(self):
self.assertEqual(validate_equipment(self.fixtures['valid']), self.fixtures['normalized'])
for value in self.fixtures['invalid']:
with self.subTest(value=value), self.assertRaises(ValueError):
validate_equipment(value)
def test_lore_keeps_blank_lines_and_independent_piece_edits(self):
item = default_equipment({'lore': ['First', '', 'Third']})
item['armor']['helmet']['lore'][0]['text'] = 'Edited'
self.assertEqual(item['armor']['boots']['lore'][0]['text'], 'First')
self.assertEqual(item['armor']['boots']['lore'][1]['text'], '')
self.assertFalse(item['armor']['boots']['lore'][0]['italic'])
def test_office_blueprints_validate_equipment_without_accepting_identity_overrides(self):
body = {'uuid': '11111111-1111-4111-8111-111111111111', 'office': 'emperor',
'term': 'current-term', 'version': 1, 'name': 'Imperial Regalia',
'color': '#bca05b', 'lore': ['Duty endures.'], 'equipment': self.fixtures['valid']}
self.assertEqual(player_kits.validate(body)['equipment'], self.fixtures['normalized'])
invalid = copy.deepcopy(body)
invalid['buyerUuid'] = '22222222-2222-4222-8222-222222222222'
with self.assertRaises(ValueError):
player_kits.validate(invalid)
invalid = copy.deepcopy(body)
invalid['equipment']['armor']['helmet']['lore'][0]['clickEvent'] = {'action': 'run_command'}
with self.assertRaises(ValueError):
player_kits.validate(invalid)
if __name__ == '__main__':
unittest.main()