Persist Plutonium keys by server ID and add key management

This commit is contained in:
2026-09-17 15:54:10 -04:00
parent e4505a3be8
commit ae173517b6
10 changed files with 305 additions and 19 deletions
+7
View File
@@ -238,6 +238,13 @@ CREATE TABLE IF NOT EXISTS deployment_scripts (
);
CREATE INDEX IF NOT EXISTS idx_deployment_scripts_dep ON deployment_scripts(deployment_id);
-- Deliberately independent of servers: credentials survive server destruction.
CREATE TABLE IF NOT EXISTS server_keys (
server_id TEXT PRIMARY KEY,
pluto_key TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
+24 -3
View File
@@ -2,6 +2,7 @@ import { mkdir, chmod, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { config, destOfKind } from '../config.js';
import { db } from '../db/index.js';
import { getServerKey, saveServerKey } from './server-keys.js';
import { getServer } from './servers.js';
import { t5ZombieMapBySlug, type GameMode } from './map-aliases.js';
import {
@@ -26,6 +27,7 @@ const T5_ZOMBIE_CONFIG_FILE = config.configTargetFile;
const T5_ZOMBIE_GAME_ID = 't5sp';
export type CreateServerFailure =
| 'bad-request'
| 'unconfigured' // Komodo creds / target server missing
| 'unknown-map' // slug isn't in the catalog
| 'no-slot' // all lobby slots for this map are taken
@@ -45,7 +47,8 @@ export type DestroyServerResult =
export interface CreateServerInput {
gameMode: GameMode; // 'zombie' — only value supported today
mapSlug: string; // 'cosmodrome'
plutoKey: string; // required; never persisted
plutoKey?: string; // saved for this server ID when supplied
lobby?: number; // explicit stable identity; otherwise first available
createdBy?: string; // 'ui' by default
}
@@ -132,7 +135,15 @@ function buildSpec(args: {
};
}
let creating = false;
export async function createServer(input: CreateServerInput): Promise<CreateServerResult> {
if (creating) return { ok: false, kind: 'no-slot', message: 'Another server is being created. Please retry shortly.' };
creating = true;
try { return await createServerUnlocked(input); }
finally { creating = false; }
}
async function createServerUnlocked(input: CreateServerInput): Promise<CreateServerResult> {
if (input.gameMode !== 'zombie') {
return { ok: false, kind: 'unknown-map', message: `unsupported game mode: ${input.gameMode}` };
}
@@ -149,11 +160,17 @@ export async function createServer(input: CreateServerInput): Promise<CreateServ
}
const baseName = `t5_${input.gameMode}_${mapEntry.slug}`;
const lobby = nextLobbyNumber(baseName);
if (input.lobby !== undefined && (!Number.isInteger(input.lobby) || input.lobby < 1 || input.lobby > 20)) {
return { ok: false, kind: 'bad-request', message: 'Lobby must be an integer from 1 to 20' };
}
const lobby = input.lobby ?? nextLobbyNumber(baseName);
if (lobby === null) {
return { ok: false, kind: 'no-slot', message: `all lobby slots (1..20) for ${baseName} are taken` };
}
const name = `${baseName}_${lobby}`;
if (getServer(name)) return { ok: false, kind: 'no-slot', message: `${name} is already deployed` };
const plutoKey = input.plutoKey?.trim() || getServerKey(name);
if (!plutoKey) return { ok: false, kind: 'bad-request', message: `No saved key for ${name}. Enter a Plutonium server key.` };
const port = nextAvailablePort();
if (port === null) {
@@ -164,6 +181,10 @@ export async function createServer(input: CreateServerInput): Promise<CreateServ
};
}
// Save before external operations so a failed deployment can also be retried.
try { saveServerKey(name, plutoKey); }
catch (err) { return { ok: false, kind: 'bad-request', message: (err as Error).message }; }
const hostDir = `${config.serversRoot}/${name}`;
const initialConfig = getPromotedServerConfig('t5', mapEntry.canonical);
const mapConfig = getServerMapConfig('t5', mapEntry.canonical)!;
@@ -190,7 +211,7 @@ export async function createServer(input: CreateServerInput): Promise<CreateServ
}
// Step 2: Komodo CreateDeployment.
const spec = buildSpec({ name, port, hostDir, plutoKey: input.plutoKey });
const spec = buildSpec({ name, port, hostDir, plutoKey });
const createRes = await komodoCreateDeployment(spec);
if (!createRes.ok) {
await rm(hostDir, { recursive: true, force: true }).catch(() => {});
+35
View File
@@ -0,0 +1,35 @@
import { db } from '../db/index.js';
import { t5ZombieMapBySlug } from './map-aliases.js';
export function validServerId(value: unknown): value is string {
if (typeof value !== 'string') return false;
const match = /^t5_zombie_([a-z0-9]+)_([1-9]|1[0-9]|20)$/.exec(value);
return !!match && !!t5ZombieMapBySlug(match[1]);
}
export function listServerKeys() {
return db().prepare(`SELECT k.server_id, k.updated_at,
EXISTS(SELECT 1 FROM servers s WHERE s.name = k.server_id) AS deployed
FROM server_keys k ORDER BY k.server_id`).all() as Array<{
server_id: string; updated_at: string; deployed: number;
}>;
}
export function getServerKey(serverId: string): string | undefined {
return (db().prepare('SELECT pluto_key FROM server_keys WHERE server_id = ?')
.get(serverId) as { pluto_key: string } | undefined)?.pluto_key;
}
export function saveServerKey(serverId: unknown, key: unknown): void {
if (!validServerId(serverId)) throw new Error('Choose a valid T5 zombie server ID with a lobby number from 1 to 20');
if (typeof key !== 'string' || !key.trim() || key.trim().length > 512 || /\s/.test(key.trim())) {
throw new Error('Enter a server key without whitespace (maximum 512 characters)');
}
db().prepare(`INSERT INTO server_keys (server_id, pluto_key) VALUES (?, ?)
ON CONFLICT(server_id) DO UPDATE SET pluto_key = excluded.pluto_key, updated_at = datetime('now')`)
.run(serverId, key.trim());
}
export function removeServerKey(serverId: string): boolean {
return db().prepare('DELETE FROM server_keys WHERE server_id = ?').run(serverId).changes > 0;
}
@@ -22,6 +22,10 @@
let gameMode = $state<'zombie'>('zombie');
let mapSlug = $state<string>('');
let plutoKey = $state('');
let lobby = $state('1');
let savedIds = $state<string[]>([]);
let deployedIds = $state<string[]>([]);
let keysLoaded = $state(false);
let deploying = $state(false);
let flash = $state<string | null>(null);
@@ -52,10 +56,21 @@
function reset(): void {
plutoKey = '';
void loadKeys();
flash = null;
deploying = false;
if (maps.length > 0 && !maps.some((m) => m.slug === mapSlug)) mapSlug = maps[0].slug;
}
async function loadKeys() {
keysLoaded = false;
try {
const [keysRes, serversRes] = await Promise.all([fetch('/api/server-keys'), fetch('/api/servers')]);
if (!keysRes.ok || !serversRes.ok) throw new Error('Could not load saved keys and server slots. Reopen this dialog to retry.');
savedIds = (await keysRes.json()).keys.map((k: { server_id: string }) => k.server_id);
deployedIds = (await serversRes.json()).servers.map((s: { name: string }) => s.name);
keysLoaded = true;
} catch (err) { flash = (err as Error).message; }
}
function close(): void { open = false; }
function onDialogClick(e: MouseEvent): void {
@@ -63,7 +78,21 @@
}
let selectedMap = $derived(maps.find((m) => m.slug === mapSlug));
let previewName = $derived(selectedMap ? `t5_${gameMode}_${selectedMap.slug}_?` : '');
let previewName = $derived(selectedMap ? `t5_${gameMode}_${selectedMap.slug}_${lobby}` : '');
let hasSavedKey = $derived(savedIds.includes(previewName));
let alreadyDeployed = $derived(deployedIds.includes(previewName));
let lobbyOptions = $derived(Array.from({ length: 20 }, (_, i) => {
const value = String(i + 1);
const id = `t5_${gameMode}_${mapSlug}_${value}`;
return { value, label: `${value}${deployedIds.includes(id) ? ' (deployed)' : savedIds.includes(id) ? ' (saved key)' : ''}` };
}));
$effect(() => {
const prefix = `t5_${gameMode}_${mapSlug}_`;
lobby = String(Array.from({ length: 20 }, (_, i) => i + 1)
.find(n => !deployedIds.includes(`${prefix}${n}`)) ?? 1);
});
$effect(() => { mapSlug; lobby; plutoKey = ''; });
let modeOptions = [{ value: 'zombie', label: 'Zombies' }];
let mapOptions = $derived(maps.map((m) => ({ value: m.slug, label: m.friendly })));
@@ -72,14 +101,14 @@
e.preventDefault();
if (deploying) return;
if (!selectedMap) { flash = 'Pick a map'; return; }
if (plutoKey.trim().length === 0) { flash = 'Pluto server key is required'; return; }
if (!hasSavedKey && plutoKey.trim().length === 0) { flash = 'Pluto server key is required'; return; }
deploying = true;
flash = null;
try {
const res = await fetch('/api/servers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ gameMode, mapSlug: selectedMap.slug, plutoKey })
body: JSON.stringify({ gameMode, mapSlug: selectedMap.slug, lobby: Number(lobby), plutoKey: plutoKey.trim() || undefined })
});
const body = (await res.json()) as { ok: boolean; name?: string; port?: number; error?: string; kind?: string };
if (!body.ok || !body.name) {
@@ -121,11 +150,15 @@
<Select bind:value={mapSlug} options={mapOptions} disabled={deploying} />
</Field>
<Field label="Pluto server key" hint="Paste each deploy — not stored anywhere.">
<Field label="Lobby number" hint="Choose the same lobby to reuse its server ID and saved key.">
<Select bind:value={lobby} options={lobbyOptions} disabled={deploying} />
</Field>
<Field label="Pluto server key" hint={hasSavedKey ? 'Saved key ready. Leave blank to reuse it, or enter a replacement.' : 'Saved for this server ID and reused on future deployments.'}>
<Input
type="password"
bind:value={plutoKey}
placeholder="paste key"
placeholder={hasSavedKey ? "Saved key ready" : "paste key"}
autocomplete="off"
disabled={deploying}
/>
@@ -135,15 +168,16 @@
<div class="preview">
<span class="preview-k">Will create</span>
<span class="preview-v">{previewName || '—'}</span>
<span class="preview-sub">(lobby number + port auto-assigned)</span>
<span class="preview-sub">{alreadyDeployed ? "Already deployed; choose another lobby" : "Port auto-assigned"}</span>
</div>
<a href="/server-keys" onclick={close}>Manage saved keys</a>
<div class="actions">
<Button variant="ghost" onclick={close} disabled={deploying}>Cancel</Button>
<Button
type="submit"
variant="primary"
disabled={deploying || !selectedMap}
disabled={deploying || !selectedMap || !keysLoaded || alreadyDeployed}
loading={deploying}
>
Deploy server
@@ -217,7 +251,7 @@
gap: var(--space-4);
}
.fields :global(.field):nth-child(1),
.fields :global(.field):nth-child(4) {
.fields :global(.field):nth-child(5) {
grid-column: 1 / -1;
}