CREATE TABLE IF NOT EXISTS users ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, email VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, secret VARCHAR(255) NULL, totp_last_counter BIGINT NULL, admin TINYINT(1) NOT NULL DEFAULT 0, suspended TINYINT(1) NOT NULL DEFAULT 0, suspended_at BIGINT UNSIGNED NULL, suspended_by VARCHAR(255) NULL, agent_access TINYINT(1) NOT NULL DEFAULT 0, avatar_url VARCHAR(2048) NULL, username VARCHAR(50) NULL, username_changed_at BIGINT UNSIGNED NULL, preferences JSON NULL, recovery_codes TEXT NULL, -- Per-account session discriminator: the CLI bumps it on every credential -- mutation and the running panel revokes browser sessions carrying a stale -- value, so a credential never outlives the account it was issued to. session_epoch BIGINT UNSIGNED NOT NULL DEFAULT 0, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY uniq_users_email (email), -- The unique key inherits the table's utf8mb4_unicode_ci collation, so it -- is case-insensitive and also rejects case-variant duplicates like -- 'Alice' vs 'alice' (impersonation guard). The column is nullable, and -- unique keys allow any number of NULLs, so accounts that never set a -- username are unaffected. UNIQUE KEY uniq_users_username (username) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS nodes ( id VARCHAR(64) NOT NULL, uuid VARCHAR(64) NULL, name VARCHAR(120) NOT NULL, address VARCHAR(255) NOT NULL, ram_mb INT NOT NULL DEFAULT 0, disk_gb INT NOT NULL DEFAULT 0, ports JSON NOT NULL, token_id VARCHAR(64) NULL, token VARCHAR(255) NULL, token_status VARCHAR(32) NULL, created_at BIGINT NULL, api_port INT NOT NULL DEFAULT 8080, sftp_port INT NOT NULL DEFAULT 2022, port_ok TINYINT(1) NULL, last_seen BIGINT NULL, last_check BIGINT NULL, online TINYINT(1) NULL, build_config JSON NULL, max_upload_mb INT NOT NULL DEFAULT 10240, PRIMARY KEY (id), UNIQUE KEY uniq_nodes_uuid (uuid), -- nodes.name is resolved case-insensitively throughout the app -- (LOWER(name) lookups in nodes.js), so the unique key relies on the -- column's inherited utf8mb4_unicode_ci collation to also block -- case-variant duplicates like 'Node1' vs 'node1'. UNIQUE KEY uniq_nodes_name (name) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS servers ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(120) NOT NULL, display_name VARCHAR(120) NULL, legacy_id VARCHAR(120) NULL, bot VARCHAR(120) NULL, template VARCHAR(64) NULL, start VARCHAR(255) NULL, node_id VARCHAR(64) NULL, ip VARCHAR(255) NULL, port INT NULL, status VARCHAR(32) NULL, suspended TINYINT(1) NOT NULL DEFAULT 0, suspended_at BIGINT UNSIGNED NULL, suspended_by VARCHAR(255) NULL, runtime JSON NULL, docker JSON NULL, acl JSON NULL, resources JSON NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY uniq_servers_name (name), KEY idx_servers_node (node_id), KEY idx_servers_legacy (legacy_id), KEY idx_servers_bot (bot), KEY idx_servers_status (status), CONSTRAINT fk_servers_node FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE SET NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS server_reinstall_dispatch ( server_id BIGINT UNSIGNED NOT NULL, operation_id CHAR(32) NOT NULL, host_port INT NOT NULL, template_id VARCHAR(64) NOT NULL, intent JSON NOT NULL, PRIMARY KEY (server_id), UNIQUE KEY uniq_server_reinstall_operation (operation_id), KEY idx_server_reinstall_template (template_id), CONSTRAINT fk_server_reinstall_dispatch FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS server_delete_jobs ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, server_name VARCHAR(120) NOT NULL, server_row_id BIGINT UNSIGNED NULL, technical_name VARCHAR(120) NOT NULL, node_id VARCHAR(64) NOT NULL, status ENUM('queued','running','completed','failed') NOT NULL DEFAULT 'queued', attempts INT UNSIGNED NOT NULL DEFAULT 0, next_attempt_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, last_error TEXT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY uniq_server_delete_jobs_server (server_name), KEY idx_server_delete_jobs_status_next (status, next_attempt_at), KEY idx_server_delete_jobs_node (node_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS user_access ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, user_id BIGINT UNSIGNED NOT NULL, server_name VARCHAR(120) NOT NULL, PRIMARY KEY (id), UNIQUE KEY uniq_user_access (user_id, server_name), CONSTRAINT fk_user_access_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS destructive_action_grants ( grant_id CHAR(64) NOT NULL, user_id BIGINT UNSIGNED NOT NULL, email VARCHAR(255) NOT NULL, session_hash CHAR(64) NOT NULL, secret_hash CHAR(64) NOT NULL, ip_hash CHAR(64) NOT NULL, ua_hash CHAR(64) NOT NULL, verified_at BIGINT UNSIGNED NOT NULL, expires_at BIGINT UNSIGNED NOT NULL, revoked_at BIGINT UNSIGNED NULL, subject VARCHAR(190) NULL, use_count BIGINT UNSIGNED NOT NULL DEFAULT 0, scope_hash CHAR(64) NULL, -- adpanel:stepup-proof-strength — records how strong the proof that minted -- the grant was ('password+totp' / 'password' / 'totp', NULL = unknown): -- consumption refuses to satisfy a stronger verification requirement with a -- weaker proof, so NULL/unknown grants only ever satisfy weaker gates -- (this comment must never contain a statement-terminating character: -- parseSchemaStatements splits the file on raw terminators without -- comment stripping) proof_strength VARCHAR(16) NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (grant_id), KEY idx_destructive_grants_user_expires (user_id, expires_at), KEY idx_destructive_grants_session (session_hash), KEY idx_destructive_grants_expires (expires_at), CONSTRAINT fk_destructive_grants_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS ai_chats ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, user_email VARCHAR(255) NOT NULL DEFAULT '', title VARCHAR(255) NOT NULL DEFAULT 'New Chat', created_by BIGINT UNSIGNED NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_ai_chats_user (user_email), KEY idx_ai_chats_created (created_at), KEY idx_ai_chats_owner_updated (created_by, updated_at), CONSTRAINT fk_ai_chats_user FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS ai_messages ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, chat_id BIGINT UNSIGNED NOT NULL, role ENUM('user', 'assistant', 'system') NOT NULL, content LONGTEXT NOT NULL, agent_actions MEDIUMTEXT NULL, image_data LONGTEXT NULL, image_expires_at DATETIME(3) NULL, thinking_time_ms INT UNSIGNED NULL, thinking_content LONGTEXT NULL, model VARCHAR(255) NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_ai_messages_chat (chat_id), KEY idx_ai_messages_created (created_at), KEY idx_ai_messages_image_expiry (image_expires_at), CONSTRAINT fk_ai_messages_chat FOREIGN KEY (chat_id) REFERENCES ai_chats(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS user_ai_model_selections ( user_id BIGINT UNSIGNED NOT NULL, provider VARCHAR(64) NOT NULL, model VARCHAR(255) NOT NULL, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (user_id), KEY idx_user_ai_model_provider (provider), CONSTRAINT fk_user_ai_model_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS ai_agent_worker_state ( id TINYINT UNSIGNED PRIMARY KEY, enabled BOOLEAN NOT NULL DEFAULT FALSE, generation BIGINT UNSIGNED NOT NULL DEFAULT 0, enabled_since DATETIME(3) NULL ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS ai_agent_schedule_receipts ( schedule_ref CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, occurrence_ref CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, job_id BIGINT UNSIGNED NULL, chat_id BIGINT UNSIGNED NULL, PRIMARY KEY (schedule_ref, occurrence_ref) ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS ai_agent_jobs ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, chat_id BIGINT UNSIGNED NOT NULL, user_id BIGINT UNSIGNED NOT NULL, user_email VARCHAR(255) NOT NULL, server_name VARCHAR(120) NOT NULL, -- adpanel:ai-job-server-identity — the enqueue-time identity bind: stores -- String(entry.id) of the server row findServer resolved when the job was -- queued (the composed legacy_id-first id — the same field the fire-time -- BullMQ bind stores as job.data.serverId), so the claim-time re-bind in -- index.js processAiAgentJob can refuse a run whose server name now answers -- for a different row (same-name recreate landing between enqueue and -- claim). VARCHAR(120) is the composed id's own domain (servers.legacy_id -- is VARCHAR(120), else the BIGINT id's 20-digit string) — narrower could -- truncate and fail the insert under strict mode. NULL only where the -- enqueue resolution carried no id, which the enqueue 404 makes -- unreachable, and for rows predating this column (those skip the -- claim-time check and drain naturally). Kept in lockstep with the runtime -- CREATE TABLE and the boot ALTER in index.js, like the 'cancelled' ENUM -- and perm_file_envelope pins above. Same position as the runtime DDL -- (AFTER server_name). Note: this file is split on raw semicolons by the -- schema loader, so a comment here must never contain a semicolon -- character. server_id VARCHAR(120) NULL, provider VARCHAR(64) NOT NULL, model VARCHAR(255) NOT NULL, prompt LONGTEXT NOT NULL, -- adpanel:planner-job-retract — 'cancelled' is the terminal status that the -- index.js cancelQueuedPlannerAgentJobs retract helper writes. Keep this -- file, the runtime CREATE TABLE and the widening migration in lockstep. -- Note: this file is split on raw semicolons by the schema loader, so a -- comment here must never contain a semicolon character. status ENUM('queued','running','completed','failed','cancelled') NOT NULL DEFAULT 'queued', source VARCHAR(64) NOT NULL DEFAULT 'manual', source_ref VARCHAR(255) NULL, -- adpanel:planner-agent-perms — the enqueue-time file-perm envelope the two -- planner job origins (scheduler_planner_next, planner_send) stamp onto -- their rows. Kept in lockstep with the runtime CREATE TABLE and the boot -- ALTER in index.js, like the 'cancelled' ENUM above. Same position as the -- runtime DDL (AFTER source_ref). perm_file_envelope TEXT NULL, error TEXT NULL, feature_generation BIGINT UNSIGNED NULL, claim_token CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL, request_key CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL, request_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL, submission_message_id BIGINT UNSIGNED NULL, result_message_id BIGINT UNSIGNED NULL, account_epoch BIGINT UNSIGNED NULL, auto_approve_file_edits BOOLEAN NOT NULL DEFAULT FALSE, auto_file_edit_attempts TINYINT UNSIGNED NOT NULL DEFAULT 0, auto_file_edit_generation BIGINT UNSIGNED NULL, schedule_ref CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, started_at TIMESTAMP NULL, completed_at TIMESTAMP NULL, PRIMARY KEY (id), KEY idx_ai_agent_jobs_user (user_id, created_at), KEY idx_ai_agent_jobs_status (status, created_at), KEY idx_ai_agent_jobs_chat (chat_id), KEY idx_ai_agent_schedule_ref (schedule_ref, status), UNIQUE KEY uniq_ai_agent_submission (user_id, request_key), -- adpanel:ai-agent-jobs-target-index — the cascade-retract and the -- cancelQueuedPlannerAgentJobs helper resolve queued planner jobs through -- (server_name = ? AND source_ref = ?) pairs. Without this index they fall -- back to idx_ai_agent_jobs_status and next-key-lock the panel-wide queued -- range for the whole delete transaction. Column order matches every query -- shape (both equality predicates always appear together, server_name -- leading). Kept in lockstep with the runtime CREATE TABLE and the boot -- ALTER in index.js KEY idx_ai_agent_jobs_target (server_name, source_ref), CONSTRAINT fk_ai_agent_jobs_chat FOREIGN KEY (chat_id) REFERENCES ai_chats(id) ON DELETE CASCADE, CONSTRAINT fk_ai_agent_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS server_planner_items ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, server_name VARCHAR(120) NOT NULL, title VARCHAR(255) NOT NULL, prompt LONGTEXT NOT NULL, is_done TINYINT(1) NOT NULL DEFAULT 0, sort_order INT NOT NULL DEFAULT 0, created_by_email VARCHAR(255) NOT NULL, updated_by_email VARCHAR(255) NOT NULL, prompt_author_id BIGINT UNSIGNED NULL, agent_edit_hold_job_id BIGINT UNSIGNED NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_server_planner_server (server_name), KEY idx_server_planner_sort (server_name, is_done, sort_order, updated_at), -- adpanel:planner-item-cascade-retract — the email-keyed account-delete and -- orphan-sweep DELETE key on created_by_email: without this index the delete -- full-scans and next-key-locks every row and gap under REPEATABLE READ, -- blocking concurrent planner writes on every server for the delete's -- duration and inverting against the scheduler fire's range lock -- (planner range lock -> ai_chats writes). Kept in lockstep with the runtime -- CREATE TABLE and the boot ALTER in index.js. KEY idx_server_planner_author (created_by_email), KEY idx_server_planner_prompt_author (prompt_author_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS user_status ( user_id BIGINT UNSIGNED NOT NULL, status_text VARCHAR(80) NOT NULL DEFAULT 'Available', expires_at BIGINT UNSIGNED NULL, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (user_id), KEY idx_user_status_expires (expires_at), CONSTRAINT fk_user_status_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS sftp_credentials ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, user_id BIGINT UNSIGNED NOT NULL, server_name VARCHAR(120) NOT NULL, sftp_username VARCHAR(255) NOT NULL, sftp_password_hash VARCHAR(255) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY uniq_sftp_user_server (user_id, server_name), UNIQUE KEY uniq_sftp_username (sftp_username), KEY idx_sftp_server (server_name), CONSTRAINT fk_sftp_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Legacy cleanup: the subdomains feature was removed from the panel and the -- node agent. Databases that predate the removal keep an unreachable table -- (with its fk_subdomains_server cascade and uniq_subdomains_domain index), -- this statement is idempotent and drops it on boot. Fresh installs never -- had the table, so this is a no-op for them. DROP TABLE IF EXISTS subdomains; -- Round-robin style panel monitoring history. One averaged row per minute, -- pruned to a fixed retention window (default ~31 days) so the table stays at a -- small, predictable size. bucket_ts is the UTC epoch (ms) truncated to the -- minute, used as a stable upsert key. CREATE TABLE IF NOT EXISTS panel_metrics ( bucket_ts BIGINT UNSIGNED NOT NULL, cpu_percent DECIMAL(5,1) NOT NULL DEFAULT 0, mem_percent DECIMAL(5,1) NOT NULL DEFAULT 0, disk_percent DECIMAL(5,1) NOT NULL DEFAULT 0, net_rx_bps BIGINT UNSIGNED NOT NULL DEFAULT 0, net_tx_bps BIGINT UNSIGNED NOT NULL DEFAULT 0, rps DECIMAL(8,1) NOT NULL DEFAULT 0, PRIMARY KEY (bucket_ts) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Queue of CLI-issued session-revocation requests (scripts/create-user.js). -- email is the PRIMARY KEY on purpose: the running panel claims a row by -- DELETEing it, so the key is the cross-process claim mechanism and must not -- be changed. This table is keyed by email, not user_id — never add it to any -- user-owned-table list. CREATE TABLE IF NOT EXISTS pending_session_revocations ( email VARCHAR(255) NOT NULL, requested_at BIGINT UNSIGNED NOT NULL, reason VARCHAR(64) NOT NULL DEFAULT '', attempts INT UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (email) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- adpanel:login-audit-durable — ONE durable, operator-owned row per -- successful login (both authentication completion paths: the POST /login -- password success and the captcha-completion finalize). Forensics previously -- relied only on the Redis remember-login registry entry, which the -- attacker's own logout or password change wipes, and securityLog is -- console-only. The insert is fail-open: a failed audit write warns and never -- gates the login. Shape is owned here (replayed by db.ensureSchema on every -- boot) and kept byte-identical with the guarded belt-and-suspenders DDL in -- utils/login-audit.js — pinned by tests/login-audit-durable.test.js. -- Retention: boot-time prune of rows older than 180 days -- (LOGIN_AUDIT_RETENTION_DAYS in utils/login-audit.js). CREATE TABLE IF NOT EXISTS login_audit ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, user_id BIGINT UNSIGNED NOT NULL, email VARCHAR(255) NOT NULL, ip VARCHAR(64) NOT NULL DEFAULT '', user_agent VARCHAR(255) NOT NULL DEFAULT '', method VARCHAR(32) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_login_audit_user_created (user_id, created_at), KEY idx_login_audit_created (created_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;