import { isReservedConfigFilename } from './private-config.js'; import { scriptVersionError } from '../../script-version.js'; import { putFileBlob, blobContent } from '../db/file-blobs.js'; import { createHash } from 'node:crypto'; import { db } from '../db/index.js'; import { configFileForGame, type ArtifactKind } from '../config.js'; import { MAX_ARTIFACT_BYTES } from '../../artifact-limits.js'; export type { ArtifactKind }; export const ARTIFACT_KINDS: ReadonlyArray = [ 'script', 'config', 'plugin', 'baseline' ]; export function isArtifactKind(v: unknown): v is ArtifactKind { return typeof v === 'string' && (ARTIFACT_KINDS as readonly string[]).includes(v); } export type ScopeType = 'game' | 'map'; export interface ScriptRow { id: number; name: string; target_rel_path: string; scope_type: ScopeType | null; scope_value: string | null; current_version_id: number | null; kind: ArtifactKind; created_at: string; } export type ScriptVersionState = 'untested' | 'tested' | 'test-failed'; export interface ScriptVersionRow { id: number; script_id: number; version: number; release_version: string | null; sha256: string; size: number; notes: string | null; state: ScriptVersionState; kind: ArtifactKind; uploaded_at: string; } // The script name is the primary user-facing identifier; slugify to derive a // URL-safe form. Same rules as the old beta slugify — lowercase, letters + digits. export function slugify(name: string): string { return name .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); } export class ScriptError extends Error { constructor( message: string, public readonly kind: | 'name-empty' | 'name-taken' | 'path-empty' | 'path-reserved' | 'no-such-script' | 'no-such-version' | 'invalid-scope' | 'in-use-current' | 'in-use-beta' | 'has-scope' | 'has-active-beta' | 'invalid-kind' | 'baseline-requires-scope' | 'baseline-exists' | 'empty-overlay' | 'invalid-release-version' | 'release-version-conflict' | 'too-large' ) { super(message); } } function sha256(buf: Buffer): string { return createHash('sha256').update(buf).digest('hex'); } function normalizeReleaseVersion(value: string | null | undefined): string | null { if (value == null) return null; // eslint-disable-next-line no-control-regex -- Reject control characters in release versions. if (typeof value !== 'string' || value.length > 80 || /[\u0000-\u001f\u007f]/.test(value)) { throw new ScriptError( 'release version must be a single line of at most 80 characters', 'invalid-release-version' ); } return value.trim() || null; } function releaseForKind(kind: ArtifactKind, value: string | null | undefined): string | null { if (kind === 'script') { const error = scriptVersionError(value); if (error) throw new ScriptError(error, 'invalid-release-version'); } return normalizeReleaseVersion(value); } export function getScript(id: number): ScriptRow | undefined { return db().prepare('SELECT * FROM scripts WHERE id = ?').get(id) as ScriptRow | undefined; } export function getScriptByName(name: string): ScriptRow | undefined { return db().prepare('SELECT * FROM scripts WHERE name = ?').get(name) as ScriptRow | undefined; } export function listScripts(kind?: ArtifactKind): ScriptRow[] { if (kind) { return db() .prepare('SELECT * FROM scripts WHERE kind = ? ORDER BY name') .all(kind) as ScriptRow[]; } return db().prepare('SELECT * FROM scripts ORDER BY name').all() as ScriptRow[]; } // Look up the current baseline for a given scope. Baselines have exactly one // current_version_id after their first promote; before that they are still // gated through the beta pipeline. `includeUntested` returns the baseline row // even without a promoted version (used at beta-open time when the baseline is // being introduced in the same beta as the overlays). export function getBaselineForScope( scopeType: ScopeType, scopeValue: string ): ScriptRow | undefined { return db() .prepare( `SELECT * FROM scripts WHERE kind = 'baseline' AND scope_type = ? AND scope_value = ? LIMIT 1` ) .get(scopeType, scopeValue) as ScriptRow | undefined; } // All promoted config overlays for a scope. `exceptScriptIds` lets callers // skip overlays whose new version is bundled in a beta — avoids applying the // prior version twice when composing. export function listPromotedOverlaysForScope( scopeType: ScopeType, scopeValue: string, exceptScriptIds: number[] = [] ): ScriptRow[] { const rows = db() .prepare( `SELECT * FROM scripts WHERE kind = 'config' AND scope_type = ? AND scope_value = ? AND current_version_id IS NOT NULL ORDER BY id` ) .all(scopeType, scopeValue) as ScriptRow[]; if (exceptScriptIds.length === 0) return rows; const skip = new Set(exceptScriptIds); return rows.filter((r) => !skip.has(r.id)); } export const VERSION_COLUMNS = 'id, script_id, version, release_version, sha256, size, notes, state, kind, uploaded_at'; export function getVersionContent(id: number): Buffer { const row = db() .prepare( `SELECT ${blobContent('content_hash')} AS content FROM script_versions WHERE id = ?` ) .get(id) as { content: Buffer } | undefined; if (!row?.content) throw new ScriptError(`version content is unavailable (id=${id})`, 'no-such-version'); return row.content; } export function listVersions(scriptId: number): ScriptVersionRow[] { return db() .prepare( `SELECT ${VERSION_COLUMNS} FROM script_versions WHERE script_id = ? ORDER BY version DESC` ) .all(scriptId) as ScriptVersionRow[]; } export function getVersion(id: number): ScriptVersionRow | undefined { return db().prepare(`SELECT ${VERSION_COLUMNS} FROM script_versions WHERE id = ?`).get(id) as ScriptVersionRow | undefined; } export type ScriptVersionMetadata = Pick< ScriptVersionRow, 'id' | 'version' | 'release_version' | 'sha256' | 'size' >; /** Planning a launch never needs to load potentially large script or plugin bytes. */ export function getVersionMetadata(id: number): ScriptVersionMetadata | undefined { return db() .prepare( 'SELECT id, version, release_version, sha256, size FROM script_versions WHERE id = ?' ) .get(id) as ScriptVersionMetadata | undefined; } // Latest version is 'max(version)' — used everywhere we want the freshest // upload, whether or not it has been promoted (current_version_id). export function getLatestVersion(scriptId: number): ScriptVersionRow | undefined { return db() .prepare( `SELECT ${VERSION_COLUMNS} FROM script_versions WHERE script_id = ? ORDER BY version DESC LIMIT 1` ) .get(scriptId) as ScriptVersionRow | undefined; } export interface CreateScriptInput { name: string; /** Optional: defaults to the upload filename for script/plugin, and to * the configured config target file for config/baseline. */ targetRelPath?: string; scopeType?: ScopeType | null; scopeValue?: string | null; content: Buffer; notes?: string; /** Publisher's release tag, e.g. v3.1.0. Upload numbering stays independent. */ releaseVersion?: string; /** Defaults to 'script' for back-compat with existing callers. */ kind?: ArtifactKind; } // Insert script + version 1 in one transaction. Scope may be set at creation // because the script has no current_version_id yet (nothing to gate). export function createScript(input: CreateScriptInput): { script: ScriptRow; version: ScriptVersionRow; } { if (input.content.byteLength > MAX_ARTIFACT_BYTES) throw new ScriptError('Artifacts must not exceed 32 MiB.', 'too-large'); if (!input.name.trim()) throw new ScriptError('script name is required', 'name-empty'); const kind: ArtifactKind = input.kind ?? 'script'; if (!isArtifactKind(kind)) throw new ScriptError(`invalid kind: ${input.kind}`, 'invalid-kind'); // Target file defaulting per kind. Configs and baselines all compose into // the same on-disk cfg file, so the operator never picks it. let targetRelPath = input.targetRelPath?.trim() ?? ''; if (!targetRelPath && (kind === 'config' || kind === 'baseline')) { targetRelPath = configFileForGame( input.scopeType === 'game' ? (input.scopeValue ?? null) : input.scopeValue?.startsWith('zm_') ? 't6' : 't5' ); } if (!targetRelPath) throw new ScriptError('target rel path is required', 'path-empty'); if (isReservedConfigFilename(targetRelPath)) throw new ScriptError( `${targetRelPath} is reserved for instance credentials.`, 'path-reserved' ); // Kind-specific validation. if (kind === 'baseline') { if (!input.scopeType || !input.scopeValue) { throw new ScriptError( 'baselines require a scope (game or map)', 'baseline-requires-scope' ); } if (getBaselineForScope(input.scopeType, input.scopeValue)) { throw new ScriptError( `a baseline already exists for ${input.scopeType}=${input.scopeValue}`, 'baseline-exists' ); } } if (kind === 'config') { if (!input.scopeType || !input.scopeValue) { throw new ScriptError('config overlays require a scope', 'invalid-scope'); } // Reject empty or comment-only overlays — nothing to apply. const text = input.content.toString('utf8'); if (!/^\s*set\s+\S+\s+/m.test(text)) { throw new ScriptError( 'config overlay must contain at least one `set KEY VALUE` line', 'empty-overlay' ); } } validateScope(input.scopeType ?? null, input.scopeValue ?? null); if (getScriptByName(input.name)) throw new ScriptError(`script "${input.name}" already exists`, 'name-taken'); const sha = sha256(input.content); const releaseVersion = releaseForKind(kind, input.releaseVersion); const size = input.content.byteLength; const insertScript = db().prepare( `INSERT INTO scripts (name, target_rel_path, scope_type, scope_value, kind) VALUES (?, ?, ?, ?, ?)` ); const insertVersion = db().prepare( `INSERT INTO script_versions (script_id, version, sha256, size, content_hash, notes, kind, release_version) VALUES (?, 1, ?, ?, ?, ?, ?, ?)` ); let scriptId!: number; let versionId!: number; db().transaction(() => { const s = insertScript.run( input.name, targetRelPath, input.scopeType ?? null, input.scopeValue ?? null, kind ); scriptId = Number(s.lastInsertRowid); const v = insertVersion.run( scriptId, sha, size, putFileBlob(input.content), input.notes ?? null, kind, releaseVersion ); versionId = Number(v.lastInsertRowid); })(); return { script: getScript(scriptId)!, version: getVersion(versionId)! }; } export function uploadNewVersion( scriptId: number, content: Buffer, notes?: string, releaseVersion?: string ): ScriptVersionRow { if (content.byteLength > MAX_ARTIFACT_BYTES) throw new ScriptError('Artifacts must not exceed 32 MiB.', 'too-large'); const script = getScript(scriptId); if (!script) throw new ScriptError(`no such script (id=${scriptId})`, 'no-such-script'); if (script.kind === 'config') { const text = content.toString('utf8'); if (!/^\s*set\s+\S+\s+/m.test(text)) { throw new ScriptError( 'config overlay must contain at least one `set KEY VALUE` line', 'empty-overlay' ); } } const release = releaseForKind(script.kind, releaseVersion); const sha = sha256(content); return db().transaction(() => { if (script.kind === 'script') { const existing = listVersions(scriptId).filter((v) => v.release_version === release); if (existing.some((v) => v.sha256 !== sha)) { throw new ScriptError( `Release ${release} already has different contents. Bump the script release version.`, 'release-version-conflict' ); } if (existing.length) return existing[0]; } const latest = getLatestVersion(scriptId); const nextVersion = (latest?.version ?? 0) + 1; const res = db() .prepare( `INSERT INTO script_versions (script_id, version, sha256, size, content_hash, notes, kind, release_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?)` ) .run( scriptId, nextVersion, sha, content.byteLength, putFileBlob(content), notes ?? null, script.kind, release ); return getVersion(Number(res.lastInsertRowid))!; })(); } function validateScope(scopeType: ScopeType | null, scopeValue: string | null): void { if (scopeType === null && scopeValue === null) return; if (scopeType === 'game' || scopeType === 'map') { if (!scopeValue || !scopeValue.trim()) { throw new ScriptError( `scope_value required for scope_type=${scopeType}`, 'invalid-scope' ); } return; } throw new ScriptError(`unknown scope_type: ${scopeType}`, 'invalid-scope'); } export interface SetScopeInput { scriptId: number; scopeType: ScopeType | null; scopeValue: string | null; } // Scope edits preserve the promoted version and do not deploy files. An active // beta must finish first because promotion reads the script's current scope. export function setScope(input: SetScopeInput): ScriptRow { const script = getScript(input.scriptId); if (!script) throw new ScriptError(`no such script (id=${input.scriptId})`, 'no-such-script'); validateScope(input.scopeType, input.scopeValue); const activeBeta = db() .prepare( `SELECT b.id FROM betas b JOIN beta_scripts bs ON bs.beta_id = b.id WHERE bs.script_id = ? AND b.state IN ('running','ready-promote') LIMIT 1` ) .get(input.scriptId) as { id: number } | undefined; if (activeBeta) { throw new ScriptError( `rollback or promote beta ${activeBeta.id} before changing scope`, 'has-active-beta' ); } db() .prepare('UPDATE scripts SET scope_type = ?, scope_value = ? WHERE id = ?') .run(input.scopeType, input.scopeValue, input.scriptId); return getScript(input.scriptId)!; } // Version delete is metadata-only: it never touches server disks. But deleting // the current version or a version referenced by a running beta would break // downstream state, so those are blocked. export function deleteVersion(versionId: number): void { const version = getVersion(versionId); if (!version) throw new ScriptError(`no such version (id=${versionId})`, 'no-such-version'); const script = getScript(version.script_id)!; if (script.current_version_id === versionId) { throw new ScriptError('cannot delete the current version', 'in-use-current'); } const beta = db() .prepare( `SELECT b.id FROM betas b JOIN beta_scripts bs ON bs.beta_id = b.id WHERE bs.script_version_id = ? AND b.state IN ('running','ready-promote') LIMIT 1` ) .get(versionId) as { id: number } | undefined; if (beta) throw new ScriptError( `beta ${beta.id} is still running against this version`, 'in-use-beta' ); db().prepare('DELETE FROM script_versions WHERE id = ?').run(versionId); } export function deleteScript(scriptId: number): void { const script = getScript(scriptId); if (!script) throw new ScriptError(`no such script (id=${scriptId})`, 'no-such-script'); if (script.scope_type !== null) { throw new ScriptError('un-set scope before deleting a script', 'has-scope'); } const beta = db() .prepare( `SELECT b.id FROM betas b JOIN beta_scripts bs ON bs.beta_id = b.id WHERE bs.script_id = ? AND b.state IN ('running','ready-promote') LIMIT 1` ) .get(scriptId) as { id: number } | undefined; if (beta) throw new ScriptError( `beta ${beta.id} is still running against this script`, 'has-active-beta' ); // Every FK that references scripts(id) or script_versions(id) with NO // ACTION (the default) will abort the delete unless we null it first. // ON DELETE CASCADE / SET NULL fires automatically. The list below covers // every NO ACTION reference in schema.sql; add to it if new ones appear. // deployments.script_id, script_version_id, prior_version_id, beta_id // deployment_scripts.prior_version_id // beta_servers.prior_version_id // beta_server_scripts.prior_version_id // deployments.beta_id needs nulling because betas.script_id ON DELETE // CASCADE nukes any beta bundled against this script, which would then // dangle deployments.beta_id. const handle = db(); const tx = handle.transaction((id: number) => { const inMyVersions = 'IN (SELECT id FROM script_versions WHERE script_id = ?)'; const inMyBetas = 'IN (SELECT id FROM betas WHERE script_id = ? UNION SELECT beta_id FROM beta_scripts WHERE script_id = ?)'; handle .prepare( `UPDATE beta_servers SET prior_version_id = NULL WHERE prior_version_id ${inMyVersions}` ) .run(id); handle .prepare( `UPDATE beta_server_scripts SET prior_version_id = NULL WHERE prior_version_id ${inMyVersions}` ) .run(id); handle .prepare( `UPDATE deployment_scripts SET prior_version_id = NULL WHERE prior_version_id ${inMyVersions}` ) .run(id); handle .prepare( `UPDATE deployments SET prior_version_id = NULL WHERE prior_version_id ${inMyVersions}` ) .run(id); handle .prepare( `UPDATE deployments SET script_version_id = NULL WHERE script_version_id ${inMyVersions}` ) .run(id); handle .prepare(`UPDATE deployments SET beta_id = NULL WHERE beta_id ${inMyBetas}`) .run(id, id); handle.prepare('UPDATE deployments SET script_id = NULL WHERE script_id = ?').run(id); handle.prepare('DELETE FROM scripts WHERE id = ?').run(id); }); tx(scriptId); } // Servers that match a script's scope. Empty for unscoped scripts — those are // only ever pushed to explicitly chosen beta targets. export function serversMatchingScope( scopeType: ScopeType | null, scopeValue: string | null ): string[] { if (scopeType === null || scopeValue === null) return []; const rows = db() .prepare(`SELECT name FROM servers WHERE ${scopeType} = ? ORDER BY name`) .all(scopeValue) as Array<{ name: string }>; return rows.map((r) => r.name); } // Distinct game IDs present in the registered fleet. Powers the scope=game // dropdown so operators can only pick values that will match at least one // server. export function listDistinctGames(): string[] { const rows = db() .prepare( `SELECT DISTINCT game FROM servers WHERE game IS NOT NULL AND game <> '' ORDER BY game` ) .all() as Array<{ game: string }>; return rows.map((r) => r.game); } // Distinct maps grouped by their game. Scope=map is chained (pick game → pick // map) so the UI can filter map options to those valid under the selected game. export function listMapsByGame(): Record { const rows = db() .prepare( `SELECT DISTINCT game, map FROM servers WHERE game IS NOT NULL AND game <> '' AND map IS NOT NULL AND map <> '' ORDER BY game, map` ) .all() as Array<{ game: string; map: string }>; const out: Record = {}; for (const r of rows) { (out[r.game] ??= []).push(r.map); } return out; }