Compare commits

..
8 changed files with 387 additions and 14 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 - **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 - **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 - **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
--- ---
+172 -1
View File
@@ -2146,7 +2146,9 @@ def register_api_routes(app, services, settings):
@app.route('/api/backup/schedule', methods=['GET']) @app.route('/api/backup/schedule', methods=['GET'])
@auth_req @auth_req
def api_backup_schedule_get(): def api_backup_schedule_get():
return jsonify({'success': True, 'schedule': backup_svc.get_schedule()}) sched = backup_svc.get_schedule()
sched.pop('password', None) # never send password to client
return jsonify({'success': True, 'schedule': sched})
@app.route('/api/backup/schedule', methods=['POST']) @app.route('/api/backup/schedule', methods=['POST'])
@auth_req @auth_req
@@ -2160,3 +2162,172 @@ def register_api_routes(app, services, settings):
def api_backup_run_scheduled(): def api_backup_run_scheduled():
result = backup_svc.run_scheduled_backup() result = backup_svc.run_scheduled_backup()
return jsonify(result) 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)})
+6 -2
View File
@@ -12,7 +12,7 @@ import threading
import time import time
from datetime import datetime, timedelta from datetime import datetime, timedelta
from cryptography.fernet import Fernet from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
@@ -311,7 +311,9 @@ class BackupService:
cfg['schedule_times'] = data['schedule_times'] cfg['schedule_times'] = data['schedule_times']
cfg['keep'] = int(data.get('keep', cfg['keep'])) cfg['keep'] = int(data.get('keep', cfg['keep']))
if 'password' in data: if 'password' in data:
if data['password']:
cfg['password'] = data['password'] cfg['password'] = data['password']
# empty string = keep existing password (don't overwrite)
if cfg.get('mode') == 'schedule': if cfg.get('mode') == 'schedule':
cfg['next_run'] = self._next_run_from_schedule(cfg) cfg['next_run'] = self._next_run_from_schedule(cfg)
else: else:
@@ -434,8 +436,10 @@ class BackupService:
'size': os.path.getsize(path), 'size': os.path.getsize(path),
'components': meta.get('components', []), 'components': meta.get('components', []),
} }
except InvalidToken:
return {'success': False, 'valid': False, 'error': 'Wrong password'}
except Exception as e: except Exception as e:
return {'success': False, 'valid': False, 'error': str(e)} return {'success': False, 'valid': False, 'error': f'Backup corrupted: {e}'}
# ── Restore Orchestration ───────────────────────────────────────── # ── Restore Orchestration ─────────────────────────────────────────
+35
View File
@@ -95,6 +95,7 @@ class SSHService:
try: try:
client = self._get_client() client = self._get_client()
stdin, stdout, stderr = client.exec_command(command, timeout=timeout) stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
stdout.channel.settimeout(timeout)
out = stdout.read().decode('utf-8', errors='replace') out = stdout.read().decode('utf-8', errors='replace')
err = stderr.read().decode('utf-8', errors='replace') err = stderr.read().decode('utf-8', errors='replace')
rc = stdout.channel.recv_exit_status() rc = stdout.channel.recv_exit_status()
@@ -121,6 +122,40 @@ class SSHService:
self._client = None self._client = None
return '', str(ex), -1 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): def check_connection(self):
"""Test SSH connectivity with a simple echo command. """Test SSH connectivity with a simple echo command.
+2 -2
View File
@@ -74,6 +74,7 @@ NAV_PAGES = [
('/director', 'Director'), ('/director', 'Director'),
('/shell', 'Shell'), ('/shell', 'Shell'),
('/files', 'Files'), ('/files', 'Files'),
('/backup', 'Backup'),
('/events', 'Events'), ('/events', 'Events'),
('/chat', 'Chat'), ('/chat', 'Chat'),
('/players', 'Players'), ('/players', 'Players'),
@@ -82,7 +83,6 @@ NAV_PAGES = [
('/buildings', 'Buildings'), ('/buildings', 'Buildings'),
('/map', 'Map'), ('/map', 'Map'),
('/admin-experimental', 'Experimental'), ('/admin-experimental', 'Experimental'),
('/backup', 'Backup'),
] ]
NAV_GROUPS = [ NAV_GROUPS = [
@@ -92,6 +92,7 @@ NAV_GROUPS = [
('/director', 'Director'), ('/director', 'Director'),
('/shell', 'Shell'), ('/shell', 'Shell'),
('/files', 'Files'), ('/files', 'Files'),
('/backup', 'Backup'),
]), ]),
('Players', [ ('Players', [
('/players', 'Players'), ('/players', 'Players'),
@@ -106,6 +107,5 @@ NAV_GROUPS = [
]), ]),
('System', [ ('System', [
('/admin-experimental', 'Experimental'), ('/admin-experimental', 'Experimental'),
('/backup', 'Backup'),
]), ]),
] ]
+92 -6
View File
@@ -9,6 +9,14 @@
<div id="backup-status" class="error-banner" style="display:none;"></div> <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="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: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;"> <div style="font-size:13px;color:var(--text);line-height:1.6;">
@@ -119,7 +127,7 @@
</div> </div>
<div style="margin-bottom:8px;"> <div style="margin-bottom:8px;">
<label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">Encryption password (leave blank for no encryption)</label> <label style="display:block;font-size:12px;color:var(--text-muted);margin-bottom:2px;">Encryption password (leave blank for no encryption)</label>
<input type="password" id="sched-password" placeholder="All scheduled backups use this password" <input type="password" id="sched-password" placeholder="Leave blank to keep existing password"
style="width:100%;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;"> style="width:100%;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:13px;">
</div> </div>
</div> </div>
@@ -264,8 +272,51 @@
} }
</style> </style>
<!-- Create Backup Password Modal -->
<div id="create-pw-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('create-pw-modal')">
<div class="modal" style="max-width:400px;">
<div class="modal-header"><h3>Encrypt Backup (optional)</h3></div>
<div class="modal-body" style="padding:20px;">
<label style="display:block;margin-bottom:12px;font-size:13px;color:var(--text-light);">
Password
<input type="password" id="create-pw" placeholder="Leave blank for no encryption"
style="display:block;width:100%;margin-top:4px;padding:8px 10px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--card-bg);color:var(--text);">
</label>
<label style="display:block;font-size:13px;color:var(--text-light);">
Confirm password
<input type="password" id="create-pw-confirm" placeholder="Repeat password"
style="display:block;width:100%;margin-top:4px;padding:8px 10px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--card-bg);color:var(--text);">
</label>
<div id="create-pw-error" style="color:#c0392b;font-size:12px;margin-top:8px;display:none;"></div>
</div>
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
<button onclick="closeModal('create-pw-modal')" class="btn-cancel">Cancel</button>
<button id="create-pw-confirm-btn" onclick="confirmCreateBackup()" class="btn-save" style="margin-left:8px;">Create Backup</button>
</div>
</div>
</div>
<!-- Verify Backup Password Modal -->
<div id="verify-pw-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('verify-pw-modal')">
<div class="modal" style="max-width:380px;">
<div class="modal-header"><h3>Verify Backup — <span id="verify-pw-label"></span></h3></div>
<div class="modal-body" style="padding:20px;">
<label style="display:block;font-size:13px;color:var(--text-light);">
Password
<input type="password" id="verify-pw" placeholder="Leave blank if not encrypted"
style="display:block;width:100%;margin-top:4px;padding:8px 10px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--card-bg);color:var(--text);">
</label>
</div>
<div class="modal-actions" style="padding:12px 16px;border-top:1px solid var(--border);">
<button onclick="closeModal('verify-pw-modal')" class="btn-cancel">Cancel</button>
<button id="verify-pw-confirm-btn" onclick="confirmVerifyBackup()" class="btn-save" style="margin-left:8px;">Verify</button>
</div>
</div>
</div>
<script> <script>
let restorePollInterval = null; let restorePollInterval = null;
let _pendingVerifyBackup = null;
function showStatus(msg, type) { function showStatus(msg, type) {
const el = document.getElementById('backup-status'); const el = document.getElementById('backup-status');
@@ -333,8 +384,32 @@ function populateRestoreSelect(backups) {
} }
} }
function openModal(id) {
document.getElementById(id).style.display = '';
}
function closeModal(id) {
document.getElementById(id).style.display = 'none';
}
async function createBackup() { async function createBackup() {
const pw = prompt('Optional: Enter a password to encrypt this backup (leave blank for no encryption):', ''); document.getElementById('create-pw').value = '';
document.getElementById('create-pw-confirm').value = '';
document.getElementById('create-pw-error').style.display = 'none';
openModal('create-pw-modal');
document.getElementById('create-pw').focus();
}
async function confirmCreateBackup() {
const pw = document.getElementById('create-pw').value;
const confirm = document.getElementById('create-pw-confirm').value;
const errEl = document.getElementById('create-pw-error');
if (pw !== confirm) {
errEl.textContent = 'Passwords do not match.';
errEl.style.display = '';
return;
}
errEl.style.display = 'none';
closeModal('create-pw-modal');
const btn = document.getElementById('create-btn'); const btn = document.getElementById('create-btn');
btn.disabled = true; btn.disabled = true;
btn.textContent = 'Creating...'; btn.textContent = 'Creating...';
@@ -360,7 +435,17 @@ async function createBackup() {
} }
async function verifyBackup(name) { async function verifyBackup(name) {
const pw = prompt('Enter backup password (leave blank if not encrypted):', ''); _pendingVerifyBackup = name;
document.getElementById('verify-pw-label').textContent = name;
document.getElementById('verify-pw').value = '';
openModal('verify-pw-modal');
document.getElementById('verify-pw').focus();
}
async function confirmVerifyBackup() {
const name = _pendingVerifyBackup;
const pw = document.getElementById('verify-pw').value;
closeModal('verify-pw-modal');
showStatus('Verifying ' + name + '...', 'info'); showStatus('Verifying ' + name + '...', 'info');
try { try {
const r = await csrfFetch('/api/backup/verify', { const r = await csrfFetch('/api/backup/verify', {
@@ -375,11 +460,12 @@ async function verifyBackup(name) {
showStatus(name + ' verified: ' + d.files + ' files, ' + bytesStr(d.size), 'success'); showStatus(name + ' verified: ' + d.files + ' files, ' + bytesStr(d.size), 'success');
} }
} else { } else {
showStatus('Verification failed: ' + esc(d.error || 'Corrupt backup'), 'error'); showStatus('Verification failed: ' + esc(d.error || 'Unknown error'), 'error');
} }
} catch (e) { } catch (e) {
showStatus('Error: ' + esc(e.message), 'error'); showStatus('Error: ' + esc(e.message), 'error');
} }
_pendingVerifyBackup = null;
} }
async function deleteBackup(name) { async function deleteBackup(name) {
@@ -469,7 +555,7 @@ async function loadSchedule() {
list.appendChild(div); list.appendChild(div);
}); });
document.getElementById('sched-keep').value = s.keep; document.getElementById('sched-keep').value = s.keep;
document.getElementById('sched-password').value = s.password || ''; document.getElementById('sched-password').value = '';
const status = document.getElementById('schedule-status'); const status = document.getElementById('schedule-status');
status.innerHTML = s.enabled status.innerHTML = s.enabled
? '<span style="color:#27ae60;">&#9679; Active</span>' ? '<span style="color:#27ae60;">&#9679; Active</span>'
@@ -648,7 +734,7 @@ async function startRestore() {
try { try {
const r = await csrfFetch('/api/backup/restore/start', { const r = await csrfFetch('/api/backup/restore/start', {
method:'POST', headers:{'Content-Type':'application/json'}, method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({name, vm_ip: vmIp, options}) body: JSON.stringify({name, options})
}); });
const d = await r.json(); const d = await r.json();
if (!d.success) { if (!d.success) {
-3
View File
@@ -63,9 +63,6 @@
<div class="map-summary-item"><strong id="summary-bases">0</strong><span>Bases</span></div> <div class="map-summary-item"><strong id="summary-bases">0</strong><span>Bases</span></div>
</div> </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 class="map-layout">
<div id="map-container"> <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> <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> </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">
<div class="card-header" style="cursor:pointer;" onclick="document.getElementById('debug-section').classList.toggle('hidden');"> <div class="card-header" style="cursor:pointer;" onclick="document.getElementById('debug-section').classList.toggle('hidden');">
<span>🐛 Debug Logging</span> <span>🐛 Debug Logging</span>
@@ -784,5 +812,56 @@ loadDebugStatus();
// Auto-load battlegroup and pods once on page load, then require manual refresh // Auto-load battlegroup and pods once on page load, then require manual refresh
bgRefreshStatus(); bgRefreshStatus();
refreshPods(); 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> </script>
{% endblock %} {% endblock %}