Compare commits

...
7 changed files with 294 additions and 5 deletions

No files matched your search

+1
View File
@@ -40,6 +40,7 @@ chmod +x start.sh
- **SSH Key Rotation** — scan all key locations and sync the newest key
- **Backup & Restore** — full server snapshots (game DB, K8s resources, RMQ config, dashboard schema) with optional AES-256 encryption and password protection
- **Scheduled Backups** — configurable interval or day/time-based scheduling with automatic retention cleanup
- **Funcom Service Auth Token Management** — update the `ServiceAuthToken` JWT across files and live K8s resources (secret, YAML, BattleGroup CR) with verification
---
+169
View File
@@ -2162,3 +2162,172 @@ def register_api_routes(app, services, settings):
def api_backup_run_scheduled():
result = backup_svc.run_scheduled_backup()
return jsonify(result)
# ── Funcom ServiceAuthToken ────────────────────────────────────────
@app.route('/api/server/service-auth-token', methods=['POST'])
@auth_req
def api_set_service_auth_token():
data = request.get_json() or {}
token = (data.get('token') or '').strip()
if not token:
return jsonify({'success': False, 'error': 'Token cannot be empty'})
if not token.startswith('eyJ'):
return jsonify({'success': False, 'error': 'Token does not look like a valid JWT'})
ns = settings.get('kubernetes', {}).get('namespace', '')
if not ns:
return jsonify({'success': False, 'error': 'Kubernetes namespace not configured'})
resource_prefix = ns
for prefix in ['funcom-seabass-']:
if resource_prefix.startswith(prefix):
resource_prefix = resource_prefix[len(prefix):]
break
secret_yaml = f'/home/dune/.dune/{resource_prefix}-fls-secret.yaml'
main_yaml = f'/home/dune/.dune/{resource_prefix}.yaml'
try:
import base64
# Force fresh SSH connection to avoid stale client reuse
ssh.close()
# ── Step 1: Read & update secret YAML (small file, keep current approach) ──
t0 = time.time()
out, err, rc = ssh.run(f'cat {secret_yaml}', timeout=10)
t1 = time.time()
logger.info(f'[token] read secret YAML: {t1-t0:.2f}s rc={rc}')
if rc != 0:
return jsonify({'success': False, 'error': f'Failed to read secret file: {err}'})
fls_prefix = 'FuncomLiveServices__ServiceAuthToken: "'
idx = out.find(fls_prefix)
if idx == -1:
logger.error(f'Secret YAML lines: {[l for l in out.splitlines() if "ServiceAuthToken" in l]}')
return jsonify({'success': False, 'error': 'Could not find FuncomLiveServices__ServiceAuthToken line in secret file'})
start = idx + len(fls_prefix)
end = out.find('"', start)
if end == -1:
return jsonify({'success': False, 'error': 'Could not find closing quote for ServiceAuthToken'})
old_token = out[start:end]
new_secret = out[:start] + token + out[end:]
t2 = time.time()
out, err, rc = ssh.write_file(secret_yaml, new_secret, timeout=10)
t3 = time.time()
logger.info(f'[token] write secret YAML: {t3-t2:.2f}s rc={rc}')
if rc != 0:
return jsonify({'success': False, 'error': f'Failed to write secret file: {err}'})
# ── Step 2: Update main battlegroup YAML via read-modify-write ──
# Extract old token from the main YAML (may differ from secret YAML)
t4 = time.time()
out, err, rc = ssh.run(f'cat {main_yaml}', timeout=10)
t5 = time.time()
logger.info(f'[token] read main YAML: {t5-t4:.2f}s rc={rc}')
if rc != 0:
return jsonify({'success': False, 'error': f'Failed to read battlegroup file: {err}'})
ini_prefix = '-ini:engine:[FuncomLiveServices]:ServiceAuthToken='
idx = out.find(ini_prefix)
if idx == -1:
logger.error(f'Main YAML lines: {[l for l in out.splitlines() if "ServiceAuthToken" in l]}')
return jsonify({'success': False, 'error': 'Could not find ServiceAuthToken in battlegroup file'})
old_start = idx + len(ini_prefix)
old_end = out.find('\n', old_start)
old_token_main = out[old_start:old_end].strip() if old_end != -1 else out[old_start:].strip()
count = out.count(old_token_main)
new_main = out.replace(old_token_main, token)
logger.info(f'[token] replaced {count} occurrences in main YAML')
t6 = time.time()
out, err, rc = ssh.write_file(main_yaml, new_main, timeout=15)
t7 = time.time()
logger.info(f'[token] write main YAML: {t7-t6:.2f}s rc={rc}')
if rc != 0:
return jsonify({'success': False, 'error': f'Failed to write battlegroup file: {err}'})
# Verify: count total ServiceAuthToken lines vs new-token lines
out, err, rc = ssh.run(f"grep -c 'ServiceAuthToken' {main_yaml} || true", timeout=5)
total_lines = int(out.strip() or 0)
out, err, rc = ssh.run(f"grep -cF '{token}' {main_yaml} || true", timeout=5)
new_count = int(out.strip() or 0)
logger.info(f'[token] main YAML verify: {new_count}/{total_lines} tokens replaced')
# ── Step 3: Update live K8s BattleGroup CR (may differ from disk YAML) ──
bg_name = resource_prefix
t8 = time.time()
out, err, rc = ssh.run(
f'sudo kubectl get battlegroup {bg_name} -n {ns} -o yaml', timeout=10
)
t9 = time.time()
logger.info(f'[token] read BG CR: {t9-t8:.2f}s rc={rc}')
if rc != 0:
return jsonify({'success': False, 'error': f'Failed to read BattleGroup CR: {err}'})
old_start = out.find(ini_prefix)
if old_start == -1:
logger.error(f'BG CR lines: {[l for l in out.splitlines() if "ServiceAuthToken" in l]}')
return jsonify({'success': False, 'error': 'Could not find ServiceAuthToken in BattleGroup CR'})
old_start += len(ini_prefix)
old_end = out.find('\n', old_start)
old_token_cr = out[old_start:old_end].strip() if old_end != -1 else out[old_start:].strip()
cr_count = out.count(old_token_cr)
new_cr = out.replace(old_token_cr, token)
logger.info(f'[token] replaced {cr_count} occurrences in BG CR')
cr_temp = '/tmp/bg-cr-update.yaml'
t10 = time.time()
out, err, rc = ssh.write_file(cr_temp, new_cr, timeout=15)
t11 = time.time()
logger.info(f'[token] write BG CR temp: {t11-t10:.2f}s rc={rc}')
if rc != 0:
return jsonify({'success': False, 'error': f'Failed to write BG CR temp file: {err}'})
out, err, rc = ssh.run(
f'sudo kubectl apply -f {cr_temp}', timeout=15
)
t12 = time.time()
logger.info(f'[token] apply BG CR: {t12-t11:.2f}s rc={rc}')
if rc != 0:
return jsonify({'success': False, 'error': f'Failed to apply BattleGroup CR: {err}'})
# Verify new token count in live CR
out, err, rc = ssh.run(
f"sudo kubectl get battlegroup {bg_name} -n {ns} -o yaml | grep -cF '{token}' || true",
timeout=5
)
live_count = int(out.strip() or 0)
logger.info(f'[token] BG CR verify: {live_count}/{cr_count} tokens replaced')
# Clean up temp file
ssh.run(f'rm -f {cr_temp}', timeout=3)
# ── Step 4: Update K8s secret via kubectl patch ──
patch = json.dumps({'stringData': {'FuncomLiveServices__ServiceAuthToken': token}})
patch_encoded = base64.b64encode(patch.encode()).decode()
t13 = time.time()
out, err, rc = ssh.run(
f"printf '%s' '{patch_encoded}' | base64 -d > /tmp/service-auth-token-patch.json; "
f"sudo kubectl patch secret server-gateway-secret -n {ns} --patch-file /tmp/service-auth-token-patch.json",
timeout=15
)
t14 = time.time()
logger.info(f'[token] kubectl patch: {t14-t13:.2f}s rc={rc}')
if rc != 0:
return jsonify({'success': False, 'error': f'Failed to update K8s secret: {err}'})
total = t14 - t0
logger.info(f'[token] completed successfully in {total:.2f}s (disk={new_count}, live={live_count})')
return jsonify({
'success': True,
'message': f'Token updated in secret YAML, battlegroup YAML ({new_count} replacements), live BattleGroup CR ({live_count} replacements), and K8s secret. Consuming pods must be restarted for the change to take effect.'
})
except Exception as e:
logger.error(f'[token] exception: {e}')
return jsonify({'success': False, 'error': str(e)})
+35
View File
@@ -95,6 +95,7 @@ class SSHService:
try:
client = self._get_client()
stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
stdout.channel.settimeout(timeout)
out = stdout.read().decode('utf-8', errors='replace')
err = stderr.read().decode('utf-8', errors='replace')
rc = stdout.channel.recv_exit_status()
@@ -121,6 +122,40 @@ class SSHService:
self._client = None
return '', str(ex), -1
def write_file(self, remote_path, data, timeout=30):
"""Write text data to a remote file via base64 over stdin.
Args:
remote_path: Absolute path on the remote machine.
data: String content to write.
timeout: Max seconds to wait for command completion.
Returns:
Tuple of (stdout, stderr, return_code).
"""
import base64
encoded = base64.b64encode(data.encode('utf-8'))
try:
client = self._get_client()
stdin, stdout, stderr = client.exec_command(
f'base64 -d > {remote_path}',
timeout=timeout
)
stdout.channel.settimeout(timeout)
stdin.write(encoded)
stdin.flush()
stdin.channel.shutdown_write()
out = stdout.read().decode('utf-8', errors='replace')
err = stderr.read().decode('utf-8', errors='replace')
rc = stdout.channel.recv_exit_status()
if rc != 0:
logger.warning(f"SSH write_file failed (rc={rc}, path={remote_path}): {err[:200]}")
return out, err, rc
except Exception as ex:
logger.error(f"SSH write_file error ({remote_path}): {ex}")
self._client = None
return '', str(ex), -1
def check_connection(self):
"""Test SSH connectivity with a simple echo command.
+2 -2
View File
@@ -74,6 +74,7 @@ NAV_PAGES = [
('/director', 'Director'),
('/shell', 'Shell'),
('/files', 'Files'),
('/backup', 'Backup'),
('/events', 'Events'),
('/chat', 'Chat'),
('/players', 'Players'),
@@ -82,7 +83,6 @@ NAV_PAGES = [
('/buildings', 'Buildings'),
('/map', 'Map'),
('/admin-experimental', 'Experimental'),
('/backup', 'Backup'),
]
NAV_GROUPS = [
@@ -92,6 +92,7 @@ NAV_GROUPS = [
('/director', 'Director'),
('/shell', 'Shell'),
('/files', 'Files'),
('/backup', 'Backup'),
]),
('Players', [
('/players', 'Players'),
@@ -106,6 +107,5 @@ NAV_GROUPS = [
]),
('System', [
('/admin-experimental', 'Experimental'),
('/backup', 'Backup'),
]),
]
+8
View File
@@ -9,6 +9,14 @@
<div id="backup-status" class="error-banner" style="display:none;"></div>
<div style="background:rgba(255,193,7,0.12);border:2px solid rgba(255,193,7,0.6);border-left:6px solid #ffc107;border-radius:8px;padding:14px 20px;margin-bottom:16px;">
<div style="font-size:14px;font-weight:700;color:#e8a317;margin-bottom:6px;">&#9888; WIP — Use with caution</div>
<div style="font-size:13px;color:var(--text);line-height:1.5;">
This feature is still experimental. Test on a non-production environment first.
Keep offline backups of anything critical before using restore.
</div>
</div>
<div style="background:rgba(220,38,38,0.12);border:2px solid rgba(220,38,38,0.6);border-left:6px solid #dc2626;border-radius:8px;padding:16px 20px;margin-bottom:20px;">
<div style="font-size:14px;font-weight:700;color:#ef4444;margin-bottom:8px;">&#9888; SECURITY WARNING</div>
<div style="font-size:13px;color:var(--text);line-height:1.6;">
-3
View File
@@ -63,9 +63,6 @@
<div class="map-summary-item"><strong id="summary-bases">0</strong><span>Bases</span></div>
</div>
</div>
<div class="map-notice">
&#9888; This page is still a work in progress - expect bugs and quirks. Base ownership names are inferred heuristically and may be inaccurate.
</div>
<div class="map-layout">
<div id="map-container">
<div class="map-credit">Map images sourced from <a href="https://awakening.wiki/" target="_blank" rel="noopener">awakening.wiki</a> — a massive thank you for their incredible work mapping Arrakis!</div>
+79
View File
@@ -233,6 +233,34 @@
</div>
</div>
<div class="card">
<div class="card-header">
<span>Funcom Service Auth Token <span style="font-size:10px;color:var(--warn);font-weight:400;">[WIP]</span></span>
<span id="sat-status" style="font-size:12px;color:var(--text-muted);"></span>
</div>
<div class="card-body">
<div style="margin-bottom:12px;padding:10px 12px;background:var(--warn-bg, #fff3cd);border:1px solid var(--warn-border, #ffc107);border-radius:6px;font-size:12px;line-height:1.5;color:var(--warn-text, #856404);">
<strong>⚠ WIP — Use with caution.</strong> This feature is still experimental.
Only use if you understand the risks. Backup your <code>*.yaml</code> files first.
</div>
<div style="margin-bottom:12px;padding:12px;background:var(--bg);border-radius:6px;font-size:13px;line-height:1.6;">
<strong style="color:var(--primary);">ServiceAuthToken</strong> — Used by the game server to authenticate with Funcom's live services.
If this token is regenerated by Funcom, paste the new JWT below and save.
All consuming pods must be restarted afterward.
</div>
<div style="margin-bottom:12px;">
<textarea id="sat-token" rows="4"
style="width:100%;padding:10px 12px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:12px;font-family:monospace;resize:vertical;"
placeholder="Paste the new ServiceAuthToken JWT here..."></textarea>
</div>
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
<button id="sat-save-btn" onclick="saveServiceAuthToken()"
style="padding:8px 20px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Save Token</button>
<span id="sat-message" style="font-size:12px;color:var(--text-muted);"></span>
</div>
</div>
</div>
<div class="card">
<div class="card-header" style="cursor:pointer;" onclick="document.getElementById('debug-section').classList.toggle('hidden');">
<span>🐛 Debug Logging</span>
@@ -784,5 +812,56 @@ loadDebugStatus();
// Auto-load battlegroup and pods once on page load, then require manual refresh
bgRefreshStatus();
refreshPods();
// ServiceAuthToken
async function saveServiceAuthToken() {
const token = document.getElementById('sat-token').value.trim();
const btn = document.getElementById('sat-save-btn');
const msg = document.getElementById('sat-message');
const status = document.getElementById('sat-status');
if (!token) {
msg.textContent = 'Please paste the new token first.';
msg.style.color = 'var(--danger)';
return;
}
if (!confirm('Are you sure you want to replace the ServiceAuthToken?\n\nThis will update the K8s secret and YAML file. All consuming pods must be restarted for the change to take effect.')) return;
if (!confirm('Are you absolutely sure? An incorrect token may break server connectivity with Funcom live services.')) return;
btn.disabled = true;
btn.textContent = 'Saving...';
msg.textContent = 'Updating token...';
msg.style.color = 'var(--text-muted)';
status.textContent = 'Updating...';
try {
const resp = await csrfFetch('/api/server/service-auth-token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token })
});
const data = await resp.json();
if (data.success) {
msg.textContent = data.message || 'Token updated successfully.';
msg.style.color = 'var(--success)';
status.textContent = 'Token saved';
status.style.color = 'var(--success)';
document.getElementById('sat-token').value = '';
} else {
msg.textContent = 'Error: ' + (data.error || 'Unknown error');
msg.style.color = 'var(--danger)';
status.textContent = 'Failed';
status.style.color = 'var(--danger)';
}
} catch (e) {
msg.textContent = 'Error: ' + e.message;
msg.style.color = 'var(--danger)';
status.textContent = 'Error';
status.style.color = 'var(--danger)';
}
btn.disabled = false;
btn.textContent = 'Save Token';
}
</script>
{% endblock %}